I have a block of code which reads powerpoint slides and creates xml for them.Everything is working fine on my local machine.but on server,when second slide is read.I Get the exception:
EXCEPTION:The message filter indicated that the application is busy. (Exception from HRESULT: 0x8001010A (RPC_E_SERVERCALL_RETRYLATER)) for Powerpoint Interop
Function Throwing Error:
public string AddPPTPages(long templateid, long pptFileId)
{
string strPptFilePath = "";
string strSuccess = "";
using (var dc = new DataContext())
{
var template = dc.Templates.GetByID(templateid);
template.ExtendedData = "<template><pptfileid>" + pptFileId + "</pptfileid></template>";
template.Save();
dc.SubmitChanges();
var file = dc.FileHandles.GetByID(Convert.ToInt64(pptFileId));
file.EnsureUrlFiles();
strPptFilePath = file.GetPhysicalPath(file.FileName);//get path of original ppt file
}
try
{
using (new Impersonator(Installs.Current.PPTUser, null, Installs.Current.PPTPassword))
{
PowerPoint.Application PowerPoint_App = new PowerPoint.Application();//Open PowerPoint app/process
PowerPoint.Presentation presentation = null;//initialize presentation to null
try
{
PowerPoint_App.Visible = MsoTriState.msoTrue;//set app visibility to true
presentation = PowerPoint_App.Presentations.Open(strPptFilePath, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoFalse, Microsoft.Office.Core.MsoTriState.msoTrue);//open powerpoint presentation using path strPptFilePath
templateID = templateid;//required for readslide function
/////////ERROR is THROWN FOR BELOW LINE//////////////////
for (int i = 0; i < presentation.Slides.Count; i++)
{
ReadSlides(presentation, i);//call to read current slide
}
using (var dc = new DataContext())
{
var template = dc.Templates.GetByID(templateID);
template.FixPageIndexes();
template.Save();
dc.SubmitChanges();
}
presentation.Close();//close presentation
PowerPoint_App.Quit();//quit opened powerpoint app/process
}
catch (Exception ex)
{
strSuccess = ex.ToString();
}
finally
{
while (Marshal.FinalReleaseComObject(presentation) != 0) { }
presentation = null;
while (Marshal.FinalReleaseComObject(PowerPoint_App) != 0) { }
PowerPoint_App = null;
GC.Collect();
GC.WaitForPendingFinalizers();
KillPPTProcess();//find ppt process in taskmanager and kill it
}
}
}
catch (Exception e)
{
strSuccess = e.ToString();
MindMatrix.Libraries.Entities.ExceptionMessage.HandleException(e, null);
Loggers.HandleException2(e);
}
return strSuccess;
}
private void ReadSlides(PowerPoint.Presentation presentation, int i)
{
try
{
string strPptXml = "";
//get number of objects(text and image) present in current slide
foreach (var item in presentation.Slides[i + 1].Shapes)
{
var shape = (PowerPoint.Shape)item;
strPptXml += ReadShape(shape);//read object and add it to xml
}
int height = ConvertToPixel(presentation.Slides[i + 1].Master.Height);//get height of current slide
int width = ConvertToPixel(presentation.Slides[i + 1].Master.Width);//get width of current slide
strFileImage = Installs.Current.GetTempDirectory(DirectoryType.PPT);//get the temporary folder path for current loggedin user in machine
if (System.IO.Directory.Exists(strFileImage) == false)
{
System.IO.Directory.CreateDirectory(strFileImage);
}
strFileImage = strFileImage + "\\" + (i + 1) + ".png";//create image path for slide snapshot
presentation.Slides[i + 1].Export(strFileImage, "png", width, height);//create snapshot as png image to temp folder
strPptXml = "<slides datasourceid='0' repeaterid = '0' id='" + presentation.Slides[i + 1].SlideID + "' >" + strPptXml + "</slides>";//create slide xml using slideid and ppt xml(contains text and image objects of slide)
MemoryStream ms = new MemoryStream();
System.Drawing.Image imageIn;
imageIn = System.Drawing.Image.FromFile(strFileImage);//Creates an Image from location strFileImage.
imageIn.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
using (var dc = new DataContext())
{
var template = dc.Templates.GetByID(templateID);
//template.createPptPage(strPptXml, height, width, ms);//call to create ppt page for current slide
template.createPptPage(RemoveTroublesomeCharacters(strPptXml), height, width, ms);//call to create ppt page for current slide
dc.SubmitChanges();
}
}
catch (Exception e)
{
Loggers.HandleException2(e);
}
}
Any help guys??
My guess is that ReadSlides is changing the value of presentation.Slides.Count. This would happen if you were adding slides to, or removing slides from your presentation within ReadSlides.
I would pull this out into it's own variable and then use this variable in your for loop, like so:
var slideCount = presentation.Slides.Count;
for (int i = 0; i < slideCount; i++)
{
//etc etc
Have you tried setting DisplayAlert to false?
PowerPoint_App.DisplayAlerts = Powerpoint.PpAlertLevel.ppAlertsNone
You normally get this exception when Office opens a dialogue, and your application is unable to continue.
Quoting from your question:
Everything is working fine on my local machine.but on server,when second slide is read.I Get the exception
If your app is truly running in an unattended server environment, be aware that Microsoft specifically does not support COM for Office. Their warnings are fairly explicit. Here's a snippet:
If you use an Office application from a server-side solution, the application will lack many of the necessary capabilities to run successfully. Additionally, you will be taking risks with the stability of your overall solution.
Related
I have an existing program that does some processing a .pdf file and splitting it into multiple .pdf files based on looking for barcodes on the pages.
The program uses ImageMagick and C#.
I want to change it from outputting pdfs to outputting tifs. Look for the comment in the code below for where I would guess the change would be made.
I included the ImageMagick tag because someone might offer a commandline option that someone else can help me convert to C#.
private void BurstPdf(string bigPdfName, string targetfolder)
{
bool outputPdf = true; // change to false to output tif.
string outputExtension = "";
var settings = new MagickReadSettings { Density = new Density(200) };
string barcodePng = Path.Combine("C:\TEMP", "tmp.png");
using (MagickImageCollection pdfPageCollection = new MagickImageCollection())
{
pdfPageCollection.Read(bigPdfName, settings);
int inputPageCount = 0;
int outputPageCount = 0;
int outputFileCount = 0;
MagickImageCollection resultCollection = new MagickImageCollection();
string barcode = "";
string resultName = "";
IBarcodeReader reader = new BarcodeReader();
reader.Options.PossibleFormats = new List<BarcodeFormat>();
reader.Options.PossibleFormats.Add(BarcodeFormat.CODE_39);
reader.Options.TryHarder = false;
foreach (MagickImage pdfPage in pdfPageCollection)
{
MagickGeometry barcodeArea = getBarCodeArea(pdfPage);
IMagickImage barcodeImg = pdfPage.Clone();
barcodeImg.ColorType = ColorType.Bilevel;
barcodeImg.Depth = 1;
barcodeImg.Alpha(AlphaOption.Off);
barcodeImg.Crop(barcodeArea);
barcodeImg.Write(barcodePng);
inputPageCount++;
using (var barcodeBitmap = new Bitmap(barcodePng))
{
var result = reader.Decode(barcodeBitmap);
if (result != null)
{
// found a first page because it has bar code.
if (result.BarcodeFormat.ToString() == "CODE_39")
{
if (outputFileCount != 0)
{
// write out previous pages.
if (outputPdf) {
outputExtension = ".pdf";
} else {
// What do I put here to output a g4 compressed tif?
outputExtension = ".tif";
}
resultName = string.Format("{0:D4}", outputFileCount) + "-" + outputPageCount.ToString() + "-" + barcode + outputExtension;
resultCollection.Write(Path.Combine(targetfolder, resultName));
resultCollection = new MagickImageCollection();
}
barcode = standardizePhysicalBarCode(result.Text);
outputFileCount++;
resultCollection.Add(pdfPage);
outputPageCount = 1;
}
else
{
Console.WriteLine("WARNING barcode is not of type CODE_39 so something is wrong. check page " + inputPageCount + " of " + bigPdfName);
if (inputPageCount == 1)
{
throw new Exception("barcode not found on page 1. see " + barcodePng);
}
resultCollection.Add(pdfPage);
outputPageCount++;
}
}
else
{
if (inputPageCount == 1)
{
throw new Exception("barcode not found on page 1. see " + barcodePng);
}
resultCollection.Add(pdfPage);
outputPageCount++;
}
}
if (File.Exists(barcodePng))
{
File.Delete(barcodePng);
}
}
if (resultCollection.Count > 0)
{
if (outputPdf) {
outputExtension = ".pdf";
} else {
// What do I put here to output a g4 compressed tif?
outputExtension = ".tif";
}
resultName = string.Format("{0:D4}", outputFileCount) + "-" + outputPageCount.ToString() + "-" + barcode + outputExtension;
resultCollection.Write(Path.Combine(targetfolder, resultName));
outputFileCount++;
}
}
}
[EDIT] The above code is what I am using (which some untested modifications) to split a .pdf into other .pdfs. I want to know how to modify this code to output tiffs. I put a comment in the code where I think the change would go.
[EDIT] So encouraged by #fmw42 I just ran the code with the .tif extension enabled. Looks like it did convert to a .tif, but the tif is not compressed. I am surprised that IM just configures the output based on the extension name of the file. Handy I guess, but just seems a little loose.
[EDIT] I figured it out. Although counter-intuitive ones sets the compression on the read of the file. I am reading a .pdf but I set the compression to Group for like this:
var settings = new MagickReadSettings { Density = new Density(200), Compression = CompressionMethod.Group4 };
The thing I learned was that simply naming the output file .tif tells IM to output a tif. That is a handy way to do it, but it just seems sloppy.
I have an issue with Files.
I am doing an image importer so clients put their files on an FTP server and then they can import it in the application.
During the import process I copy the file in the FTP Folder to another folder with File.copy
public List<Visuel> ImportVisuel(int galerieId, string[] images)
{
Galerie targetGalerie = MemoryCache.GetGaleriById(galerieId);
List<FormatImage> listeFormats = MemoryCache.FormatImageToList();
int i = 0;
List<Visuel> visuelAddList = new List<Visuel>();
List<Visuel> visuelUpdateList = new List<Visuel>();
List<Visuel> returnList = new List<Visuel>();
foreach (string item in images)
{
i++;
Progress.ImportProgress[Progress.Guid] = "Image " + i + " sur " + images.Count() + " importées";
string extension = Path.GetExtension(item);
string fileName = Path.GetFileName(item);
string originalPath = HttpContext.Current.Request.PhysicalApplicationPath + "Uploads\\";
string destinationPath = HttpContext.Current.Server.MapPath("~/Images/Catalogue") + "\\";
Visuel importImage = MemoryCache.GetVisuelByFilName(fileName);
bool update = true;
if (importImage == null) { importImage = new Visuel(); update = false; }
Size imageSize = importImage.GetJpegImageSize(originalPath + fileName);
FormatImage format = listeFormats.Where(f => f.width == imageSize.Width && f.height == imageSize.Height).FirstOrDefault();
string saveFileName = Guid.NewGuid() + extension;
File.Copy(originalPath + fileName, destinationPath + saveFileName);
if (format != null)
{
importImage.format = format;
switch (format.key)
{
case "Catalogue":
importImage.fileName = saveFileName;
importImage.originalFileName = fileName;
importImage.dossier = targetGalerie;
importImage.dossier_id = targetGalerie.id;
importImage.filePath = "Images/Catalogue/";
importImage.largeur = imageSize.Width;
importImage.hauteur = imageSize.Height;
importImage.isRoot = true;
if (update == false) { MemoryCache.Add(ref importImage); returnList.Add(importImage); }
if (update == true) visuelUpdateList.Add(importImage);
foreach (FormatImage f in listeFormats)
{
if (f.key.StartsWith("Catalogue_"))
{
string[] keys = f.key.Split('_');
string destinationFileName = saveFileName.Insert(saveFileName.IndexOf('.'), "-" + keys[1].ToString());
string destinationFileNameDeclinaison = destinationPath + destinationFileName;
VisuelResizer declinaison = new VisuelResizer();
declinaison.Save(originalPath + fileName, f.width, f.height, 1000, destinationFileNameDeclinaison);
Visuel visuel = MemoryCache.GetVisuelByFilName(fileName.Insert(fileName.IndexOf('.'), "-" + keys[1].ToString()));
update = true;
if (visuel == null) { visuel = new Visuel(); update = false; }
visuel.parent = importImage;
visuel.filePath = "Images/Catalogue/";
visuel.fileName = destinationFileName;
visuel.originalFileName = string.Empty;
visuel.format = f;
//visuel.dossier = targetGalerie; On s'en fout pour les déclinaisons
visuel.largeur = f.width;
visuel.hauteur = f.height;
if (update == false)
{
visuelAddList.Add(visuel);
}
else
{
visuelUpdateList.Add(visuel);
}
//importImage.declinaisons.Add(visuel);
}
}
break;
}
}
}
MemoryCache.Add(ref visuelAddList);
// FONCTION à implémenter
MemoryCache.Update(ref visuelUpdateList);
return returnList;
}
After some processes on the copy (the original file is no more used)
the client have a pop-up asking him if he wants to delete the original files in the ftp folder.
If he clicks on Ok another method is called on the same controller
and this method use
public void DeleteImageFile(string[] files)
{
for (int i = 0; i < files.Length; i++)
{
File.Delete(HttpContext.Current.Request.PhysicalApplicationPath + files[i].Replace(#"/", #"\"));
}
}
This method works fine and really delete the good files when I use it in other context.
But here I have an error message:
Process can't acces to file ... because it's used by another process.
Someone have an idea?
Thank you.
Here's the screenshot of Process Explorer
There are couple of thing you can do here.
1) If you can repro it, you can use Process Explorer at that moment and see which process is locking the file and if the process is ur process then making sure that you close the file handle after your work is done.
2) Use try/catch around the delete statement and retry after few seconds to see if the file handle was released.
3) If you can do it offline you can put in some queue and do the deletion on it later on.
You solve this by using c# locks. Just embed your code inside a lock statement and your threads will be safe and wait each other to complete processing.
I found the solution:
in my import method, there a call to that method
public void Save(string originalFile, int maxWidth, int maxHeight, int quality, string filePath)
{
Bitmap image = new Bitmap(originalFile);
Save(ref image, maxWidth, maxHeight, quality, filePath);
}
The bitmap maintains the file opened blocking delete.
just added
image.Dispose();
in the methos and it work fine.
Thank you for your help, and thank you for process explorer. Very useful tool
I want to create workbook and then write data using EPPlus. When I create new workbook, it can create successfully. But when I want to write some data to that worksheet, it failed and error says
The process cannot access the file 'filename' because it is being
used by another process.
I have disposed previous ExcelPackage but the error still show when I write data.
//Create new Workbook
private void PengisianBaruBW_DoWork(object sender, DoWorkEventArgs e)
{
this.Invoke(new MethodInvoker(delegate
{
SetPengisianBtn.Enabled = false;
}));
FileInfo filePath = new FileInfo("D:\\Data Pengisian SLA Surabaya\\" + day + "_" + date + ".xlsx");
if (File.Exists(filePath.ToString()))
{
File.Delete(filePath.ToString());
}
using (ExcelPackage pck = new ExcelPackage(filePath))
{
var schedule = pck.Workbook.Worksheets.Add("Schedule");
var cart = pck.Workbook.Worksheets.Add("Cartridge");
var unsche = pck.Workbook.Worksheets.Add("Unschedule");
var rekap = pck.Workbook.Worksheets.Add("Rekap");
//My Code here
pck.SaveAs(filePath);
pck.Dispose(); //I have disposed ExcelPakcage here
}
}
//Write Data to Excel File
private void PrintScheduleBtn_Click(object sender, EventArgs e)
{
if (StaffATB.Text != "" && HelperTeamATB.Text != "" && StaffBTB.Text != "" && HelperTeamBTB.Text != "" && StaffCTB.Text != "" && HelperTeamCTB.Text != "" && StaffDTB.Text != "" && HelperTeamDTB.Text != "")
{
DialogResult dialogResult = MessageBox.Show("Apakah Anda yakin ingin menyimpan jadwal pengisian ?", "", MessageBoxButtons.YesNo);
if (dialogResult == DialogResult.Yes)
{
FileInfo file = new FileInfo("D:\\Data Pengisian SLA Surabaya\\" + day + "_" + date + ".xlsx");
using (ExcelPackage pck = new ExcelPackage(file)) //error here
{
var rekap = pck.Workbook.Worksheets["Rekap"];
var data = pck.Workbook.Worksheets["Data"];
//my code to write data here
pck.SaveAs(file);
pck.Dispose();
}
}
}
else
{
MessageBox.Show("Silakan isi PIC terlebih dahulu !");
}
}
I have added this code to check whether my excel file is active or not. But the error still exsit. I set breakpoint and I see that stream value is null that indicate that my excel file is close. But why the error still exists ? Can anyone help me ?
string file = "D:\\Data Pengisian SLA Surabaya\\" + day + "_" + date + ".xlsx";
var path = Path.Combine(Path.GetTempPath(), "D:\\Data Pengisian SLA Surabaya\\" + day + "_" + date + ".xlsx");
var tempfile = new FileInfo(path);
FileStream stream = null;
try
{
stream = tempfile.Open(FileMode.Open, FileAccess.ReadWrite, FileShare.None);
}
catch (IOException)
{
}
finally
{
if (stream != null)
stream.Close();
}
I simplified your snippet for testing. It all worked as it should. Are you sure there is no other cause of the file access problem, like a virus scanner, backup program etc. since you also have another question with the same basic problem.
Take a look at the snippet below, try it and see if this one works. If not the problem is not in the code.
FileInfo filePath = new FileInfo("ExcelDemo.xlsx");
if (File.Exists(filePath.ToString()))
{
File.Delete(filePath.ToString());
}
using (ExcelPackage pck = new ExcelPackage(filePath))
{
var schedule = pck.Workbook.Worksheets.Add("Schedule");
var cart = pck.Workbook.Worksheets.Add("Cartridge");
var unsche = pck.Workbook.Worksheets.Add("Unschedule");
var rekap = pck.Workbook.Worksheets.Add("Rekap");
pck.SaveAs(filePath);
}
using (ExcelPackage pck = new ExcelPackage(filePath))
{
var rekap = pck.Workbook.Worksheets["Rekap"];
var schedule = pck.Workbook.Worksheets["Schedule"];
rekap.Cells[4, 1].Value = "Added data";
schedule.Cells[4, 1].Value = "Added data";
pck.SaveAs(filePath);
}
As already stated, the basic code should work just fine. However, looking at your code, I sense that you are using some kind of BackgroundWorker (PengisianBaruBW_DoWork name suggests this).
If so, you might run into accessing the same file from another thread (PengisianBaruBW_DoWork executes in parallel with PrintScheduleBtn_Click).
To help you more, you should add where (what line) do you receive this error and the call stack.
[Edit]
Based on additional comments, I think of one of these scenarios:
1) PengisianBaruBW_DoWork gets called many times and sometimes it happens to do work with the file, while PrintScheduleBtn_Click is trying to do work with the same file
2) An unhandled exception in _DoWork might get swallowed and leave the file opened (highly improbable since you have a disposable context).
Either way, put a breakpoint at the start of your _DoWork and one at beginning of PrintScheduleBtn_Click and use step over (F10).
I know this an old post, but it never got solved. I ran into the same problem, but i think i found the solution for it (at least it unlocked my excel file):
excelPackage.Dispose();
excelPackage = null;
GC.Collect();
I am trying to save selected slide so it doesnt retain my source template. how do i retain the existing template while i save the slides
private void SaveSelectedSlide_Click(object sender, RibbonControlEventArgs e)
{
try
{
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
temporaryPresentation.Slides.Paste();
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
}
catch (COMException Ex)
{
Debug.WriteLine("Some problem" + Ex.Message + Ex.StackTrace);
MessageBox.Show("PLease enter text ");
}
}
I think I got what you want. When pasting the new slide, save the new SlideRange. Afterwards assign the design of the source slide.
PowerPoint.Application ppApp = Globals.ThisAddIn.Application;
PowerPoint.SlideRange ppslr = ppApp.ActiveWindow.Selection.SlideRange;
string desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
var temporaryPresentation = Globals.ThisAddIn.Application.Presentations.Add(Microsoft.Office.Core.MsoTriState.msoTrue);
Microsoft.Office.Interop.PowerPoint.CustomLayout customLayout = ppApp.ActivePresentation.SlideMaster.CustomLayouts[Microsoft.Office.Interop.PowerPoint.PpSlideLayout.ppLayoutText];
for (int i = 1; i <= ppslr.Count; i++)
{
var sourceSlide = ppslr[i];
sourceSlide.Copy();
var design = sourceSlide.Design;
SlideRange sr = temporaryPresentation.Slides.Paste(); // get newly created slideRange
sr.Design = sourceSlide.Design; // manually set design
}
temporaryPresentation.SaveAs("Temporary", Microsoft.Office.Interop.PowerPoint.PpSaveAsFileType.ppSaveAsPresentation, Microsoft.Office.Core.MsoTriState.msoTrue);
temporaryPresentation.Close();
It worked for me. Please let me know if this is the expected behaviour!
I’m working on an ASP webpage that uses a Minitab DCOM object. My problem is that this DCOM object stops responding (hangs) if the Identity is set as “This User” under Component Services (DCONCNFG) but if I log into windows with the user that I used under “This User” and set the Identity as “Interactive user” everything works fine.
My question is what is different between DCOM Identity “The interactive user” and “This user” if the username is the same (Administrator)?
Mainly this webpage uses Minitab to generate graphs. Before it hangs it does generate graphs but only 5 or 6 graphs then it stops responding.
Here is the C# code incase you are wondering where it hangs:
using System;
using System.Web;
using System.Web.UI.WebControls;
using Mtb; // Minitab Library (Mtb 16.0 Type Library)
using System.IO;
using System.Data;
using System.Runtime.InteropServices;
using System.Threading;
namespace TRWebApp.TestDetails
{
public partial class TestDetails : System.Web.UI.Page
{
// MiniTab Stuff
Mtb.IApplication g_MtbApp;
Mtb.IProject g_MtbProj;
Mtb.IUserInterface g_MtbUI;
Mtb.IWorksheets g_MtbWkShts;
Mtb.ICommands g_MtbCommands;
Mtb.IOutputs g_MtbOutputs;
Mtb.IGraph g_MtbGraph;
Mtb.IOutputs g_MtbOutputs2;
Mtb.IGraph g_MtbGraph2;
int g_GraphIdx = 1;
int g_Loop = 1;
// Tests Table
enum testsTable { TestIdx, TestSeq, ParamName, LSL, USL, Units };
Tools tools = new Tools();
string g_SessionID = "";
Mtb_DataSetTableAdapters.XBarTableAdapter xbarTA = new Mtb_DataSetTableAdapters.XBarTableAdapter();
protected void Page_Init(object sender, EventArgs e)
{
g_MtbApp = new Application();
g_MtbProj = g_MtbApp.ActiveProject;
g_MtbUI = g_MtbApp.UserInterface;
g_MtbWkShts = g_MtbProj.Worksheets;
g_MtbCommands = g_MtbProj.Commands;
g_MtbUI.DisplayAlerts = false;
g_MtbUI.Interactive = false;
g_MtbUI.UserControl = false;
lblProductDesc.Text = ""; // Start with a clear variable
g_SessionID = HttpContext.Current.Session.SessionID;
string imgFolder = "Images/Mtb/";
string mtbSessionPath = Server.MapPath(ResolveUrl("~/" + imgFolder)) + g_SessionID;
Directory.CreateDirectory(mtbSessionPath);
Array.ForEach(Directory.GetFiles(mtbSessionPath), File.Delete); // Delete all the files from the directory
Session["MtbSessionPath"] = mtbSessionPath; // Store the Session Path so we can later delete it
// Add the two image columns to the grid view
GridView1.AutoGenerateColumns = false;
ImageField imgColumn = new ImageField();
imgColumn.HeaderText = "Scatterplot";
imgColumn.DataImageUrlField = "TestIdx";
imgColumn.DataImageUrlFormatString = "~\\Images\\Mtb\\" + g_SessionID + "\\{0}.GIF";
imgColumn.ControlStyle.CssClass = "MtbImgDetail";
GridView1.Columns.Add(imgColumn);
ImageField img2Column = new ImageField();
img2Column.HeaderText = "Histogram";
img2Column.DataImageUrlField = "TestIdx";
img2Column.DataImageUrlFormatString = "~\\Images\\Mtb\\" + g_SessionID + "\\H{0}.GIF";
img2Column.ControlStyle.CssClass = "MtbImgDetail";
GridView1.Columns.Add(img2Column);
}
protected void Page_Load(object sender, EventArgs e)
{
try
{
lblErrMsg.Text = "";
// Fill dates if they are empty
if (String.IsNullOrEmpty(tbxFromDate.Text))
tbxFromDate.Text = String.Format("{0:MM/01/yy}", DateTime.Today, null, DateTime.Today);
if (String.IsNullOrEmpty(tbxToDate.Text))
tbxToDate.Text = String.Format("{0:MM/dd/yy}", DateTime.Today);
}
catch (Exception ex)
{
lblErrMsg.Text = ex.Message;
}
}
protected void GridView1_RowDataBound(object sender, GridViewRowEventArgs e)
{
if (e.Row.RowIndex >= 0)
{
// Get the data for the parameter name
DataTable dt = xbarTA.GetXBarData(lbxProduct.SelectedValue, Convert.ToDateTime(tbxFromDate.Text), Convert.ToDateTime(tbxToDate.Text), e.Row.Cells[(int)testsTable.ParamName].Text);
// Pass the data to an object array so we can pass it to minitab
object[] data = new object[dt.Rows.Count];
object[] time = new object[dt.Rows.Count];
int i = 0;
foreach (DataRow dr in dt.Rows)
{
if (tools.IsNumeric(dr["ParamValue"]))
{
data[i] = Convert.ToDouble(dr["ParamValue"]);
time[i] = i;
}
i++;
}
if (dt.Rows.Count > 1) // Do graphs with at least two measurements
{
// Only pass it to minitab if we have numeric data
if (!ReferenceEquals(data[0], null)) // if it is not null it means it has a numeric value
{
g_MtbWkShts.Item(1).Columns.Add().SetData(data);
g_MtbWkShts.Item(1).Columns.Add().SetData(time);
g_MtbWkShts.Item(1).Columns.Item(1).Name = e.Row.Cells[(int)testsTable.ParamName].Text + " (" + e.Row.Cells[(int)testsTable.Units].Text + ")";
g_MtbWkShts.Item(1).Columns.Item(2).Name = "Time";
//// H E R E
////
//// FOLLOWING LINE HANGS AFTER GENERATING 6 GRAPHS WHEN THE IDENTITY "THIS USER" IS SET
////
g_MtbProj.ExecuteCommand("Plot C1*C2;\nSymbol;\nConnect.", g_MtbWkShts.Item(1));
// Convert LSL and USL to Decimal
if (tools.IsNumeric(e.Row.Cells[(int)testsTable.LSL].Text.Trim()) && tools.IsNumeric(e.Row.Cells[(int)testsTable.USL].Text.Trim()))
{
if (Convert.ToDouble(e.Row.Cells[(int)testsTable.LSL].Text) < Convert.ToDouble(e.Row.Cells[(int)testsTable.USL].Text))
{
g_MtbProj.ExecuteCommand("Capa C1 " + dt.Rows.Count.ToString() + ";\nLspec " + e.Row.Cells[(int)testsTable.LSL].Text + ";\nUspec " + e.Row.Cells[(int)testsTable.USL].Text + ";\nPooled;\nAMR;\nUnBiased;\nOBiased;\nToler 6;\nWithin;\nOverall;\nCStat.", g_MtbWkShts.Item(1));
}
else
{
g_MtbProj.ExecuteCommand("Histogram C1;\nBar;\nDistribution;\nNormal.", g_MtbWkShts.Item(1));
}
}
else
{
g_MtbProj.ExecuteCommand("Histogram C1;\nBar;\nDistribution;\nNormal.", g_MtbWkShts.Item(1));
}
try
{
g_MtbOutputs = g_MtbCommands.Item(g_GraphIdx).Outputs;
g_GraphIdx++;
g_MtbOutputs2 = g_MtbCommands.Item(g_GraphIdx).Outputs;
g_GraphIdx++;
string graphPath = "";
if (g_MtbOutputs.Count > 0)
{
g_MtbGraph = g_MtbOutputs.Item(1).Graph;
graphPath = Server.MapPath(ResolveUrl("~/Images/Mtb/")) + g_SessionID + Path.DirectorySeparatorChar + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif";
g_MtbGraph.SaveAs(graphPath, true, MtbGraphFileTypes.GFGIF, 600, 400, 96);
}
if (g_MtbOutputs2.Count > 0)
{
g_MtbGraph2 = g_MtbOutputs2.Item(1).Graph;
graphPath = Server.MapPath(ResolveUrl("~/Images/Mtb/")) + g_SessionID + Path.DirectorySeparatorChar + "H" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif";
g_MtbGraph2.SaveAs(graphPath, true, MtbGraphFileTypes.GFGIF, 600, 400, 96);
}
}
catch (Exception ex)
{
lblErrMsg.Text = "Test Idx: " + e.Row.Cells[(int)testsTable.TestIdx].Text + " seems to have problems.<BR />Error: " + ex.Message;
}
g_MtbWkShts.Item(1).Columns.Delete(); // Delete all the columns (This line of code is needed otherwise the Mtb.exe will still running on the server side task manager
}
else
{
// Copy the No numeric image as a graph
File.Copy(Server.MapPath("~\\Images\\Mtb\\NaN.gif"), Server.MapPath("~\\Images\\Mtb\\" + g_SessionID + "\\" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif"));
File.Copy(Server.MapPath("~\\Images\\Mtb\\NaN.gif"), Server.MapPath("~\\Images\\Mtb\\" + g_SessionID + "\\H" + e.Row.Cells[(int)testsTable.TestIdx].Text + ".gif"));
}
}
}
}
protected void GridView1_Unload(object sender, EventArgs e)
{
// All these lines of code are needed otherwise the Mtb.exe will not be close on the task manager (server side)
GC.Collect();
GC.WaitForPendingFinalizers();
if (g_MtbGraph != null)
Marshal.ReleaseComObject(g_MtbGraph); g_MtbGraph = null;
if (g_MtbOutputs != null)
Marshal.ReleaseComObject(g_MtbOutputs); g_MtbOutputs = null;
if (g_MtbGraph2 != null)
Marshal.ReleaseComObject(g_MtbGraph2); g_MtbGraph2 = null;
if (g_MtbOutputs2 != null)
Marshal.ReleaseComObject(g_MtbOutputs2); g_MtbOutputs2 = null;
if (g_MtbCommands != null)
Marshal.ReleaseComObject(g_MtbCommands); g_MtbCommands = null;
if (g_MtbWkShts != null)
Marshal.ReleaseComObject(g_MtbWkShts); g_MtbWkShts = null;
if (g_MtbUI != null)
Marshal.ReleaseComObject(g_MtbUI); g_MtbUI = null;
if (g_MtbProj != null)
Marshal.ReleaseComObject(g_MtbProj); g_MtbProj = null;
if (g_MtbApp != null)
{
g_MtbApp.Quit();
Marshal.ReleaseComObject(g_MtbApp); g_MtbApp = null;
}
}
}
}
I'm using:
Windows Server 2008 R2 Standard (SP 1)
IIS 7.5.7600.16385
Framework 4.0.30319
Visual Studio 2010 Version 10.0.30319.1
Minitab 16.1.0
Thank you,
Pablo
Just a guess, based on something that happened to me ages ago:
For some reason, Minitab is displaying a modal error dialog of some kind. When you configure DCOM to launch as some user (not the interactive user), the process gets its own "windows station" which is not actually visible to you as the logged in user. So there is a dialog popped up somewhere invisible, waiting for input forever, hence the hang. Why the dialog is displaying is a different matter, likely a permissions issue. Sometimes, certain parts of the registry are available or not available in different activation contexts, for example.
Thanks Jlew for the link. It helped me to solve the problem by changing a register value from “Shared Section=1024,20480,768” to “Shared Section=1024,20480,2304” (3 times bigger) on this register key: HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session Manager\SubSystems\Windows
This value specifies a memory heap size when the user is not logged on. I guess it was not enough to handle all the MiniTab graphs.
Pablo