Free Support Forum - aspose.com

Exception "OutOfMemoryException" when converting when generating PPTX using Aspose.Slides for .NET

Hello aspose,

I am facing this issue while generating pptx file more than 50mb. Please help me to sort out this issue.I am using version 15.11.0.0.

13784 09:50:11 ERROR ChiragDekavadiya:System.OutOfMemoryException: Exception of type ‘System.OutOfMemoryException’ was thrown.
at ? ?.( ? , ? ? , Int32 , Int32 , ? ? )
at ?.(Boolean )
at ?.()
at ?.Write(Byte[] , Int32 , Int32 )
at ? ?.Write(Byte[] , Int32 , Int32 )
at ?.(Stream )
at ?.(Stream )
at ?.(Stream )
at ?. ()
at ?.(Stream )
at Aspose.Slides.Charts.ChartDataWorkbook.(Stream )
at Aspose.Slides.Charts.ChartData.ReadWorkbookStream()
at .(IChart , , ? )
at .(IChart , , ? , ? )
at .(IChart , ? , ? )
at .(IChart , ? , ? )
at ? .(IShape , , ? , ? )
at ? .(IGroupShape , , ? , ? )
at .(IBaseSlide , , ? )
at ? .(ISlide )
at ? .( , ISlide , ? )
at ? .(IPresentation , ? , PresentationTypeEx , IPptxOptions )
at Aspose.Slides.Presentation.(Stream , PresentationTypeEx , IPptxOptions )
at Aspose.Slides.Presentation.Save(Stream stream, SaveFormat format, ISaveOptions options)
at Aspose.Slides.Presentation.Save(Stream stream, SaveFormat format)
at SiriusDecisions.Website.Areas.BenchmarkAdmin.Controllers.MetricsResearchManagementController.PrintByMetricsAMFGroupThread(Object stateInfo)

I am facing this issue while generating pptx file. please let me know if you have idea about this.

@tushar007,

I have observed your comments. Can you please share source files along with environment details and sample project to reproduce issue so that we may further investigate to help you out. Also please try to use Aspose.Slides latest version 18.3 on your end before sharing requested information.

Please find character in bold with login below.

public void PrintByMetricsAMFGroupThread(object stateInfo)
{
bool IsGroupThreadError = false;
try
{
slideIndex = 0;
string ReportName = string.Format(@“Metrics Research Group.pptx”);
string ReportTemplatePath = string.Empty;
string ReportTemplateName = string.Empty;
string FolderPath = “Areas/BenchmarkAdmin/Common/”;
string subPath = currentLoginUser;
string PresentationSavePath = SharedPathForPPT + subPath + “/” + ReportName;
string MasterTemplatePath = Path.Combine(HttpRuntime.AppDomainAppPath, FolderPath + “DS_MetricsResearchMaster.pptx”);

            TableOfContents = new DataTable();
            TableOfContents.Columns.Add("MetricName", typeof(string));
            TableOfContents.Columns.Add("AMFType", typeof(string));
            TableOfContents.Columns.Add("SlideNumber", typeof(int));

            ReportTemplateName = "DS_MetricsResearch.pptx";
            ReportTemplatePath = Path.Combine(HttpRuntime.AppDomainAppPath, FolderPath + ReportTemplateName);

            Presentation MasterTemplate = new Presentation(MasterTemplatePath);
            Presentation Pres = new Presentation(ReportTemplatePath);

            LicenseFile licenseFile = new LicenseFile();
            licenseFile.AssignLicense();

            Contacts contact = _metricResearchDataStore.GetContactDetailsFromProfileId(currentLoginUser);
            string company_name = _metricResearchDataStore.GetCompanyNameFromAccountId(contact.AccountId);

            #region Title Slide (0)

            string PrimarySetName, SecondaryPeerSetName;
            if (printIsPeerSet == 0)
            {
                PrimarySetName = _peerSetDataStore.GetPeerSetByPeerSetId(Convert.ToInt64(printPrimaryPeerset)).PeerSet;
            }
            else
            {
                PrimarySetName = _responseSetDataStore.GetResponseSetByResponseSetId(Convert.ToInt64(printPrimaryPeerset)).ServiceResponseID;
            }
            if (Convert.ToInt64(printSecondaryPeerset) != 0)
            {
                if (printIsSecondaryPeerSet == 0)
                {
                    SecondaryPeerSetName = _peerSetDataStore.GetPeerSetByPeerSetId(Convert.ToInt64(printSecondaryPeerset)).PeerSet;
                }
                else
                {
                    SecondaryPeerSetName = _responseSetDataStore.GetResponseSetByResponseSetId(Convert.ToInt64(printSecondaryPeerset)).ServiceResponseID;
                }
            }
            else
            {
                SecondaryPeerSetName = "";
            }


            //SecondaryPeerSetName = Convert.ToInt64(printSecondaryPeerset) == 0 ? "" : _peerSetDataStore.GetPeerSetByPeerSetId(Convert.ToInt64(printSecondaryPeerset)).PeerSet;

            Pres = GetFirstSlide(MasterTemplate, Pres, PrimarySetName, SecondaryPeerSetName, contact);

            #endregion

            #region Get all metrics to print

            List<MetricsResearchMetricsViewModel> lstMetric = new List<MetricsResearchMetricsViewModel>();
            if (PrintIsfavourite)
            {
                lstMetric = _metricResearchDataStore.GetFavouriteMetrics();
            }
            else
            {
                if (PrintSelectedColor == "ALL")
                    lstMetric = _metricResearchDataStore.GetMetricsByMetricAMF(PrintFunctionId, PrintRoleId, PrintPrioritiesId, PrintModuleId, printMetric, null);
                else
                    lstMetric = _metricResearchDataStore.GetMetricsBasedonFilter(PrintFunctionId, PrintRoleId, PrintPrioritiesId, PrintModuleId, printMetric, null, null, (int?)(Convert.ToInt16(printPrimaryPeerset)), (int?)printIsPeerSet, (int?)printIsSecondaryPeerSet, (int?)(Convert.ToInt16(printSecondaryPeerset)), PrintSelectedColor);
            }

            DataSet ds = new DataSet();
            lstMetric = lstMetric.OrderBy(i => i.MetricAMF == "Readiness").
                                                 ThenBy(i => i.MetricAMF == "Activity").
                                                 ThenBy(i => i.MetricAMF == "Output").
                                                 ThenBy(i => i.MetricAMF == "Impact")
                                                 .ToList();
            // foreach (MetricsResearchMetricsViewModel metric in lstMetric)
            for (int metric = 0; metric < lstMetric.Count(); metric++)
            {
                try
                {
                    if ((lstMetric[metric].MetricType.ToLower() == "numeric ranges - single column" || lstMetric[metric].MetricType.ToLower() == "numeric ranges - grid" || lstMetric[metric].MetricType.ToLower() == "maturity scale - single column") && ((printIsPeerSet == 1 && printIsSecondaryPeerSet == 1) || (printIsPeerSet == 1 && printIsSecondaryPeerSet == 0 && printSecondaryPeerset == "0")))
                    {
                        lstMetric[metric].ChartType = "line";
                    }

                    // Author : Ghanshyam  Gandhi
                    // Date : 13/02/2018
                    // Desc : If Chart Type is Box and Whisker than change chart type as Grid and use Second Priority Chart type
                    //Start
                    if (lstMetric[metric].ChartType.ToLower() == "boxandwhiskers")
                    {
                        lstMetric[metric].ChartType = lstMetric[metric].SChartType;
                        lstMetric[metric].MetricType = "grid";
                    }
                    //END
                    PrintIncludeMetrics = true;
                    if (PrintSelectedColor != "ALL" ? (PrintfilteredMetricIds != null ? PrintfilteredMetricIds.Contains(" " + lstMetric[metric].MetricId + " ") : false) : true)
                    {
                        #region Chart Slide (1) and Table Slide (2)

                        TableOfContents.Rows.Add(lstMetric[metric].Metric, lstMetric[metric].MetricAMF, slideIndex);
                        TableId++;

                        if (lstMetric[metric].MetricType.ToLower() == "grid" || lstMetric[metric].MetricType.ToLower() == "numeric ranges - single column" || lstMetric[metric].MetricType.ToLower() == "numeric ranges - grid")
                        {
                            vmColumnsAndRows columnsAndRows = BindColumnsAndRowsForReport(lstMetric[metric].MetricId);
                            Pres = generateChartForReport(printPrimaryPeerset, printSecondaryPeerset, printIsPeerSet, printIsSecondaryPeerSet, lstMetric[metric], MasterTemplate, Pres, "Group", contact, company_name, PrimarySetName, SecondaryPeerSetName, columnsAndRows, PrintSelectedColor);
                        }
                        else
                        {
                            vmColumnsAndRows columnsAndRows = BindColumnsAndRowsForReport(lstMetric[metric].MetricId);
                            if ((columnsAndRows.Columns != null || columnsAndRows.Rows != null) && (lstMetric[metric].MetricType.ToLower() == "list - single select" || lstMetric[metric].MetricType.ToLower() == "h-list - open response"))
                            {
                                Pres = generateChartForReport(printPrimaryPeerset, printSecondaryPeerset, printIsPeerSet, printIsSecondaryPeerSet, lstMetric[metric], MasterTemplate, Pres, "Group", contact, company_name, PrimarySetName, SecondaryPeerSetName, columnsAndRows, PrintSelectedColor);
                            }
                            else
                            {
                                Pres = generateChartForReport(printPrimaryPeerset, printSecondaryPeerset, printIsPeerSet, printIsSecondaryPeerSet, lstMetric[metric], MasterTemplate, Pres, "Group", contact, company_name, PrimarySetName, SecondaryPeerSetName, null, PrintSelectedColor);
                            }
                        }
                        if (!PrintIncludeMetrics)
                        {
                            TableOfContents.Rows.RemoveAt(TableOfContents.Rows.Count - 1);
                            continue;
                        }
                        #endregion

                        #region Research Related Slide (last)

                        Pres = generateResearchTable(printPrimaryPeerset, printSecondaryPeerset, printIsPeerSet, lstMetric[metric], MasterTemplate, Pres, contact, company_name, PrimarySetName, SecondaryPeerSetName);

                        #endregion
                    }
                }
                catch (Exception e)
                {
                    Elmah.ErrorSignal.FromCurrentContext().Raise(e);
                }
            }

            #endregion

            #region Table Of Contents

            int max = 0;
            max = TableOfContents.Select("AMFType = 'Impact'").Count() > max ? TableOfContents.Select("AMFType = 'Impact'").Count() : max;
            max = TableOfContents.Select("AMFType = 'Output'").Count() > max ? TableOfContents.Select("AMFType = 'Output'").Count() : max;
            max = TableOfContents.Select("AMFType = 'Activity'").Count() > max ? TableOfContents.Select("AMFType = 'Activity'").Count() : max;
            max = TableOfContents.Select("AMFType = 'Readiness'").Count() > max ? TableOfContents.Select("AMFType = 'Readiness'").Count() : max;

            int rowCountInSlide = 0;
            ISlide TempSlide, IndexSlide;
            ISlideCollection slds = Pres.Slides;
            IShape shape;
            ITable table;
            IHyperlinkManager hyperLinkMgr;

            rowCountInSlide = 14;
            IndexSlide = MasterTemplate.Slides[1];

            double TableOfContentSlides = Math.Ceiling(Convert.ToDouble(max) / rowCountInSlide);
            int RemoveRows = max % rowCountInSlide == 0 && max > 0 ? 13 : (max % rowCountInSlide) + 1;
            int count = 0;
            string str;
            int index;
            int outcolIndex = 0, actcolIndex = 0, readcolIndex = 0;
            //Impact
            for (int i = 1; i <= TableOfContentSlides; i++)
            {
                slds.InsertClone(i, IndexSlide);
                TempSlide = Pres.Slides[i];
                shape = FindShape(TempSlide, "Tableofcontents");
                if (shape != null)
                {
                    table = (ITable)shape;

                    //Add Elements in Table of Contents
                    for (int j = 1; j <= rowCountInSlide && count < max; j++)
                    {
                        if (count >= TableOfContents.Select("AMFType = 'Impact'").Count() || TableOfContents.Select("AMFType = 'Impact'").Count() == 0)
                        {
                            table[0, j].TextFrame.Text = " ";
                        }
                        else
                        {
                            table[0, j].TextFrame.Text = TableOfContents.Select("AMFType = 'Impact'").ElementAt(count)["MetricName"].ToString();
                            hyperLinkMgr = table[0, j].TextFrame.Paragraphs[0].Portions[0].PortionFormat.HyperlinkManager;
                            index = Convert.ToInt16(TableOfContents.Select("AMFType = 'Impact'").ElementAt(count)["SlideNumber"]) + i;
                            hyperLinkMgr.SetInternalHyperlinkClick(Pres.Slides[index]);
                        }


                        //output
                        if (j == 1)
                        {
                            if (table[0, 1].TextFrame.Text == " " || table[0, 1].TextFrame.Text.ElementAt(0) == '<')
                                outcolIndex = 0;
                            else
                                outcolIndex = 1;
                            //Add Elements in Table of Contents
                            table[outcolIndex, 0].TextFrame.Text = "Output";
                        }

                        if (count >= TableOfContents.Select("AMFType = 'Output'").Count() || TableOfContents.Select("AMFType = 'Output'").Count() == 0)
                        {
                            table[outcolIndex, j].TextFrame.Text = " ";
                        }
                        else
                        {
                            table[outcolIndex, j].TextFrame.Text = TableOfContents.Select("AMFType = 'Output'").ElementAt(count)["MetricName"].ToString();
                            hyperLinkMgr = table[outcolIndex, j].TextFrame.Paragraphs[0].Portions[0].PortionFormat.HyperlinkManager;
                            index = Convert.ToInt16(TableOfContents.Select("AMFType = 'Output'").ElementAt(count)["SlideNumber"]) + Convert.ToInt16(TableOfContentSlides);
                            hyperLinkMgr.SetInternalHyperlinkClick(Pres.Slides[index]);
                        }


                        //Activities
                        if (j == 1)
                        {
                            for (int c = 0; c < 2; c++)
                            {
                                if (table[c, 1].TextFrame.Text == " " || table[c, 1].TextFrame.Text.ElementAt(0) == '<')
                                {
                                    actcolIndex = c;
                                    break;
                                }
                                else
                                    actcolIndex = 2;
                            }
                            //Add Elements in Table of Contents
                            table[actcolIndex, 0].TextFrame.Text = "Activity";
                        }

                        if (count >= TableOfContents.Select("AMFType = 'Activity'").Count() || TableOfContents.Select("AMFType = 'Activity'").Count() == 0)
                        {
                            table[actcolIndex, j].TextFrame.Text = " ";
                        }
                        else
                        {
                            table[actcolIndex, j].TextFrame.Text = TableOfContents.Select("AMFType = 'Activity'").ElementAt(count)["MetricName"].ToString();
                            hyperLinkMgr = table[actcolIndex, j].TextFrame.Paragraphs[0].Portions[0].PortionFormat.HyperlinkManager;
                            index = Convert.ToInt16(TableOfContents.Select("AMFType = 'Activity'").ElementAt(count)["SlideNumber"]) + Convert.ToInt16(TableOfContentSlides);
                            hyperLinkMgr.SetInternalHyperlinkClick(Pres.Slides[index]);
                        }

                        //Readiness
                        if (j == 1)
                        {
                            for (int c = 0; c < 3; c++)
                            {
                                if (table[c, 1].TextFrame.Text == " " || table[c, 1].TextFrame.Text.ElementAt(0) == '<')
                                {
                                    readcolIndex = c;
                                    break;
                                }
                                else
                                    readcolIndex = 3;
                            }
                        }

                        if (count >= TableOfContents.Select("AMFType = 'Readiness'").Count() || TableOfContents.Select("AMFType = 'Readiness'").Count() == 0)
                        {
                            table[readcolIndex, j].TextFrame.Text = " ";
                        }
                        else
                        {
                            table[readcolIndex, j].TextFrame.Text = TableOfContents.Select("AMFType = 'Readiness'").ElementAt(count)["MetricName"].ToString();
                            hyperLinkMgr = table[readcolIndex, j].TextFrame.Paragraphs[0].Portions[0].PortionFormat.HyperlinkManager;
                            index = Convert.ToInt16(TableOfContents.Select("AMFType = 'Readiness'").ElementAt(count)["SlideNumber"]) + Convert.ToInt16(TableOfContentSlides);
                            hyperLinkMgr.SetInternalHyperlinkClick(Pres.Slides[index]);
                        }

                        count++;


                    }

                    //remove extra rows in last table of content slide
                    if (i == TableOfContentSlides)
                    {
                        for (int j = rowCountInSlide; j >= RemoveRows; j--)
                        {
                            table.Rows.RemoveAt(j, true);
                        }
                    }

                }

                //Remove Continued in first Table of Contents Slide Header
                if (i == 1)
                {
                    shape = FindShape(TempSlide, "Header");
                    if (shape != null)
                    {
                        str = ((IAutoShape)shape).TextFrame.Text;
                        str = str.Replace("<continued>", "");
                        ((IAutoShape)shape).TextFrame.Text = str;
                    }
                }

                //last part

                shape = FindShape(TempSlide, "Tableofcontents");
                if (shape != null)
                {
                    table = (ITable)shape;
                    for (int j = 3; j >= 0; j--)
                    {
                        if (table[j, 1].TextFrame.Text == " " || table[j, 1].TextFrame.Text.ElementAt(0) == '<')
                            table.Columns.RemoveAt(j, true);
                    }
                    if (table.Columns.Count == 1)
                    {
                        if (table.Columns[0] != null)
                        {
                            table.Columns[0].Width = 34 * 2 * 10;
                        }
                    }
                    else if (table.Columns.Count == 2)
                    {
                        table.Columns[0].Width = 34 * 10;
                        table.Columns[1].Width = 34 * 10;
                    }
                    else if (table.Columns.Count == 3)
                    {
                        table.Columns[0].Width = 22 * 10;
                        table.Columns[1].Width = 22 * 10;
                        table.Columns[2].Width = 22 * 10;
                    }
                }

            }

            #endregion

            #region Master Slide Update

            Pres = UpdateMasterSlide(Pres);

            #endregion

            #region Save Report
            TempData["ReportName"] = ReportName;

            //Get a reference to the directory
            CloudFileDirectory profileDir = GetCloudAccess(subPath);

            //Get a reference to the PPT file
            CloudFile file = profileDir.GetFileReference(ReportName);

            //MemoryTributary ms = new MemoryTributary();
                              
            
            //Save ppt in memory stream
            **MemoryStream ms = new MemoryStream();**

** Pres.Save(ms, Aspose.Slides.Export.SaveFormat.Pptx);**

            //Set poistion to 0 in memory stream
            ms.Position = 0;

            //Uplode stream to Azure file storage                
            file.UploadFromStream(ms);

            //Close memory stream and releases resources
            ms.Close();

            //Set value to true
            isFileUploadOnAzure = true;
            #endregion

        }
        catch (Exception ex)
        {
            Sitecore.Diagnostics.Log.Error("ChiragDekavadiya:" + ex, this);
            // Check Exception type and accordingly update flag in database
            if (ex.InnerException != null)
            {
                if (ex.InnerException.Message == "Thread was being aborted.")
                    IsGroupThreadError = true;
                else
                    IsGroupThreadError = false;
            }
            else
            {
                if (ex.Message == "Thread was being aborted.")
                    IsGroupThreadError = true;
                else
                    IsGroupThreadError = false;
            }
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
        }
        finally
        {
            //update end status of print
            if (IsGroupThreadError)
                _metricResearchDataStore.UpdatePrintStatus(currentLoginUser, "GroupPrint", "false", null, 1);
            else
                _metricResearchDataStore.UpdatePrintStatus(currentLoginUser, "GroupPrint", "false", null, 0);
        }
    }

Please find this to line where my ppt generated.

//Save ppt in memory stream
MemoryStream ms = new MemoryStream();
Pres.Save(ms, Aspose.Slides.Export.SaveFormat.Pptx);

            //Set poistion to 0 in memory stream
            ms.Position = 0;

            //Uplode stream to Azure file storage                
            file.UploadFromStream(ms);

            //Close memory stream and releases resources
            ms.Close();

@tushar007,

I have observed part of sample code shared by you and unfortunately we may not use this to reproduce the issue. I request you to please share the source presentation used on your end along with a sample Visual Studio project reproducing the issue. We will investigate the issue further on our end to help you out.

Please find source code to generate error. more than 7 MB presentation file i can not save. i throws below exception. Please provide solution for that.thanks.

Exception of type ‘System.OutOfMemoryException’ was thrown.

at Aspose.Slides. .(String )
at Aspose.Slides. .(IShape , , , )
at Aspose.Slides. .(IGroupShape , , , )
at Aspose.Slides. .(IBaseSlide , , )
at Aspose.Slides. .(ISlide )
at Aspose.Slides. .( , ISlide , )
at Aspose.Slides. .(IPresentation , Stream , PresentationTypeEx , IPptxOptions )
at Aspose.Slides.Presentation.(Stream , PresentationTypeEx , IPptxOptions )
at Aspose.Slides.Presentation.Save(Stream stream, SaveFormat format, ISaveOptions options)
at Aspose.Slides.Presentation.Save(String fname, SaveFormat format)
at ConsoleAspose.Program.Main(String[] args) in
D:\ConsoleApp\ConsoleAspose\ConsoleAspose\Program.cs:line 86

@tushar007,

I have observed the stack trace and information shared by you. I like to share that Aspose forums allows attachment upto 3 MB in forums. You may please upload the requested sample project and source presentation on some FTP server or Dropbox and sharing the download link with us so that we may proceed further with our investigation.

Hi,
I have use Aspose.Slide to Save ppt file in my application.when i try to save presentation having size more than 47.5MB it’s giving me OutofMemory exception in C#. Here i have attached one sample console application which try to save PPT file having size more than 47.5MB.
Steps to run application

1.Unzip attached application folder.
2.Add Aspose.slide dll in attached application of bin folder.
3.Use Aspose.Slide Version 18.3.
4. Presentation will be download in below folder where 0 kb file will be created than error will be thrown(Demo_Overview_Report.pptx)
(ConsoleApp\ConsoleAspose\ConsoleAspose\bin\Debug\PresentationDownloads)
5.Master template you can find in below folder(DS_MetricsResearchMaster.pptx)
(ConsoleApp\ConsoleAspose\ConsoleAspose\bin\Debug\PresentationTemplate)
6. When you run Application it will take 10-15 minutes to create presentation than error will thrown.
Please try to provide solution ASAP.

ConsoleApp.zip (2.4 MB)

@tushar007,

I have observed your comments. A ticket with ID SLIDESNET-40042 has been created in our issue tracking system to investigate and resolve the issue. This thread has been associated with the ticket so that we may share the notification with you once issue will be fixed.

Any Update on ticket with ID SLIDESNET-40042 issue?

@tushar007,

I have verified from our issue tracking system and regret to share that at present the issue is still unresolved as it has just recently been added. I request for your patience till the time we schedule and investigate the issue on its due turn.

Thanks for your reply. May i know priority of this issue?

@tushar007,

I have observed your comments. I like to inform that issue has medium priority. The issue shared has been added recently and is awaiting investigation in waiting queue. Actually, as per Aspose policy first of all issues added in Aspose.Enterprise and Aspose.Priority forums are addressed and resolved. Then issues added in normal support forum are selected for investigation on first come and first serve basis. On the basis of complexity of the issue that is determined after investigation, the issues are scheduled for resolution. We will share the feedback with you regarding ETA as soon as possible.

Any Progress/Update on ticket with ID SLIDESNET-40042 issue? when can i expect this to resolved?

@tushar007,

I have verified from our issue tracking system and have verified the issue status. The issue shared has been added recently and is awaiting investigation in waiting queue. Actually, as per Aspose policy first of all issues added in Aspose.Enterprise and Aspose.Priority forums are addressed and resolved. Then issues added in normal support forum are selected for investigation on first come and first serve basis. On the basis of complexity of the issue that is determined after investigation, the issues are scheduled for resolution. We will share the feedback with you regarding ETA as soon as possible.

When you are going to start work on this issue? After 2 week Issue still Open. Try to provide solution for this as soon as possible.

@tushar007,

I have observed your comments. This issue is scheduled for further investigation for week 2018/w19. We will share good news with you soon.

Any Progress/Update on ticket with ID SLIDESNET-40042 issue? when can i expect this to resolved?

@tushar007,

I have observed your comments. I like to inform that work is in progress regarding to this issue. We will share good news with you soon.