Showing posts with label Server Side. Show all posts
Showing posts with label Server Side. Show all posts

Thursday, May 28, 2015

Interface between systems - call to WS\ WCF service from CRM

Interface between systems - call to WS\ WCF service from CRM
The easy way to call WCF service using Plugin..
Invoke plugin from JS for instance by createing temp entity record
Write the next code in plugin:

public void Execute(IServiceProvider serviceProvider){
 IOrganizationService _srv = null;
 try
 {
  IPluginExecutionContext context = (IPluginExecutionContext)serviceProvider.GetService(typeof(IPluginExecutionContext));
 IOrganizationServiceFactory factory = (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
 _srv = factory.CreateOrganizationService(context.InitiatingUserId);
  if (context.MessageName.ToLower() == "create"){
    HttpWebRequest httpWReq= HttpWebRequest)WebRequest.Create("https://service/lalala.asmx");
    ASCIIEncoding encoding = new ASCIIEncoding();
    string postData = "request";
    byte[] data = encoding.GetBytes(postData);
    httpWReq.Method = "POST";
    httpWReq.ContentType = "text/xml; charset=utf-8";
    httpWReq.Host = "iservices.service.example";
    httpWReq.ContentLength = data.Length;
    using (Stream stream = httpWReq.GetRequestStream()){
      Write(data, 0, data.Length);
      HttpWebResponse response = (HttpWebResponse)httpWReq.GetResponse();
      string responseString = new StreamReader(response.GetResponseStream()).ReadToEnd();
                    }
                }
       }
 catch (FaultException<OrganizationServiceFault> ex){}
 Catch (Exception ez){}
        }



Enjoy,
Rami Heleg

Thursday, May 21, 2015

Implement nolock in Fetch

By default SQL server defined to lock records when execute query and rows selected until finish to execute.. problem when we have many records.

to prevent lock records in CRM, DBA allow to define all database to work with no-lock and we have another option to request fetch with no lock.

Example:









Enjoy,
Rami Heleg

Wednesday, May 20, 2015

Close Opportunity as Lose

LoseOpportunityRequest loseReq = new LoseOpportunityRequest();
Entity OpportunityClose = new Entity("opportunityclose");
OpportunityClose.Attributes.Add("opportunityid", eOpportunity);
OpportunityClose.Attributes.Add("actualend", DateTime.Now);
OpportunityClose.Attributes.Add("actualrevenue", 0);
loseReq.Status = new OptionSetValue(((OptionSetValue)context.InputParameters["Status"]).Value);
loseReq.OpportunityClose = OpportunityClose;
service.Execute(loseReq);

Close Opportunity as Win


 WinOpportunityRequest winReq = new WinOpportunityRequest();
Entity OpportunityClose = new Entity("opportunityclose");
OpportunityClose.Attributes.Add("opportunityid", eOpportunity);
OpportunityClose.Attributes.Add("actualend", DateTime.Now);
OpportunityClose.Attributes.Add("actualrevenue", 0);

winReq.Status = new OptionSetValue(3);
winReq.OpportunityClose = OpportunityClose;
service.Execute(winReq);

Enjoy,
Rami Heleg

Tuesday, February 7, 2012

Early Bound – generate Entity class

Early Bound – generate Entity class

CRM 3, 4 and now in 2011 have 2 options to work with attributers.

Strong type (early bound) and Late bound Dynamic Entity\Entity)

The different code between two options:

If you need to work for CRM online strong type not good for you because plugin issues.

Nice to work strong type and maybe faster but I prefer Entity

1 strong type example:

Contact c= new contact

c.firstname = “rami;

 2. late bound (dynamic entity was for CRM 3, 4):

Entity c= new Entity (“contact”);

C[“firstname”]= “rami”;…..

To generate data.cs file with metadata attributes need to use file:crmsvcutil.exe

Crmsvcutil.exe must reference the next files:

1.       Microsoft.xrm.client.codegeneration.dll

2.       Microsoft.xrm.client.dll

3.       Microsoft.xml.sdk.dll

Create Bat file CreateMetadata.bat and set inside the next command:

Define:

CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration" /out:OutputfileName/url:http://Server/organizationName/XRMServices/2011/Organization.svc /domain:DomainName/username:UserName/password:password/namespace:Xrm /serviceContextName:XrmServiceContext

 Example:

CrmSvcUtil.exe /codeCustomization:"Microsoft.Xrm.Client.CodeGeneration.CodeCustomization, Microsoft.Xrm.Client.CodeGeneration" /out:Xrm.cs /url:http://crm2011/CRM/XRMServices/2011/Organization.svc /domain:CONTOSO /username:administrator /password:pass@word1 /namespace:Xrm /serviceContextName:XrmServiceContext

After run the batch file get file Xrm.cs.

Now u can use this file in your code. (Don’t forget to generate after change the entities.

Enjoy,
Rami Heleg

Friday, July 1, 2011

Server Side Example - Run query expression

Hi,
Here is an example of run query QueryExpression in CRM 2011.
Example project for Console application.

Before run the application musat add reference to dlls:
1. Microsoft.Xrm.Sdk.dll ( get this file from SDK 2011)
2. Microsoft.Crm.Sdk.Proxy.dll ( get this file from SDK 2011)

Before run the console application add Service References to:

http://ServerName:5555/XRMServices/2011/Organization.svc

Console Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;

namespace crm2011Test1
{
    class query2
    {
        static void Main(string[] args)
        {
            Button1_Click();
        }
        static void Button1_Click()
        {
            //Authenticate using credentials of the logged in user;       
            ClientCredentials Credentials = new ClientCredentials();
            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://crmserver:5555/crm2011dev/XRMServices/2011/Organization.svc");
            Uri HomeRealmUri = null;
            using (Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy serviceProxy = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceProxy;
                // Create query in contact entity                Microsoft.Xrm.Sdk.Query.QueryExpression qe = new Microsoft.Xrm.Sdk.Query.QueryExpression();
                qe.EntityName = "contact";
                Microsoft.Xrm.Sdk.Query.FilterExpression filter1 = new Microsoft.Xrm.Sdk.Query.FilterExpression();
                filter1.FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.And;
                filter1.Conditions.Add(new Microsoft.Xrm.Sdk.Query.ConditionExpression("firstname", Microsoft.Xrm.Sdk.Query.ConditionOperator.Equal, "amos"));
                filter1.FilterOperator = Microsoft.Xrm.Sdk.Query.LogicalOperator.Or;
                filter1.Conditions.Add(new Microsoft.Xrm.Sdk.Query.ConditionExpression("createdon", Microsoft.Xrm.Sdk.Query.ConditionOperator.NextXDays, 7));
                filter1.Conditions.Add(new Microsoft.Xrm.Sdk.Query.ConditionExpression("createdon", Microsoft.Xrm.Sdk.Query.ConditionOperator.NextXDays, 30));
                qe.Criteria = filter1;
                //first retrive
                EntityCollection ec = service.RetrieveMultiple(qe);
                //create loog on result
                foreach (Entity act in ec.Entities){}
                Console.ReadKey();            }
        }
    }
}

Server Side Example - Fetch

Hi,
Here is an example of update entity in CRM 2011.
Example project for Console application.

Before run the application musat add reference to dlls:
1. Microsoft.Xrm.Sdk.dll ( get this file from SDK 2011)
2. Microsoft.Crm.Sdk.Proxy.dll ( get this file from SDK 2011)

Before run the console application add Service References to:

http://ServerName:5555/XRMServices/2011/Organization.svc

Console Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;

namespace crm2011Test1
{
    class Fetch
    {
        static void Main(string[] args)
        {
            Button1_Click();
        }

        static void Button1_Click()
        {
            ClientCredentials Credentials = new ClientCredentials();
            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://crmserver:5555/crm2011dev/XRMServices/2011/Organization.svc");
            Uri HomeRealmUri = null;
            using (Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy serviceProxy = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceProxy;
                //fetch example
         
       string opportunity_count = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                              <entity name='contact'>
                                                <attribute name='fullname' />
                                                <attribute name='new_customernumber' />
                                                <attribute name='donotemail' />
                                                <attribute name='birthdate' />
                                                <order attribute='new_customernumber' descending='true' />
                                                <filter type='and'>
                                                  <filter type='or'>
                                                    <condition attribute='birthdate' operator='next-seven-days' />
                                                    <condition attribute='birthdate' operator='last-x-days' value='30' />
                                                  </filter>
                                                </filter>
                                              </entity>
                                            </fetch>";

                EntityCollection contact_count_result = service.RetrieveMultiple(new Microsoft.Xrm.Sdk.Query.FetchExpression(opportunity_count));
                //Create loop of the result                 foreach (var c in contact_count_result.Entities){}
                //end fetch example
                Console.ReadKey();
                //This code will clear the textboxes after the contact is created.
            }
        }
    }
}

Thanks,
Rami Heleg

Server Side Example - Update Entity

Hi,
Here is an example of update entity in CRM 2011.
Example project for Console application.

Before run the application musat add reference to dlls:
1. Microsoft.Xrm.Sdk.dll ( get this file from SDK 2011)
2. Microsoft.Crm.Sdk.Proxy.dll ( get this file from SDK 2011)

Before run the console application add  Service References to:

http://ServerName:5555/XRMServices/2011/Organization.svc

Console Example:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;


namespace crm2011Test1
{
    class Update
    {
        //static void Main(string[] args)
        //{
        //    Button1_Click();
        //}
        static void Button1_Click()
        {
            //Authenticate using credentials of the logged in user;       
            ClientCredentials Credentials = new ClientCredentials();
            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://crmserver:5555/crm2011dev/XRMServices/2011/Organization.svc");
            Uri HomeRealmUri = null;
            using (Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy serviceProxy = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceProxy;
                //Create Entity - > define entity name
                Entity contact = new Entity("EntityName");

                contact["contactid"] ="{EntityId}";
                contact["firstname"] = "rami11";
                contact["lastname"] = "heleg11";
                service.Update(contact);                Console.ReadKey();
            }
        }
    }
}

Thanks,
Rami Heleg

Server Side example – SetState

Hi,
Here is an example of setstate entity in CRM 2011.
Example project for Console application.

Before run the application musat add reference to dlls:
1. Microsoft.Xrm.Client.dll ( get this file from SDK 2011)
2. Microsoft.Xrm.Sdk.dll ( get this file from SDK 2011)
3. Microsoft.Crm.Sdk.Proxy.dll ( get this file from SDK 2011)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Description;
using System.Net;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk;

namespace crm2011Test1
{
    class SetState
    {
        //static void Main(string[] args)
        //{
        //    Button1_Click();
        //}
        static void Button1_Click()
        {
            //Authenticate using credentials of the logged in user;       
            ClientCredentials Credentials = new ClientCredentials();
            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://crmserver:5555/crm2011dev/XRMServices/2011/Organization.svc");
            Uri HomeRealmUri = null;
            using (Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy serviceProxy = new Microsoft.Xrm.Sdk.Client.OrganizationServiceProxy(OrganizationUri, HomeRealmUri, Credentials, null))
            {
                serviceProxy.ServiceConfiguration.CurrentServiceEndpoint.Behaviors.Add(new ProxyTypesBehavior());
                IOrganizationService service = (IOrganizationService)serviceProxy;
                //set state of contact to disable (add microsoft.xrm.client.dll)
                OrganizationServiceContext osc = new OrganizationServiceContext(service);
                Microsoft.Xrm.Client.Messages.OrganizationServiceContextExtensions.SetState(osc, new EntityReference("contact", new Guid("{contactGuid}")), new OptionSetValue(1), new OptionSetValue(2));
                Console.ReadKey();
            }
        }
    }
}

Thanks,
Rami Heleg