Skip to main content

Notifications

Microsoft Dynamics CRM (Archived)

Continued Frustration Create email and attach PDF

Posted on by 1,695

Firstly a big thank you to all the suggestions and links that have helped me get this far. 

I import a text file into crm via a workflow that creates records in the new_remittanceadvice entity. Once the record is created I then execute the following code to create an email and attach a SSRS report ( PDF) to that email.  I have spent a few days trying different things to get this to work. I thus so far have managed to generate the email into the activities queue but there is no attachment. After putting in loads of writing to a log file I have narrowed the issue down to the point reportresult. Using SQL Manager , I can confirm that the new_remittanceadvice record has been created and the email record has been created and both record id's are passed to the workflow. I keep getting the error

reportresult The given key was not present in the dictionary.

( key info changed for security ) 

My code

Imports System.Activities
Imports Microsoft.Xrm.Sdk.Workflow
Imports System.IO
Imports Microsoft.Xrm.Sdk
Imports Generate_Send__PDF_ReportGenerationWorkflow
Imports Generate_Send__PDF_ReportGenerationWorkflow.ReportGenerator

Public Class clsEmailPDF
    Inherits CodeActivity



    Protected Overrides Sub Execute(executionContext As CodeActivityContext)
        Dim serviceFactory As IOrganizationServiceFactory = executionContext.GetExtension(Of IOrganizationServiceFactory)()
        Dim service As IOrganizationService = serviceFactory.CreateOrganizationService(Nothing)
        Dim context As IWorkflowContext = executionContext.GetExtension(Of IWorkflowContext)()
        Dim LogFile As String = C:\Logs\Remittance Email Errors " & context.PrimaryEntityId.ToString & " .txt"
        Try
            Dim rg As New ReportGenerator("xxx/.../reportexecution2005.asmx", System.Net.CredentialCache.DefaultCredentials)
            Dim parameters(0) As ReportServer.ParameterValue
            parameters(0) = New ReportServer.ParameterValue()
            parameters(0).Name = "ID"
            parameters(0).Value = context.PrimaryEntityId.ToString
            Try
                Dim reportresult As Byte() = rg.Render("/XXXXX_MSCRM/XXXXX Remittance Advice - AutoGenerate", FormatType.PDF, parameters)

                Dim attachment As New Entity("activitymimeattachment")
                attachment("objectid") = Email.[Get](Of EntityReference)(executionContext)
                attachment("objecttypecode") = "email"
                attachment("filename") = InlineAssignHelper(attachment("subject"), "Test.pdf")
                attachment("body") = System.Convert.ToBase64String(reportresult)
                service.Create(attachment)
            Catch ex As Exception
                Using sw As StreamWriter = File.AppendText(LogFile)
                    sw.WriteLine("reportresult " & ex.Message.ToString)
                End Using
            End Try
        Catch ex As Exception
            Using sw As StreamWriter = File.AppendText(LogFile)
                sw.WriteLine("TEST x " & ex.Message.ToString)
            End Using

        End Try

        Try

            'service.Execute(New SendEmailRequest() With {
            '        key.EmailId = new_emailaddress.[Get](Of EntityReference)(executionContext).Id,
            '        Key.IssueSend = True,
            '        Key.TrackingToken = String.Empty
            '    })
        Catch ex As Exception
            Using sw As StreamWriter = File.AppendText(LogFile)
                sw.WriteLine("TEST " & ex.Message.ToString)
            End Using
        End Try


    End Sub

    Private Shared Function InlineAssignHelper(Of T)(ByRef target As T, ByVal value As T) As T
        target = value
        Return value
    End Function


    <RequiredArgument>
    <Input("new_supplier")>
    Public Property new_supplier() As InArgument(Of String)
        Get
            Return m_new_supplier
        End Get
        Set
            m_new_supplier = Value
        End Set
    End Property
    Private m_new_supplier As InArgument(Of String)

    <Input("E-Mail")>
    <ReferenceTarget("email")>
    Public Property Email() As InArgument(Of EntityReference)
        Get
            Return m_Email
        End Get
        Set
            m_Email = Value
        End Set
    End Property
    Private m_Email As InArgument(Of EntityReference)
End Class

Report Generator Class

Imports System.IO
Imports System.Net
Imports System.Web.Services.Protocols
Imports Generate_Send__PDF_217263.ReportServer

Namespace ReportGenerationWorkflow
    Friend Class ReportGenerator

#Region "Privates"

        Private _reportexecutionservice As ReportServer.ReportExecutionService = Nothing
        Dim LogFile As String = "C:\Logs\Remittance Email Errors .txt"

#End Region

#Region "CTOR"
        Friend Sub New(ServiceUrl As String, credentials As ICredentials)

            If String.IsNullOrEmpty(ServiceUrl) Then
                Using sw As StreamWriter = File.AppendText(LogFile)
                    sw.WriteLine("TEST " & "Parameter ServiceUrl has to contain value")
                End Using
            End If

            If credentials Is Nothing Then
                Using sw As StreamWriter = File.AppendText(LogFile)
                    sw.WriteLine("TEST " & "Parameter Credentials has to contain value")
                End Using
            End If
            _reportexecutionservice = New ReportServer.ReportExecutionService()
            _reportexecutionservice.Credentials = System.Net.CredentialCache.DefaultCredentials ' credentials
            _reportexecutionservice.Url = ServiceUrl

        End Sub
#End Region

#Region "Methods"
        Friend Function Render(Report As String, formattype As FormatType) As Byte()
            Return Me.Render(Report, formattype, New ParameterValue() {})
        End Function
        Friend Function Render(Report As String, formattype As FormatType, parameters As ParameterValue()) As Byte()
            Dim result As Byte() = Nothing
            Dim format As String = GetFormatType(formattype)
            Dim historyID As String = Nothing
            Dim devInfo As String = "<DeviceInfo><Toolbar>False</Toolbar></DeviceInfo>"
            Dim encoding As String = String.Empty
            Dim mimeType As String = String.Empty
            Dim extension As String = String.Empty
            Dim warnings As Warning() = Nothing
            Dim streamIDs As String() = Nothing



            Try
                Dim execInfo As New ExecutionInfo()
                Dim execHeader As New ExecutionHeader()
                _reportexecutionservice.ExecutionHeaderValue = execHeader
                execInfo = _reportexecutionservice.LoadReport(Report, historyID)
                _reportexecutionservice.SetExecutionParameters(parameters, "en-us")
                result = _reportexecutionservice.Render(format, devInfo, extension, mimeType, encoding, warnings,
                    streamIDs)
            Catch ex As Exception
                If TypeOf ex Is SoapException Then
                    Dim sexc As SoapException = TryCast(ex, SoapException)
                    Using sw As StreamWriter = File.AppendText(LogFile)
                        sw.WriteLine("TEST " & String.Format("Error generating report - {0}", sexc.Detail.InnerText))
                    End Using
                Else
                    Using sw As StreamWriter = File.AppendText(LogFile)
                        sw.WriteLine("TEST " & String.Format("Error generating report - {0}", ex.Message))
                    End Using
                End If
                Using sw As StreamWriter = File.AppendText(LogFile)
                    sw.WriteLine("TEST " & ex.Message.ToString)
                End Using

            End Try
            Return result
        End Function

        Private Function GetFormatType(formattype__1 As FormatType) As String
            Select Case formattype__1
                Case FormatType.XML, FormatType.CSV, FormatType.IMAGE, FormatType.PDF, FormatType.MHTML, FormatType.EXCEL,
                    FormatType.Word
                    Return formattype__1.ToString()
                Case FormatType.HTML40
                    Return "HTML4.0"
                Case FormatType.HTML32
                    Return "HTML3.2"
                Case Else
                    Using sw As StreamWriter = File.AppendText(LogFile)
                        sw.WriteLine("TEST " & "Rendering type {0} is not available")
                    End Using
                    Return ""
            End Select
        End Function

#End Region

        Friend Enum FormatType
            XML
            CSV
            IMAGE
            PDF
            HTML40
            HTML32
            MHTML
            EXCEL
            Word
        End Enum

    End Class
End Namespace


*This post is locked for comments

  • Suggested answer
    Pete_N Profile Picture
    Pete_N 1,695 on at
    RE: Continued Frustration Create email and attach PDF

    resolved. Error in coding 

Under review

Thank you for your reply! To ensure a great experience for everyone, your content is awaiting approval by our Community Managers. Please check back later.

Helpful resources

Quick Links

December Spotlight Star - Muhammad Affan

Congratulations to a top community star!

Top 10 leaders for November!

Congratulations to our November super stars!

Community AMA December 12th

Join us as we continue to demystify the Dynamics 365 Contact Center

Leaderboard

#1
André Arnaud de Calavon Profile Picture

André Arnaud de Cal... 291,240 Super User 2024 Season 2

#2
Martin Dráb Profile Picture

Martin Dráb 230,149 Most Valuable Professional

#3
nmaenpaa Profile Picture

nmaenpaa 101,156

Leaderboard

Featured topics

Product updates

Dynamics 365 release plans