Esempio n. 1
0
        public ActionResult DeleteImage(int id)
        {
            string data         = "false";
            var    galleryImage = context.Gallery.Where(c => c.Id == id).FirstOrDefault();

            if (galleryImage != null)
            {
                ImageFiles imgFile = context.ImageFiles.Where(c => c.FileGuid == galleryImage.ImageId).FirstOrDefault();
                if (imgFile != null)
                {
                    if (System.IO.File.Exists(imgFile.FilePath))
                    {
                        System.IO.File.Delete(imgFile.FilePath);
                    }
                    context.Gallery.Remove(galleryImage);
                    context.Entry(galleryImage).State = System.Data.Entity.EntityState.Deleted;
                    context.SaveChanges();

                    context.ImageFiles.Remove(imgFile);
                    context.Entry(imgFile).State = System.Data.Entity.EntityState.Deleted;
                    context.SaveChanges();

                    data = "true";
                }
            }
            return(Json(data, JsonRequestBehavior.AllowGet));
        }
Esempio n. 2
0
        private void openToolStripMenuItem_Click(object sender, EventArgs e)
        {
            var openFile = new OpenFileDialog()
            {
                DefaultExt       = "jpg",
                AddExtension     = true,
                Filter           = "Bitmap files (*.bmp)|*.bmp|Image files (*.jpg)|*.jpg|Image files (*.jpeg)|*.jpeg|Gif files (*.gif)|*.gif|PNG files (*.png)|*.png",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            };

            if (openFile.ShowDialog() == DialogResult.OK)
            {
                PathToOpenFolder = null;
                ImageFiles.Clear();
                PathToFile = openFile.FileName;
            }
            try
            {
                panelBitmap = new Bitmap(panel1.Width - 15, panel1.Height);
                panel1.AutoScrollMinSize = new Size(0, 900);
                var img     = new Bitmap(PathToFile);
                var drawImg = Graphics.FromImage(panelBitmap);
                var imgSize = new Rectangle(0, 0, panel1.Width - 15, (int)(img.Height / (img.Width / (double)(panel1.Width - 15))));
                drawImg.DrawImage(img, imgSize);
                pictureBox1.Image = null;
                pictureBox1.Tag   = null;
                panel1.Refresh();
            }
            catch
            {
            }
        }
Esempio n. 3
0
        public string UplaodFile(string fileName, string fileType, string size)
        {
            string fileReturnGuid = string.Empty;

            using (TransactionScope scope = new TransactionScope())
            {
                Gallery    gal      = new Gallery();
                string     fileGuid = Guid.NewGuid().ToString();
                ImageFiles imgFiles = new ImageFiles();
                imgFiles.ContentType = Path.GetExtension(fileName);
                imgFiles.FileGuid    = fileGuid;
                imgFiles.FileName    = fileName;
                imgFiles.FilePath    = Path.Combine(Server.MapPath("/GalleryImages"), fileGuid + Path.GetExtension(fileName));
                imgFiles.Size        = Convert.ToDecimal(size);

                context.ImageFiles.Add(imgFiles);
                context.SaveChanges();

                gal.ImageId = fileGuid;
                gal.Name    = fileName;
                context.Gallery.Add(gal);
                context.SaveChanges();

                scope.Complete();

                fileReturnGuid = fileGuid + imgFiles.ContentType;
            }
            return(fileReturnGuid);
        }
Esempio n. 4
0
        public ActionResult AddImages(SliderImages sldrImages, IEnumerable <HttpPostedFileBase> files)
        {
            if (files != null)
            {
                CloudiNarySetup cldNSetup = new CloudiNarySetup();
                using (TransactionScope scope = new TransactionScope())
                {
                    foreach (var file in files)
                    {
                        string filePath = cldNSetup.SaveToCloud(file);

                        string     fileGuid = Guid.NewGuid().ToString();
                        ImageFiles imgFiles = new ImageFiles();
                        imgFiles.ContentType = Path.GetExtension(file.FileName);
                        imgFiles.FileGuid    = fileGuid;
                        imgFiles.FileName    = file.FileName;
                        imgFiles.FilePath    = filePath;
                        imgFiles.Size        = file.ContentLength;

                        context.ImageFiles.Add(imgFiles);
                        context.SaveChanges();

                        sldrImages.ImageId     = fileGuid;
                        sldrImages.CreatedDate = DateTime.Now;
                        context.SliderImages.Add(sldrImages);
                        context.SaveChanges();
                    }
                    scope.Complete();
                }
            }
            return(RedirectToAction("Index"));
        }
Esempio n. 5
0
        public ActionResult DeleteImage(int id)
        {
            string strResult   = string.Empty;
            var    sliderImage = context.SliderImages.Where(c => c.SliderImageId == id).FirstOrDefault();

            using (TransactionScope scope = new TransactionScope())
            {
                if (sliderImage != null)
                {
                    ImageFiles imgFile = context.ImageFiles.Where(c => c.FileGuid == sliderImage.ImageId).FirstOrDefault();
                    if (imgFile != null)
                    {
                        if (System.IO.File.Exists(imgFile.FilePath))
                        {
                            System.IO.File.Delete(imgFile.FilePath);
                        }
                        context.SliderImages.Remove(sliderImage);
                        context.Entry(sliderImage).State = System.Data.Entity.EntityState.Deleted;
                        context.SaveChanges();

                        context.ImageFiles.Remove(imgFile);
                        context.Entry(imgFile).State = System.Data.Entity.EntityState.Deleted;
                        context.SaveChanges();
                    }
                }
                scope.Complete();
                strResult = "true";
            }

            return(Json(strResult, JsonRequestBehavior.AllowGet));
        }
Esempio n. 6
0
        public IFormFile CreateFile(IFormFile file)
        {
            var supportedTypes = new[] { "jpg", "jpeg", "png", "tiff" };

            var fileName = System.IO.Path.GetFileName(file.FileName);

            var fileExtension = System.IO.Path.GetExtension(file.FileName).Substring(1);

            using (var stream = new System.IO.MemoryStream())
            {
                file.CopyTo(stream);

                if (!supportedTypes.Contains(fileExtension))
                {
                    throw new NotSupportedException("Unsupported File Format");
                }

                var image = new ImageFiles()
                {
                    FileId    = 0,
                    FileName  = fileName,
                    FileType  = file.ContentType,
                    ImageFile = stream.ToArray(),
                    CreatedOn = DateTime.Now
                };

                _context.ImageFiles.Add(image);
                _context.SaveChanges();
            }

            return(file);
        }
 protected async void OnCancelCommand()
 {
     try
     {
         //dont exit app on sharing
         if ((!SharingProcess) && (ImageFiles == null || ImageFiles?.Count == 0) || (_selectedFiles == null || _selectedFiles?.Count() != 0))
         {
             _applicationService.Exit();
         }
         else
         {
             foreach (var imagefile in ImageFiles)
             {
                 if (imagefile != null)
                 {
                     imagefile.Stream?.Dispose();
                     imagefile.Stream = null;
                 }
             }
             ImageFiles.Clear();
             LastFile?.Stream?.Dispose();
             LastFile = null;
         }
         SharingProcess = false;
         await _localSettings.SaveSettingsAsync();
     }
     catch (Exception e)
     {
         _loggerService?.LogException(nameof(OnCancelCommand), e);
     }
     _loggerService?.LogEvent(nameof(OnCancelCommand));
 }
Esempio n. 8
0
        public ActionResult Create(TreatmentDetails treatmentDetails, HttpPostedFileBase file)
        {
            using (TransactionScope scope = new TransactionScope())
            {
                string     filePath = cldSetup.SaveToCloud(file);
                ImageFiles imgFile  = new ImageFiles();
                string     fileGuid = Guid.NewGuid().ToString();

                imgFile.ContentType = System.IO.Path.GetExtension(file.FileName);
                imgFile.FileName    = System.IO.Path.GetFileName(file.FileName);
                imgFile.FilePath    = filePath;
                imgFile.Size        = file.InputStream.Length;
                imgFile.FileGuid    = fileGuid;

                context.ImageFiles.Add(imgFile);
                context.SaveChanges();

                var maxOrderId = context.TreatmentDetails.Max(c => c.OrderId);
                maxOrderId = maxOrderId == null ? 1 : maxOrderId + 1;
                treatmentDetails.CreatedDate = DateTime.Now;
                treatmentDetails.ImageId     = fileGuid;
                treatmentDetails.OrderId     = maxOrderId;
                context.TreatmentDetails.Add(treatmentDetails);
                context.SaveChanges();
                scope.Complete();
                return(RedirectToAction("Index"));
            }
        }
Esempio n. 9
0
        /// <summary>
        /// Updates the Gallery object with the new imageFiles for the thumbnail.
        /// </summary>
        private static async Task UpdateGalleryThumbnailAsync(Gallery gallery, ImageFiles imageFiles)
        {
            gallery.ThumbnailFiles = imageFiles;
            var replaceResponse = await _galleriesContainer.ReplaceItemAsync(gallery, gallery.Id, new PartitionKey(gallery.CategoryId));

            _log.Information($"LB.PhotoGalleries.Worker.Program.UpdateGalleryThumbnailAsync() - Gallery thumbnail updated. Charge: {replaceResponse.RequestCharge}");
        }
Esempio n. 10
0
        private async Task AssignMissingThumbnailAsync(Gallery gallery)
        {
            // get the first image
            // try and get where position = 0 first
            // if no results, then get where date created is earliest

            var        query           = "SELECT TOP 1 * FROM i WHERE i.GalleryId = @galleryId AND i.Position = 0";
            var        queryDefinition = new QueryDefinition(query).WithParameter("@galleryId", gallery.Id);
            var        imagesContainer = Server.Instance.Database.GetContainer(Constants.ImagesContainerName);
            var        queryResult     = imagesContainer.GetItemQueryIterator <Image>(queryDefinition);
            ImageFiles imageFiles      = null;

            while (queryResult.HasMoreResults)
            {
                var queryResponse = await queryResult.ReadNextAsync();

                Log.Debug($"GalleryServer.AssignMissingThumbnailAsync() - Position query charge: {queryResponse.RequestCharge}. GalleryId: {gallery.Id}");

                foreach (var item in queryResponse.Resource)
                {
                    imageFiles = item.Files;
                    Log.Debug($"GalleryServer.AssignMissingThumbnailAsync() - Got thumbnail image via Position query. GalleryId: {gallery.Id}");
                    break;
                }
            }

            if (imageFiles == null)
            {
                // no position value set on images, get first image created
                query           = "SELECT TOP 1 * FROM i WHERE i.GalleryId = @galleryId ORDER BY i.Created";
                queryDefinition = new QueryDefinition(query).WithParameter("@galleryId", gallery.Id);
                queryResult     = imagesContainer.GetItemQueryIterator <Image>(queryDefinition);

                while (queryResult.HasMoreResults)
                {
                    var queryResponse = await queryResult.ReadNextAsync();

                    Log.Debug($"GalleryServer.AssignMissingThumbnailAsync() - Date query charge: {queryResponse.RequestCharge}. GalleryId: {gallery.Id}");

                    foreach (var item in queryResponse.Resource)
                    {
                        imageFiles = item.Files;
                        Log.Debug($"GalleryServer.AssignMissingThumbnailAsync() - Got thumbnail image via date query. GalleryId: {gallery.Id}");
                        break;
                    }
                }
            }

            if (imageFiles == null)
            {
                Log.Debug($"GalleryServer.AssignMissingThumbnailAsync() - No thumbnail candidate, yet. GalleryId: {gallery.Id}");
                return;
            }

            gallery.ThumbnailFiles = imageFiles;
            await UpdateGalleryAsync(gallery);

            Log.Debug($"GalleryServer.AssignMissingThumbnailAsync() - Gallery updated. GalleryId: {gallery.Id}");
        }
Esempio n. 11
0
 public MainPage()
 {
     this.InitializeComponent();
     this.PageSlider.Maximum = 1;
     this.PageSlider.Minimum = 1;
     imageFiles = ImageFiles.GetInstance();
     CoreWindow.GetForCurrentThread().KeyUp += Window_KeyUp;
 }
        public ActionResult DeleteConfirmed(int id, string photo)
        {
            string directoryToDelete = Server.MapPath(Url.Content("~/Content/Images"));

            ImageFiles.DeleteFile(directoryToDelete, photo);

            menuCategoryRepository.Delete(id);
            return(RedirectToAction("Index"));
        }
Esempio n. 13
0
        public void ProcessSingletonImages(string repository)
        {
            List <ImageFileInfo> singletonFiles = ImageFiles.Where(i => i.Value.Count == 1).SelectMany(i => i.Value).ToList();
            int uniqueNamesCount    = ImageFiles.Count;
            int allFilesCount       = ImageFiles.SelectMany(i => i.Value).Count();
            int singletonFilesCount = singletonFiles.Count;

            if (!System.IO.Directory.Exists(repository))
            {
                System.IO.Directory.CreateDirectory(repository);
            }

            foreach (ImageFileInfo imageFile in singletonFiles)
            {
                string yearDirectory = Path.Combine(repository, $"{imageFile.LikelyDateTime.Year}");

                if (!System.IO.Directory.Exists(yearDirectory))
                {
                    System.IO.Directory.CreateDirectory(yearDirectory);
                }

                string monthDirectory = Path.Combine(yearDirectory, $"{imageFile.LikelyDateTime.Month:D2}");

                if (!System.IO.Directory.Exists(monthDirectory))
                {
                    System.IO.Directory.CreateDirectory(monthDirectory);
                }

                string dayDirectory = Path.Combine(monthDirectory, $"{imageFile.LikelyDateTime.Day:D2}");

                if (!System.IO.Directory.Exists(dayDirectory))
                {
                    System.IO.Directory.CreateDirectory(dayDirectory);
                }

                try
                {
                    File.Copy(imageFile.FileFullPath, Path.Combine(dayDirectory, imageFile.FileName));
                    imageFile.NewFullPath = Path.Combine(dayDirectory, imageFile.FileName);
                    imageFile.IsMoved     = true;
                    imageFile.AsSQLImageFileInfo(_DBOConn).MarkMoved();
                }
                catch (Exception ex)
                {
                    throw;
                }
            }

            GenerateReport($@"E:SingletonPictureReport_{DateTime.Now.ToString("yyyyMMdd_hhmmss")}.csv", singletonFiles, ",");

            foreach (string fileName in singletonFiles.Select(u => u.FileName))
            {
                ImageFiles.Remove(fileName);
            }
        }
Esempio n. 14
0
        public int LoadFromDatabase(FileStatus fileStatus, FileGrouping fileGrouping)
        {
            DataObjects.ImageFileInfoList sqlImageFileInfos = new DataObjects.ImageFileInfoList();

            switch (fileGrouping)
            {
            case FileGrouping.All:
                if (fileStatus == FileStatus.All)
                {
                    sqlImageFileInfos = SQL_ImageFileInfo.GetAll(DBOConn);
                }
                else
                {
                    sqlImageFileInfos = SQL_ImageFileInfo.GetSingletons(fileStatus == FileStatus.Moved, DBOConn);
                    sqlImageFileInfos.AddRange(SQL_ImageFileInfo.GetMultiples(fileStatus == FileStatus.Moved, DBOConn));
                }
                break;

            case FileGrouping.Singleton:
                if (fileStatus == FileStatus.All)
                {
                    sqlImageFileInfos = SQL_ImageFileInfo.GetSingletons(true, DBOConn);
                    sqlImageFileInfos.AddRange(SQL_ImageFileInfo.GetSingletons(false, DBOConn));
                }
                else
                {
                    sqlImageFileInfos = SQL_ImageFileInfo.GetSingletons(fileStatus == FileStatus.Moved, DBOConn);
                }
                break;

            case FileGrouping.Multiple:
                if (fileStatus == FileStatus.All)
                {
                    sqlImageFileInfos = SQL_ImageFileInfo.GetMultiples(true, DBOConn);
                    sqlImageFileInfos.AddRange(SQL_ImageFileInfo.GetMultiples(false, DBOConn));
                }
                else
                {
                    sqlImageFileInfos = SQL_ImageFileInfo.GetMultiples(fileStatus == FileStatus.Moved, DBOConn);
                }
                break;

            default:
                break;
            }

            foreach (DataObjects.ImageFileInfo sqlImageFileInfo in sqlImageFileInfos)
            {
                ImageFileInfo imageFileInfo = sqlImageFileInfo.AsImageFileInfo();

                ImageFiles.AddImageFileInfoToDictionary(imageFileInfo, DBOConn);
            }

            return(ImageFiles.Count);
        }
Esempio n. 15
0
        private void BtnOpenFolder_OnClick(object sender, RoutedEventArgs e)
        {
            var folderBrowserDialog = new FolderBrowserDialog();

            if (folderBrowserDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                TxtFolder.Text = SelectedFolder = folderBrowserDialog.SelectedPath;
                ImageFiles.Clear();
                var imageFiles = MediaFileParser.ReadAllFiles(SelectedFolder);
                imageFiles.ForEach(ImageFiles.Add);
            }
        }
Esempio n. 16
0
        public ImageFiles AddFolder(string name, int parentid)
        {
            var data = new ImageFiles()
            {
                Name     = name,
                IsFolder = true,
                ParentId = parentid,
            };

            this.db.Insert(data);
            return(data);
        }
        public ActionResult Create([Bind(Include = "Id,NameCategory,Comment")] MenuCategory menuCategory, HttpPostedFileBase uploadedFile)
        {
            if (ModelState.IsValid)
            {
                string directory = Server.MapPath(Url.Content("~/Content/Images"));
                menuCategory.Photo = ImageFiles.AddFile(directory, uploadedFile);

                menuCategoryRepository.Add(menuCategory);
                return(RedirectToAction("Index"));
            }
            return(View(menuCategory));
        }
Esempio n. 18
0
 private void UnloadFiles()
 {
     foreach (var item in ImageFiles)
     {
         item.Stream?.Dispose();
         item.Stream = null;
         if (item.Tag is Image img)
         {
             img.Dispose();
         }
     }
     ImageFiles.Clear();
 }
Esempio n. 19
0
        public async Task <IActionResult> Update(ImageFiles img)
        {
            if (!ModelState.IsValid)
            {
                return(View("Edit"));
            }

            db.ImageFiles.Update(img);
            db.SaveChanges();
            List <ImageFiles> images = await db.ImageFiles.ToListAsync();

            return(View("Index", images));
        }
Esempio n. 20
0
        public ImageFiles AddFileByUpload(int parentid)
        {
            var data = new ImageFiles()
            {
                Name     = Session["filename"].ToString(),
                IsFolder = false,
                FileName = Session["filepath"].ToString(),
                ParentId = parentid,
            };

            this.db.Insert(data);
            return(data);
        }
Esempio n. 21
0
        public ActionResult Gallery()
        {
            var galleryImages = context.Gallery.ToList();

            foreach (var item in galleryImages)
            {
                ImageFiles imageFile = context.ImageFiles.Where(c => c.FileGuid == item.ImageId).FirstOrDefault();
                if (imageFile != null)
                {
                    galleryImages.Where(c => c.ImageId == item.ImageId).FirstOrDefault().ImageFiles.FilePath = imageFile.FilePath;
                }
            }
            return(View(galleryImages));
        }
Esempio n. 22
0
 //今の画像番号の画像を表示
 private void ViewImage()
 {
     if (ImageFiles == null || !ImageFiles.Any())
     {
         pbMain.Tag           = "";
         pbMain.ImageLocation = "";
         pbMain.Image         = ImageResource.NoImageInFolder();
     }
     else
     {
         pbMain.Tag           = ImageFiles[ImageNumber];
         pbMain.ImageLocation = ImageFiles[ImageNumber];
     }
     UpdateTitle();
 }
Esempio n. 23
0
        private void OnButtonClick_RemoveSelection(object sender, RoutedEventArgs e)
        {
            if (ActiveSelection < 0)
            {
                return;
            }
            ListBox box = this.listboxImages;// sender as ListBox;

            if (box != null && box.Items.Count > 0)
            {
                ImageFiles.RemoveAt(ActiveSelection);
                box.Items.RemoveAt(ActiveSelection);
                SelectedFile = null;
            }
        }
        public ActionResult Create([Bind(Include = "Id,NameDish,CompositionDish,Weight,Photo,Price,MenuCategoryId")] Dish dish, HttpPostedFileBase uploadedFile)
        {
            if (ModelState.IsValid)
            {
                string directory = Server.MapPath(Url.Content("~/Content/Images"));
                dish.Photo = ImageFiles.AddFile(directory, uploadedFile);

                dishRepository.Add(dish);
                return(RedirectToAction("Index"));
            }

            var menuCategories = menuCategoryRepository.MenuCategories.ToList();

            ViewBag.MenuCategoryId = new SelectList(menuCategories, "Id", "NameCategory", dish.MenuCategoryId);
            return(View(dish));
        }
Esempio n. 25
0
        private void OnFileListChanged(object o, string[] files)
        {
            Application.Current.Dispatcher.BeginInvoke(new System.Action(() =>
            {
                TerminaFiles.Clear();
                foreach (var file in files)
                {
                    TerminaFiles.Add(file);
                }

                ImageFiles.Clear();
                var images = TerminaFiles.Where(x => Path.GetExtension(x) == ".png").ToList();
                images.ForEach(x => ImageFiles.Add(x));
                ImageFile = ImageFiles.FirstOrDefault();
            }));
        }
Esempio n. 26
0
        public ActionResult Gallery()
        {
            var galleryImages = context.Gallery.ToList();

            foreach (var item in galleryImages)
            {
                ImageFiles imageFile = context.ImageFiles.Where(c => c.FileGuid == item.ImageId).FirstOrDefault();
                if (imageFile != null)
                {
                    var imagePath = imageFile.FilePath;
                    imagePath = imagePath.Substring(imagePath.IndexOf("GalleryImages"), imagePath.Length - imagePath.IndexOf("GalleryImages"));
                    imagePath = Properties.Settings.Default.SliderImagePath + imagePath.Replace("\\", "//");
                    galleryImages.Where(c => c.ImageId == item.ImageId).FirstOrDefault().ImageFiles.FilePath = imagePath;
                }
            }
            return(View(galleryImages));
        }
Esempio n. 27
0
        public int AnalyzeFiles(string fileSearchPattern, string rootFolderPath)
        {
            try
            {
                IEnumerable <string> imageFiles = GetFileList(fileSearchPattern, rootFolderPath);

                foreach (string filename in imageFiles)
                {
                    AnalyzeFile(filename);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unexpected error in AnalyzeFiles(): {ex.Message}");
            }

            return(ImageFiles?.Sum(k => k.Value?.Count ?? 0) ?? 0);
        }
 protected void OnDeleteFile(ImageFile param)
 {
     try
     {
         if (ImageFiles != null && param != null)
         {
             ImageFiles.Remove(param);
             _loggerService?.LogEvent(nameof(OnDeleteFile), new Dictionary <string, string>()
             {
                 { nameof(ImageFile), param?.Name }
             });
         }
     }
     catch (Exception e)
     {
         _loggerService?.LogException(nameof(OnDeleteFile), e);
     }
 }
Esempio n. 29
0
        public IActionResult PostImage([FromForm] ImageFiles images)
        {
            try
            {
                if (images.files.Length > 0)
                {
                    if (!Directory.Exists(_environment.WebRootPath + "\\Images\\"))
                    {
                        Directory.CreateDirectory(_environment.WebRootPath + "\\Images\\");
                    }
                    string     newFileName = Guid.NewGuid().ToString() + images.files.FileName;
                    FileStream fileStream  = System.IO.File.Create(_environment.WebRootPath + "\\Images\\" + newFileName);
                    images.files.CopyTo(fileStream);
                    fileStream.Flush();
                    fileStream.Close();

                    Image img = new Image();
                    img.ImageName  = newFileName;
                    img.PhoneRefId = images.phoneId;
                    img.Date       = DateTime.Now;
                    _context.Add(img);
                    try
                    {
                        _context.SaveChanges();
                    }
                    catch (DbUpdateException)
                    {
                        return(BadRequest());
                    }

                    return(Ok("\\Images\\" + newFileName));
                }
                else
                {
                    return(BadRequest("Upload one file at a time"));
                }
            }
            catch (Exception e)
            {
                return(BadRequest(e.Message.ToString()));
            }
        }
Esempio n. 30
0
        public void AddImageFile(ImageFile imageFile)
        {
            if (!CanAddImageFile(imageFile))
            {
                throw new ArgumentException();
            }

            ImageFiles.Add(imageFile);
            SizeInBytes += imageFile.SizeInBytes;

            var drive = imageFile.Path.Substring(0, 2);

            if (!_imageFileCountByDrive.ContainsKey(drive))
            {
                _imageFileCountByDrive[drive] = 0;
            }
            else
            {
                _imageFileCountByDrive[drive] = _imageFileCountByDrive[drive] + 1;
            }
        }
Esempio n. 31
0
        /// <summary>
        /// This is where all of the work is done to extract information from
        /// the phone's binary file. 
        /// It calls methods for image block identification, removal, block hash filtering, field and record level Viterbi infrerence, postprocessing of results.
        /// </summary>
        private void Run()
        {
            bool success = false;
            PostProcessor postProcess = null;
            PhoneInfo phoneInfo = null;
            try
            {
                // Use the SHA1 of the binary file to identify it.
                _canAbort = true;
                StartStep(1);
                write("Calculating file SHA1");
                fileSha1 = DcUtils.CalculateFileSha1(this.filePath);
                if (_cancel) return;
                NextStep(1);
                // We scan the file to locate images. This is done independent
                // of block hashes.
                write("Extracting graphical images");
            #if LOADONLY || SKIPIMAGES
                ImageFiles imageFiles = new ImageFiles();
            #else
                ImageFiles imageFiles = ImageFiles.LocateImages(this.filePath);
                if (_cancel) return;
                _canAbort = false;
                write("Extracted {0} graphical images", imageFiles.ImageBlocks.Count);
            #endif
                NextStep(2);
                if (_cancel) return;
                // Load the block hashes into the DB (if they're not already
                // there).
                HashLoader.HashLoader hashloader = HashLoader.HashLoader.LoadHashesIntoDB(fileSha1, this.filePath, this.manufacturer,
                    this.model, this.note, this.doNotStoreHashes);
                if (_cancel || (hashloader == null)) return;
                int phoneId = hashloader.PhoneId;
            #if LOADONLY
                _cancel = true;
                return;
            #endif
                _canAbort = true;
                NextStep(3);
                if (_cancel) return;
                // Identify block hashes that are already in the DB, which we
                // will then filter out.
                FilterResult filterResult = RunBlockHashFilter(fileSha1, phoneId, hashloader.GetAndForgetStoredHashes());
                hashloader = null;
                NextStep(4);
                // Since images were located before block hash filter, forget
                // about any image that overlaps a filtered block hash.
                write("Filtering image locations");
                //filterResult = ImageFiles.FilterOutImages(filterResult, imageFiles);
                //Dump_Filtered_Blocks(filterResult, filePath);
                NextStep(5);
                // Finally, we're ready to use the Viterbi state machine.
                // Start by identifying fields.
                ViterbiResult viterbiResultFields = RunViterbi(filterResult, fileSha1);
                // Allow garbage collection.
                filterResult.UnfilteredBlocks.Clear();
                NextStep(6);
                List<MetaField> addressBookEntries = new List<MetaField>();
                List<MetaField> callLogs = new List<MetaField>();
                List<MetaField> sms = new List<MetaField>();
                // Second run of Viterbi, this time for records.
                //ViterbiResult viterbiResultRecord = RunMetaViterbi(viterbiResultFields,addressBookEntries,callLogs,sms);
                RunMetaViterbi(viterbiResultFields, addressBookEntries, callLogs, sms);
                viterbiResultFields = null;
                NextStep(7);
                // Perform post processing. This may remove some records.
                postProcess = new PostProcessor(callLogs, addressBookEntries, sms, imageFiles.ImageBlocks);
                success = PerformPostProcessing(postProcess);
                NextStep(8);

                GTC_CSV_Writer wr = new GTC_CSV_Writer(this.metaResults, postProcess, filePath);
                wr.Write_CSV();
                wr.Write_Field_Paths(this.fieldPaths);

                // Finished.
                phoneInfo = new PhoneInfo(manufacturer, model, note, doNotStoreHashes);
                write("Finished work");
                FinishedStep(9);
            }
            finally
            {
                if (_cancel)
                {
                    MainForm.Program.EndWork(false, null, null, null);
                }
                else
                {
                    MainForm.Program.EndWork(success, postProcess, this.filePath, phoneInfo);
                }
            }
        }