private static string ReadJournal(IStorageFile executionJournal)
 {
     using (var stream = executionJournal.OpenRead()) {
         using (var streamReader = new StreamReader(stream)) {
             return(streamReader.ReadToEnd());
         }
     }
 }
        /// <summary>
        /// Extract the block model file from the nominated Zip file.  A temp folder is created to store the file
        /// and the path to that file is generated for use when importing.
        /// </summary>
        /// <param name="bmFileName"></param>
        /// <param name="targetFolder"></param>
        /// <param name="attmemptModelLoad"></param>
        /// <returns></returns>
        private string ExtractBlockModelFromZip(string bmFileName, out string targetFolder, out bool attmemptModelLoad)
        {
            IStorageFile bmZipFile = _storageProvider.GetFile(bmFileName);

            targetFolder = bmFileName + "extracted";
            List <string> filesInZip = new List <string>();

            attmemptModelLoad = false;
            if (bmFileName.EndsWith(".zip"))
            {
                Stream bmZipFileStream = bmZipFile.OpenRead();
                // extract file to a temp location
                using (var fileInflater = ZipFile.Read(bmZipFileStream))
                {
                    foreach (ZipEntry entry in fileInflater)
                    {
                        if (entry == null)
                        {
                            continue;
                        }

                        if (!entry.IsDirectory && !string.IsNullOrEmpty(entry.FileName))
                        {
                            // skip disallowed files
                            //if (FileAllowed(entry.FileName, false))
                            // {
                            string fullFileName = _storageProvider.Combine(targetFolder, entry.FileName);
                            filesInZip.Add(fullFileName);
                            using (var stream = entry.OpenReader())
                            {
                                // the call will return false if the file already exists
                                if (!_storageProvider.TrySaveStream(fullFileName, stream))
                                {
                                    // try to delete the file and save again
                                    try
                                    {
                                        _storageProvider.DeleteFile(fullFileName);
                                        _storageProvider.TrySaveStream(fullFileName, stream);
                                    }
                                    catch (ArgumentException)
                                    {
                                        // ignore the exception as the file doesn't exist
                                    }
                                }
                            }
                            //}
                        }
                    }
                }
                bmZipFileStream.Close();
                if (filesInZip.Count() > 0)
                {
                    bmFileName        = filesInZip.First();
                    attmemptModelLoad = true;
                }
            }
            return(bmFileName);
        }
Exemple #3
0
        public FileResult Create(string name, string mediaPath, int width, int height, bool force = false)
        {
            IStorageFile thumbnailFile = _thumbnailsService.CreateThumbnail(mediaPath, name, width, height, force);

            if (thumbnailFile != null)
            {
                return(File(thumbnailFile.OpenRead(), thumbnailFile.GetFileType()));
            }
            return(File(Encoding.UTF8.GetBytes("Invalid media"), "text/plain"));
        }
        public List <string> GetImportFileColumnsAsList(Guid guid, string bmFileName, string modelAlias)
        {
            List <string> columnNames = new List <string>();

            BaseImportTools bit = new BaseImportTools();

            string targetFolder;
            bool   attmemptModelLoad;
            string originalName = bmFileName;

            bmFileName = ExtractBlockModelFromZip(bmFileName, out targetFolder, out attmemptModelLoad);
            IStorageFile bmFile       = _storageProvider.GetFile(bmFileName);
            Stream       bmFileStream = bmFile.OpenRead();

            NKD.Import.FormatSpecification.ImportDataMap idm = null;
            double _originX = -1;
            double _originY = -1;
            double _originZ = -1;

            try
            {
                StreamReader sr            = new StreamReader(bmFileStream);
                string       headerLine    = "";
                string       firstDataLine = "";
                if (sr != null)
                {
                    headerLine    = sr.ReadLine();
                    firstDataLine = sr.ReadLine();

                    bit.ParseDataLinesForOrigins(headerLine, firstDataLine, ',', out _originX, out _originY, out _originZ);
                    // auto generate a format defintion based on Goldfields typical input column data
                    idm = bit.AutoGenerateFormatDefinition(headerLine, ',');
                }
                sr.Close();
            }
            catch
            {
            }

            if (idm != null)
            {
                foreach (ColumnMap cm in idm.columnMap)
                {
                    columnNames.Add(cm.sourceColumnName);
                }
            }
            return(columnNames);
        }
        public void AppendModel(ContentItem c)
        {
            var m = c.As <BlockModelPart>();

            string            statusMessage = "";
            bool              completed     = false;
            BaseImportTools   bit           = new BaseImportTools();
            string            targetFolder;
            bool              attmemptModelLoad;
            var               bmFileName   = ExtractBlockModelFromZip(m.BmFileName, out targetFolder, out attmemptModelLoad);
            IStorageFile      bmFile       = _storageProvider.GetFile(bmFileName);
            Stream            bmFileStream = bmFile.OpenRead();
            ModelImportStatus mos          = new ModelImportStatus();

            try
            {
                // Special append method for GF requirements - contains X, Y, Z, and value to append.
                // target model must have matching X, Y and Z centroids.
                // auto generate a format defintion based on Goldfields typical input column data
                var opts = new TransactionOptions();
                opts.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                using (new TransactionScope(TransactionScopeOption.Suppress, opts))
                {
                    mos = bit.PerformBMAppend(bmFileStream, m.BmGuid, m.Alias, m.ColumnNameToAdd, m.ColumnIndexToAdd, _users.ApplicationConnectionString, ',');
                    mos.importTextFileName = m.BmFileName;
                    mos.targetModelName    = m.Alias;
                }
                statusMessage += string.Format("Successfully appended data to block model:\n{0} - {1}\n\nFrom file:{2}\n\n", m.Alias, m.BmGuid, m.BmFileName);
                completed      = true;
            }
            catch (Exception ex)
            {
                statusMessage += string.Format("Error appending data to block model:\n{0} - {1}\n\nFrom file:{2}\n\nError:\n{3}\n\n", m.Alias, m.BmGuid, m.BmFileName, ex.ToString());
            }
            finally {
                statusMessage += mos.GenerateStringMessage();
                bmFileStream.Close();
                _storageProvider.DeleteFile(bmFileName);
                _storageProvider.DeleteFolder(targetFolder);
            }
            statusMessage += string.Format("Time Elapsed: {0}\n\n", m.Processed.HasValue ? (DateTime.UtcNow - m.Processed.Value).ToString(@"hh\h\:mm\m\:ss\s\:fff\m\s") : "Unknown");

            Logger.Information(statusMessage);

            _users.EmailUsers(m.Recipients.SplitStringArray(), completed ? "Model Append Succeeded" : "Model Append Failed", statusMessage);
        }
        /// <summary>
        /// Import the block model.  This is ultimatly carried out throught he import library which must be
        /// passed the streams for the import file (and defintiion possibly).
        /// </summary>
        /// <param name="bmFileName"></param>
        /// <param name="formatFileName"></param>
        /// <param name="projectID"></param>
        /// <param name="alias"></param>
        /// <param name="authorGuid"></param>
        /// <param name="res2"></param>
        /// <param name="domains"></param>
        /// <param name="targetFolder"></param>
        /// <param name="attmemptModelLoad"></param>
        /// <param name="notes"></param>
        /// <param name="stage"></param>
        /// <returns></returns>
        private ModelImportStatus  DoNewModelImport(string bmFileName, string formatFileName, string projectID, string alias, Guid authorGuid, ref List <string> domains, string targetFolder, bool attmemptModelLoad, string notes, string stage, Guid stageMetaID)
        {
            ModelImportStatus mos = new ModelImportStatus();

            mos.finalErrorCode = ModelImportStatus.OK;
            double          _originX = -1;
            double          _originY = -1;
            double          _originZ = -1;
            BaseImportTools bit      = new BaseImportTools();

            if (attmemptModelLoad)
            {
                //IStorageFile formatFile = _storageProvider.GetFile(formatFileName);
                IStorageFile bmFile           = _storageProvider.GetFile(bmFileName);
                Stream       bmFileStream     = bmFile.OpenRead();
                Stream       bmTempFileStream = bmFile.OpenRead();
                // try and automatically detect the origin coordinates from the file itself - a datamine file
                // always carries the origin coords in XMORIG, YMORIG, ZMORIG

                NKD.Import.FormatSpecification.ImportDataMap idm = null;
                try
                {
                    StreamReader sr            = new StreamReader(bmTempFileStream);
                    string       headerLine    = "";
                    string       firstDataLine = "";
                    if (sr != null)
                    {
                        headerLine    = sr.ReadLine();
                        firstDataLine = sr.ReadLine();
                        bit.ParseDataLinesForOrigins(headerLine, firstDataLine, ',', out _originX, out _originY, out _originZ);
                        // auto generate a format defintion based on Goldfields typical input column data
                        idm = bit.AutoGenerateFormatDefinition(headerLine, ',');
                    }
                    sr.Close();
                }
                catch (Exception ex) {
                    mos.AddWarningMessage("Unable to auto detect origin and other format information from the file\n\n" + ex.ToString());
                }
                var opts = new TransactionOptions();
                opts.IsolationLevel = System.Transactions.IsolationLevel.ReadUncommitted;
                using (new TransactionScope(TransactionScopeOption.Suppress, opts))
                {
                    try
                    {
                        Guid blockModelGUID = Guid.NewGuid();
                        mos.modelID = blockModelGUID;
                        domains     = bit.PerformBMImport(mos, blockModelGUID, bmFileStream, null, idm, _originX, _originY, _originZ, null, 1000, projectID, alias, authorGuid, _users.ApplicationConnectionString);
                        List <Tuple <string, string> > doms = new List <Tuple <string, string> >();
                        string domainColumnName             = "Domain";
                        foreach (string ss in domains)
                        {
                            doms.Add(new Tuple <string, string>(domainColumnName, ss));
                        }
                        UpdateDomains(doms, blockModelGUID);
                        AddModelNotes(notes, blockModelGUID);
                        UpdateStage(blockModelGUID, stageMetaID, stage);
                    }
                    catch (Exception ex)
                    {
                        mos.finalErrorCode = ModelImportStatus.ERROR_WRITING_TO_DB;
                        mos.AddErrorMessage("Error importing block model:\n" + ex.ToString());
                    }
                }

                //TODO call into import library with the stream object for the import

                bmFileStream.Close();
                _storageProvider.DeleteFile(bmFileName);
                _storageProvider.DeleteFolder(targetFolder);
            }
            return(mos);
        }
        /// <summary>
        /// Creates an images thumbnail.
        /// </summary>
        /// <param name="image">The image full path on the media storage.</param>
        /// <param name="thumbnailFolderPath">The media path to thumbnails folder.</param>
        /// <param name="imageName">The image name.</param>
        /// <param name="thumbnailWidth">The thumbnail width in pixels.</param>
        /// <param name="thumbnailHeight">The thumbnail height in pixels.</param>
        /// <param name="keepAspectRatio">Indicates whether to keep the original image aspect ratio</param>
        /// <param name="expandToFill">Indicates whether to expand the thumbnail to fill the bounds specified by width and height</param>
        /// <returns>The thumbnail file media path.</returns>
        protected Thumbnail CreateThumbnail(string image, string thumbnailFolderPath, string imageName, int thumbnailWidth,
                                            int thumbnailHeight, bool keepAspectRatio, bool expandToFill)
        {
            if (thumbnailWidth <= 0)
            {
                throw new ArgumentException("Thumbnail width must be greater than zero", "thumbnailWidth");
            }

            if (thumbnailHeight <= 0)
            {
                throw new ArgumentException("Thumbnail height must be greater than zero", "thumbnailHeight");
            }

            string thumbnailFilePath = _storageProvider.Combine(thumbnailFolderPath, imageName);

            IStorageFile imageFile = _storageProvider.GetFile(image);

            using (Stream imageStream = imageFile.OpenRead()) {
                using (Image drawingImage = Image.FromStream(imageStream))
                {
                    bool shouldCreateImage = true;

                    // Verify if the image already has a Thumbnail
                    var thumbnailName = _mediaService.GetMediaFiles(thumbnailFolderPath)
                                        .Select(o => o.Name).SingleOrDefault(o => o == imageName);

                    if (thumbnailName != null)
                    {
                        // Verify if the existing thumbnail has the correct size (in case the thumbnail settings have been changed)
                        IStorageFile thumbnailFile = _storageProvider.GetFile(thumbnailFilePath);
                        using (Stream thumnailFileStream = thumbnailFile.OpenRead()) {
                            using (Image thumbnailImage = Image.FromStream(thumnailFileStream)) {
                                if (ImageHasCorrectThumbnail(drawingImage, thumbnailImage, thumbnailWidth, thumbnailHeight, keepAspectRatio, expandToFill))
                                {
                                    shouldCreateImage = false;
                                    thumbnailWidth    = thumbnailImage.Width;
                                    thumbnailHeight   = thumbnailImage.Height;
                                }
                            }
                        }
                    }

                    if (shouldCreateImage)
                    {
                        using (Image thumbDrawing = CreateThumbnail(drawingImage, thumbnailWidth, thumbnailHeight, keepAspectRatio, expandToFill)) {
                            if (_storageProvider.ListFiles(thumbnailFolderPath).Select(o => o.GetName()).Contains(imageName))
                            {
                                _storageProvider.DeleteFile(thumbnailFilePath);
                            }

                            IStorageFile thumbFile = _storageProvider.CreateFile(thumbnailFilePath);
                            using (Stream thumbStream = thumbFile.OpenWrite())
                            {
                                thumbDrawing.Save(thumbStream, _thumbnailImageFormat);
                                thumbnailWidth  = thumbDrawing.Width;
                                thumbnailHeight = thumbDrawing.Height;
                            }
                        }
                    }
                }
            }

            string thumbnailPublicUrl = _mediaService.GetMediaPublicUrl(Path.GetDirectoryName(thumbnailFilePath), Path.GetFileName(thumbnailFilePath));

            return(new Thumbnail {
                PublicUrl = thumbnailPublicUrl, Width = thumbnailWidth, Height = thumbnailHeight
            });
        }
 private static string ReadJournal(IStorageFile executionJournal)
 {
     using (var stream = executionJournal.OpenRead()) {
         using (var streamReader = new StreamReader(stream)) {
             return streamReader.ReadToEnd();
         }
     }
 }
Exemple #9
0
        /// <summary>
        /// Compares the content of the photo with old photo.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="content">The content.</param>
        /// <returns></returns>
        private bool CompareFileContent(IStorageFile file, byte[] content)
        {
            if (file == null)
                return false;

            // The byte[] to save the data in
            var bytes = new byte[file.GetSize()];

            // Load a filestream and put its content into the byte[]
            using (Stream fs = file.OpenRead())
            {
                fs.Read(bytes, 0, bytes.Length);
            }

            return content.SequenceEqual(bytes);
        }