Ejemplo n.º 1
0
            public static async Task <FolderWatcher> CreateAsync(FolderViewModel vm)
            {
                var fw = new FolderWatcher();
                await fw.Create(vm);

                return(fw);
            }
Ejemplo n.º 2
0
        private List <FolderViewModel> DataTableToList(DataTable table)
        {
            List <FolderViewModel> vResult = new List <FolderViewModel>();

            try {
                foreach (DataRow row in table.Rows)
                {
                    FolderViewModel vFolder = new FolderViewModel {
                        Id             = Guid.Parse(Convert.ToString(row["STRID"])),
                        Name           = Convert.ToString(row["STRNAME"]),
                        VisualName     = Convert.ToString(row["STRVISUALNAME"]),
                        Thumnail       = Convert.ToString(row["STRTHUMBNAIL"]),
                        Url            = Convert.ToString(row["STRABSOLUTEURL"]),
                        Icon           = Convert.ToString(row["STRICON"]),
                        IdParentFolder = !string.IsNullOrEmpty(Convert.ToString(row["STRIDPARENTFOLDER"])) ? Guid.Parse(Convert.ToString(row["STRIDPARENTFOLDER"])) : Guid.Empty,
                        IsShared       = Convert.ToInt16(row["INTISSHARED"]),
                        UserId         = Guid.Parse(Convert.ToString(row["STRIDUSER"])),
                        State          = Convert.ToInt16(row["INTSTATE"]),
                        UserCreate     = Convert.ToString(row["STRUSERCREATE"]),
                        DateCreate     = Convert.ToDateTime(row["DTTDATECREATE"]),
                        UserUpdate     = Convert.ToString(row["STRUSERUPDATE"]),
                        DateUpdate     = Convert.ToString(row["DTTDATEUPDATE"]) != string.Empty ? Convert.ToDateTime(row["DTTUSERUPDATE"]) : DateTime.MinValue
                    };
                    vResult.Add(vFolder);
                }
            } catch (Exception vEx) {
                string vMessage = vEx.Message;
                vResult = new List <FolderViewModel>();
            }
            return(vResult);
        }
Ejemplo n.º 3
0
            private async Task Create(FolderViewModel vm)
            {
                var sf = await vm.GetStorageFolderAsync();

                var options = new QueryOptions
                {
                    FolderDepth             = FolderDepth.Deep,
                    IndexerOption           = IndexerOption.DoNotUseIndexer,
                    ApplicationSearchFilter = ComposeFilters(),
                };

                options.FileTypeFilter.AddRange(Statics.AudioFileTypes);

                Query = sf.CreateFileQueryWithOptions(options);
                // Event "ContentsChanged" only fires after GetFilesAsync has been called at least once.
                await Query.GetFilesAsync();

                _subscription = Observable.FromEventPattern <TypedEventHandler <IStorageQueryResultBase, object>, object>(
                    h => Query.ContentsChanged += h, h => Query.ContentsChanged -= h)
                                //.SkipUntil(autoRefresh.Where(x => x == true))
                                //.TakeUntil(autoRefresh.Where(x => x == false))
                                //.Repeat()
                                .Select(_ => Unit.Default)
                                .Subscribe(_contentChanged);
            }
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     if (e.NavigationMode == NavigationMode.Back)
     {
         DataContext      = History.Current.GetLastItem <FolderViewModel>(GetType());
         App.SelectedItem = ((FolderViewModel)DataContext).SelectedFolder;
     }
     else if (e.NavigationMode == NavigationMode.New)
     {
         if (App.SelectedItem is BaseItemDto)
         {
             DataContext = new FolderViewModel(ViewModelLocator.NavigationService, ViewModelLocator.ApiClient)
             {
                 SelectedFolder = (BaseItemDto)App.SelectedItem
             };
         }
         else if (App.SelectedItem is BaseItemPerson)
         {
             DataContext = new FolderViewModel(ViewModelLocator.NavigationService, ViewModelLocator.ApiClient)
             {
                 SelectedPerson = (BaseItemPerson)App.SelectedItem
             };
         }
     }
 }
Ejemplo n.º 5
0
        public async Task <ActionResult> CreateFolderinContainer(string valNameFolder)
        {
            bool vResult = false;

            if (!string.IsNullOrEmpty(valNameFolder))
            {
                try {
                    UserViewModel vUserSession = HttpContext.Session.Get <UserViewModel>("UserSesion");
                    IFolderData   vFolderData  = new FolderData();
                    string        vFullUrl     = await UploadAzureHelper.CreateFolderContainerBlobStorage(valNameFolder);

                    string[]        vInfoUrl = vFullUrl.Split("/");
                    string          vUrl     = string.Join("/", vInfoUrl.Take(vInfoUrl.Count() - 1));
                    FolderViewModel vFolder  = new FolderViewModel();
                    vFolder.Id         = Guid.NewGuid();
                    vFolder.Name       = vInfoUrl.ElementAt(vInfoUrl.Count() - 2);
                    vFolder.VisualName = valNameFolder;
                    vFolder.Thumnail   = string.Empty;
                    vFolder.Url        = vUrl;
                    vFolder.Icon       = string.Empty;
                    vFolder.State      = 1;
                    vFolder.UserCreate = vUserSession.Id.ToString();

                    vResult = vFolderData.SaveFolder(vFolder);
                } catch (Exception vEx) {
                    vResult = false;
                    return(Json(new { content = vResult.ToString(), message = vEx.Message }));
                }
            }

            return(Json(new { content = vResult.ToString(), message = valNameFolder }));
        }
Ejemplo n.º 6
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="operationEvents"></param>
        /// <returns></returns>
        public static IEnumerable <OperationEvent> FilteredOperationEvents(
            this IEnumerable <OperationEvent> operationEvents)
        {
            var filteredOperations = operationEvents
                                     .Where(opEvent => !(opEvent.EventType == EventType.Edit && opEvent.FileType == FileType.Directory))
                                     .OrderBy(opEvent => opEvent.RaisedTime).ToList();

            if (filteredOperations.Count() <= 1)
            {
                return(filteredOperations);
            }

            var rootFolder = new FolderViewModel(filteredOperations.GetRootPath());

            foreach (var opEvent in filteredOperations)
            {
                if (opEvent.FileType == FileType.Directory)
                {
                    rootFolder.AddFolderToRootFolder(opEvent);
                }
                else
                {
                    rootFolder.AddFileToRootFolder(opEvent);
                }
            }

            return(rootFolder.GetOperationEventsFromRootFolderViewModel().OrderBy(opEvent => opEvent.RaisedTime));
        }
        protected override DriverResult Editor(AttachToFolderPart part, dynamic shapeHelper)
        {
            int?projectId = null;

            // if it is Create Mode
            AttachToProjectPart attachToProjectPart = part.As <AttachToProjectPart>();

            if (attachToProjectPart == null || attachToProjectPart.Record.Project == null)
            {
                projectId = this.projectService.GetProjectIdFromQueryString();
            }
            else
            {
                projectId = attachToProjectPart.Record.Project != null ? (int?)attachToProjectPart.Record.Project.Id : null;
            }

            if (projectId == null)
            {
                return(null);
            }

            var             folders = this.folderService.GetFolders(projectId.Value).Select(c => c.As <FolderPart>()).ToList();
            FolderViewModel model   = this.folderService.ConvertToTree(folders, part.Record.Folder != null ? (int?)part.Record.Folder.Id : null);

            List <DriverResult> shapes = new List <DriverResult>();

            shapes.Add(ContentShape("Parts_AttachToFolder_Edit",
                                    () => shapeHelper.EditorTemplate(
                                        TemplateName: "Parts/AttachToFolder",
                                        Model: model,
                                        Prefix: Prefix)));

            var project = this.projectService.GetProject(projectId.Value);

            if (part.Id != default(int) && part.Record.Folder != null)
            {
                var folder = folders.FirstOrDefault(c => c.Id == part.Record.Folder.Id);
                shapes.AddRange(this.GetFolderMenuAndTitleShapes(folder, project, shapeHelper));
            }
            else
            {
                if (project != null)
                {
                    shapes.Add(this.GetWikiMenuAndTitle(part, project, shapeHelper));
                }
                else
                {
                    FolderWithAncestorsViewModel titleModel = new FolderWithAncestorsViewModel
                    {
                        Title     = T("[No Folder Is Selected]").Text,
                        Project   = project.Record,
                        ProjectId = projectId
                    };

                    shapes.Add(ContentShape("Parts_Folder_Title", () => shapeHelper.Parts_Folder_Title(Model: titleModel)));
                }
            }

            return(Combined(shapes.ToArray()));
        }
Ejemplo n.º 8
0
        public int Compare(FileSystemArtifactViewModel artifact1, FileSystemArtifactViewModel artifact2)
        {
            if (artifact1 == null)
            {
                throw new ArgumentNullException("artifact1");
            }
            if (artifact2 == null)
            {
                throw new ArgumentNullException("artifact2");
            }

            FolderViewModel artifact1AsFolder = artifact1 as FolderViewModel;
            FolderViewModel artifact2AsFolder = artifact2 as FolderViewModel;

            bool artifact1IsAFolder = (artifact1AsFolder != null);
            bool artifact2IsAFolder = (artifact2AsFolder != null);

            if ((artifact2IsAFolder && artifact1IsAFolder) || ((!artifact2IsAFolder) && (!artifact1IsAFolder)))
            {
                return(StringComparer.CurrentCulture.Compare(artifact1.Name, artifact2.Name));
            }
            else if (artifact1IsAFolder && (!artifact2IsAFolder))
            {
                return(-1);
            }
            else if (!artifact1IsAFolder && (artifact2IsAFolder))
            {
                return(1);
            }

            throw new NotSupportedException();
        }
Ejemplo n.º 9
0
        protected async override void OnNavigatedTo(NavigationEventArgs e)
        {
            AppService.SetAppViewBackButtonVisibility(true);
            SystemNavigationManager.GetForCurrentView().BackRequested += OnBackRequested;

            UiService.HideStatusBar();

            var parameters = NavigateService.GetNavigationObject(e.Parameter).Parameters;

            _parentFolder = parameters[NavigationParamType.Data] as FolderViewModel;

            if (_parentFolder == null)
            {
                // If something went wrong, disables the command bars
                this.TopCommandBar.IsEnabled    = false;
                this.BottomCommandBar.IsEnabled = false;

                await DialogService.ShowAlertAsync(
                    ResourceService.AppMessages.GetString("AM_PreviewImageFailed_Title"),
                    ResourceService.AppMessages.GetString("AM_PreviewImageInitFailed"));

                return;
            }

            this.ViewModel.Initialize(_parentFolder);

            base.OnNavigatedTo(e);
        }
Ejemplo n.º 10
0
        private async Task RequestRemoveFolderAsyncInner(FolderViewModel vm)
        {
            Track track = default;

            using (var tr = await db.Database.BeginTransactionAsync())
            {
                try
                {
                    var folder = await db.Folders.SingleAsync(x => x.Id == vm.Id);

                    var tracks = await db.Tracks.Where(x => x.Folder.Id == folder.Id).ToListAsync();

                    await tracks.ForEachAsync(async x =>
                    {
                        track = x;
                        await RemoveTrackAsync(x);
                    });

                    db.Folders.Remove(folder);

                    await db.SaveChangesAsync();

                    await tr.CommitAsync();

                    _musicFolders.Remove(vm);
                }
                catch
                {
                    await tr.RollbackAsync();

                    await DialogService.NotificateAsync(track.Path);
                }
            }
        }
Ejemplo n.º 11
0
        public async Task MarkFolderAsync(FolderViewModel folderViewModel)
        {
            this.saveMarkedFoldersTimer.Stop();

            await Task.Run(() =>
            {
                try
                {
                    lock (this.markedFolders)
                    {
                        if (this.markedFolders.Contains(folderViewModel))
                        {
                            this.markedFolders[this.markedFolders.IndexOf(folderViewModel)].ShowInCollection = folderViewModel.ShowInCollection;
                        }
                        else
                        {
                            this.markedFolders.Add(folderViewModel);
                        }
                    }

                    this.saveMarkedFoldersTimer.Start();
                }
                catch (Exception ex)
                {
                    LogClient.Error("Error marking folder with path='{0}'. Exception: {1}", folderViewModel.Path, ex.Message);
                }
            });
        }
 private static void UpdateRelativeRootFolder(CommunityViewModel changingViewModel, string oldNamespace,
                                              string newNamespace)
 {
     if (!string.IsNullOrEmpty(oldNamespace))
     {
         FolderViewModel rootFolder = changingViewModel.Items.OfType <FolderViewModel>()
                                      .First(f => f.IsRelativeRoot);
         if (!string.IsNullOrEmpty(newNamespace))
         {
             rootFolder.Name = newNamespace;
         }
         else
         {
             changingViewModel.RemoveItem(rootFolder);
         }
     }
     else if (!string.IsNullOrEmpty(newNamespace))
     {
         FolderViewModel rootFolder = new()
         {
             Name           = newNamespace,
             IsRelativeRoot = true
         };
         changingViewModel.Items.Add(rootFolder);
     }
 }
Ejemplo n.º 13
0
        public FolderPage()
        {
            base.OnAppearing();

            if (viewModel == null)
            {
                viewModel = new FolderViewModel();
            }

            if (viewModel.Folders.Count == 0)
            {
                viewModel.LoadFoldersCommand.Execute(null);
            }

            List <Folder> CurrentFolders;

            new DataEngine(); //lazy init

            if (DataEngine.Folders == null)
            {
                CurrentFolders = DataEngine.getFolders();
            }
            else
            {
                CurrentFolders = DataEngine.Folders;
            }
            FoldersListView = new ListView();
            AddCellData(CurrentFolders);
        }
Ejemplo n.º 14
0
        public static FolderViewModel ReturnFolderViewModel(ItemTreeViewModel _item)
        {
            if (_item == null)
            {
                //System.Windows.MessageBox.Show("Вы находитесь в корневой директории");
                // _item = CreatCollectionModel.rootItemViewModel;
                return(null);
            }

            FolderViewModel result = new FolderViewModel
            {
                FolderTitle                      = _item.NameFolder,
                FolderPath                       = _item.FolderPath,
                UpItemTreeViewFolder             = _item.UpFolder,
                ChildrenFileViewModelsCollection = _item.ChildrenFiles
            };


            // Необходим для окрытия диалоговых окон
            //if (FolderViewModel.GetMainViewModel == null)
            //{
            //    FolderViewModel.GetMainViewModel = this;
            //}

            return(result);
        }
        public void RenameFolder(FolderViewModel folder)
        {
            var folderEntity = _folderRepository.FindById(folder.Id);

            folderEntity.Name = folder.Name;
            _folderRepository.Update(folderEntity);
        }
Ejemplo n.º 16
0
        public override void UnmountView()
        {
            base.UnmountView();

            FileNameViewModel.UnmountView();
            FolderViewModel.UnmountView();
        }
Ejemplo n.º 17
0
        public FolderWindow(IPlatformFolder folder, bool newFolder)
        {
            InitializeComponent();

            _isNewFolder = newFolder;
            if (!newFolder)
            {
                Title = "Folder Details";
                ConfirmButtonContent = "Save Changes";
                FolderNameTextBox.Text = folder.Name;
                FolderNameTextBox.BorderThickness = new Thickness(0, 0, 0, 0);
            }
            else
            {
                ConfirmButtonContent = "Create";
                FolderNameTextBox.Focus();
                FolderNameTextBox.BorderThickness = new Thickness(1, 1, 1, 1);
                FolderNameTextBox.SetValue(Grid.ColumnSpanProperty, 4);
                
                EditFolderNameImage.Visibility = Visibility.Collapsed;
            }

            _view = new FolderViewModel(folder, newFolder);
            DataContext = _view;

            FolderNameTextBox.TextChanged += OnFolderNameTextChanged;
            FolderNameTextBox.GotFocus += OnFolderNameGotFocus;
        }
 protected override void OnNavigatedTo(NavigationEventArgs e)
 {
     base.OnNavigatedTo(e);
     if (e.NavigationMode == NavigationMode.New)
     {
         var selectedItem = new BaseItemDto();
         if (App.SelectedItem == null)
         {
             string name, id;
             if (NavigationContext.QueryString.TryGetValue("name", out name) &&
                 NavigationContext.QueryString.TryGetValue("id", out id))
             {
                 selectedItem = new BaseItemDto
                 {
                     Name = name,
                     Id   = id,
                     Type = "FolderCollection"
                 };
             }
         }
         if (App.SelectedItem is BaseItemDto)
         {
             selectedItem = (BaseItemDto)App.SelectedItem;
         }
         DataContext = new FolderViewModel(ViewModelLocator.NavigationService, ViewModelLocator.ConnectionManager)
         {
             SelectedFolder = selectedItem
         };
     }
 }
Ejemplo n.º 19
0
 public BARViewModel(BARFile file, string name)
 {
     Name = name;
     Source = file;
     Root = new FolderViewModel(name, this);
     if (file != null) {
         foreach (var subFile in file.Files) {
             string directory = Path.GetDirectoryName(subFile.Name);
             var folder = Root;
             if (!string.IsNullOrEmpty(directory)) {
                 if (folders.ContainsKey(directory)) folder = folders[directory];
                 else {
                     string[] folderNames = directory.Split(Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar);
                     for (int f = 0; f < folderNames.Length; ++f) {
                         var folderName = folderNames[f];
                         var subFolder = folder.Folders.FirstOrDefault(subF => subF.Name == folderName);
                         if (subFolder == null) {
                             subFolder = new FolderViewModel(folderName, this);
                             folder.AddFolder(subFolder);
                         }
                         folder = subFolder;
                     }
                     // Doesnt add parent directories created, but idk if safe the
                     // directory name might not match.. might have a slash after
                     // or use the wrong slashes
                     folders.Add(directory, folder);
                 }
             }
             folder.AddFile(new FileViewModel(subFile, this));
         }
     }
 }
Ejemplo n.º 20
0
        public IHttpActionResult Post(
            FolderViewModel folder)
        {
            IHttpActionResult ret = null;

            if (ModelState.IsValid)
            {
                folder.Components = new List <BasicComponentViewModel>();
                if (folder.TargetComponentId > 0)
                {
                    folder.Components.Add(new BasicComponentViewModel()
                    {
                        Id            = folder.TargetComponentId,
                        ComponentType = BgsComponentsEnum.Task
                    });
                }

                var savedFolder = _folderService.AddFolder(folder);
                ret = Created <FolderViewModel>(
                    Request.RequestUri +
                    savedFolder.Id.ToString(),
                    folder);
            }
            else
            {
                System.Web.Http.ModelBinding.ModelStateDictionary errors =
                    BgsHelper.ConvertToModelState(ModelState);

                ret = BadRequest(errors);
            }

            return(ret);
        }
Ejemplo n.º 21
0
 public override void MountView()
 {
     FileNameViewModel.MountView();
     FolderViewModel.MountView();
     RaisePropertyChanged(nameof(FileNameViewModel));
     RaisePropertyChanged(nameof(FolderViewModel));
     base.MountView();
 }
        private async Task GetFoldersAsync()
        {
            this.Folders = new ObservableCollection <FolderViewModel>(await this.foldersService.GetFoldersAsync());
            FolderViewModel proposedSelectedFolder = await this.foldersService.GetSelectedFolderAsync();

            this.selectedFolder = this.Folders.Where(x => x.Equals(proposedSelectedFolder)).FirstOrDefault();
            this.RaisePropertyChanged(nameof(this.SelectedFolder));
        }
        private FolderViewModel CreateFolderViewModel(DirectoryInfo folderInfo)
        {
            var result = new FolderViewModel();

            result.Name     = folderInfo.Name;
            result.SitePath = GetSitePath(folderInfo.FullName);
            return(result);
        }
        private void Expand(FolderViewModel dir, int row, FolderViewCell cell)
        {
            var subDir = dir.SubItems[row];

            cell.Dir   = subDir;
            cell.Title = subDir.ShortPath;
            cell.Leaf  = !subDir.SubItems.Any();
        }
Ejemplo n.º 25
0
        // GET: Folders/Create
        public IActionResult Create2(Guid?id)
        {
            var model = new FolderViewModel {
                FolderId = id
            };

            return(View(model));
        }
        public FolderViewModel CreateFolderViewModel(string path, bool needCountFoldersSize)
        {
            var model = new FolderViewModel();

            model.FIleObjects = CreateListOfFileobjects(path);
            model.Name        = path;
            return(model);
        }
Ejemplo n.º 27
0
        public void VisitFolder(FolderViewModel folderViewModel)
        {
            if (folderViewModel == null)
            {
                throw new ArgumentNullException("folderViewModel");
            }

            var pathViewModel = new VirtualFolderPathViewModel(_pathValidator)
            {
                Path = VirtualFileSystem.Root
            };

            if (_userInteractionService.GetVirtualFolderPath(pathViewModel))
            {
                var taskToken = new FileSystemCancellableTaskToken();

                _taskViewModel = new TaskViewModel(
                    "Копирование папки \"{0}\" по следующему пути \"{1}\"".FormatWith(folderViewModel.FullPath, pathViewModel.Path),
                    _applicationController,
                    taskToken);

                _taskCounter.IncreaseNumberOfOutstandingTasks();

                ThreadPool.QueueUserWorkItem(
                    delegate
                {
                    try
                    {
                        var results = _fileSystem.CopyFolder(folderViewModel.FullPath, pathViewModel.Path, taskToken);

                        var viewModels = TaskViewModelConverter.CreateViewModelsFromResults(results);

                        _taskViewModel.SetResult(viewModels);
                    }
                    catch (FolderNotFoundException exception)
                    {
                        this.SetCopyFileError(folderViewModel.FullPath, pathViewModel.Path, exception);
                    }
                    catch (InvalidPathException exception)
                    {
                        this.SetCopyFileError(folderViewModel.FullPath, pathViewModel.Path, exception);
                    }
                    catch (MaximumFolderCountReachedException exception)
                    {
                        this.SetCopyFileError(folderViewModel.FullPath, pathViewModel.Path, exception);
                    }
                    catch (InsufficientSpaceException exception)
                    {
                        this.SetCopyFileError(folderViewModel.FullPath, pathViewModel.Path, exception);
                    }
                    finally
                    {
                        MarkTaskViewModelAsCompleted(_taskViewModel);
                        _taskCounter.DecreaseNumberOfOutstandingTasks();
                    }
                });
            }
        }
Ejemplo n.º 28
0
        public static void CaptureCameraImage(FolderViewModel currentFolder)
        {
            try
            {
                var cameraCaptureTask = new CameraCaptureTask();

                cameraCaptureTask.Completed += async(sender, result) =>
                {
                    if (result == null || result.TaskResult != TaskResult.OK)
                    {
                        return;
                    }

                    try
                    {
                        string fileName = Path.GetFileName(result.OriginalFileName);
                        if (fileName != null)
                        {
                            string newFilePath = Path.Combine(AppService.GetUploadDirectoryPath(), fileName);
                            using (var fs = new FileStream(newFilePath, FileMode.Create))
                            {
                                await result.ChosenPhoto.CopyToAsync(fs);

                                await fs.FlushAsync();

                                fs.Close();
                            }
                            var uploadTransfer = new TransferObjectModel(currentFolder.MegaSdk,
                                                                         currentFolder.FolderRootNode,
                                                                         TransferType.Upload,
                                                                         newFilePath);
                            App.MegaTransfers.Insert(0, uploadTransfer);
                            uploadTransfer.StartTransfer();
                        }

                        NavigateService.NavigateTo(typeof(TransferPage), NavigationParameter.Normal);
                    }
                    catch (Exception)
                    {
                        new CustomMessageDialog(
                            AppMessages.PhotoUploadError_Title,
                            AppMessages.PhotoUploadError,
                            App.AppInformation,
                            MessageDialogButtons.Ok).ShowDialog();
                    }
                };

                cameraCaptureTask.Show();
            }
            catch (Exception e)
            {
                new CustomMessageDialog(
                    AppMessages.CapturePhotoFailed_Title,
                    String.Format(AppMessages.CapturePhotoFailed, e.Message),
                    App.AppInformation,
                    MessageDialogButtons.Ok).ShowDialog();
            }
        }
Ejemplo n.º 29
0
 public async Task FolderVm1()
 {
     var tree = new FolderTreeViewModel();
     var folder = new FolderViewModel("Test", tree);
     await folder.Save();
   
     var root = tree.Children;
     Assert.AreNotEqual(0, root.Count(), "Folder niet aangemaakt");
 }
Ejemplo n.º 30
0
        public void IsChecked(bool?input, bool?expectedResult)
        {
            var treeViewModel = new FolderViewModel
            {
                IsChecked = input
            };

            Assert.Equal(expectedResult, treeViewModel.IsChecked);
        }
Ejemplo n.º 31
0
        public void IsExpanded(bool value)
        {
            var treeViewModel = new FolderViewModel
            {
                IsExpanded = value
            };

            Assert.Equal(value, treeViewModel.IsExpanded);
        }
Ejemplo n.º 32
0
        public FolderPage()
        {
            InitializeComponent();
            BuildApplicationBar();
            _viewModel = DataContext as FolderViewModel;

            _filesList.SetValue(InteractionEffectManager.IsInteractionEnabledProperty, true);
            InteractionEffectManager.AllowedTypes.Add(typeof(RadDataBoundListBoxItem));
        }
        // GET: TreeView
        public ActionResult Index(string path)
        {
            var rootFolderViewModel = new FolderViewModel();
            var rootFolder          = repo.GetFolder(path);
            var subFolders          = repo.GetSubFolders(rootFolder.Id).ToList();

            rootFolderViewModel = rootFolder.MapToViewModel(subFolders);
            return(View(rootFolderViewModel));
        }
        /// <summary>
        /// Initializes a new instance of the MongoDbDatabaseViewModel class.
        /// </summary>
        public MongoDbDatabaseViewModel(MongoDbServerViewModel server, string name)
        {
            Server = server;
            Name = name;
            _children = new ObservableCollection<BaseTreeviewViewModel>();
            _collections = new FolderViewModel("Collections", this);
            _users = new FolderViewModel("Users", this);
            _children.Add(_collections);
            _collections.Children.Add(new MongoDbCollectionViewModel(this, null) { IconVisible = false });

            if (_server.ServerVersion < SemanticVersion.Parse("2.6.0"))
            {
                _children.Add(_users);
                _users.Children.Add(new MongoDbUserViewModel(null, null) { IconVisible = false });
            }

            CreateDatabase = new RelayCommand(InnerCreateDatabase, () =>
            {
                return !string.IsNullOrWhiteSpace(Name) && IsNew;
            });

            RunCommand = new RelayCommand<DatabaseCommand>(InnerOpenRunCommand);

            OpenCreateNewCollection = new RelayCommand<MongoDbDatabaseViewModel>(
            database =>
            {
                Messenger.Default.Send(new NotificationMessage<MongoDbDatabaseViewModel>(this, Constants.OpenCreateNewCollectionMessage));
            });

            Refresh = new RelayCommand(LoadCollections);

            DatabaseCommands = new Dictionary<string, DatabaseCommand>();
            DatabaseCommands.Add("repairDatabase", new DatabaseCommand() { Command = "{ repairDatabase: 1 }" });

            ConfirmDropDatabase = new RelayCommand(() =>
            {
                Messenger.Default.Send(new NotificationMessage<MongoDbDatabaseViewModel>(this, Constants.ConfirmDropDatabaseMessage));
            });

            Messenger.Default.Register<PropertyChangedMessage<bool>>(this, (message) =>
            {
                if (message.Sender == _collections && message.PropertyName == "IsExpanded" && _collections.IsExpanded)
                {
                    if (!IsNew && !_collectionsLoaded && !string.IsNullOrWhiteSpace(Name))
                        LoadCollections();
                }
                else if (Server.ServerVersion < SemanticVersion.Parse("2.6.0") && message.Sender == _users && message.PropertyName == "IsExpanded" && _users.IsExpanded)
                {
                    if (!IsNew && !_usersLoaded && !string.IsNullOrWhiteSpace(Name))
                        LoadUsers();
                }
            });

            Messenger.Default.Register<NotificationMessage<CreateCollectionViewModel>>(this, InnerCreateNewCollection);
            Messenger.Default.Register<NotificationMessage<MongoDbCollectionViewModel>>(this, InnerDropCollection);
        }
Ejemplo n.º 35
0
 public async Task FolderVmRecusie1()
 {
     var tree = new FolderTreeViewModel();
     var testFolder = new FolderViewModel("TestParent", tree);
     await testFolder.Save();
     var testChild = await testFolder.AddChild(testFolder);
     Assert.IsNotNull(testFolder, "Folder niet aangemaakt");
     Assert.IsNull(testFolder.Parent, "Parent recursie!");
     Assert.AreEqual(testFolder.Children.Count, 0, "Child recursie!");
 }
Ejemplo n.º 36
0
 public async Task FolderVMaddChild()
 {
     var tree = new FolderTreeViewModel();
     var testFolder = new FolderViewModel("TestParent", tree);
     await testFolder.Save();
     var test = await testFolder.AddChild("testChild");
     await test.Save();
     Assert.IsNotNull(test, "Folder niet aangemaakt");
     Assert.AreEqual("testChild", testFolder.Children[0].Name, false);
 }
Ejemplo n.º 37
0
 public async Task FolderVmparent1()
 {
     var tree = new FolderTreeViewModel();
     var parentFolder = new FolderViewModel("TestParent", tree);
     await parentFolder.Save();
     var testFolder = await parentFolder.AddChild("Test");
     Assert.IsNotNull(testFolder, "Folder niet aangemaakt");
     Assert.IsNotNull(parentFolder, "parentFolder niet aangemaakt");
     Assert.AreEqual<int>(0, testFolder.Children.Count, "Child ten onrechte aangemaakt");
     Assert.AreEqual("Test", parentFolder.Children[0].Name, false);
 }
     private async Task AddAllFolders(string rootName)
     {
         var rootFolder = new FolderViewModel(rootName, _folderTree);
         await rootFolder.Save();
         var infolder = await rootFolder.AddChild("In");
         this._emailProvider.InFolderId= infolder.Id;
         var outFolder = await rootFolder.AddChild("Out");
         this._emailProvider.OutFolderId= outFolder.Id;
         var sentFolder = await rootFolder.AddChild("Sent");
         this._emailProvider.SentFolderId = sentFolder.Id;
         var conceptsFolder = await rootFolder.AddChild("Concepts");
         this._emailProvider.ConceptsFolderId = conceptsFolder.Id;
 }
        /// <summary>
        /// Initializes a new instance of the MongoDbCollectionViewModel class.
        /// </summary>
        public MongoDbCollectionViewModel(MongoDbDatabaseViewModel database, string collectionName)
        {
            _children = new ObservableCollection<BaseTreeviewViewModel>();
            _indexes = new FolderViewModel("Indexes", this);
            _children.Add(_indexes);
            _indexes.Children.Add(new MongoDbIndexViewModel(this, null) { IconVisible = false });

            OpenTab = new RelayCommand(InternalOpenTab);
            RenameCollection = new RelayCommand(InternalRenameCollection);
            SaveCollection = new RelayCommand(InnerSaveCollection, () =>
            {
                return !string.IsNullOrWhiteSpace(Name) && _oldName != Name;
            });
            InsertDocuments = new RelayCommand(InternalInsertDocuments);
            CreateIndex = new RelayCommand(InternalCreateIndex);
            ConfirmDropCollection = new RelayCommand(
            () =>
            {
                Messenger.Default.Send(new NotificationMessage<MongoDbCollectionViewModel>(this, ServiceLocator.Current.GetInstance<MainViewModel>(), this, Constants.ConfirmDropCollectionMessage));
            });

            Messenger.Default.Register<PropertyChangedMessage<bool>>(this, (message) =>
            {
                if (message.Sender == _indexes && message.PropertyName == "IsExpanded" && _indexes.IsExpanded)
                {
                    if (!IsNew && !_indexesLoaded && !string.IsNullOrWhiteSpace(Name))
                        LoadIndexes();
                }
            });

            Messenger.Default.Register<NotificationMessage<CreateIndexViewModel>>(this, InnerCreateIndex);

            Messenger.Default.Register<NotificationMessage<MongoDbIndexViewModel>>(this, (message) => IndexMessageHandler(message));

            Database = database;
            _name = collectionName;
            _oldName = collectionName;
        }
        public async void LoadCollections()
        {
            _collections.IsBusy = true;
            try
            {
                var collections = await Server.MongoDbService.GetCollectionsAsync(Name);

                List<MongoDbCollectionViewModel> systemCollections = new List<MongoDbCollectionViewModel>();
                List<MongoDbCollectionViewModel> standardCollections = new List<MongoDbCollectionViewModel>();
                foreach (var collection in collections)
                {
                    var collectionVm = new MongoDbCollectionViewModel(this, collection["name"].AsString);
                    collectionVm.Database = this;

                    if (collection["name"].AsString.StartsWith("system."))
                        systemCollections.Add(collectionVm);
                    else
                        standardCollections.Add(collectionVm);
                }
                FolderViewModel systemCollectionsFolder = new FolderViewModel("System", this);
                foreach (var systemCollection in systemCollections.OrderBy(o => o.Name))
                    systemCollectionsFolder.Children.Add(systemCollection);

                DispatcherHelper.CheckBeginInvokeOnUI(() =>
                {
                    _collections.Children.Clear();

                    _collections.Children.Add(systemCollectionsFolder);

                    foreach (var collection in standardCollections.OrderBy(o => o.Name))
                        _collections.Children.Add(collection);

                    _collectionsLoaded = true;
                    _collections.ItemsCount = _collections.Children.OfType<MongoDbCollectionViewModel>().Count();
                });
                _collections.IsBusy = false;

                await LoadCollectionsStats(systemCollections.Union(standardCollections));
            }
            catch (Exception ex)
            {
                Utils.LoggerHelper.Logger.Error(string.Format("Failed to get collections on database '{0}', server '{1}'", Name, Server.Name), ex);
            }
            finally
            {
                _collections.IsBusy = false;
            }
        }
Ejemplo n.º 41
0
 internal async Task<bool> SelectItem(FolderViewModel element, bool refreshOnFail = false)
 {
     var ancestors = new List<FolderViewModel>();
     var current = element;
     while (current.Parent != null)
     {
         ancestors.Add(current.Parent);
         current = current.Parent;
     }
     for (int i = ancestors.Count - 1; i <= 0; i--)
     {
         if (!ancestors[i].IsExpanded)
         {
             ancestors[i].IsExpanded = true;
         }
     }
     element.IsSelected = true;
     return true;
 }
Ejemplo n.º 42
0
 public void ProcessFolderTo(Func<FileViewModel, string, string> withFiles, FolderViewModel folder, string path)
 {
     foreach (var subfolder in folder.Folders) {
         string subfolderPath = Path.Combine(path, subfolder.Name);
         Directory.CreateDirectory(subfolderPath);
         ProcessFolderTo(withFiles, subfolder, subfolderPath);
     }
     foreach (var subfile in folder.Files) {
         var conversion = GetConversionExtensions(subfile);
         string subfilePath = Path.Combine(path, Path.GetFileNameWithoutExtension(subfile.Name) + conversion);
         withFiles(subfile, subfilePath);
     }
 }
Ejemplo n.º 43
0
 public void AddFolder(FolderViewModel folder)
 {
     Folders.Add(folder);
 }
        public void LoadDatabases(List<BsonDocument> databases)
        {
            try
            {
                LoggerHelper.Logger.Debug("Loading database list of server " + Name);
                this.Children.Clear();
                List<MongoDbDatabaseViewModel> systemDatabases = new List<MongoDbDatabaseViewModel>();
                List<MongoDbDatabaseViewModel> standardDatabases = new List<MongoDbDatabaseViewModel>();

                FolderViewModel systemDbFolder = new FolderViewModel("System", this);
                foreach (var database in databases)
                {
                    var databaseVm = new MongoDbDatabaseViewModel(this, database["name"].AsString);
                    databaseVm.SizeOnDisk = database["sizeOnDisk"].AsDouble;
                    if (databaseVm.Name == "local")
                        systemDatabases.Add(databaseVm);
                    else
                        standardDatabases.Add(databaseVm);
                }

                foreach (var systemDb in systemDatabases.OrderBy(o => o.Name))
                    systemDbFolder.Children.Add(systemDb);

                this.Children.Add(systemDbFolder);

                if (ServerVersion >= SemanticVersion.Parse("2.6.0"))
                {
                    _users = new FolderViewModel("Users", this);
                    _users.Children.Add(new MongoDbUserViewModel(null, null) { IconVisible = false });
                    this.Children.Add(_users);
                }

                foreach (var db in standardDatabases.OrderBy(o => o.Name))
                    this.Children.Add(db);

                this.IsExpanded = true;
            }
            catch (Exception ex)
            {
                LoggerHelper.Logger.Error("Failed to load database list on server " + Name, ex);
            }
        }