/// <summary>
        /// Invoked when this page is about to be displayed in a Frame.
        /// </summary>
        /// <param name="e">Event data that describes how this page was reached.
        /// This parameter is typically used to configure the page.</param>
        protected override async void OnNavigatedTo(NavigationEventArgs e)
        {
            this._navigationhelper.OnNavigatedTo(e);

            _fileViewModel = Resources["filesSource"] as FileViewModel;
            _saveFile = Resources["saveFileSource"] as FileModel;

            _fileViewModel.Clear();
            var task1 = _fileViewModel.GetStorageFolder();
            var task2 = _fileViewModel.GetFiles();
            await Task.WhenAll(task1, task2);
            
            var savefile = e.Parameter as FileModel;
            if (savefile != null)
            {
                _saveFile.Name = savefile.Name;
                _saveFile.Content = savefile.Content;
            }
            else
            {
                savePanel.Visibility = Visibility.Collapsed;
            }
            if (nameText.IsReadOnly == true)
            {
                nameText.IsReadOnly = false;                
            }

        }
Example #2
0
 public ActionResult Delete(FileViewModel model)
 {
     if (!IoC.Resolve<IFileBrowserCommands>()
         .DeleteFile(User.Identity.Name, model.Ident))
     {
         ModelState.AddModelError(string.Empty, vlko.BlogModule.ModelResources.FileDeleteFailedError);
         return ViewWithAjax(model);
     }
     return RedirectToActionWithAjax("Index");
 }
        public override int Compare(FileViewModel x, FileViewModel y)
        {
            var a = this.ExtractNumber(x.FileName);
            var b = this.ExtractNumber(y.FileName);

            if (a.Item1 == b.Item1)
                return a.Item2.CompareTo(b.Item2);

            return a.Item1.CompareTo(b.Item1);
        }
 public ActionResult UploadFile(FileViewModel model, HttpPostedFileBase upload)
 {
     if (upload != null && upload.ContentLength > 0)
     {
         byte[] content = null;
         using (var reader = new BinaryReader(upload.InputStream))
         {
             content = reader.ReadBytes(upload.ContentLength);
         }
         _files.SetAvatar(model.UserId, Path.GetFileName(upload.FileName), upload.ContentType, content);
     }
     return RedirectToAction("FileList", new { userId = model.UserId });
 }
Example #5
0
        public DirectoryViewModel(string path, ITreeNode parrent = null, IObservableCollection<FileViewModel> allFiles = null, SynchronizationContext synchronizationContext = null)
        {
            if (synchronizationContext == null)
              {
            if (parrent is DirectoryViewModel)
              synchronizationContext = ((DirectoryViewModel)parrent).m_synchronizationContext;
            if (synchronizationContext == null)
              synchronizationContext = SynchronizationContext.Current;
              }
              Debug.Assert(synchronizationContext != null, "SynchronizationContext should not be null");
              m_synchronizationContext = synchronizationContext;

              m_children = new SortedObservableCollection<ITreeNode>(new AsyncObservableCollection<ITreeNode>(synchronizationContext),
                          (node, treeNode) => (String.Compare(node.Name, treeNode.Name, StringComparison.Ordinal) + (node is DirectoryViewModel ? -1000 : 0) + (treeNode is DirectoryViewModel ? 1000 : 0)), m_synchronizationContext);
              m_path = path;
              m_parrent = parrent;
              m_name = System.IO.Path.GetFileName(path);
              if (!Directory.Exists(path))
            return;
              if (allFiles == null)
              {
            m_allFiles = new SortedObservableCollection<FileViewModel>(new AsyncObservableCollection<FileViewModel>(), (model, viewModel) => String.Compare(model.Name, viewModel.Name, StringComparison.Ordinal));
            allFiles = AllFiles;
              }
              foreach (string directory in Directory.GetDirectories(path))
            Children.Add(new DirectoryViewModel(directory, this, allFiles, m_synchronizationContext));
              foreach (string file in Directory.GetFiles(path))
              {
            FileViewModel fileViewModel = new FileViewModel(file, this);
            Children.Add(fileViewModel);
            allFiles.Add(fileViewModel);
              }
              if (parrent == null)
              {
            m_externalChanges = new Dictionary<string, DateTime>();
            m_fileSystemWatcher = new FileSystemWatcher(path)
            {
              NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.LastWrite,
              IncludeSubdirectories = true
            };

            m_fileSystemWatcher.Created += FileSystemWatcherOnCreated;
            m_fileSystemWatcher.Deleted += FileSystemWatcherOnDeleted;
            m_fileSystemWatcher.Changed += FileSystemWatcherOnChanged;
            m_fileSystemWatcher.Renamed += FileSystemWatcherOnRenamed;

            m_fileSystemWatcher.EnableRaisingEvents = true;
            m_cleanUpTimer = new Timer(ClanUp, null, 5000, Timeout.Infinite);
              }
        }
Example #6
0
        public DirectoryViewModel FolderInfo(string dir)
        {
            try
            {
                string currentFolderName = dir;
                if (!string.IsNullOrEmpty(currentFolderName) && currentFolderName != "/")
                {
                    currentFolderName = Path.GetFileName(dir);
                }

                DirectoryViewModel        directoryModel = new DirectoryViewModel(currentFolderName, dir);
                CloudBlobContainer        container      = GetCloudBlobContainer();
                CloudBlobDirectory        azureDirectory = container.GetDirectoryReference(dir);
                List <CloudBlobDirectory> directories    = azureDirectory.ListBlobs()
                                                           .Select(b => b as CloudBlobDirectory)
                                                           .Where(b => b != null)
                                                           .ToList();

                List <CloudBlockBlob> files = azureDirectory.ListBlobs()
                                              .OfType <CloudBlockBlob>()
                                              .Where(b => !FilesToExclude.Contains(Path.GetFileName(b.Name)))
                                              .ToList();

                foreach (CloudBlobDirectory directory in directories)
                {
                    string dirName = directory.Prefix.TrimEnd('/');
                    dirName = dirName.Replace(directory.Parent.Prefix, String.Empty);
                    DirectoryViewModel childModel = new DirectoryViewModel(dirName, directory.Prefix.TrimEnd('/'));
                    directoryModel.ChildFolders.Add(childModel);
                }

                foreach (CloudBlockBlob file in files)
                {
                    file.FetchAttributes();
                    string        filename  = file.Name;
                    FileViewModel fileModel = new FileViewModel(Path.GetFileName(file.Name), Path.GetExtension(file.Name).Replace(".", ""), file.Properties.Length, ((DateTimeOffset)file.Properties.LastModified).DateTime, dir);
                    directoryModel.Files.Add(fileModel);
                }


                return(directoryModel);
            }
            catch (StorageException e)
            {
                throw new FileException(e.Message, e);
            }
        }
Example #7
0
        public async Task <FilesViewModel> BuildModelAsync(FilesComponentModel componentModel)
        {
            if (componentModel.Files != null)
            {
                var files = await this.mediaRepository.GetMediaItemsAsync(componentModel.Files, componentModel.Language, PaginationConstants.DefaultPageIndex, PaginationConstants.DefaultPageSize, componentModel.Token);

                if (files != null)
                {
                    var filesViewModel = new FilesViewModel
                    {
                        NameLabel             = this.globalLocalizer.GetString("Name"),
                        FilenameLabel         = this.globalLocalizer.GetString("Filename"),
                        DescriptionLabel      = this.globalLocalizer.GetString("Description"),
                        SizeLabel             = this.globalLocalizer.GetString("Size"),
                        DownloadFilesLabel    = this.globalLocalizer.GetString("FilesToDownload"),
                        DownloadLabel         = this.globalLocalizer.GetString("Download"),
                        CopyLinkLabel         = this.globalLocalizer.GetString("CopyLink"),
                        CreatedDateLabel      = this.globalLocalizer.GetString("CreatedDate"),
                        LastModifiedDateLabel = this.globalLocalizer.GetString("LastModifiedDate")
                    };

                    var fileViewModels = new List <FileViewModel>();

                    foreach (var file in files.Data.OrEmptyIfNull())
                    {
                        var fileViewModel = new FileViewModel
                        {
                            Name             = file.Name,
                            Filename         = file.Filename,
                            Url              = this.mediaHelperService.GetFileUrl(this.options.Value.MediaUrl, file.Id),
                            Description      = file.Description ?? "-",
                            IsProtected      = file.IsProtected,
                            Size             = string.Format("{0:0.00} MB", file.Size / 1024f / 1024f),
                            LastModifiedDate = file.LastModifiedDate,
                            CreatedDate      = file.CreatedDate
                        };

                        fileViewModels.Add(fileViewModel);
                    }

                    filesViewModel.Files = fileViewModels;

                    return(filesViewModel);
                }
            }

            return(default);
Example #8
0
        public bool SaveFile(FileViewModel file)
        {
            try
            {
                if (!string.IsNullOrEmpty(file.Filename))
                {
                    CreateDirectoryIfNotExist(file.FileFolder);

                    string fileName = $"{file.Filename}{file.Extension}";
                    if (!string.IsNullOrEmpty(file.FileFolder))
                    {
                        fileName = CommonHelper.GetFullPath(new string[] { file.FileFolder, fileName });
                    }
                    if (File.Exists(fileName))
                    {
                        DeleteFile(fileName);
                    }
                    if (!string.IsNullOrEmpty(file.Content))
                    {
                        using (var writer = File.CreateText(fileName))
                        {
                            writer.WriteLine(file.Content); //or .Write(), if you wish
                            writer.Dispose();
                            return(true);
                        }
                    }
                    else
                    {
                        string base64 = file.FileStream.Split(',')[1];
                        byte[] bytes  = Convert.FromBase64String(base64);
                        using (var writer = File.Create(fileName))
                        {
                            writer.Write(bytes, 0, bytes.Length);
                            return(true);
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Example #9
0
        public bool SaveWebFile(FileViewModel file)
        {
            try
            {
                string fullPath = CommonHelper.GetFullPath(new string[] {
                    SWCmsConstants.Parameters.WebRootPath,
                    SWCmsConstants.Parameters.FileFolder,
                    file.FileFolder
                });
                if (!string.IsNullOrEmpty(file.Filename))
                {
                    CreateDirectoryIfNotExist(fullPath);

                    string fileName = SwCmsHelper.GetFullPath(new string[] { fullPath, file.Filename + file.Extension });
                    if (File.Exists(fileName))
                    {
                        DeleteFile(fileName);
                    }
                    if (string.IsNullOrEmpty(file.FileStream))
                    {
                        using (var writer = File.CreateText(fileName))
                        {
                            writer.WriteLine(file.Content); //or .Write(), if you wish
                            return(true);
                        }
                    }
                    else
                    {
                        string base64 = file.FileStream.Split(',')[1];
                        byte[] bytes  = Convert.FromBase64String(base64);
                        using (var writer = File.Create(fileName))
                        {
                            writer.Write(bytes, 0, bytes.Length);
                            return(true);
                        }
                    }
                }
                else
                {
                    return(false);
                }
            }
            catch
            {
                return(false);
            }
        }
Example #10
0
        public async Task <RepositoryResponse <string> > Export(int id, [FromBody] SiteStructureViewModel data)
        {
            var getTheme = await ReadViewModel.Repository.GetSingleModelAsync(
                theme => theme.Id == id).ConfigureAwait(false);

            //path to temporary folder
            string tempPath   = $"wwwroot/Exports/Themes/{getTheme.Data.Name}/temp";
            string outputPath = $"Exports/Themes/{getTheme.Data.Name}";

            data.ThemeName = getTheme.Data.Name;
            string filename = $"schema";
            var    file     = new FileViewModel()
            {
                Filename   = filename,
                Extension  = ".json",
                FileFolder = $"{tempPath}/Data",
                Content    = JObject.FromObject(data).ToString()
            };

            // Delete Existing folder
            FileRepository.Instance.DeleteFolder(outputPath);
            // Copy current templates file
            FileRepository.Instance.CopyDirectory($"{getTheme.Data.TemplateFolder}", $"{tempPath}/Templates");
            // Copy current assets files
            FileRepository.Instance.CopyDirectory($"wwwroot/{getTheme.Data.AssetFolder}", $"{tempPath}/Assets");
            // Copy current uploads files
            FileRepository.Instance.CopyDirectory($"wwwroot/{getTheme.Data.UploadsFolder}", $"{tempPath}/Uploads");
            // Save Site Structures
            FileRepository.Instance.SaveFile(file);

            // Zip to [theme_name].zip ( wwwroot for web path)
            string filePath = FileRepository.Instance.ZipFolder($"{tempPath}", outputPath, $"{getTheme.Data.Name}-{Guid.NewGuid()}");



            // Delete temp folder
            FileRepository.Instance.DeleteWebFolder($"{outputPath}/Assets");
            FileRepository.Instance.DeleteWebFolder($"{outputPath}/Uploads");
            FileRepository.Instance.DeleteWebFolder($"{outputPath}/Templates");
            FileRepository.Instance.DeleteWebFolder($"{outputPath}/Data");

            return(new RepositoryResponse <string>()
            {
                IsSucceed = !string.IsNullOrEmpty(outputPath),
                Data = $"{HttpContext.Request.Scheme}://{HttpContext.Request.Host}/{filePath}"
            });
        }
 public static void FetchIcon(FileViewModel file)
 {
     if (IsFetchingIcons)
     {
         lock (IncommingFetcherPool)
         {
             IncommingFetcherPool.Add(file);
         }
     }
     else
     {
         lock (FetcherPool)
         {
             FetcherPool.Add(file);
         }
     }
 }
Example #12
0
        public FileViewModel GetFile(string name, string ext, string FileFolder, bool isCreate = false, string defaultContent = "")
        {
            FileViewModel result = null;

            string fullPath = Path.Combine(CurrentDirectory, FileFolder, string.Format("{0}{1}", name, ext));

            FileInfo file = new FileInfo(fullPath);

            if (file.Exists)
            {
                try
                {
                    using (StreamReader s = file.OpenText())
                    {
                        result = new FileViewModel()
                        {
                            FileFolder = FileFolder,
                            Filename   = name,
                            Extension  = ext,
                            Content    = s.ReadToEnd()
                        };
                    }
                }
                catch
                {
                    // File invalid
                }
            }
            else if (isCreate)
            {
                file.Create();
                result = new FileViewModel()
                {
                    FileFolder = FileFolder,
                    Filename   = name,
                    Extension  = ext,
                    Content    = defaultContent
                };
                SaveFile(result);
            }

            return(result ?? new FileViewModel()
            {
                FileFolder = FileFolder
            });
        }
Example #13
0
        public ActionResult UploadFile(FileViewModel model)
        {
            // ファイルが既にアップロード済みの場合、使いまわす
            if (!string.IsNullOrEmpty(model.FileName))
            {
                var fileInfo = businessService.CreateUploadFileInfo(HttpContext, model.FileName);
                if (fileInfo.Exists)
                {
                    return(CreateSuccessResult(model.FileName));
                }
            }

            // アップロードされたファイルをサーバに保存する
            var fileName = fileService.SaveUploadedFileToServer(HttpContext, Request.Files[0], model.ScreenId, model.ItemId);

            return(CreateSuccessResult(fileName));
        }
Example #14
0
        public IActionResult Post(FileViewModel file)
        {
            var serializedContent = System.Text.Json.JsonSerializer.Serialize(
                file,
                new System.Text.Json.JsonSerializerOptions {
                WriteIndented = true
            }
                );

            var messageBodyBytes = System.Text.Encoding.UTF8.GetBytes(serializedContent);

            var prop = rabbitMQModel.CreateBasicProperties();

            rabbitMQModel.BasicPublish("", "s3", prop, messageBodyBytes);

            return(Ok("Success"));
        }
        public IActionResult RemoveFile(int id, string idFileProperty)
        {
            var fileViewModel = new FileViewModel()
            {
                Id = idFileProperty
            };

            var file = Context.Files.FirstOrDefault(w => w.Id == id);

            if (file != null)
            {
                Context.Files.Remove(file);
                Context.SaveChanges();
            }

            return(View("File", fileViewModel));
        }
Example #16
0
        public ActionResult Search(string searchString)
        {
            int id    = (int)Session["userID"];
            var model = new FileViewModel();

            model.fileMetadataList = (from file in db.Files
                                      where file.userID == id &&
                                      file.fileName.Contains(searchString)
                                      select new FileMetadata()
            {
                fileID = file.FileID,
                fileName = file.fileName,
                fileSize = file.fileSize,
                fileDateCreated = file.fileDateCreated,
            }).ToList();
            return(View(model));
        }
        public IActionResult Files()
        {
            var model = new FileViewModel();

            foreach (var item in
                     this.fileProvider.GetDirectoryContents(""))
            {
                model.Files.Add(
                    new FileDetails
                {
                    Name = item.Name,
                    Path =
                        item.PhysicalPath
                });
            }
            return(View(model));
        }
Example #18
0
 public List <FileViewModel> GetFiles(string fullPath)
 {
     this.CreateDirectoryIfNotExist(fullPath);
     V_0 = new List <FileViewModel>();
     V_1 = Directory.GetDirectories(fullPath, "*", 1);
     V_2 = 0;
     while (V_2 < (int)V_1.Length)
     {
         stackVariable15 = new DirectoryInfo(V_1[V_2]);
         V_3             = stackVariable15.get_Name();
         stackVariable17 = stackVariable15.GetFiles();
         stackVariable18 = FileRepository.u003cu003ec.u003cu003e9__30_0;
         if (stackVariable18 == null)
         {
             dummyVar0       = stackVariable18;
             stackVariable18 = new Func <FileInfo, DateTime>(FileRepository.u003cu003ec.u003cu003e9.u003cGetFilesu003eb__30_0);
             FileRepository.u003cu003ec.u003cu003e9__30_0 = stackVariable18;
         }
         V_4 = ((IEnumerable <FileInfo>)stackVariable17).OrderByDescending <FileInfo, DateTime>(stackVariable18).GetEnumerator();
         try
         {
             while (V_4.MoveNext())
             {
                 V_5 = V_4.get_Current();
                 V_6 = new FileViewModel();
                 V_6.set_FolderName(V_3);
                 stackVariable31    = new string[2];
                 stackVariable31[0] = fullPath;
                 stackVariable31[1] = V_3;
                 V_6.set_FileFolder(CommonHelper.GetFullPath(stackVariable31));
                 V_6.set_Filename(V_5.get_Name().Substring(0, V_5.get_Name().LastIndexOf('.')));
                 V_6.set_Extension(V_5.get_Extension());
                 V_0.Add(V_6);
             }
         }
         finally
         {
             if (V_4 != null)
             {
                 V_4.Dispose();
             }
         }
         V_2 = V_2 + 1;
     }
     return(V_0);
 }
        public FileViewModel GetWebFile(string filename, string folder)
        {
            string fullPath = CommonHelper.GetFullPath(new string[]
            {
                SWCmsConstants.Parameters.WebRootPath,
                SWCmsConstants.Parameters.FileFolder,
                folder,
                filename
            });
            string folderPath = CommonHelper.GetFullPath(new string[]
            {
                SWCmsConstants.Parameters.WebRootPath,
                SWCmsConstants.Parameters.FileFolder,
                folder
            });
            FileInfo      file   = new FileInfo(fullPath);
            FileViewModel result = null;

            if (file != null)
            {
                try
                {
                    DirectoryInfo path = new DirectoryInfo(folderPath);
                    using (StreamReader s = file.OpenText())
                    {
                        result = new FileViewModel()
                        {
                            FolderName = path.Name,
                            FileFolder = folder,
                            Filename   = file.Name.Substring(0, file.Name.LastIndexOf('.')),
                            Extension  = file.Extension,
                            Content    = s.ReadToEnd()
                        };
                    }
                }
                catch
                {
                    // File invalid
                }
            }

            return(result ?? new FileViewModel()
            {
                FileFolder = folder
            });
        }
        private async Task <FileViewModel> GetFileInfo(IFormFile file)
        {
            var request    = this.httpContextAccessor.HttpContext.Request;
            var uriBuilder = new UriBuilder
            {
                Scheme = request.Scheme,
                Host   = request.Host.Host,
                Path   = request.Path.ToString()
            };
            var uri = uriBuilder.Uri;

            var           stream             = file.OpenReadStream();
            var           fileName           = file.FileName;
            var           hostingEnvironment = this.environment;
            FileViewModel info = null;

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

            var path = this.configuracion?.Configuration <string>("UploadsPath");


            var filePath        = Path.Combine(path, fileName);
            var ext             = Path.GetExtension(filePath);
            var fileNameDestino = $"{DateTime.Now: ddMMyyyHHmmssfffffff}{ext}".Trim();

            filePath = Path.Combine(path, fileNameDestino);

            using (var newFile = new FileStream(filePath, FileMode.Create))
            {
                await stream.CopyToAsync(newFile)
                .ConfigureAwait(false);
            }

            info = new FileViewModel
            {
                FechaActualizacion = DateTime.Now,
                NombreOrigen       = fileName,
                NombreDestino      = fileNameDestino,
                Url = uri.ToString()
            };

            return(info);
        }
Example #21
0
 public async Task<ActionResult> UploadFile(OrderViewModel order)
 {
     FileViewModel fileViewModel = new FileViewModel();
     fileViewModel.OrderId = order.Id;
     fileViewModel.PostedFile = order.PostedFile;           
     FileDTO fileDTO = _mapper.Map<FileViewModel, FileDTO>(fileViewModel);
     ServerRequest result = await _fileStorageService.UploadFileAsync(fileDTO);
     if (!result.ErrorOccured)
     {
         return RedirectToAction("GetTakenOrders", "Musician");
     }
     else
     {
         ViewBag.Error = result.Message;
         return RedirectToAction("GetTakenOrders", "Musician");
     }
 }
        public static string GetChangeSummary(ManagedFile file, FileViewModel model)
        {
            var builder = new StringBuilder();

            CheckProperty("Public Name", file.PublicName, model.PublicName, builder);
            CheckProperty("Type", file.Type, model.Type, builder);
            CheckProperty("Data Type", file.KindOfData, model.KindOfData, builder);
            CheckProperty("Software", file.Software, model.Software, builder);
            CheckProperty("Software Version", file.SoftwareVersion, model.SoftwareVersion, builder);
            CheckProperty("Hardware", file.Hardware, model.Hardware, builder);
            CheckProperty("Source", file.Source, model.Source, builder);
            CheckProperty("Source Information", file.SourceInformation, model.SourceInformation, builder);
            CheckProperty("Rights", file.Rights, model.Rights, builder);
            CheckProperty("Public Access", file.IsPublicAccess ? "Yes" : "No", model.IsPublicAccess.ToString(), builder);

            return(builder.ToString());
        }
Example #23
0
        public FileStream FileViewModelToFileStream(FileViewModel file)
        {
            var bytes = Convert.FromBase64String(file.Base64);

            using FileStream fileStream = new FileStream(file.FileName, FileMode.Create);

            // Write the data to the file, byte by byte.
            for (int i = 0; i < bytes.Length; i++)
            {
                fileStream.WriteByte(bytes[i]);
            }

            // Set the stream position to the beginning of the file.
            fileStream.Seek(0, SeekOrigin.Begin);

            return(fileStream);
        }
Example #24
0
        public ActionResult AddCodeFileCurationTasks(FileViewModel model)
        {
            var logger = LogManager.GetLogger("FileController");

            using (var db = ApplicationDbContext.Create())
            {
                var user = db.Users
                           .Where(x => x.UserName == User.Identity.Name)
                           .FirstOrDefault();
                if (user == null)
                {
                    return(RedirectToAction("Index"));
                }

                if (!user.IsAdministrator)
                {
                    throw new HttpException(403, "This is only allowed for administrators.");
                }

                // Fetch the appropriate ManagedFile by ID.
                Guid id   = model.Id;
                var  file = GetFile(id, db);

                // Add the code file tasks, if needed.
                logger.Debug("Updating file tasks");
                TaskHelpers.AddProcessingTasksForFile(file, file.CatalogRecord, db, addAllCodeTasks: true);
                logger.Debug("Done updating file tasks");

                // Log the editing of the file.
                var log = new Event()
                {
                    EventType            = EventTypes.EditManagedFile,
                    Timestamp            = DateTime.UtcNow,
                    User                 = user,
                    RelatedCatalogRecord = file.CatalogRecord,
                    Title                = "Edit a File",
                    Details              = "Added code file curation tasks"
                };
                log.RelatedManagedFiles.Add(file);
                db.Events.Add(log);

                db.SaveChanges();

                return(RedirectToAction("General", new { id = file.Id }));
            }
        }
        public FileViewModel SaveFile(FileViewModel model)
        {
            var dto = new FileDto
            {
                FileId      = model.FileId,
                Name        = model.Name,
                CreatedDate = model.CreatedDate
            };
            var result = CpAbeCloud.SaveFile(dto);

            return(new FileViewModel
            {
                FileId = result.FileId,
                CreatedDate = result.CreatedDate,
                Name = result.Name
            });
        }
Example #26
0
        public ActionResult SaveFiles(FileViewModel model)
        {
            string rootPath = Server.MapPath("~/");

            string pathFile1 = Path.Combine(rootPath + "/Files/archivo1.png");
            string pathFile2 = Path.Combine(rootPath + "/Files/archivo2.png");

            if (!ModelState.IsValid)
            {
                return(View("Index", model));
            }
            model.Archivo1.SaveAs(pathFile1);
            model.Archivo2.SaveAs(pathFile2);

            TempData["Message"] = "Se cargaron los archivos exitosamente";
            return(RedirectToAction("Index"));
        }
Example #27
0
        public IActionResult Import([FromForm] FileViewModel model)
        {
            IFormFile file = model.importedFile;

            // Sollte kein File übergeben worden sein passiert nichts.
            if (file == null)
            {
                return(RedirectToAction("Cartemplates"));
            }

            //Übersetzten des Files in ein Viewmodel.
            List <VehicleExportImportViewModel> importedVehicles = service.import(file);

            // Die Liste der Autos wird aus dem Cache geladen.
            if (!cache.TryGetValue(CacheKeys.VEHICLE, out vehicles))
            {
                vehicles = new List <IVehicle>();
            }

            // Hinzufügen der Importierten Autos, sollten diese nicht im Cache sein.
            foreach (VehicleExportImportViewModel v in importedVehicles)
            {
                Vehicle vehicle = (Vehicle)v.generateVehicle();

                bool unique = true;
                foreach (IVehicle ve in vehicles)
                {
                    if (ve.id.Equals(vehicle.id))
                    {
                        unique = false;
                        break;
                    }
                }

                if (unique)
                {
                    vehicles.Add(vehicle);
                }
            }

            cache.Set(CacheKeys.VEHICLE, vehicles);
            this.model.vehicles = vehicles;

            return(View("Cartemplates", this.model));
        }
Example #28
0
        public ActionResult AddNewFile(FileViewModel viewModel)
        {
            if (ModelState.IsValid)
            {
                var path     = Server.MapPath("~/App_Data/Files");
                var fileName = Path.GetFileName(viewModel.ProjectFile.FileName);
                fileName = DateTime.Now.ToString("yyMMddHHmmss") + fileName;

                var fullPath = Path.Combine(path, fileName);

                //saving the file in the server at "full path"
                viewModel.ProjectFile.SaveAs(fullPath);

                var projectFile = new ProjectFile
                {
                    FileName  = fileName,
                    ProjectId = viewModel.ProjectId,
                    FilePath  = fullPath,
                    FileType  = viewModel.FileType
                };
                _context.ProjectFiles.Add(projectFile);
                _context.SaveChanges();

                return(RedirectToAction("Details", new { id = viewModel.ProjectId }));
            }

            IEnumerable <SelectListItem> fileTypes = new List <SelectListItem>
            {
                new SelectListItem()
                {
                    Value = "Proposal", Text = "Proposal"
                },
                new SelectListItem()
                {
                    Value = "Presentation", Text = "Presentation"
                },
                new SelectListItem()
                {
                    Value = "Others", Text = "Others"
                }
            };

            ViewBag.FileTypes = fileTypes;
            return(View(viewModel));
        }
Example #29
0
        public IActionResult Index(FileViewModel model)
        {
            var result = new Result();

            if (model.File != null)
            {
                var path = Path.Combine(_environment.ContentRootPath, model.File.FileName);
                using (var stream = new FileStream(path, FileMode.Create))
                {
                    try
                    {
                        model.File.CopyTo(stream);
                    }
                    catch (Exception ex)
                    {
                        result.Text    = ex.Message;
                        result.Success = false;
                        HttpContext.Session.SetString("result", JsonConvert.SerializeObject(result));
                        return(RedirectToAction("Result"));
                    }
                }
                var extractor = new TextExtractor();
                var watch     = Stopwatch.StartNew();
                var text      = extractor.SelectStrategy(path, model.Language);
                watch.Stop();
                if (text != null)
                {
                    System.IO.File.Delete(path);
                    result.Text          = text.Trim();
                    result.Success       = true;
                    result.ExecutionTime = watch.ElapsedMilliseconds;
                    HttpContext.Session.SetString("result", JsonConvert.SerializeObject(result));
                    return(RedirectToAction("Result"));
                }
                System.IO.File.Delete(path);
                result.Success = false;
                result.Text    = $"Supported Formats: {extractor.SupportedFormats()} {Environment.NewLine}{Environment.NewLine} Supported Languages: {extractor.SupportedLanguages()}";
                HttpContext.Session.SetString("result", JsonConvert.SerializeObject(result));
                return(RedirectToAction("Result"));
            }
            result.Success = false;
            result.Text    = "File is null";
            HttpContext.Session.SetString("result", JsonConvert.SerializeObject(result));
            return(RedirectToAction("Result"));
        }
        /// <summary>
        /// Closes the file
        /// </summary>
        /// <param name="File">File to close</param>
        public virtual void CloseFile(FileViewModel file)
        {
            if (file != null)
            {
                var args = new FileClosingEventArgs();
                args.File = file;

                FileClosing?.Invoke(this, args);

                if (!args.Cancel)
                {
                    for (var i = OpenFiles.Count - 1; i >= 0; i--)
                    {
                        if (ReferenceEquals(OpenFiles[i], file))
                        {
                            OpenFiles[i].Dispose();

                            var openFilesCount = OpenFiles.Count;
                            try
                            {
                                OpenFiles.RemoveAt(i);
                            }
                            catch (NullReferenceException)
                            {
                                // There's been a bug in a dependency where OpenFiles.RemoveAt fails because of UI stuff.
                                // If the same exception is encountered, and the file has actually been removed, then ignore it.
                                if (openFilesCount <= OpenFiles.Count) // OpenFiles.Count should have decreased by 1. If it has not, then throw the exception.
                                {
                                    throw;
                                }
                            }
                        }
                    }

                    if (ReferenceEquals(file, SelectedFile))
                    {
                        SelectedFile = null;
                    }

                    FileClosed?.Invoke(this, new FileClosedEventArgs {
                        File = file.Model
                    });
                }
            }
        }
Example #31
0
        public IActionResult AddFile([FromForm] FileViewModel file)
        {
            var redis = ConnectionMultiplexer.Connect("redis_image:6379");
            var db    = redis.GetDatabase();
            var x     = db.StringGet("user_" + file.UserGuid);

            if (x.IsNullOrEmpty)
            {
                return(this.NotFound($"Użytkownik z id {file.UserGuid} nie został znaleziony"));
            }
            byte[] fileBytes;
            if (file.PDF != null)
            {
                using (var ms = new MemoryStream())
                {
                    file.PDF.CopyTo(ms);
                    fileBytes = ms.ToArray();
                }
            }
            else if (!String.IsNullOrEmpty(file.PDFbytes))
            {
                fileBytes = Convert.FromBase64String(file.PDFbytes);
            }
            else
            {
                return(this.BadRequest());
            }
            File newFile = new File
            {
                Guid      = Guid.NewGuid().ToString(),
                FileName  = file.FileName,
                FileBytes = fileBytes,
                Links     = new List <Link>()
            };
            var serialized = JsonConvert.SerializeObject(newFile);

            db.StringSet("file_" + newFile.Guid, serialized);
            var user = JsonConvert.DeserializeObject <User>(x.ToString());

            user.Files.Add(newFile.Guid);
            var serializedU = JsonConvert.SerializeObject(user);

            db.StringSet("user_" + user.Id, serializedU);
            return(Ok(this.CreateLinksForFile(newFile, file.UserGuid)));
        }
Example #32
0
 public IActionResult Post([FromForm] FileViewModel model)
 {
     if (ModelState.IsValid && model.File != null)
     {
         if (_img.Create(model.File, out string path))
         {
             return(Ok(new FileDTO {
                 Name = path
             }));
         }
         return(BadRequest(new ErrorDTO {
             Message = "We could not add this resource. Please try again"
         }));
     }
     return(BadRequest(new ErrorDTO {
         Message = "Your data is bad"
     }));
 }
        public async Task <bool> SaveFile(FileViewModel sFile)
        {
            var result = false;

            if (!(await _repository.IsFileExists(sFile.Name)))
            {
                var file = new File()
                {
                    Name = sFile.Name,
                    Data = sFile.TextData.ToByteArray(sFile.Name, 9)
                };
                await _repository.CreateAsync(file);

                result = true;
            }

            return(result);
        }
        public async Task <FileViewModel> LoadFile(long id)
        {
            var result = default(FileViewModel);

            if (await _repository.IsEntityExists(id))
            {
                File file = await _repository.GetByIdAsync(id);

                result = new FileViewModel
                {
                    Id       = file.Id,
                    Name     = file.Name,
                    TextData = file.Data.ToStringText()
                };
            }

            return(result);
        }
Example #35
0
        /// <summary>
        /// Checks if a document can be closed and asks the user whether
        /// to save before closing if the document appears to be dirty.
        /// </summary>
        /// <param name="fileToClose"></param>
        public void Close(FileViewModel fileToClose)
        {
            if (fileToClose.IsDirty)
            {
                var res = MessageBox.Show(string.Format("Save changes for file '{0}'?", fileToClose.FileName), "AvalonDock Test App", MessageBoxButton.YesNoCancel);
                if (res == MessageBoxResult.Cancel)
                {
                    return;
                }

                if (res == MessageBoxResult.Yes)
                {
                    Save(fileToClose);
                }
            }

            _files.Remove(fileToClose);
        }
Example #36
0
        public ActionResult UploadFile(HttpPostedFileBase file, int id, int type, int loginId)
        {
            if ((file == null) || (file.ContentLength <= 0))
                return Json(new { result = false, message = "File does not exist." });
            var fileName = Path.GetFileName(file.FileName);
            var validateFile = type == (int) DocumentType.StockPicture ? _systemService.CheckValidPictureExtension(fileName) : _systemService.CheckValidExtension(fileName);
            if (!validateFile)
            {
                const string messageErrorPicture = "Invalid file. Unfortunately it was not possible to upload the file because it is not supported by our system. We are able to accept documents in the following formats: .jpg; .jpeg; .gif; .png.";
                const string messageErrorDocument = "Invalid file. Unfortunately it was not possible to upload the file because it is not supported by our system. We are able to accept documents in the following formats: .txt; .doc; .xls; .csv; .pdf; .docx; .xlsx; .jpg; .jpeg; .gif; .png.";
                var message = type == (int)DocumentType.StockPicture ? messageErrorPicture : messageErrorDocument;
                return Json(new
                {
                    result = false,
                    message
                });
            }
            // check file size
            var maxPictureSize = Convert.ToInt64(WebConfigurationManager.AppSettings["PictureSize"]);
            var maxDocumentSize = Convert.ToInt64(WebConfigurationManager.AppSettings["DocumentSize"]);
            var maxFile = type == (int) DocumentType.StockPicture ? maxPictureSize : maxDocumentSize;
            if (file.ContentLength > maxFile * 1024)
            {
                return Json(new { result = false, message = "File size is more than " + maxFile + " bytes ("+ maxFile/1024 +" Mb), cannot be uploaded" });
            }

            var fileExtend = Path.GetExtension(fileName);
            var nameUrl = Path.GetFileNameWithoutExtension(fileName) + "_" + id + "_" + DateTime.Now.ToString("ddMMyyyyHHmmss");
            var documentUrl = nameUrl + fileExtend;
            var saveLocation = type == (int)DocumentType.StockPicture ? WebConfigurationManager.AppSettings["PathImg"] : WebConfigurationManager.AppSettings["PathDoc"];
            var fullFilePath = _systemService.GetDocumentUrl(saveLocation, nameUrl, fileExtend);
            try
            {
                file.SaveAs(Server.MapPath(fullFilePath));
            }
            catch (Exception e)
            {
                return Json(new { result = false, message = e.Message });
            }

            // Save to db
            var document = _systemService.AddDocument(documentUrl, string.Empty, id, type, fileName, string.Empty, saveLocation, new byte(), loginId);
            var fileViewModel = new FileViewModel()
            {
                FileId = document.Id,
                FileGuid = documentUrl,
                FileName = fileName,
                //FileSize = Math.Round((float)file.ContentLength / 1048576, 2).ToString(),
                FileSource = fullFilePath,
                ActionDate = DateTime.Now.ToString("MM/dd/yyyy")
            };
            return Json(new { result = true, file = fileViewModel });
        }
Example #37
0
    public IFileViewModel OpenFile(string path, LayoutElementViewModel layoutElement = null, bool select = true)
    {
      IFileViewModel fileViewModel = null;
      foreach (ITreeNode treeNode in m_treeNodes.Values)
      {
        if (treeNode == null)
          continue;
        fileViewModel = treeNode.GetFile(path);
        if (fileViewModel != null)
          break;
      }
      if (fileViewModel == null)
      {
        IEditor editor = m_editorManager.BaseEditors.FirstOrDefault(n => n.Settings != null && n.Settings.Path == path);
        if (editor != null)
          fileViewModel = editor.Settings;
      }

      if (fileViewModel == null)
        fileViewModel = new FileViewModel(path);
      OpenFile(fileViewModel, layoutElement, select);
      return fileViewModel;
    }
 public override int Compare(FileViewModel x, FileViewModel y)
 {
     return String.Compare(x.FileName, y.FileName, StringComparison.InvariantCultureIgnoreCase);
 }
Example #39
0
 public IFileViewModel CreateNewFileAtSelectedNode(string obj)
 {
   m_selectedNode.IsExpanded = true;
   int index = 1;
   while (m_selectedNode.Children.Any(n => n.Name == obj))
   {
     string name = System.IO.Path.GetFileNameWithoutExtension(obj);
     if (name == null)
       return null;
     if (index > 1)
       name = name.Substring(0, name.Length - ((index - 1).ToString().Length));
     obj = name + index + System.IO.Path.GetExtension(obj);
     index++;
   }
   FileViewModel fileViewModel = new FileViewModel(null, m_selectedNode) { Name = obj };
   m_selectedNode.Children.Add(fileViewModel);
   fileViewModel.HasUnsavedChanges = true;
   Save(fileViewModel);
   SelectedNode = fileViewModel;
   OpenFile(fileViewModel);
   fileViewModel.IsRenaming = true;
   return fileViewModel;
 }
Example #40
0
 public void CreateNewFile()
 {
   FileViewModel fileViewModel = new FileViewModel(null);
   LayoutManager.ActiveLayoutElement.OpenFiles.Add(fileViewModel);
   LayoutManager.ActiveLayoutElement.SelectedFile = fileViewModel;
 }
Example #41
0
 private void FileSystemWatcherOnCreated(object sender, FileSystemEventArgs fileSystemEventArgs)
 {
     string[] path = fileSystemEventArgs.Name.Split('\\');
       ITreeNode treeNode = this;
       for (int i = 0; i < path.Length - 1; i++)
       {
     treeNode = treeNode.Children.First(n => n.Name == path[i]);
       }
       if (treeNode.Children.Any(n => n.Path == fileSystemEventArgs.FullPath))
     return;
       if (File.Exists(fileSystemEventArgs.FullPath))
       {
     FileViewModel fileViewModel = new FileViewModel(fileSystemEventArgs.FullPath, treeNode);
     treeNode.Children.Add(fileViewModel);
     AllFiles.Add(fileViewModel);
       }
       else if (Directory.Exists(fileSystemEventArgs.FullPath))
     treeNode.Children.Add(new DirectoryViewModel(fileSystemEventArgs.FullPath, treeNode, AllFiles, m_synchronizationContext));
 }
 public UnPinCommand(FileViewModel viewModel)
 {
     Ensure.NotNull(viewModel, "viewModel");
     this.viewModel = viewModel;
 }
Example #43
0
 public void SetFileData(FileViewModel file, byte[] newData)
 {
     Source.SetFileData(file.Entry, newData);
 }
Example #44
0
        protected override void OnStartup(StartupEventArgs e)
        {
            base.OnStartup(e);
              List<string> files = new List<string>();
              StringBuilder errors = new StringBuilder();
              string outputPath = null;
              bool silent = false;
              MainViewModel mainViewModel = new MainViewModel();

              foreach (string arg in e.Args)
              {
            if (arg.StartsWith("-"))
            {
              Regex regex = new Regex("-([a-zA-Z]*):?([^,]*),?([^,]*),?([^,]*)");
              Match match = regex.Match(arg);
              if (match.Success)
              {
            string parameter = match.Groups[2].ToString();
            switch (match.Groups[1].ToString().ToLower())
            {
              case "folder":
                if (Directory.Exists(parameter))
                {
                  mainViewModel.Path = parameter;
                }
                else
                {
                  errors.AppendLine("Folder does not exist: " + parameter);
                }
                break;
              case "closeall":
                foreach (LayoutElementViewModel layoutElementViewModel in mainViewModel.LayoutManager.LayoutElements)
                {
                  layoutElementViewModel.OpenFiles.Clear();
                  layoutElementViewModel.FileUseOrder.Clear();
                  layoutElementViewModel.SelectedFile = null;
                }
                break;
              case "layout":
                LayoutType layoutType;
                if (Enum.TryParse(parameter, true, out layoutType))
                  mainViewModel.LayoutManager.SelectedLayoutType = layoutType;
                else
                  errors.AppendLine("Unknown layout: " + parameter);
                break;
              case "validate":
                if (File.Exists(parameter))
                {
                  JsonException jsonException;
                  string text = File.ReadAllText(parameter);
                  JsonObject jsonObject = JsonHelperFunctions.Parse(text, out jsonException);
                  if (jsonException != null)
                  {
                    errors.AppendLine("json error: " + jsonException.Message);
                    Environment.ExitCode = 1;
                    break;
                  }
                  Regex scheamRegex = new Regex(@"""\$schema""\s*\:\s*""(.*)""", RegexOptions.IgnoreCase);
                  Match schemaMatch = scheamRegex.Match(text);
                  Schema schema = schemaMatch.Success ? mainViewModel.SchemaManager.GetSchema(schemaMatch.Groups[1].ToString()) : null;
                  if (schema == null)
                  {
                    errors.AppendLine("Sschema not found: " + arg);
                    Environment.ExitCode = 2;
                    break;
                  }
                  Dictionary<int, List<ValidationError>> validationErrors = new Dictionary<int, List<ValidationError>>();
                  schema.Validate(jsonObject, validationErrors, Path.GetDirectoryName(parameter));
                  if (validationErrors.Count > 0)
                  {
                    Environment.ExitCode = 1;
                    foreach (KeyValuePair<int, List<ValidationError>> validationError in validationErrors)
                    {
                      foreach (ValidationError error in validationError.Value)
                      {
                        errors.AppendLine(validationError.Key + ": " + error.Message);
                      }
                    }
                  }
                }
                else
                {
                  errors.AppendLine("File not found: " + parameter);
                  Environment.ExitCode = 2;
                }
                break;
              case "silent":
                silent = true;
                break;
              case "output":
                outputPath = parameter;
                break;
              default:
                errors.AppendLine("Unknown command: " + arg);
                break;
            }
              }
              else
              {
            errors.AppendLine("Argument with wrong format: " + arg);
              }
            }
            else
            {
              if (File.Exists(arg))
            files.Add(arg);
              else
              {
            errors.Append("Can't find file: " + arg);
              }
            }
              }

              foreach (string file in files)
            mainViewModel.OpenFile(file);

              if (!silent)
              {
            if (outputPath != null)
            {
              File.WriteAllText(outputPath, errors.ToString());
            }
            else
            {
              if (errors.Length > 0)
              {
            FileViewModel fileViewModel = new FileViewModel(errors.ToString(), "Errors");
            mainViewModel.OpenFile(fileViewModel);
              }

              mainViewModel.Window.ShowDialog();
            }
              }

              Shutdown();
        }
 public override int Compare(FileViewModel x, FileViewModel y)
 {
     return x.CreationDate.ValueOrDefault(DateTime.MinValue).CompareTo(y.CreationDate.ValueOrDefault(DateTime.MinValue));
 }
Example #46
0
 public static string[] GetConversionExtensions(FileViewModel file)
 {
     if (file == null) return null;
     switch (file.Extension.ToLower()) {
         case ".xmb": return new[] { ".xml" };
         case ".ddt": return new[] { ".png", ".jpg", ".bmp", ".gif" };
         case ".btx": return new[] { ".png", ".jpg", ".bmp", ".gif" };
     }
     return new[] { file.Extension };
 }
Example #47
0
 public byte[] UnConvertData(FileViewModel file, byte[] data)
 {
     switch (file.Extension.ToLower()) {
         case ".xmb": {
             var xdoc = XDocument.Load(new MemoryStream(data));
             var xmb = XMBFile.FromDocument(xdoc);
             using (var stream = new MemoryStream()) {
                 xmb.Save(stream, true);
                 return stream.GetBuffer().Take((int)stream.Length).ToArray();
             }
         }
         default: return null;
     }
 }
Example #48
0
 public ActionResult EditFile(FileViewModel fileViewModel)
 {
     fileService.Edit(fileViewModel.ToBllFile());
     return RedirectToAction("Index");
 }
Example #49
0
        public ActionResult Upload(HttpPostedFileBase file, FileViewModel fileViewModel)
        {
            if (ModelState.IsValid && file!= null)
            {
                ViewBag.Message = "File successfully upload, one more?";

                fileViewModel.FileName = fileViewModel.FileName.ToCapitalLetter();
                fileViewModel.Description = fileViewModel.Description.ToCapitalLetter();
                string fileName = Guid.NewGuid().ToString();
                string extension = Path.GetExtension(file.FileName);
                fileName += extension;
                file.SaveAs(Server.MapPath("/Uploads/" + fileName));
                fileViewModel.Path = fileName;
                fileViewModel.FileType = file.ContentType;
                fileViewModel.CreationTime = DateTime.Now;
                fileViewModel.Rating = 3.0;
                fileViewModel.UserId = userService.GetAllEntities().First(u => u.Email == User.Identity.Name).Id;
                fileService.Create(fileViewModel.ToBllFile());
            }
            else ModelState.AddModelError("", "Fill all placeholders");
            return View();
        }
Example #50
0
 public string ConvertFileTo(FileViewModel file, string path)
 {
     try {
         switch (file.Extension.ToLower()) {
             case ".xmb": {
                 var xdoc = XMBFile.Load(GetFileStream(file.Entry)).GetAsXDocument();
                 xdoc.Save(path);
             } break;
             case ".btx":
             case ".ddt": {
                 RTS3Image srcImg = null;
                 if (file.Extension.ToLower() == ".ddt") {
                     srcImg = DDTImage.Load(GetFileStream(file.Entry));
                 } else if (file.Extension.ToLower() == ".btx") {
                     srcImg = BTXImage.Load(GetFileStream(file.Entry));
                 }
                 byte[] pixData = srcImg.Get32BitUncompressed();
                 if (pixData == null) return null;
                 var bmp = BitmapSource.Create(srcImg.Width, srcImg.Height, 96, 96, PixelFormats.Bgra32, null, pixData, srcImg.Width * 4);
                 BitmapEncoder encoder = null;
                 if (Path.GetExtension(path).ToLower() == ".png") encoder = new PngBitmapEncoder();
                 else if (Path.GetExtension(path).ToLower() == ".jpg") encoder = new JpegBitmapEncoder();
                 else if (Path.GetExtension(path).ToLower() == ".gif") encoder = new GifBitmapEncoder();
                 else if (Path.GetExtension(path).ToLower() == ".bmp") encoder = new BmpBitmapEncoder();
                 encoder.Frames.Add(BitmapFrame.Create(bmp));
                 using (var stream = File.Create(path)) {
                     encoder.Save(stream);
                 }
             } break;
             default: return null;
         }
     } catch {
         return null;
     }
     return path;
 }
Example #51
0
 public string SaveFileTo(FileViewModel file, string path)
 {
     var stream = Source.GetFileStream(file.Entry);
     using (var outFile = File.Create(path)) {
         stream.CopyTo(outFile);
     }
     return path;
 }
        private static List<FileViewModel> GetActualItemList(string path)
        {
            var list = new List<FileViewModel>();

                bool isRoot = false;
                if (path == "\\" || path == "")
                {
                    isRoot = true;
                }

                if (!isRoot)
                {
                    var back = new FileViewModel();
                    back.Text = "..";
                    back.IsDirectory = true;
                    back.IconUri = "icons/back.png";
                    back.IsSpecial = true;
                    if (Utils.IsLightTheme())
                        back.IconUri = back.IconUri.Replace("icons/", "icons/light/");
                    list.Add(back);
                }

                string searchPattern = System.IO.Path.Combine(path, "*");
                var files = InteropLib.GetContent(searchPattern);
                foreach (var file in files)
                {
                    string loweredFileName = file.FileName.ToLower();
                    if (file.IsDirectory ||
                        loweredFileName.EndsWith(".xap") ||
                        loweredFileName.EndsWith(".exe7") ||
                        loweredFileName.EndsWith(".exe") ||
                        loweredFileName.EndsWith(".provxml"))
                    {

                        var lbd = new FileViewModel();
                        lbd.Text = file.FileName;
                        lbd.IsDirectory = file.IsDirectory;
                        if (file.IsDirectory)
                        {
                            lbd.IconUri = "icons/folder.png";
                        }
                        else
                        {
                            if (loweredFileName.EndsWith(".xap"))
                                lbd.IconUri = "icons/xap.png";
                            else if (loweredFileName.EndsWith(".exe"))
                                lbd.IconUri = "icons/exe.png";
                            else if (loweredFileName.EndsWith(".provxml"))
                                lbd.IconUri = "icons/provxml.png";
                            else
                                lbd.IconUri = "icons/exe7.png";
                        }
                        if (Utils.IsLightTheme())
                            lbd.IconUri = lbd.IconUri.Replace("icons/", "icons/light/");
                        list.Add(lbd);
                    }
                }
                list.Sort(new FileViewModelComparer());
            return list;
        }
Example #53
0
 public void AddFile(FileViewModel file)
 {
     Files.Add(file);
 }