Exemple #1
0
        public async Task <LibraryModel> NewLibrary()
        {
            try
            {
                if (!await this.Connector.TryConnectAsync())
                {
                    return(null);
                }

                var root = await this.Connector.GetDetailsAsync();

                var initialFolder = new Helpers.Folder {
                    Key = root.id, FullPath = "/", Name = "/"
                };

                var selectedFolder = await Selector.GetFolder(initialFolder, async (folder) =>
                {
                    var folderData = new FileData {
                        id = folder.Key, FilePath = folder.FullPath, FileName = folder.Name
                    };
                    var folderChilds = await this.Connector.GetChildFoldersAsync(folderData);
                    var folderList   = folderChilds
                                       .Select(x => new Helpers.Folder
                    {
                        Key      = x.id,
                        FullPath = x.FilePath
                                   .Trim()
                                   .Replace("/ / ", "/")
                                   .Replace("/ /", "/")
                                   .Replace("// ", "/")
                                   .Replace("//", "/"),
                        Name = x.FileName
                    })
                                       .ToArray();
                    return(folderList);
                });

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

                var library = new LibraryModel
                {
                    Key         = selectedFolder.Key,
                    Path        = selectedFolder.FullPath,
                    Description = selectedFolder.Name,
                    Type        = LibraryType.OneDrive
                };

                // library.Path = library.Path;
                if (!string.IsNullOrEmpty(library.Path))
                {
                    library.Path += "/";
                }

                return(library);
            }
            catch (Exception ex) { await App.ShowMessage(ex); return(null); }
        }
Exemple #2
0
        public void TestLibrarySortDes()
        {
            LibraryModel lm = new LibraryModel();
            Book         b1 = new Book();
            Book         b2 = new Book();

            b1.Title = "A";
            b2.Title = "B";

            List <Book> Expectedlib = new List <Book>();

            lm.library = new List <Book>();

            Expectedlib.Add(b2);
            Expectedlib.Add(b1);

            lm.library.Add(b1);
            lm.library.Add(b2);

            lm.SortLib(2);

            Assert.NotNull(lm.library);
            Assert.IsType <List <Book> >(lm.library);
            Assert.True(Expectedlib.Any() == lm.library.Any());
        }
Exemple #3
0
        protected override async Task OnInitializedAsync()
        {
            model = await UploadRepositoryAsyncReference.GetByIdAsync(Id);

            content  = Dul.HtmlUtility.EncodeWithTabAndSpace(model.Content);
            ParentId = model.ParentId.ToString();
        }
Exemple #4
0
        public void TestLibrarySortPrice()
        {
            LibraryModel lm = new LibraryModel();
            Book         b1 = new Book();
            Book         b2 = new Book();

            b1.Cost = 4.00m;
            b2.Cost = 5.00m;

            List <Book> Expectedlib = new List <Book>();

            lm.library = new List <Book>();

            Expectedlib.Add(b2);
            Expectedlib.Add(b1);

            lm.library.Add(b1);
            lm.library.Add(b2);

            lm.SortLib(3);

            Assert.NotNull(lm.library);
            Assert.IsType <List <Book> >(lm.library);
            Assert.True(Expectedlib.Any() == lm.library.Any());
        }
        /// <summary>
        ///		Crea los nodos de eBook correspondiente a los archivos pasados como parámetros
        /// </summary>
        private void CreateEBookNodes(LibraryModel library, string[] fileNames, bool killSource)
        {
            string pathTarget = null;

            // Obtiene el directorio destino
            if (library != null)                     // ... por los directorios raíz
            {
                pathTarget = library.Path;
            }
            // Si no se ha encontrado el directorio, recoge el directorio principal
            if (pathTarget.IsEmpty() || !System.IO.Directory.Exists(pathTarget))
            {
                pathTarget = BookLibraryViewModel.Instance.BooksManager.Configuration.PathLibrary;
            }
            // Guarda los libros en la librería
            foreach (string fileName in fileNames)
            {
                string fileTarget = LibCommonHelper.Files.HelperFiles.GetConsecutiveFileName(pathTarget, System.IO.Path.GetFileName(fileName));

                // Crea el directorio
                LibCommonHelper.Files.HelperFiles.MakePath(System.IO.Path.GetDirectoryName(fileTarget));
                // Copia el archivo
                if (!LibCommonHelper.Files.HelperFiles.CopyFile(fileName, fileTarget))
                {
                    BookLibraryViewModel.Instance.ControllerWindow.ShowMessage("No se ha podido copiar el archivo");
                }
                else if (killSource)                                 // Elimina el archivo origen si es necesario
                {
                    LibCommonHelper.Files.HelperFiles.KillFile(fileTarget);
                }
            }
            // Actualiza
            Refresh();
        }
Exemple #6
0
 public SearchHandler(
     LibraryModel libraryModel
     , TabControlEx mainViewTabControl
     , TabPage libraryBrowserViewTabPage
     , TabPage galleryBrowserViewTabPage
     , Configuration.ConfigCache cacheSettings
     , ISearchResultCache searchResultCache
     , ILogger logger
     , BrowsingModel browsingModel
     , IPathFormatter pathFormatter
     , HttpClient httpClient
     , IQueryParser queryParser
     , GalleryModel galleryModel
     , DetailsModel detailsModel
     , GalleryDownloader galleryDownloader)
 {
     LibraryModel              = libraryModel;
     MainViewTabControl        = mainViewTabControl;
     LibraryBrowserViewTabPage = libraryBrowserViewTabPage;
     GalleryBrowserViewTabPage = galleryBrowserViewTabPage;
     CacheSettings             = cacheSettings;
     SearchResultCache         = searchResultCache;
     Logger            = logger;
     BrowsingModel     = browsingModel;
     PathFormatter     = pathFormatter;
     HttpClient        = httpClient;
     QueryParser       = queryParser;
     GalleryModel      = galleryModel;
     DetailsModel      = detailsModel;
     GalleryDownloader = galleryDownloader;
 }
Exemple #7
0
 protected void ShowEditorForm()
 {
     EditorFormTitle      = "CREATE";
     this.model           = new LibraryModel();
     this.model.ParentKey = ParentKey; //
     EditorFormReference.Show();
 }
Exemple #8
0
        public ActionResult Index(LibraryModel model, HttpPostedFileBase pdfFile)
        {
            bool exists = System.IO.Directory.Exists(Server.MapPath("~/LibraryPDFFiles/"));

            if (!exists)
            {
                System.IO.Directory.CreateDirectory(Server.MapPath("~/LibraryPDFFiles/"));
            }

            string fileName, fileExistence = string.Empty;
            string destinationPath = string.Empty;

            fileName            = Path.GetFileName(pdfFile.FileName);
            fileExistence       = Path.GetExtension(pdfFile.FileName);
            destinationPath     = Path.Combine(Server.MapPath("~/LibraryPDFFiles/"), model.LibraryName + fileExistence);
            model.FileExistence = Path.GetExtension(pdfFile.FileName);
            pdfFile.SaveAs(destinationPath);

            library.FileExistence = fileExistence;
            library.FilePath      = destinationPath;
            library.FileTypeId    = model.FileTypeId;
            library.LibraryID     = model.LibraryID;
            library.LibraryName   = model.LibraryName;

            actionResult = libraryAction.Library_AddEdit(library);
            if (actionResult.IsSuccess)
            {
                TempData["SuccessMessage"] = " Library Details Successfully Saved !!";
            }
            else
            {
                TempData["ErrorMessage"] = "Error in Request !!";
            }
            return(RedirectToAction("Index"));
        }
Exemple #9
0
        public void Test_AddingBook()
        {
            LibraryModel model    = new LibraryModel();
            Book         testbook = model.AddBook(1, "Pan Tadeusz", "Adam Mickiewicz");

            Assert.AreEqual(1, model.ListBooks.Count);
        }
Exemple #10
0
        public async Task <IActionResult> AddorEdit(int id, [Bind("BookID,BookName,Author,Pages,Read,Rating,Date")] LibraryModel libraryModel)
        {
            if (ModelState.IsValid)
            {
                //Insert
                if (id == 0)
                {
                    libraryModel.Date = DateTime.Now;
                    _context.Add(libraryModel);
                    await _context.SaveChangesAsync();
                }
                else
                {
                    try
                    {
                        _context.Update(libraryModel);
                        await _context.SaveChangesAsync();
                    }
                    catch (DbUpdateConcurrencyException)
                    {
                        if (!LibraryModelExists(libraryModel.BookID))
                        {
                            return(NotFound());
                        }
                        else
                        {
                            throw;
                        }
                    }
                }

                return(Json(new { isValid = true, html = Helper.RenderRazorViewToString(this, "_ViewAll", _context.Library.ToList()) }));
            }
            return(Json(new { isValid = false, html = Helper.RenderRazorViewToString(this, "AddorEdit", libraryModel) }));
        }
Exemple #11
0
        public void Test_EmptyCollection()
        {
            LibraryModel model = new LibraryModel();

            Assert.AreEqual(0, model.ListBooks.Count);
            Assert.AreEqual(0, model.ListReaders.Count);
        }
 /// <summary>
 ///		Abre el formulario de modificación / creación de una biblioteca
 /// </summary>
 private void OpenFormUpdateLibrary(LibraryModel library, LibraryModel libraryParent)
 {
     if (BookLibraryViewModel.Instance.ViewsController.OpenUpdateLibrary(new LibraryViewModel(library, libraryParent)) == SystemControllerEnums.ResultType.Yes)
     {
         Refresh();
     }
 }
Exemple #13
0
 /// <summary>
 ///		Carga un archivo
 /// </summary>
 public bool Load(string fileName, out string error)
 {
     // Inicializa los argumentos de salida
     error = "";
     // Inicializa el juego
     Library = new LibraryModel();
     // Carga el juego
     if (!string.IsNullOrEmpty(fileName) && System.IO.File.Exists(fileName))
     {
         // Carga el juego
         try
         {
             // Carga el juego
             Library = LoadLibrary(fileName);
             // Asigna el nombre de archivo
             FullFileName = fileName;
             FileName     = System.IO.Path.GetFileName(fileName);
         }
         catch (Exception exception)
         {
             error = $"Error al cargar el juego: {exception.Message}";
         }
     }
     else
     {
         error = $"No existe el archivo: {fileName}";
     }
     // y lo muestra (lo hace fuera del try porque debe crear el modelo vacío)
     ConvertToViewModel(Library);
     // Devuelve el valor que indica si los datos son correctos
     return(string.IsNullOrEmpty(error));
 }
        public async Task <ComicFile[]> SearchFiles(LibraryModel library)
        {
            try
            {
                if (!await this.HasStoragePermission())
                {
                    return(null);
                }

                var fileList = await this.FileSystem.GetFiles(new Folder { FullPath = library.Path });

                var result = fileList.Select(file => new ComicFile
                {
                    Key        = file.FileKey,
                    LibraryKey = library.ID,
                    FilePath   = file.FilePath,
                    FolderPath = file.FolderPath.Replace($"{library.Path}{this.FileSystem.PathSeparator}", ""),
                    FullText   = file.Text,
                    SmallText  = file.Text.Replace(System.IO.Path.GetFileNameWithoutExtension(file.FolderPath), ""),
                    CachePath  = $"{Helpers.Constants.FilesCachePath}{file.FileKey}"
                })
                             .ToArray();

                return(result);
            }
            catch (Exception ex) { await App.ShowMessage(ex); return(null); }
        }
Exemple #15
0
        private void FilterComboBox_KeyDown(object sender, KeyEventArgs e)
        {
            ToolStripComboBox comboBox = sender as ToolStripComboBox;

            if (e.KeyCode == Keys.Return)
            {
                SubmitFilter();

                e.Handled          = true;
                e.SuppressKeyPress = true;
            }
            else if (e.KeyCode == Keys.Delete)
            {
                if (comboBox.SelectedIndex != -1)
                {
                    // FIXME: this crashes sometimes.

                    LibraryModel.RemoveFilter(comboBox.SelectedItem as string);
                    //comboBox.Items.RemoveAt(comboBox.SelectedIndex);

                    e.Handled          = true;
                    e.SuppressKeyPress = true;
                }
            }
        }
Exemple #16
0
        private async Task <string> LoadDataAsync_GetFileID(LibraryModel library)
        {
            try
            {
                // LIBRARY FILE ALREADY DEFINED
                var fileID = library.GetKeyValue(SYNC_FILE_ID);
                if (!string.IsNullOrEmpty(fileID))
                {
                    return(fileID);
                }

                // TRY TO SEARCH ON FOLDER
                var folder = new FileData {
                    id = library.Key
                };
                var fileList = await this.Connector.SearchFilesAsync(folder, LibraryModel.SyncFile, 100);

                if (fileList == null || fileList.Count == 0)
                {
                    return(string.Empty);
                }
                var file = fileList.Where(x => x.parentID == library.Key).FirstOrDefault();
                if (file == null)
                {
                    return(string.Empty);
                }

                // RESULT
                return(file.id);
            }
            catch (Exception) { throw; }
        }
Exemple #17
0
        public async Task <bool> SaveSyncData(LibraryModel library, byte[] serializedValue)
        {
            try
            {
                using (var serializedStream = new System.IO.MemoryStream(serializedValue))
                {
                    var syncFile = new FileData {
                        FileName = LibraryModel.SyncFile
                    };

                    // SYNC FILE PREVIOUSLY SAVED
                    syncFile.id = library.GetKeyValue(SYNC_FILE_ID);

                    // SET THE MAIN FOLDER WHERE THE FILE MUST BE CREATED
                    if (string.IsNullOrEmpty(syncFile.id))
                    {
                        syncFile.parentID = library.Key;
                    }

                    // UPLOAD CONTENT
                    syncFile = await this.Connector.UploadAsync(syncFile, serializedStream);

                    if (string.IsNullOrEmpty(syncFile.id))
                    {
                        return(false);
                    }

                    // STORE THE LIBRARY FILE ID
                    library.SetKeyValue(SYNC_FILE_ID, syncFile.id);
                    return(true);
                }
            }
            catch (Exception ex) { Helpers.AppCenter.TrackEvent(ex); return(false); }
        }
Exemple #18
0
        public async Task <IActionResult> GameToLibrary(int gameId)
        {
            var userName = HttpContext.User.Identity.Name;
            var userId   = await _db.Users.Where(u => u.UserName == userName).Select(u => u.Id).FirstOrDefaultAsync();

            if (userName != null)
            {
                var library = await(
                    from lib in _db.Libraries
                    where lib.GameId == gameId
                    join usr in _db.Users on lib.UserId equals usr.Id
                    select new LibraryModel
                {
                    Id     = lib.Id,
                    UserId = lib.UserId,
                    GameId = lib.GameId
                }
                    ).AsNoTracking().FirstOrDefaultAsync();

                if (library == null)
                {
                    var gameToAdd = new LibraryModel
                    {
                        GameId = gameId,
                        UserId = userId
                    };
                    await _db.Libraries.AddAsync(gameToAdd);

                    await _db.SaveChangesAsync();
                }
            }

            return(RedirectToAction("Index"));
        }
        public async Task <LibraryModel> NewLibrary()
        {
            try
            {
                if (!await this.HasStoragePermission())
                {
                    return(null);
                }

                var initialFolder = await this.FileSystem.GetRootPath();

                var selectedFolder = await Selector.GetFolder(initialFolder, async (folder) =>
                {
                    return(await this.FileSystem.GetFolders(folder));
                });

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

                var library = new LibraryModel
                {
                    Key         = selectedFolder.Key,
                    Path        = selectedFolder.FullPath,
                    Description = selectedFolder.Name,
                    Type        = LibraryType.LocalDrive
                };
                return(library);
            }
            catch (Exception ex) { await App.ShowMessage(ex); return(null); }
        }
Exemple #20
0
 protected void EditBy(LibraryModel model)
 {
     EditorFormTitle      = "EDIT";
     this.model           = new LibraryModel();
     this.model           = model;
     this.model.ParentKey = ParentKey; //
     EditorFormReference.Show();
 }
Exemple #21
0
        public void Test_AddingReader()
        {
            LibraryModel model      = new LibraryModel();
            Reader       testreader = model.AddReader(1, "Iwona", "Wołkowicz");

            Assert.AreEqual(1, model.ListReaders.Count);
            Assert.AreSame(testreader, model.ListReaders[0]);
        }
Exemple #22
0
        public void Test_RemoveReader()
        {
            LibraryModel model      = new LibraryModel();
            Reader       testreader = model.AddReader(1, "Marcin", "Wołkowicz");

            model.RemoveReader(1);
            Assert.AreEqual(0, model.ListReaders.Count);
        }
 public LibraryViewModel()
 {
     windowManager            = WindowManager.Instance;
     libraryModel             = new LibraryModel();
     addBookCommand           = null;
     removeFromLibraryCommand = null;
     openBookCommand          = null;
     RefreshLibrary();
 }
Exemple #24
0
 public LibraryView()
 {
     InitializeComponent();
     libraryModel             = new LibraryModel();
     addBookCommand           = null;
     removeFromLibraryCommand = null;
     openBookCommand          = null;
     RefreshLibrary();
 }
 public LibraryViewModel(LibraryModel library, LibraryModel libraryParent)
 {
     _library       = library;
     _libraryParent = libraryParent;
     if (_library == null)
     {
         _library = new LibraryModel();
     }
     InitProperties();
 }
Exemple #26
0
        public void Test_DropOffBook()
        {
            LibraryModel model      = new LibraryModel();
            Book         testbook   = model.AddBook(1, "Pan Tadeusz", "Adam Mickiewicz");
            Reader       testreader = model.AddReader(1, "Marcin", "Wołkowicz");

            model.BorrowBook(1, 1);
            model.DropOffBook(1);
            Assert.AreEqual(0, testreader.Books.Count);
        }
Exemple #27
0
 /// <summary>
 /// Closing window logic
 /// </summary>
 /// <param name="sender">The source of the event</param>
 /// <param name="e">The instance containing the event data</param>
 private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
 {
     if (LibraryModel.AreItemsRemoved() || LibraryModel.AreItemsUpdated())
     {
         if (MessageBox.Show("All unsaved changes will be lost. Are you sure you want to exit?", "Exit Program", MessageBoxButton.YesNo) == MessageBoxResult.No)
         {
             e.Cancel = true;
         }
     }
 }
Exemple #28
0
 public static LibraryView Map(this LibraryModel source)
 => source == null ? null : new LibraryView
 {
     Name                = source.Name,
     OwnerEmail          = source.OwnerEmail,
     Language            = source.Language,
     SupportsPeriodicals = source.SupportsPeriodicals,
     PrimaryColor        = source.PrimaryColor,
     SecondaryColor      = source.SecondaryColor
 };
Exemple #29
0
        protected async void ToggleClick()
        {
            this.model.IsPinned = (this.model?.IsPinned == true) ? false : true;

            await UploadRepositoryAsyncReference.EditAsync(this.model);

            IsInlineDialogShow = false;
            this.model         = new LibraryModel();
            await DisplayData();
        }
Exemple #30
0
        public async Task <ComicFile[]> SearchFiles(LibraryModel library)
        {
            try
            {
                // DEFINE ROOT FOLDER
                var rootFolder = new FileData
                {
                    id       = library.Key,
                    FilePath = library.Path,
                    FileName = library.Description
                };

                // LOCATE ALL CHILDREN FILES
                // var fileList = await this.Connector.SearchFilesAsync(rootFolder, "*.cbz", 10000);
                var fileList = await this.SearchFiles(rootFolder);

                // CONVERT
                var comicFiles = fileList
                                 .Select(file => new ComicFile
                {
                    LibraryKey  = library.ID,
                    Key         = file.id,
                    FilePath    = $"{file.FilePath.Replace("/ /", "/")}/{file.FileName}",
                    FolderPath  = file.FilePath.Replace("/ /", "/"),
                    ReleaseDate = (!file.CreatedDateTime.HasValue ? DateTime.MinValue : file.CreatedDateTime.Value.ToLocalTime()),
                    KeyValues   = new Dictionary <string, string> {
                        { "StreamSize", $"{(file.Size.HasValue ? file.Size.Value : 0)}" }
                    },
                    CachePath = $"{Helpers.Constants.FilesCachePath}{file.id}"
                })
                                 .ToList();

                // TEXT
                foreach (var comicFile in comicFiles)
                {
                    comicFile.FullText = System.IO.Path.GetFileNameWithoutExtension(comicFile.FilePath).Trim();
                    if (!string.IsNullOrEmpty(rootFolder.FilePath) && !string.IsNullOrEmpty(comicFile.FolderPath))
                    {
                        comicFile.FolderPath = comicFile.FolderPath.Replace(rootFolder.FilePath.Replace("/ / ", "/"), "").Trim();
                    }
                    var folderText = System.IO.Path.GetFileNameWithoutExtension(comicFile.FolderPath);
                    if (!string.IsNullOrEmpty(folderText))
                    {
                        comicFile.SmallText = comicFile.FullText.Replace(folderText, "");
                    }
                    if (string.IsNullOrEmpty(comicFile.SmallText))
                    {
                        comicFile.SmallText = comicFile.FullText;
                    }
                }

                return(comicFiles.ToArray());
            }
            catch (Exception ex) { await App.ShowMessage(ex); return(null); }
        }
Exemple #31
0
 public LibraryViewModel()
 {
     model = new LibraryModel();
 }