Showing posts with label Coding. Show all posts
Showing posts with label Coding. Show all posts

Saturday, May 16, 2015

Paging and Bulk Update in CRM

       private void TestExample()
        {
            getCRMService();
            XrmServiceContext _context = new XrmServiceContext(service);

            int Fetchcount = 3;
            int PageNumber = 1;
            int RecordCount = 0;
            string pagingCookie = null;

            string FetchXML = @"<fetch version='1.0' output-format='xml-platform' mapping='logical' distinct='false'>
                                  <entity name='account'>
                                    <attribute name='name' />
                                    <attribute name='primarycontactid' />
                                    <attribute name='telephone1' />
                                    <attribute name='accountid' />
                                    <order attribute='name' descending='false' />
                                  </entity>
                                </fetch>";

            while (true)
            {
                string xml = CreateXml(FetchXML, pagingCookie, PageNumber, Fetchcount);
                RetrieveMultipleRequest fetchRequest = new RetrieveMultipleRequest
                {
                    Query = new FetchExpression(xml)
                };

                EntityCollection entity = ((RetrieveMultipleResponse)service.Execute(fetchRequest)).EntityCollection;

                if (entity.MoreRecords)
                {
                    PageNumber++;
                }
                else
               {
                    BulkUpdate(service, entity);
                    break;
                }

                BulkUpdate(service, entity);
            }

        }
        public static void BulkUpdate(IOrganizationService service, EntityCollection entities)
        {
            ExecuteMultipleRequest req = new ExecuteMultipleRequest();

            req.Requests = new OrganizationRequestCollection();

            req.Settings = new ExecuteMultipleSettings();

            req.Settings.ContinueOnError = true;

            req.Settings.ReturnResponses = true;


            foreach (var entity in entities.Entities)
            {
                entity.Attributes.Remove("telephone1");
                entity.Attributes["telephone1"] ="121454";
                UpdateRequest updateRequest = new UpdateRequest { Target = entity };
           
                req.Requests.Add(updateRequest);
            }

            ExecuteMultipleResponse responseWithNoResults =
                       (ExecuteMultipleResponse)_serviceProxy.Execute(req);

            if (responseWithNoResults.Responses.Count > 0)
            {
                foreach (var responseItem in responseWithNoResults.Responses)
                {
                    if (responseItem.Fault != null)
                    {
                    }
                }
            }
            else
            {
                Console.WriteLine("All account records have been updated successfully.");
            }

        }
        public string CreateXml(string xml, string cookie, int page, int count)
        {
            StringReader stringReader = new StringReader(xml);
            XmlTextReader reader = new XmlTextReader(stringReader);

            // Load document
            XmlDocument doc = new XmlDocument();
            doc.Load(reader);

            return CreateXml(doc, cookie, page, count);
        }
        public string CreateXml(XmlDocument doc, string cookie, int page, int count)
        {
            XmlAttributeCollection attrs = doc.DocumentElement.Attributes;

            if (cookie != null)
            {
                XmlAttribute pagingAttr = doc.CreateAttribute("paging-cookie");
                pagingAttr.Value = cookie;
                attrs.Append(pagingAttr);
            }

            XmlAttribute pageAttr = doc.CreateAttribute("page");
            pageAttr.Value = System.Convert.ToString(page);
            attrs.Append(pageAttr);

            XmlAttribute countAttr = doc.CreateAttribute("count");
            countAttr.Value = System.Convert.ToString(count);
            attrs.Append(countAttr);

            StringBuilder sb = new StringBuilder(1024);
            StringWriter stringWriter = new StringWriter(sb);

            XmlTextWriter writer = new XmlTextWriter(stringWriter);
            doc.WriteTo(writer);
            writer.Close();

            return sb.ToString();
        }

Thursday, August 21, 2014

Check Entity and Attribute Exist in CRM or not?

   private bool DoesAttributeExist(string entityName,string attributeName, IOrganizationService service)
        {
            RetrieveEntityRequest request = new RetrieveEntityRequest
            {
                EntityFilters = Microsoft.Xrm.Sdk.Metadata.EntityFilters.Attributes,
                LogicalName = entityName
            };
            RetrieveEntityResponse response
              = (RetrieveEntityResponse)service.Execute(request);

            return response.EntityMetadata.Attributes.FirstOrDefault(element => element.LogicalName == attributeName && element.AttributeType.Value == AttributeTypeCode.DateTime) != null;
        }

        private bool DoesEntityExist(string entityName, IOrganizationService _service)
        {
            RetrieveAllEntitiesRequest allEntitiesRequest = new RetrieveAllEntitiesRequest();
            // Retrieve only the currently published changes, ignoring the changes that have
            // not been published.
            allEntitiesRequest.RetrieveAsIfPublished = false;
            //allEntitiesRequest.MetadataItems = MetadataItems.EntitiesOnly;

            // Execute the request
            RetrieveAllEntitiesResponse allEntitiesResponse = (RetrieveAllEntitiesResponse)_service.Execute(allEntitiesRequest);

            // Iterate through the retrieved entities
            foreach (EntityMetadata entity in allEntitiesResponse.EntityMetadata)
            {
                if (entity.LogicalName == entityName)
                    return true;
            }
            return false;
        }

Thursday, April 24, 2014

How to use ExecuteMultipleRequest with ServiceContext and Linq

The following code is retrieving all the contacts where parent customer id is C6CB814A-BA75-E011-8720-00155DA5304E and updating their phone number.
var ServiceContext = new OrganizationServiceContext(service);
Guid accountid = new Guid("C6CB814A-BA75-E011-8720-00155DA5304E");

// Create an ExecuteMultipleRequest object.
ExecuteMultipleRequest requestWithResults = new ExecuteMultipleRequest()
{
    // Assign settings that define execution behavior: continue on error, don't return responses. 
    Settings = new ExecuteMultipleSettings()
    {
        ContinueOnError = false,
        ReturnResponses = false
    }, 
    // Create an empty organization request collection.
    Requests = new OrganizationRequestCollection()
};
               
requestWithResults.Requests.AddRange(from c in ServiceContext.CreateQuery("contact")
                                    where c["parentcustomerid"].Equals(accountid)
                                    select new UpdateRequest()
                                    {
                                        Target = new Entity("contact")
                                        {
                                            Id = c.Id,
                                            Attributes = { new KeyValuePair<string,object>("telephone1", "+61402234212") }
                                        }
                                    });

// Excute the requests
ExecuteMultipleResponse Response = (ExecuteMultipleResponse)service.Execute(requestWithResults);

Monday, February 3, 2014

Create View in CRM using coding.

 var fetchxml = "<fetch distinct='true' mapping='logical' output-format='xml-platform' version='1.0'><entity name='account'><attribute name='name'/><attribute name='primarycontactid'/><attribute name='telephone1'/><attribute name='accountid'/><order descending='false' attribute='name'/><link-entity name='incident' alias='ac' link-type='outer' to='accountid' from='customerid'/><filter type='and'><condition attribute='customerid' operator='null' entityname='incident'/><condition attribute='statecode' operator='eq' value='0'/></filter></entity></fetch>";

            var savedQuery = new SavedQuery()
            {
                Name = "Acount with no Cases",
                ReturnedTypeCode = "account",
                FetchXml = fetchxml,

                QueryType = 0
            };
            _service.Create(savedQuery);

Friday, May 24, 2013

Get Required Attendee(Activity Party) value from Appointment.


Guid Id = new Guid("D77839B3-CBC2-E211-8DC3-B4B52F6714CA");
            XrmServiceContext _context = new XrmServiceContext(_service);
            Appointment appointment = _context.AppointmentSet.Where(p=>p.ActivityId==Id).SingleOrDefault();
            if (appointment != null)
            {
               
                EntityCollection receipt = new EntityCollection();
                receipt = appointment.GetAttributeValue<EntityCollection>("requiredattendees");
                for (int i = 0; i < receipt.Entities.Count; i++)
                {
                    ActivityParty ap = receipt[i].ToEntity<ActivityParty>();

                    string id,name;

                    if (ap.PartyId.LogicalName == "account")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "contact")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                    if (ap.PartyId.LogicalName == "systemuser")
                    {
                        id = ap.PartyId.Id.ToString();
                        name = ap.PartyId.Name;
                    }
                }
            }

Monday, November 5, 2012

how to get (ScriptObject)HtmlPage.Window.GetProperty(“Xrm”) in Silverlight Application when it embedded to HTML Page in CRM


dynamic xrmnew = (ScriptObject)HtmlPage.Window.GetProperty("Xrm");
if (xrmnew == null)
{
    HtmlWindow parentWindow = HtmlPage.Window.GetProperty("parent") as HtmlWindow;
    xrmnew = (ScriptObject)parentWindow.GetProperty("Xrm");
}
Guid Id = new Guid(xrmnew.Page.data.entity.getId());

Monday, October 29, 2012

How to Publish Webresource using coding/InPlug


 PublishXmlRequest request = new PublishXmlRequest()
 {
                           ParameterXml = String.Format(@"<importexportxml><webresources><webresource>{0}</webresource></webresources></importexportxml>", webResource.WebResourceId)
 };

 service.Execute(request);


webResource.WebResourceId=This is the Guid of Webresource


Please make sure that if you are using this code in PlugIn then you should register the PlugIn in Asynchnronous mode.

if you want to Publish all customization then


PublishAllXmlRequest publishRequest = new PublishAllXmlRequest();
service.Execute(publishRequest);

Tuesday, September 11, 2012

Qualified Lead in CRM 2011.


SetStateRequest request = new SetStateRequest
{
               EntityMoniker = new EntityReference("lead", new Guid(leadduns["leadid"].ToString())),
               State = new OptionSetValue(1),
               Status = new OptionSetValue(3)
};
 _service.Execute(request);

Monday, August 13, 2012

Activate or Deactivate record in CRM 2011

We can Activate\Deactivate record. Below is the code snippet.


For Ex.


  Entity entNewLead = new Entity("lead");
  entNewLead["leadid"] = new Guid(leadduns["leadid"].ToString());
  entNewLead["statuscode"] = new OptionSetValue(2);
  entNewLead["statecode"] = new OptionSetValue(1);
  _service.Update(entNewLead);

Wednesday, July 11, 2012

How to set status Completed in Phone call in CRM 2011?

Introduction;

                       I am going to show you how to set status of Phone call in CRM 2011.For that first you have to create the Phone call activities and then after you can set the status of that Phonecall.That means First create a Phone call and then after you set the status of that Phone call.

    SetStateRequest stateform = new SetStateRequest();
    stateform.EntityMoniker = new EntityReference();
    stateform.EntityMoniker.LogicalName = "phonecall";
    stateform.EntityMoniker.Id = new Guid(accid.ToString()); //This is activityId of that Phone call.
    stateform.State = new OptionSetValue(1);
    stateform.Status = new OptionSetValue(2);

If you want to check more status code about phone call or any Entity then Click on this URL.
http://rc.crm.dynamics.com/rc/regcont/en_us/op/articles/statestatus.aspx
                      

Monday, July 9, 2012

How to Attach Notes in Entity in CRM 2011.


Introduction:
                   Hello Today I am going to show tou how to Add Notes in Entity.Here I have insert one Record into the Account entity and after that i am inserting Notes into that Record.

For this First you have to create Console Application.

See the Class Code here.

using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Reflection;
using System.Security.Cryptography.X509Certificates;
using System.Net.Security;

using System.ServiceModel.Description;
using System.ServiceModel;
public class Program
    {
        private static IOrganizationService _service;
        private static OrganizationServiceProxy _serviceProxy;
        private static OrganizationServiceContext orgContext;
        static public void Main(string[] args)
        {
            Program p = new Program();
            p.InsertAccount();
            Console.WriteLine("Inserted eith Notes");
            Console.ReadKey();
        }
        private void InsertAccount()
        {
            try
            {
                string file = "insertlead.txt";
                GetCRMService();
                Entity entity = new Entity("account");
                entity["name"] = "Kartik G Patel";

                entity["emailaddress1"] = "kartik@gmail.com";
                 Guid Accountid=_service.Create(entity);

                


                Entity annotation = new Entity("annotation");
                annotation["objectid"] = new EntityReference("account", Accountid);
                annotation["subject"] = "Kartik Comments";
                annotation["notetext"] = Convert.ToString("This is Kartik's Comment.");
                _service.Create(annotation);
            



            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    
        public static void GetCRMService()
        {
            try
            {

                string file = "connection.txt";
                Uri organizationuri = new Uri("https://kartik.crm5.dynamics.com/XRMServices/2011/Organization.svc");
                Uri homeRealmUri = null;

                /*Live CRM*/
                var deviceIDcreds = new ClientCredentials();
                deviceIDcreds.UserName.UserName = "11pqlm4ldg5nqps9b4ivlngbfv";
                deviceIDcreds.UserName.Password = "J-n60IBG7h;Ga`b5##SsDQhP";



                /*Live CRM*/
                var liveIDCreds = new ClientCredentials();
                liveIDCreds.UserName.UserName = "username";
                liveIDCreds.UserName.Password = "password";

                /* If you are not using Live CRM
                ClientCredentials credential = new ClientCredentials();
                credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Organization Name");
                */
                //_serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, credential, null);
                _serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, liveIDCreds, deviceIDcreds);
                _serviceProxy.EnableProxyTypes();

                _service = (IOrganizationService)_serviceProxy;
                orgContext = new OrganizationServiceContext(_serviceProxy);
                File.AppendAllLines(file, new string[] { "connection tested" });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    }

In My code you can see the comments where i show you if you are not using Live CRM then just Replace

var deviceIDcreds = new ClientCredentials();
deviceIDcreds.UserName.UserName = "11pqlm4ldg5nqps9b4ivlngbfv";
deviceIDcreds.UserName.Password = "J-n60IBG7h;Ga`b5##SsDQhP";

var liveIDCreds = new ClientCredentials();
liveIDCreds.UserName.UserName = "username";
liveIDCreds.UserName.Password = "password";

with

ClientCredentials credential = new ClientCredentials();
credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Organization Name");
_serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, credential, null);

Download the Sample Code from Here
 Download

Wednesday, June 20, 2012

Assign Owner to Account in CRM 2011


Introduction:

  Here I am Posting how to assign/Change a Owner to any account.

Here The First step will find the account to which the owner to set.after finding it pass the Guid of the new owner to the AssignRequest.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Collections;
using System.ServiceModel.Description;
using System.ServiceModel;

    public class Setowner
    {
        private static IOrganizationService _service;
        private static OrganizationServiceProxy _serviceProxy;
        private static OrganizationServiceContext orgContext;


        static public void Main(string[] args)
        {
            Setowner p = new Setowner();
            p.Settingowner();
            Console.WriteLine("Owner set");
            Console.ReadKey();
        }

        private void Settingowner()
        {
            try
            {
                string file = "SetOwner.txt";
                GetCRMService();
              
                //Find the account to which the owner has to set
                var query = from a in orgContext.CreateQuery("account")
                            where (String)a["name"] == "manish"
                            select a["accountid"];
                foreach (var accid in query)
                {

                    try
                    {
                        AssignRequest assign = new AssignRequest
                        {

                            //systemuser; i.e., User to whome you are assigning the entity to
                            //Current record which you are assigning to the user
                            Assignee = new EntityReference("systemuser", GetOwnerId("Dinesh Desai")),
                            Target = new EntityReference("account", new Guid(accid.ToString()))

                        };

                        // Execute the Request
                        _service.Execute(assign);
                        File.AppendAllLines(file, new string[] { "Assigned" });

                    }
                    catch (FaultException ex)
                    {
                        File.AppendAllLines("Error.txt", new string[] { "manish" + ":" + (ex.InnerException == null ? ex.Message : ex.InnerException.Message) });
                    }
                }
            }

            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    
       // This Method will Find the Guid of the Owner
        private Guid GetOwnerId(string owner)
        {
            Guid OwnerId = Guid.Empty;

            var query = from a in orgContext.CreateQuery("systemuser")
                        where (String)a["fullname"] == owner.Trim()
                        select a["systemuserid"];

            foreach (var id in query)
            {
                OwnerId = new Guid(id.ToString());
            }

            return OwnerId;
        }

       //For connection to CRM
        private static void GetCRMService()
        {
            try
            {

                string file = "connection.txt";
                Uri organizationuri = new Uri("https://kartik.crm5.dynamics.com/XRMServices/2011/Organization.svc");
                Uri homeRealmUri = null;

            


          
                ClientCredentials credential = new ClientCredentials();
                credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Kartik");
            
              
                _serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri,credential, null);
                _serviceProxy.EnableProxyTypes();

                _service = (IOrganizationService)_serviceProxy;
                orgContext = new OrganizationServiceContext(_serviceProxy);
                File.AppendAllLines(file, new string[] { "connection tested" });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    }
}


GetCRMService()-This Method is For Setting up with CRM.That includes credential+CRM Url etc.
Settingowner():-This Method will be For setting the Owner to any account
GetOwnerId():-This Method is For Finding the Guid Of the new owner for account.

Same way you can set the Owner for any Entity You have to just set the Target in Settingowner() Method.
Here I take "account" in Target.Because we are setting the owner in account if you want to set it in contact then you just need to specify "contact" in place of  "account".


Download the Sample Code from Here
 Download

Insert Account Record in Account Entity in MS CRM 2011


Introduction:

      Here I am going to show how to insert account into CRM 2011.
      First you have to Add the appropriate Reference Dll for CRM.Add Reference microsoft.crm.sdk.proxy,microsoft.xrm.sdk,System.Servicemodel,System.EnterpriceService,System.Web.Services etc

       Here I am insering the account in CRM.I am insering the name,parent account and Email Address to CRM.As we know that Parent account is the Lookup value and to set the Look up value we need top find the Id of it and then need to insert it.so to set the Parent Account I need to Find the accountid of Account and then have to set.so I have Created on Method here that will Find the account id of the parent account.Here i am just inserting three value name,parent account and Email Address.but you can insert more if you want just need to set it.

Example

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Query;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Crm.Sdk.Messages;
using System.Net;
using System.IO;
using System.Xml;
using System.Xml.Linq;
using System.Data;
using System.Collections;
using System.ServiceModel.Description;
using System.ServiceModel;

 private static IOrganizationService _service;
        private static OrganizationServiceProxy _serviceProxy;
        private static OrganizationServiceContext orgContext;


        static public void Main(string[] args)
        {
            SampleTest p = new SampleTest();
            p.InsertAccount();
            Console.WriteLine("Inserted");
            Console.ReadKey();
        }

        private void InsertAccount()
        {
            try
            {
                string file = "insertlead.txt";
                GetCRMService();
                Entity entity = new Entity("account");
                entity["name"] = "Manish";
                entity["parentaccountid"] = new EntityReference("account", GetParentaccountid("dinesh"));//GetParentaccountid("Kartik"));
                entity["emailaddress1"] = "manish@gmail.com";
                _service.Create(entity);
                File.AppendAllLines(file, new string[] { entity["name"].ToString() });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }

        private Guid GetParentaccountid(string accountname)
        {
            Guid accountid = Guid.Empty;
            var querry = (from a in orgContext.CreateQuery("account") where (string)a["name"] == accountname select a["accountid"]).SingleOrDefault();
            accountid = new Guid(querry.ToString());
            //foreach (var k in querry)
            //{
            //    accountid = new Guid(querry.ToString());
            //}
            return accountid;
        }

        private static void GetCRMService()
        {
            try
            {

                string file = "connection.txt";
                Uri organizationuri = new Uri("https://kartik.crm5.dynamics.com/XRMServices/2011/Organization.svc");
                Uri homeRealmUri = null;

            
                ClientCredentials credential = new ClientCredentials();
                credential.Windows.ClientCredential = new NetworkCredential("username", "password", "Kartik");
          
            
                _serviceProxy = new OrganizationServiceProxy(organizationuri, homeRealmUri, credential, null);
                _serviceProxy.EnableProxyTypes();

                _service = (IOrganizationService)_serviceProxy;
                orgContext = new OrganizationServiceContext(_serviceProxy);
                File.AppendAllLines(file, new string[] { "connection tested" });
            }
            catch (FaultException ex)
            {
                File.AppendAllLines("error.txt", new string[] { (ex.InnerException == null ? ex.Message.ToString() : ex.InnerException.ToString()) });
            }
        }
    }
}

Download the Sample Code from Here
 Download