CRM 2013 自动发送报表

Sql Server Report非常强大,导出不同格式的文档,比如work 或者excel都可以委托Reporting先做报表开发然后再在程序中调用生成指定格式的报表推送给用户,CRM也是集成了Reporting的强大功能。前些天遇到一个朋友请教一个功能说如何样利用报表订阅功能推送周报表,查询资料后可以配置Reporting订阅的功能来实现,可是局限于自己的reporting报表配置能力没有配送成功。最后又回到程序员的角度来考虑自己写程序来实现这个功能。

核心功能就是生成指定报表。将生成的报表附加到电子邮件上,然后发送给到相关人员。

1 生成报表,报表可以通过URL指定生成的格式,传给指定参数

  var url = "http://reportServer/ReportServer?%2fTeachNet_MSCRM%2f%E5%91%A8%E6%8A%A5&rs:Command=Render&rs:format=excel";


            NetworkCredential nc = new NetworkCredential(userName, password, domain);
            var path = @"c:\file.xls";

            string weekname = string.Format("周报-{0}", DateTime.Now.ToShortDateString());
            

            var handler = new HttpClientHandler { Credentials = nc };

            HttpClient client = new HttpClient(handler);
            client.DefaultRequestHeaders.Add("Authorization", key);


            var betys = client.GetByteArrayAsync(url).Result;

 2 创建电子邮件,指定发件人,收件人,主题,内容

 Email createEmail = new Email()
            {

                Subject = weekname,
                Description = "这是这周的周报请查收",

                From = new List<ActivityParty>() { new ActivityParty() { PartyId = new ContextCurrentUser().Current } },
                To = new List<ActivityParty>() { new ActivityParty() { PartyId = new ContextCurrentUser().Current } },



            };
            var id = _orgService.Create(createEmail);

 3 创建电子邮件附件

   ActivityMimeAttachment _sampleAttachment = new ActivityMimeAttachment
            {
                ObjectId = new EntityReference(Email.EntityLogicalName, id),
                ObjectTypeCode = Email.EntityLogicalName,
                Subject = weekname,
                Body = System.Convert.ToBase64String(
                       betys),
                FileName = String.Format("周报报表.xls")
            };
            _orgService.Create(_sampleAttachment);

 4 发送邮件

  SendEmailRequest sendEmailreq = new SendEmailRequest
            {
                EmailId = id,
                TrackingToken = "",
                IssueSend = true
            };

    SendEmailResponse sendEmailresp = (SendEmailResponse)_orgService.Execute(sendEmailreq);

 

posted on 2015-11-16 14:16  HelloHongfu  阅读(660)  评论(1编辑  收藏  举报

导航