/ Very primitive RTF 2 HTML reader
// Converts tiny subset of RTF (from VS IDE) into html.
// Author: Mike Stall (http://blogs.msdn.com/jmstall)
// Gets input RTF from clipboard.
using System;
using System.Collections.Generic;
using System.Text;
using System.Windows.Forms;
using System.Text.RegularExpressions;
using System.IO;
namespace ClipBoard1
{
class Program
{
[STAThread()]
static void Main(string[] args)
{
Console.WriteLine("Get RTF from the clipboard.");
IDataObject iData = Clipboard.GetDataObject();
string[] f = iData.GetFormats();
string rtf = (string)iData.GetData(DataFormats.Rtf);
Console.WriteLine(iData.GetData(DataFormats.Text));
// We assume the colortable and fontable are a standard preset used by VS.
// Avoids hassle of parsing them.
// Skip past {\colortbl.*;} and to the start of the real data
// @todo - regular expression would be good here.
int i1 = rtf.IndexOf(@"{\colortbl");
if (i1 <= 0) throw new ArgumentException("Bad input RTF.");
int i2 = rtf.IndexOf(";}", i1);
if (i2 <= 0) throw new ArgumentException("Bad input RTF.");
string data = rtf.Substring(i2 + 2, rtf.Length - (i2 + 2) - 1);
TextWriter tw = new StreamWriter("out.html");
Format(tw, data);
tw.Close();
}
// Default color table used by VS's IDE.
static string[] m_colorTable = new string[]
{
// rrGGbb
"#000000", // default, starts at index 0
"#000000", // real color table starts at index 1
"#0000FF",
"#00ffFF",
"#00FF00",
"#FF00FF",
"#FF0000",
"#FFFF00",
"#FFffFF",
"#000080",
"#008080",
"#008000",
"#800080",
"#800000",
"#808000",
"#808080",
"#c0c0c0"
};
// Escape HTML chars
static string Escape(string st)
{
st = st.Replace("&", "&");
st = st.Replace("<", "<");
st = st.Replace(">", ">");
return st;
}
// Convert the RTF data into an HTML stream.
// This rtf snippet is past the font + color tables, so we're just transfering control words now.
// Write out HTML to the text writer.
static void Format(TextWriter tw, string rtf)
{
tw.Write("");"); } // end Format() } }
tw.Write("");
// Example: \fs20 \cf2 using\cf0 System;
// root --> ('text' '\' ('control word' | 'escaped char'))+
// 'control word' --> (alpha)+ (numeric*) space?
// 'escaped char' = 'x'. Some characters \, {, } are escaped: '\x' --> 'x'
// @todo - handle embedded groups (begin with '{')
int idx = 0;
while (idx < rtf.Length)
{
// Get any text up to a '\'.
Regex r1 = new Regex(@"(.*?)\\", RegexOptions.Singleline | RegexOptions.IgnoreCase);
Match m = r1.Match(rtf, idx);
if (m.Length == 0) break;
// text will be empty if we have adjacent control words
string stText = m.Groups[1].ToString();
tw.Write(Escape(stText));
idx += m.Length;
// check for RTF escape characters. According to the spec, these are the only escaped chars.
char chNext = rtf[idx];
if (chNext == '{' || chNext == '}' || chNext == '\\')
{
// Escaped char
tw.Write(chNext);
idx++;
continue;
}
// Must be a control char. @todo- delimeter includes more than just space, right?
Regex r2 = new Regex(@"([\{a-z]+)([0-9]*) ", RegexOptions.Singleline | RegexOptions.IgnoreCase);
m = r2.Match(rtf, idx);
string stCtrlWord = m.Groups[1].ToString();
string stCtrlParam = m.Groups[2].ToString();
if (stCtrlWord == "cf")
{
// Set font color.
int iColor = Int32.Parse(stCtrlParam);
tw.Write(""); // close previous span, and start a new one for the given color.
tw.Write("");
}
else if (stCtrlWord == "fs")
{
// Sets font size. ignore
}
else if (stCtrlWord == "par")
{
// This is a newline. ignore
// @todo- I think the only reason we can ignore this is because the \par in our input are always followed by
// a '\r\n' and we're accidentally writing that.
}
else
{
throw new ArgumentException("Unrecognized control word '" + stCtrlWord + stCtrlParam + "'after:" + stText);
}
idx += m.Length;
}
tw.Write(Escape(rtf.Substring(idx))); // rest of string
tw.Write("
Tag Cloud
Pages
Wednesday, April 17, 2013
RTF to HTML Convertor
Sunday, April 14, 2013
Route an Incident from a User to a Queue
The following code example demonstrates how to route an incident from a user's work-in-progress queue to another queue.
1: //# Route an Incident from a User to a Queue
2: using System;
3: using CrmSdk;
4: using Microsoft.Crm.Sdk.Utility;
5: 6: namespace Microsoft.Crm.Sdk.HowTo
7: {8: public class HowToRoute
9: {10: static void Main(string[] args)
11: {12: // TODO: Change the server URL and organization to match your Microsoft
13: // Dynamics CRM Server and Microsoft Dynamics CRM organization.
14: HowToRoute.Run("http://localhost:5555", "CRM_SDK");
15: } 16: 17: public static bool Run(string crmServerUrl, string orgName)
18: {19: bool success = false;
20: 21: try
22: {23: // Set up the CRM Service.
24: CrmService service = CrmServiceUtility.GetCrmService(crmServerUrl, orgName); 25: 26: // Get the ID of the system user.
27: WhoAmIRequest userRequest = new WhoAmIRequest();
28: WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest); 29: 30: #region Setup Data Required for this Sample
31: // Create a new customer account.
32: account myAccount = new account();
33: myAccount.name = "A Bike Store";
34: Guid accountID = service.Create(myAccount); 35: 36: // Create a new subject.
37: subject mySubject = new subject();
38: mySubject.title = "Bicycles";
39: Guid subjectID = service.Create(mySubject); 40: 41: // Create a new incident.
42: incident incident = new incident();
43: 44: Customer myCustomer = new Customer();
45: myCustomer.Value = accountID; 46: myCustomer.type = EntityName.account.ToString(); 47: incident.customerid = myCustomer; 48: 49: Lookup subjectLookup = new Lookup();
50: subjectLookup.Value = subjectID; 51: subjectLookup.type = EntityName.subject.ToString(); 52: incident.subjectid = subjectLookup; 53: 54: incident.title = "Broken Chain";
55: Guid incidentID = service.Create(incident); 56: 57: // Create a new public Bicycle Cases queue.
58: queue publicQueue = new queue();
59: 60: Lookup businessLookup = new Lookup();
61: businessLookup.Value = user.BusinessUnitId; 62: businessLookup.type = EntityName.businessunit.ToString(); 63: publicQueue.businessunitid = businessLookup; 64: 65: Lookup userLookup = new Lookup();
66: userLookup.Value = user.UserId; 67: userLookup.type = EntityName.systemuser.ToString(); 68: publicQueue.primaryuserid = userLookup; 69: 70: Picklist plist = new Picklist();
71: plist.name = "Public";
72: plist.Value = 1; 73: publicQueue.queuetypecode = plist; 74: 75: publicQueue.name = "Bicycle Cases";
76: Guid publicQueueID = service.Create(publicQueue);77: #endregion
78: 79: // Find the WIP queue for the user who currently owns the incident.
80: // The queue type code for a WIP queue is 3.
81: QueryByAttribute query = new QueryByAttribute();
82: // Be aware that using AllColumns may adversely affect
83: // performance and cause unwanted cascading in subsequent
84: // updates. A best practice is to retrieve the least amount of
85: // data required.
86: query.ColumnSet = new AllColumns();
87: query.EntityName = EntityName.queue.ToString();88: query.Attributes = new string[] { "primaryuserid", "queuetypecode" };
89: query.Values = new string[] { user.UserId.ToString(), "3" };
90: BusinessEntityCollection results = service.RetrieveMultiple(query); 91: 92: queue wipQueue = (queue)results.BusinessEntities[0]; 93: 94: // Create a Target object that refers to the incident.
95: TargetQueuedIncident target = new TargetQueuedIncident();
96: // SDK:target.EntityId = new Guid("A0F2D8FE-6468-DA11-B748-000D9DD8CDAC");
97: target.EntityId = incidentID; 98: 99: // Route the incident from the WIP queue to the public queue.
100: RouteRequest route = new RouteRequest();
101: route.Target = target; 102: route.RouteType = RouteType.Queue;103: // SDK:route.EndpointId = new Guid("A0F2D8FE-6468-DA11-C748-000D9DD8CDAC");
104: route.EndpointId = publicQueueID;105: // SDK:route.SourceQueueId = new Guid("A0F2D8FE-6468-DA11-D748-000D9DD8CDAC");
106: route.SourceQueueId = wipQueue.queueid.Value; 107: 108: RouteResponse routed = null;
109: routed = (RouteResponse)service.Execute(route); 110: 111: #region check success
112: 113: if (routed != null) success = true;
114: 115: #endregion
116: 117: #region Remove Data Required for this Sample
118: 119: service.Delete(EntityName.incident.ToString(), incidentID); 120: service.Delete(EntityName.queue.ToString(), publicQueueID); 121: service.Delete(EntityName.subject.ToString(), subjectID); 122: service.Delete(EntityName.account.ToString(), accountID); 123: 124: #endregion
125: }126: catch (System.Web.Services.Protocols.SoapException ex)
127: {128: Console.WriteLine(String.Format("{0}. {1}", ex.Message, ex.Detail.InnerText));
129: } 130: 131: return success;
132: } 133: } 134: }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;
}
}
}