示例#1
0
 public WinRTFileSystemObject(string fullPath, bool asDirectory)
 {
     _asDirectory = asDirectory;
     _fullPath = fullPath;
     _item = null;
     _initializationException = null;
 }
示例#2
0
 public ItemChangedEventArgs(object sender, IStorageItem changedItem ,ChangeKinds kind,string oldName, object locker=null, ItemChangedEventArgs source=null) {
     this.ChangeKind = kind;
     this.SynchronizingObject = locker;
     this.SourceEventArgs = source;
     this.Sender = sender;
     this.ChangedItem = changedItem;
     this.OldName = oldName;
 }
		protected override async Task GetAdditionalInformation(IStorageItem storageItem)
		{
			var file = (StorageFile)storageItem;
			var thumb = await Task.Run(async () =>
			{
				return await this.GetThumbnailForFile(file);
			});

			this.Thumbnail = thumb;
		}
 public CustomIStorageItem(IStorageItem Item)
 {
     StorageItem = Item;
     Name = Item.Name;
     if (Item is StorageFolder)
         FileType = null; // 
     else
     {
         FileType = ((StorageFile)Item).FileType.Substring(1);
         Date = Item.DateCreated.DateTime.ToString("d MMM HH:mm");
     }
 }
示例#5
0
        internal static void RollbackItemUpdate(IStorageItem oldStorageItem, IStorageItem newStorageItem)
        {
            var oldItem = (PropertyNeedsDictionaryClass)oldStorageItem;
            var newItem = (PropertyNeedsDictionaryClass)newStorageItem;

#if DEBUG
            DC.Trace?.Invoke($"Rolling back PropertyNeedsDictionaryClass.Update(): {newItem.ToTraceString()}");
#endif
            DC.Data._PropertyNeedsDictionaryClassesByIdInt.Remove(newItem.IdInt);
            newItem.IdInt = oldItem.IdInt;
            DC.Data._PropertyNeedsDictionaryClassesByIdInt.Add(newItem.IdInt, newItem);
            if (newItem.IdString != null)
            {
                DC.Data._PropertyNeedsDictionaryClassesByIdString.Remove(newItem.IdString);
            }
            newItem.IdString = oldItem.IdString;
            if (newItem.IdString != null)
            {
                DC.Data._PropertyNeedsDictionaryClassesByIdString.Add(newItem.IdString, newItem);
            }
            DC.Data._PropertyNeedsDictionaryClassesByTextLower.Remove(newItem.TextLower);
            newItem.Text      = oldItem.Text;
            newItem.TextLower = newItem.Text.ToLowerInvariant();
            DC.Data._PropertyNeedsDictionaryClassesByTextLower.Add(newItem.TextLower, newItem);
            if (newItem.TextNullableLower != null)
            {
                DC.Data._PropertyNeedsDictionaryClassesByTextNullableLower.Remove(newItem.TextNullableLower);
            }
            newItem.TextNullable      = oldItem.TextNullable;
            newItem.TextNullableLower = newItem.TextNullable?.ToLowerInvariant();
            if (newItem.TextNullableLower != null)
            {
                DC.Data._PropertyNeedsDictionaryClassesByTextNullableLower.Add(newItem.TextNullableLower, newItem);
            }
            if (newItem.TextReadonly != oldItem.TextReadonly)
            {
                throw new Exception($"PropertyNeedsDictionaryClass.Update(): Property TextReadonly '{newItem.TextReadonly}' is " +
                                    $"readonly, TextReadonly '{oldItem.TextReadonly}' read from the CSV file should be the same." + Environment.NewLine +
                                    newItem.ToString());
            }
            newItem.onRollbackItemUpdated(oldItem);
#if DEBUG
            DC.Trace?.Invoke($"Rolled back PropertyNeedsDictionaryClass.Update(): {newItem.ToTraceString()}");
#endif
        }
示例#6
0
        private async Task AddItemToRecentList(IStorageItem item, Windows.Storage.AccessCache.AccessListEntry entry)
        {
            BitmapImage      ItemImage;
            string           ItemPath;
            string           ItemName;
            StorageItemTypes ItemType;
            Visibility       ItemFolderImgVis;
            Visibility       ItemEmptyImgVis;
            Visibility       ItemFileIconVis;

            if (item.IsOfType(StorageItemTypes.File))
            {
                using (var inputStream = await((StorageFile)item).OpenReadAsync())
                    using (var classicStream = inputStream.AsStreamForRead())
                        using (var streamReader = new StreamReader(classicStream))
                        {
                            // Try to read the file to check if still exists
                            streamReader.Peek();
                        }

                ItemName  = item.Name;
                ItemPath  = string.IsNullOrEmpty(item.Path) ? entry.Metadata : item.Path;
                ItemType  = StorageItemTypes.File;
                ItemImage = new BitmapImage();
                StorageFile file      = (StorageFile)item;
                var         thumbnail = await file.GetThumbnailAsync(Windows.Storage.FileProperties.ThumbnailMode.SingleItem, 30, Windows.Storage.FileProperties.ThumbnailOptions.UseCurrentScale);

                if (thumbnail == null)
                {
                    ItemEmptyImgVis = Visibility.Visible;
                }
                else
                {
                    await ItemImage.SetSourceAsync(thumbnail.CloneStream());

                    ItemEmptyImgVis = Visibility.Collapsed;
                }
                ItemFolderImgVis = Visibility.Collapsed;
                ItemFileIconVis  = Visibility.Visible;
                recentItemsCollection.Add(new RecentItem()
                {
                    RecentPath = ItemPath, Name = ItemName, Type = ItemType, FolderImg = ItemFolderImgVis, EmptyImgVis = ItemEmptyImgVis, FileImg = ItemImage, FileIconVis = ItemFileIconVis
                });
            }
        }
        private void GetActivationInfo()
        {
            AppActivationArguments args = AppInstance.GetCurrent().GetActivatedEventArgs();
            ExtendedActivationKind kind = args.Kind;
            OutputMessage($"ActivationKind: {kind}");

            if (kind == ExtendedActivationKind.Launch)
            {
                if (args.Data is ILaunchActivatedEventArgs launchArgs)
                {
                    string argString = launchArgs.Arguments;
                    string[] argStrings = argString.Split();
                    foreach (string arg in argStrings)
                    {
                        if (!string.IsNullOrWhiteSpace(arg))
                        {
                            OutputMessage(arg);
                        }
                    }
                }
            }
            else if (kind == ExtendedActivationKind.File)
            {
                if (args.Data is IFileActivatedEventArgs fileArgs)
                {
                    IStorageItem file = fileArgs.Files.FirstOrDefault();
                    OutputMessage(file.Name);
                }
            }
            else if (kind == ExtendedActivationKind.Protocol)
            {
                if (args.Data is IProtocolActivatedEventArgs protocolArgs)
                {
                    Uri uri = protocolArgs.Uri;
                    OutputMessage(uri.AbsoluteUri);
                }
            }
            else if (kind == ExtendedActivationKind.StartupTask)
            {
                if (args.Data is IStartupTaskActivatedEventArgs startupArgs)
                {
                    OutputMessage(startupArgs.TaskId);
                }
            }
        }
示例#8
0
        /// <summary>
        /// Request Token from system. If it returns null, there is no more space for saving this item.
        /// </summary>
        /// <param name="accessibleItem"></param>
        /// <returns></returns>
        public string RequestToken(IStorageItem accessibleItem)
        {
            if (accessibleItem == null)
            {
                return(null);
            }

            var item = _tokens.SingleOrDefault(i => i.Path.Equals(accessibleItem.Path, StringComparison.OrdinalIgnoreCase));

            if (item != null)
            {
                item.Count++;
                _db.Update(item);
                return(item.Token);
            }

            if (_tokens.Count == 1000)
            {
                return(null);
            }

            var file = accessibleItem as IStorageFile; // For saving tokens, just optimizing for IStorageFile

            if (file != null)
            {
                var fileFolder    = Path.GetDirectoryName(file.Path);
                var reusableToken = _tokens.FirstOrDefault(t => t.Path.Equals(fileFolder, StringComparison.OrdinalIgnoreCase));
                if (reusableToken != null)
                {
                    reusableToken.Count++;
                    _db.Update(reusableToken);
                    return(reusableToken.Token);
                }
            }

            var token   = StorageApplicationPermissions.FutureAccessList.Add(accessibleItem);
            var newItem = new MediaItemToken {
                Path = accessibleItem.Path, Token = token, Count = 1
            };

            _tokens.Add(newItem);
            _db.Insert(newItem);

            return(token);
        }
示例#9
0
        public static async Task <T> LoadObjectFromXmlFileAsync <T>(string fileName)
        {
            // this reads XML content from a file ("filename") and returns an object  from the XML
            T   objectFromXml = default(T);
            var serializer    = new XmlSerializer(typeof(T));

            IStorageItem item = await localFolder.TryGetItemAsync(fileName);

            if (item != null)
            {
                StorageFile file   = item as StorageFile;
                Stream      stream = await file.OpenStreamForReadAsync();

                objectFromXml = (T)serializer.Deserialize(stream);
                stream.Dispose();
            }
            return(objectFromXml);
        }
        public async Task <bool> createFile()
        {
            try
            {
                IStorageItem item = await storageFolder.TryGetItemAsync(fileName);

                if (item == null)
                {
                    IStorageFile myFile = await storageFolder.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
                }
            }
            catch (Exception ex)
            {
                printError(ex);
                return(false);
            }
            return(true);
        }
示例#11
0
        public async static void AffactItem(this ExplorerItem item, IStorageItem realItem)
        {
            item.Name = realItem.Name;
            item.Path = realItem.Path;

            if (realItem is StorageFolder)
            {
                item.StorageFolder = realItem as StorageFolder;
                item.Type = ExplorerItemType.Folder;
            }
            else if (realItem is StorageFile)
            {
                item.StorageFile = realItem as StorageFile;
                item.Type = ExplorerItemType.File;
                item.Size = (await item.StorageFile.GetBasicPropertiesAsync()).Size;
                item.ModifiedDateTime = (await item.StorageFile.GetBasicPropertiesAsync()).DateModified.DateTime;
            }
        }
        public async Task <bool> fileExists()
        {
            try
            {
                IStorageItem item = await storageFolder.TryGetItemAsync(fileName);

                if (item == null)
                {
                    return(false);
                }
            }
            catch (Exception ex)
            {
                printError(ex);
                return(false);
            }
            return(true);
        }
示例#13
0
        public async static void AffactItem(this ExplorerItem item, IStorageItem realItem)
        {
            item.Name = realItem.Name;
            item.Path = realItem.Path;

            if (realItem is StorageFolder)
            {
                item.StorageFolder = realItem as StorageFolder;
                item.Type          = ExplorerItemType.Folder;
            }
            else if (realItem is StorageFile)
            {
                item.StorageFile      = realItem as StorageFile;
                item.Type             = ExplorerItemType.File;
                item.Size             = (await item.StorageFile.GetBasicPropertiesAsync()).Size;
                item.ModifiedDateTime = (await item.StorageFile.GetBasicPropertiesAsync()).DateModified.DateTime;
            }
        }
示例#14
0
        /// <summary>
        /// Return storage file.
        /// </summary>
        /// <param name="v_sfFolder"></param>
        /// <param name="v_sFileName"></param>
        /// <returns></returns>
        public async Task <object> ReturnStorageFile(object v_sfFolder, string v_sFileName)
        {
            try
            {
                //Check if signature file exists
                IStorageItem siItem = await((StorageFolder)v_sfFolder).TryGetItemAsync(v_sFileName);
                if (siItem != null)
                {
                    return(await((StorageFolder)v_sfFolder).GetFileAsync(v_sFileName));
                }

                return(null);
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message + " - FILENAME(" + v_sFileName + ")");
            }
        }
        private async Task <IStorageItem> TryGetItemAsync(string name)
        {
            IStorageItem item = null;

#if WINDOWS_PHONE_APP
            try
            {
                item = await _wrappedFolder.GetItemAsync(name).AsTask().ConfigureAwait(false);
            }
            catch (FileNotFoundException)
            {
            }
#else // UWP, Win8RT
            var storageFolder = _wrappedFolder as StorageFolder;
            item = await storageFolder.TryGetItemAsync(name).AsTask().ConfigureAwait(false);
#endif
            return(item);
        }
        private async Task <string> readFromFile()
        {
            try
            {
                IStorageItem item = await storageFolder.TryGetItemAsync(fileName);

                if (item.IsOfType(StorageItemTypes.File))
                {
                    IStorageFile file = (IStorageFile)item;
                    return(await FileIO.ReadTextAsync(file));
                }
            }
            catch (Exception ex)
            {
                printError(ex);
            }
            return("");
        }
示例#17
0
        public static string AddStorage(IStorageItem item, DataType type)
        {
            string token = "";

            if (type == DataType.Latest)
            {
                if (!EnvPath.IsLocalFolder(item.Path))
                {
                    token = StorageApplicationPermissions.MostRecentlyUsedList.Add(item, DateTime.Now.ToString("yyyyMMddHHmmss"));
                }
            }
            else
            {
                token = StorageApplicationPermissions.FutureAccessList.Add(item, type.ToString());
            }

            return(token);
        }
示例#18
0
        public async Task ShowItemInExplorer(LibraryItem item)
        {
            if (item == null)
            {
                return;
            }

            StorageFolder folder = await GetStorageFolderForItem(item);

            IStorageItem storageItem = await folder.TryGetItemAsync(GetFileNameFromFullPath(item.FilePath));

            if (storageItem != null)
            {
                FolderLauncherOptions options = new FolderLauncherOptions();
                options.ItemsToSelect.Add(storageItem);
                await Launcher.LaunchFolderAsync(folder, options);
            }
        }
        /// <summary>
        /// Carrega o XML da coleção
        /// </summary>
        /// <returns>True se carregou e false se o arquivo não existe ou está vazio</returns>
        public static async Task <bool> LoadCollectionFile()
        {
            IStorageItem storageItem = await ApplicationData.Current.LocalFolder.TryGetItemAsync("Collection");

            if (storageItem != null)
            {
                StorageFolder folder = storageItem as StorageFolder;

                storageItem = await folder.TryGetItemAsync("Collection.xml");

                if (storageItem != null)
                {
                    StorageFile file = storageItem as StorageFile;

                    string content = await FileIO.ReadTextAsync(file);

                    if (string.IsNullOrWhiteSpace(content) == false)
                    {
                        try
                        {
                            CollectionDocument = new XmlDocument();
                            CollectionDocument.LoadXml(content);
                            return(true);
                        }
                        catch
                        {
                            return(false);
                        }
                    }
                    else
                    {
                        return(false);
                    }
                }
                else
                {
                    return(false);
                }
            }
            else
            {
                return(false);
            }
        }
示例#20
0
        private async Task <string> NewCacheStorageForTaskAsync(string taskKey, bool isFolder)
        {
            try
            {
                string       ext        = RandomUtils.String(4);
                var          randomName = $"{taskKey}-{ext}";
                IStorageItem item       = null;

                if (isFolder)
                {
                    item = await cacheFolder.CreateFolderAsync(
                        randomName, CreationCollisionOption.GenerateUniqueName);

                    D($"Cache folder created <{item.Path}>");
                }
                else
                {
                    item = await cacheFolder.CreateFileAsync(
                        randomName, CreationCollisionOption.GenerateUniqueName);

                    D($"Cache file created <{item.Path}>");
                }

                lock (cacheItems)
                {
                    string token = RandomUtils.String(16);
                    while (cacheItems.ContainsKey(token))
                    {
                        token = RandomUtils.String(16);
                    }
                    cacheItems[token] = new CacheItemInfo()
                    {
                        Token    = token,
                        TaskKey  = taskKey,
                        FilePath = item.Path,
                    };
                    return(token);
                }
            }
            catch (Exception)
            {
                return(null);
            }
        }
        public override async Task <Stream> GetStreamAsync(string path)
        {
            FileInfo     fileInfo    = new FileInfo(path);
            string       filename    = fileInfo.Name;
            IStorageItem storageItem = await ApplicationData.Current.LocalCacheFolder.TryGetItemAsync(filename);

            if (storageItem == null)
            {
                storageItem = await ApplicationData.Current.LocalCacheFolder.CreateFileAsync(fileInfo.Name);
            }
            if (storageItem is StorageFile storageFile)
            {
                return(await storageFile.OpenStreamForWriteAsync());
            }
            else
            {
                throw new NotImplementedException();
            }
        }
        private async Task <bool> writeToFile(string input)
        {
            try
            {
                IStorageItem item = await storageFolder.TryGetItemAsync(fileName);

                if (item.IsOfType(StorageItemTypes.File))
                {
                    IStorageFile file = (IStorageFile)item;
                    await FileIO.WriteTextAsync(file, input);
                }
            }
            catch (Exception ex)
            {
                printError(ex);
                return(false);
            }
            return(true);
        }
示例#23
0
文件: Host.cs 项目: yanyitec/Yanyitec
 private void Storage_OnChange(IStorageItem sender, StorageChangeEventArgs e)
 {
     try
     {
         SynchronizingObject.EnterReadLock();
         foreach (var pair in Modules)
         {
             //if (pair.Value.Artifact.IsDependon(e.OldFullName ?? e.Item.FullName)) {
             //    SynchronizingObject.UpgradeToWriteLock();
             //    pair.Value.Reflush(false);
             //}
         }
     }
     finally
     {
         SynchronizingObject.ExitLock();
     }
     
 }
示例#24
0
        internal async Task SetCustomColumnsDataAsync(IEnumerable <FileSystemItemPropertyData> customColumnsData)
        {
            List <StorageProviderItemProperty> customColumns = new List <StorageProviderItemProperty>();

            if (customColumnsData != null)
            {
                foreach (FileSystemItemPropertyData column in customColumnsData)
                {
                    customColumns.Add(new StorageProviderItemProperty()
                    {
                        Id = column.Id,
                        // If value is empty Windows File Manager crushes.
                        Value = string.IsNullOrEmpty(column.Value) ? "-" : column.Value,
                        // If icon is not set Windows File Manager crushes.
                        IconResource = column.IconResource ?? Path.Combine(Config.Settings.IconsFolderPath, "Blank.ico")
                    });
                }
            }

            // Can not set provider properties on read-only files.
            // Changing read-only attribute on folders triggers folders listing. Changing it on files only.
            FileInfo file     = new FileInfo(userFileSystemPath);
            bool     readOnly = file.IsReadOnly;

            // Remove read-only attribute.
            if (readOnly && ((file.Attributes & System.IO.FileAttributes.Directory) == 0))
            {
                file.IsReadOnly = false;
                //new FileInfo(userFileSystemPath).Attributes &= ~System.IO.FileAttributes.ReadOnly;
            }

            // Update columns data.
            IStorageItem storageItem = await FsPath.GetStorageItemAsync(userFileSystemPath);

            await StorageProviderItemProperties.SetAsync(storageItem, customColumns);

            // Set read-only attribute.
            if (readOnly && ((file.Attributes & System.IO.FileAttributes.Directory) == 0))
            {
                file.IsReadOnly = true;
                //new FileInfo(userFileSystemPath).Attributes |= System.IO.FileAttributes.ReadOnly;
            }
        }
        private static async Task TestItemRoundtrip(IStorageItem item)
        {
            var expectedContent = GetRandomItemContent();

            Assert.False(await item.Exists());
            Assert.Null(await item.Get());
            Assert.False(await item.Delete());
            await item.PutText(expectedContent);

            var actualContent = await item.GetText();

            Assert.Equal(expectedContent, actualContent);

            Assert.True(await item.Exists());
            Assert.True(await item.Delete());
            Assert.False(await item.Exists());
            Assert.Null(await item.Get());
            Assert.False(await item.Delete());
        }
示例#26
0
        public async Task <bool> Apply()
        {
            bool result = false;

            IStorageItem storageItem = await ApplicationData.Current.LocalFolder.TryGetItemAsync(ENTIRES_FILENAME);

            if (storageItem != null)
            {
                StorageFile entries = storageItem as StorageFile;

                if (entries != null)
                {
                    StorageFile accounts = await ApplicationData.Current.LocalFolder.CreateFileAsync(ACCOUNTS_FILENAME, CreationCollisionOption.ReplaceExisting);

                    try
                    {
                        string data = await FileIO.ReadTextAsync(entries);

                        DataProtectionProvider provider = new DataProtectionProvider(DESCRIPTOR);

                        IBuffer buffMsg       = CryptographicBuffer.ConvertStringToBinary(data, BinaryStringEncoding.Utf8);
                        IBuffer buffProtected = await provider.ProtectAsync(buffMsg);

                        await FileIO.WriteBufferAsync(accounts, buffProtected);

                        await entries.DeleteAsync();

                        result = true;
                    }
                    catch
                    {
                        // TODO: Add logging.
                    }
                }
            }
            else
            {
                // No entries file exists, this patch is unnessecary.
                result = true;
            }

            return(result);
        }
示例#27
0
        public static string Enqueue(this StorageItemAccessList list, IStorageItem item)
        {
            if (list.MaximumItemsAllowed - 10 >= list.Entries.Count)
            {
                var first = list.Entries.FirstOrDefault();
                var token = first.Token;

                list.Remove(token);
            }

            try
            {
                return(list.Add(item));
            }
            catch
            {
                return(null);
            }
        }
示例#28
0
        internal static void RollbackItemUpdate(IStorageItem oldStorageItem, IStorageItem newStorageItem)
        {
            var oldItem = (ChildrenList_CreateOnlyParent)oldStorageItem;
            var newItem = (ChildrenList_CreateOnlyParent)newStorageItem;

#if DEBUG
            DC.Trace?.Invoke($"Rolling back ChildrenList_CreateOnlyParent.Update(): {newItem.ToTraceString()}");
#endif
            if (newItem.Text != oldItem.Text)
            {
                throw new Exception($"ChildrenList_CreateOnlyParent.Update(): Property Text '{newItem.Text}' is " +
                                    $"readonly, Text '{oldItem.Text}' read from the CSV file should be the same." + Environment.NewLine +
                                    newItem.ToString());
            }
            newItem.onRollbackItemUpdated(oldItem);
#if DEBUG
            DC.Trace?.Invoke($"Rolled back ChildrenList_CreateOnlyParent.Update(): {newItem.ToTraceString()}");
#endif
        }
        public static void DisplayResult(Image image, TextBlock textBlock, string thumbnailModeName, uint size, IStorageItem item, StorageItemThumbnail thumbnail, bool isGroup)
        {
            // ErrorMessage.Visibility = Visibility.Collapsed;
            BitmapImage bitmapImage = new BitmapImage();

            bitmapImage.SetSource(thumbnail);
            image.Source = bitmapImage;

            textBlock.Text = String.Format("ThumbnailMode.{0}\n"
                                           + "{1} used: {2}\n"
                                           + "Requested size: {3}\n"
                                           + "Returned size: {4}x{5}",
                                           thumbnailModeName,
                                           isGroup ? "Group" : item.IsOfType(StorageItemTypes.File) ? "File" : "Folder",
                                           item.Name,
                                           size,
                                           thumbnail.OriginalWidth,
                                           thumbnail.OriginalHeight);
        }
示例#30
0
        private static void AddToFutureRequestList(string Token, IStorageItem item)
        {
            if (!string.IsNullOrEmpty(Token))
            {
                try
                {
                    StorageApplicationPermissions.FutureAccessList.AddOrReplace(Token, item);
                }
                catch (Exception ex)
                {
                    if (System.Diagnostics.Debugger.IsAttached)
                    {
                        System.Diagnostics.Debugger.Break();
                    }

                    Log.Write("Could not AddToFutureRequestList: " + Token, ex, logType: LogType.Error);
                }
            }
        }
示例#31
0
 public static BaseStorageFolder AsBaseStorageFolder(this IStorageItem item)
 {
     if (item == null)
     {
         return(null);
     }
     else if (item.IsOfType(StorageItemTypes.Folder))
     {
         if (item is StorageFolder folder)
         {
             return((BaseStorageFolder)folder);
         }
         else
         {
             return(item as BaseStorageFolder);
         }
     }
     return(null);
 }
示例#32
0
 public static BaseStorageFile AsBaseStorageFile(this IStorageItem item)
 {
     if (item == null)
     {
         return(null);
     }
     else if (item.IsOfType(StorageItemTypes.File))
     {
         if (item is StorageFile file)
         {
             return((BaseStorageFile)file);
         }
         else
         {
             return(item as BaseStorageFile);
         }
     }
     return(null);
 }
示例#33
0
        internal static void RollbackItemUpdate(IStorageItem oldStorageItem, IStorageItem newStorageItem)
        {
            var oldItem = (Lookup_Child)oldStorageItem;
            var newItem = (Lookup_Child)newStorageItem;

#if DEBUG
            DC.Trace?.Invoke($"Rolling back Lookup_Child.Update(): {newItem.ToTraceString()}");
#endif
            newItem.Text = oldItem.Text;
            if (newItem.LookupParent != oldItem.LookupParent)
            {
                newItem.LookupParent = oldItem.LookupParent;
            }
            if (newItem.LookupParentNullable is null)
            {
                if (oldItem.LookupParentNullable is null)
                {
                    //nothing to do
                }
                else
                {
                    newItem.LookupParentNullable = oldItem.LookupParentNullable;
                }
            }
            else
            {
                if (oldItem.LookupParentNullable is null)
                {
                    newItem.LookupParentNullable = null;
                }
                else
                {
                    if (oldItem.LookupParentNullable != newItem.LookupParentNullable)
                    {
                        newItem.LookupParentNullable = oldItem.LookupParentNullable;
                    }
                }
            }
            newItem.onRollbackItemUpdated(oldItem);
#if DEBUG
            DC.Trace?.Invoke($"Rolled back Lookup_Child.Update(): {newItem.ToTraceString()}");
#endif
        }
示例#34
0
 /// <summary>
 /// Restituisce la dimensione di File o di una Cartella
 /// </summary>
 public static async Task<string> GetItemSize(IStorageItem item)
 {
     if(item.IsOfType(StorageItemTypes.File))
     {
         BasicProperties bp = await item.GetBasicPropertiesAsync();
         ulong peso = bp.Size;
         return SizeConvert(peso);
     }
     else if(item.IsOfType(StorageItemTypes.Folder))
     {
         StorageHelper total =new StorageHelper();
         await total.FilesNumber((StorageFolder)item);
         return SizeConvert(total.GetFilesSize());
     }
     else
     {
         return SizeConvert(0);
     }
 }
示例#35
0
        static public async Task <bool> DeleteFeed(string FeedId)
        {
            try
            {
                string[][]          RequestHeader = new string[][] { new[] { "Authorization", "GoogleLogin auth=" + AppVariables.ApplicationSettings["ConnectApiAuth"].ToString() } };
                HttpStringContent   PostContent   = new HttpStringContent("ac=unsubscribe&s=feed/" + FeedId, Windows.Storage.Streams.UnicodeEncoding.Utf8, "application/x-www-form-urlencoded");
                HttpResponseMessage PostHttp      = await AVDownloader.SendPostRequestAsync(7500, "News Scroll", RequestHeader, new Uri(ApiConnectionUrl + "subscription/edit"), PostContent);

                if (PostHttp != null && (PostHttp.Content.ToString() == "OK" || PostHttp.Content.ToString().Contains("<error>Not found</error>")))
                {
                    //Wait for busy database
                    await ApiUpdate.WaitForBusyDatabase();

                    //Clear feed from database
                    await SQLConnection.ExecuteAsync("DELETE FROM TableFeeds WHERE feed_id = ('" + FeedId + "')");

                    //Clear items from database
                    await SQLConnection.ExecuteAsync("DELETE FROM TableItems WHERE item_feed_id = ('" + FeedId + "') AND item_star_status = ('0')");

                    //Delete the feed icon
                    IStorageItem LocalFile = await ApplicationData.Current.LocalFolder.TryGetItemAsync(FeedId + ".png");

                    if (LocalFile != null)
                    {
                        try { await LocalFile.DeleteAsync(StorageDeleteOption.PermanentDelete); } catch { }
                    }

                    Debug.WriteLine("Deleted the feed and items off: " + FeedId);
                    return(true);
                }
                else
                {
                    Debug.WriteLine("Failed to delete feed: " + FeedId + " / server error.");
                    return(false);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Failed to delete feed: " + FeedId + " / " + ex.Message);
                return(false);
            }
        }
示例#36
0
        private async void ContentDialog_PersonName_TextChanged(object sender, TextChangedEventArgs e)
        {
            // Make sure that our name exists
            if (String.IsNullOrWhiteSpace(PersonName.Text))
            {
                this.IsPrimaryButtonEnabled = false;
                textBlock.Text = "Please enter a user name.";
                return;
            }

            // Make sure the name if valid - we can check the directory since each person has a local directory

            IStorageItem folderItem = null;

            try
            {
                // See if the folder exists
                folderItem = await ApplicationData.Current.LocalFolder.TryGetItemAsync("Users\\" + PersonName.Text);
            }
            catch (Exception)
            {
                // We don't get an exception if the item doesn't exist. We will if we were passed an illegal
                // path in which case we can't have a user with that name. Or there could be some other
                // issue with that directory name. Regardless you can't use that name.
                this.IsPrimaryButtonEnabled = false;
                textBlock.Text = "Sorry, can't use that name.";
                return;
            }

            // If it doesn't exist, add the user
            if (folderItem == null)
            {
                this.IsPrimaryButtonEnabled = true;
                textBlock.Text = "";
            }
            // If it does, then this user already exists
            else
            {
                this.IsPrimaryButtonEnabled = false;
                textBlock.Text = "This user name already exists.";
            }
        }
示例#37
0
        private async void PopulateRecentsList()
        {
            var mostRecentlyUsed = StorageApplicationPermissions.MostRecentlyUsedList;

            Empty.Visibility = Visibility.Collapsed;

            foreach (AccessListEntry entry in mostRecentlyUsed.Entries)
            {
                string mruToken = entry.Token;
                var    added    = await FilesystemTasks.Wrap(async() =>
                {
                    IStorageItem item = await mostRecentlyUsed.GetItemAsync(mruToken, AccessCacheOptions.FastLocationsOnly);
                    await AddItemToRecentListAsync(item, entry);
                });

                if (added == FileSystemStatusCode.Unauthorized)
                {
                    // Skip item until consent is provided
                }
                // Exceptions include but are not limited to:
                // COMException, FileNotFoundException, ArgumentException, DirectoryNotFoundException
                // 0x8007016A -> The cloud file provider is not running
                // 0x8000000A -> The data necessary to complete this operation is not yet available
                // 0x80004005 -> Unspecified error
                // 0x80270301 -> ?
                else if (!added)
                {
                    await FilesystemTasks.Wrap(() =>
                    {
                        mostRecentlyUsed.Remove(mruToken);
                        return(Task.CompletedTask);
                    });

                    System.Diagnostics.Debug.WriteLine(added.ErrorCode);
                }
            }

            if (recentItemsCollection.Count == 0)
            {
                Empty.Visibility = Visibility.Visible;
            }
        }
        /// <summary>
        /// Launches the given <paramref name="protocol"/> parameter
        /// </summary>
        /// <example>
        /// file:///C:\Users\marti\Downloads
        /// </example>
        /// <example>
        /// ms-settings:privacy-broadfilesystemaccess
        /// </example>
        /// <exception cref="Contract.Exceptions.UnauthorizedAccessException" />
        /// <param name="protocol"></param>
        /// <returns></returns>
        public async Task <bool> LaunchUriAsync(string protocol)
        {
            if (protocol.StartsWith(fileProtocol))
            {
                IStorageItem storageItem = await TryGetStorageItemFromProtocol(protocol);

                //detect whether its a directory or file
                if (storageItem is IStorageFolder storageFolder)
                {
                    return(await Launcher.LaunchFolderAsync(storageFolder, new FolderLauncherOptions()
                    {
                    }));
                }
                else if (storageItem is IStorageFile storageFile)
                {
                    return(await Launcher.LaunchFileAsync(storageFile));
                }
            }
            return(await Launcher.LaunchUriAsync(new Uri(protocol)));
        }
示例#39
0
 public async static void AddItem(this GroupInfoList<ExplorerItem> itemList, IStorageItem retrievedItem)
 {
     ExplorerItem item = new ExplorerItem
         {
             Name = retrievedItem.Name,
             Path = retrievedItem.Path
         };
     if (retrievedItem is StorageFolder)
     {
         item.StorageFolder = retrievedItem as StorageFolder;
         item.Type = ExplorerItemType.Folder;
     }
     else if (retrievedItem is StorageFile)
     {
         item.StorageFile = retrievedItem as StorageFile;
         item.Type = ExplorerItemType.File;
         item.Size = (await item.StorageFile.GetBasicPropertiesAsync()).Size;
         item.ModifiedDateTime = (await item.StorageFile.GetBasicPropertiesAsync()).DateModified.DateTime;
     }
     if (itemList.All(p => p.Name != item.Name))
         itemList.Add(item);
 }
		protected abstract Task GetAdditionalInformation(IStorageItem storageItem);
 public FileManagerPageViewModel(IWebsite website, IStorageItem currentStorageItem, IList<IStorageItem> childStorageItems)
     : base(website)
 {
     this._childStorageItems = childStorageItems.OrderBy(o => o.Uri.ToString()).ToList();
     this._currentStorageItem = currentStorageItem;
 }
示例#42
0
 public StorageChangeEventArgs(StorageChangeTypes type, IStorageItem item, string oldName) {
     this.ChangeType = type;
     this.Item = item;
     this.OldName = oldName;
 }
示例#43
0
            // Similar to WinRTFileSystem.TryGetStorageItemAsync but we only 
            // want to capture exceptions that are not related to file not 
            // found.  This matches the behavior of the Win32 implementation.
            private async Task RefreshAsync()
            {
                string directoryPath, itemName;
                _item = null;
                _initializationException = null;

                try
                {
                    PathHelpers.SplitDirectoryFile(_fullPath, out directoryPath, out itemName);

                    StorageFolder parent = null;

                    try
                    {
                        parent = await StorageFolder.GetFolderFromPathAsync(directoryPath).TranslateWinRTTask(directoryPath, isDirectory: true);
                    }
                    catch (DirectoryNotFoundException)
                    {
                        // Ignore DirectoryNotFound, in this case we just return null;
                    }

                    if (String.IsNullOrEmpty(itemName) || null == parent)
                        _item = parent;
                    else
                        _item = await parent.TryGetItemAsync(itemName).TranslateWinRTTask(_fullPath);
                }
                catch (Exception e)
                {
                    _initializationException = ExceptionDispatchInfo.Capture(e);
                }
            }
示例#44
0
            // Consumes cached file/directory information and throw if any error occurred retrieving 
            // it, including file not found.
            private void EnsureItemExists()
            {
                // If we've already tried and failed to get the item, throw
                if (_initializationException != null)
                    _initializationException.Throw();

                // We don't have the item, try and get it allowing any exception to be thrown
                if (_item == null)
                {
                    EnsureBackgroundThread();
                    _item = SynchronousResultOf(GetStorageItemAsync(_fullPath));
                }
            }
示例#45
0
 public bool Equals(IStorageItem other)
 {
     if (other == null) return false;
     var otherStorageItem = other as StorageItem;
     if (otherStorageItem == null) return false;
     return otherStorageItem == this || otherStorageItem.FullName == this.FullName;
 }
示例#46
0
 /// <summary>
 /// Deletes the storage item and any children
 /// </summary>
 /// <param name="storageItem"></param>
 private void DeleteStorageItem(IStorageItem storageItem)
 {
     this._storageItemRepository.Delete(storageItem as StorageItem);
 }
示例#47
0
        /// <summary>
        /// Save Storage Item
        /// </summary>
        /// <param name="storageItem">Storage Item</param>
        /// <param name="exists">Exists</param>
        public void Save(IStorageItem storageItem, bool exists = false)
        {
            Directory.CreateDirectory(System.IO.Path.GetDirectoryName(this.Path));

            File.WriteAllBytes(this.Path, storageItem.GetData());
        }
示例#48
0
 public static async void DeletItem(IStorageItem item)
 {
     await item.DeleteAsync();
 }
示例#49
0
 internal BasicProperties(IStorageItem item)
 {
     _item = item;
 }
 protected StorageItemViewModel(IStorageItem item)
 {
     this.item = item;
 }
 public StorageItemPathAttributes(IStorageItem storageItem)
 {
     this.storageItem = storageItem;
 }
示例#52
0
 public async Task NavigateTo(IStorageItem storageItem)
 {
     var item = storageItem as StorageFolder;
     if (item != null)
     {
         BackStack.Add(item);
         var _ = Task.Run(async () => await GetFiles());
     }
     else
     {
         var file = storageItem as StorageFile;
         if (file == null) return;
         if (VLCFileExtensions.AudioExtensions.Contains(file.FileType))
         {
             await Locator.MediaPlaybackViewModel.PlayAudioFile(file);
         }
         else if (VLCFileExtensions.VideoExtensions.Contains(file.FileType))
         {
             await Locator.MediaPlaybackViewModel.PlayVideoFile(file);
         }
     }
     OnPropertyChanged("CurrentFolderName");
 }
示例#53
0
 private async void Initialize(IStorageItem file)
 {
     TextBox.Text = await FileIO.ReadTextAsync((StorageFile) file);
 }
示例#54
0
 public Photo(IStorageItem file)
 {
     if (file == null) return;
     ImagePath = file.Path;
     Name = Path.GetFileName(ImagePath);
 }
示例#55
0
 private async Task<BasicProperties> getPhotoBasicPropertiesAsync(IStorageItem file)
 {
     return await file.GetBasicPropertiesAsync();
 }
示例#56
0
 /// <summary>
 /// Create to storage item
 /// </summary>
 /// <param name="existing">existing storage Item</param>
 /// <returns>Storage item</returns>
 public IStorageItem To(IStorageItem existing)
 {
     if (null != this.toContainer)
     {
         return new Azure(this.toContainer, existing.RelativePath);
     }
     else if (null != this.toClient)
     {
         return new S3(this.toClient, this.to, existing.RelativePath);
     }
     else
     {
         return new Disk(this.to, System.IO.Path.Combine(this.to, existing.RelativePath));
     }
 }
示例#57
0
        private async Task Load(IStorageItem item)
        {
            bool loaderFound = false;
            foreach (MetaData metaData in _plugins)
            {
                if (await metaData.Supports(item))
                {
                    IBook book = await metaData.Load(item);
                    Copy(book);
                    loaderFound = true;
                    break;
                }
            }

            if (!loaderFound)
            {
                throw new PlatformNotSupportedException("Cannot open " + item.Path);
            }

            // The path doesn't need parsing.
            Path = item.Path;
            _entry = new Entry(this);

            SanityCheck();
        }
示例#58
0
        /// <summary>
        /// Save Storage Item
        /// </summary>
        /// <param name="source">Storage Item</param>
        /// <param name="exists">Exists</param>
        public void Save(IStorageItem source, bool exists = false)
        {
            if (exists)
            {
                if (createSnapShot)
                {
                    this.blob.CreateSnapshot();

                    Trace.WriteLine(string.Format("Created snapshot of blob: '{0}'.", this.blob.Uri));
                }
            }

            if (source.Exists())
            {
                this.blob.Properties.ContentType = source.ContentType;
                //// Currently there is a bug in the library that this isn't being stored or retrieved properly, this will be compatible when the new library comes out
                this.blob.Properties.ContentMD5 = source.MD5;
                this.blob.UploadByteArray(source.GetData());

                if (!string.IsNullOrWhiteSpace(source.MD5))
                {
                    this.blob.Metadata[MD5MetadataKey] = source.MD5;
                    this.blob.SetMetadata();
                }
            }
        }
示例#59
0
 public static async Task<EBook> CreateEBook(IStorageItem item)
 {
     EBook returnValue = new EBook();
     await returnValue.Load(item);
     return returnValue;
 }
示例#60
0
        private MediaHistory CreateHistory(IStorageItem item, string token, bool isAudio)
        {
            var history = new MediaHistory
            {
                Token = token,
                Filename = item.Name,
                LastPlayed = DateTime.Now,
                TotalWatchedMilliseconds = 0,
                IsAudio = isAudio
            };

            return history;
        }