Пример #1
0
        private void BatchFileButton_Click(object sender, RoutedEventArgs e)
        {
            // show message box warns user about options selected such as: make new name or skip, ...

            foreach (var filename in OldNameFiles)
            {
                // each filename
                string newFilename = filename.Value;
                filename.BatchState    = "Success";
                filename.FailedActions = "Failed Actions List:\n";
                bool isSuccess = true;

                foreach (var action in _actions)
                {
                    try
                    {
                        newFilename = action.ActionProcess(newFilename, true);
                    }
                    catch (Exception ex)
                    {
                        isSuccess = false;
                        filename.FailedActions += action.Description + "\n";
                    }
                }
                filename.NewFilename = newFilename;
                NewFileName.Add(newFilename);

                if (!isSuccess)
                {
                    filename.BatchState = "Fail";
                }
            }
        }
Пример #2
0
        public static void SetNewFileName()
        {
            //파일 경로가 있을때.
            if (!string.IsNullOrEmpty(FIleManager.FilePath))
            {
                string path = FIleManager.FilePath.Substring(0, FilePath.LastIndexOf('\\') + 1);
                //새로운파일 이름 입력 안했을 때.
                if (string.IsNullOrEmpty(FIleManager.NewFileName))
                {
                    string newName = FilePath.Substring(FilePath.LastIndexOf('\\') + 1, FileName.Split('.')[0].Length) + @".json";
                    NewFileName = path + newName;
                }

                //입력 했을 때.
                else
                {
                    if (NewFileName.Contains(".json"))
                    {
                        //json입력.
                        NewFileName = path + NewFileName;
                    }
                    else
                    {
                        NewFileName = path + NewFileName + @".json";
                    }
                }
            }
        }
 public NewFileWindow()
 {
     InitializeComponent();
     CurrentPointNumber = 0;
     NewFileName.Focus();
     NewFileName.SelectAll();
     CoordsList = new List <SharpKml.Base.Vector>();
     NewKmlFile = new Kml();
 }
Пример #4
0
 /// <summary>
 /// Serves as a hash function for a particular type.
 /// </summary>
 /// <returns>
 /// A hash code for the current <see cref="T:System.Object"/>.
 /// </returns>
 /// <filterpriority>2</filterpriority>
 public override int GetHashCode()
 {
     unchecked {
         int hashCode = (int)FirstState;
         hashCode = (hashCode * 397) ^ (int)SecondState;
         hashCode = (hashCode * 397) ^ (FileName != null ? FileName.GetHashCode() : 0);
         hashCode = (hashCode * 397) ^ (NewFileName != null ? NewFileName.GetHashCode() : 0);
         return(hashCode);
     }
 }
Пример #5
0
    private void trimPreviousName()
    {
        this.OriginalFileName = (this.GridViewRowSelected.FindControl("ltlFileItem") as Literal).Text;
        this.Prefix           = OriginalFileName.Substring(0, 3);
        this.NewFileName      = OriginalFileName.Substring(0, OriginalFileName.Length - 4);
        int ingnoreMe = 0;

        if (int.TryParse(Prefix.Substring(0, 2), out ingnoreMe))
        {
            this.NewFileName = NewFileName.Substring(3);
        }
    }
Пример #6
0
 private void NewFileName_Click(object sender, EventArgs e)
 {
     if (sender.Equals(LabNewFileName))
     {
         NewFileName.Focus();
     }
     //elseif(sender.Equals(labelPwd))
     //{
     //   PwdTxt.Focus();
     //   //PwdTxt.PasswordChar = '*';
     //}
 }
Пример #7
0
        protected override void Execute(CodeActivityContext context)
        {
            //retrieve the parameters from the Context
            string oldFilePath     = OldFilePath.Get(context);
            string newFileName     = NewFileName.Get(context);
            string directoryToSave = DirectoryToSave.Get(context);

            //convert and set result
            string resultingFilePath = Utils.ConvertWord(oldFilePath, newFileName, directoryToSave, FileTypes.PDFExtension,
                                                         Word.WdSaveFormat.wdFormatPDF);

            ResultingFilePath.Set(context, resultingFilePath);
        }
        protected override void Execute(CodeActivityContext context)
        {
            //retrieve the parameters from the Context
            string oldFilePath     = OldFilePath.Get(context);
            string newFileName     = NewFileName.Get(context);
            string directoryToSave = DirectoryToSave.Get(context);

            //convert and set result
            string resultingFilePath = Utils.ConvertExcel(oldFilePath, newFileName, directoryToSave, FileTypes.NewExcel,
                                                          Microsoft.Office.Interop.Excel.XlFileFormat.xlOpenXMLWorkbook);

            ResultingFilePath.Set(context, resultingFilePath);
        }
Пример #9
0
        /// <summary>
        /// Finds and sets song artist, sets determines song title then returns if artist was identified.
        /// </summary>
        /// <returns></returns>
        private void setSongInfo()
        {
            string s1, s2;

            if (NewFileName.Contains('-'))
            {
                //Dividing character between artist and song title.
                int div = NewFileName.IndexOf("-");

                //Split filename into artist and song name, lower and trim string.
                s1 = NewFileName.Substring(0, div).ToLower().Trim();
                s2 = NewFileName.Substring(div + 1, NewFileName.Length - (div + 1)).ToLower().Trim();

                //If substring 1 contains a matching artist set filename with artist first.
                if (LibraryManager.checkArtist(s1))
                {
                    Artist      = StringUtils.formatText(s1);
                    Title       = StringUtils.formatText(s2);
                    NewFileName = Artist + " - " + Title;

                    artistFound = true;
                }
                //If substring 2 contains a matching artist set filename with artist first.
                else if (LibraryManager.checkArtist(s2))
                {
                    Artist      = StringUtils.formatText(s2);
                    Title       = StringUtils.formatText(s1);
                    NewFileName = Artist + " - " + Title;

                    artistFound = true;
                }
                else
                {
                    Artist      = StringUtils.formatText(s1);
                    Title       = StringUtils.formatText(s2);
                    NewFileName = Artist + " - " + Title;
                }
            }
        }
Пример #10
0
        public static void ReArrangeFiles(string FilePath, bool isMovedFromFolder)
        {
            // To Get All Files In Directory
            string[] files = Directory.GetFiles(FilePath);
            string   NewFileName; // declare varible will hold a new name of the file
            int      filenum;     //holds the file number to move it to the first of the name

            //loop through each file in directory
            foreach (var file in files)
            {
                /*
                 * General Case of the file name will be like this  Folder Name - File Name -mXX-XX .mp4
                 * mXX will represent folder name or set of releated files , -XX the file number in series
                 * here we take the file name from the full path and without extension '.*'
                 */
                NewFileName = file.Substring(file.LastIndexOf(@"\") + 1, file.LastIndexOf('.') - file.LastIndexOf(@"\") - 1);
                //Remove the folder name from downloaded file
                NewFileName = NewFileName.Substring(NewFileName.IndexOf('-') + 1);
                //Chek if the file moved from folder to Remove mxx from file name
                if (!isMovedFromFolder)
                {
                    // copy file number and move it to the beggining of the file name
                    NewFileName = NewFileName.Substring(NewFileName.LastIndexOf('m')) + "- " + NewFileName;
                }
                else
                {
                    // copy file number and move it to the beggining of the file name without mxx
                    NewFileName = NewFileName.Substring(NewFileName.LastIndexOf('-') + 1) + "- " + NewFileName;
                }
                //remove the file name from the end of file
                NewFileName = NewFileName.Remove(NewFileName.LastIndexOf('m') - 1);

                //In C# we can move cause we don't have rename , replace old path with new path and new file name and add extension
                File.Move(file, Path.GetDirectoryName(file) + @"\" + NewFileName + ".mp4");
            }
        }
Пример #11
0
        private void TraverseDirectoryTree(string root)
        {
            StreamWriter MetadataTable = null;
            StreamWriter CountsTable = null;
            int          errorCount = 0, copyCount = 0, deleteCount = 0, extractCount = 0, tableCount = 0;

            lostTagCount = 0;
            Stack <string> dirs  = new Stack <string>(100);
            List <string>  files = new List <string>();

            //Acquisition
            if (!Directory.Exists(root))
            {
                throw new ArgumentException("Specified root directory doesn't exist: " + root);
            }
            dirs.Push(root);
            while (dirs.Count > 0)
            {
                string currentDir = dirs.Pop();

                string[] subDirs;
                try { subDirs = Directory.GetDirectories(currentDir); }
                catch (UnauthorizedAccessException) { continue; }
                catch (DirectoryNotFoundException) { continue; }
                foreach (string str in subDirs)
                {
                    dirs.Push(str);
                }                                                                               // Push subdirectories on stack for traversal.

                string[] DICOMFiles = null;
                try { DICOMFiles = Directory.GetFiles(currentDir, "*.dcm"); }
                catch (UnauthorizedAccessException) { continue; }
                catch (DirectoryNotFoundException) { continue; }
                foreach (string file in DICOMFiles)
                {
                    files.Add(file);
                }
            }             // while dirs.Count > 0

            //Processing; could technically be split off into a separate fuuuuunctionnnnnn
            //but i don't give a shit
            bool DoSimpleParse = !(checkBoxCreateMetadataTable.Checked || checkBoxExtractMetadata.Checked);

            List <StudyObject> StudyFiles = new List <StudyObject>();

            int maxFiles = files.Count;

            for (int i = 0; i < maxFiles; i++)
            {
                float progress = ((float)(i + 1) / maxFiles);
                labelProgressBar.Text       = string.Format("Processing file {0} of {1} ({2:p0})", i + 1, maxFiles, progress);
                progressBarDICOMFiles.Value = (int)Math.Floor(progress * 100);
                Application.DoEvents();                 //keeps GUI alive by returning control to OS thread

                string     DICOMFile = files[i];
                string     NewFolderName, NewFileName, StudyTime, PatientName, StudyDate, PatientID;
                int        nFrames;
                DICOM.File dcf = null;
                try
                {                 //Take and open file, extract metadata
                    dcf         = new DICOM.File(DICOMFile, DoSimpleParse);
                    PatientName = TagValueOrDefault(0x00100010, dcf.Tags);
                    PatientID   = TagValueOrDefault(0x00100020, dcf.Tags);
                    StudyDate   = TagValueOrDefault(0x00080023, dcf.Tags);
                    StudyTime   = TagValueOrDefault(0x00080033, dcf.Tags);
                    if (!DoSimpleParse)
                    {
                        nFrames = int.Parse(TagValueOrDefault(0x00280008, dcf.Tags, "1"));
                    }
                    else
                    {
                        nFrames = ((new FileInfo(DICOMFile).Length / 1024) > 811) ? 125 : 1;
                    }                                                                                                 //single-image files are always 811KB big, so 811 * 1024 bytes; 125 frames is max and an assumption...

                    switch (comboBoxCopyMode.SelectedIndex)
                    {
                    case 0:                             //Both
                        break;

                    case 1:                             //Images only
                        if (nFrames > 1)
                        {
                            continue;
                        }
                        break;

                    case 2:                             //Videos only
                        if (nFrames < 2)
                        {
                            continue;
                        }
                        break;
                    }

                    NewFolderName = string.Format("{0}_{1}_{2}", StudyDate, PatientID, PatientName);
                    foreach (char c in InvalidPathChars)
                    {
                        NewFolderName = NewFolderName.Replace(c.ToString(), "");
                    }                                                                                                                     //sanitize path input
                    foreach (char c in new char[] { '/', '\\', '?' })
                    {
                        NewFolderName = NewFolderName.Replace(c.ToString(), "-");
                    }                                                                                                                                   //these aren't in InvalidPathChars since they're allowed in (full) paths
                    if (comboBoxExportMode.SelectedIndex == 1)
                    {
                        NewFolderName = PatientID.ToLowerInvariant() + Path.DirectorySeparatorChar + NewFolderName;
                    }
                    if (comboBoxExportMode.SelectedIndex == 2)
                    {
                        NewFolderName = "";
                    }            //no subfolders
                }                // try
                catch (FileNotFoundException) { errorCount++; continue; }

                if (checkBoxExportPerStudyCounts.Checked || checkBoxCreateMetadataTable.Checked)
                {
                    StudyObject obj         = new StudyObject();
                    string[]    FolderSplit = DICOMFile.Split(Path.DirectorySeparatorChar);
                    obj.Folder      = string.Join(Path.DirectorySeparatorChar.ToString(), FolderSplit.Take(FolderSplit.Length - 1));
                    obj.File        = FolderSplit.Skip(FolderSplit.Length - 1).ToArray()[0];
                    obj.PatientID   = PatientID;
                    obj.PatientName = PatientName;
                    obj.StudyDate   = StudyDate;
                    obj.StudyTime   = StudyTime;
                    obj.nFrames     = (short)nFrames;
                    obj.NewFolder   = NewFolderName;
                    StudyFiles.Add(obj);
                }

                DirectoryInfo OutputFolder = new DirectoryInfo(Path.Combine(textBoxOutputDirectory.Text, NewFolderName));
                if (checkBoxCopyAndRename.Checked || checkBoxExtractMetadata.Checked)
                {
                    //prepare receiving folder
                    if (!Directory.Exists(OutputFolder.FullName))
                    {
                        try { Directory.CreateDirectory(OutputFolder.FullName); }
                        catch (UnauthorizedAccessException)
                        {
                            MessageBox.Show("Cannot gain access to " + textBoxOutputDirectory.Text + ". Please select another directory or run as administrator.");
                            return;
                        }
                    }                    //if FolderName doesn't exist
                }

                if (checkBoxCopyAndRename.Checked)
                {
                    //Ensure numbering is consistent and continuous
                    int nPictures = 1, nVideos = 1;
                    //HACK to ensure Image/Video numbers are study-specific even if no subfolders are being used - previous code searched *.dcm responding to ALL files from ALL studies
                    string searchStr = string.Format("{0}_*_{1}_*.dcm", StudyDate, PatientID, PatientName);
                    foreach (char c in new char[] { '/', '\\', '?' })
                    {
                        searchStr = searchStr.Replace(c.ToString(), "-");
                    }                                                                                                                           //these are invalid as f**k for files
                    foreach (char c in InvalidFileChars)
                    {
                        searchStr.Replace(c.ToString(), "");
                    }
                    FileInfo[] ExistingFiles = OutputFolder.GetFiles(searchStr);

                    nPictures  += ExistingFiles.Where(n => n.Name.Contains("Image")).Count();
                    nVideos    += ExistingFiles.Where(n => n.Name.Contains("Video")).Count();
                    NewFileName = string.Format("{0}_{1}_{2}_{3}_{4}.dcm", StudyDate, StudyTime, PatientID, PatientName, (nFrames > 1 ? ("Video" + nVideos) : ("Image" + nPictures)));
                    foreach (char c in new char[] { '/', '\\', '?' })
                    {
                        NewFileName = NewFileName.Replace(c.ToString(), "-");
                    }                                                                                                                               //these are invalid as f**k for files
                    foreach (char c in InvalidFileChars)
                    {
                        NewFileName.Replace(c.ToString(), "");
                    }

                    //Copy File, Test File, if there's a request, Delete File
                    string NewFilePath = Path.Combine(OutputFolder.FullName, NewFileName);
                    if (File.Exists(NewFilePath))
                    {                     //Need to change name not to overwrite; safety first
                        int fileCount = OutputFolder.GetFiles(Path.GetFileNameWithoutExtension(NewFileName) + "*").Length + 1;
                        NewFileName = string.Format("{0}({1}){2}", Path.GetFileNameWithoutExtension(NewFileName), fileCount, Path.GetExtension(NewFileName));
                        NewFilePath = Path.Combine(OutputFolder.FullName, NewFileName);
                    }                     //File.Exists(NewFilePath)

                    try
                    {
                        File.Copy(DICOMFile, NewFilePath);
                        copyCount++;
                    }
                    catch (UnauthorizedAccessException) { MessageBox.Show("Access denied for export directory. Please select another directory or restart as administrator."); return; }
                    catch (IOException ioe) { MessageBox.Show("Unexpected IO Exception: " + ioe.Message); }

                    if (checkBoxCheckAndDeleteAfterCopy.Checked)
                    {
                        if (TestFileEquality(new FileInfo(DICOMFile), new FileInfo(NewFilePath)))
                        {
                            File.Delete(DICOMFile);
                            deleteCount++;
                        }
                    }            //checkBoxCheckAndDeleteAfterCopy.Checked
                }                //if checkboxCopyAndRename.Checked

                if (checkBoxExtractMetadata.Checked)
                {
                    using (StreamWriter metadataFile = new StreamWriter(Path.Combine(OutputFolder.FullName, "metadata.txt"), true))
                    {
                        metadataFile.WriteLine("Metadata extracted from " + DICOMFile + "\nTag\tValue");
                        foreach (DICOM.Tag tag in dcf.Tags)
                        {
                            metadataFile.WriteLine(tag.Name + "\t" + tag.Value);
                        }                                                                                                                    //TODO something fucky here.
                        metadataFile.WriteLine("\n");
                        extractCount++;
                    }
                }        //if checkboxExtractMetadata.Checked
            }            //foreach DICOMFile

            if (checkBoxCreateMetadataTable.Checked)
            {
                MetadataTable = new StreamWriter(Path.Combine(textBoxOutputDirectory.Text, DateTime.Now.ToString("yyyy-MM-dd_HH-mm") + "_DICOMFilesMetadata-Table.txt"), false);
                MetadataTable.WriteLine("Filename\tPatient ID\tPatient Name\tStudy Date\tStudy Time\tData Type\tFrames");
                foreach (var obj in StudyFiles)
                {
                    MetadataTable.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}\t{4}\t{5}\t{6}", Path.Combine(obj.Folder, obj.File), obj.PatientID, obj.PatientName, obj.StudyDate, obj.StudyTime, (obj.nFrames > 1 ? "Movie" : "Image"), obj.nFrames));
                    tableCount++;
                }
                MetadataTable.Flush();
                MetadataTable.Close();
            }

            if (checkBoxExportPerStudyCounts.Checked)
            {
                HashSet <string> DataFolders = new HashSet <string>(StudyFiles.Select(x => x.Folder));

                CountsTable = new StreamWriter(Path.Combine(textBoxOutputDirectory.Text, DateTime.Now.ToString("yyyy-MM-dd_HH-mm") + "_DICOMFiles-DataPerStudyTable.txt"), false);
                CountsTable.WriteLine("Full Path\tStudy\tImages\tVideos");
                foreach (var DataFolder in DataFolders)
                {
                    HashSet <string> Studies = new HashSet <string>(StudyFiles.Where(x => x.Folder == DataFolder).Select(x => x.NewFolder));
                    foreach (var Study in Studies)
                    {
                        IEnumerable <StudyObject> Members = StudyFiles.Where(x => (x.NewFolder == Study && x.Folder == DataFolder));
                        CountsTable.WriteLine(string.Format("{0}\t{1}\t{2}\t{3}", DataFolder, Study, Members.Count(y => y.nFrames <= 1), Members.Count(y => y.nFrames > 1)));
                    }
                }
                CountsTable.Flush();
                CountsTable.Close();
            }

            //Generating success message to user
            string Report        = "Operation(s) completed successfully\n";
            string LostTagReport = lostTagCount > 0 ? lostTagCount + " values could not found and defaulted to 'undefined'.\n" : "";

            if (checkBoxCopyAndRename.Checked)
            {
                Report += copyCount + " files copied and renamed. " + LostTagReport;
            }
            if (checkBoxCheckAndDeleteAfterCopy.Checked)
            {
                Report += deleteCount + " files deleted.\n";
            }
            if (checkBoxExtractMetadata.Checked)
            {
                Report += "Metadata extracted for " + extractCount + " files. " + LostTagReport;
            }
            if (checkBoxCreateMetadataTable.Checked)
            {
                Report += tableCount + " files processed for metadata table. " + LostTagReport;
            }
            progressBarDICOMFiles.Value = 100;
            Application.DoEvents();
            MessageBox.Show(Report, "DICOM processing complete.");
        }         // TraverseDirectoryTree
Пример #12
0
        public async Task CopyBlobInSameStorageAccountAsync()
        {
            var cloudBlocks    = 0;
            var cloudDirectory = 0;
            var cloudPages     = 0;
            var noDots         = 0;
            var notePages      = 0;

            try
            {
                BlobContinuationToken token = null;
                do
                {
                    var watchAllBlobsSelection      = Stopwatch.StartNew();
                    BlobResultSegment resultSegment = await _azureStorage.Container.ListBlobsSegmentedAsync(token);

                    watchAllBlobsSelection.Stop();
                    var elapsedMs = watchAllBlobsSelection.ElapsedMilliseconds;
                    _logger.LogInformation($"Gettting all blobs elapsed time (ms): {elapsedMs}");
                    token = resultSegment.ContinuationToken;

                    var watchCopyingBlobs = Stopwatch.StartNew();
                    foreach (IListBlobItem item in resultSegment.Results)
                    {
                        if (item.GetType() == typeof(CloudBlockBlob))
                        {
                            cloudBlocks++;
                            CloudBlockBlob blob = (CloudBlockBlob)item;

                            NewFileName FileName = GetBlobDetails(blob);

                            if (FileName.ApplicantId.Contains("NotePage"))
                            {
                                notePages++;
                                continue;
                            }

                            if (!ApplicantIds.Contains(FileName.ApplicantId))
                            {
                                ApplicantIds.Add(FileName.ApplicantId);
                                Console.WriteLine($"Creating directory: {FileName.ApplicantId}");
                                _logger.LogInformation($"Directory created for applicant: {FileName.ApplicantId}");
                            }
                            var previousDocumentLocation = _azureStorage.Container.GetBlockBlobReference($"{blob.Name}");
                            var newDocumentLocation      = _azureStorage.Container.GetBlockBlobReference($"{FileName.ApplicantId}/{FileName.FileName}");
                            try
                            {
                                await newDocumentLocation.StartCopyAsync(previousDocumentLocation);
                            }
                            catch (Exception e)
                            {
                                _logger.LogError(e.Message);
                                throw;
                            }
                            Log.Logger.Information($"Moved {previousDocumentLocation.Name} to {newDocumentLocation.Name}");
                        }
                        else if (item.GetType() == typeof(CloudBlobDirectory))
                        {
                            CloudBlobDirectory directory = (CloudBlobDirectory)item;
                            Console.WriteLine($"Skipping existing directory: {directory.Uri}");
                            cloudDirectory++;

                            /* Delete blobs in directory
                             * await DeleteBlobsInDirectory(directory);
                             * continue;
                             */
                        }
                        else if (item.GetType() == typeof(CloudPageBlob))
                        {
                            CloudPageBlob pageBlob = (CloudPageBlob)item;
                            Console.WriteLine($"We are not using pageBlobs: {pageBlob}");
                            cloudPages++;
                        }
                    }
                    watchCopyingBlobs.Stop();

                    /* Only run this if you want to create records to be processed.
                     * await CreateNBlobsOf500KbAsync(1200);
                     */
                    /*
                     */
                    _logger.LogInformation($"Copying blobs elapsed time(ms): {watchCopyingBlobs.ElapsedMilliseconds}");
                } while (token != null);
                _logger.LogInformation($"Cloud Blobs: {cloudBlocks}");
                _logger.LogInformation($"Cloud Directory: {cloudDirectory}");
                _logger.LogInformation($"No Dots: {noDots}");
                _logger.LogInformation($"Note Pages: {notePages}");
                _logger.LogInformation("Finished with the Script.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #13
0
        public async Task CountBlobsDirectoriesAndPages()
        {
            var cloudBlocks    = 0;
            var cloudDirectory = 0;
            var cloudPages     = 0;
            var noDots         = 0;
            var notePages      = 0;

            try
            {
                BlobContinuationToken token = null;
                do
                {
                    var watchAllBlobsSelection      = Stopwatch.StartNew();
                    BlobResultSegment resultSegment = await _azureStorage.Container.ListBlobsSegmentedAsync(token);

                    watchAllBlobsSelection.Stop();
                    var elapsedMs = watchAllBlobsSelection.ElapsedMilliseconds;
                    _logger.LogInformation($"Gettting all blobs elapsed time (ms): {elapsedMs}");
                    token = resultSegment.ContinuationToken;

                    var watchCopyingBlobs = Stopwatch.StartNew();
                    foreach (IListBlobItem item in resultSegment.Results)
                    {
                        if (item.GetType() == typeof(CloudBlockBlob))
                        {
                            CloudBlockBlob blob = (CloudBlockBlob)item;
                            if (blob.Name.Contains("."))
                            {
                                NewFileName FileName = GetBlobDetails(blob);
                                if (FileName.ApplicantId.Contains("NotePage"))
                                {
                                    notePages++;
                                    continue;
                                }
                            }
                            else
                            {
                                noDots++;
                            }

                            cloudBlocks++;
                        }
                        else if (item.GetType() == typeof(CloudBlobDirectory))
                        {
                            cloudDirectory++;
                        }
                        else if (item.GetType() == typeof(CloudPageBlob))
                        {
                            cloudPages++;
                        }
                    }
                    watchCopyingBlobs.Stop();

                    /* Only run this if you want to create records to be processed.
                     * await CreateNBlobsOf500KbAsync(1200);
                     */
                    /*
                     */
                    _logger.LogInformation($"Copying blobs elapsed time(ms): {watchCopyingBlobs.ElapsedMilliseconds}");
                } while (token != null);
                _logger.LogInformation($"Cloud Blobs: {cloudBlocks}");
                _logger.LogInformation($"Cloud Directory: {cloudDirectory}");
                _logger.LogInformation($"No Dots: {noDots}");
                _logger.LogInformation($"Note Pages: {notePages}");
                _logger.LogInformation("Finished with the Script.");
            }
            catch (Exception e)
            {
                Console.WriteLine(e);
                throw;
            }
        }
Пример #14
0
        protected override void Execute(NativeActivityContext context)
        {
            try
            {
                String workbookFullName = FilePath.Get(context);
                String newFileName      = NewFileName.Get(context);
                string newfilePath      = NewFilePath.Get(context);

                string   fileFormat               = ToDescriptionString(FileFormatType);
                String[] fileFormatTypeStr        = FileFormatType.ToString().TrimStart().Split('_');
                String   extension                = String.Concat(".", fileFormatTypeStr[0]);
                string   newFileNameWithExtension = String.Concat(newFileName, extension);

                string  workbookName     = string.Empty;
                dynamic xlWorkbook       = null;
                bool    excelFileVisible = false;

                if (true == NeedToOpen)
                {
                    excelFileVisible = true;
                }

                // Combine 2 path parts.
                string workbooknameas = Path.Combine(newfilePath, newFileName);
                string workbooknameasWithExtension = Path.Combine(newfilePath, newFileNameWithExtension);

                if (File.Exists(workbookFullName))
                {
                    ExcelHelper.Shared.Close_OpenedFile(workbookFullName);
                    workbookName = Path.GetFileName(workbookFullName);

                    ExcelHelper.Shared.GetApp(excelFileVisible).DisplayAlerts = false;
                    xlWorkbook = ExcelHelper.Shared.GetApp(excelFileVisible).Workbooks.Open(workbookFullName);

                    if (File.Exists(workbooknameasWithExtension))
                    {
                        if (true == IsOverride)
                        {
                            // xlWorkbook.SaveAs(workbooknameas, FileFormatType, Missing.Value, Missing.Value, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                            XlFileFormat fm = (XlFileFormat)Enum.Parse(typeof(XlFileFormat), fileFormat);
                            xlWorkbook.SaveAs(workbooknameas, fm, Missing.Value, Missing.Value, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                        }
                        else
                        {
                            Log.Logger.LogData("The file \"" + newFileName + "\" is already exists in activity Excel_Workbook_SaveAs", LogLevel.Error);
                            if (!ContinueOnError)
                            {
                                context.Abort();
                            }
                        }
                    }
                    else
                    {
                        // xlWorkbook.SaveAs(workbooknameas, XlFileFormat.xlWorkbookDefault, Missing.Value, Missing.Value, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                        //xlWorkbook.SaveAs(workbooknameas, FileFormatType, Missing.Value,Missing.Value, false, false, XlSaveAsAccessMode.xlNoChange,XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                        XlFileFormat fm = (XlFileFormat)Enum.Parse(typeof(XlFileFormat), fileFormat);
                        xlWorkbook.SaveAs(workbooknameas, fm, Missing.Value, Missing.Value, false, false, XlSaveAsAccessMode.xlNoChange, XlSaveConflictResolution.xlUserResolution, true, Missing.Value, Missing.Value, Missing.Value);
                    }
                    if (true == NeedToClose)
                    {
                        xlWorkbook.Close();
                    }
                    if (false == NeedToClose && false == NeedToOpen)
                    {
                        xlWorkbook.Close();
                    }
                    if (false == NeedToClose && true == NeedToOpen)
                    {
                        xlWorkbook.Close();
                        ExcelHelper.Shared.GetApp(excelFileVisible).Workbooks.Open(workbookFullName);
                    }
                    if (ExcelHelper.Shared.GetApp(excelFileVisible).Workbooks.Count == 0)
                    {
                        ExcelHelper.Shared.Dispose();
                    }
                }
                else
                {
                    Log.Logger.LogData("Excel file does not exist:\"" + workbookFullName + "\" in activity Excel_Workbook_SaveAs", LogLevel.Error);
                    if (!ContinueOnError)
                    {
                        context.Abort();
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Logger.LogData(ex.Message + " in activity Excel_Workbook_SaveAs", LogLevel.Error);
                if (!ContinueOnError)
                {
                    context.Abort();
                }
            }
        }