November 23, 2010 by Christoff Truter C#
I recently had the opportunity to do some integration with Microsoft CRM 4.0 (for the first time) for a client
- which proved to be quite straightforward.
Microsoft provides a SDK
(with tons of examples and documentation) and WebServices (soap based) to aid us with integration etc.
In this post we're going to have a quick look at how to add a file programmatically (using C#) to an account located within CRM.
Step 1: We need to connect/authenticate to CRM.
First of all add a web reference to the crm service e.g. http://cstruter/MSCRMServices/2007/CrmService.asmx".
Observe the following snippet:
CrmService crmService = new CrmService(); void Authenticate() { CrmAuthenticationToken token = new CrmAuthenticationToken(); token.AuthenticationType = 0; token.OrganizationName = "CSTruter"; crmService.Credentials = System.Net.CredentialCache.DefaultCredentials; crmService.CrmAuthenticationTokenValue = token; }
BusinessEntity[] GetAccount(string value) { ConditionExpression condition = new ConditionExpression { AttributeName = "name", Operator = ConditionOperator.Equal, Values = new object[] { value } }; QueryExpression query = new QueryExpression { EntityName = "account", ColumnSet = new ColumnSet { Attributes = new string[] { "name", "accountid" } }, Criteria = new FilterExpression { Conditions = new ConditionExpression[] { condition } } }; return crmService.RetrieveMultiple(query).BusinessEntities; }
Guid? AddAttachment(string filename, EntityName ObjectType, string ObjectId) { FileInfo fileInfo = new FileInfo(filename); if (fileInfo.Exists) { TargetCreateAnnotation target = new TargetCreateAnnotation { Annotation = new annotation { filename = fileInfo.Name, isdocument = new CrmBoolean { Value = true }, documentbody = Convert.ToBase64String(File.ReadAllBytes(filename)), mimetype = "application/octet-stream", objectid = new Lookup { type = "annotation", Value = new Guid(ObjectId) }, objecttypecode = new EntityNameReference { Value = ObjectType.ToString() } } }; CreateRequest request = new CreateRequest { Target = target }; CreateResponse response = (CreateResponse)crmService.Execute(request); return response.id; } return null; }Note: rather pass the actual mimetype of the file, than the octet defined in the snippet above
static void Main(string[] args) { Authenticate(); string somedoc = @"c:\6.xls"; BusinessEntity[] account = GetAccount("dude"); if (account.Length > 0) { string accountid = ((account)account[0]).accountid.Value.ToString(); AddAttachment(somedoc, EntityName.account, accountid); } }