Is there any way to edit the email content before Autoemailing the PO through SSRS Routing.?

When I use:

http://exco-erp10-sql.excoeng.com/ReportServer/ReportExecution2005.asmx?/Reports/CustomReports/PurchaseOrderForm/POForm_9-22-20

I get this error:

  • The item ‘/Reports/CustomReports/PurchaseOrderForm/POForm_9-22-20’ cannot be found. (rsItemNotFound)

ok, can you try apending one of the other form name to the url instead of _9-22-20

Ok So I just realized there is another directory path ahead of the /reports…

I tired it last night thinking that was the problem but it still gave me an error…but I just noticed I had an extra // which was the issue…now I get to the Tableguid…so let me update my code and see if that fixes it

Urgh…now I am getting a new error ha ha this is going to be the death of me…

Application Error

Exception caught in: mscorlib

Error Detail 
============
Message: The network path was not found.

Program: CommonLanguageRuntimeLibrary
Method: WinIOError

Client Stack Trace 
==================
   at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
   at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
   at System.IO.File.InternalWriteAllBytes(String path, Byte[] bytes, Boolean checkHost)
   at System.IO.File.WriteAllBytes(String path, Byte[] bytes)
   at Script.GenerateReportPDF(String ServerURL, String report, String tableguid, String PDFfilename)
   at Script.epiButtonC1_Click(Object sender, EventArgs args)
   at System.Windows.Forms.Control.OnClick(EventArgs e)
   at Infragistics.Win.Misc.UltraButtonBase.OnClick(EventArgs e)
   at Ice.Lib.Framework.EpiButton.OnClick(EventArgs e)
   at Infragistics.Win.Misc.UltraButton.OnMouseUp(MouseEventArgs e)
   at Ice.Lib.Framework.EpiButton.OnMouseUp(MouseEventArgs e)
   at System.Windows.Forms.Control.WmMouseUp(Message& m, MouseButtons button, Int32 clicks)
   at System.Windows.Forms.Control.WndProc(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.OnMessage(Message& m)
   at System.Windows.Forms.Control.ControlNativeWindow.WndProc(Message& m)
   at System.Windows.Forms.NativeWindow.Callback(IntPtr hWnd, Int32 msg, IntPtr wparam, IntPtr lparam)

Ok so I have eliminated the errors…I changed the location that the PDF is being saved to my local drive…and the PDF is being created (finally). However, Outlook seems to be the issue now. After a few mins and email DOES show up in my drafts, so it is doing something…with the correct PO number and contact info…but no attachment and its not showing my the draft when its being created…so I am getting closer!

Yeah, was gonna say that this is refering to a local path on your PC… I have this pointing to a shared drive on a local server

string FileName = String.Format(@"C:\Epicor\ERP10.2Client\ExcoClient\PrintReports\{0}.pdf", PONUM);

Regarding the no attachment… I’ll read through your code again…

Have you got this line un-commented??

oMsg.Attachments.Add(FileName,Outlook.OlAttachmentType.olByValue, Type.Missing,Type.Missing);

yeah the code is so messy now as well as I have been going back and forth and updating pulling my hair out ha ha going to go through it line by line now as I know that its at least “working”…see where I get to

Again, appreciate all your time on this, really helps having someone pointing me in the right direction

Yeah, I remember when I was trying to get it working… very tricky

Comment out all this part

oMsg.Attachments.Add(@"\\<SERVER>\Shared\Purchasing\Purchase Order Terms and Conditions.pdf",Outlook.OlAttachmentType.olByValue, Type.Missing,Type.Missing);


var FolderId = Guid.NewGuid().ToString("N").ToUpper();		          
var TempPath = Path.Combine(Path.GetTempPath(), FolderId);
if (!Directory.Exists(TempPath))
{
Directory.CreateDirectory(TempPath);
}
foreach (DataRowView row in edvAutoAttachPOHeader.dataView)
{
var AttachPath = row["FileName"].ToString();
var AttachFileName = Path.GetFileName(AttachPath);
var AttachNewPath = Path.Combine(TempPath, AttachFileName);
var AttachDesc = row["DrawDesc"].ToString();
File.Copy(AttachPath, AttachNewPath);
if (File.Exists(AttachNewPath))
{
oMsg.Attachments.Add(AttachNewPath, Outlook.OlAttachmentType.olByValue, Type.Missing, Type.Missing);
}
}

MsgInspector.Activate(); // shows the new email message as topmost window.

Any ways… I’m going to bed

Ok I will keep trudging along…thanks Lawson!

Ok so for anyone following along I finally have it working…email pops up, adds the PO as attachment AND I have a Zip file that is created with a Windows batch file that pulls all of the attachments…we don’t always send attachment so if that file isn’t there it just skips it. I have NOT cleaned up the code so I am sure there are some things in there that aren’t needed but will go through when I have time…for now…it works…so that’s as good way to end the week as any! Thank you @LBARKER for all of the time spent…very much appreciated

// ** Place Event Handling Code Here **
		
		// This customisation requires 2 .dll files for the email automation to work. These files must exsist in the client
		// folder on the client machine before the customistaion can load. 
		// The files are:
		// - Microsoft.Office.Interop.Outlook.dll
		// - Microsoft.ReportViewer.WebForms.dll

		MessageBox.Show("Email and PO creation process has begun, this will take approx 10 seconds");
		EpiDataView edvPOHeader = (EpiDataView)oTrans.EpiDataViews["POHeader"];
		int PONUM;
		string Approved;
		string Requestor;
		string Supplier;
		string CurrentCompany;
		string toName;
		string VendorContact;

		// check if there is data loaded into the form. if not return from method.
		if ( (bool)edvPOHeader.HasRow == false )
		{
						MessageBox.Show("There is no data present to email");
						return;
		}
		
		// Get data from the form
		Approved = (string)edvPOHeader.dataView[edvPOHeader.Row]["ApprovalStatus"];
		PONUM = (int)edvPOHeader.dataView[edvPOHeader.Row]["PONum"];
		Requestor = (string)edvPOHeader.dataView[edvPOHeader.Row]["EntryPerson"];
		Supplier = (string)edvPOHeader.dataView[edvPOHeader.Row]["VendorCntEmailAddress"];
		CurrentCompany = (string)edvPOHeader.dataView[edvPOHeader.Row]["Company"];
		toName = (string)edvPOHeader.dataView[edvPOHeader.Row]["VendorCntName"];
		VendorContact = (string)VenderName.Text;

		if (Approved == "A")
		{
				// check the supplier has an email address in Purchase Point.
				// grab the email address textbox (this textbox is a customisation) so we can check and get the address if it is there.....
				string PPemailAddress;
				

				PPemailAddress = txtEmail.Text;  //Supplier email address is in this Textbox.
				if (PPemailAddress == "")
				{
                    MessageBox.Show("No Email address. Add address to Supplier Purchase Point");
                    return;  // bailout - no email address...
				}

				Erp.Proxy.Rpt.POFormImpl Form = WCFServiceSupport.CreateImpl<Erp.Proxy.Rpt.POFormImpl>((Ice.Core.Session)oTrans.Session, Epicor.ServiceModel.Channels.ImplBase<Erp.Contracts.POFormSvcContract>.UriPath);

				// Make the report from the PO data
				Erp.Rpt.POFormDataSet POFormDS;
				POFormDS = Form.GetNewParameters();

				// set the PO number and report style and submit the form to the system agent.
				POFormDS.POFormParam[0].PONum = PONUM;

				switch (CurrentCompany) 
				{
					case "A":
						POFormDS.POFormParam[0].ReportStyleNum = 3001;
						break;
				}
				
				Guid workstationid = Guid.NewGuid();  // Put a GUID in the workstationId to allow searching for the report later.
				POFormDS.POFormParam[0].WorkstationID = String.Format("{0}",workstationid);			 // Using a GUID as the WorkstationID so it is easy to reteive this report
				POFormDS.POFormParam[0].DateFormat = "dd/MM/yy";
				POFormDS.POFormParam[0].ArchiveCode = 1;

				POFormDS.POFormParam[0].AutoAction = "SSRSGenerate";
				//MessageBox.Show("Submit to System Agent ...");
				Form.SubmitToAgent(POFormDS, "SystemTaskAgent", 0, 0, "Erp.UIRtp.POForm");   //Submit the report to be generate by the system agent.
				

				// get report data. Make a ReportMonitor, use it to get a reportmonitor dataset. The reportmonitor dataset will have the sysrowID of the report
				// we want, we can then use the sysrowID to get the report data to put into the SSRS report.
				Ice.Proxy.BO.ReportMonitorImpl RM = WCFServiceSupport.CreateImpl<Ice.Proxy.BO.ReportMonitorImpl>((Ice.Core.Session)oTrans.Session, Epicor.ServiceModel.Channels.ImplBase<Ice.Contracts.ReportMonitorSvcContract>.UriPath);
		
				int timer=0;
				
				bool morepages;
				SysRptLstListDataSet RptList;
				RptList = RM.GetList(@"WorkStationID ='"+workstationid+"'", 0, 0, out morepages);

				while (RptList.SysRptLstList.Count == 0 ) // setup a loop to look for when the report has been generated.
					{					
					System.Threading.Thread.Sleep(500);
					timer = timer + 1;
					if (timer > 120)
						{
						MessageBox.Show("Attempts to generate a PO pdf has timed-out. Please try again, and if that does not work, contact ERP Support");
						return;
						}
					RptList = RM.GetList(@"WorkStationID ='"+workstationid+"'", 0, 0, out morepages);
					}

				string tableguid;
				tableguid = RptList.SysRptLstList[0].FileName.Replace("REPORT DATABASE: ","");
				

				// make a pdf of the PO from the report
				string FileName = String.Format(@"C:\Purchase Orders\PO{0}.pdf", PONUM); // use this path to save to LOCAL
				string reportStyle;
				switch (CurrentCompany)
				{
				 default:
					case "A":
				reportStyle = "/Reports/CustomReports/PurchaseOrderForm/POForm_5.27.21";
						break;
				}
				GenerateReportPDF("/ReportServer/ReportExecution2005.asmx",reportStyle,tableguid,FileName);

				// create email message
				try
					{
					MessageBox.Show("Attaching to email...");
					Outlook.Application oApp = new Outlook.Application();
					Outlook.MailItem oMsg = (Outlook.MailItem)oApp.CreateItem(Outlook.OlItemType.olMailItem);
					Outlook.Inspector  MsgInspector =  oMsg.GetInspector; 
					string Signature = oMsg.HTMLBody; //capture signature for appending to custom message later.
					oMsg.Subject = "Confirmation of Purchase Order " + PONUM ;

					oMsg.HTMLBody = "<p>Hello " + VendorContact + ",<br><br>Please find new PO " + PONUM + " attached.<br><br>Please provide confirmation and advise any issues.<br><br>Thank You,</p>" + Signature;
										
					MsgInspector.Activate(); // shows the new email message as topmost window.
					
					// Set up the recipients for the email
					Outlook.Recipients oRecips = (Outlook.Recipients)oMsg.Recipients;
					Outlook.Recipient oRecip = (Outlook.Recipient)oRecips.Add(PPemailAddress);
					oRecip.Resolve();
					
					oMsg.Attachments.Add(FileName,Outlook.OlAttachmentType.olByValue, Type.Missing,Type.Missing);
					oMsg.Attachments.Add(@"C:\Users\adamk\Desktop\POList"+PONUM+".zip",Outlook.OlAttachmentType.olByValue, Type.Missing,Type.Missing);
					
					
					//Clean up
					oRecips = null;
					oRecip = null;
					oMsg = null;
					oApp = null;
					
					}
				catch (Exception Ex)
					{
					//MessageBox.Show("PO Email was attempted but failed. Please try again. If that doesn't work, please contact ERP Support");
					}
			}
		else
			MessageBox.Show("PO must be approved before it can be sent out");

	}

    private void GenerateReportPDF(String ServerURL, String report, String tableguid, String PDFfilename)
        {
            // setup report variables
            string deviceInfo = null;
            string extension = String.Empty;
            string mimeType = String.Empty;
            string encoding = String.Empty;
            Warning[] warnings = null;
            string[] streamIDs = null;
            string historyId = null;

            // Create a Report Execution object
            Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution.ReportExecutionService rsExec = new ReportExecutionService();
            
			rsExec.Credentials = System.Net.CredentialCache.DefaultCredentials;
            rsExec.Url = "/ReportServer/ReportExecution2005.asmx";

            // Load the report
            rsExec.LoadReport(report, historyId);

            // pass parameters
            rsExec.SetExecutionParameters(
            new ParameterValue[] { new ParameterValue() { Name = "TableGuid", Value = tableguid } }, null);

            // get pdf of report
            Byte[] results = rsExec.Render("PDF", deviceInfo,
                out extension, out encoding,
                out mimeType, out warnings, out streamIDs);

            File.WriteAllBytes(PDFfilename, results);
	

	}
3 Likes

Hi,

@LBARKER & @bmanners i’m getting below error after adding using Microsoft.Reporting.WebForms.Internal.Soap.ReportingServices2005.Execution;

Error: CS0234 - line 66 (66) - The type or namespace name ‘Internal’ does not exist in the namespace ‘Microsoft.Reporting.WebForms’ (are you missing an assembly reference?)

Naveen

You will need to add the assembly file to the client and add a reference to the file in the customisation.

Also note that this kind of customisation will not be possible in the Kinetic UI and as the desktop client is going away in the not too distant future you will get a limited life span out of this.

b46130cc-5962-4792-89d6-7bcaaeaba82cli_c1773357-d90a-462e-a5f4-1a23bdddff62.png

c2c5bc30-3253-49b1-937c-3fa275077c24fb_930174fc-b7fa-41f9-9c09-ea06f4d40955.png

ee659a15-bcb8-4bfe-affd-ec3104b46042tmt_db22fc01-3331-41d0-aa95-e3bf7418b3a0.png

1 Like

Hi @bmanners ,

I added to version 8 DLL, so it does not work. now changed to version 10 it’s working Thanks.

Hi @bmanners / @LBARKER ,
one more error:
Error: CS0246 - line 1836 (3795) - The type or namespace name ‘SysRptLstListDataSet’ could not be found (are you missing a using directive or an assembly reference?)

Naveen

Check you have the same assembly references as my screenshot…You might be missing the ReportMonitor one??

Brett

@bmanners Please find the below screenshot, already there.

Naveen

try adding below using to the code.

using Ice.BO;
1 Like

@bmanners Its worked :blush:

Now one more error :

Invalid URI: The format of the URI could not be determined.

below screenshot generatereportpdf getting error.

Naveen

I am guessing your report server is not called “xxx”. Put the correct server name in there instead.

Brett

@bmanners its not xxx. while pasting here, I changed as xxx.

the reportingservice is connecting.

@LBARKER @bmanners
Error : Invalid URI: The format of the URI could not be determined. kindly check and help on this