Forum Visual Studio

Debugging showing null in the window, but still somehow getting data?

JKnottJKnott Member ✭✭✭

Hey there, I am scratching my head on this one...
I have this code...
As you can see I am using reflection.... I have heard this is a bad thing... are there better options to do what I'm doing here?

    /// <summary>
    /// Build an excel report for the reloading supplies, using the supplied lists
    /// </summary>
    /// <returns> The <see cref="Task" /> </returns>
    public async static Task ExportSuppliesFromLists(
                        ObservableCollection<PowderInventory> powder,
                        ObservableCollection<BarStockInventory> barstock)
    {
        await Semaphore.WaitAsync(0).ConfigureAwait(true);

        var rowID = 0;
        var n = 0;

        var PowderRelavantRows = new List<string> { "Photos", "Manufacturer", "Weight", "Unit", "Price", "Lot", "Acquired" };
        var BarstockRelavantRows = new List<string> { "Photos", "Manufacturer", "Dia", "Style", "ShortStyle", "Weight", "Quantity", "Price", "Lot", "Acquired" };


        try
        {
            // Create an instance of ExcelEngine.
            using (ExcelEngine excelEngine = new ExcelEngine())
            {
                // Set the default application version as Excel 2013.
                excelEngine.Excel.DefaultVersion = ExcelVersion.Excel2016;

                var inventoryWorsheets = 0;
                IWorksheet worksheet;

                if (powder.Count > 0)
                {
                    inventoryWorsheets++;
                }

                if (barstock.Count > 0)
                {
                    inventoryWorsheets++;
                }

                // Create a workbook with inventoryWorsheets number of sheets
                var workbook = excelEngine.Excel.Workbooks.Create(inventoryWorsheets);

                //Output the Powder worksheet
                if (powder.Count > 0)
                {
                    // access first worksheet from the workbook instance.

                    worksheet = workbook.Worksheets[--inventoryWorsheets];
                    worksheet.Name = "Powder";

                    rowID = 1; //Reset the rowID to 1
                    n = 0; //Set column to 0 which does not exist, but we iterate to 1 as the first thing so its all good.

                    foreach (string lbl in PowderRelavantRows)
                    {
                        n++; //iterate to the next cell
                        worksheet.Range[rowID, n].CellStyle.Font.Bold = true;
                        worksheet.Range[rowID, n].CellStyle.VerticalAlignment = ExcelVAlign.VAlignCenter;
                        worksheet.Range[rowID, n].Text = lbl;
                    }

                    foreach (PowderInventory pwdr in powder)
                    {
                        rowID++;
                        n = 0; //Again this is safe, because we iterate to col 1 as the first thing we do.
                        pwdr.Photos = await new PhotosRepository().GetItemByParentID(pwdr.Id, (int)RecordCatagory.Supplies, (int)RecordType.Powder).ConfigureAwait(true);

                        foreach (string lbl in PowderRelavantRows)
                        {
                            n++; //Iterate to the next cell
                            var thisproperties = pwdr.GetType().GetProperties();
                            worksheet.Range[rowID, n].CellStyle.Font.Bold = false;
                            worksheet.Range[rowID, n].CellStyle.VerticalAlignment = ExcelVAlign.VAlignCenter;
                            worksheet.Range[rowID, n].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignLeft;

                            if (lbl.Equals("Photos") && pwdr.Photos != null)
                            {
                                var imgstream = pwdr.Photos.FirstOrDefault(x => x.KeyImage.Equals(1))?.Image;
                                if (imgstream != null)
                                {
                                    // Build the image from the database and populate it to the worksheet.
                                    var img = new Syncfusion.Drawing.Image(new MemoryStream(imgstream));

                                    if (img != null)
                                    {
                                        //worksheet.Range[rowID, 10, rowID + 9, 12].Merge();
                                        var shape = worksheet.Pictures.AddPicture(rowID, n, img, ExcelImageFormat.Jpeg);

                                        // Re-sizing a Picture.
                                        shape.Height = 80;
                                        shape.Width = 120;
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                                    Debug.WriteLine($"Searching {thisproperties}, for {lbl}", "Info");
                                    string data = Array.Find(thisproperties, x => x.Name.Equals(lbl))?.GetValue(pwdr).ToString() ?? string.Empty;
                                    worksheet.Range[rowID, n].Text = data;
                                }
                                catch (ArgumentNullException ex)
                                {
                                    Debug.WriteLine($"Received a NullException Index of row:{rowID} col:{n} searching for ({lbl}) in the array of Powder", "Error");
                                }
                            }
                        }
                    }

                    worksheet.UsedRange.AutofitColumns();
                }

                //Output the Barstock worksheet
                if (barstock.Count > 0)
                {
                    // access first worksheet from the workbook instance.

                    worksheet = workbook.Worksheets[--inventoryWorsheets];
                    worksheet.Name = "Barstock";

                    rowID = 1; //Reset the rowID to 0
                    n = 0;

                    foreach (string lbl in BarstockRelavantRows)
                    {
                        n++; //iterate to the next cell
                        worksheet.Range[rowID, n].CellStyle.Font.Bold = true;
                        worksheet.Range[rowID, n].CellStyle.VerticalAlignment = ExcelVAlign.VAlignCenter;
                        worksheet.Range[rowID, n].Text = lbl;
                    }

                    foreach (BarstockInventory bar in barstock)
                    {
                        rowID++;
                        n = 0;
                        bar.Photos = await new PhotosRepository().GetItemByParentID(bar.Id, (int)RecordCatagory.Supplies, (int)RecordType.Barstock).ConfigureAwait(true);

                        foreach (string lbl in BarstockRelavantRows)
                        {
                            n++; //Iterate to the next cell
                            var thisproperties = bar.GetType().GetProperties();
                            worksheet.Range[rowID, n].CellStyle.Font.Bold = false;
                            worksheet.Range[rowID, n].CellStyle.VerticalAlignment = ExcelVAlign.VAlignCenter;
                            worksheet.Range[rowID, n].CellStyle.HorizontalAlignment = ExcelHAlign.HAlignLeft;
                            if (lbl.Equals("Photos") && bar.Photos != null)
                            {
                                var imgstream = bar.Photos.FirstOrDefault(x => x.KeyImage.Equals(1))?.Image;
                                if (imgstream != null)
                                {
                                    // Build the image from the database and populate it to the worksheet.
                                    var img = new Syncfusion.Drawing.Image(new MemoryStream(imgstream));

                                    if (img != null)
                                    {
                                        //worksheet.Range[rowID, 10, rowID + 9, 12].Merge();
                                        var shape = worksheet.Pictures.AddPicture(rowID, n, img, ExcelImageFormat.Jpeg);

                                        // Re-sizing a Picture.
                                        shape.Height = 80;
                                        shape.Width = 120;
                                    }
                                }
                            }
                            else
                            {
                                try
                                {
                // NO Matter what this will always show lbl = null
                                    Debug.WriteLine($"Searching {thisproperties}, for {lbl}", "Info");
                                    string data = Array.Find(thisproperties, x => x.Name.Equals(lbl))?.GetValue(bar).ToString() ?? string.Empty;
                                    worksheet.Range[rowID, n].Text = data;
                                }
                                catch (ArgumentNullException ex)
                                {
                                    Debug.WriteLine($"Received a NullException Index of row:{rowID} col:{n} searching for ({lbl}) in the array of Barstock", "Error");
                                }
                            }
                        }
                    }

                    worksheet.UsedRange.AutofitColumns();
                }

                // Save the workbook to stream in xlsx format.
                var stream = new MemoryStream();
                workbook.SaveAs(stream);
                workbook.Close();

                // Save the stream as a file in the device and invoke it for viewing
                await Xamarin.Forms.DependencyService.Get<ISave>().SaveAndView($"{DateTime.Now.ToString("yyyy-dd-M-", CultureInfo.InvariantCulture)}-Inventory-Export.xlsx", "application/msexcel", stream).ConfigureAwait(true);
                stream.Dispose();
            }
        }
        catch (Exception ex)
        {
            Debug.WriteLine($"ExportReports.cs->BuildPhotoList(){ex.Message}==={ex.InnerException}--{ex.StackTrace}");
        }
        finally
        {
            Semaphore.Release();
        }
    }

Looks harmless enough.. BUT When debugging, once I have passed through the first instance of foreach (string lbl in <List>) The second time I use the same logic to gather the actual data from the lists, I get null reported as the value of lbl no matter what.
the code is still reporting (via my Debug.Writeline() calls) that the values are there, but the debugger is showing null and that's it...

To make it even more confusing, the code is crashing somewhere in one of the record data retrieval calls (between the call to get the Lot, and the Acquired Date) When I set a breakpoint on the catch (Exception ex) I am again getting null reported as the value for ex...

I'm completely at a loss here....

Has anyone seen or know of what could be causing this?

Best Answer

  • JKnottJKnott ✭✭✭
    Accepted Answer

    Well, I am going to mark this as fixed, but it's not entirely true...
    This morning I am reminded of why it's a bad idea to abandon a project for a month and a half then come back to it and try digging in like all is normal... (and not having my coffee in me due to a society collapsing over a virus)...
    Rather than using system.reflection to get the objects I wanted to report, I simply used a If else if tree, similar to a switch case. (I may change it to switch case later even)
    By just creating multiple checks like so...

                                else if (lbl.Equals("Acquired") && !String.IsNullOrEmpty(bar.Acquired.ToString()))
                                {
                                    worksheet.Range[rowID, n].Text = bar.Acquired.ToString();
                                }
                                else if (lbl.Equals("Manufacturer") && !String.IsNullOrEmpty(bar.Manufacturer.ToString()))
                                {
                                    worksheet.Range[rowID, n].Text = bar.Manufacturer.ToString();
                                }
                                else if (lbl.Equals("BarDia") && !String.IsNullOrEmpty(bar.BarDia.ToString()))
                                {
                                    worksheet.Range[rowID, n].Text = bar.BarDia.ToString();
                                }
    

    I added about 60 lines of code (80% of which was copy and paste) I removed about 90% of my headache...

    I am still quite curious why reflection was breaking the debugger however... Perhaps I should start a bug entry over at MS...

    Cheers!

Answers

  • JKnottJKnott Member ✭✭✭
    Accepted Answer

    Well, I am going to mark this as fixed, but it's not entirely true...
    This morning I am reminded of why it's a bad idea to abandon a project for a month and a half then come back to it and try digging in like all is normal... (and not having my coffee in me due to a society collapsing over a virus)...
    Rather than using system.reflection to get the objects I wanted to report, I simply used a If else if tree, similar to a switch case. (I may change it to switch case later even)
    By just creating multiple checks like so...

                                else if (lbl.Equals("Acquired") && !String.IsNullOrEmpty(bar.Acquired.ToString()))
                                {
                                    worksheet.Range[rowID, n].Text = bar.Acquired.ToString();
                                }
                                else if (lbl.Equals("Manufacturer") && !String.IsNullOrEmpty(bar.Manufacturer.ToString()))
                                {
                                    worksheet.Range[rowID, n].Text = bar.Manufacturer.ToString();
                                }
                                else if (lbl.Equals("BarDia") && !String.IsNullOrEmpty(bar.BarDia.ToString()))
                                {
                                    worksheet.Range[rowID, n].Text = bar.BarDia.ToString();
                                }
    

    I added about 60 lines of code (80% of which was copy and paste) I removed about 90% of my headache...

    I am still quite curious why reflection was breaking the debugger however... Perhaps I should start a bug entry over at MS...

    Cheers!

Sign In or Register to comment.