Tag Cloud

CRM 2011 (161) CRM 4.0 (144) C# (116) JScript (109) Plugin (92) Registry (90) Techpedia (77) PyS60 (68) WScript (43) Plugin Message (31) Exploit (27) ShellCode (26) FAQ (22) JavaScript (21) Killer Codes (21) Hax (18) VB 6.0 (17) Commands (16) VBScript (16) Quotes (15) Turbo C++ (13) WMI (13) Security (11) 1337 (10) Tutorials (10) Asp.Net (9) Safe Boot (9) Python (8) Interview Questions (6) video (6) Ajax (5) VC++ (5) WebService (5) Workflow (5) Bat (4) Dorks (4) Sql Server (4) Aptitude (3) Picklist (3) Tweak (3) WCF (3) regex (3) Config (2) LINQ (2) PHP (2) Shell (2) Silverlight (2) TSql (2) flowchart (2) serialize (2) ASHX (1) CRM 4.0 Videos (1) Debug (1) FetchXml (1) GAC (1) General (1) Generics (1) HttpWebRequest (1) InputParameters (1) Lookup (1) Offline Plug-ins (1) OutputParameters (1) Plug-in Constructor (1) Protocol (1) RIA (1) Sharepoint (1) Walkthrough (1) Web.config (1) design patterns (1) generic (1) iframe (1) secure config (1) unsecure config (1) url (1)

Pages

Saturday, April 13, 2013

CrmService.RetrieveMultiple Method

Retrieves a collection of entity instances based on the specified query criteria.

Syntax

  public BusinessEntityCollection RetrieveMultiple(
    QueryBase  query
  );



Parameters

query

Specifies either a QueryExpression or a QueryByAttribute object derived from the QueryBase class. This is the query to be executed for an entity. The QueryExpression or QueryByAttribute object contains the type information for the entity.

Return Value

A BusinessEntityCollection that is a collection of entities of the type of specified in the query parameter.

Remarks

Use this method to retrieve one or more entity instances based on criteria specified in the QueryExpression.

For better performance, use this method instead of using the Execute method with the RetrieveMultiple message.

To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see Retrieve Privileges.

The ColumnSet specified within the QueryExpression can only include the objects of the type of the calling entity. For more information, see Using ColumnSet.

Example

The following example demonstrates the use of the RetrieveMultiple method.

   1:  //# [ CrmService.RetrieveMultiple Method ]
   2:  // Set up the CRM Service.
   3:  CrmAuthenticationToken token = new CrmAuthenticationToken();
   4:  // You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
   5:  token.AuthenticationType = 0; 
   6:  token.OrganizationName = "AdventureWorksCycle";
   7:   
   8:  CrmService service = new CrmService();
   9:  service.Url = "http://<servername>:<port>/mscrmservices/2007/crmservice.asmx";
  10:  service.CrmAuthenticationTokenValue = token;
  11:  service.Credentials = System.Net.CredentialCache.DefaultCredentials;
  12:   
  13:  // Create the ColumnSet that indicates the properties to be retrieved.
  14:  ColumnSet cols = new ColumnSet();
  15:   
  16:  // Set the properties of the ColumnSet.
  17:  cols.Attributes = new string [] {"fullname", "contactid"};
  18:   
  19:  // Create the ConditionExpression.
  20:  ConditionExpression condition = new ConditionExpression();
  21:   
  22:  // Set the condition for the retrieval to be when the contact's address' city is Sammamish.
  23:  condition.AttributeName = "address1_city";
  24:  condition.Operator = ConditionOperator.Like;
  25:  condition.Values = new string [] {"Sammamish"};
  26:   
  27:  // Create the FilterExpression.
  28:  FilterExpression filter = new FilterExpression();
  29:   
  30:  // Set the properties of the filter.
  31:  filter.FilterOperator = LogicalOperator.And;
  32:  filter.Conditions = new ConditionExpression[] {condition};
  33:   
  34:  // Create the QueryExpression object.
  35:  QueryExpression query = new QueryExpression();
  36:   
  37:  // Set the properties of the QueryExpression object.
  38:  query.EntityName = EntityName.contact.ToString();
  39:  query.ColumnSet = cols;
  40:  query.Criteria = filter;
  41:   
  42:  // Retrieve the contacts.
  43:  BusinessEntityCollection contacts = service.RetrieveMultiple(query);

Monday, April 08, 2013

Dump the Entity Metadata

This sample shows how to use the MetadataService Web Service. It creates an XML file that provides a snapshot of attributes for a single entity using the Metadata APIs.




[C#]
sing System;
using System.Xml.Serialization;
using System.Xml;
using System.IO;

using Microsoft.Crm.Sdk.Utility;
using CrmSdk;
using MetadataServiceSdk;

namespace Microsoft.Crm.Sdk.HowTo
{
///
/// This sample shows how to retrieve all the metadata and write it to a file.
///

public class HowToMetaData
{
static void Main(string[] args)
{
// TODO: Change the server URL and Organization to match your CRM Server and CRM Organization
HowToMetaData.Run("http://localhost:5555", "CRM_SDK");
}

public static bool Run(string crmServerUrl, string orgName)
{
// Standard MetaData Service Setup
MetadataService service = CrmServiceUtility.GetMetadataService(crmServerUrl, orgName);

#region Setup Data Required for this Sample

bool success = false;

#endregion

try
{
// Retrieve the Metadata
RetrieveAllEntitiesRequest request = new RetrieveAllEntitiesRequest();
request.MetadataItems = MetadataItems.All;
RetrieveAllEntitiesResponse metadata = (RetrieveAllEntitiesResponse)service.Execute(request);


// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter sw = new StreamWriter("testfile.xml"))
{
// Create Xml Writer.
XmlTextWriter metadataWriter = new XmlTextWriter(sw);

// Start Xml File.
metadataWriter.WriteStartDocument();

// Metadata Xml Node.
metadataWriter.WriteStartElement("Metadata");

AttributeMetadata currentAttribute;// Declared outside of loop

// Iterate through all entities and add their attributes and relationships to the file.
foreach(EntityMetadata currentEntity in metadata.CrmMetadata)
{
// Start Entity Node
metadataWriter.WriteStartElement("Entity");

// Write the Entity's Information.
metadataWriter.WriteElementString("Name", currentEntity.LogicalName);

if (currentEntity.DisplayName.UserLocLabel != null)
{
metadataWriter.WriteElementString("DisplayName", currentEntity.DisplayName.UserLocLabel.Label);
}
else
{
metadataWriter.WriteElementString("DisplayName", "[NONE]");
}

if (currentEntity.DisplayCollectionName.UserLocLabel != null)
{
metadataWriter.WriteElementString("DisplayCollectionName", currentEntity.DisplayCollectionName.UserLocLabel.Label);
}
else
{
metadataWriter.WriteElementString("DisplayCollectionName", "[NONE]");
}

metadataWriter.WriteElementString("IsCustomEntity", currentEntity.IsCustomEntity.ToString());
metadataWriter.WriteElementString("IsCustomizable", currentEntity.IsCustomizable.ToString());
metadataWriter.WriteElementString("ReportViewName", currentEntity.ReportViewName);
metadataWriter.WriteElementString("PrimaryField", currentEntity.PrimaryField);
metadataWriter.WriteElementString("PrimaryKey", currentEntity.PrimaryKey);

#region Attributes

// Write Entity's Attributes.
metadataWriter.WriteStartElement("Attributes");

for (int j = 0; j < currentEntity.Attributes.Length; j++)
{
// Get Current Attribute.
currentAttribute = currentEntity.Attributes[j];
// Start Attribute Node
metadataWriter.WriteStartElement("Attribute");

// Write Attribute's information.
metadataWriter.WriteElementString("Name", currentAttribute.LogicalName);
metadataWriter.WriteElementString("Type", currentAttribute.AttributeType.ToString());

if (currentAttribute.DisplayName.UserLocLabel != null)
{
metadataWriter.WriteElementString("DisplayName", currentAttribute.DisplayName.UserLocLabel.Label);
}
else
{
metadataWriter.WriteElementString("DisplayName", "[NONE]");
}

metadataWriter.WriteElementString("Description", currentAttribute.IsCustomField.ToString());
metadataWriter.WriteElementString("IsCustomField", currentAttribute.IsCustomField.ToString());
metadataWriter.WriteElementString("RequiredLevel", currentAttribute.RequiredLevel.ToString());
metadataWriter.WriteElementString("ValidForCreate", currentAttribute.ValidForCreate.ToString());
metadataWriter.WriteElementString("ValidForRead", currentAttribute.ValidForRead.ToString());
metadataWriter.WriteElementString("ValidForUpdate", currentAttribute.ValidForUpdate.ToString());

// Write the Default Value if it is set.
if (currentAttribute.DefaultValue != null)
{
metadataWriter.WriteElementString("DefualtValue", currentAttribute.DefaultValue.ToString());
}

// Write the Description if it is set.
if (currentAttribute.Description != null &&
currentAttribute.Description.UserLocLabel != null)
{
metadataWriter.WriteElementString("Description", currentAttribute.Description.UserLocLabel.Label);
}


// Write Type Specific Attribute Information using helper functions.

Type attributeType = currentAttribute.GetType();

if (attributeType == typeof(DecimalAttributeMetadata))
{
writeDecimalAttribute((DecimalAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(FloatAttributeMetadata))
{
writeFloatAttribute((FloatAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(IntegerAttributeMetadata))
{
writeIntegerAttribute((IntegerAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(MoneyAttributeMetadata))
{
writeMoneyAttribute((MoneyAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(PicklistAttributeMetadata))
{
writePicklistAttribute((PicklistAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(StateAttributeMetadata))
{
writeStateAttribute((StateAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(StatusAttributeMetadata))
{
writeStatusAttribute((StatusAttributeMetadata)currentAttribute, metadataWriter);
}
else if (attributeType == typeof(StringAttributeMetadata))
{
writeStringAttribute((StringAttributeMetadata)currentAttribute, metadataWriter);
}

// End Attribute Node
metadataWriter.WriteEndElement();

}
// End Attributes Node
metadataWriter.WriteEndElement();

#endregion

#region References From

metadataWriter.WriteStartElement("OneToMany");

// Get Current ReferencesFrom
foreach (OneToManyMetadata currentRelationship in currentEntity.OneToManyRelationships)
{
// Start ReferencesFrom Node
metadataWriter.WriteStartElement("From");
metadataWriter.WriteElementString("Name", currentRelationship.SchemaName);
metadataWriter.WriteElementString("IsCustomRelationship", currentRelationship.IsCustomRelationship.ToString());
metadataWriter.WriteElementString("ReferencedEntity", currentRelationship.ReferencedEntity);
metadataWriter.WriteElementString("ReferencingEntity", currentRelationship.ReferencingEntity);
metadataWriter.WriteElementString("ReferencedAttribute", currentRelationship.ReferencedAttribute);
metadataWriter.WriteElementString("ReferencingAttribute", currentRelationship.ReferencingAttribute);

// End ReferencesFrom Node
metadataWriter.WriteEndElement();
}

metadataWriter.WriteEndElement();

#endregion

#region References To

metadataWriter.WriteStartElement("ManyToOne");

foreach (OneToManyMetadata currentRelationship in currentEntity.ManyToOneRelationships)
{
// Start ReferencesFrom Node
metadataWriter.WriteStartElement("To");
metadataWriter.WriteElementString("Name", currentRelationship.SchemaName);
metadataWriter.WriteElementString("IsCustomRelationship", currentRelationship.IsCustomRelationship.ToString());
metadataWriter.WriteElementString("ReferencedEntity", currentRelationship.ReferencedEntity);
metadataWriter.WriteElementString("ReferencingEntity", currentRelationship.ReferencingEntity);
metadataWriter.WriteElementString("ReferencedAttribute", currentRelationship.ReferencedAttribute);
metadataWriter.WriteElementString("ReferencingAttribute", currentRelationship.ReferencingAttribute);

// End ReferencesFrom Node
metadataWriter.WriteEndElement();
}

metadataWriter.WriteEndElement();

#endregion

// End Entity Node
metadataWriter.WriteEndElement();
}

// End Metadata Xml Node
metadataWriter.WriteEndElement();
metadataWriter.WriteEndDocument();

// Close xml writer.
metadataWriter.Close();
}

#region check success

if (metadata.CrmMetadata.Length > 0)
{
success = true;
}

#endregion
}
catch (System.Web.Services.Protocols.SoapException)
{
// Add your error handling code here.
}

return success;
}


#region Specific Attribute Helper Functions

// Writes the Decimal Specific Attributes
private static void writeDecimalAttribute (DecimalAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
writer.WriteElementString("Precision", attribute.Precision.ToString());
}

// Writes the Float Specific Attributes
private static void writeFloatAttribute (FloatAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
writer.WriteElementString("Precision", attribute.Precision.ToString());
}

// Writes the Integer Specific Attributes
private static void writeIntegerAttribute (IntegerAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
}

// Writes the Money Specific Attributes
private static void writeMoneyAttribute (MoneyAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MinValue", attribute.MinValue.ToString());
writer.WriteElementString("MaxValue", attribute.MaxValue.ToString());
writer.WriteElementString("Precision", attribute.Precision.ToString());
}

// Writes the Picklist Specific Attributes
private static void writePicklistAttribute (PicklistAttributeMetadata attribute, XmlTextWriter writer)
{
// Writes the picklist's options
writer.WriteStartElement("Options");

// Writes the attributes of each picklist option
for (int i = 0; i < attribute.Options.Length; i++)
{
writer.WriteStartElement("Option");
writer.WriteElementString("OptionValue", attribute.Options[i].Value.ToString());
writer.WriteElementString("Description", attribute.Options[i].Label.UserLocLabel.Label);
writer.WriteEndElement();
}

writer.WriteEndElement();
}

// Writes the State Specific Attributes
private static void writeStateAttribute (StateAttributeMetadata attribute, XmlTextWriter writer)
{
// Writes the state's options
writer.WriteStartElement("Options");

// Writes the attributes of each picklist option
for (int i = 0; i < attribute.Options.Length; i++)
{
writer.WriteStartElement("Option");
writer.WriteElementString("OptionValue", attribute.Options[i].Value.ToString());
writer.WriteElementString("Description", attribute.Options[i].Label.UserLocLabel.Label);
writer.WriteElementString("DefaultStatus", attribute.Options[i].DefaultStatus.ToString());
writer.WriteEndElement();
}

writer.WriteEndElement();
}

// Writes the Status Specific Attributes
private static void writeStatusAttribute (StatusAttributeMetadata attribute, XmlTextWriter writer)
{
// Writes the status's options
writer.WriteStartElement("Options");

// Writes the attributes of each picklist option
for (int i = 0; i < attribute.Options.Length; i++)
{
writer.WriteStartElement("Option");
writer.WriteElementString("OptionValue", attribute.Options[i].Value.ToString());
writer.WriteElementString("Description", attribute.Options[i].Label.UserLocLabel.Label);
writer.WriteElementString("State", attribute.Options[i].State.ToString());
writer.WriteEndElement();
}

writer.WriteEndElement();
}

// Writes the String Specific Attributes
private static void writeStringAttribute (StringAttributeMetadata attribute, XmlTextWriter writer)
{
writer.WriteElementString("MaxLength", attribute.MaxLength.ToString());
}
#endregion
}
}



Sunday, April 07, 2013

Route an Incident from a User to a Queue

The following code example shows how to route an incident from a user's Work In Progress (WIP) queue into a public queue. Similar code could be used to route an incident from a public queue into a WIP queue.


using System;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
public class HowToRoute
{
static void Main(string[] args)
{
// TODO: Change the server URL and organization to match your Microsoft
// Dynamics CRM Server and Microsoft Dynamics CRM organization.
HowToRoute.Run("http://localhost:5555", "CRM_SDK");
}

public static bool Run(string crmServerUrl, string orgName)
{
bool success = false;

try
{
// Set up the CRM Service.
CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

// Get the ID of the system user.
WhoAmIRequest userRequest = new WhoAmIRequest();
WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);

#region Setup Data Required for this Sample
// Create a new customer account.
account myAccount = new account();
myAccount.name = "A Bike Store";
Guid accountID = service.Create(myAccount);

// Create a new subject.
subject mySubject = new subject();
mySubject.title = "Bicycles";
Guid subjectID = service.Create(mySubject);

// Create a new incident.
incident incident = new incident();

Customer myCustomer = new Customer();
myCustomer.Value = accountID;
myCustomer.type = EntityName.account.ToString();
incident.customerid = myCustomer;

Lookup subjectLookup = new Lookup();
subjectLookup.Value = subjectID;
subjectLookup.type = EntityName.subject.ToString();
incident.subjectid = subjectLookup;

incident.title = "Broken Chain";
Guid incidentID = service.Create(incident);

// Create a new public Bicycle Cases queue.
queue publicQueue = new queue();

Lookup businessLookup = new Lookup();
businessLookup.Value = user.BusinessUnitId;
businessLookup.type = EntityName.businessunit.ToString();
publicQueue.businessunitid = businessLookup;

Lookup userLookup = new Lookup();
userLookup.Value = user.UserId;
userLookup.type = EntityName.systemuser.ToString();
publicQueue.primaryuserid = userLookup;

Picklist plist = new Picklist();
plist.name = "Public";
plist.Value = 1;
publicQueue.queuetypecode = plist;

publicQueue.name = "Bicycle Cases";
Guid publicQueueID = service.Create(publicQueue);
#endregion

// Find the WIP queue for the user who currently owns the incident.
// The queue type code for a WIP queue is 3.
QueryByAttribute query = new QueryByAttribute();
// Be aware that using AllColumns may adversely affect
// performance and cause unwanted cascading in subsequent
// updates. A best practice is to retrieve the least amount of
// data required.
query.ColumnSet = new AllColumns();
query.EntityName = EntityName.queue.ToString();
query.Attributes = new string[] { "primaryuserid", "queuetypecode" };
query.Values = new string[] { user.UserId.ToString(), "3" };
BusinessEntityCollection results = service.RetrieveMultiple(query);

queue wipQueue = (queue)results.BusinessEntities[0];

// Create a Target object that refers to the incident.
TargetQueuedIncident target = new TargetQueuedIncident();
// SDK:target.EntityId = new Guid("A0F2D8FE-6468-DA11-B748-000D9DD8CDAC");
target.EntityId = incidentID;

// Route the incident from the WIP queue to the public queue.
RouteRequest route = new RouteRequest();
route.Target = target;
route.RouteType = RouteType.Queue;
// SDK:route.EndpointId = new Guid("A0F2D8FE-6468-DA11-C748-000D9DD8CDAC");
route.EndpointId = publicQueueID;
// SDK:route.SourceQueueId = new Guid("A0F2D8FE-6468-DA11-D748-000D9DD8CDAC");
route.SourceQueueId = wipQueue.queueid.Value;

RouteResponse routed = null;
routed = (RouteResponse)service.Execute(route);

#region check success

if (routed != null) success = true;

#endregion

#region Remove Data Required for this Sample

service.Delete(EntityName.incident.ToString(), incidentID);
service.Delete(EntityName.queue.ToString(), publicQueueID);
service.Delete(EntityName.subject.ToString(), subjectID);
service.Delete(EntityName.account.ToString(), accountID);

#endregion
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine(String.Format("{0}. {1}", ex.Message, ex.Detail.InnerText));
}

return success;
}
}
}

Saturday, April 06, 2013

RetrieveMultiple Message (CrmService)

Retrieves a collection of business entity instances of a specified type based on query criteria.

The relevant classes are specified in the following table.

 

Type  Class
Request  RetrieveMultipleRequest
Response  RetrieveMultipleResponse
Entity account, activitypointer, etc

Remarks

To use this message, pass an instance of the RetrieveMultipleRequest class as the request parameter in the Execute method.

To perform this action, the caller must have access rights on the specified entity instance. For a list of required privileges, see RetrieveMultiple Privileges.

For better performance, use the RetrieveMultiple method instead of using this message.

Example

The following code examples show how to use the RetrieveMultiple message.

  


//# [RetrieveMultiple Message (CrmService)]

// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";
CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the column set that indicates the fields to be retrieved.
ColumnSet cols = new ColumnSet();

// Set the properties of the column set.
cols.Attributes = new string[] { "name", "accountid" };

// Create the ConditionExpression.
ConditionExpression condition = new ConditionExpression();

// Set the condition for the retrieval to be when the city in the account's address is Sammamish.
condition.AttributeName = "address1_city";
condition.Operator = ConditionOperator.Like;
condition.Values = new string[] { "Sammamish" };

// Create the FilterExpression.
FilterExpression filter = new FilterExpression();

// Set the properties of the filter.
filter.FilterOperator = LogicalOperator.And;
filter.Conditions = new ConditionExpression[] { condition };

// Create the QueryExpression object.
QueryExpression query = new QueryExpression();

// Set the properties of the QueryExpression object.
query.EntityName = EntityName.account.ToString();
query.ColumnSet = cols;
query.Criteria = filter;

// Create the request object.
RetrieveMultipleRequest retrieve = new RetrieveMultipleRequest();

// Set the properties of the request object.
retrieve.Query = query;

// Execute the request.
RetrieveMultipleResponse retrieved = (RetrieveMultipleResponse)service.Execute(retrieve);

Wednesday, April 03, 2013

Serialize and Deserialize Entities

This sample shows how to do standard serialization in Microsoft.NET Framework using Microsoft Dynamics CRM objects.

 

//CRM4.0 Serialize and Deserialize Entities
using System;
using System.Xml;
using System.Xml.Serialization;
using System.IO;
using CrmSdk;
using Microsoft.Crm.Sdk.Utility;

namespace Microsoft.Crm.Sdk.HowTo
{
///
/// The following sample demonstrates how to serialize a Microsoft Dynamics CRM contact into XML.
/// and then how to deserialize the XML back into a Microsoft Dynamics CRM contact. The sample performs
/// the following steps:
///
/// - Creates a contact to serialize.
/// - Retrieves the contact from Microsoft Dynamics CRM.
/// - Serializes the contact and writes the resulting XML to a file.
/// - Loads the XML file and deserializes it back into a Microsoft Dynamics CRM contact.
/// - Updates the contact in Microsoft Dynamics CRM.
///
/// NOTE: This process does not create Microsoft Dynamics CRM v1.x compatible XML.
///

public class SerializeAndDeserialize
{
static void Main(string[] args)
{
// TODO: Change the server URL and organization to match your Microsoft
// Dynamics CRM Server and Microsoft Dynamics CRM organization.
SerializeAndDeserialize.Run("http://localhost:5555", "CRM_SDK");
}

public static bool Run(string crmServerUrl, string orgName)
{
// Set up the CRM Service.
CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName);

#region Setup Data Required for this Sample

bool success = false;

#endregion

try
{
#region Create a temporary contact for this sample

// Create a contact entity that will be serialized into XML.
contact contactCreate = new contact();
contactCreate.firstname = "Jesper";
contactCreate.lastname = "Aaberg";
contactCreate.jobtitle = "Doctor";

// Create the entity in Microsoft Dynamics CRM and get its ID.
Guid contactId = service.Create(contactCreate);

#endregion

#region Retrieve the contact from CRM

// Create the column set object that indicates the fields to be retrieved.
ColumnSet columns = new ColumnSet();
columns.Attributes = new string [] {"contactid",
"firstname",
"lastname",
"jobtitle"};

// Retrieve the contact from Microsoft Dynamics CRM
// using the ID of the record that was just created.
// The EntityName indicates the EntityType of the object being retrieved.
contact contact = (contact)service.Retrieve(EntityName.contact.ToString(),
contactId,
columns);

#endregion

#region Serialize the contact into XML and save it

// Serialize the contact into XML and write it to the hard drive.
XmlSerializer serializer = new XmlSerializer(typeof(contact));

// Create a unique file name for the XML.
string filename = "Contact_" + contact.contactid.Value.ToString("B") + ".xml";

// Create an instance of StreamWriter to write text to a file.
// The using statement also closes the StreamWriter.
using (StreamWriter writer = new StreamWriter(filename))
{
// Write the XML to disk.
serializer.Serialize(writer, contact);
}

#endregion

#region Deserialize the CRM contact from XML

// Declare a Microsoft Dynamics CRM contact.
contact restoredContact;

using (StreamReader reader = new StreamReader(filename))
{
// Deserialize the contact object.
object tmp = serializer.Deserialize(reader);

// Cast the object into a Microsoft Dynamics CRM contact.
restoredContact = tmp as contact;
}

#endregion

#region Update contact in CRM

// Update the contact in Microsoft Dynamics CRM to verify that the deserialization worked.
restoredContact.jobtitle = "Plumber";
service.Update(restoredContact);

#endregion

#region Delete Data Required for this Sample
service.Delete(EntityName.contact.ToString(), contactId);
#endregion

#region Unit Test: Check if all is ok (test suite)

// If some key things are OK, return true.
if (filename != null &&
filename.Length > "Contact_.XML".Length &&
restoredContact != null)
{
return true;
}
else
{
return false;
}

#endregion
}
catch (System.Web.Services.Protocols.SoapException)
{
// Add your error handling code here.
}

return success;
}
}
}

Sunday, March 31, 2013

How to reference Assemblies in the GAC

If you install assemblies in the GAC and then wonder why you don't see them enumerated in the Add Reference dialogs, or, if you are complaining that if you browse the assembly folder in the Windows directory, you can't see the assembly in order to add a reference to it, read on.

The Add Reference dialog box is path-based and does not enumerate the components from the GAC. The assembly folder under windows is a special folder view and so you cannot browse to an assembly from this folder and expect to be able to Add a reference to it in the normal way.

If you want to use an assembly from the GAC, you should drop your assemblies into a local folder, and then add a reference to the assembly from this folder. You may want to set the "Copy Local" property to False for that assembly if you do not want the assembly to be copied locally to your project folders. At runtime, the application will automatically use the assembly from the GAC.

How to make your custom assemblies appear in the Add Reference dialog:

To display your assembly in the Add Reference dialog box, you can add a registry key, such as the following, which points to the location of the assembly


[HKEY_CURRENT_USER\SOFTWARE\Microsoft\.NETFramework\AssemblyFolders\MyAssemblies]@="C:\\MyAssemblies"
-- where "MyAssemblies" is the name of the folder in which the assemblies reside.


NOTE: You can create the this registry entry under the HKEY_LOCAL_MACHINE hive. This will change the setting for all of the users on the system. If you create this registry entry under HKEY_CURRENT_USER, this entry will affect the setting for only the current user.



For more information about assemblies and the GAC, vist the following MSDN Web Page:

http://msdn.microsoft.com/library/en-us/cpguide/html/cpconglobalassemblycache.asp

GrantAccess Message

Grants a security principal (user or team) access to the specified entity instance.

Remarks

To use this message, pass an instance of the GrantAccessRequest class as the request parameter in the Execute method.

This action applies to all child instances of the target entity instance. For all child instances, if the caller does not have share privileges for those entity types, or share rights to the instances, the child instances are not shared. As a result, the owner of the instance, or a user who shares the instance with share rights, automatically has share rights to all child instances of the target entity instance. In this case, only the lack of privileges for a particular entity type prevents the child instances from being shared.

See Cascading Rules for a description of how actions on a parent instance affect child instances.

To perform this action, the caller must have access rights on the entity instance specified in the request class. For a list of required privileges, see GrantAccess Privileges.



//# The following code example shows how to use the GrantAccess message.
// Set up the CRM service.
CrmAuthenticationToken token = new CrmAuthenticationToken();
// You can use enums.cs from the SDK\Helpers folder to get the enumeration for Active Directory authentication.
token.AuthenticationType = 0;
token.OrganizationName = "AdventureWorksCycle";

CrmService service = new CrmService();
service.Url = "http://:/mscrmservices/2007/crmservice.asmx";
service.CrmAuthenticationTokenValue = token;
service.Credentials = System.Net.CredentialCache.DefaultCredentials;

// Create the SecurityPrincipal Object
SecurityPrincipal principal = new SecurityPrincipal();
principal.Type = SecurityPrincipalType.User;

// PrincipalId is the Guid of the user to whom access is being granted
principal.PrincipalId = new Guid("7B222F98-F48A-4AED-9D09-77A19CB6EE82");

// Create the PrincipalAccess Object
PrincipalAccess principalAccess = new PrincipalAccess();

// Set the PrincipalAccess Object's Properties
principalAccess.Principal = principal;

// Gives the principal access to read
principalAccess.AccessMask = AccessRights.ReadAccess;

// Create the Target Object for the Request
TargetOwnedAccount target = new TargetOwnedAccount();

// EntityId is the Guid of the account access is being granted to
target.EntityId = new Guid("6A92D3AE-A9C9-4E44-9FA6-F3D5643753C1");

// Create the Request Object
GrantAccessRequest grant = new GrantAccessRequest();

// Set the Request Object's properties
grant.PrincipalAccess = principalAccess;
grant.Target = target;

// Execute the Request
GrantAccessResponse granted = (GrantAccessResponse)service.Execute(grant);