Email with Attachment produces null reference exception  Topic is solved

Discussions relating to Jiwa 7 plugin development, and the Jiwa 7 API.

Email with Attachment produces null reference exception

Postby SBarnes » Mon Mar 16, 2026 2:56 pm

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;
       


    }
}
Regards
Stuart Barnes
SBarnes
Shihan
Shihan
 
Posts: 1696
Joined: Fri Aug 15, 2008 3:27 pm
Topics Solved: 191

Re: Email with Attachment produces null reference exception

Postby Mike.Sheen » Mon Mar 16, 2026 3:32 pm

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.
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2583
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 807

Re: Email with Attachment produces null reference exception

Postby Mike.Sheen » Mon Mar 16, 2026 5:39 pm

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.
Attachments
Plugin Email Attachment Test.xml
(15.25 KiB) Downloaded 168 times
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2583
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 807

Re: Email with Attachment produces null reference exception

Postby SBarnes » Mon Mar 16, 2026 6:04 pm

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;
        }

Regards
Stuart Barnes
SBarnes
Shihan
Shihan
 
Posts: 1696
Joined: Fri Aug 15, 2008 3:27 pm
Topics Solved: 191

Re: Email with Attachment produces null reference exception

Postby Mike.Sheen » Mon Mar 16, 2026 7:09 pm

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.
Mike Sheen
Chief Software Engineer
Jiwa Financials

If I do answer your question to your satisfaction, please mark it as the post solving the topic so others with the same issue can readily identify the solution
User avatar
Mike.Sheen
Overflow Error
Overflow Error
 
Posts: 2583
Joined: Tue Feb 12, 2008 11:12 am
Location: Perth, Republic of Western Australia
Topics Solved: 807

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

Postby SBarnes » Tue Mar 17, 2026 11:23 am

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.
Regards
Stuart Barnes
SBarnes
Shihan
Shihan
 
Posts: 1696
Joined: Fri Aug 15, 2008 3:27 pm
Topics Solved: 191


Return to Technical and or Programming

Who is online

Users browsing this forum: No registered users and 1 guest