locked
CRM 2011 WCF to do CRUD operations, all i need is example RRS feed

  • Question

  • As in the title of this thread, all i need is example of using the WCF of CRM in visual studio but without adding any dll references just adding web services as reference.

    All i need is an example of CRUD operations .... just the start.

    Thanks.


    Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com
    Friday, June 24, 2011 7:52 PM

All replies

  • You can download Microsoft Dynamics CRM SDK, there is some sample code that shows you how to make service calls to CRM server.

    Hope this helps.


    Daniel Cai | http://danielcai.blogspot.com
    Friday, June 24, 2011 8:43 PM
  • Ofcourse i downloaded the SDK but all is using the dll even the project is called WCF... i want example using the WCF without adding reference to any DLLs

    Can you help?


    Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com
    Saturday, June 25, 2011 6:10 AM
  • Hi,

    You may refer the following blog posr for You can refer CRM 2011 WCF CRUD examples. http://blog.rostacik.net/post/2011/05/12/How-to-read-create-update-and-detele-objects-in-Microsoft-CRM-2011-via-WCF-service.aspx

    I hope this will be helpful.


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".
    Sunday, June 26, 2011 4:07 PM
  • Jehanzeb, do you know that you can reply to a thread but can't mark your reply as an answer !

    And if you read my question its clear that i don't want to put using for using Microsoft.Xrm.Sdk.Client;
    using Microsoft.Xrm.Sdk;
    I only want to use WCF service without adding dlls as reference.

    Is this doable? I heard a lot that it is doable but never saw it online.

    If you know, please advice or provide link or something.

    Thanks.


    Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com
    Monday, June 27, 2011 5:30 AM
  • Hi,

    Yes you can by adding a Web reference to your Visual Studio project. See the CRM 2011 SDK topic Use the WSDL Endpoint & (http://msdn.microsoft.com/en-us/library/cc151015.aspx). Note that the WSDL contains a subset of the full CRM SDK capability. I have not found an exact example for CRUD operations (might have to create one) but hope this will be helpful

    You can also refer the blog post (http://www.shanmcarthur.net/crm/developers-corner/using-crm-sdk-instead-of-web-reference) if why to use SDK libraries instead of Web Service direct refrence.


    Jehanzeb Javeed

    http://worldofdynamics.blogspot.com
    Linked-In Profile |CodePlex Profile

    If you find this post helpful then please "Vote as Helpful" and "Mark As Answer".




    Monday, June 27, 2011 6:58 AM
  • Thanks for the links, will take a look but adding CRM Web Service to Visual Studio 2010 is not my problem, my problem is how to do CRUD operations or even one of those operations using only CRM WCF ?? !!

    That's it.

    I know the URL of service, i know how to add it to my project, don't know first step only then i will continue from here, [ to do any operation of those ??? ]

    Can you help?


    Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com
    Monday, June 27, 2011 7:38 AM
  • Hi,

    I'm not sure to understand correctly what you are trying to ask/do, but it seems like I'm using WebReference like you try to.

    Here's a snippet of a Retrieve request (I'm only retrieving actually):

    private void LoadAllAccountsAsync()
    {
    	// Creating service with help of the SilverlightUtility Class from the SDK
    	IOrganizationService service = SilverlightUtility.GetSoapService(BaseURI);
    	RetrieveMultipleRequest req = new RetrieveMultipleRequest()
    	{
    		query = new QueryExpression()
    		{
    			ColumnSet = new ColumnSet() { AllColumns = true },
    			EntityName = "account"
    		}
    	};
    	service.BeginRetrieveMultiple(req, LoadAllAccountsCompleted, service);
    }
    private void LoadAllAccountsCompleted(IAsyncResult result)
    {
    	var resp = ((IOrganizationService)result.AsyncState).EndRetrieveMultiple(result);
    	var accounts = resp.RetrieveMultipleResult.Entities.ToList();
    }
    

    Hope that it can helps you a bit (or someone else).

    BTW, I troubled with the request at the start of my project, not sure it is the best way, but it works ;)

    Monday, June 27, 2011 8:27 AM
  • Once you add the web references to your project as Jehanzeb suggested you can do CRUD operations in the exact same way as if you had referenced your dlls. Any sample code you find in the SDK or the web should work. For example, create an account:

     

    Entity account = new Entity("account")

    account["name"] = "account name";

    service.Create(account);

     

    You mentioned you downloaded the SDK, you will find tons of samples that do CRUD operations in the sample code. Most of these samples use the WCF endpoint by using the IOrganizationService interface.


    Gonzalo | gonzaloruizcrm.blogspot.com


    Monday, June 27, 2011 5:19 PM
    Moderator
  • As suggested by other folks, here is a little more detailed steps which might help you get started. 

    1. Add a service reference to http://crmservername:port/OrganizationName/xrmServices/2011/organization.svc
    2. Then you may consume the OrganizationServiceClient in the following fashion
        static void Main(string[] args)
        {
          using (var xrmServiceClient = InstantiateXrmService())
          {
            var account = new Entity
                      {
                        LogicalName = "account"
                      };
    
            var accountAttributes = new AttributeCollection
                          {
                            new KeyValuePair<string, object>("name", "ABC Inc."),
                            new KeyValuePair<string, object>("telephone1", "111-222-3333")
                          };
    
            account.Attributes = accountAttributes;
            xrmServiceClient.Create(account);
          }
        }
    
        private static OrganizationServiceClient InstantiateXrmService()
        {
          var credentials = new NetworkCredential("crmusername", "password", "domain");
          var xrmServiceClient = new OrganizationServiceClient();
    
          xrmServiceClient.ClientCredentials.Windows.ClientCredential = credentials;
    
          return xrmServiceClient;
        }
    

    I only provided a Create sample. If you need, I can provide more samples. But I think you are capable to carry on based on the above snippet. 

    Hope this helps. 


    Daniel Cai | http://danielcai.blogspot.com
    Tuesday, June 28, 2011 4:54 AM
  • Hi Mai, 

    I just wrote a blog post with step-by-step instructions how to perform CRUD through CRM using pure WCF client service call without using any CRM SDK assemblies. 

    Hope it helps. 


    Daniel Cai | http://danielcai.blogspot.com
    Tuesday, June 28, 2011 2:11 PM
  • Daniel, Where were you all this time... Thanks indeed, but please lets wait till i give it a try, does not have to be all code but at the least the above method and get back to you and mark you as answer, just give me time. Ok.

    Thanks.


    Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com
    Wednesday, June 29, 2011 7:04 AM
  • Mai, welcome to the CRM world! Take your time, please let us know if you need any further assistance. I might need your help on SharePoint one day. ;-)

    Cheers,


    Daniel Cai | http://danielcai.blogspot.com
    Wednesday, June 29, 2011 3:59 PM
  • Daniel i am getting namespace is not found under OrganizationServiceClient and AttributeCollection.

    I create new console application, and add reference service reference of one you mentioned.

    Am i missing something?


    Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com
    Thursday, June 30, 2011 8:36 AM
  • Strange i found this link http://nishantrana.wordpress.com/2010/11/18/using-organizationserviceclient-in-crm-2011/

    And it says as you said but i am still seeing namespace not found !


    Mai Omar Desouki | Software Consultant | Infusion | MCP, MCTS, MCPD, MCITP, MCT Microsoft Certified Trainer & MCC Microsoft Community Contributor | Email: mai_omar_86@live.com
    Thursday, June 30, 2011 8:41 AM
  • Mai, I just updated the blog post with the namespace issue addressed. I originally created my console application under a different namespace, but later on I decided to follow the namespace patterns that SDK document used, which I didn't verify thereafter. Also in the blog post I have provided a download link of the entire project that I compiled. 


    Daniel Cai | http://danielcai.blogspot.com
    Thursday, June 30, 2011 1:16 PM
  • 1. Add Service Request to your VS project with the format “http://CRM ServerName:defaultPort/OrganizationName/XRMServices/2011/Organization.svc“. For example “http://pxtsgo0666:5555/CRMDev/XRMServices/2011/Organization.svc“.

    2. Add namespace of that Service Request to your project (using).

    3. use below code

    ==================================================

    string strOrg = “CRMDev”;
    string strURI = @”http://CRMServerName:defaultPort/” + strOrg + “/XRMServices/2011/Organization.svc”;
    OrganizationServiceClient orgProxy = new OrganizationServiceClient();
    orgProxy.ClientCredentials.Windows.ClientCredential = new System.Net.NetworkCredential(“UserId”, “Password”, “DomainName”);
    System.ServiceModel.EndpointAddress myEndpointAdd = new System.ServiceModel.EndpointAddress(new Uri strURI), System.ServiceModel.EndpointIdentity.CreateDnsIdentity(“aa”));
    orgProxy.Endpoint.Address= myEndpointAdd;
    Entity objAcc = new Entity();
    objAcc.LogicalName = “account”;
    AttributeCollection myAttColl = new AttributeCollection();
    myAttColl.Add(new KeyValuePair<string,object>(“name”, “AAA from UNTYPE ClientMethod”));
    myAttColl.Add(new KeyValuePair<string,object>(“emailaddress1″, “testfrom@test.com“));
    myAttColl.Add(new KeyValuePair<string,object>(“telephone1″, “+1122334455″));
    objAcc.Attributes = myAttColl;
    orgProxy.Create(objAcc);

    ==================================================

    Now, you can use the same piece of code to access multiple organizations within the same installation by changing the “strOrg” variable. Here an account record is being created.
    Note: you must create a DNS Name separately with statement “System.ServiceModel.EndpointAddress myEndpointAdd = new System.ServiceModel.EndpointAddress(new Uri(strURI),System.ServiceModel.EndpointIdentity.CreateDnsIdentity(“aa”));”
    Here you can pass any value in place of aa.

    regards

    joon

    http://joonsarena.wordpress.com/

    Friday, February 10, 2012 12:17 PM
  • This is code to get Organization Service for 3.5. Do not forget to add service reference for needed organization service(http://<servername>:<portnumber>/<organizationname>/XRMServices/2011/Organization.svc?wsdl). I use it for developing SSIS packages for SQL Server 2008.
    Uri orgURL = new Uri (stringURL);
    
    
                SymmetricSecurityBindingElement security = SecurityBindingElement.CreateSspiNegotiationBindingElement();
                security.DefaultAlgorithmSuite = SecurityAlgorithmSuite.Default;
                security.SecurityHeaderLayout = SecurityHeaderLayout.Strict;
                security.IncludeTimestamp = true;
                security.KeyEntropyMode = SecurityKeyEntropyMode.CombinedEntropy;
                security.MessageProtectionOrder = MessageProtectionOrder.SignBeforeEncryptAndEncryptSignature;
                security.MessageSecurityVersion = MessageSecurityVersion.WSSecurity11WSTrustFebruary2005WSSecureConversationFebruary2005WSSecurityPolicy11BasicSecurityProfile10;
                security.LocalClientSettings.CacheCookies = true;
                security.LocalClientSettings.DetectReplays = true;
                security.LocalClientSettings.ReplayCacheSize = 900000;
                security.LocalClientSettings.MaxClockSkew = new TimeSpan(0, 5, 0);
                security.LocalClientSettings.MaxCookieCachingTime = new TimeSpan(23, 0, 0, 0);
                security.LocalClientSettings.ReplayWindow = new TimeSpan(0, 5, 0);
                security.LocalClientSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0);
                security.LocalClientSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0);
                security.LocalClientSettings.ReconnectTransportOnFailure = true;
                security.LocalClientSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0);
                security.LocalClientSettings.CookieRenewalThresholdPercentage = 60;
                security.LocalServiceSettings.DetectReplays = true;
                security.LocalServiceSettings.IssuedCookieLifetime = new TimeSpan(10, 0, 0);
                security.LocalServiceSettings.MaxStatefulNegotiations = 128;
                security.LocalServiceSettings.ReplayCacheSize = 900000;
                security.LocalServiceSettings.MaxClockSkew = new TimeSpan(0, 5, 0);
                security.LocalServiceSettings.NegotiationTimeout = new TimeSpan(0, 1, 0);
                security.LocalServiceSettings.ReplayWindow = new TimeSpan(0, 5, 0);
                security.LocalServiceSettings.InactivityTimeout = new TimeSpan(0, 2, 0);
                security.LocalServiceSettings.SessionKeyRenewalInterval = new TimeSpan(15, 0, 0);
                security.LocalServiceSettings.SessionKeyRolloverInterval = new TimeSpan(0, 5, 0);
                security.LocalServiceSettings.ReconnectTransportOnFailure = true;
                security.LocalServiceSettings.MaxPendingSessions = 128;
                security.LocalServiceSettings.MaxCachedCookies = 1000;
                security.LocalServiceSettings.TimestampValidityDuration = new TimeSpan(0, 5, 0);
    
                TextMessageEncodingBindingElement textEncoding = new TextMessageEncodingBindingElement();
                textEncoding.MaxReadPoolSize = 64;
                textEncoding.MaxWritePoolSize = 16;
                textEncoding.MessageVersion = MessageVersion.Default;
                textEncoding.WriteEncoding = System.Text.Encoding.UTF8;
                    
                
    
                HttpTransportBindingElement httpTransport = new HttpTransportBindingElement();
                httpTransport.ManualAddressing = false;
                httpTransport.MaxBufferSize = 65536;
                httpTransport.MaxReceivedMessageSize = 65536;
                httpTransport.AllowCookies = false;
                httpTransport.AuthenticationScheme = AuthenticationSchemes.Anonymous;
                httpTransport.BypassProxyOnLocal = false;
                httpTransport.HostNameComparisonMode = HostNameComparisonMode.StrongWildcard;
                httpTransport.KeepAliveEnabled = true;
                httpTransport.MaxBufferPoolSize = 524288;
                httpTransport.ProxyAuthenticationScheme = AuthenticationSchemes.Anonymous;
                httpTransport.TransferMode = TransferMode.Buffered;
                httpTransport.UnsafeConnectionNtlmAuthentication = false;
                httpTransport.UseDefaultWebProxy = true;
                
    
                CustomBinding binding = new CustomBinding(new List<BindingElement> { security, textEncoding, httpTransport });
                EndpointAddress endpoint = new EndpointAddress(orgURL);
    
                OrganizationServiceClient client = new OrganizationServiceClient(binding, endpoint);
    
               
                
                
                
                IOrganizationService _orgservice = (IOrganizationService) client;

    Thursday, July 19, 2012 10:47 AM