/// <summary>
		/// Initializes a new instance of the <see cref= "T:WorldWind.Renderable.GeoSpatialDownloadRequest"/> class.
		/// </summary>
		/// <param name="quadTile"></param>
		public GeoSpatialDownloadRequest(QuadTile quadTile, ImageStore imageStore, string localFilePath, string downloadUrl)
		{
			m_quadTile = quadTile;
			m_url = downloadUrl;
			m_localFilePath = localFilePath;
            m_imageStore = imageStore;
		}
Example #2
0
        private QuadTileSet GetQuadTileSet()
        {
            if (m_layer == null)
            {
                SwitchToUseTiles();

                string strCachePath = GetCachePath();
                System.IO.Directory.CreateDirectory(strCachePath);

                // Determine the needed levels (function of tile size and resolution if available)
                // Shared code in DappleUtils of dapxmlclient
                try
                {
                    if (m_iLevels == 0)
                    {
                        m_iLevels = DappleUtils.Levels(m_oServer.Command, m_hDataSet);
                    }
                }
                catch
                {
                    m_iLevels = 15;
                }

                ImageStore[] imageStores = new ImageStore[1];
                imageStores[0] = new DAPImageStore(m_hDataSet, m_oServer)
                {
                    DataDirectory            = null,
                    LevelZeroTileSizeDegrees = LevelZeroTileSize,
                    LevelCount        = m_iLevels,
                    ImageExtension    = ".png",
                    CacheDirectory    = strCachePath,
                    TextureSizePixels = m_iTextureSizePixels
                };

                m_layer = new QuadTileSet(m_hDataSet.Title, m_oWorldWindow.CurrentWorld, 0, m_hDataSet.Boundary.MaxY, m_hDataSet.Boundary.MinY,
                                          m_hDataSet.Boundary.MinX, m_hDataSet.Boundary.MaxX, true, imageStores)
                {
                    AlwaysRenderBaseTiles = true,
                    IsOn    = m_IsOn,
                    Opacity = m_bOpacity
                };
            }
            return(m_layer);
        }
Example #3
0
        /// <summary>This form will get the necessary images off disk so that it can control layout.</summary>
        public void SetImage(Document thisDocument, string displayTitle)
        {
            //for now, the document is single. Later, it will get groups for composite images/mounts.
            Text         = displayTitle;
            displayedDoc = thisDocument;
            List <long> docNums = new List <long>();

            docNums.Add(thisDocument.DocNum);
            string fileName = (string)Documents.GetPaths(docNums, ImageStore.GetPreferredAtoZpath())[0];

            if (!File.Exists(fileName))
            {
                MessageBox.Show(fileName + " could not be found.");
                return;
            }
            try {
                ImageCurrent = new Bitmap(fileName);
                renderImage  = ImageHelper.ApplyDocumentSettingsToImage(thisDocument, ImageCurrent,
                                                                        //ContrDocs.ApplyDocumentSettingsToImage(thisDocument,ImageCurrent,
                                                                        ImageSettingFlags.CROP | ImageSettingFlags.COLORFUNCTION);
                if (renderImage == null)
                {
                    imageZoom        = 1;
                    imageTranslation = new PointF(0, 0);
                }
                else
                {
                    float matchWidth = PictureBox1.Width - 16;
                    matchWidth = (matchWidth <= 0?1:matchWidth);
                    float matchHeight = PictureBox1.Height - 16;
                    matchHeight      = (matchHeight <= 0?1:matchHeight);
                    imageZoom        = (float)Math.Min(matchWidth / renderImage.Width, matchHeight / renderImage.Height);
                    imageTranslation = new PointF(PictureBox1.Width / 2.0f, PictureBox1.Height / 2.0f);
                }
                zoomLevel  = 0;
                zoomFactor = 1;
            }
            catch (System.Exception exception) {
                MessageBox.Show(Lan.g(this, exception.Message));
                ImageCurrent = null;
                renderImage  = null;
            }
            UpdatePictureBox();
        }
Example #4
0
        ///<summary>Saves the image to A to Z in a new document if the program property to save images is set. Returns null if images are not set to be
        ///saved or if the image already exists.</summary>
        public static Document SaveApteryxImageToDoc(ApteryxImage img, Bitmap saveImage, Patient patCur)
        {
            if (ProgramProperties.GetPropVal(Programs.GetProgramNum(ProgramName.XVWeb), ProgramProps.SaveImages).Trim().ToLower() != "yes" ||
                Documents.DocExternalExists(img.Id.ToString(), ExternalSourceType.XVWeb))                   //if they want to save and it doesn't already exist in DB
            {
                return(null);
            }
            //store the image in the database
            string   imageCat = ProgramProperties.GetPropVal(Programs.GetProgramNum(ProgramName.XVWeb), ProgramProps.ImageCategory);
            Document doc      = ImageStore.Import(saveImage, (Defs.GetDef(DefCat.ImageCats, PIn.Long(imageCat)).DefNum), ImageType.Photo, patCur);

            doc.ToothNumbers   = img.FormattedTeeth;
            doc.DateCreated    = img.AcquisitionDate;
            doc.Description    = doc.ToothNumbers;
            doc.ExternalGUID   = img.Id.ToString();
            doc.ExternalSource = ExternalSourceType.XVWeb;
            Documents.Update(doc);
            return(doc);
        }
        public void Show(long imageId, string imageUrl)
        {
            id = imageId;

            root = new RootElement("Spiffy Dialog View Controller Demo")
            {
                new Section()
                {
                    new MultilineElement(string.Format("This is a Spiffy Dialog View Controller with a cool background. Loaded from {0}", imageUrl))
                }
            };

            imgBG = ImageStore.RequestImage(imageId, imageUrl, this);

            if (imgBG != null)
            {
                ShowMe(root, imgBG);
            }
        }
        public static IActionResult RunHocrGenerator([HttpTrigger(AuthorizationLevel.Function, "post", Route = null)] HttpRequest req, TraceWriter log, ExecutionContext executionContext)
        {
            string skillName = executionContext.FunctionName;
            IEnumerable <WebApiRequestRecord> requestRecords = WebApiSkillHelpers.GetRequestRecords(req);

            if (requestRecords == null || requestRecords.Count() != 1)
            {
                return(new BadRequestObjectResult($"{skillName} - Invalid request record array: Skill requires exactly 1 image per request."));
            }

            var blobStorageConnectionString = GetAppSetting("BlobStorageAccountConnectionString");
            var blobContainerName           = String.IsNullOrEmpty(req.Headers["BlobContainerName"]) ? Config.AZURE_STORAGE_CONTAINER_NAME : (string)req.Headers["BlobContainerName"];

            if (String.IsNullOrEmpty(blobStorageConnectionString) || String.IsNullOrEmpty(blobContainerName))
            {
                return(new BadRequestObjectResult($"{skillName} - Information for the blob storage account is missing"));
            }
            var imageStore   = new ImageStore(blobStorageConnectionString, blobContainerName);
            var expiry       = DateTimeOffset.UtcNow.Add(s_imageBlobSASDuration);
            var imageBlobSAS = imageStore.GetSharedAccessSignature(expiry);

            WebApiSkillResponse response = WebApiSkillHelpers.ProcessRequestRecords(skillName, requestRecords,
                                                                                    (inRecord, outRecord) => {
                List <OcrImageMetadata> imageMetadataList = JsonConvert.DeserializeObject <List <OcrImageMetadata> >(JsonConvert.SerializeObject(inRecord.Data["ocrImageMetadataList"]));
                Dictionary <string, string> annotations   = JsonConvert.DeserializeObject <JArray>(JsonConvert.SerializeObject(inRecord.Data["wordAnnotations"]))
                                                            .Where(o => o.Type != JTokenType.Null)
                                                            .GroupBy(o => o["value"].Value <string>())
                                                            .Select(g => g.First())
                                                            .ToDictionary(o => o["value"].Value <string>(), o => o["description"].Value <string>());

                List <HocrPage> pages = new List <HocrPage>();
                for (int i = 0; i < imageMetadataList.Count; i++)
                {
                    pages.Add(new HocrPage(imageMetadataList[i], i, imageBlobSAS, annotations));
                }
                HocrDocument hocrDocument      = new HocrDocument(pages);
                outRecord.Data["hocrDocument"] = hocrDocument;
                return(outRecord);
            });

            return((ActionResult) new OkObjectResult(response));
        }
        private void FillGrid()
        {
            int curSelection = gridMain.GetSelectedIndex();

            gridMain.BeginUpdate();
            gridMain.ListGridColumns.Clear();
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableLabImage", "Attached"), 60, HorizontalAlignment.Center));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableLabImage", "Date"), 80, HorizontalAlignment.Center));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableLabImage", "Category"), 80, HorizontalAlignment.Center));
            gridMain.ListGridColumns.Add(new GridColumn(Lan.g("TableLabImage", "Desc"), 180, HorizontalAlignment.Left));
            gridMain.ListGridRows.Clear();
            GridRow row;

            for (int i = 0; i < _listPatientDocuments.Count; i++)
            {
                if (_listPatientDocuments[i].DocNum <= 0)                //Invalid doc num indicates 'Waiting for images'. This flag is set in the Load event.
                {
                    continue;
                }
                //Test if this is a valid image.
                Bitmap bmp = ImageStore.OpenImage(_listPatientDocuments[i], _patFolder);
                if (bmp == null)
                {
                    continue;
                }
                bmp.Dispose();
                bmp = null;
                bool isAttached = EhrLabImages.GetDocNumExistsInList(_ehrLabNum, _listPatientDocuments[i].DocNum, _listAttached);
                row = new GridRow();
                row.Cells.Add(isAttached?"X":"");
                row.Cells.Add(_listPatientDocuments[i].DateCreated.ToString());
                row.Cells.Add(Defs.GetName(DefCat.ImageCats, _listPatientDocuments[i].DocCategory));
                row.Cells.Add(_listPatientDocuments[i].Description);
                row.Tag = _listPatientDocuments[i];
                gridMain.ListGridRows.Add(row);
            }
            gridMain.EndUpdate();
            if (curSelection >= 0)
            {
                gridMain.SetSelected(curSelection, true);
            }
        }
        private void ButtonLoadImage_Click(object sender, EventArgs e)
        {
            if (OpenFileDialogImageLoader.ShowDialog() == DialogResult.OK)
            {
                ButtonSaveImage.Enabled = false;
                Quantizer quantizer = GetQuantizer();
                IDitherer ditherer  = GetDitherer();

                ProgressBarQuantization.Value = 0;
                ImagePath      = OpenFileDialogImageLoader.FileName;
                LabelPath.Text = ImagePath;
                var image = new Bitmap(ImagePath);
                PictureBoxLoadedImage.Image = image;

                imageStore = new ImageStore(image, quantizer, ditherer);
                drawer     = GetDrawer(imageStore);
                imageStore.InitFinished += AfterInit;
                drawer.ProgressUpdate   += ProgressUpdate;
            }
        }
Example #9
0
 public bool UpdateImage(ImageModel model)
 {
     try
     {
         var imageStore = new ImageStore();
         var dt         = imageStore.UpdateImage(model);
         if (dt)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #10
0
 public bool ImageChangeStatus(string id, string status)
 {
     try
     {
         var imageStore = new ImageStore();
         var dt         = imageStore.ImageChangeStatus(id, status);
         if (dt)
         {
             return(true);
         }
         else
         {
             return(false);
         }
     }
     catch (Exception)
     {
         return(false);
     }
 }
Example #11
0
 public void RefreshData(Patient pat, SheetField sheetField)
 {
     if (pat == null ||
         PrefC.AtoZfolderUsed == DataStorageType.InDatabase)              //Do not use patient image when A to Z folders are disabled.
     {
         return;
     }
     try{
         _docPatPicture = Documents.GetByNum(PIn.Long(sheetField.FieldValue), true);
         //GetFullImage applies cropping/transposing/etc...
         Bitmap fullImage = ImageHelper.GetFullImage(_docPatPicture, ImageStore.GetPatientFolder(pat, ImageStore.GetPreferredAtoZpath()));
         SwapPatPicture(() => ImageHelper.GetThumbnail(fullImage, Math.Min(sheetField.Width, sheetField.Height)));
         fullImage.Dispose();
     }
     catch (Exception e) {
         e.DoNothing();
         _patPicture?.Dispose();
         _patPicture = null;              //Something went wrong retrieving the image.  Default to "Patient Picture Unavailable".
     }
 }
Example #12
0
        public void UploadImages()
        {
            List <Stream> files = new List <Stream>();

            foreach (string filename in Request.Files)
            {
                files.Add(Request.Files[filename].InputStream);
                //HttpPostedFileBase hpf = Request.Files[filename] as HttpPostedFileBase;
                //using (var binaryReader = new BinaryReader(Request.Files[filename].InputStream))
                //{
                //    files.Add(new Files { FileStream = binaryReader.ReadBytes(Request.Files[filename].ContentLength), Name = filename });
                //}
            }
            ImageStore _store = new ImageStore();

            if (files.Count > 0)
            {
                _store.SaveImage(files);
            }
        }
Example #13
0
        private QuadTileSet GetQuadTileSet()
        {
            if (m_layer == null)
            {
                ImageStore[] imageStores = new ImageStore[1];
                imageStores[0] = new DAPImageStore(null, m_oServer);
                imageStores[0].DataDirectory            = null;
                imageStores[0].LevelZeroTileSizeDegrees = 22.5;
                imageStores[0].LevelCount        = 10;
                imageStores[0].ImageExtension    = ".png";
                imageStores[0].CacheDirectory    = GetCachePath();
                imageStores[0].TextureSizePixels = 256;

                m_layer = new QuadTileSet(this.Title, m_oWorldWindow.CurrentWorld, 0, m_oServer.ServerExtents.MaxY, m_oServer.ServerExtents.MinY, m_oServer.ServerExtents.MinX, m_oServer.ServerExtents.MaxX, true, imageStores);
                m_layer.AlwaysRenderBaseTiles = true;
                m_layer.IsOn    = m_IsOn;
                m_layer.Opacity = m_bOpacity;
            }
            return(m_layer);
        }
Example #14
0
        private void butSave_Click(object sender, EventArgs e)
        {
            long defNumToothCharts = Defs.GetImageCat(ImageCategorySpecial.T);

            if (defNumToothCharts == 0)
            {
                MsgBox.Show(this, "In Setup, Definitions, Image Categories, a category needs to be set for graphical tooth charts.");
                return;
            }
            Bitmap   bitmap = null;
            Graphics g      = null;
            Document doc    = new Document();

            bitmap = new Bitmap(750, 1000);
            g      = Graphics.FromImage(bitmap);
            g.Clear(Color.White);
            g.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            g.SmoothingMode      = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            RenderPerioPrintout(g, _patCur, new Rectangle(0, 0, bitmap.Width, bitmap.Height));
            try {
                ImageStore.Import(bitmap, defNumToothCharts, ImageType.Photo, _patCur);
            }
            catch (Exception ex) {
                MessageBox.Show(Lan.g(this, "Unable to save file: ") + ex.Message);
                bitmap.Dispose();
                bitmap = null;
                g.Dispose();
                return;
            }
            MsgBox.Show(this, "Saved.");
            if (g != null)
            {
                g.Dispose();
                g = null;
            }
            if (bitmap != null)
            {
                bitmap.Dispose();
                bitmap = null;
            }
        }
Example #15
0
 private void SaveSignature()
 {
     if (SigChanged)
     {
         //This check short-circuits so that sigBoxTopaz.Visible will not be checked in MONO ever.
         if (Environment.OSVersion.Platform != PlatformID.Unix && sigBoxTopaz.Visible)
         {
             DocCur.SigIsTopaz = true;
             if (sigBoxTopaz.NumberOfTabletPoints() == 0)
             {
                 DocCur.Signature = "";
                 return;
             }
             sigBoxTopaz.SetSigCompressionMode(0);
             sigBoxTopaz.SetEncryptionMode(0);
             sigBoxTopaz.SetKeyString(ImageStore.GetHashString(DocCur, PatFolder));
             //"0000000000000000");
             //sigBoxTopaz.SetAutoKeyData(ProcCur.Note+ProcCur.UserNum.ToString());
             sigBoxTopaz.SetEncryptionMode(2);
             sigBoxTopaz.SetSigCompressionMode(2);
             DocCur.Signature = sigBoxTopaz.GetSigString();
         }
         else
         {
             DocCur.SigIsTopaz = false;
             if (sigBox.NumberOfTabletPoints() == 0)
             {
                 DocCur.Signature = "";
                 return;
             }
             //sigBox.SetSigCompressionMode(0);
             //sigBox.SetEncryptionMode(0);
             sigBox.SetKeyString(ImageStore.GetHashString(DocCur, PatFolder));
             //"0000000000000000");
             //sigBox.SetAutoKeyData(ProcCur.Note+ProcCur.UserNum.ToString());
             //sigBox.SetEncryptionMode(2);
             //sigBox.SetSigCompressionMode(2);
             DocCur.Signature = sigBox.GetSigString();
         }
     }
 }
Example #16
0
        public void DeleteBlobImage(string blobid)
        {
            //var id = Request.Form["id"];
            Stream stream = null;

            if (Request.Files.Count != 0)
            {
                stream = Request.Files[0].InputStream;
            }

            ImageStore _store = new ImageStore();

            if (blobid != null && stream == null)
            {
                _store.DeleteUpdateBlobImage(blobid, IOActions.Delete.ToString(), null);
            }
            else if (blobid != null && stream != null)
            {
                _store.DeleteUpdateBlobImage(blobid, IOActions.Update.ToString(), stream);
            }
        }
Example #17
0
        public async Task <IActionResult> CreateDeck([FromForm] CreationDeckDto dto)
        {
            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            var user = (await GetCurrentUser()) !;

            var dbo = mapper.Map(dto, new DeckDbo
            {
                Author = user
            });

            dbo.ImagePath = await ImageStore.SaveImage(dto.Image?.OpenReadStream(),
                                                       '.' + dto.Image?.FileName.Split('.')[1]);

            dbo = await deckRepo.AddAsync(dbo);

            return(CreatedAtRoute(nameof(GetDeckById), new { deckId = dbo.Id }, mapper.Map <DeckDbo, DeckResult>(dbo)));
        }
Example #18
0
        public async Task <IActionResult> UpdateImage([FromRoute] Guid deckId, [FromRoute] Guid cardId,
                                                      [Models.Validation.FileExtensions("jpg", "jpeg", "png")]
                                                      IFormFile?image)
        {
            if (!ModelState.IsValid)
            {
                return(UnprocessableEntity(ModelState));
            }

            var deck = await deckRepo.FindAsync(deckId);

            if (deck is null)
            {
                return(NotFound());
            }

            var card = deck.Cards.Find(cardDbo => cardDbo.Id == cardId);

            if (card is null)
            {
                return(NotFound());
            }

            if (image is null)
            {
                ImageStore.RemoveImage(card.ImagePath?.Split('/').Last());
                card.ImagePath = null;
            }
            else
            {
                var oldPath = card.ImagePath;
                card.ImagePath = await ImageStore.SaveImage(image.OpenReadStream(), '.' + image.FileName.Split('.')[1]);

                ImageStore.RemoveImage(oldPath?.Split('/').Last());
            }

            await cardRepo.UpdateAsync(card);

            return(NoContent());
        }
 public void CreateImageForItem(ItemModelview model)
 {
     using (var ImageStorerepo = new ImageStoreService())
     {
         int count = 0;
         // from the website
         if (model.ImageFile != null)
         {
             foreach (var file in model.ImageFile)
             {
                 byte[]       imgbyte = null;
                 BinaryReader reader  = new BinaryReader(file.InputStream);
                 imgbyte = reader.ReadBytes(file.ContentLength);
                 ImageStore img = new ImageStore
                 {
                     imgId    = model.ItemRef + count,
                     UserName = model.UserName,
                     ItemName = model.ItemName,
                     date     = DateTime.Now,
                     imgByte  = imgbyte
                 };
                 ImageStorerepo.Insert(img);
                 count++;
             }
         }
         // from app
         else
         {
             ImageStore img = new ImageStore
             {
                 imgId    = model.ItemRef + count,
                 UserName = model.UserName,
                 ItemName = model.ItemName,
                 date     = DateTime.Now,
                 imgByte  = model.src
             };
             ImageStorerepo.Insert(img);
         }
     }
 }
        void CreateImages(string searchTerm)
        {
            ImageStore.ClearCache();

            int            i    = 1;
            RootElement    root = new RootElement(searchTerm + " Results");
            SpiffyViewDemo svd;

            if (!string.IsNullOrEmpty(searchTerm))
            {
                foreach (string result in SearchImages(searchTerm, 1, 100, false))
                {
                    long   imageId  = i;
                    string imageUrl = result;

                    UIFont fTest = new UIFont();

                    UrlImageStringElement element = new UrlImageStringElement(result, i, result);

                    element.Tapped += delegate
                    {
                        svd = new SpiffyViewDemo(navigation);
                        svd.Show(imageId, imageUrl);
                    };

                    root.Add(new Section {
                        element
                    });

                    i++;
                }
            }

            DialogViewController dvc = new DialogViewController(root, true)
            {
                Autorotate = true
            };

            navigation.PushViewController(dvc, true);
        }
Example #21
0
 ///<summary></summary>
 public void FormDocInfo_Load(object sender, System.EventArgs e)
 {
     //if (Docs.Cur.FileName.Equals(null))
     listCategory.Items.Clear();
     for (int i = 0; i < DefC.Short[(int)DefCat.ImageCats].Length; i++)
     {
         string folderName = DefC.Short[(int)DefCat.ImageCats][i].ItemName;
         listCategory.Items.Add(folderName);
         if (i == 0 || DefC.Short[(int)DefCat.ImageCats][i].DefNum == DocCur.DocCategory || folderName == initialSelection)
         {
             listCategory.SelectedIndex = i;
         }
     }
     listType.Items.Clear();
     listType.Items.AddRange(Enum.GetNames(typeof(ImageType)));
     listType.SelectedIndex = (int)DocCur.ImgType;
     textToothNumbers.Text  = Tooth.FormatRangeForDisplay(DocCur.ToothNumbers);
     textDate.Text          = DocCur.DateCreated.ToString("d");
     textDescript.Text      = DocCur.Description;
     if (PrefC.AtoZfolderUsed)
     {
         string patFolder = ImageStore.GetPatientFolder(PatCur, ImageStore.GetPreferredAtoZpath());
         textFileName.Text = ODFileUtils.CombinePaths(patFolder, DocCur.FileName);
         if (File.Exists(textFileName.Text))
         {
             FileInfo fileInfo = new FileInfo(textFileName.Text);
             textSize.Text = fileInfo.Length.ToString("n0");
         }
     }
     else
     {
         labelFileName.Visible = false;
         textFileName.Visible  = false;
         butOpen.Visible       = false;
         textSize.Text         = DocCur.RawBase64.Length.ToString("n0");
     }
     textToothNumbers.Text = Tooth.FormatRangeForDisplay(DocCur.ToothNumbers);
     //textNote.Text=DocCur.Note;
 }
Example #22
0
        internal override RenderableObject GetLayer()
        {
            if (m_blnIsChanged)
            {
                ImageStore[] aImageStore = new ImageStore[1];
                aImageStore[0] = new ArcIMSImageStore(m_szServiceName, m_szLayerID, m_oServerUri as ArcIMSServerUri, TileSize, m_oCultureInfo, m_dMinScale, m_dMaxScale);
                aImageStore[0].DataDirectory            = null;
                aImageStore[0].LevelZeroTileSizeDegrees = LevelZeroTileSize;
                aImageStore[0].LevelCount     = m_iLevels;
                aImageStore[0].ImageExtension = ".png";
                aImageStore[0].CacheDirectory = GetCachePath();

                m_oQuadTileSet = new QuadTileSet(m_szTreeNodeText, m_oWorldWindow.CurrentWorld, 0,
                                                 Extents.North, Extents.South, Extents.West, Extents.East,
                                                 true, aImageStore);
                m_oQuadTileSet.AlwaysRenderBaseTiles = true;
                m_oQuadTileSet.IsOn    = m_IsOn;
                m_oQuadTileSet.Opacity = m_bOpacity;
                m_blnIsChanged         = false;
            }
            return(m_oQuadTileSet);
        }
Example #23
0
        ///<summary>This is a stupid place for this, but keeping it around because it's used from many places.</summary>
        public static string GetAttachPath()
        {
            string attachPath;

            if (PrefC.UsingAtoZfolder)
            {
                attachPath = ODFileUtils.CombinePaths(ImageStore.GetPreferredAtoZpath(), "EmailAttachments");
                if (!Directory.Exists(attachPath))
                {
                    Directory.CreateDirectory(attachPath);
                }
            }
            else
            {
                //For users which have the A to Z folders disabled, there is no defined image path, so we
                //have to use another path. Since we have chosen the temporary directory, this means that
                //email attachements for a particular email may or may not be viewable later (i.e. in case
                //someone cleaned out their temporary files to conserve disk space).
                attachPath = Path.GetTempPath();
            }
            return(attachPath);
        }
		///<summary>Accepts a list of MimeEntity and parses it for paths, htmls and other key factors. It will test that the resulting parts
		///have a valid image extension. If they do, they are saved to a temporary web page for presentation to the user. If they are not
		///then they are disreguarded an a message is sent to the user warning them of potentially malicious content.</summary>
		private string ParseAndSaveAttachement(string htmlFolderPath,string html,List<MimeEntity> listParts) {
				bool hasDangerousAttachment=false;
				foreach(MimeEntity entity in listParts) {
					string contentId=EmailMessages.GetMimeImageContentId(entity);
					string fileName=EmailMessages.GetMimeImageFileName(entity);
					//Only show image types.  Otherwise, prompt user that potentially dangerous code is attached to the email and will not be shown.
					if(!ImageStore.HasImageExtension(fileName)) {//Check file format against known image format extensions.
						hasDangerousAttachment=true;
						continue;
					}
					html=html.Replace("cid:"+contentId,fileName);
					EmailAttach attachment=_listEmailAttachDisplayed.FirstOrDefault(x => x.DisplayedFileName.ToLower().Trim()==fileName.ToLower().Trim());
					//The path and filename must be directly accessed from the EmailAttach object in question, otherwise subsequent code would have accessed
					//an empty bodied message and never shown an image.
					EmailMessages.SaveMimeImageToFile(entity,htmlFolderPath,attachment?.ActualFileName);
				}
				if(hasDangerousAttachment) {
					//Since the extension is not within the image formats it may contain mallware and we will not parse or present it.
					MsgBox.Show("This message contains some elements that may not be safe and will not be loaded.");
				}
				return html;
		}
        /// <summary>
        /// Find the drawer selected in the combobox
        /// </summary>
        /// <param name="imageStore">the imagestore the drawer will be drawing</param>
        /// <returns>the requested drawer</returns>
        private Drawer GetDrawer(ImageStore imageStore)
        {
            Drawer drawer;

            if (ComboBoxDrawerSelection.SelectedIndex == 0)
            {
                drawer = new SimpleDrawer(imageStore);
            }
            else if (ComboBoxDrawerSelection.SelectedIndex == 1)
            {
                drawer = new SynchronousDitheredDrawer(imageStore);
            }
            else if (ComboBoxDrawerSelection.SelectedIndex == 2)
            {
                drawer = new AsynchronousDitheredDrawer(imageStore);
            }
            else
            {
                throw new Exception("Invalid Drawer option!");
            }
            return(drawer);
        }
Example #26
0
        private void Image_Click()
        {
            //Store the images in their own a-z folder and retrieve them from there.
            string emailFolder = "";

            try {
                emailFolder = ImageStore.GetEmailImagePath();              //will create the folder if it doesn't exist already.
            }
            catch (Exception ex) {
                FriendlyException.Show(Lans.g(this, "Unable to find Email Images folder"), ex);
                return;
            }
            FormImagePicker FormIP = new FormImagePicker(emailFolder);

            FormIP.ShowDialog();
            if (FormIP.DialogResult != DialogResult.OK)
            {
                return;
            }
            textContentEmail.SelectionLength = 0;
            textContentEmail.SelectedText    = "[[img:" + FormIP.SelectedImageName + "]]";
        }
Example #27
0
        public TextureSource(string url, string cacheLocation, ImageStore imageStore, PriorityCallback priorityCallback)
        {
//            if (s_inQueueTexture == null)
//                InitStaticTextures();

            // convert cache location to dds
//            string ddsCache = Path.GetDirectoryName(cacheLocation)+"\\"+Path.GetFileNameWithoutExtension(cacheLocation) + ".dds";
            m_drd = new DataRequestDescriptor(url, cacheLocation, new CacheCallback(CacheCallback));
            m_drd.CompletionCallback = new CompletionCallback(CompletionCallback);
            m_drd.PriorityCallback   = priorityCallback;

            m_imageStore = imageStore;

            if (m_settings == null)
            {
                // get the World Wind Settings through reflection.
                Assembly a       = Assembly.GetEntryAssembly();
                Type     appType = a.GetType("WorldWind.MainApplication");
                System.Reflection.FieldInfo finfo = appType.GetField("Settings", BindingFlags.Static | BindingFlags.Public | BindingFlags.GetField);
                m_settings = finfo.GetValue(null) as WorldWindSettings;
            }
        }
        //Clear the user image disk cache if userid is found in clear list and is within ClientCacheExpiration time.
        private bool ClearDiskImageCacheIfNecessary(int userId, int portalId, string cacheId)
        {
            var cacheKey = string.Format(DataCache.UserIdListToClearDiskImageCacheKey, portalId);
            Dictionary <int, DateTime> userIds;

            if ((userIds = DataCache.GetCache <Dictionary <int, DateTime> >(cacheKey)) == null || !userIds.ContainsKey(userId))
            {
                return(false);
            }
            ImageStore.ForcePurgeFromServerCache(cacheId);
            DateTime expiry;

            //The clear mechanism is performed for ClientCacheExpiration timespan so that all active clients clears the cache and don't see old data.
            if (!userIds.TryGetValue(userId, out expiry) || DateTime.UtcNow <= expiry.Add(ClientCacheExpiration))
            {
                return(true);
            }
            //Remove the userId from the clear list when timespan is > ClientCacheExpiration.
            userIds.Remove(userId);
            DataCache.SetCache(cacheKey, userIds);
            return(true);
        }
Example #29
0
 private void gridMain_CellClick(object sender, ODGridClickEventArgs e)
 {
     //Determine if it's a folder or a file that was clicked
     //If a folder, do nothing
     //If a file, download a thumbnail and display it
     if (ImageStore.HasImageExtension(gridMain.ListGridRows[gridMain.GetSelectedIndex()].Cells[0].Text))
     {
         try {
             //Place thumbnail within odPictureox to display
             OpenDentalCloud.Core.TaskStateThumbnail state = CloudStorage.GetThumbnail(textPath.Text, gridMain.ListGridRows[gridMain.GetSelectedIndex()].Cells[0].Text);
             if (state == null || state.FileContent == null || state.FileContent.Length < 2)
             {
                 labelThumbnail.Visible = true;
                 odPictureBox.Visible   = false;
             }
             else
             {
                 labelThumbnail.Visible = false;
                 odPictureBox.Visible   = true;
                 using (MemoryStream stream = new MemoryStream(state.FileContent)) {
                     _thumbnail = new Bitmap(Image.FromStream(stream));
                 }
                 odPictureBox.Image = _thumbnail;
                 odPictureBox.Invalidate();
             }
         }
         catch (Exception ex) {
             labelThumbnail.Visible = false;
             odPictureBox.Visible   = false;
             ex.DoNothing();
         }
     }
     else
     {
         labelThumbnail.Visible = false;
         odPictureBox.Visible   = false;
     }
 }
        private void buttonAddImage_Click(object sender, EventArgs e)
        {
            string         patFolder  = ImageStore.GetPatientFolder(_claimPat, ImageStore.GetPreferredAtoZpath());
            OpenFileDialog fileDialog = new OpenFileDialog();

            fileDialog.Multiselect      = false;
            fileDialog.InitialDirectory = patFolder;
            if (fileDialog.ShowDialog() != DialogResult.OK)
            {
                return;
            }
            //The filename property is the entire path of the file.
            string selectedFile = fileDialog.FileName;

            if (selectedFile.EndsWith(".pdf"))
            {
                MessageBox.Show(this, "DentalXChange does not support PDF attachments.");
                return;
            }
            //There is purposely no validation that the user selected an image as that will be handled on Dentalxchange's end.
            Image image;

            try {
                image = Image.FromFile(selectedFile);
                ShowImageAttachmentItemEdit(image);
            }
            catch (System.IO.FileNotFoundException ex) {
                FriendlyException.Show(Lan.g(this, "The selected file at: " + selectedFile + " could not be found"), ex);
            }
            catch (System.OutOfMemoryException ex) {
                //Image.FromFile() will throw an OOM exception when the image format is invalid or not supported.
                //See MSDN if you have trust issues:  https://msdn.microsoft.com/en-us/library/stf701f5(v=vs.110).aspx
                FriendlyException.Show(Lan.g(this, "The file does not have a valid image format. Please try again or call support." + "\r\n" + ex.Message), ex);
            }
            catch (Exception ex) {
                FriendlyException.Show(Lan.g(this, "An error occurred. Please try again or call support.") + "\r\n" + ex.Message, ex);
            }
        }
Example #31
0
        private void butShowHL7_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            List <string[]> listFileNamesDateMod = new List <string[]>();

            for (int i = 0; i < ListMedLabs.Count; i++)
            {
                string filePath    = ODFileUtils.CombinePaths(ImageStore.GetPreferredAtoZpath(), ListMedLabs[i].FileName);
                bool   isFileAdded = false;
                for (int j = 0; j < listFileNamesDateMod.Count; j++)
                {
                    if (listFileNamesDateMod[j][0] == filePath)
                    {
                        isFileAdded = true;
                        break;
                    }
                }
                if (isFileAdded)
                {
                    continue;
                }
                string dateModified = DateTime.MinValue.ToString();
                try {
                    dateModified = File.GetLastWriteTime(filePath).ToString();
                }
                catch (Exception ex) {
                    ex.DoNothing();
                    //dateModified will be min value, do nothing?
                }
                listFileNamesDateMod.Add(new string[] { filePath, dateModified });
            }
            FormMedLabHL7MsgText FormMsgText = new FormMedLabHL7MsgText();

            FormMsgText.ListFileNamesDatesMod = listFileNamesDateMod;
            Cursor = Cursors.Default;
            FormMsgText.ShowDialog();
        }
Example #32
0
        /// <summary>
        /// Initializes a new instance of the <see cref= "T:WorldWind.Renderable.QuadTileSet"/> class.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentWorld"></param>
        /// <param name="distanceAboveSurface"></param>
        /// <param name="north"></param>
        /// <param name="south"></param>
        /// <param name="west"></param>
        /// <param name="east"></param>
        /// <param name="terrainAccessor"></param>
        /// <param name="imageAccessor"></param>
        public QuadTileSet(string name, World parentWorld, double distanceAboveSurface, double north, double south, double west, double east, bool terrainMapped, ImageStore imageStore)
            : base(name, parentWorld)
        {
            float layerRadius = (float) (parentWorld.EquatorialRadius + distanceAboveSurface);
            m_north = north;
            m_south = south;
            m_west = west;
            m_east = east;

            // Layer center position
            Position = MathEngine.SphericalToCartesian((north + south)*0.5f, (west + east)*0.5f, layerRadius);

            m_layerRadius = layerRadius;
            m_tileDrawDistance = 3.5f;
            m_tileDrawSpread = 2.9f;
            m_imageStore = imageStore;
            m_terrainMapped = terrainMapped;

            // Default terrain mapped imagery to terrain mapped priority
            if (terrainMapped) {
                m_renderPriority = RenderPriority.TerrainMappedImages;
            }
        }
Example #33
0
        private static void addQuadTileLayersFromXPathNodeIterator(XPathNodeIterator iter, World parentWorld, RenderableObjectList parentRenderable, Cache cache)
        {
            if (iter.Count > 0) {
                while (iter.MoveNext()) {
                    string name = getInnerTextFromFirstChild(iter.Current.Select("Name"));
                    double distanceAboveSurface = ParseDouble(getInnerTextFromFirstChild(iter.Current.Select("DistanceAboveSurface")));
                    bool showAtStartup = ParseBool(iter.Current.GetAttribute("ShowAtStartup", ""));

                    double north = 0;
                    double south = 0;
                    double west = 0;
                    double east = 0;

                    XPathNodeIterator boundingBoxIter = iter.Current.Select("BoundingBox");
                    if (boundingBoxIter.Count > 0) {
                        boundingBoxIter.MoveNext();
                        north = ParseDouble(getInnerTextFromFirstChild(boundingBoxIter.Current.Select("North")));
                        south = ParseDouble(getInnerTextFromFirstChild(boundingBoxIter.Current.Select("South")));
                        west = ParseDouble(getInnerTextFromFirstChild(boundingBoxIter.Current.Select("West")));
                        east = ParseDouble(getInnerTextFromFirstChild(boundingBoxIter.Current.Select("East")));
                    }

                    string terrainMappedString = getInnerTextFromFirstChild(iter.Current.Select("TerrainMapped"));
                    string renderStrutsString = getInnerTextFromFirstChild(iter.Current.Select("RenderStruts"));

                    bool terrainMapped = true;

                    if (terrainMappedString != null) {
                        terrainMapped = ParseBool(terrainMappedString);
                    }
                    XPathNodeIterator imageAccessorIter = iter.Current.Select("ImageAccessor");

                    QuadTileSet qts = null;

                    byte opacity = 255;

                    if (imageAccessorIter.Count > 0) {
                        imageAccessorIter.MoveNext();
                        double levelZeroTileSizeDegrees = ParseDouble(getInnerTextFromFirstChild(imageAccessorIter.Current.Select("LevelZeroTileSizeDegrees")));
                        int numberLevels = Int32.Parse(getInnerTextFromFirstChild(imageAccessorIter.Current.Select("NumberLevels")));
                        int textureSizePixels = Int32.Parse(getInnerTextFromFirstChild(imageAccessorIter.Current.Select("TextureSizePixels")));
                        string imageFileExtension = getInnerTextFromFirstChild(imageAccessorIter.Current.Select("ImageFileExtension"));
                        string permanentDirectory = getInnerTextFromFirstChild(imageAccessorIter.Current.Select("PermanentDirectory"));
                        if (permanentDirectory == null
                            || permanentDirectory.Length == 0) {
                            permanentDirectory = getInnerTextFromFirstChild(imageAccessorIter.Current.Select("PermanantDirectory"));
                        }

                        TimeSpan dataExpiration = getCacheExpiration(imageAccessorIter.Current.Select("DataExpirationTime"));

                        string duplicateTilePath = getInnerTextFromFirstChild(imageAccessorIter.Current.Select("DuplicateTilePath"));
                        string cacheDir = getInnerTextFromFirstChild(imageAccessorIter.Current.Select("CacheDirectory"));

                        if (cacheDir == null
                            || cacheDir.Length == 0) {
                            cacheDir = String.Format("{0}{1}{2}{1}{3}", cache.CacheDirectory, Path.DirectorySeparatorChar, getRenderablePathString(parentRenderable), name);
                        }
                        else {
                            cacheDir = Path.Combine(cache.CacheDirectory, cacheDir);
                        }

                        if (permanentDirectory != null
                            && permanentDirectory.IndexOf(":") < 0) {
                            permanentDirectory = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), permanentDirectory);
                        }

                        if (duplicateTilePath != null
                            && duplicateTilePath.IndexOf(":") < 0) {
                            duplicateTilePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), duplicateTilePath);
                        }

                        if (permanentDirectory != null) {
                            ImageStore ia = new ImageStore();
                            ia.DataDirectory = permanentDirectory;
                            ia.LevelZeroTileSizeDegrees = levelZeroTileSizeDegrees;
                            ia.LevelCount = numberLevels;
                            ia.ImageExtension = imageFileExtension;
                            //doesn't work when this is set
                            //ia.CacheDirectory = cacheDir;

                            if (duplicateTilePath != null
                                && duplicateTilePath.Length > 0) {
                                ia.DuplicateTexturePath = duplicateTilePath;
                            }

                            //	ia.DataExpirationTime = dataExpiration;

                            qts = new QuadTileSet(name, parentWorld, distanceAboveSurface, north, south, west, east, terrainMapped, ia);
                        }
                        else {
                            XPathNodeIterator imageTileServiceIter = imageAccessorIter.Current.Select("ImageTileService");
                            if (imageTileServiceIter.Count > 0) {
                                imageTileServiceIter.MoveNext();

                                string serverUrl = getInnerTextFromFirstChild(imageTileServiceIter.Current.Select("ServerUrl"));
                                string dataSetName = getInnerTextFromFirstChild(imageTileServiceIter.Current.Select("DataSetName"));
                                string serverLogoFilePath = getInnerTextFromFirstChild(imageTileServiceIter.Current.Select("ServerLogoFilePath"));

                                TimeSpan cacheExpiration = getCacheExpiration(imageTileServiceIter.Current.Select("CacheExpirationTime"));

                                if (serverLogoFilePath != null && serverLogoFilePath.Length > 0
                                    && !Path.IsPathRooted(serverLogoFilePath)) {
                                    serverLogoFilePath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), serverLogoFilePath);
                                }

                                string opacityString = getInnerTextFromFirstChild(imageTileServiceIter.Current.Select("Opacity"));

                                if (opacityString != null) {
                                    opacity = byte.Parse(opacityString);
                                }

                                ImageStore ia = new NltImageStore(dataSetName, serverUrl);
                                ia.DataDirectory = null;
                                ia.LevelZeroTileSizeDegrees = levelZeroTileSizeDegrees;
                                ia.LevelCount = numberLevels;
                                ia.ImageExtension = imageFileExtension;
                                ia.CacheDirectory = cacheDir;

                                //if(newImageTileService.CacheExpirationTime == TimeSpan.MaxValue)
                                //	{
                                //	ia.DataExpirationTime = dataExpiration;
                                //	}
                                //	else
                                //	{
                                //	ia.DataExpirationTime = newImageTileService.CacheExpirationTime;
                                //	}

                                qts = new QuadTileSet(name, parentWorld, distanceAboveSurface, north, south, west, east, terrainMapped, ia);

                                qts.Opacity = opacity;
                                if (serverLogoFilePath != null) {
                                    qts.ServerLogoFilePath = serverLogoFilePath;
                                }
                            }
                            else {
                                XPathNodeIterator wmsAccessorIter = imageAccessorIter.Current.Select("WMSAccessor");
                                if (wmsAccessorIter.Count > 0) {
                                    wmsAccessorIter.MoveNext();

                                    WmsImageStore wmsLayerStore = new WmsImageStore();

                                    wmsLayerStore.ImageFormat = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("ImageFormat"));

                                    wmsLayerStore.ImageExtension = imageFileExtension;
                                    wmsLayerStore.CacheDirectory = cacheDir;
                                    //wmsLayerAccessor.IsTransparent = ParseBool(getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("UseTransparency")));
                                    wmsLayerStore.ServerGetMapUrl = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("ServerGetMapUrl"));
                                    wmsLayerStore.Version = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("Version"));
                                    wmsLayerStore.WMSLayerName = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("WMSLayerName"));

                                    string username = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("Username"));
                                    string password = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("Password"));
                                    string wmsStyleName = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("WMSLayerStyle"));
                                    string serverLogoPath = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("ServerLogoFilePath"));
                                    string opacityString = getInnerTextFromFirstChild(wmsAccessorIter.Current.Select("Opacity"));

                                    if (serverLogoPath != null && serverLogoPath.Length > 0
                                        && !Path.IsPathRooted(serverLogoPath)) {
                                        serverLogoPath = Path.Combine(Path.GetDirectoryName(Application.ExecutablePath), serverLogoPath);
                                    }
                                    if (opacityString != null) {
                                        opacity = byte.Parse(opacityString);
                                    }

                                    TimeSpan cacheExpiration = getCacheExpiration(iter.Current.Select("CacheExpirationTime"));

                                    //	if(username != null && username.Length > 0)
                                    //		wmsLayerStore.Username = username;

                                    //	if(password != null)
                                    //		wmsLayerAccessor.Password = password;

                                    if (wmsStyleName != null
                                        && wmsStyleName.Length > 0) {
                                        wmsLayerStore.WMSLayerStyle = wmsStyleName;
                                    }
                                    else {
                                        wmsLayerStore.WMSLayerStyle = "";
                                    }

                                    wmsLayerStore.LevelCount = numberLevels;
                                    wmsLayerStore.LevelZeroTileSizeDegrees = levelZeroTileSizeDegrees;

                                    //	if(cacheExpiration == TimeSpan.MaxValue)
                                    //		imageAccessor.DataExpirationTime = dataExpiration;
                                    //	else
                                    //		imageAccessor.DataExpirationTime = cacheExpiration;

                                    if (wmsLayerStore != null) {
                                        qts = new QuadTileSet(name, parentWorld, distanceAboveSurface, north, south, west, east, terrainMapped, wmsLayerStore);

                                        qts.Opacity = opacity;
                                        if (serverLogoPath != null) {
                                            qts.ServerLogoFilePath = serverLogoPath;
                                        }
                                    }
                                }
                            }
                        }

                        if (qts != null) {
                            string infoUri = iter.Current.GetAttribute("InfoUri", "");

                            if (infoUri != null
                                && infoUri.Length > 0) {
                                if (qts.MetaData.Contains("InfoUri")) {
                                    qts.MetaData["InfoUri"] = infoUri;
                                }
                                else {
                                    qts.MetaData.Add("InfoUri", infoUri);
                                }
                            }

                            if (iter.Current.Select("TransparentColor").Count > 0) {
                                Color c = getColor(iter.Current.Select("TransparentColor"));
                                qts.ColorKey = c.ToArgb();
                            }

                            if (iter.Current.Select("TransparentMinValue").Count > 0) {
                                qts.ColorKey = int.Parse(getInnerTextFromFirstChild(iter.Current.Select("TransparentMinValue")));
                            }

                            if (iter.Current.Select("TransparentMaxValue").Count > 0) {
                                qts.ColorKeyMax = int.Parse(getInnerTextFromFirstChild(iter.Current.Select("TransparentMaxValue")));
                            }

                            if (renderStrutsString != null) {
                                qts.RenderStruts = ParseBool(renderStrutsString);
                            }

                            qts.ParentList = parentRenderable;
                            if (World.Settings.useDefaultLayerStates) {
                                qts.IsOn = showAtStartup;
                            }
                            else {
                                qts.IsOn = IsLayerOn(qts);
                            }

                            qts.MetaData.Add("XmlSource", (string) parentRenderable.MetaData["XmlSource"]);
                            addExtendedInformation(iter.Current.Select("ExtendedInformation"), qts);
                            parentRenderable.Add(qts);
                        }
                    }
                }
            }
        }