Page 1 of 1

Email with Attachment produces null reference exception

PostPosted: Mon Mar 16, 2026 2:56 pm
by SBarnes
With the code below in a scheduled plugin I am getting object not set to a reference of an object on save of the email.

If I remove adding the attachment it works.

Any ideas on how to fix this?

Code: Select all
private void ProcessSubscriptionInvoice(string invoice, DatabaseWorker dbWorker)
{
    Debug.DoDebug();
    var salesOrder = this._Manager.BusinessLogicFactory.CreateBusinessLogic<JiwaFinancials.Jiwa.JiwaSales.SalesOrder.SalesOrder >(null);
    salesOrder.Read(invoice);
    var lines = salesOrder.SalesOrderLines.Cast<JiwaFinancials.Jiwa.JiwaSales.SalesOrder.SalesOrderLine>().Where(l => l.CustomFieldValues.get_ItemFromSettingName("SubSales").Contents == "True" && l.CustomFieldValues.get_ItemFromSettingName("SubSent").Contents != "True"  && l.QuantityThisDelivery > 0).ToList();
    if(lines == null || lines.Count == 0)
    {
        return;
    }   
    var message = CreateSubscriptionMessage(salesOrder, lines);
    JiwaFinancials.Jiwa.JiwaApplication.JiwaEmail.EmailMessage email = this._Manager.BusinessLogicFactory.CreateBusinessLogic<JiwaFinancials.Jiwa.JiwaApplication.JiwaEmail.EmailMessage>(null);
    email.CreateNew();
    email.EmailFrom = this._Manager.Staff.EmailAddress;
    email.BodyIsHTML = false;
    email.EmailSubject = "Your RGS+ Subscription Purchase";
    string emailAddress = salesOrder.CustomFieldValues.get_ItemFromSettingName("SubEmail").Contents;
    if(emailAddress == null || emailAddress.Trim() == "" || !IsValidEmail(emailAddress))
    {
        return;
    }   
    email.EmailTo = emailAddress;
    email.EmailBody = message;

    var docName = GenerateReport(salesOrder.SalesOrderHistorys[salesOrder.CurrentHistoryNo].RecID);
    // Return the file
    byte[] bytes = System.IO.File.ReadAllBytes(docName);
    JiwaFinancials.Jiwa.JiwaApplication.Documents.Document doc = this._Manager.CollectionItemFactory.CreateCollectionItem<JiwaFinancials.Jiwa.JiwaApplication.Documents.Document>();
    doc.PhysicalFileName = System.IO.Path.GetFileName(docName)  ;
    doc.FileBinary = bytes;
    doc.Description = "Subscription Notice";
    doc.DocumentType = email.Attachments.DocumentTypes.GetDefaultDocumentType();

    email.Attachments.Add(doc);
    email.Save();
   SetOrdertoSubscriptionSent(salesOrder, email, doc);
    salesOrder.Save();
}


Code: Select all

public string GenerateReport(string historyID)
{
    string parameterName = SettingsVault.ParameterName;
    using (JiwaFinancials.Jiwa.JiwaApplication.Manager manager = this._Manager)
    {
        JiwaFinancials.Jiwa.JiwaApplication.Report.Configuration.ReportCollection m_Reports = manager.BusinessLogicFactory.CreateBusinessLogic<JiwaFinancials.Jiwa.JiwaApplication.Report.Configuration.ReportCollection>(null);
        m_Reports.Read();

        // find report with request.ReportID
        JiwaFinancials.Jiwa.JiwaApplication.Report.Configuration.Report report = m_Reports[SettingsVault.ReportID];

        if (report == null)
            throw new JiwaFinancials.Jiwa.JiwaApplication.Exceptions.RecordNotFoundException("Report not found");

        JiwaFinancials.Jiwa.JiwaApplication.JiwaPrintReport.JiwaPrintReport printReportObject = manager.BusinessLogicFactory.CreateBusinessLogic<JiwaFinancials.Jiwa.JiwaApplication.JiwaPrintReport.JiwaPrintReport>(null);
        printReportObject.Setup();

        printReportObject.LoadReport(report);


        foreach (JiwaFinancials.Jiwa.JiwaApplication.JiwaPrintReport.JiwaReportRange jiwaReportRange in printReportObject.JiwaReportRangeCollection)
        {
            string formulaName = printReportObject.JiwaPrintFormulaCollection[jiwaReportRange.FormulaKey].Name.Replace("{", "").Replace("}", "").Replace("@", "").Trim().ToUpper();
            string parameterCleaned = parameterName.Replace("{", "").Replace("}", "").Replace("@", "").Trim().ToUpper();   
            if (printReportObject.JiwaPrintFormulaCollection[jiwaReportRange.FormulaKey].Name.Replace("{", "").Replace("}", "").Replace("@", "").Trim().ToUpper() == parameterName.Replace("{", "").Replace("}", "").Replace("@", "").Trim().ToUpper())
            {
                jiwaReportRange.Value = historyID;
                break;
            }
        }


        printReportObject.UpdateReport();

        // export report to PDF
        string tempFolderPath = System.IO.Path.GetTempPath();
        string fileName = report.Title;

        // Make filename safe
        foreach (char c in System.IO.Path.GetInvalidFileNameChars())
        {
            fileName = fileName.Replace(c.ToString(), "");
        }

        string fullFileName = System.IO.Path.Combine(tempFolderPath, fileName) + ".pdf";
        if(System.IO.File.Exists(fullFileName))
        {
            System.IO.File.Delete(fullFileName);
        }   
        printReportObject.CrystalReportObject.ExportToDisk(CrystalDecisions.Shared.ExportFormatType.PortableDocFormat, fullFileName);
       
        return fullFileName;
       


    }
}

Re: Email with Attachment produces null reference exception

PostPosted: Mon Mar 16, 2026 3:32 pm
by Mike.Sheen
It may be the attempt to send the email which is causing the error - isolate that by setting the status of the email to ready to send prior to calling Save.
If that no longer causes the error, then it means the sending is causing the error - in which case, what Email Provider plugin(s) are enabled?

If the error does still occur on Save even when setting status to ready to send first, we have a standard plugin in Version 7 - Email Plugin - it adds an Email tool to the ribbon of the Plugin Maintenance form - when you press this, it creates an email with an attachment.

Does that work for you when you try it? If yes, then compare how that plugin creates, and adds attachments compared to yours.

Re: Email with Attachment produces null reference exception

PostPosted: Mon Mar 16, 2026 5:39 pm
by Mike.Sheen
Attached plugin works for me - it sends an email from the sales order form by adding a new tool to the ribbon "Email Test" - when pressed it executes your code to create an email message with an attachment and save it.

I had to remove some bits of your code which referred to methods not defined (such as IsValidEmail) - but it works fine.

Email.png


I used 7.2.1.25.

Re: Email with Attachment produces null reference exception

PostPosted: Mon Mar 16, 2026 6:04 pm
by SBarnes
Thanks Mike,

I'll have a look at it again tomorrow, given what I've looked at I have a suspicion that the last modified staff member is not getting set and that's what is causing the null reference as in the debugger that is null, I might switch it to the constructor below, there appears to be no override of the Setup method to create the object.


Code: Select all
 public Document(string RecID, byte[] NewFileBinary, JiwaFinancials.Jiwa.JiwaApplication.Documents.DocumentType DocumentType, DateTime LastSavedDateTime, string PhysicalFileName, string Description, Staff LastModifiedByStaffMember, int ItemNo, JiwaFinancials.Jiwa.JiwaApplication.Manager Manager)
        {
            this._PhysicalFileName = "";
            this._Description = "";
            this._LastSavedDateTime = DateAndTime.Now;
            this.Manager = Manager;
            base.RecID = RecID;
            this.FileBinary = NewFileBinary;
            this._DocumentType = DocumentType;
            this._LastSavedDateTime = LastSavedDateTime;
            this._PhysicalFileName = MyProject.Computer.FileSystem.GetName(PhysicalFileName);
            this._Description = Description;
            this._LastModifiedByStaffMember = LastModifiedByStaffMember;
            base.ItemNo = ItemNo;
        }


Re: Email with Attachment produces null reference exception

PostPosted: Mon Mar 16, 2026 7:09 pm
by Mike.Sheen
You could also give us a plugin which we can import into demo data that causes the issue - we'll be able to tell you quickly what the problem is then, and what the solution or workaround would be.

Re: Email with Attachment produces null reference exception  Topic is solved

PostPosted: Tue Mar 17, 2026 11:23 am
by SBarnes
Hey Mike,

Thanks for the help I finally figured out what was causing the problem if you look at the original Generate report code it has a using clause involving the manager, so c# did what it should do when it goes out of scope it disposed of it, and that was causing unpredictable behaviour my bad :x sorry for the time you spent on it.