Example #1
0
        async Task <int> GetFiles(String directory)
        {
            int filesInDir = Directory.EnumerateFiles(directory, "*", SearchOption.TopDirectoryOnly).Count();

            Res        += "Folder: " + directory + "\tFiles: " + filesInDir + "\n";
            FilesCount += filesInDir;
            foreach (String x in Directory.GetFiles(directory))
            {
                System.Threading.ThreadPool.QueueUserWorkItem(async(obj) =>
                {
                    Models.FileInfo file = await System.Threading.Tasks.Task.Run(() => new Models.FileInfo(new System.IO.FileInfo(x)));
                    Files.Add(file);
                    Progress++;
                    Res += "Progress: " + Progress + "/" + FilesCount + "\n";
                });
            }
            foreach (String x in Directory.GetDirectories(directory))
            {
                try
                {
                    await GetFiles(x);
                }
                catch (UnauthorizedAccessException ex)
                {
                    MessageBox.Show("Can\'t get access to " + x);
                }
                catch (Exception e) {
                    MessageBox.Show(e.Message);
                }
            }
            return(0);
        }
Example #2
0
        async Task ExecuteLoadItemsCommand()
        {
            IsBusy = true;

            try
            {
                Items.Clear();

                foreach (var file in System.IO.Directory.GetFiles(Constants.BaseFilePath))
                {
                    var fileItem = new Models.FileInfo()
                    {
                        Name = Path.GetFileName(file), Size = 0, Path = file
                    };
                    Items.Add(fileItem);
                }
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex);
            }
            finally
            {
                IsBusy = false;
            }
        }
Example #3
0
        public IActionResult CreateThesis(long id, string filename, IFormFile file)
        {
            var user = DB.Users
                       .Where(x => x.Id == id)
                       .SingleOrDefault();

            file.SaveAs(".\\wwwroot\\uploads\\" + user.UserName + "\\thesis\\" + filename + ".docx");
            var fileinfo = new Models.FileInfo
            {
                Title      = filename,
                CreateTime = DateTime.Now,
                Path       = user.UserName + "\\thesis\\" + filename + ".docx",
                FType      = FType.论文,
                StudentId  = DB.Students.Where(x => x.UserId == user.Id).SingleOrDefault().Id,
            };

            DB.FinleInfos.Add(fileinfo);
            DB.SaveChanges();
            var log = DB.Logs.Add(new Log
            {
                Roles     = Roles.学生,
                Operation = Operation.文件,
                Time      = DateTime.Now,
                Number    = fileinfo.Id,
                UserId    = User.Current.Id,
            });

            DB.SaveChanges();
            return(RedirectToAction("Thesis", "Home"));
        }
Example #4
0
        public void ShowToast(Models.FileInfo file, string message = "Success")
        {
            var image = "https://raw.githubusercontent.com/Windows-XAML/Template10/master/Assets/Template10.png";

            var content = new NotificationsExtensions.Toasts.ToastContent()
            {
                Launch = file.Ref.Path,
                Visual = new NotificationsExtensions.Toasts.ToastVisual()
                {
                    TitleText = new NotificationsExtensions.Toasts.ToastText()
                    {
                        Text = message
                    },
                    BodyTextLine1 = new NotificationsExtensions.Toasts.ToastText()
                    {
                        Text = file.Name
                    },
                    AppLogoOverride = new NotificationsExtensions.Toasts.ToastAppLogo()
                    {
                        Crop   = NotificationsExtensions.Toasts.ToastImageCrop.Circle,
                        Source = new NotificationsExtensions.Toasts.ToastImageSource(image)
                    }
                },
                Audio = new NotificationsExtensions.Toasts.ToastAudio()
                {
                    Src = new Uri("ms-winsoundevent:Notification.IM")
                }
            };

            var notification = new Windows.UI.Notifications.ToastNotification(content.GetXml());
            var notifier     = Windows.UI.Notifications.ToastNotificationManager.CreateToastNotifier();

            notifier.Show(notification);
        }
Example #5
0
        public virtual async Task <IActionResult> Post(
            [FromHeader] string source,
            [FromHeader] string entity,
            [FromHeader] string filename,
            [FromHeader] string format,
            [FromForm] IFormFile fileData)
        {
            if (fileData == null)
            {
                return(BadRequest("No file data"));
            }

            var id       = Guid.NewGuid().ToString();
            var fileInfo = new Models.FileInfo
            {
                Id       = id,
                Source   = source,
                Entity   = entity,
                Filename = filename,
                Format   = format,
                Uri      = this.BuildLink($"/files/{id}")
            };

            using (var stream = fileData.OpenReadStream())
            {
                await blobRepository.UploadAsync(new BlobInfo(id), stream);
            }
            return(Ok());
        }
        private async void CreateFileInfoAsync()
        {
            await Task.Factory.StartNew(() => {
                mp3Files = new ObservableCollection <string>(Directory.EnumerateFiles(_sourceDirectory, "*.mp3"));
            });

            for (int i = 0; i < mp3Files.Count; i++)
            {
                await Task.Run(() =>
                {
                    Models.FileInfo fileInfo = new Models.FileInfo
                    {
                        Directory = mp3Files[i],
                        FileIndex = i,
                        Title     = TagLib.File.Create(mp3Files[i]).Tag.Title,
                        Artist    = !string.IsNullOrEmpty(TagLib.File.Create(mp3Files[i]).Tag.FirstPerformer) ?
                                    TagLib.File.Create(mp3Files[i]).Tag.FirstPerformer :
                                    TagLib.File.Create(mp3Files[i]).Tag.FirstAlbumArtist
                    };

                    App.Current.Dispatcher.Invoke(delegate
                    {
                        Directories.Add(fileInfo);
                    });
                });
            }
        }
Example #7
0
 public async Task SaveAsync(Models.FileInfo model)
 {
     if (model != null)
     {
         await Windows.Storage.FileIO.WriteTextAsync(model.Ref, model.Text);
     }
 }
        public async Task SaveFileInfoAsync(Models.FileInfo model)
        {
            // nothing to save (can be okay)
            if (model == null)
            {
                return;
            }

            // save content to file
            await Windows.Storage.FileIO.WriteTextAsync(model.Ref, model.Text);
        }
Example #9
0
        public async void Create()
        {
            // Create sample file; replace if exists.
            Windows.Storage.StorageFolder storageFolder =
                Windows.Storage.ApplicationData.Current.LocalFolder;
            Windows.Storage.StorageFile sampleFile = await storageFolder.CreateFileAsync("Untitled.txt",
                                                                                         Windows.Storage.CreationCollisionOption.ReplaceExisting);

            File = await _FileService.LoadAsync(sampleFile);

            await sampleFile.DeleteAsync(Windows.Storage.StorageDeleteOption.PermanentDelete);
        }
Example #10
0
        /// <summary>
        /// Uploads a file by bucket id and file name to Backblaze B2 Cloud Storage.
        /// </summary>
        /// <param name="bucketId">The bucket id you want to upload to.</param>
        /// <param name="fileName">The name of the file to upload.</param>
        /// <param name="localPath">The relative or absolute path to the file. This string is not case-sensitive.</param>
        /// <param name="progress">A progress action which fires every time the write buffer is cycled.</param>
        /// <param name="cancel">The cancellation token to cancel operation.</param>
        /// <exception cref="AuthenticationException">Thrown when authentication fails.</exception>
        /// <exception cref="CapExceededExecption">Thrown when a cap is exceeded or an account in bad standing.</exception>
        /// <exception cref="InvalidHashException">Thrown when a checksum hash is not valid.</exception>
        /// <exception cref="ApiException">Thrown when an error occurs during client operation.</exception>
        async Task <IApiResults <UploadFileResponse> > IStorageFiles.UploadAsync
            (string bucketId, string fileName, string localPath, IProgress <ICopyProgress> progress, CancellationToken cancel)
        {
            using (var content = File.OpenRead(localPath))
            {
                var fileInfo = new Models.FileInfo();

                // get last modified date
                DateTime lastModified = File.GetLastWriteTime(localPath);

                // check whether a file is read only
                var isReadOnly = ((File.GetAttributes(localPath) & FileAttributes.ReadOnly) == FileAttributes.ReadOnly);
                fileInfo.Add("src_file_readonly", isReadOnly.ToString().ToLower());

                // check whether a file is hidden
                var isHidden = ((File.GetAttributes(localPath) & FileAttributes.Hidden) == FileAttributes.Hidden);
                fileInfo.Add("src_file_hidden", isHidden.ToString().ToLower());

                // check whether a file has archive attribute
                var isArchive = ((File.GetAttributes(localPath) & FileAttributes.Archive) == FileAttributes.Archive);
                fileInfo.Add("src_file_archive", isArchive.ToString().ToLower());

                // check whether a file has compressed attribute
                var isCompressed = ((File.GetAttributes(localPath) & FileAttributes.Compressed) == FileAttributes.Compressed);
                fileInfo.Add("src_file_compressed", isCompressed.ToString().ToLower());

                var request = new UploadFileByBucketIdRequest(bucketId, fileName)
                {
                    LastModified = lastModified, FileInfo = fileInfo
                };
                var results = await _client.UploadAsync(request, content, progress, cancel);

                if (results.IsSuccessStatusCode)
                {
                    _logger.LogInformation($"Successfully uploaded '{localPath}' file to '{bucketId}' bucket id");
                }
                else
                {
                    _logger.LogError($"Failed uploading '{localPath}' file with error: {results.Error?.Message}");
                }

                return(results);
            }
        }
Example #11
0
        public async void Save()
        {
            //if this is a new file, (meaning no file was opened, then build the fileinfo model)
            if (File == null)
            {
                // get the current frame so that you can get the contents of the textbox.
                //Frame frame = (Frame)Window.Current.Content;
                //MainPage page = (MainPage)frame.Content;
                //TextBox textBox = (TextBox)page.FindName("textBox");

                // set text value to contents of textbox or to an empty string.
                File = new Models.FileInfo
                {
                    Text = textBox.Text ?? ""
                };

                // use a save file picker to allow the user to save the file.
                GetPicker(File);
            }
            // not sure if this is a good idea.
            //I'm trying to force avoid saving in appdata folder.
            //But what about phones and cloud storage
            else if (File.Ref.Path.Contains("AppData"))
            {
                GetPicker(File);
            }
            else
            {
                try
                {
                    // if the file existed, try and save.
                    await _FileService.SaveAsync(File);

                    // display a toast notification to let the user know that the file was saved.
                    _ToastService.ShowToast(File, "File successfully saved.");
                } catch (Exception ex)
                {
                    // if there was an error, display a toast notifying the user.
                    _ToastService.ShowToast(File, $"Save failed: {ex.Message}");
                }
            }
        }
Example #12
0
        public async void Open()
        {
            // prompt a picker
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.List,
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
            };

            picker.FileTypeFilter.Add(".txt");
            var file = await picker.PickSingleFileAsync();

            if (file == null)
            {
                await new Windows.UI.Popups.MessageDialog("No file selected.").ShowAsync();
            }
            else
            {
                File = await _FileService.LoadAsync(file);
            }
        }
Example #13
0
        public async void Open()
        {
            // prompt a picker
            var picker = new FileOpenPicker
            {
                ViewMode = PickerViewMode.List,
                SuggestedStartLocation = PickerLocationId.DocumentsLibrary,
            };
            picker.FileTypeFilter.Add(".txt");
            var file = await picker.PickSingleFileAsync();

            // handle result
            if (file == null)
            {
                // nothing picked
                File = null;
                await new Windows.UI.Popups.MessageDialog("No file selected.").ShowAsync();
            }
            else
            {
                // load file
                File = await _DataService.GetFileInfoAsync(file);
            }
        }
Example #14
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="directoryPath">Server path</param>
        /// <returns></returns>
        public static FileManager GetFileFromDirectory(string directoryPath, int pageIndex)
        {
            var result = new FileManager();

            // Get all file and directory
            var directoryInfo   = new System.IO.DirectoryInfo(directoryPath);
            var allFilePath     = directoryInfo.GetFiles().OrderByDescending(p => p.CreationTime).Select(s => Path.Combine(directoryPath, s.Name));
            var allDirectoyPath = Directory.GetDirectories(directoryPath);

            // Paging
            var allPaths = new List <PathInfo>();

            allPaths.AddRange(allDirectoyPath.Select(s => new PathInfo {
                Path = s, IsDirectory = true
            }));
            allPaths.AddRange(allFilePath.Select(s => new PathInfo {
                Path = s, IsFile = true
            }));

            result.Total = allPaths.Count();
            var skip         = (pageIndex - 1) * PageSize;
            var allPathPaged = allPaths.Skip(skip).Take(PageSize).ToList();

            // Directories
            var allDirectoyPathPaged = allPathPaged.Where(p => p.IsDirectory).ToList();

            foreach (var pathItem in allDirectoyPathPaged)
            {
                var item = new Models.DirectoryInfo
                {
                    Name = GetDirectoryName(pathItem.Path),
                    Path = pathItem.Path
                };

                result.Directories.Add(item);
            }

            // Files
            var allFilePathPaged = allPathPaged.Where(p => p.IsFile).ToList();

            foreach (var pathItem in allFilePathPaged)
            {
                var item = new Models.FileInfo
                {
                    Name        = Path.GetFileNameWithoutExtension(pathItem.Path),
                    WebsitePath = pathItem.Path.Replace("wwwroot", ""),
                    Path        = pathItem.Path,
                    FileType    = Path.GetExtension(pathItem.Path)
                };

                result.Files.Add(item);
            }

            // Breadcrumbs
            //var homePath = FileConstants.FileManagerRootPath;
            //result.Breadcrumbs.Add(new Breadcrumb { Title = "Home", Path = homePath });
            //var remainPath = directoryPath.Substring(homePath.Length);
            //if (remainPath.Length > 0)
            //{
            //    var remainDirectories = remainPath.Split("\\").Where(path => !string.IsNullOrEmpty(path)).ToArray();
            //    foreach (var name in remainDirectories)
            //    {
            //        result.Breadcrumbs.Add(new Breadcrumb { Title = name, Path = Path.Combine(result.Breadcrumbs.Last().Path, name) });
            //    }
            //}

            return(result);
        }
        public async Task <IEnumerable <SearchResult> > FindInFileAsync(Models.FileInfo file, string[] searchKeywords)
        {
            return(await Task.Run(() =>
            {
                var localResults = new List <SearchResult>();

                if (searchKeywords.Any(key => !string.IsNullOrWhiteSpace(key)))
                {
                    var lines = File.ReadAllLines(file.FilePath);
                    var lineCounter = 0;

                    //loop through lines looking for our text and filling in the table with found results
                    foreach (var line in lines.Select(s => s.ToUpperInvariant()))
                    {
                        foreach (string keyword in searchKeywords.Where(key => !string.IsNullOrWhiteSpace(key)))
                        {
                            if (line.Contains(keyword))
                            {
                                var view = new SearchResult()
                                {
                                    SearchKeyword = keyword,
                                    FileName = file.FileName,
                                    RowNumber = lineCounter + 1,
                                    FilePath = file.FilePath,
                                    Id = IDGenerator.Instance.Next,
                                    IsGuptaFile = file.FileType == FileType.Apt
                                };

                                //if format of file is "Apt" get class function/window name
                                if (file.FileType == FileType.Apt || file.FileType == FileType.Sql)
                                {
                                    var goBack = true;
                                    var classNameFound = false;
                                    var backwardsCounter = lineCounter;

                                    if (file.FileType == FileType.Apt)
                                    {
                                        while (goBack && backwardsCounter > 0)
                                        {
                                            if (!classNameFound && (guptaFunctions.Any(lines[backwardsCounter].Contains)))
                                            {
                                                view.ClassName = ParseObjectName(lines[backwardsCounter], guptaFunctions);
                                                classNameFound = true;
                                            }

                                            if (guptaClasses.Any(lines[backwardsCounter].Contains))
                                            {
                                                goBack = false;
                                                view.ObjectName = ParseObjectName(lines[backwardsCounter], guptaClasses);
                                            }

                                            backwardsCounter--;
                                        }
                                    }
                                    else
                                    {
                                        while (goBack && backwardsCounter >= 0)
                                        {
                                            if (sqlHeaders.Any(lines[backwardsCounter].ToUpperInvariant().Contains))
                                            {
                                                goBack = false;
                                                view.ClassName = ParseObjectName(lines[backwardsCounter], sqlHeaders, true);
                                            }

                                            backwardsCounter--;
                                        }
                                    }
                                }

                                lock (_lock)
                                    localResults.Add(view);
                            }
                        }

                        lock (_lock)
                            lineCounter++;
                    }
                }

                return localResults;
            })
                   .ConfigureAwait(false));
        }
Example #16
0
        public IActionResult CreateDocument(long id, string filename,string type, IFormFile file)
        {
            var user = DB.Users
                .Where(x => x.Id == id)
                .SingleOrDefault();
            if (type == "文档")
            {
                file.SaveAs(".\\wwwroot\\uploads\\" + user.UserName + "\\document\\" + filename + ".docx");
                var fileinfo = new Models.FileInfo
                {
                    Title = filename,
                    CreateTime = DateTime.Now,
                    Path = user.UserName + "\\document\\" + filename + ".docx",
                    FType = FType.文档,
                    StudentId = DB.Students.Where(x => x.UserId == user.Id).SingleOrDefault().Id,

                };
                DB.FinleInfos.Add(fileinfo);
                DB.SaveChanges();
                var log = DB.Logs.Add(new Log
                {
                    Roles = Roles.学生,
                    Operation = Operation.上传文件,
                    Time = DateTime.Now,
                    Number = fileinfo.Id,
                    UserId = User.Current.Id,
                });
            }
            else if (type == "论文")
            {
                file.SaveAs(".\\wwwroot\\uploads\\" + user.UserName + "\\thesis\\" + filename + ".docx");
                var fileinfo = new Models.FileInfo
                {
                    Title = filename,
                    CreateTime = DateTime.Now,
                    Path = user.UserName + "\\thesis\\" + filename + ".docx",
                    FType = FType.论文,
                    StudentId = DB.Students.Where(x => x.UserId == user.Id).SingleOrDefault().Id,

                };
                DB.FinleInfos.Add(fileinfo);
                DB.SaveChanges();
                var log = DB.Logs.Add(new Log
                {
                    Roles = Roles.学生,
                    Operation = Operation.上传文件,
                    Time = DateTime.Now,
                    Number = fileinfo.Id,
                    UserId = User.Current.Id,
                });
            }
            else if (type == "外文翻译")
            {
                file.SaveAs(".\\wwwroot\\uploads\\" + user.UserName + "\\english\\" + filename + ".docx");
                var fileinfo = new Models.FileInfo
                {
                    Title = filename,
                    CreateTime = DateTime.Now,
                    Path = user.UserName + "\\english\\" + filename + ".docx",
                    FType = FType.外文翻译,
                    StudentId = DB.Students.Where(x => x.UserId == user.Id).SingleOrDefault().Id,

                };
                DB.FinleInfos.Add(fileinfo);
                DB.SaveChanges();
                var log = DB.Logs.Add(new Log
                {
                    Roles = Roles.学生,
                    Operation = Operation.上传文件,
                    Time = DateTime.Now,
                    Number = fileinfo.Id,
                    UserId = User.Current.Id,
                });
            }
            else
            {
                file.SaveAs(".\\wwwroot\\uploads\\" + user.UserName + "\\report\\" + filename + ".docx");
                var fileinfo = new Models.FileInfo
                {
                    Title = filename,
                    CreateTime = DateTime.Now,
                    Path = user.UserName + "\\report\\" + filename + ".docx",
                    FType = FType.报告,
                    StudentId = DB.Students.Where(x => x.UserId == user.Id).SingleOrDefault().Id,

                };
                DB.FinleInfos.Add(fileinfo);
                DB.SaveChanges();
                var log = DB.Logs.Add(new Log
                {
                    Roles = Roles.学生,
                    Operation = Operation.上传文件,
                    Time = DateTime.Now,
                    Number = fileinfo.Id,
                    UserId = User.Current.Id,
                });
            }
            DB.SaveChanges();
            return RedirectToAction("Document", "Home");
        }
Example #17
0
        public IActionResult CreateSourceCode(long id,string filename,IFormFile file)
        {
            var user = DB.Users
                .Where(x => x.Id == id)
                .SingleOrDefault();
            file.SaveAs(".\\wwwroot\\uploads\\" + user.UserName + "\\sourcecode\\" + filename + ".zip");
            var fileinfo = new Models.FileInfo
            {
                Title = filename,
                CreateTime = DateTime.Now,
                Path = user.UserName + "\\sourcecode\\" + filename + ".zip",
                FType = FType.源代码,
                StudentId = DB.Students.Where(x => x.UserId == user.Id).SingleOrDefault().Id,

            };
            DB.FinleInfos.Add(fileinfo);
            DB.SaveChanges();
            var log = DB.Logs.Add(new Log
            {
                Roles = Roles.学生,
                Operation = Operation.上传文件,
                Time = DateTime.Now,
                Number = fileinfo.Id,
                UserId = User.Current.Id,
            });
            DB.SaveChanges();
            return RedirectToAction("SourceCode", "Home");
        }
Example #18
0
        public JsonResult Get(string path)
        {
            path = path.Replace("<", "\\");

            if (path.Length == 0)
            {
                path = _root;
            }

            Models.FileInfo currentInfo = new Models.FileInfo();

            if (Directory.Exists(path))
            {
                DirectoryInfo info = new DirectoryInfo(path);

                currentInfo.Name       = info.Name;
                currentInfo.Path       = info.FullName;
                currentInfo.IsFolder   = true;
                currentInfo.InnerDir   = null;
                currentInfo.FilesSizes = new int[3] {
                    0, 0, 0
                };

                List <Models.FileInfo> infoList = new List <Models.FileInfo>();

                if (info.Parent != null)
                {
                    infoList.Add(new Models.FileInfo {
                        Name = "..", Path = info.Parent.FullName.Replace("\\", "<"), IsFolder = true, InnerDir = null, FilesSizes = null
                    });
                }

                try
                {
                    foreach (DirectoryInfo innerInfo in info.GetDirectories())
                    {
                        infoList.Add(new Models.FileInfo {
                            Name = innerInfo.Name, IsFolder = true, Path = innerInfo.FullName.Replace("\\", "<"), InnerDir = null, FilesSizes = null
                        });
                    }

                    foreach (FileInfo innerFile in info.GetFiles())
                    {
                        infoList.Add(new Models.FileInfo {
                            Name = innerFile.Name, IsFolder = false, Path = innerFile.FullName.Replace("\\", "<"), InnerDir = null, FilesSizes = null
                        });
                    }

                    foreach (var allFiles in info.GetFiles("*", SearchOption.AllDirectories))
                    {
                        var size = allFiles.Length / 1000000;
                        if (size <= 10)
                        {
                            currentInfo.FilesSizes[0]++;
                        }
                        else if (size <= 50)
                        {
                            currentInfo.FilesSizes[1]++;
                        }
                        else if (size >= 100)
                        {
                            currentInfo.FilesSizes[2]++;
                        }
                    }
                }
                catch (UnauthorizedAccessException ex)
                {
                    //Console.WriteLine("Exception: " + ex.Message);
                }

                currentInfo.InnerDir = infoList.ToArray();
            }

            return(Json(currentInfo));
        }
Example #19
0
        public async void GetPicker(Models.FileInfo model)
        {
            //if the application window is snapped the save file picker will not display
            //so ensure that it isn't snapped.
            //var unSnapped = await EnsureUnsnapped();
            var unSnapped = true;

            if (unSnapped)
            {
                //instantiate a save file picker and set it's default location to the 'Documents' folder.
                FileSavePicker savePicker = new FileSavePicker()
                {
                    SuggestedStartLocation = PickerLocationId.DocumentsLibrary
                };

                // Dropdown of file types the user can save the file as
                savePicker.FileTypeChoices.Add("Plain Text", new List <string>()
                {
                    ".txt"
                });

                // Default file name if the user does not type one in or select a file to replace
                savePicker.SuggestedFileName = "Untitled.txt";

                // the save file picker returns an instance of windows storage file when the file is saved.
                // if the user clicks cancel on the save dialog, the storage file object will be null.
                StorageFile file = await savePicker.PickSaveFileAsync();

                // if the file is not null
                if (file != null)
                {
                    // Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
                    Windows.Storage.CachedFileManager.DeferUpdates(file);

                    // write to file
                    await Windows.Storage.FileIO.WriteTextAsync(file, model.Text);

                    // Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
                    // Completing updates may require Windows to ask for user input.
                    Windows.Storage.Provider.FileUpdateStatus status = await Windows.Storage.CachedFileManager.CompleteUpdatesAsync(file);

                    // populate model fields to be used in toast notifications.
                    model.Name = file.Name;
                    model.Ref  = file;

                    // update the property so that the INotifyPropertyChangedEvent is fired.
                    File = model;

                    // when the file update status is complete, notify the user that the file save was successful.
                    if (status == Windows.Storage.Provider.FileUpdateStatus.Complete)
                    {
                        // moved from using MessageDialogs to ToastNotifications
                        //await new Windows.UI.Popups.MessageDialog($"{file.Name} was saved.").ShowAsync();
                        _ToastService.ShowToast(model, $"{file.Name} successfully saved.");
                    }
                    else
                    {
                        // if the file update status did not complete for some reason, notify the user that the save failed.

                        // moved from using MessageDialogs to ToastNotifications
                        //await new Windows.UI.Popups.MessageDialog($"{file.Name} could not be saved.").ShowAsync();
                        _ToastService.ShowToast(model, $"{file.Name} could not be saved.");
                    }
                }
                else
                {
                    //again if the user clicked cancel on the save picker, then notify the user that the save was cancelled.

                    // moved from using MessageDialogs to ToastNotifications
                    //await new Windows.UI.Popups.MessageDialog("Save cancelled.").ShowAsync();
                    _ToastService.ShowToast(model, "Save cancelled.");

                    //if user cancels the save, set the file to null.
                    File = null;
                }
                //restore contents of textbox.
                textBox.Text = model.Text;
            }
        }
Example #20
0
        public void ShowToast(Models.FileInfo file, string message = "Success")
        {
            var image = "https://raw.githubusercontent.com/Windows-XAML/Template10/master/Assets/Template10.png";

            if (file.Ref == null)
            {
                var content = new NotificationsExtensions.Toasts.ToastContent()
                {
                    Launch = "",
                    Visual = new NotificationsExtensions.Toasts.ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            AppLogoOverride = new ToastGenericAppLogo
                            {
                                HintCrop = ToastGenericAppLogoCrop.Circle,
                                Source   = image
                            },
                            Children =
                            {
                                new AdaptiveText {
                                    Text = "File save cancelled."
                                }
                            },
                            Attribution = new ToastGenericAttributionText
                            {
                                Text = "User Cancelled."
                            },
                        }
                    },
                    Audio = new NotificationsExtensions.Toasts.ToastAudio()
                    {
                        Src = new Uri("ms-winsoundevent:Notification.IM")
                    }
                };
                var notification = new ToastNotification(content.GetXml());
                ToastNotificationManager.CreateToastNotifier().Show(notification);
            }
            else
            {
                var content = new NotificationsExtensions.Toasts.ToastContent()
                {
                    Launch = file.Ref.Path,
                    Visual = new NotificationsExtensions.Toasts.ToastVisual()
                    {
                        BindingGeneric = new ToastBindingGeneric()
                        {
                            AppLogoOverride = new ToastGenericAppLogo
                            {
                                HintCrop = ToastGenericAppLogoCrop.Circle,
                                Source   = image
                            },
                            Children =
                            {
                                new AdaptiveText {
                                    Text = file.Name
                                }
                            },
                            Attribution = new ToastGenericAttributionText
                            {
                                Text = message
                            },
                        }
                    },
                    Audio = new NotificationsExtensions.Toasts.ToastAudio()
                    {
                        Src = new Uri("ms-winsoundevent:Notification.IM")
                    }
                };
                var notification = new ToastNotification(content.GetXml());
                ToastNotificationManager.CreateToastNotifier().Show(notification);
            }
        }