Показаны сообщения с ярлыком sample code. Показать все сообщения
Показаны сообщения с ярлыком sample code. Показать все сообщения

2010-02-04

Get Picklist Value By Picklist Name

I wrote some method to get picklist value by knowing picklist name.

namespace test
{
    public class CrmServiceProvider
    {

  private WebMetadataService.MetadataService _MetaService = null;
  
  ///* Create a MetadataService end point */
        private WebMetadataService.MetadataService MetaService
        {
            get
            {
                if (_MetaService == null)
                {
                    _MetaService = new WebMetadataService.MetadataService();
                    _MetaService.Url = "http://localhost/mscrmservices/2007/metadataservice.asmx";

                    // Use a special user credentials
     NetworkCredential cred = new NetworkCredential();
                    cred.Domain = ConfigurationManager.AppSettings["Domain"];
                    cred.UserName = ConfigurationManager.AppSettings["UserName"];
                    cred.Password = ConfigurationManager.AppSettings["PassWord"];

                    _MetaService.UseDefaultCredentials = false;
                    _MetaService.Credentials = cred;

                    _MetaService.UnsafeAuthenticatedConnectionSharing = true;

                    WebMetadataService.CrmAuthenticationToken token = new WebMetadataService.CrmAuthenticationToken();
                    token.AuthenticationType = 0;
                    token.OrganizationName = ConfigurationManager.AppSettings["Organization"];

                    _MetaService.CrmAuthenticationTokenValue = token;
                }
                return _MetaService;
            }
        }


  public int GetPicklistValueByPicklistName(string PicklistName, string EntityLogicalName, string LogicalName)
  {
   int retval = -1;
   
   /* Retrieve the attribute metadata */
   WebMetadataService.RetrieveAttributeRequest attributeRequest = new WebMetadataService.RetrieveAttributeRequest();
   attributeRequest.EntityLogicalName = EntityLogicalName;
   attributeRequest.LogicalName = LogicalName; //picklist

   WebMetadataService.RetrieveAttributeResponse attributeResponse =
      (WebMetadataService.RetrieveAttributeResponse)MetaService.Execute(attributeRequest);

   /* Cast the attribute metadata to a picklist metadata */
   WebMetadataService.PicklistAttributeMetadata picklist =
      (WebMetadataService.PicklistAttributeMetadata)attributeResponse.AttributeMetadata;


   foreach (WebMetadataService.Option op in picklist.Options)
   {
    if (op.Label.UserLocLabel.Label == PicklistName)
     retval = op.Value.Value;
   }

   return retval;
  }
 }
}

To call this method use the next construction:
int psv = GetPicklistValueByPaymentSystemName(categorycode, "account", "accountcategorycode");
if (psv > 0)
{
 acc.accountcategorycode = new Picklist();
 acc.accountcategorycode.Value = psv;
}

2009-10-20

MS CRM Fetch and Retrieve from javascript

This code snippet was writing exactly like recommended in MSCRM SDK 4.09.
I was put it in OnLoad() event of my account form, and in the lookup field(at my example - new_postalcodeid) at OnChange() event I was calling my function.

There is two function that are doing the same work but with different methods.

var authenticationHeader = GenerateAuthenticationHeader();
crmForm.all.address1_city.ForceSubmit = true;

window.GetRegionByIndex_Retrieve = function()  
{  
 
if (crmForm.all.new_postalcodeid.DataValue == null)
{
  crmForm.all.address1_city.Disabled = false;
 crmForm.all.address1_city.DataValue = "";
 return;
}

var lookupItem = new Array;

lookupItem = crmForm.all.new_postalcodeid.DataValue;
if(lookupItem[0] != null)
{
 // Prepare the SOAP message.
 var xml = "<?xml version='1.0' encoding='utf-8'?>"+ 
 "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'"+
 " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'"+
 " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>"+ 
 authenticationHeader+ 
 "<soap:Body>"+ 
 "<Retrieve xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>"+ 
 "<entityName>new_postalcode</entityName>"+ 
 "<id>"+lookupItem[0].id+"</id>"+ 
 "<columnSet xmlns:q1='http://schemas.microsoft.com/crm/2006/Query' xsi:type='q1:ColumnSet'>"+ 
 "<q1:Attributes>"+ 
 "<q1:Attribute>new_regcityarea</q1:Attribute>"+ 
 "</q1:Attributes>"+ 
 "</columnSet>"+ 
 "</Retrieve>"+ 
 "</soap:Body>"+ 
 "</soap:Envelope>";
 // Prepare the xmlHttpObject and send the request.
 var xHReq = new ActiveXObject("Msxml2.XMLHTTP");
 xHReq.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
 xHReq.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
 xHReq.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xHReq.setRequestHeader("Content-Length", xml.length);
 xHReq.send(xml);
 // Capture the result.
 var resultXml = xHReq.responseXML;

 // Check for errors.
 var errorCount = resultXml.selectNodes('//error').length;
 if (errorCount != 0)
 {
 var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
 alert(msg);
 }
 // Display the retrieved value.
 else
 {
 crmForm.all.address1_city.DataValue = resultXml.selectSingleNode("//q1:new_regcityarea").nodeTypedValue;
 crmForm.all.address1_city.Disabled = true;
 }
}
}



window.GetRegionByIndex_Fetch = function (){
if (crmForm.all.new_postalcodeid.DataValue == null)
{
  crmForm.all.address1_city.Disabled = false;
 crmForm.all.address1_city.DataValue = "";
 return;
}

var lookupItem = new Array;

lookupItem = crmForm.all.new_postalcodeid.DataValue;
if(lookupItem[0] != null)
{
 var xml = "<?xml version='1.0' encoding='utf-8'?>" +
 "<soap:Envelope xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'" +
 " xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'" +
 " xmlns:xsd='http://www.w3.org/2001/XMLSchema'>" +
 authenticationHeader +
 "<soap:Body>" +
 "<Fetch xmlns='http://schemas.microsoft.com/crm/2007/WebServices'>" +
 "<fetchXml>" +
 "&lt;fetch mapping='logical'&gt;" +
 "&lt;entity name='new_postalcode'&gt;" +
 "&lt;attribute name='new_postalcodeid'/&gt;"+
 "&lt;attribute name='new_regcityarea'/&gt;"+
 "&lt;filter type='and'&gt;"+
 "&lt;condition attribute='new_postalcodeid' operator='eq' value='"+lookupItem[0].id+"'/&gt;"+
 "&lt;/filter&gt;&lt;/entity&gt;&lt;/fetch&gt;" +
 "</fetchXml>" +
 "</Fetch>" +
 " </soap:Body>" +
 "</soap:Envelope>";

 var xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
 xmlHttpRequest.Open("POST", "/mscrmservices/2007/CrmService.asmx", false);
 xmlHttpRequest.setRequestHeader("SOAPAction","http://schemas.microsoft.com/crm/2007/WebServices/Fetch");
 xmlHttpRequest.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
 xmlHttpRequest.setRequestHeader("Content-Length", xml.length);
 xmlHttpRequest.send(xml);
 
 var resultXml = xmlHttpRequest.responseXML;
 // Check for errors.
 var errorCount = resultXml.selectNodes('//error').length;
 if (errorCount != 0)
 {
  var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
  alert(msg);
 }
 // Process and display the results.
 else
 {

  // Capture the result and UnEncode it.
  var resultSet = new String();
  resultSet = resultXml.text;
  resultSet.replace('&lt;','<');
  resultSet.replace('&gt;','>');

  var xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
  xmlDoc.async = false;
  xmlDoc.loadXML(resultSet);
  var results = xmlDoc.getElementsByTagName('result');
  
  for(i=0;i<results.length;i++)
  {
   crmForm.all.address1_city.DataValue = results[i].selectSingleNode('//new_regcityarea').nodeTypedValue;
  }
   crmForm.all.address1_city.Disabled = true;
 }
}
}

2009-10-13

How to retrieve from many-to-many entity.

If you need to retrieve something from many-to-many relationship entity, and there is no such entity in CRM, then you should use the FetchXml, instead of Query.
// Base bodel of FetchXml for get relationship entity
string fetchXML =
"<fetch distinct='false' mapping='logical'>" +
"<entity name='" + relationshipName + "'><filter type='and'>" +
"<condition attribute='" + relatedEntityName + "id' operator='eq' value='" + relatedId + "' />" +
"<condition attribute='" + typeEntityName + "id' operator='eq' value='" + profileId + "' />" +
"</filter></entity>" + "</fetch>";

For example, next code snippet is checking a count of relations between the Account entity and New_Industry entity, wich relationship is many-to-many. To achieve this, I need to check the relationship entity - New_industry_account, wich is contains all of relation of our two entities.
ICrmService crmService = context.CreateCrmService(true);

// check for relation
#region FetchXML
string fetchXML =
"<fetch distinct='false' mapping='logical'>" +
"<entity name='new_industry_account'><filter type='and'>" +
"<condition attribute='accountid' operator='eq' value='" + accountid.ToString() + "' />" +
"</filter></entity></fetch>";
#endregion

string fetchresult = crmService.Fetch(fetchXML);
XmlDocument xmldoc = new XmlDocument();
xmldoc.LoadXml(fetchresult);
XmlNodeList xnodlist = xmldoc.SelectNodes("resultset/result");
if (xnodlist.Count > 0) { return; }

Update a number of custom attributes of DynamicEntity with TargetUpdateDynamic.

This code I was used in plugins for updating the custom attributes using Microsoft.Crm.SDK.

using System;
using System.Collections.Generic;
using System.Collections;

// Microsoft Dynamics CRM namespaces
using Microsoft.Crm.Sdk;
using Microsoft.Crm.Sdk.Query;
using Microsoft.Crm.SdkTypeProxy;

...

// Extract the DynamicEntity from the request.
entity = (DynamicEntity)retrieved.BusinessEntity;

// declare a property array
ArrayList arrProps = new ArrayList();

// create some property
CrmBooleanProperty new_withindustry = new CrmBooleanProperty();
new_withindustry.Name="new_withindustry";
new_withindustry.Value= new CrmBoolean();
new_withindustry.Value.Value=true;
arrProps.Add(new_withindustry);

// create another property
CrmMoneyProperty new_industrydeal = new CrmMoneyProperty();
new_industrydeal.Name = "new_industrydeal";
new_industrydeal.Value = new CrmMoney();
new_industrydeal.Value.Value = 12345.0m;
arrProps.Add(new_industrydeal);

//   Update the properties array on the DynamicEntity.
entity.Properties.AddRange((Property[])arrProps.ToArray(typeof(Property)));

// Create the update target.
TargetUpdateDynamic updateDynamic = new TargetUpdateDynamic();

// Set the properties of the target.
updateDynamic.Entity = entity;

//   Create the update request object.
UpdateRequest update = new UpdateRequest();

//   Set request properties.
update.Target = updateDynamic;

//   Execute the request.
UpdateResponse updated = (UpdateResponse)crmService.Execute(update);

2009-08-20

Embeded notification

We were needed some kind of notify message for user without any pop-up or an alerts.


function CreateRequestObject() {
if (window.XMLHttpRequest) {
try {
return new XMLHttpRequest();
} catch (e) { }
} else if (window.ActiveXObject) {
try {
return new ActiveXObject('Msxml2.XMLHTTP');
} catch (e) {
try {
return new ActiveXObject('Microsoft.XMLHTTP');
} catch (e) { }
}
}
return null;
}

function RetrieveEntity(sEntityName, GUID, sAttributeNames) {
var attributes = "";
if (sAttributeNames.length == 0)
return null;
for (var i = 0; i < sAttributeNames.length; i++) {
attributes += "" + sAttributeNames[i] + "";
}
var soapBody = "" +
"" +
"" + sEntityName + "" +
"" + GUID + "" +
"" +
"" + attributes + "" +
"
" +
"
" +
"
";
var soapXml = " "xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' " +
"xmlns:xsd='http://www.w3.org/2001/XMLSchema' " +
"xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'>";
soapXml += GenerateAuthenticationHeader();
soapXml += soapBody;
soapXml += "
";

xmlhttp = CreateRequestObject();
xmlhttp.open("POST", "/mscrmservices/2007/crmservice.asmx", false);
xmlhttp.setRequestHeader("Content-Type", "text/xml; charset=utf-8");
xmlhttp.setRequestHeader("SOAPAction", "http://schemas.microsoft.com/crm/2007/WebServices/Retrieve");
xmlhttp.setRequestHeader("Content-Length", soapXml.length);
xmlhttp.send(soapXml);

// Capture the result.
var resultXml = xmlhttp.responseXML;
// Check for errors.
var errorCount = resultXml.selectNodes('//error').length;
if (errorCount != 0) {
var msg = resultXml.selectSingleNode('//description').nodeTypedValue;
alert(msg);
return null;
}
// Display the retrieved value.
else {
var retEntityValues = new Array();
var retrieveNodes = resultXml.selectNodes("soap:Envelope/soap:Body/RetrieveResponse/RetrieveResult/q1:*");
for (var i = 0; i < retrieveNodes.length; i++) {
var nodeName = retrieveNodes[0].baseName;
var nodeValue = retrieveNodes[0].nodeTypedValue;
retEntityValues[nodeName] = nodeValue;
}
return retEntityValues
}
}

function AddNotification(noticationId, text) {
if (crmForm.all.Notifications.all[noticationId] != null)
crmForm.all.Notifications.all[noticationId + '_text'].innerHTML = text;
else {
crmForm.all.Notifications.innerHTML += '
' + text + '
';
crmForm.all.Notifications.style.display = 'block';
}
}

function RemoveNotification(noticationId) {
if (crmForm.all.Notifications.all[noticationId] != null) {
crmForm.all.Notifications.all[noticationId].removeNode(true);
if (crmForm.all.Notifications.childNodes.length == 0)
crmForm.all.Notifications.style.display = 'none';
}
}

var customer = crmForm.all.customerid;
if (customer.DataValue != null && customer.DataValue[0].typename == 'account') {
var cs = new Array();
cs[0] = 'new_attention';
var acc = RetrieveEntity('account', customer.DataValue[0].id, cs);
if (acc != null && acc['new_attention'] == 1) {
AddNotification('NotificationAccount', 'Клиент требует внимания! Для более подробной информации перейдите в карточку клиента.');
crmForm.all.customerid_d.getElementsByTagName('SPAN')[0].style.color = 'Red';
}
else {
RemoveNotification('NotificationAccount');
}
}
else {
RemoveNotification('NotificationAccount');
}

2009-08-19

Get contact status in custom extended marketing list


declare @contactid uniqueidentifier
declare @campaignactivityid uniqueidentifier
-- some Guids
set @contactid='48CF39EE-AA8C-DE11-A526-000C2989FA53'
set @campaignactivityid='72CE8156-AD8C-DE11-A526-000C2989FA53'

select exL.New_ExtMarketingListsElementId, exL.New_contactStatus
from dbo.New_ExtMarketingListsElementExtensionBase exL
JOIN dbo.ContactBase cnt ON exL.new_contact=cnt.ContactId
JOIN dbo.ListBase lst ON exL.new_list=lst.ListId
JOIN dbo.CampaignActivityItemBase cai ON lst.ListId=cai.ItemId
where cnt.ContactId=@contactid
and cai.CampaignActivityId=@campaignactivityid

2009-07-20

How to write into the eventlog custom journal with impersonalization in code


private const string LOG_NAME = "MSCRM.Common";

///
/// Write message in log
///

public static void WriteLog(string message, Exception exception)
{
System.Security.Principal.WindowsImpersonationContext ctx = null;
ctx = System.Security.Principal.WindowsIdentity.Impersonate(IntPtr.Zero);
try
{
string logSource = "MSCRM.Common.Web.Controls.Grid";

if (EventLog.SourceExists(logSource))
{
if (!EventLog.LogNameFromSourceName(logSource, ".").Equals(LOG_NAME))
{
EventLog.DeleteEventSource(logSource, ".");
EventLog.CreateEventSource(logSource, LOG_NAME);
}
}
else
{
EventLog.CreateEventSource(logSource, LOG_NAME);
}
EventLog el = new EventLog();
el.Log = LOG_NAME;
el.Source = logSource;
el.WriteEntry(String.Format("{0}\nDetails:\n{1}", message, GetLogInfo(exception)), EventLogEntryType.Error);
}
catch (Exception ex)
{
throw ex;
}
finally
{
ctx.Undo();
}
}

2009-07-16

How to programmatically launch an application under a specific user


ProcessStartInfo psi = new ProcessStartInfo("cmd", @"/C c:\SomeApp.exe");
psi.UserName = "UserName";
psi.Domain = "DomaiName";
psi.Password = ReadPassword("password");
psi.UseShellExecute = false;
psi.RedirectStandardInput = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardError = true;
using (Process p = Process.Start(psi))
{
// if you need to wait the end of the process
p.WaitForExit();
}

public System.Security.SecureString ReadPassword(string password)
{
System.Security.SecureString secPass = new System.Security.SecureString();
for (int i = 0; i < password.Length; i++)
secPass.AppendChar(password[i]);
return secPass;
}

2009-06-26

Convert HTML to plain text and remove tags


// convert HTML to plain text
string Description = System.Web.HttpUtility.HtmlDecode(HTML_encoded_string);

Description = StripTags(Description);

...

// remove tags from HTML-parsed string
private string StripTags(string HTML)
{
System.Text.RegularExpressions.Regex objRegEx = new System.Text.RegularExpressions.Regex("<[^>]*>");

return objRegEx.Replace(HTML, "");
}

2009-05-05

Test before save

I don't want to write a server code if I can do the same at the client side.
Here is the test for INN field, that must contain only the numbers.

var re = new RegExp("[^0-9]");
if(crmForm.all.new_inn.DataValue != null){
if(re.test(crmForm.all.new_inn.DataValue == true){
alert("ИНН должен содержать только цифры");
event.returnValue = false;
return false;
}
}

2009-04-26

DateTime in MSCRM

How to format string to write in CrmDateTime attribute:


string startdate; // - can be a parameter in method

opportunity oop = new opportunity();

opp.new_startdate = new CrmDateTime();

if(startdate!="")
opp.new_startdate.Value = (Convert.ToDateTime(startdate)).ToString("yyyy-MM-ddTHH:mm:ss");
else
opp.new_startdate.Value = DateTime.Today.ToString("yyyy-MM-ddTHH:mm:ss");

2009-04-10

Null Values - based on MS CRM SDK

From Microsoft CRM SDK :

When you update an entity instance there is a mechanism you can use to differentiate the absence of a value from a null value. To set an attribute value to null you must set both IsNull and IsNullSpecified to true. For attributes of type String, you must assign the value to String.Empty. This same mechanism is used when you create a query to find a null value.

Another option is to use the type helper code available in Microsoft.Crm.Sdk assembly and in the CRMHelpers classes.

Example
The following code example shows you how to create null instances of the various Microsoft Dynamics CRM attribute types.

CrmBoolean boolean = new CrmBoolean();
boolean.IsNull = true;
boolean.IsNullSpecified = true;

CrmDecimal dec = new CrmDecimal();
dec.IsNull = true;
dec.IsNullSpecified = true;

CrmFloat f = new CrmFloat();
f.IsNull = true;
f.IsNullSpecified = true;

CrmMoney money = new CrmMoney();
money.IsNull = true;
money.IsNullSpecified = true;

CrmNumber number = new CrmNumber();
number.IsNull = true;
number.IsNullSpecified = true;

Lookup lookup = new Lookup();
lookup.IsNull = true;
lookup.IsNullSpecified = true;

PickList list = new PickList();
list.IsNull = true;
list.IsNullSpecified = true;

Status status = new Status();
status.IsNull = true;
status.IsNullSpecified = true;

Owner owner = new Owner();
owner.IsNull = true;
owner.IsNullSpecified = true;


Example
The following code example shows you how to create null instances of the various Microsoft Dynamics CRM attribute types using the type helper classes.

CrmBoolean boolean = CrmBoolean.Null;

CrmDecimal dec = CrmDecimal.Null;

CrmFloat flt = CrmFloat.Null;

CrmMoney money = CrmMoney.Null;

CrmNumber number = CrmNumber.Null;

Lookup lookup = Lookup.Null;

Picklist list = Picklist.Null;

Status status = Status.Null;

Owner owner = Owner.Null;


My Example
Moving the data from one field to another and cleaning the first field after that.

opportunity opp = new opportunity();
opp.opportunityid = new Key();
opp.opportunityid.Value = findedopp.opportunityid.Value;

opp.new_profittreshold = new CrmMoney();
opp.new_profittreshold.Value = (decimal)findedopp.new_investmenttreshold.Value;

opp.new_investmenttreshold = new CrmFloat();
opp.new_investmenttreshold.IsNull = true;
opp.new_investmenttreshold.IsNullSpecified = true;

service.Update(opp);

2008-09-17

Plugin's Starter Execution Method

Have found excellent method at David Fronk blog Starter Execution Method and slightly update it in to separate method.

// based on Starter Execution Method

/// 
/// Return the opportunity id
/// 
/// Plugin context/// opportunityid
public string GetEntityId(IPluginExecutionContext context)
{
 string opportunityid = "";
 DynamicEntity opportunityClose = null;

 switch (context.MessageName)
 {
  case "Create":
   if (context.OutputParameters.Properties.Contains("id"))
   {
    opportunityid = context.OutputParameters.Properties["id"].ToString();
   }
   break;
  case "Update":
   if (context.InputParameters.Properties.Contains(ParameterName.Target) && context.InputParameters.Properties[ParameterName.Target] is DynamicEntity)
   {
    DynamicEntity entity = (DynamicEntity)context.InputParameters.Properties[ParameterName.Target];
    opportunityid = ((Key)entity.Properties["opportunityid"]).Value.ToString();
   }
   break;
  case "SetState":
   if (context.InputParameters.Properties.Contains("EntityMoniker"))
   {
    if (context.InputParameters.Properties.Contains("State"))
    {
     Moniker entityMoniker = (Moniker)context.InputParameters.Properties[ParameterName.EntityMoniker];
     opportunityid = entityMoniker.Id.ToString();
    }
   }
   break;
  case "SetStateDynamicEntity":
   if (context.InputParameters.Properties.Contains("EntityMoniker"))
   {
    if (context.InputParameters.Properties.Contains("State"))
    {
     Moniker entityMoniker = (Moniker)context.InputParameters.Properties[ParameterName.EntityMoniker];
     opportunityid = entityMoniker.Id.ToString();
    }
   }
   break;
  case "Win":
   opportunityClose = (DynamicEntity)context.InputParameters["OpportunityClose"];
   Lookup WonLook = (Lookup)opportunityClose.Properties["opportunityid"];
   opportunityid = WonLook.Value.ToString();
   break;
  case "Lose":
   opportunityClose = (DynamicEntity)context.InputParameters["OpportunityClose"];
   Lookup LoseLook = (Lookup)opportunityClose.Properties["opportunityid"];
   opportunityid = LoseLook.Value.ToString();
   break;
  case "Assign":
   if (context.InputParameters.Properties.Contains("Assignee") && context.InputParameters.Properties["Assignee"] is SecurityPrincipal)
   {
    Moniker assignEntity = (Moniker)context.InputParameters.Properties["Target"];
    opportunityid = assignEntity.Id.ToString();
   }
   break;
  case "Delete":
   if (context.InputParameters.Properties.Contains("Target"))
   {
    Moniker entityMoniker = null;
    entityMoniker = (Moniker)context.InputParameters.Properties[ParameterName.Target];
    opportunityid = entityMoniker.Id.ToString();
   }
   break;
 }
 return opportunityid;
}

2008-08-05

TargetUpdate Sample Code.

Этого Sample Code я не нашел в SDK, однако нашел вопросы на форумах, оставленные без ответов и решенные с помощью CrmService.Update. Потому я решил написать такой пример.
Думаю кому-то будет интересно как же на самом деле может быть решена задача обновления через TargetUpdate.
private void EmailDeliveryChange(email emailResult, int new_delivery)
{
service = new CrmService.CrmService();
service.Credentials = System.Net.CredentialCache.DefaultCredentials;
service.Url = CrmServiceUrl;

TargetUpdateEmail tue = new TargetUpdateEmail();
// create new email entity for update
email emailUpdate = new email();

// Set the ID of entity which we want to update
emailUpdate.activityid = new Key();
emailUpdate.activityid.Value = new Guid(emailResult.activityid.Value.ToString()); // parameter

// set new value of attribute
emailUpdate.new_delivery = new Picklist();    
emailUpdate.new_delivery.Value = new_delivery;  // parameter

tue.Email = emailUpdate;    
UpdateRequest upreq = new UpdateRequest();

upreq.Target = tue;
UpdateResponse upres = (UpdateResponse)service.Execute(upreq);
}