serving the solutions day and night

Pages

Showing posts with label delete. Show all posts
Showing posts with label delete. Show all posts

Wednesday, September 4, 2013

MS Dynamics CRM - Bulk Delete using XRM

Import
MSDynamicsCRM2011.DNS.Entities
microsoft.crm.sdk.proxy
microsoft.xrm.client
microsoft.xrm.sdk
System.ServiceModel
System.Data.DataSetExtensions

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Crm.Sdk.Messages;
using Microsoft.Xrm.Sdk;
using Microsoft.Xrm.Sdk.Client;
using Microsoft.Xrm.Sdk.Query;
using GCEntity = BT.CRM2011.DNS.Entities;
using System.ServiceModel.Description;

namespace CRM.Audit.BulkDelete
{
    class Audit
    {
        private BulkDeleteResponse _bdRes;
        private Guid _bdResID;
        private Guid _bdGUID;
        private ConditionExpression _conExp;

//Delete Method
        public void Delete()
        {
            SystemJob(GCEntity.dns_audit.EntityLogicalName, "Audit Bulk Delete - Code", _conExp);
            Console.WriteLine("Audit Deleted");
            SystemJob(GCEntity.Contact.EntityLogicalName, "Contact Bulk Delete - Code", _conExp);
            Console.WriteLine("Contact Deleted");
            Console.ReadLine();
        }


Saturday, December 8, 2012

CRM Dynamics 2011 OData Query Designer

OData Queries
Select All fields from all board entities
http://<Server_Name>/<Org_Name>/XRMServices/2011/OrganizationData.svc/g_boardSet()

Select specific fields from a specific board entity - g_boardSet(guid'{11b8a0d5-5328-e211-913d-0050568c5ad}')?$select=g_lastname,g_state

Select all board entities ordered by first name - select=g_lastname,g_state&orderby=g_firstname

Filter
All board entities with 'k' in their last name - orderby=gab_firstname&$filter=substringof('k',g_lastname)

number - CreditLimit/Value gt 1000
beginning/ending with z - &$filter=startswith( gab_lastname,'z'), endswith( gab_lastname,'z'), substringof('store',Name)
string or pick list - $filter=gab_ZipCode eq '68105'
Date time - filter=gab_DOB gt datetime'2012-09-01'
Lookup or entity reference - filter=gab_State/Id eq guid'{6512AB94-77F3-E111-9564-0050568C5AD0}'

$expand - Retrieve related records.
For example, to retrieve opportunity records related to accounts,
the query /AccountSet?$expand=opportunity_customer_accounts returns the opportunity records and the account records.

$skip - Sets the number of records to skip before it retrieves records in a collection. - $skip=2

$top - Determines the maximum number of records to return. Products?$top=5

Use the REST Endpoint for Web Resources
The REST endpoint for web resources provides an alternative interface to work with CRM data. You can use the REST endpoint to execute HTTP requests by using a service that is based on a Uniform Resource Identifier (URI).

MS Dynamics CRM Implementation of REST
MS Dynamics CRM 2011 uses the Windows Communication Foundation (WCF) Data Services framework to provide an Open Data Protocol (OData) endpoint that is a REST-based data service. This endpoint is called the Organization Data Service. In Microsoft Dynamics CRM, the service root URI is: [Your Organization Root URL]/xrmservices/2011/organizationdata.svc

OData sends and receives data by using either ATOM or JavaScript Object Notation (JSON). ATOM is an XML-based format. JSON is a text format that allows for serialization of JavaScript objects.

OData Entity Data Model (EDM)
An EDM organizes the data in the form of records of "entity types" and the associations between them.

The MS Dynamics CRM EDM is described in an OData Service Metadata document available at the following path: [Your Organization Root URL]/xrmservices/2011/organizationdata.svc/$metadata

Web Service Data in Web Resources (REST and SOAP Endpoint)

Assign Records, Retrieve Metadata, Execute Messages - SOAP Endpoint Web Serive
<organization URL>/XRMServices/2011/Organization.svc?wsdl

OData System Query Options Using the REST Endpoint

Create, Retrieve, Update, Delete, Associate and Disassociate records  - REST Endpoint Web Service

Limitations
The REST endpoint provides an alternative to the WCF SOAP endpoint, but there are currently some limitations.
  • Only Create, Retrieve, Update, and Delete actions can be performed on entity records.
  • The REST endpoint does not provide all the capabilities available in the SOAP endpoint.
  • Authentication is only possible within the application.
  • The OData protocol is not fully implemented. Some system query options are not available.
    You cannot use late binding with managed code with Silverlight.
REST CODE
CreateOrUpdateContact: function () {
var objVoter = {};
var emptyID = "00000000-0000-0000-0000-000000000000";

objContact.AddressID = { Id: "12345678-9011-1213-1415-161718192021", LogicalName: "address" };
objContact.ContactType = { Value: 750001 };
objContact.RegistrationDate = regDate;
objContact.FirstName = firstName;
objContact.LastName = lastName;
objVoter.StatusCode = { Value: 757580013 };

var jsonEntity = window.JSON.stringify(objVoter);
var odataPath = CommonOperations.GetCrmUrl() + "/XRMServices/2011/OrganizationData.svc/ContactSet";
if (queryParams.contactid != null) odataPath += "(guid'" + queryParams.contactid + "')";

$.ajax({
type: "POST",
async: false,
contentType: "application/json; charset=utf-8",
datatype: "json",
url: odataPath,
data: jsonEntity,
beforeSend: function (XMLHttpRequest) {
    XMLHttpRequest.setRequestHeader("Accept", "application/json");
    //update existing record
    if (queryParams.contactid != null) XMLHttpRequest.setRequestHeader("X-HTTP-Method", "MERGE");
},
success: function (response, textStatus, xhr) {
alert(response)
},
error: function (XmlHttpRequest, textStatus, error) {
   alert(XmlHttpRequest.responseText);
}
});
},

DELETE
//"/XRMServices/2011/OrganizationData.svc/ContactSet(guid'" + queryParams.contactid + "')";
XMLHttpRequest.setRequestHeader("X-HTTP-Method", "DELETE");

SOAP Code
 GenerateEnvelope: function (request) {
        var envelope = "";
        envelope += "<s:Envelope xmlns:s=\"http://schemas.xmlsoap.org/soap/envelope/\">";
        envelope += "  <s:Body>";
        envelope += "    <Execute xmlns=\"http://schemas.microsoft.com/xrm/2011/Contracts/Services\" xmlns:i=\"http://www.w3.org/2001/XMLSchema-instance\">";
        envelope += request;
        envelope += "    </Execute>";
        envelope += "  </s:Body>";
        envelope += "</s:Envelope>";
        return envelope;
    },
   
GenerateRequest: function (requesttype, keyvalue, requestname) {
        var request = "";
        request += "      <request ";
        if (requesttype.length >0)
            request += "      i:type=\"b:" + requesttype + "\" ";
        request += "       xmlns:a=\"http://schemas.microsoft.com/xrm/2011/Contracts\" xmlns:b=\"http://schemas.microsoft.com/crm/2011/Contracts\">";
        request += "        <a:Parameters xmlns:c=\"http://schemas.datacontract.org/2004/07/System.Collections.Generic\">";
        request += keyvalue;
        request += "        </a:Parameters>";
        request += "        <a:RequestId i:nil=\"true\" />";
        request += "        <a:RequestName>" + requestname + "</a:RequestName>";
        request += "      </request>";
        return request;
    },
   
    EntityReferenceKeyValue: function (key, entityname, id) {
        var kv = "<a:KeyValuePairOfstringanyType>";
        kv += "     <c:key>" + key + "</c:key>";
        kv += "     <c:value i:type=\"a:EntityReference\">";
        kv += "         <a:Id>" + id + "</a:Id>";
        kv += "         <a:LogicalName>" + entityname + "</a:LogicalName>";
        kv += "         <a:Name i:nil=\"true\" />";
        kv += "     </c:value>";
        kv += "</a:KeyValuePairOfstringanyType>";
        return kv;
    },

StringAnyTypeKeyValue: function (key, datatype, value) {
        var kv = "<a:KeyValuePairOfstringanyType>";
        kv += "     <c:key>" + key + "</c:key>";
        kv += "     <c:value i:type=\"a:" + datatype + "\">";
        kv += "         <a:Value>" + value + "</a:Value>";
        kv += "     </c:value>";
        kv += "</a:KeyValuePairOfstringanyType>";
        return kv;
    },  

ExecuteSoap(envelope) {
    $.ajax({
        type: 'POST',
        async: false,
        url: Xrm.Page.context.getClientUrl()+"/XRMServices/2011/OrganizationData.svc/",
        contentType: 'text/xml; charset=utf-8',
        headers: {
            SOAPAction: "http://schemas.microsoft.com/xrm/2011/Contracts/Services/IOrganizationService/Execute"
        },
        data: envelope,
        success: function (data, textStatus, XmlHttpRequest) {
            alert(data)
        },
        error: function (XmlHttpRequest, textStatus, error) {
            alert(error);
        }
    });
}


Change record Owner
var contactid = "get record id";
var teamid = "get current login user team id";
var keyvalue = EntityReferenceKeyValue("Target", "contact", contactid);
keyvalue += EntityReferenceKeyValue("Assignee", "team", teamid);
var request = GenerateRequest("AssignRequest", keyvalue, "Assign")
var envelope = GenerateEnvelope(request);
ExecuteSoap(envelope)


Retrieve Principal Access Request:
var userid = "get current login user id";
var contactid = "get contact record id";
var keyvalue = EntityReferenceKeyValue("Target", "contact", contactid);
keyvalue += EntityReferenceKeyValue("Principal", "systemuser", userid);
var request = GenerateRequest("RetrievePrincipalAccessRequest", keyvalue, "RetrievePrincipalAccess")

Change State and Status Reason
var keyvalue = EntityReferenceKeyValue("EntityMoniker", "contact", voterid);
keyvalue += StringAnyTypeKeyValue("State", "OptionSetValue", state);
keyvalue += StringAnyTypeKeyValue("Status", "OptionSetValue", status);
var request = GenerateRequest("SetStateRequest", keyvalue, "SetState")

Call Action
var StaffContactEntityName = "staffcontact",
    StaffContactEntityId = "{12341234-1234-1234-5668-7890568C3250}",
    ContactEntityName = "contact",
    ContactEntityId = Xrm.Page.data.entity.getId(),
    ActionUniqueName = "SendEmail_Action"
    var keyvalue = EntityReferenceKeyValue('Target', ContactEntityName, ContactEntityId);
    keyvalue += EntityReferenceKeyValue('ChiefOfficial', StaffContactEntityName, StaffContactEntityId);
var request = GenerateRequest('', keyvalue, ActionUniqueName);

Share Record
var keyvalue = EntityReferenceKeyValue("Target", "contact", contactid);
keyvalue += "          <a:KeyValuePairOfstringanyType>";
keyvalue += "            <c:key>PrincipalAccess</c:key>";
keyvalue += "            <c:value i:type=\"b:PrincipalAccess\">";
keyvalue += "              <b:AccessMask>ShareAccess WriteAccess</b:AccessMask>";
keyvalue += "              <b:Principal>";
keyvalue += "                <a:Id>" + userId + "</a:Id>";
keyvalue += "                <a:LogicalName>systemuser</a:LogicalName>";
keyvalue += "                <a:Name i:nil=\"true\" />";
keyvalue += "              </b:Principal>";
keyvalue += "            </c:value>";
keyvalue += "          </a:KeyValuePairOfstringanyType>";
var request = GenerateRequest("GrantAccessRequest", keyvalue, "GrantAccess")


Wednesday, October 3, 2012

Microsoft Dynamics CRM 2011 Data Management - Import, Export, Duplicate & Delete

Import
  • CRM Import Files formats: XML Spreadsheet 2003 (.xml), Comma-separated values (.csv), Rext (.txt), Compressed files (.zip)
  • Include a column for each required field on the entity into which you are importing the data.
  • One import file for each type of entity. 
  • Import multiple files into a single .zip file.
  • Maximum 8 megabytes (MB) size for each import file. 
  • Import Data Wizard basic process: Prepare the import files, Import the file and map the records & View the results and correct failures.
  • Dynamics CRM allows you to create templates for your import that you can download from the system.  In the Settings area -> click Data Management - > click Templates for Data Import. OR On the application ribbon -> click the Import Data button -> select Download Template for Import.
  • An import template outputs an XML file with all of the columns for the entity you selected:
    • All possible data fields for the entity are included.
    • All of the column headers are named and labeled correctly. 
    • Required data field names are bold in the top row.
    • Each cell provides additional information about the data that should go in the field, such as its  data type, maximum and minimum values, or maximum length.
    • For option sets, the template displays a list of the possible values for the field. 
    • If you try to enter a value that is not included in the option set or not in the format, you receive an error message
  • On the application ribbon -> click the Import Data button OR click the File tab -> select Import  OR Data from the Tools menu -> The Import Data Wizard opens.