使用c#到Crm 2015从xml数据获取附件

时间:2018-06-13 08:50:07

标签: c# xml dynamics-crm crm dynamics-crm-2015

我们有一个网站,客户用附件写下她的事件。 我可以把事件保存到Crm 2015系统。 我想要保存附件,如图片等。

我从xml中获取事件并逐个阅读并保存到Crm 2015系统:

foreach (XElement xmlIncident in xmlIncidents)
{

}

在这个foreach中,我可以获得附件值:

var attachments = xmlIncident.Elements("attachments"); //get the collection of attachments.

作为一个例子,ın可能的事件我有4张jpg照片,其中一个似乎是这样的c#代码:

  https://docs.sikayetvar.com/complaint/1054/10543034/gbhjk-1528636381_160x160.jpg   https://docs.sikayetvar.com/complaint/1054/10543034/gbhjk-1528636381.jpg   照片

我的问题是如何从xml数据中获取附件并使用c#将其保存到Crm 2015事件表

enter image description here

1 个答案:

答案 0 :(得分:0)

我想直接更新CRM数据库并不是一个好主意,因为CRM SDK中有很多可用的东西。

执行步骤:

  1. 从XML
  2. 获取文件路径
  3. 验证文件类型为 jpg ,然后将文件读为 Base64
  4. 创建Annotation类型的实体,其中objectid =记录GUID
  5. 请查看以下适用于您的代码

    Guid AttachToIncident(string filePath, Guid recordGuid){    
        Func<string,string> imageToBase64 = (fpath) => {
            using (Image image = Image.FromFile(fpath))
            {
                using (MemoryStream memStrm = new MemoryStream())
                {
                    image.Save(memStrm, image.RawFormat);
                    byte[] imageBytes = memStrm.ToArray();
                    string base64String = Convert.ToBase64String(imageBytes);
                    return base64String;
                }
            }   
        };
    
        string fileName = Path.GetFileName(filePath);
    
        Guid attachmentId = Guid.Empty;
    
        Entity newAnnotation = new Entity("annotation");
        newAnnotation["subject"] = "external attachment";
        newAnnotation["filename"] = filename;
        newAnnotation["mimetype"] = @"image/jpeg";
        newAnnotation["documentbody"] = imageToBase64(filePath);
        newAnnotation["objectid"] = new EntityReference("incident", recordGuid);
    
       //you must be knowing what this service is ;)
        attachmentId = orgService.Create(newAnnotation); 
        return attachmentId;    
    }