Пример #1
0
        ///<summary>This function will throw if the Process fails to start. Catch in calling class. Runs the file.
        ///Downloads it from the cloud if necessary.</summary>
        public static void StartProcess(string fileFullPath)
        {
            string filePathToOpen;

            if (CloudStorage.IsCloudStorage)
            {
                FormProgress FormP = CreateFormProgress("Downloading...");
                OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(Path.GetDirectoryName(fileFullPath), Path.GetFileName(fileFullPath),
                                                                                          new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
                FormP.ShowDialog();
                if (FormP.DialogResult == DialogResult.Cancel)
                {
                    state.DoCancel = true;
                    return;
                }
                filePathToOpen = PrefC.GetRandomTempFile(Path.GetExtension(fileFullPath));
                File.WriteAllBytes(filePathToOpen, state.FileContent);
            }
            else
            {
                filePathToOpen = fileFullPath;
            }
            if (ODBuild.IsWeb())
            {
                ThinfinityUtils.HandleFile(filePathToOpen);
            }
            else
            {
                Process.Start(filePathToOpen);
            }
        }
Пример #2
0
 ///<summary>Returns null if the the image could not be downloaded or the user canceled the download.</summary>
 public static Image GetImage(string imagePath)
 {
     if (CloudStorage.IsCloudStorage)
     {
         FormProgress FormP = CreateFormProgress("Downloading...");
         OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(Path.GetDirectoryName(imagePath), Path.GetFileName(imagePath),
                                                                                   new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
         if (FormP.ShowDialog() == DialogResult.Cancel)
         {
             state.DoCancel = true;
             return(null);
         }
         if (state == null || state.FileContent == null || state.FileContent.Length < 2)
         {
             return(null);
         }
         else
         {
             using (MemoryStream stream = new MemoryStream(state.FileContent)) {
                 return(new Bitmap(Image.FromStream(stream)));
             }
         }
     }
     else              //Not cloud
     {
         return(Image.FromFile(imagePath));
     }
 }
Пример #3
0
        private void butPreview_Click(object sender, EventArgs e)
        {
            //A couple options here
            //Download the file and run the explorer windows process to show the temporary file
            if (!gridMain.ListGridRows[gridMain.GetSelectedIndex()].Cells[0].Text.Contains("."))             //File path doesn't contain an extension and thus is a subfolder.
            {
                return;
            }
            FormProgress FormP = new FormProgress();

            FormP.DisplayText          = "Downloading...";
            FormP.NumberFormat         = "F";
            FormP.NumberMultiplication = 1;
            FormP.MaxVal = 100;          //Doesn't matter what this value is as long as it is greater than 0
            FormP.TickMS = 1000;
            OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(textPath.Text
                                                                                      , Path.GetFileName(gridMain.ListGridRows[gridMain.GetSelectedIndex()].Cells[0].Text)
                                                                                      , new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
            if (FormP.ShowDialog() == DialogResult.Cancel)
            {
                state.DoCancel = true;
                return;
            }
            string tempFile = ODFileUtils.CreateRandomFile(Path.GetTempPath(), Path.GetExtension(gridMain.ListGridRows[gridMain.GetSelectedIndex()].Cells[0].Text));

            File.WriteAllBytes(tempFile, state.FileContent);
            if (ODBuild.IsWeb())
            {
                ThinfinityUtils.HandleFile(tempFile);
            }
            else
            {
                System.Diagnostics.Process.Start(tempFile);
            }
        }
Пример #4
0
 private void butOpen_Click(object sender, EventArgs e)
 {
     if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ)
     {
         System.Diagnostics.Process.Start("Explorer", Path.GetDirectoryName(textFileName.Text));
     }
     else if (CloudStorage.IsCloudStorage)             //First download, then open
     {
         FormProgress FormP = new FormProgress();
         FormP.DisplayText          = "Downloading...";
         FormP.NumberFormat         = "F";
         FormP.NumberMultiplication = 1;
         FormP.MaxVal = 100;              //Doesn't matter what this value is as long as it is greater than 0
         FormP.TickMS = 1000;
         OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(ImageStore.GetPatientFolder(PatCur, "")
                                                                                   , DocCur.FileName
                                                                                   , new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
         FormP.ShowDialog();
         if (FormP.DialogResult == DialogResult.Cancel)
         {
             state.DoCancel = true;
             return;
         }
         //Create temp file here or create the file with the actual name?  Changes made when opening the file won't be saved, so I think temp file is best.
         string tempFile = PrefC.GetRandomTempFile(Path.GetExtension(DocCur.FileName));
         File.WriteAllBytes(tempFile, state.FileContent);
         System.Diagnostics.Process.Start(tempFile);
     }
 }
Пример #5
0
        ///<summary>Converts an image markup tag like [[img:myimage.jpeg]] to html.</summary>
        private static string TranslateEmailImages(string s)
        {
            //[[img:myimage.jpg]]------------------------------------------------------------------------------------------------------------
            MatchCollection matches = Regex.Matches(s, _odWikiImage);

            foreach (Match match in matches)
            {
                string imgName   = match.Value.Substring(match.Value.IndexOf(":") + 1).TrimEnd("]".ToCharArray());
                string imagePath = "";
                try {
                    imagePath = ImageStore.GetEmailImagePath();
                }
                catch (Exception ex) {
                    ex.DoNothing();
                    throw;
                }
                string fullPath = FileAtoZ.CombinePaths(imagePath, POut.String(imgName));
                if (CloudStorage.IsCloudStorage)
                {
                    //WebBrowser needs to have a local file to open, so we download the images to temp files.
                    OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.Download(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath));
                    string tempFile = PrefC.GetRandomTempFile(Path.GetExtension(fullPath));
                    File.WriteAllBytes(tempFile, state.FileContent);
                    fullPath = tempFile;
                }
                s = s.Replace(match.Value, "<img src=\"" + fullPath + "\"></img>");                 //"\" />");
            }
            return(s);
        }
Пример #6
0
 ///<summary>Returns the string contents of the file. Sychronous for cloud storage.</summary>
 public static string ReadAllText(string fileFullPath)
 {
     if (CloudStorage.IsCloudStorage)
     {
         OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.Download(Path.GetDirectoryName(fileFullPath), Path.GetFileName(fileFullPath));
         return(Encoding.UTF8.GetString(state.FileContent));
     }
     else              //Not cloud
     {
         return(File.ReadAllText(fileFullPath));
     }
 }
Пример #7
0
 ///<summary>Returns the byte contents of the file. Sychronous for cloud storage.</summary>
 public static byte[] ReadAllBytes(string fileFullPath)
 {
     if (CloudStorage.IsCloudStorage)
     {
         OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.Download(Path.GetDirectoryName(fileFullPath), Path.GetFileName(fileFullPath));
         return(state.FileContent);
     }
     else              //Not cloud
     {
         return(File.ReadAllBytes(fileFullPath));
     }
 }
Пример #8
0
 ///<summary>Returns null if the the image could not be downloaded. Sychronous.</summary>
 public static Bitmap GetImage(string imagePath)
 {
     if (CloudStorage.IsCloudStorage)
     {
         OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.Download(Path.GetDirectoryName(imagePath), Path.GetFileName(imagePath));
         if (state == null || state.FileContent == null || state.FileContent.Length < 2)
         {
             return(null);
         }
         using (MemoryStream stream = new MemoryStream(state.FileContent)) {
             return(new Bitmap(Image.FromStream(stream)));
         }
     }
     //Not cloud
     return(new Bitmap(Image.FromFile(imagePath)));
 }
Пример #9
0
 ///<summary>Copies or downloads the file and opens it. acutalFileName should be a full path, displayedFileName should be a file name only.
 ///</summary>
 public static void OpenFile(string actualFilePath, string displayedFileName = "")
 {
     try {
         string tempFile;
         if (displayedFileName == "")
         {
             tempFile = ODFileUtils.CombinePaths(PrefC.GetTempFolderPath(), Path.GetFileName(actualFilePath));
         }
         else
         {
             tempFile = ODFileUtils.CombinePaths(PrefC.GetTempFolderPath(), displayedFileName);
         }
         if (CloudStorage.IsCloudStorage)
         {
             FormProgress FormP = CreateFormProgress("Downloading...");
             OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(Path.GetDirectoryName(actualFilePath),
                                                                                       Path.GetFileName(actualFilePath), new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
             FormP.ShowDialog();
             if (FormP.DialogResult == DialogResult.Cancel)
             {
                 state.DoCancel = true;
                 return;
             }
             File.WriteAllBytes(tempFile, state.FileContent);
         }
         else                   //Not Cloud
                                //We have to create a copy of the file because the name is different.
                                //There is also a high probability that the attachment no longer exists if
                                //images are stored in the database, since the file will have originally been
                                //placed in the temporary directory.
         {
             File.Copy(actualFilePath, tempFile, true);
         }
         if (ODBuild.IsWeb())
         {
             ThinfinityUtils.HandleFile(tempFile);
         }
         else
         {
             Process.Start(tempFile);
         }
     }
     catch (Exception ex) {
         MessageBox.Show(ex.Message);
     }
 }
Пример #10
0
 ///<summary>Returns the string contents of the file.</summary>
 public static string ReadAllText(string fileName)
 {
     if (CloudStorage.IsCloudStorage)
     {
         FormProgress FormP = CreateFormProgress("Downloading...");
         OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(Path.GetDirectoryName(fileName), Path.GetFileName(fileName),
                                                                                   new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
         FormP.ShowDialog();
         if (FormP.DialogResult == DialogResult.Cancel)
         {
             state.DoCancel = true;
             return("");
         }
         return(Encoding.UTF8.GetString(state.FileContent));
     }
     else              //Not cloud
     {
         return(File.ReadAllText(fileName));
     }
 }
Пример #11
0
        ///<summary>Attempts to open the document using the default program. If not using AtoZfolder saves a local temp file and opens it.</summary>
        public static void OpenDoc(long docNum)
        {
            Document docCur = Documents.GetByNum(docNum);

            if (docCur.DocNum == 0)
            {
                return;
            }
            Patient patCur = Patients.GetPat(docCur.PatNum);

            if (patCur == null)
            {
                return;
            }
            string docPath;

            if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ)
            {
                docPath = ImageStore.GetFilePath(docCur, ImageStore.GetPatientFolder(patCur, ImageStore.GetPreferredAtoZpath()));
            }
            else if (PrefC.AtoZfolderUsed == DataStorageType.InDatabase)
            {
                //Some programs require a file on disk and cannot open in memory files. Save to temp file from DB.
                docPath = PrefC.GetRandomTempFile(ImageStore.GetExtension(docCur));
                File.WriteAllBytes(docPath, Convert.FromBase64String(docCur.RawBase64));
            }
            else              //Cloud storage
                              //Download file to temp directory
            {
                OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.Download(ImageStore.GetPatientFolder(patCur, ImageStore.GetPreferredAtoZpath())
                                                                                     , docCur.FileName);
                docPath = PrefC.GetRandomTempFile(ImageStore.GetExtension(docCur));
                if (ODBuild.IsWeb())
                {
                    ThinfinityUtils.HandleFile(docPath);
                    return;
                }
                File.WriteAllBytes(docPath, state.FileContent);
            }
            Process.Start(docPath);
        }
Пример #12
0
        ///<summary>Uses sheet framework to generate a PDF file, save it to patient's image folder, and attempt to launch file with defualt reader.
        ///If using ImagesStoredInDB it will not launch PDF. If no valid patient is selected you cannot perform this action.</summary>
        private void butPDF_Click(object sender, EventArgs e)
        {
            if (PatCur == null)           //not attached to a patient when form loaded and they haven't selected a patient to attach to yet
            {
                MsgBox.Show(this, "The Medical Lab must be attached to a patient before the PDF can be saved.");
                return;
            }
            if (PatCur.PatNum > 0 && _medLabCur.PatNum != PatCur.PatNum)         //save the current patient attached to the MedLab if it has been changed
            {
                MoveLabsAndImagesHelper();
            }
            Cursor = Cursors.WaitCursor;
            SheetDef sheetDef = SheetUtil.GetMedLabResultsSheetDef();
            Sheet    sheet    = SheetUtil.CreateSheet(sheetDef, _medLabCur.PatNum);

            SheetFiller.FillFields(sheet, null, null, _medLabCur);
            //create the file in the temp folder location, then import so it works when storing images in the db
            string tempPath = ODFileUtils.CombinePaths(PrefC.GetTempFolderPath(), _medLabCur.PatNum.ToString() + ".pdf");

            SheetPrinting.CreatePdf(sheet, tempPath, null, _medLabCur);
            HL7Def defCur   = HL7Defs.GetOneDeepEnabled(true);
            long   category = defCur.LabResultImageCat;

            if (category == 0)
            {
                category = Defs.GetFirstForCategory(DefCat.ImageCats, true).DefNum;             //put it in the first category.
            }
            //create doc--------------------------------------------------------------------------------------
            OpenDentBusiness.Document docc = null;
            try {
                docc = ImageStore.Import(tempPath, category, Patients.GetPat(_medLabCur.PatNum));
            }
            catch (Exception ex) {
                ex.DoNothing();
                Cursor = Cursors.Default;
                MsgBox.Show(this, "Error saving document.");
                return;
            }
            finally {
                //Delete the temp file since we don't need it anymore.
                try {
                    File.Delete(tempPath);
                }
                catch {
                    //Do nothing.  This file will likely get cleaned up later.
                }
            }
            docc.Description = Lan.g(this, "MedLab Result");
            docc.DateCreated = DateTime.Now;
            Documents.Update(docc);
            string filePathAndName = "";

            if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ)
            {
                string patFolder = ImageStore.GetPatientFolder(Patients.GetPat(_medLabCur.PatNum), ImageStore.GetPreferredAtoZpath());
                filePathAndName = ODFileUtils.CombinePaths(patFolder, docc.FileName);
            }
            else if (CloudStorage.IsCloudStorage)
            {
                FormProgress FormP = new FormProgress();
                FormP.DisplayText          = "Downloading...";
                FormP.NumberFormat         = "F";
                FormP.NumberMultiplication = 1;
                FormP.MaxVal = 100;              //Doesn't matter what this value is as long as it is greater than 0
                FormP.TickMS = 1000;
                OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(
                    ImageStore.GetPatientFolder(Patients.GetPat(_medLabCur.PatNum), ImageStore.GetPreferredAtoZpath())
                    , docc.FileName
                    , new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
                if (FormP.ShowDialog() == DialogResult.Cancel)
                {
                    state.DoCancel = true;
                    return;
                }
                filePathAndName = PrefC.GetRandomTempFile(Path.GetExtension(docc.FileName));
                File.WriteAllBytes(filePathAndName, state.FileContent);
            }
            Cursor = Cursors.Default;
            if (filePathAndName != "")
            {
                Process.Start(filePathAndName);
            }
            SecurityLogs.MakeLogEntry(Permissions.SheetEdit, sheet.PatNum, sheet.Description + " from " + sheet.DateTimeSheet.ToShortDateString() + " pdf was created");
            DialogResult = DialogResult.OK;
        }
        private void SaveAttachment()
        {
            Patient PatCur = Patients.GetPat(PatNum);

            //if(PatCur.ImageFolder=="") {
            //	MsgBox.Show(this,"Invalid patient image folder.");
            //	return;
            //}
            if (PrefC.AtoZfolderUsed == DataStorageType.InDatabase)
            {
                MsgBox.Show(this, "Error. Not using AtoZ images folder.");
                return;
            }
            string patfolder = ImageStore.GetPatientFolder(PatCur, ImageStore.GetPreferredAtoZpath());
            //ODFileUtils.CombinePaths(
            //FormPath.GetPreferredImagePath(),PatCur.ImageFolder.Substring(0,1).ToUpper(),PatCur.ImageFolder);
            //if(!Directory.Exists(patfolder)) {
            //	MsgBox.Show(this,"Patient folder not found in AtoZ folder.");
            //	return;
            //}
            Document doc = Docs[gridMain.GetSelectedIndex()];

            if (!ImageHelper.HasImageExtension(doc.FileName))
            {
                MsgBox.Show(this, "Invalid file.  Only images may be attached, no other file format.");
                return;
            }
            string oldPath = ODFileUtils.CombinePaths(patfolder, doc.FileName);
            Random rnd     = new Random();
            string newName = DateTime.Now.ToString("yyyyMMdd") + "_" + DateTime.Now.TimeOfDay.Ticks.ToString() + rnd.Next(1000).ToString()
                             + Path.GetExtension(oldPath);
            string attachPath = EmailAttaches.GetAttachPath();
            string newPath    = ODFileUtils.CombinePaths(attachPath, newName);

            if (CloudStorage.IsCloudStorage)
            {
                oldPath = oldPath.Replace("\\", "/");
                newPath = newPath.Replace("\\", "/");
            }
            try {
                if (ImageHelper.HasImageExtension(oldPath))
                {
                    if (doc.CropH != 0 ||
                        doc.CropW != 0 ||
                        doc.CropX != 0 ||
                        doc.CropY != 0 ||
                        doc.DegreesRotated != 0 ||
                        doc.IsFlipped ||
                        doc.WindowingMax != 0 ||
                        doc.WindowingMin != 0 ||
                        CloudStorage.IsCloudStorage)
                    {
                        //this does result in a significantly larger images size if jpg.  A later optimization would recompress it.
                        Bitmap bitmapold = null;
                        if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ)
                        {
                            bitmapold = (Bitmap)Bitmap.FromFile(oldPath);
                            Bitmap bitmapnew = ImageHelper.ApplyDocumentSettingsToImage(doc, bitmapold, ImageSettingFlags.ALL);
                            bitmapnew.Save(newPath);
                        }
                        else if (CloudStorage.IsCloudStorage)
                        {
                            //First, download the file.
                            FormProgress FormP = new FormProgress();
                            FormP.DisplayText          = "Downloading Image...";
                            FormP.NumberFormat         = "F";
                            FormP.NumberMultiplication = 1;
                            FormP.MaxVal = 100;                          //Doesn't matter what this value is as long as it is greater than 0
                            FormP.TickMS = 1000;
                            OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(patfolder
                                                                                                      , doc.FileName
                                                                                                      , new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
                            FormP.ShowDialog();
                            if (FormP.DialogResult == DialogResult.Cancel)
                            {
                                state.DoCancel = true;
                                return;
                            }
                            //Successfully downloaded, now do stuff with state.FileContent
                            FormP                      = new FormProgress();
                            FormP.DisplayText          = "Uploading Image for Claim Attach...";
                            FormP.NumberFormat         = "F";
                            FormP.NumberMultiplication = 1;
                            FormP.MaxVal               = 100;            //Doesn't matter what this value is as long as it is greater than 0
                            FormP.TickMS               = 1000;
                            OpenDentalCloud.Core.TaskStateUpload state2 = CloudStorage.UploadAsync(attachPath
                                                                                                   , newName
                                                                                                   , state.FileContent
                                                                                                   , new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
                            FormP.ShowDialog();
                            if (FormP.DialogResult == DialogResult.Cancel)
                            {
                                state2.DoCancel = true;
                                return;
                            }
                            //Upload was successful
                        }
                    }
                    else
                    {
                        File.Copy(oldPath, newPath);
                    }
                }
                else
                {
                    File.Copy(oldPath, newPath);
                }
                ClaimAttachNew = new ClaimAttach();
                ClaimAttachNew.DisplayedFileName = Docs[gridMain.GetSelectedIndex()].FileName;
                ClaimAttachNew.ActualFileName    = newName;
                DialogResult = DialogResult.OK;
            }
            catch (FileNotFoundException ex) {
                MessageBox.Show(Lan.g(this, "File not found: ") + ex.Message);
                return;
            }
            catch (Exception ex) {
                MessageBox.Show(ex.Message);
            }
        }
Пример #14
0
 private void FillImage()
 {
     if (comboFieldName.Text == "")
     {
         return;
     }
     if (CloudStorage.IsCloudStorage)
     {
         textFullPath.Text = CloudStorage.PathTidy(ODFileUtils.CombinePaths(SheetUtil.GetImagePath(), comboFieldName.Text));
     }
     else
     {
         textFullPath.Text = ODFileUtils.CombinePaths(SheetUtil.GetImagePath(), comboFieldName.Text);
     }
     if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ && File.Exists(textFullPath.Text))
     {
         GC.Collect();
         try {
             pictureBox.Image = Image.FromFile(textFullPath.Text);
         }
         catch {
             pictureBox.Image = null;
             MsgBox.Show(this, "Invalid image type.");
         }
     }
     else if (comboFieldName.Text == "Patient Info.gif")           //Interal image
     {
         pictureBox.Image  = OpenDentBusiness.Properties.Resources.Patient_Info;
         textFullPath.Text = "Patient Info.gif (internal)";
     }
     else if (CloudStorage.IsCloudStorage)
     {
         if (comboFieldName.Text == SheetFieldDefCur.FieldName && SheetFieldDefCur.ImageField != null)
         {
             pictureBox.Image = SheetFieldDefCur.ImageField;
         }
         else
         {
             FormProgress FormP = new FormProgress();
             FormP.DisplayText          = Lan.g(CloudStorage.LanThis, "Downloading...");
             FormP.NumberFormat         = "F";
             FormP.NumberMultiplication = 1;
             FormP.MaxVal = 100;                  //Doesn't matter what this value is as long as it is greater than 0
             FormP.TickMS = 1000;
             OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(SheetUtil.GetImagePath(), comboFieldName.Text,
                                                                                       new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
             if (FormP.ShowDialog() == DialogResult.Cancel)
             {
                 state.DoCancel = true;
                 return;
             }
             if (state == null || state.FileContent == null)
             {
                 pictureBox.Image = null;
             }
             else
             {
                 using (MemoryStream stream = new MemoryStream(state.FileContent)) {
                     pictureBox.Image = new Bitmap(Image.FromStream(stream));
                 }
             }
         }
     }
     else
     {
         pictureBox.Image = null;
     }
     if (pictureBox.Image == null)
     {
         textWidth2.Text  = "";
         textHeight2.Text = "";
     }
     else
     {
         textWidth2.Text  = pictureBox.Image.Width.ToString();
         textHeight2.Text = pictureBox.Image.Height.ToString();
     }
 }
Пример #15
0
        private void butPickRxListImage_Click(object sender, EventArgs e)
        {
            if (PrefC.AtoZfolderUsed == DataStorageType.InDatabase)
            {
                MsgBox.Show(this, "This option is not supported with images stored in the database.");
                return;
            }
            FormImageSelect formIS = new FormImageSelect();

            formIS.PatNum = PatCur.PatNum;
            formIS.ShowDialog();
            if (formIS.DialogResult != DialogResult.OK)
            {
                return;
            }
            string   patFolder = ImageStore.GetPatientFolder(PatCur, ImageStore.GetPreferredAtoZpath());
            Document doc       = Documents.GetByNum(formIS.SelectedDocNum);

            if (!ImageStore.HasImageExtension(doc.FileName))
            {
                MsgBox.Show(this, "The selected file is not a supported image type.");
                return;
            }
            textDocDateDesc.Text = doc.DateTStamp.ToShortDateString() + " - " + doc.Description.ToString();
            if (BitmapOriginal != null)
            {
                BitmapOriginal.Dispose();
            }
            if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ)
            {
                BitmapOriginal = ImageStore.OpenImage(doc, patFolder);
            }
            else
            {
                FormProgress FormP = new FormProgress();
                FormP.DisplayText          = "Downloading Image...";
                FormP.NumberFormat         = "F";
                FormP.NumberMultiplication = 1;
                FormP.MaxVal = 100;              //Doesn't matter what this value is as long as it is greater than 0
                FormP.TickMS = 1000;
                OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.DownloadAsync(patFolder
                                                                                          , doc.FileName
                                                                                          , new OpenDentalCloud.ProgressHandler(FormP.OnProgress));
                FormP.ShowDialog();
                if (FormP.DialogResult == DialogResult.Cancel)
                {
                    state.DoCancel = true;
                    return;
                }
                else
                {
                    using (MemoryStream ms = new MemoryStream(state.FileContent)) {
                        BitmapOriginal = new Bitmap(ms);
                    }
                }
            }
            Bitmap bitmap = ImageHelper.ApplyDocumentSettingsToImage(doc, BitmapOriginal, ImageSettingFlags.ALL);

            pictBox.BackgroundImage = bitmap;
            resizePictBox();
        }
Пример #16
0
        ///<summary>Surround with try/catch.  Also aggregates the content into the master page (unless specified to not).
        ///If isPreviewOnly, then the internal links will not be checked to see if the page exists, as it would make the refresh sluggish.
        ///And isPreviewOnly also changes the pointer so that the page looks non-clickable.
        ///For emails, this only gets called while in the email edit window. The returned string will be used to switch between plain and html text.
        ///</summary>
        public static string TranslateToXhtml(string markupText, bool isPreviewOnly, bool hasWikiPageTitles = false, bool isEmail = false, bool canAggregate = true)
        {
            //No need to check RemotingRole; no call to db.
            #region Basic Xml Validation
            string          s = markupText;
            MatchCollection matches;
            //"<",">", and "&"-----------------------------------------------------------------------------------------------------------
            s = s.Replace("&", "&amp;");
            s = s.Replace("&amp;<", "&lt;");         //because "&" was changed to "&amp;" in the line above.
            s = s.Replace("&amp;>", "&gt;");         //because "&" was changed to "&amp;" in the line above.
            s = "<body>" + s + "</body>";
            XmlDocument doc = new XmlDocument();
            using (StringReader reader = new StringReader(s)) {
                doc.Load(reader);
            }
            #endregion
            #region regex replacements
            if (isEmail)
            {
                s = TranslateEmailImages(s);              //handle email images and wiki images separately.
            }
            else
            {
                //[[img:myimage.gif]]------------------------------------------------------------------------------------------------------------
                matches = Regex.Matches(s, _odWikiImage);
                foreach (Match match in matches)
                {
                    string imgName  = match.Value.Substring(match.Value.IndexOf(":") + 1).TrimEnd("]".ToCharArray());
                    string wikiPath = "";
                    try {
                        wikiPath = WikiPages.GetWikiPath();
                    }
                    catch (Exception ex) {
                        ex.DoNothing();
                        throw;
                    }
                    string fullPath = FileAtoZ.CombinePaths(wikiPath, POut.String(imgName));
                    if (CloudStorage.IsCloudStorage)
                    {
                        //WebBrowser needs to have a local file to open, so we download the images to temp files.
                        OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.Download(Path.GetDirectoryName(fullPath), Path.GetFileName(fullPath));
                        string tempFile = PrefC.GetRandomTempFile(Path.GetExtension(fullPath));
                        File.WriteAllBytes(tempFile, state.FileContent);
                        fullPath = tempFile;
                    }
                    s = s.Replace(match.Value, "<img src=\"file:///" + fullPath.Replace("\\", "/") + "\"></img>");
                }
                //[[keywords: key1, key2, etc.]]------------------------------------------------------------------------------------------------
                matches = Regex.Matches(s, _odWikiKeyword);
                foreach (Match match in matches)                 //should be only one
                {
                    s = s.Replace(match.Value, "<span class=\"keywords\">keywords:" + match.Value.Substring(11).TrimEnd("]".ToCharArray()) + "</span>");
                }
                //[[file:C:\eaula.txt]]------------------------------------------------------------------------------------------------
                matches = Regex.Matches(s, _odWikiFile);
                foreach (Match match in matches)
                {
                    string fileName = match.Value.Replace("[[file:", "").TrimEnd(']');
                    s = s.Replace(match.Value, "<a href=\"wikifile:" + fileName + "\">file:" + fileName + "</a>");
                }
                //[[folder:\\serverfiles\storage\]]------------------------------------------------------------------------------------------------
                matches = Regex.Matches(s, _odWikiFolder);
                foreach (Match match in matches)
                {
                    string folderName = match.Value.Replace("[[folder:", "").TrimEnd(']');
                    s = s.Replace(match.Value, "<a href=\"folder:" + folderName + "\">folder:" + folderName + "</a>");
                }
                //[[filecloud:AtoZ/SheetImages/happyclown.jpg]]------------------------------------------------------------------------------------------------
                matches = Regex.Matches(s, _odWikiFilecloud);
                foreach (Match match in matches)
                {
                    string fileName = CloudStorage.PathTidy(match.Value.Replace("[[filecloud:", "").TrimEnd(']'));
                    s = s.Replace(match.Value, "<a href=\"wikifilecloud:" + fileName + "\">filecloud:" + fileName + "</a>");
                }
                //[[foldercloud:AtoZ/PenguinPictures/]]------------------------------------------------------------------------------------------------
                matches = Regex.Matches(s, _odWikiFoldercloud);
                foreach (Match match in matches)
                {
                    string folderName = CloudStorage.PathTidy(match.Value.Replace("[[foldercloud:", "").TrimEnd(']'));
                    s = s.Replace(match.Value, "<a href=\"foldercloud:" + folderName + "\">foldercloud:" + folderName + "</a>");
                }
            }
            //Color and text are for both wiki and email. It's important we do this before Internal Link or else the translation may not work.
            //[[color:red|text]]----------------------------------------------------------------------------------------------------------------
            matches = Regex.Matches(s, _odWikiColor);           //.*? matches as few as possible.
            foreach (Match match in matches)
            {
                //string[] paragraphs = match.Value.Split(new string[] { "\n" },StringSplitOptions.None);
                string   tempText = "<span style=\"color:";
                string[] tokens   = match.Value.Split('|');
                if (tokens.Length < 2)               //not enough tokens
                {
                    continue;
                }
                if (tokens[0].Split(':').Length != 2)               //Must have a color token and a color value seperated by a colon, no more no less.
                {
                    continue;
                }
                for (int i = 0; i < tokens.Length; i++)
                {
                    if (i == 0)
                    {
                        tempText += tokens[0].Split(':')[1] + ";\">";                    //close <span> tag
                        continue;
                    }
                    tempText += (i > 1?"|":"") + tokens[i];
                }
                tempText  = tempText.TrimEnd(']');
                tempText += "</span>";
                s         = s.Replace(match.Value, tempText);
            }
            //[[font-family:courier|text]]----------------------------------------------------------------------------------------------------------------
            matches = Regex.Matches(s, _odWikiFont);           //.*? matches as few as possible.
            foreach (Match match in matches)
            {
                //string[] paragraphs = match.Value.Split(new string[] { "\n" },StringSplitOptions.None);
                string   tempText = "<span style=\"font-family:";
                string[] tokens   = match.Value.Split('|');
                if (tokens.Length < 2)               //not enough tokens
                {
                    continue;
                }
                if (tokens[0].Split(':').Length != 2)               //Must have a color token and a color value seperated by a colon, no more no less.
                {
                    continue;
                }
                for (int i = 0; i < tokens.Length; i++)
                {
                    if (i == 0)
                    {
                        tempText += tokens[0].Split(':')[1] + ";\">";                    //close <span> tag
                        continue;
                    }
                    tempText += (i > 1?"|":"") + tokens[i];
                }
                tempText  = tempText.TrimEnd(']');
                tempText += "</span>";
                s         = s.Replace(match.Value, tempText);
            }
            if (!isEmail)
            {
                //[[InternalLink]]--------------------------------------------------------------------------------------------------------------
                matches = Regex.Matches(s, @"\[\[.+?\]\]");
                List <string> pageNamesToCheck = new List <string>();
                List <bool>   pageNamesExist   = new List <bool>();
                string        styleNotExists   = "";
                if (hasWikiPageTitles)
                {
                    if (!isPreviewOnly)
                    {
                        foreach (Match match in matches)
                        {
                            //The '&' was replaced with '&amp;' above, so we change it back before looking for a wiki page with that name.
                            pageNamesToCheck.Add(match.Value.Trim('[', ']').Replace("&amp;", "&"));
                        }
                        if (pageNamesToCheck.Count > 0)
                        {
                            pageNamesExist = WikiPages.CheckPageNamesExist(pageNamesToCheck);                          //this gets a list of bools for all pagenames in one shot.  One query.
                        }
                    }
                    foreach (Match match in matches)
                    {
                        styleNotExists = "";
                        if (!isPreviewOnly)
                        {
                            //The '&' was replaced with '&amp;' above, so we change it back before looking for a wiki page with that name.
                            string pageName = match.Value.Trim('[', ']').Replace("&amp;", "&");
                            int    idx      = pageNamesToCheck.IndexOf(pageName);
                            if (!pageNamesExist[idx])
                            {
                                styleNotExists = "class='PageNotExists' ";
                            }
                        }
                        s = s.Replace(match.Value, "<a " + styleNotExists + "href=\"" + "wiki:" + match.Value.Trim('[', ']')            /*.Replace(" ","_")*/
                                      + "\">" + match.Value.Trim('[', ']') + "</a>");
                    }
                }
                else
                {
                    List <long>     listWikiPageNums = WikiPages.GetWikiPageNumsFromPageContent(s);
                    List <WikiPage> listWikiPages    = WikiPages.GetWikiPages(listWikiPageNums);
                    int             numInvalid       = 1;
                    foreach (Match match in matches)
                    {
                        WikiPage wp = listWikiPages.FirstOrDefault(x => x.WikiPageNum == PIn.Long(match.Value.TrimStart('[').TrimEnd(']')));
                        string   pageName;
                        if (wp != null)
                        {
                            pageName = wp.PageTitle;
                        }
                        else
                        {
                            pageName = "INVALID WIKIPAGE LINK " + numInvalid++;
                        }
                        if (!isPreviewOnly)
                        {
                            styleNotExists = "";
                            if (wp == null)
                            {
                                styleNotExists = "class='PageNotExists' ";
                            }
                        }
                        pageName = pageName.Replace("&", "&amp;").Replace("&amp;<", "&lt;").Replace("&amp;>", "&gt;");
                        string replace = "<a " + styleNotExists + "href=\"" + "wiki:" + pageName /*.Replace(" ","_")*/ + "\">" + pageName + "</a>";
                        Regex  regex   = new Regex(Regex.Escape(match.Value));
                        //Replace the first instance of the match with the wiki page name (or unknown if not found).
                        s = regex.Replace(s, replace, 1);
                    }
                }
            }
            //Unordered List----------------------------------------------------------------------------------------------------------------
            //Instead of using a regex, this will hunt through the rows in sequence.
            //later nesting by running ***, then **, then *
            s = ProcessList(s, "*");
            //numbered list---------------------------------------------------------------------------------------------------------------------
            s = ProcessList(s, "#");
            //table-------------------------------------------------------------------------------------------------------------------------
            //{|
            //!Width="100"|Column Heading 1!!Width="150"|Column Heading 2!!Width=""|Column Heading 3
            //|-
            //|Cell 1||Cell 2||Cell 3
            //|-
            //|Cell A||Cell B||Cell C
            //|}
            //There are many ways to parse this.  Our strategy is to do it in a way that the generated xml is never invalid.
            //As the user types, the above example will frequently be in a state of partial completeness, and the parsing should gracefully continue anyway.
            //rigorous enforcement only happens when validating during a save, not here.
            matches = Regex.Matches(s, _odWikiTable, RegexOptions.Singleline);
            foreach (Match match in matches)
            {
                //If there isn't a new line before the start of the table markup or after the end, the match group value will be an empty string
                //Tables must start with "'newline'{|" and end with "|}'newline'"
                string        tableStrOrig = match.Value;
                StringBuilder strbTable    = new StringBuilder();
                string[]      lines        = tableStrOrig.Split(new string[] { "{|\n", "\n|-\n", "\n|}" }, StringSplitOptions.RemoveEmptyEntries);
                strbTable.AppendLine("<table>");
                List <string> colWidths = new List <string>();
                for (int i = 0; i < lines.Length; i++)
                {
                    if (lines[i].StartsWith("!"))                     //header
                    {
                        strbTable.AppendLine("<tr>");
                        lines[i] = lines[i].Substring(1);                      //strips off the leading !
                        string[] cells = lines[i].Split(new string[] { "!!" }, StringSplitOptions.None);
                        colWidths.Clear();
                        for (int c = 0; c < cells.Length; c++)
                        {
                            if (Regex.IsMatch(cells[c], @"(Width="")\d+""\|"))                           //e.g. Width="90"|
                            {
                                strbTable.Append("<th ");
                                string width = cells[c].Substring(7);                              //90"|Column Heading 1
                                width = width.Substring(0, width.IndexOf("\""));                   //90
                                colWidths.Add(width);
                                strbTable.Append("Width=\"" + width + "\">");
                                strbTable.Append(ProcessParagraph(cells[c].Substring(cells[c].IndexOf("|") + 1), false));                             //surround with p tags. Allow CR in header.
                                strbTable.AppendLine("</th>");
                            }
                            else
                            {
                                strbTable.Append("<th>");
                                strbTable.Append(ProcessParagraph(cells[c], false));                               //surround with p tags. Allow CR in header.
                                strbTable.AppendLine("</th>");
                            }
                        }
                        strbTable.AppendLine("</tr>");
                    }
                    else if (lines[i].Trim() == "|-")
                    {
                        //totally ignore these rows
                    }
                    else                     //normal row
                    {
                        strbTable.AppendLine("<tr>");
                        lines[i] = lines[i].Substring(1);                      //strips off the leading |
                        string[] cells = lines[i].Split(new string[] { "||" }, StringSplitOptions.None);
                        for (int c = 0; c < cells.Length; c++)
                        {
                            strbTable.Append("<td Width=\"" + colWidths[c] + "\">");
                            strbTable.Append(ProcessParagraph(cells[c], false));
                            strbTable.AppendLine("</td>");
                        }
                        strbTable.AppendLine("</tr>");
                    }
                }
                strbTable.Append("</table>");
                s = s.Replace(tableStrOrig, strbTable.ToString());
            }
            #endregion regex replacements
            #region paragraph grouping
            StringBuilder strbSnew = new StringBuilder();
            //a paragraph is defined as all text between sibling tags, even if just a \n.
            int iScanInParagraph = 0;          //scan starting at the beginning of s.  S gets chopped from the start each time we grab a paragraph or a sibiling element.
            //The scanning position represents the verified paragraph content, and does not advance beyond that.
            //move <body> tag over.
            strbSnew.Append("<body>");
            s = s.Substring(6);
            bool startsWithCR = false;          //todo: handle one leading CR if there is no text preceding it.
            if (s.StartsWith("\n"))
            {
                startsWithCR = true;
            }
            string tagName;
            Match  tagCurMatch;
            while (true)                                             //loop to either construct a paragraph, or to immediately add the next tag to strbSnew.
            {
                iScanInParagraph = s.IndexOf("<", iScanInParagraph); //Advance the scanner to the start of the next tag
                if (iScanInParagraph == -1)                          //there aren't any more tags, so current paragraph goes to end of string.  This won't happen
                {
                    throw new ApplicationException(Lans.g("WikiPages", "No tags found."));
                    //strbSnew.Append(ProcessParagraph(s));
                }
                if (s.Substring(iScanInParagraph).StartsWith("</body>"))
                {
                    strbSnew.Append(ProcessParagraph(s.Substring(0, iScanInParagraph), startsWithCR));
                    //startsWithCR=false;
                    //strbSnew.Append("</body>");
                    s = "";
                    iScanInParagraph = 0;
                    break;
                }
                tagName     = "";
                tagCurMatch = Regex.Match(s.Substring(iScanInParagraph), "^<.*?>");             //regMatch);//.*? means any char, zero or more, as few as possible
                if (tagCurMatch == null)
                {
                    //shouldn't happen unless closing bracket is missing
                    throw new ApplicationException(Lans.g("WikiPages", "Unexpected tag:") + " " + s.Substring(iScanInParagraph));
                }
                if (tagCurMatch.Value.Trim('<', '>').EndsWith("/"))
                {
                    //self terminating tags NOT are allowed
                    //this should catch all non-allowed self-terminating tags i.e. <br />, <inherits />, etc...
                    throw new ApplicationException(Lans.g("WikiPages", "All elements must have a beginning and ending tag. Unexpected tag:") + " " + s.Substring(iScanInParagraph));
                }
                //Nesting of identical tags causes problems:
                //<h1><h1>some text</h1></h1>
                //The first <h1> will match with the first </h1>.
                //We don't have time to support this outlier, so we will catch it in the validator when they save.
                //One possible strategy here might be:
                //idxNestedDuplicate=s.IndexOf("<"+tagName+">");
                //if(idxNestedDuplicate<s.IndexOf("</"+tagName+">"){
                //
                //}
                //Another possible strategy might be to use regular expressions.
                tagName = tagCurMatch.Value.Split(new string[] { "<", " ", ">" }, StringSplitOptions.RemoveEmptyEntries)[0]; //works with tags like <i>, <span ...>, and <img .../>
                if (s.IndexOf("</" + tagName + ">") == -1)                                                                   //this will happen if no ending tag.
                {
                    throw new ApplicationException(Lans.g("WikiPages", "No ending tag:") + " " + s.Substring(iScanInParagraph));
                }
                switch (tagName)
                {
                case "a":
                case "b":
                case "div":
                case "i":
                case "span":
                    iScanInParagraph = s.IndexOf("</" + tagName + ">", iScanInParagraph) + 3 + tagName.Length;
                    continue;                            //continues scanning this paragraph.

                case "h1":
                case "h2":
                case "h3":
                case "ol":
                case "ul":
                case "table":
                case "img":                        //can NOT be self-terminating
                    if (iScanInParagraph == 0)     //s starts with a non-paragraph tag, so there is no partially assembled paragraph to process.
                    //do nothing
                    {
                    }
                    else                              //we are already part way into assembling a paragraph.
                    {
                        strbSnew.Append(ProcessParagraph(s.Substring(0, iScanInParagraph), startsWithCR));
                        startsWithCR     = false;                          //subsequent paragraphs will not need this
                        s                = s.Substring(iScanInParagraph);  //chop off start of s
                        iScanInParagraph = 0;
                    }
                    //scan to the end of this element
                    int iScanSibling = s.IndexOf("</" + tagName + ">") + 3 + tagName.Length;
                    //tags without a closing tag were caught above.
                    //move the non-paragraph content over to s new.
                    strbSnew.Append(s.Substring(0, iScanSibling));
                    s = s.Substring(iScanSibling);
                    //scanning will start a totally new paragraph
                    break;

                default:
                    if (isEmail)
                    {
                        iScanInParagraph = s.IndexOf("</" + tagName + ">", iScanInParagraph) + 3 + tagName.Length;
                        continue;                                //continues scanning this paragraph
                    }
                    throw new ApplicationException(Lans.g("WikiPages", "Unexpected tag:") + " " + s.Substring(iScanInParagraph));
                }
            }
            strbSnew.Append("</body>");
            #endregion
            #region aggregation
            doc = new XmlDocument();
            using (StringReader reader = new StringReader(strbSnew.ToString())) {
                doc.Load(reader);
            }
            StringBuilder     strbOut  = new StringBuilder();
            XmlWriterSettings settings = new XmlWriterSettings();
            settings.Indent             = true;
            settings.IndentChars        = "\t";
            settings.OmitXmlDeclaration = true;
            settings.NewLineChars       = "\n";
            using (XmlWriter writer = XmlWriter.Create(strbOut, settings)) {
                doc.WriteTo(writer);
            }
            //spaces can't be handled prior to this point because &nbsp; crashes the xml parser.
            strbOut.Replace("  ", "&nbsp;&nbsp;");           //handle extra spaces.
            strbOut.Replace("<td></td>", "<td>&nbsp;</td>"); //force blank table cells to show not collapsed
            strbOut.Replace("<th></th>", "<th>&nbsp;</th>"); //and blank table headers
            strbOut.Replace("{{nbsp}}", "&nbsp;");           //couldn't add the &nbsp; earlier because
            strbOut.Replace("<p></p>", "<p>&nbsp;</p>");     //probably redundant but harmless
            //aggregate with master
            if (isEmail)
            {
                if (canAggregate)
                {
                    s = PrefC.GetString(PrefName.EmailMasterTemplate).Replace("@@@body@@@", strbOut.ToString());
                    return(s);
                }
                return(strbOut.ToString());
            }
            else
            {
                s = WikiPages.MasterPage.PageContent.Replace("@@@body@@@", strbOut.ToString());
            }
            #endregion aggregation

            /*
             * //js This code is buggy.  It will need very detailed comments and careful review before/if we ever turn it back on.
             * if(isPreviewOnly) {
             *      //do not change cursor from pointer to IBeam to Hand as you move the cursor around the preview page
             *      s=s.Replace("*{\n\t","*{\n\tcursor:default;\n\t");
             *      //do not underline links if you hover over them in the preview window
             *      s=s.Replace("a:hover{\n\ttext-decoration:underline;","a:hover{\n\t");
             * }*/
            return(s);
        }
Пример #17
0
 public static void LoadImagesToSheetDef(SheetDef sheetDefCur)
 {
     for (int j = 0; j < sheetDefCur.SheetFieldDefs.Count; j++)
     {
         try {
             if (sheetDefCur.SheetFieldDefs[j].FieldType == SheetFieldType.Image)
             {
                 string      filePathAndName = ODFileUtils.CombinePaths(SheetUtil.GetImagePath(), sheetDefCur.SheetFieldDefs[j].FieldName);
                 Image       img             = null;
                 ImageFormat imgFormat       = null;
                 if (sheetDefCur.SheetFieldDefs[j].ImageField != null)                       //The image has already been downloaded.
                 {
                     img       = new Bitmap(sheetDefCur.SheetFieldDefs[j].ImageField);
                     imgFormat = ImageFormat.Bmp;
                 }
                 else if (sheetDefCur.SheetFieldDefs[j].FieldName == "Patient Info.gif")
                 {
                     img       = OpenDentBusiness.Properties.Resources.Patient_Info;
                     imgFormat = img.RawFormat;
                 }
                 else if (PrefC.AtoZfolderUsed == DataStorageType.LocalAtoZ && File.Exists(filePathAndName))
                 {
                     img       = Image.FromFile(filePathAndName);
                     imgFormat = img.RawFormat;
                 }
                 else if (CloudStorage.IsCloudStorage)
                 {
                     OpenDentalCloud.Core.TaskStateDownload state = CloudStorage.Download(SheetUtil.GetImagePath(), sheetDefCur.SheetFieldDefs[j].FieldName);
                     if (state == null || state.FileContent == null)
                     {
                         throw new Exception(Lan.g(CloudStorage.LanThis, "Unable to download image."));
                     }
                     else
                     {
                         using (MemoryStream stream = new MemoryStream(state.FileContent)) {
                             img = new Bitmap(Image.FromStream(stream));
                         }
                         imgFormat = ImageFormat.Bmp;
                     }
                 }
                 //sheetDefCur.SheetFieldDefs[j].ImageData=POut.Bitmap(new Bitmap(img),ImageFormat.Png);//Because that's what we did before. Review this later.
                 long fileByteSize = 0;
                 using (MemoryStream ms = new MemoryStream()) {
                     img.Save(ms, imgFormat);                            // done solely to compute the file size of the image
                     fileByteSize = ms.Length;
                 }
                 if (fileByteSize > 2000000)
                 {
                     //for large images greater that ~2MB use jpeg format for compression. Large images in the 4MB + range have difficulty being displayed. It could be an issue with MYSQL or ASP.NET
                     sheetDefCur.SheetFieldDefs[j].ImageData = POut.Bitmap(new Bitmap(img), ImageFormat.Jpeg);
                 }
                 else
                 {
                     sheetDefCur.SheetFieldDefs[j].ImageData = POut.Bitmap(new Bitmap(img), imgFormat);
                 }
             }
             else
             {
                 sheetDefCur.SheetFieldDefs[j].ImageData = "";                      // because null is not allowed
             }
         }
         catch (Exception ex) {
             sheetDefCur.SheetFieldDefs[j].ImageData = "";
             MessageBox.Show(ex.Message);
         }
     }
 }