Esempio n. 1
0
 public void OnMouseDown(object source, FileItemViewModel fileItem, MouseButtonEventArgs args)
 {
     if (args.LeftButton == MouseButtonState.Pressed && args.ClickCount == 2)
     {
         Open(fileItem);
     }
 }
Esempio n. 2
0
 public async Task DecryptFileAes(FileItemViewModel fileToDecrypt)
 {
     if (fileToDecrypt.IsEncrypted)
     {
         XmlSerializer        serializer = new XmlSerializer(typeof(SerialisableAuthData));
         SerialisableAuthData tagData    = null;
         using (Stream stream = await fileToDecrypt.File.OpenStreamForReadAsync())
         {
             tagData = serializer.Deserialize(stream) as SerialisableAuthData;
             stream.Dispose();
         }
         if (tagData != null)
         {
             IBuffer data          = tagData.GetData();
             IBuffer tag           = tagData.GetTag();
             var     decryptedData = CryptographicEngine.DecryptAndAuthenticate(aesKey, data,
                                                                                fileToDecrypt.Nonce, tag, null);
             await FileIO.WriteBufferAsync(fileToDecrypt.File, decryptedData);
         }
         fileToDecrypt.IsEncrypted = false;
     }
     else
     {
         throw new Exception("Tried to dencrypt file with encrypted flag already set to false");
     }
 }
Esempio n. 3
0
        /// <summary>
        /// Attempts to collapse parent and child if there is only one child.
        /// </summary>
        private static void PruneTree(FileItemViewModel root)
        {
            if (root.Children.Count == 1)
            {
                var child = root.Children[0];

                // Update root's name to include child's
                root.Name = root.Name + Path.AltDirectorySeparatorChar + child.Name;

                // Remove child from list of children
                root.Children.Clear();

                // Assign child's children to root. Re-assign parent to point to root.
                foreach (var grandchild in child.Children)
                {
                    root.Children.Add(grandchild);
                    grandchild.Parent = root;
                }
            }

            foreach (var child in root.Children)
            {
                WorkspacePageViewModel.PruneTree(child);
            }
        }
Esempio n. 4
0
        private void FileView_MouseMove(object sender, MouseEventArgs e)
        {
            Point  mpos = e.GetPosition(null);
            Vector diff = this.start - mpos;

            if (e.LeftButton == MouseButtonState.Pressed &&
                Math.Abs(diff.X) > SystemParameters.MinimumHorizontalDragDistance &&
                Math.Abs(diff.Y) > SystemParameters.MinimumVerticalDragDistance)
            {
                //get selected notepad (aka one being dragged)
                try
                {
                    FileItemViewModel notepad      = ViewModel.SelectedNotepadViewModel;
                    string            tempFilePath = Path.Combine(Path.GetTempPath(), notepad.Document.FileName);
                    notepad.Document.FilePath = tempFilePath;
                    File.WriteAllText(tempFilePath, notepad.Document.Text);
                    string[] path = new string[1] {
                        tempFilePath
                    };
                    DragDrop.DoDragDrop(this, new DataObject(DataFormats.FileDrop, path), DragDropEffects.Copy);
                    File.Delete(tempFilePath);
                }
                catch { }
            }
        }
Esempio n. 5
0
 /// <summary>
 ///
 /// <para>
 /// If the order of the if-queries is changed,
 /// the documentation in <see cref="ExplorerTree.API.Configuration.SelectionConfiguration.SelectionConfiguration"/>
 /// has to be adapted
 /// </para>
 /// </summary>
 /// <param name="isSelected"></param>
 /// <param name="file"></param>
 /// <returns></returns>
 internal bool MultiselectDesicions(bool isSelected, FileItemViewModel file)
 {
     // If the order of the if-queries is changed, the documentation in SelectionConfiguration has to be adapted
     if (SelectionConfiguration.IsMultiselectCombinationAllTypesAllowed)
     {
         this.AddOrRemoveFileAccordingToIsSelected(isSelected, file);
     }
     else if (SelectionConfiguration.IsMultiselectCombinationDirectoriesAndFilesAllowed)
     {
         if (IsEnsuredOnlyDirectoriesAndFilesAreNowSelectableByMultiselect())
         {
             AddOrRemoveFileAccordingToIsSelected(isSelected, file);
         }
         else
         {
             isSelected = false;
         }
     }
     else
     {
         if (IsEnsuredOnlyFilesAreNowSelectableByMultiselect())
         {
             AddOrRemoveFileAccordingToIsSelected(isSelected, file);
         }
         else
         {
             isSelected = false;
         }
     }
     return(isSelected);
 }
Esempio n. 6
0
        //String strMsg = "1234567812345678";     // Data to encrypt.
        //String strAlgName = SymmetricAlgorithmNames.AesCbc;
        //UInt32 keyLength = 32;                  // Length of the key, in bytes
        //BinaryStringEncoding encoding;          // Binary encoding value
        //IBuffer iv;                             // Initialization vector
        //CryptographicKey key;

        public async Task EncryptFileAes(FileItemViewModel fileToEncrypt)
        {
            if (!fileToEncrypt.IsEncrypted)
            {
                var fileBuffer = await FileIO.ReadBufferAsync(fileToEncrypt.File);

                CreateNonce(fileToEncrypt);
                EncryptedAndAuthenticatedData encryptedData = CryptographicEngine.EncryptAndAuthenticate(aesKey, fileBuffer, fileToEncrypt.Nonce,
                                                                                                         null);

                var serialData = new SerialisableAuthData(encryptedData.AuthenticationTag, encryptedData.EncryptedData);

                XmlSerializer serializer = new XmlSerializer(typeof(SerialisableAuthData));
                using (Stream stream = await fileToEncrypt.File.OpenStreamForWriteAsync())
                {
                    TextWriter output = new StreamWriter(stream);
                    serializer.Serialize(output, serialData);
                    await stream.FlushAsync();

                    output.Dispose();
                    stream.Dispose();
                }
                fileToEncrypt.IsEncrypted = true;
            }
            else
            {
                throw new Exception("Tried to encrypt file with encrypted flag already set to true");
            }
        }
Esempio n. 7
0
        /// <summary>
        /// Load image data from local file of a specified item and set it to current image data.
        /// </summary>
        /// <param name="item">Target item</param>
        internal async Task LoadSetFileAsync(FileItemViewModel item)
        {
            if (!isTokenSourceLoadingDisposed && (tokenSourceLoading != null) && !tokenSourceLoading.IsCancellationRequested)
            {
                try
                {
                    tokenSourceLoading.Cancel();
                }
                catch (ObjectDisposedException ode)
                {
                    Debug.WriteLine("CancellationTokenSource has been disposed when tried to cancel operation. {0}", ode);
                }
            }

            try
            {
                await LoadSetFileBaseAsync(item);
            }
            catch (OperationCanceledException)
            {
                // None.
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to load image data from local file. {0}", ex);
                throw new UnexpectedException("Failed to load image data from local file.", ex);
            }
        }
Esempio n. 8
0
 /// <summary>
 /// DataGridを指定アイテムへスクロールする
 /// </summary>
 /// <param name="item"></param>
 /// <returns></returns>
 public bool ScrollToItem(FileItemViewModel item)
 {
     if (item != null)
     {
         fileListDataGrid.ScrollIntoView(item);
     }
     return(true);
 }
Esempio n. 9
0
        /// <summary>
        /// Gets FileInfo of a local file.
        /// </summary>
        /// <param name="item">Target item</param>
        /// <returns>FileInfo</returns>
        private static FileInfo GetFileInfoLocal(FileItemViewModel item)
        {
            var localPath = ComposeLocalPath(item);

            return(File.Exists(localPath)             // File.Exists method is more robust than FileInfo constructor.
                                ? new FileInfo(localPath)
                                : null);
        }
Esempio n. 10
0
        private static List <FileItemViewModel> BuildTreeFromFiles(List <Tuple <string, float> > files)
        {
            // Step 3: Contruct a tree based on files
            var cache = new Dictionary <string, FileItemViewModel>();
            var roots = new List <FileItemViewModel>();

            for (var i = 0; i < files.Count; i++)
            {
                var filePath = files[i];

                // Get the path components
                var filePathParts = filePath.Item1.Split(Path.AltDirectorySeparatorChar);

                // Create the leaf using the file name
                var fileItemViewModel = new FileItemViewModel(
                    filePath.Item1,
                    filePathParts[filePathParts.Length - 1],
                    filePath.Item2);

                // Go through each file and add every nodes in the tree for each folder as well as leaves for each file
                var currentChild = fileItemViewModel;
                for (var j = filePathParts.Length - 2; j >= 0; j--)
                {
                    var ancestorName = filePathParts[j];
                    var ancestorId   = currentChild.Id.Substring(
                        0,
                        currentChild.Id.LastIndexOf(Path.AltDirectorySeparatorChar));
                    if (!cache.ContainsKey(ancestorId))
                    {
                        cache[ancestorId] = new FileItemViewModel(ancestorId, ancestorName, 0);
                        if (j == 0)
                        {
                            roots.Add(cache[ancestorId]);
                        }
                    }

                    var ancestor = cache[ancestorId];
                    if (!ancestor.Children.Contains(currentChild))
                    {
                        currentChild.Parent = ancestor;
                        ancestor.Children.Add(currentChild);
                    }

                    currentChild = ancestor;
                }
            }

            // Go through the entire tree and remove nodes with a single child, collapsing their info
            // into their parent node.
            SortBiggerFirst(roots);

            foreach (var root in roots)
            {
                WorkspacePageViewModel.PruneTree(root);
            }

            return(roots);
        }
Esempio n. 11
0
        private const string _unknownFolderName = "Unknown";         // Folder name for an item whose date or time is invalid

        /// <summary>
        /// Composes local file path to a specified local folder.
        /// </summary>
        /// <param name="item">Target item</param>
        /// <returns>Local file path</returns>
        private static string ComposeLocalPath(FileItemViewModel item)
        {
            var folderName = Settings.Current.CreatesDatedFolder
                                ? (item.Date != default(DateTime))
                                        ? item.Date.ToString("yyyyMMdd")
                                        : _unknownFolderName
                                : string.Empty;

            return(Path.Combine(Settings.Current.LocalFolder, folderName, item.FileNameWithCaseExtension));
        }
Esempio n. 12
0
 internal void AddOrRemoveFileAccordingToIsSelected(bool isSelected, FileItemViewModel fileItemVM)
 {
     if (isSelected)
     {
         this.SelectedItemHandler.AddFileToSelectedItems(fileItemVM);
     }
     else
     {
         this.SelectedItemHandler.RemoveFileFromSelectedItems(fileItemVM);
     }
 }
Esempio n. 13
0
        public void MultiselectDesicions_IsEnsuredOnlyFilesAreNowSelectableByMultiselectTrue_ReturnsTrue()
        {
            SelectionConfiguration          selectionConfiguration          = new SelectionConfiguration();
            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);
            FileSelectionHandler            fileSelectionHandler            = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel fileItemVM = new FileItemViewModel();

            bool result = fileSelectionHandler.MultiselectDesicions(true, fileItemVM);

            Assert.AreEqual(true, result);
        }
Esempio n. 14
0
        public void MultiselectDesicions_IsEnsuredOnlyFilesAreNowSelectableByMultiselectTrue_FileVMIsInListSelectedFiles()
        {
            SelectionConfiguration          selectionConfiguration          = new SelectionConfiguration();
            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);
            FileSelectionHandler            fileSelectionHandler            = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel fileItemVM = new FileItemViewModel();

            fileSelectionHandler.MultiselectDesicions(true, fileItemVM);

            Assert.AreEqual(fileItemVM, selectedExplorerTreeItemHandler.SelectedFiles.First());
        }
Esempio n. 15
0
 private void OnGraphFileSelected(object sender, MouseButtonEventArgs e)
 {
     if (graphView.HasHover)
     {
         FileItemViewModel view = ViewModel.RootItem.FindView(graphView.Hover, true);
         tree.FocusNode(view);
         tree.SelectedItem = view;
         //tree.Focus();
         //Keyboard.Focus(tree);
     }
 }
Esempio n. 16
0
        public void AddOrRemoveFileAccordingToIsSelected_Add_FileVMIsInListSelectedFiles()
        {
            SelectionConfiguration          selectionConfiguration          = new SelectionConfiguration();
            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);
            FileSelectionHandler            fileSelectionHandler            = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel fileItemVM = new FileItemViewModel();

            fileSelectionHandler.AddOrRemoveFileAccordingToIsSelected(true, fileItemVM);

            Assert.AreEqual(fileItemVM, selectedExplorerTreeItemHandler.SelectedFiles.First());
        }
Esempio n. 17
0
        public void MultiselectDesicions_IsEnsuredOnlyFilesAreNowSelectableByMultiselectFalseBecauseDirectoryWasSelectedFirst_ReturnsFalse()
        {
            SelectionConfiguration          selectionConfiguration          = new SelectionConfiguration();
            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);

            selectedExplorerTreeItemHandler.SelectedDirectories.Add(new DirectoryItemViewModel());
            FileSelectionHandler fileSelectionHandler = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel    fileItemVM           = new FileItemViewModel();

            bool result = fileSelectionHandler.MultiselectDesicions(true, fileItemVM);

            Assert.AreEqual(false, result);
        }
Esempio n. 18
0
        public void MultiselectDesicions_IsMultiselectCombinationAllTypesAllowedTrue_FileVMIsInListSelectedExplorerTreeItems()
        {
            SelectionConfiguration selectionConfiguration = new SelectionConfiguration();

            selectionConfiguration.IsMultiselectCombinationAllTypesAllowed = true;

            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);
            FileSelectionHandler            fileSelectionHandler            = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel fileItemVM = new FileItemViewModel();


            fileSelectionHandler.MultiselectDesicions(true, fileItemVM);

            Assert.AreEqual(fileItemVM, selectedExplorerTreeItemHandler.SelectedExplorerTreeItems.First());
        }
Esempio n. 19
0
        public void MultiselectDesicions_IsMultiselectCombinationAllTypesAllowedTrue_ReturnsTrue()
        {
            SelectionConfiguration selectionConfiguration = new SelectionConfiguration();

            selectionConfiguration.IsMultiselectCombinationAllTypesAllowed = true;

            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);
            FileSelectionHandler            fileSelectionHandler            = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel fileItemVM = new FileItemViewModel();


            bool result = fileSelectionHandler.MultiselectDesicions(true, fileItemVM);

            Assert.AreEqual(true, result);
        }
Esempio n. 20
0
        public void MultiselectDesicions__IsMultiselectCombinationDirectoriesAndFilesAllowedTrue_AndIsEnsuredOnlyDirectoriesAndFilesAreNowSelectableByMultiselectTrue__FileVMIsInListSelectedFiles()
        {
            SelectionConfiguration selectionConfiguration = new SelectionConfiguration();

            selectionConfiguration.IsMultiselectCombinationDirectoriesAndFilesAllowed = true;

            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);
            FileSelectionHandler            fileSelectionHandler            = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel fileItemVM = new FileItemViewModel();


            bool result = fileSelectionHandler.MultiselectDesicions(true, fileItemVM);

            Assert.AreEqual(fileItemVM, selectedExplorerTreeItemHandler.SelectedFiles.First());
        }
Esempio n. 21
0
        public void MultiselectDesicions__IsMultiselectCombinationDirectoriesAndFilesAllowedTrue_AndIsEnsuredOnlyDirectoriesAndFilesAreNowSelectableByMultiselectFalseBecauseDriveWasSelectedFirst__ReturnsFalse()
        {
            SelectionConfiguration selectionConfiguration = new SelectionConfiguration();

            selectionConfiguration.IsMultiselectCombinationDirectoriesAndFilesAllowed = true;

            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);

            selectedExplorerTreeItemHandler.SelectedDrives.Add(new DriveItemViewModel());
            FileSelectionHandler fileSelectionHandler = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel    fileItemVM           = new FileItemViewModel();


            bool result = fileSelectionHandler.MultiselectDesicions(true, fileItemVM);

            Assert.AreEqual(false, result);
        }
Esempio n. 22
0
        public void AddOrRemoveFileAccordingToIsSelected_Remove_FileVMIsInListSelectedFiles()
        {
            SelectionConfiguration          selectionConfiguration          = new SelectionConfiguration();
            SelectedExplorerTreeItemHandler selectedExplorerTreeItemHandler = new SelectedExplorerTreeItemHandler(selectionConfiguration);

            FileSelectionHandler fileSelectionHandler = new FileSelectionHandler(selectedExplorerTreeItemHandler, selectionConfiguration);
            FileItemViewModel    fileItemVM           = new FileItemViewModel();

            selectedExplorerTreeItemHandler.SelectedFiles.Add(new FileItemViewModel());
            selectedExplorerTreeItemHandler.SelectedFiles.Add(fileItemVM);
            selectedExplorerTreeItemHandler.SelectedFiles.Add(new FileItemViewModel());
            selectedExplorerTreeItemHandler.SelectedFiles.Add(new FileItemViewModel());


            fileSelectionHandler.AddOrRemoveFileAccordingToIsSelected(false, fileItemVM);

            Assert.AreEqual(-1, selectedExplorerTreeItemHandler.SelectedFiles.IndexOf(fileItemVM));
        }
Esempio n. 23
0
        public static async Task <FileItemViewModel> AddTotalyNewFile(StorageFile fileIn)
        {
            try
            {
                var newFile = await WorkingDirectory.CreateFileAsync(fileIn.Name, CreationCollisionOption.FailIfExists);

                var fileItem = new FileItemViewModel(newFile);
                await fileIn.CopyAndReplaceAsync(newFile);

                fileItem.SaveItem(fileItem);
                return(fileItem);
            }
            catch (Exception)
            {
                var warning =
                    new MessageDialog(
                        "Warning the file already exists in the main app directory, do you wish to overwrite it?")
                {
                    Title = "Warning!"
                };
                warning.Commands.Add(new UICommand {
                    Label = "Ok", Id = 0
                });
                warning.Commands.Add(new UICommand {
                    Label = "No", Id = 1
                });
                var res = await warning.ShowAsync();

                if ((int)res.Id == 0)
                {
                    var newFile =
                        await WorkingDirectory.CreateFileAsync(fileIn.Name, CreationCollisionOption.ReplaceExisting);

                    await fileIn.CopyAndReplaceAsync(newFile);

                    var fileItem = new FileItemViewModel(newFile);
                    fileItem.SaveItem(fileItem);
                    return(fileItem);
                }
            }

            return(null);
        }
Esempio n. 24
0
        private void FilterInternal(FileItemViewModel root, float minSize)
        {
            if (minSize < 0)
            {
                root.Visibility = Visibility.Visible;
            }
            else if (root.Megabytes < minSize)
            {
                root.Visibility = Visibility.Collapsed;
            }
            else
            {
                root.Visibility = Visibility.Visible;
            }

            foreach (var child in root.Children)
            {
                this.FilterInternal(child, minSize);
            }
        }
Esempio n. 25
0
        /// <summary>
        /// Compose path to local file of a specified item.
        /// </summary>
        /// <param name="item">Target item</param>
        private static string ComposeLocalPath(FileItemViewModel item)
        {
            var fileName = item.FileName;

            if (String.IsNullOrWhiteSpace((fileName)))
            {
                throw new InvalidOperationException("FileName property is empty.");
            }

            if (Settings.Current.MakesFileExtensionLowerCase)
            {
                var extension = Path.GetExtension(fileName);
                if (!String.IsNullOrEmpty(extension))
                {
                    fileName = Path.GetFileNameWithoutExtension(fileName) + extension.ToLower();
                }
            }

            return(Path.Combine(Settings.Current.LocalFolder, item.Date.ToString("yyyyMMdd"), fileName));
        }
Esempio n. 26
0
        private void AddFileToChart(FileItemViewModel viewModel)
        {
            var mapper = new PieMapper <FileItemViewModel>().Value(f => f.Megabytes);
            var series = new PieSeries(mapper);

            series.Title      = viewModel.Name;
            series.Visibility = viewModel.ChartVisibility;
            series.Values     = new ChartValues <FileItemViewModel>()
            {
                viewModel
            };
            series.DataContext = viewModel;
            series.SetBinding(PieSeries.VisibilityProperty, FileItemViewModel.ChartVisibilityPropertyName);
            this.PieChart.Series.Add(series);

            foreach (var child in viewModel.Children)
            {
                this.AddFileToChart(child);
            }
        }
Esempio n. 27
0
        /// <summary>
        /// Loads image data from a local file and set it to current image data.
        /// </summary>
        /// <param name="item">Target item</param>
        internal async Task LoadSetAsync(FileItemViewModel item)
        {
            _tokenSourceLoading?.TryCancel();             // Canceling already canceled source will be simply ignored.

            try
            {
                _tokenSourceLoading = new CancellationTokenSourcePlus();

                byte[] data = null;
                if (item.IsAvailableLocal && item.CanLoadDataLocal)
                {
                    data = await FileAddition.ReadAllBytesAsync(ComposeLocalPath(item), _tokenSourceLoading.Token);
                }

                CurrentItem      = item;
                CurrentImageData = data;
            }
            catch (OperationCanceledException)
            {
                // None.
            }
            catch (FileNotFoundException)
            {
                item.Status       = FileStatus.NotCopied;
                item.IsAliveLocal = false;
            }
            catch (IOException)
            {
                item.IsAvailableLocal = false;
            }
            catch (Exception ex)
            {
                Debug.WriteLine($"Failed to load image data from local file.\r\n{ex}");
                throw new UnexpectedException("Failed to load image data from local file.", ex);
            }
            finally
            {
                _tokenSourceLoading?.Dispose();
            }
        }
Esempio n. 28
0
        private async void Open(FileItemViewModel file)
        {
            // #TODO_PHXSTUDIO need to figure out how to support files that require an external viewer or such tool (eg, ddx until we support in-editor viewing)

            if (!file.IsEditorAvailable)
            {
                Debug.Trace.PhxStudio.TraceEvent(System.Diagnostics.TraceEventType.Warning, 0,
                                                 "Can't find editor for file",
                                                 file.FilePath);
            }
            else
            {
                var editor = file.EditorProvider;
                var vm     = editor.Create();

                Debug.Trace.PhxStudio.TraceInformation("Opening file with {0}: {1}",
                                                       editor, file.FilePath);

                await editor.Open(vm, file.FilePath);

                mShell.OpenDocument(vm);
            }
        }
Esempio n. 29
0
        private List <FileItemViewModel> GetFiles(SiteDb siteDb, string path)
        {
            string baseurl = siteDb.WebSite.BaseUrl();

            List <CmsFile> files = siteDb.Folders.GetFolderObjects <CmsFile>(path, true);

            List <FileItemViewModel> Result = new List <FileItemViewModel>();

            foreach (var item in files)
            {
                FileItemViewModel model = new FileItemViewModel();
                model.Id           = item.Id;
                model.Size         = item.Size;
                model.Name         = item.Name;
                model.LastModified = item.LastModified;
                model.Url          = ObjectService.GetObjectRelativeUrl(siteDb, item);
                model.PreviewUrl   = Lib.Helper.UrlHelper.Combine(baseurl, model.Url);

                model.Relations = Sites.Helper.RelationHelper.Sum(siteDb.Files.GetUsedBy(item.Id));

                Result.Add(model);
            }
            return(Result);
        }
Esempio n. 30
0
        /// <summary>
        /// Load image data from local file of a specified item and set it to current image data.
        /// </summary>
        /// <param name="item">Target item</param>
        private async Task LoadSetFileBaseAsync(FileItemViewModel item)
        {
            var localPath = ComposeLocalPath(item);

            try
            {
                tokenSourceLoading           = new CancellationTokenSource();
                isTokenSourceLoadingDisposed = false;

                byte[] data = null;
                if (item.CanLoadDataLocal)
                {
                    data = await FileAddition.ReadAllBytesAsync(localPath, tokenSourceLoading.Token);
                }

                CurrentItem      = item;
                CurrentImageData = data;
            }
            catch (FileNotFoundException)
            {
                item.Status       = FileStatus.NotCopied;
                item.IsAliveLocal = false;
            }
            catch (IOException)
            {
                item.CanLoadDataLocal = false;
            }
            finally
            {
                if (tokenSourceLoading != null)
                {
                    isTokenSourceLoadingDisposed = true;
                    tokenSourceLoading.Dispose();
                }
            }
        }
Esempio n. 31
0
		/// <summary>
		/// Load image data from a local file and set it to current image data.
		/// </summary>
		/// <param name="item">Target item</param>
		internal async Task LoadSetAsync(FileItemViewModel item)
		{
			if ((_tokenSourceLoading != null) && !_tokenSourceLoading.IsCancellationRequested)
			{
				_tokenSourceLoading.TryCancel();
			}

			try
			{
				_tokenSourceLoading = new CancellationTokenSourcePlus();

				byte[] data = null;
				if (item.IsAvailableLocal && item.CanLoadDataLocal)
					data = await FileAddition.ReadAllBytesAsync(ComposeLocalPath(item), _tokenSourceLoading.Token);

				CurrentItem = item;
				CurrentImageData = data;
			}
			catch (OperationCanceledException)
			{
				// None.
			}
			catch (FileNotFoundException)
			{
				item.Status = FileStatus.NotCopied;
				item.IsAliveLocal = false;
			}
			catch (IOException)
			{
				item.IsAvailableLocal = false;
			}
			catch (Exception ex)
			{
				Debug.WriteLine("Failed to load image data from local file. {0}", ex);
				throw new UnexpectedException("Failed to load image data from local file.", ex);
			}
			finally
			{
				if (_tokenSourceLoading != null)
					_tokenSourceLoading.Dispose();
			}
		}
Esempio n. 32
0
		private const string _unknownFolderName = "Unknown"; // Folder name for an item whose date or time is invalid

		/// <summary>
		/// Compose local file path to a specified local folder.
		/// </summary>
		/// <param name="item">Target item</param>
		/// <returns>Local file path</returns>
		private static string ComposeLocalPath(FileItemViewModel item)
		{
			var folderName = (item.Date != default(DateTime))
				? item.Date.ToString("yyyyMMdd")
				: _unknownFolderName;

			return Path.Combine(Settings.Current.LocalFolder, folderName, item.FileNameWithCaseExtension);
		}
Esempio n. 33
0
		/// <summary>
		/// Compose local file path to desktop.
		/// </summary>
		/// <param name="item">Target item</param>
		/// <returns>Local file path</returns>
		private static string ComposeDesktopPath(FileItemViewModel item)
		{
			return Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory), item.FileNameWithCaseExtension);
		}
Esempio n. 34
0
		/// <summary>
		/// Get FileInfo of a local file.
		/// </summary>
		/// <param name="item">Target item</param>
		/// <returns>FileInfo</returns>
		private static FileInfo GetFileInfoLocal(FileItemViewModel item)
		{
			var localPath = ComposeLocalPath(item);

			return File.Exists(localPath) ? new FileInfo(localPath) : null;
		}
Esempio n. 35
0
		/// <summary>
		/// Check if a local file exists
		/// </summary>
		/// <param name="item">Target item</param>
		/// <returns>True if exists</returns>
		private static bool IsAliveLocal(FileItemViewModel item)
		{
			return IsAliveLocal(GetFileInfoLocal(item), item.Size);
		}