コード例 #1
0
 public FileProjectItem(string kind, IFileInfo fileInfo, IFileSystem fileSystem, PathInfo subPath) 
     : base(subPath.ToString(), kind)
 {
     _subPath = subPath;
     _fileSystem = fileSystem;
     FileInfo = fileInfo;
 }
コード例 #2
0
        /// <summary>
        /// Initializes a new instance of the
        /// <see cref="CmisSync.Lib.Storage.Database.Entities.FileTransmissionObject"/> class.
        /// </summary>
        /// <param name="type">Type of transmission.</param>
        /// <param name="localFile">Local file.</param>
        /// <param name="remoteFile">Remote file.</param>
        public FileTransmissionObject(TransmissionType type, IFileInfo localFile, IDocument remoteFile) {
            if (localFile == null) {
                throw new ArgumentNullException("localFile");
            }

            if (!localFile.Exists) {
                throw new ArgumentException(string.Format("'{0} file does not exist", localFile.FullName), "localFile");
            }

            if (remoteFile == null) {
                throw new ArgumentNullException("remoteFile");
            }

            if (remoteFile.Id == null) {
                throw new ArgumentNullException("remoteFile.Id");
            }

            if (string.IsNullOrEmpty(remoteFile.Id)) {
                throw new ArgumentException("empty string", "remoteFile.Id");
            }

            this.Type = type;
            this.LocalPath = localFile.FullName;
            this.LastContentSize = localFile.Length;
            this.LastLocalWriteTimeUtc = localFile.LastWriteTimeUtc;
            this.RemoteObjectId = remoteFile.Id;
            this.LastChangeToken = remoteFile.ChangeToken;
            this.RemoteObjectPWCId = remoteFile.VersionSeriesCheckedOutId;
            this.LastRemoteWriteTimeUtc = remoteFile.LastModificationDate;
            if (this.LastRemoteWriteTimeUtc != null) {
                this.LastRemoteWriteTimeUtc = this.LastRemoteWriteTimeUtc.GetValueOrDefault().ToUniversalTime();
            }
        }
コード例 #3
0
        public FileProviderGlobbingDirectory(
            [NotNull] IFileProvider fileProvider,
            IFileInfo fileInfo,
            FileProviderGlobbingDirectory parent)
        {
            _fileProvider = fileProvider;
            _fileInfo = fileInfo;
            _parent = parent;

            if (_fileInfo == null)
            {
                // We're the root of the directory tree
                RelativePath = string.Empty;
                _isRoot = true;
            }
            else if (!string.IsNullOrEmpty(parent?.RelativePath))
            {
                // We have a parent and they have a relative path so concat that with my name
                RelativePath = _parent.RelativePath + DirectorySeparatorChar + _fileInfo.Name;
            }
            else
            {
                // We have a parent which is the root, so just use my name
                RelativePath = _fileInfo.Name;
            }
        }
コード例 #4
0
        private async Task<CompilationResult> CompileCore(IFileInfo file)
        {
            var host = new MvcRazorHost();
            var engine = new RazorTemplateEngine(host);
            GeneratorResults results;
            using (TextReader rdr = new StreamReader(file.CreateReadStream()))
            {
                results = engine.GenerateCode(rdr, '_' + Path.GetFileNameWithoutExtension(file.Name), "Asp", file.PhysicalPath ?? file.Name);
            }

            string generatedCode;

            using (var writer = new StringWriter())
            using (var codeProvider = new CSharpCodeProvider())
            {
                codeProvider.GenerateCodeFromCompileUnit(results.GeneratedCode, writer, new CodeGeneratorOptions());
                generatedCode = writer.ToString();
            }

            if (!results.Success) 
            {
                return CompilationResult.Failed(generatedCode, results.ParserErrors.Select(e => new CompilationMessage(e.Message)));
            }

            Directory.CreateDirectory(_tempPath);
            string tempFile = Path.Combine(_tempPath, Path.GetRandomFileName() + ".cs");

            File.WriteAllText(tempFile, generatedCode);

            _tempFileSystem.TryGetFileInfo(tempFile, out file);
            return await _baseCompilationService.Compile(file);
        }
コード例 #5
0
        /// <summary>
        /// Downloads an image at the provided URL and converts it to a valid Data Uri scheme (https://en.wikipedia.org/wiki/Data_URI_scheme)
        /// </summary>
        /// <param name="url">The url where the image is located.</param>
        /// <param name="logger">A logger.</param>
        /// <param name="fallbackFileInfo">A FileInfo to retrieve the local fallback image.</param>
        /// <param name="fallbackMediaType">The media type of the fallback image.</param>
        /// <param name="messageHandler">An optional message handler.</param>
        /// <returns>A string that contains the data uri of the downloaded image, or a default image on any error.</returns>
        public static async Task<string> DownloadImageAndConvertToDataUri(this string url, ILogger logger, IFileInfo fallbackFileInfo, string fallbackMediaType = "image/png", HttpMessageHandler messageHandler = null)
        {
            // exclude completely invalid URLs
            if (!string.IsNullOrWhiteSpace(url))
            {
                try
                {
                    // set a timeout to 10 seconds to avoid waiting on that forever
                    using (var client = new HttpClient(messageHandler) { Timeout = TimeSpan.FromSeconds(10) })
                    {
                        var response = await client.GetAsync(url);
                        response.EnsureSuccessStatusCode();

                        // set the media type and default to JPG if it wasn't provided
                        string mediaType = response.Content.Headers.ContentType?.MediaType;
                        mediaType = string.IsNullOrWhiteSpace(mediaType) ? "image/jpeg" : mediaType;

                        // return the data URI according to the standard
                        return (await response.Content.ReadAsByteArrayAsync()).ToDataUri(mediaType);
                    }
                }
                catch (Exception ex)
                {
                    logger.LogInformation(0, ex, "Error while downloading resource");
                }
            }

            // any error or invalid URLs just return the default data uri
            return await fallbackFileInfo.ToDataUri(fallbackMediaType);
        }
コード例 #6
0
        public UrlForm(IFileInfo fileInfo)
        {
            InitializeComponent();

            this.fileInfo = fileInfo;
            this.Url = fileInfo.Url;
        }
コード例 #7
0
        public StaticFileContext(HttpContext context, StaticFileOptions options, PathString matchUrl)
        {
            _context = context;
            _options = options;
            _matchUrl = matchUrl;
            _request = context.Request;
            _response = context.Response;

            _method = null;
            _isGet = false;
            _isHead = false;
            _subPath = PathString.Empty;
            _contentType = null;
            _fileInfo = null;
            _length = 0;
            _lastModified = new DateTime();
            _etag = null;
            _etagQuoted = null;
            _lastModifiedString = null;
            _ifMatchState = PreconditionState.Unspecified;
            _ifNoneMatchState = PreconditionState.Unspecified;
            _ifModifiedSinceState = PreconditionState.Unspecified;
            _ifUnmodifiedSinceState = PreconditionState.Unspecified;
            _ranges = null;
        }
コード例 #8
0
        public bool IsFileAValidAddition(IFileInfo file, IProject baseProject, IProject sourceProject, List<string> warnings)
        {
            if (FileIsOrderCollection(file))
                return OrderedCollectionIsAValidAddition(file, baseProject, sourceProject, warnings);

            return true;
        }
コード例 #9
0
        public bool IsFileAValidModification(IFileInfo file, IProject baseProject, IProject sourceProject, List<string> warnings, List<FileReleaseInfo> releases)
        {
            if (FileIsDeletedItem(file))
                return false;

            if (FileIsSharedResx(file))
            {
                var baseFile = baseProject.Drive.GetFileInfo(file.Url);
                var sourceFile = sourceProject.Drive.GetFileInfo(file.Url);
                ResxDifferences changes = ResxDiffMerge.CompareResxFiles(sourceFile, baseFile);
                if (changes.None)
                    return false;
            }

            if (FileIsRelationship(file))
            {
                Guid sourceId = GetModelItemIdFromFile(file);
                if (sourceId == Guid.Empty)
                    return true;

                OrmRelationship baseRelationship = FindRelationshipInBaseById(sourceId, baseProject);
                if (baseRelationship != null)
                {
                    var sourceRelationship = sourceProject.Get<OrmRelationship>(file.Url);
                    var diffMerge = new ObjectDiffMerge();
                    var changes = diffMerge.CompareObjects(sourceRelationship, baseRelationship);
                    if (!changes.All(change => RelationshipChangeCanBeIgnored(change)))
                        warnings.Add(string.Format("{0} is an existing SalesLogix relationship that was renamed and also modified.  This file will need to be manually merged.", file.Url));

                    return false;
                }
            }

            return true;
        }
コード例 #10
0
ファイル: LocalFileSystem.cs プロジェクト: SmartFire/FlagSync
        /// <summary>
        /// Deletes the specified file.
        /// </summary>
        /// <param name="file">The file to delete.</param>
        /// <exception cref="AccessException">The file could not be accessed.</exception>
        public void DeleteFile(IFileInfo file)
        {
            file.ThrowIfNull(() => file);

            if (!(file is LocalFileInfo))
                throw new ArgumentException("The file must be of type LocalFileInfo.", "file");

            try
            {
                File.SetAttributes(file.FullName, FileAttributes.Normal);
                File.Delete(file.FullName);
            }

            catch (IOException ex)
            {
                throw new AccessException("The file could not be accessed.", ex);
            }

            catch (SecurityException ex)
            {
                throw new AccessException("The file could not be accessed.", ex);
            }

            catch (UnauthorizedAccessException ex)
            {
                throw new AccessException("The file could not be accessed.", ex);
            }
        }
コード例 #11
0
        public static void Save(IFileInfo File, string Key, string Content)
        {
            ContentItem item;
            if (File.ContentItemID == Null.NullInteger)
            {
                item = CreateFileContentItem();
                File.ContentItemID = item.ContentItemId;
            }
            else
            {
                item = Util.GetContentController().GetContentItem(File.ContentItemID);
            }
            JObject obj;
            if (string.IsNullOrEmpty(item.Content))
                obj = new JObject();
            else
                obj = JObject.Parse(item.Content);

            if (string.IsNullOrEmpty(Content))
                obj[Key] = new JObject();
            else
                obj[Key] = JObject.Parse(Content);

            item.Content = obj.ToString();
            Util.GetContentController().UpdateContentItem(item);

            FileManager.Instance.UpdateFile(File);
        }
コード例 #12
0
        public async Task<CompilationResult> Compile(IFileInfo fileInfo)
        {
            Directory.CreateDirectory(_tempDir);
            string outFile = Path.Combine(_tempDir, Path.GetRandomFileName() + ".dll");
            StringBuilder args = new StringBuilder("/target:library ");
            args.AppendFormat("/out:\"{0}\" ", outFile);
            foreach (var file in  Directory.EnumerateFiles(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), "*.dll"))
            {
                args.AppendFormat("/R:\"{0}\" ", file);
            }
            args.AppendFormat("\"{0}\"", fileInfo.PhysicalPath);
            var outputStream = new MemoryStream();

            // common execute
            var process = CreateProcess(args.ToString());
            int exitCode = await Start(process, outputStream);

            string output = GetString(outputStream);
            if (exitCode != 0)
            {
                IEnumerable<CompilationMessage> messages = output.Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)
                                                                 .Skip(3)
                                                                 .Select(e => new CompilationMessage(e));
                return CompilationResult.Failed(String.Empty, messages);
            }

            var type = Assembly.LoadFrom(outFile)
                               .GetExportedTypes()
                               .First();
            return CompilationResult.Successful(String.Empty, type);
        }
コード例 #13
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileCopyErrorEventArgs"/> class.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="targetDirectory">The target directory.</param>
        public FileCopyErrorEventArgs(IFileInfo file, IDirectoryInfo targetDirectory)
        {
            file.ThrowIfNull(() => file);
            targetDirectory.ThrowIfNull(() => targetDirectory);

            this.File = file;
            this.TargetDirectory = targetDirectory;
        }
コード例 #14
0
        /// <summary>
        /// Get one file.
        /// </summary>
        /// <param name="path"> File path. </param>
        /// <param name="file"> File. </param>
        /// <returns> Whether the file was found or not. </returns>
        public override bool GetFile(string path, List<string> currentPath, Queue<string> remainingPathParts, out IFileInfo file)
        {
            string currentPathStr = this.GetPathString(currentPath);
            path = path.Substring(currentPathStr.Length);

            var found = this.FileSystem.TryGetFileInfo(path, out file);
            return found;
        }
コード例 #15
0
        public SnapshotForm(Bitmap image, IFileInfo fileInfo)
        {
            InitializeComponent();

            this.SnapshotImage = image;
            this.fileInfo = fileInfo;
            snapshotPicbox_SizeChanged(null, null);
        }
コード例 #16
0
 /// <summary>
 /// Returns file info extracted from the request.
 /// Good point to add extra fields or override some of them
 /// </summary>
 /// <param name="fileInfo"></param>
 /// <param name="contentHeaders"></param>
 /// <returns></returns>
 protected virtual IFileInfo SetFileInfo(IFileInfo fileInfo, HttpContentHeaders contentHeaders)
 {
     return new IncomeFileInfo
     {
         MimeType = contentHeaders.ContentType.ToString(),
         OriginalName = GetOriginalFileName(contentHeaders),
     };
 }
コード例 #17
0
 public SpaContext(HttpContext context, SpaOptions options, IFileInfo fileInfo, ILogger logger)
 {
     Debug.Assert(fileInfo.Exists, $"The file {fileInfo.Name} does not exist");
     _context = context; 
     _options = options;
     _logger = logger;
     _fileInfo = fileInfo;
 }
コード例 #18
0
 public static Mock<IMappedObject> AddLocalFile(this Mock<IMetaDataStorage> db, IFileInfo path, string id) {
     var file = new Mock<IMappedObject>();
     file.SetupAllProperties();
     file.Setup(o => o.Type).Returns(MappedObjectType.File);
     file.Object.RemoteObjectId = id;
     file.Object.Name = path.Name;
     db.AddMappedFile(file.Object, path.FullName);
     return file;
 }
コード例 #19
0
 public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
 {
     if (subpath == EnvironmentScriptSubpath)
     {
         fileInfo = _environmentScript;
         return true;
     }
     var tryGetFileInfo = _fileSystem.TryGetFileInfo(subpath, out fileInfo);
     return tryGetFileInfo;
 }
コード例 #20
0
 /// <summary>
 /// GetImageFileUrl - this method returns the valid URL for any file, regardless to folder or folder provider in use
 /// </summary>
 /// <param name="Image">Fully loaded IFileInfo object</param>
 /// <returns></returns>
 /// <remarks>
 /// WARNING!!! This method can return exceptions. They should be caught and processed in the UI though.
 /// </remarks>
 public string GetImageFileUrl(IFileInfo Image)
 {
     /*******************************************************'
     ' WARNING!!!
     ' This method can return exceptions. They should be
     ' caught and processed in the UI though.
     '*******************************************************/
     var mapFolder = FolderMappingController.Instance.GetFolderMapping(Image.FolderMappingID);
     return FolderProvider.Instance(mapFolder.FolderProviderType).GetFileUrl(Image);
 }
コード例 #21
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CmisSync.Lib.Events.FileMovedEvent"/> class.
 /// </summary>
 /// <param name="oldLocalFile">Old local file.</param>
 /// <param name="newLocalFile">New local file.</param>
 /// <param name="oldRemoteFilePath">Old remote file path.</param>
 /// <param name="newRemoteFile">New remote file.</param>
 public FileMovedEvent(
     IFileInfo oldLocalFile = null,
     IFileInfo newLocalFile = null,
     string oldRemoteFilePath = null,
     IDocument newRemoteFile = null)
     : base(newLocalFile, newRemoteFile) {
     this.Local = MetaDataChangeType.MOVED;
     this.OldLocalFile = oldLocalFile;
     this.OldRemoteFilePath = oldRemoteFilePath;
 }
コード例 #22
0
ファイル: AdamItem.cs プロジェクト: 2sic/2sxc
 public AdamItem(IFileInfo original)
 {
     IsFolder = false;
     Id = original.FileId;
     ParentId = original.FolderId;
     Path = original.RelativePath;
     Name = original.FileName;
     Size = original.Size;
     Type = "unknown"; // will be set from the outside
 }
コード例 #23
0
ファイル: FileEvent.cs プロジェクト: OpenDataSpace/CmisSync
        /// <summary>
        /// Initializes a new instance of the <see cref="CmisSync.Lib.Events.FileEvent"/> class.
        /// </summary>
        /// <param name='localFile'>
        /// Local file.
        /// </param>
        /// <param name='remoteFile'>
        /// Remote file.
        /// </param>
        public FileEvent(IFileInfo localFile = null, IDocument remoteFile = null) {
            if (localFile == null && remoteFile == null) {
                throw new ArgumentNullException("Given local or remote file must not be null");
            }

            this.LocalFile = localFile;
            this.RemoteFile = remoteFile;
            this.LocalContent = ContentChangeType.NONE;
            this.RemoteContent = ContentChangeType.NONE;
        }
コード例 #24
0
        /// <summary>
        /// Initializes a new instance of the <see cref="FileCopyEventArgs"/> class.
        /// </summary>
        /// <param name="file">The file.</param>
        /// <param name="sourceDirectory">The source directory.</param>
        /// <param name="targetDirectory">The target directory.</param>
        public FileCopyEventArgs(IFileInfo file, IDirectoryInfo sourceDirectory, IDirectoryInfo targetDirectory)
        {
            file.ThrowIfNull(() => file);
            sourceDirectory.ThrowIfNull(() => sourceDirectory);
            targetDirectory.ThrowIfNull(() => targetDirectory);

            this.File = file;
            this.SourceDirectory = sourceDirectory;
            this.TargetDirectory = targetDirectory;
        }
コード例 #25
0
        public bool TryGetFileInfo(string subpath, out IFileInfo fileInfo)
        {
            if (InnerFileSystem.TryGetFileInfo(subpath, out fileInfo))
            {
                return true;
            }

            string defaultPath = System.IO.Path.Combine(InnerFileSystem.Root, Default);
            return InnerFileSystem.TryGetFileInfo(defaultPath, out fileInfo);
        }
コード例 #26
0
        /// <summary>
        /// Copies the specified file to the target directory.
        /// </summary>
        /// <param name="sourceFileSystem">The source file system.</param>
        /// <param name="sourceFile">The source file.</param>
        /// <param name="targetDirectory">The target directory.</param>
        /// <exception cref="AccessException">The source file or target directory could not be accessed.</exception>
        public void CopyFile(IFileSystem sourceFileSystem, IFileInfo sourceFile, IDirectoryInfo targetDirectory)
        {
            sourceFileSystem.ThrowIfNull(() => sourceFileSystem);
            sourceFile.ThrowIfNull(() => sourceFile);
            targetDirectory.ThrowIfNull(() => targetDirectory);

            if (!(targetDirectory is LocalDirectoryInfo))
                throw new ArgumentException("The target directory must be of type LocalDirectoryInfo.", "targetDirectory");

            try
            {
                using (Stream sourceStream = sourceFileSystem.OpenFileStream(sourceFile))
                {
                    string targetFilePath = this.CombinePath(targetDirectory.FullName, sourceFile.Name);

                    try
                    {
                        using (FileStream targetStream = File.Create(targetFilePath))
                        {
                            if (sourceFile.Length > 0)
                            {
                                var copyOperation = new StreamCopyOperation(sourceStream, targetStream, 256 * 1024, true);

                                copyOperation.CopyProgressChanged +=
                                    (sender, e) => this.FileCopyProgressChanged.RaiseSafe(this, e);

                                copyOperation.Execute();
                            }
                        }
                    }

                    catch (IOException)
                    {
                        File.Delete(targetFilePath);

                        throw;
                    }
                }
            }

            catch (UnauthorizedAccessException ex)
            {
                throw new AccessException("The file could not be accessed.", ex);
            }

            catch (SecurityException ex)
            {
                throw new AccessException("The file could not be accessed.", ex);
            }

            catch (IOException ex)
            {
                throw new AccessException("The file could not be accessed.", ex);
            }
        }
コード例 #27
0
        protected void Page_Load(object sender, EventArgs e)
        {
            AlpacaEngine alpaca = new AlpacaEngine(Page, ModuleContext,"DesktopModules/OpenFiles/","images");
            alpaca.RegisterAll();

            int fileid = int.Parse(Page.Request.QueryString["fileId"]);
            var fm = DotNetNuke.Services.FileSystem.FileManager.Instance;
            File = fm.GetFile(fileid);
            ScopeWrapper.Visible = fm.IsImageFile(File);
            lblNoImage.Visible = !ScopeWrapper.Visible;
        }
コード例 #28
0
        public void content_type(string extension, string mimeType)
        {
            var fileInfo = new Moq.Mock<IFileInfo>();
            fileInfo.Setup(x => x.Extension).Returns(extension);
            fileInfo.Setup(x => x.OpenRead()).Returns(StreamWith("<this doesn't matter>"));
            ResponseFile = fileInfo.Object;

            WithResponseFrom("http://localhost:8080", response => {
                Verify.That(() => response.ContentType == mimeType);
            });
        }
コード例 #29
0
 public MetaInfo(IFileInfo copyFrom)
 {
     if (copyFrom != null)
     {
         MimeType = copyFrom.MimeType;
         Extra = copyFrom.Extra;
         OriginalName = copyFrom.OriginalName;
         Owner = copyFrom.Owner;
         Icon = copyFrom.Icon;
     }
 }
コード例 #30
0
 public static bool IsLinkClickURLFormat(string requestPath, NameValueCollection requestQueryString, out IFileInfo fileRequested)
 {
     if (requestPath.EndsWith(@"/LinkClick.aspx", StringComparison.OrdinalIgnoreCase) && requestQueryString["fileticket"] != null)
     {
         int fileId = FileLinkClickController.Instance.GetFileIdFromLinkClick(requestQueryString);
         fileRequested = FileManager.Instance.GetFile(fileId);
         return true;
     }
     fileRequested = null;
     return false;
 }
コード例 #31
0
 public CachedFileInfo(ILogger logger, IFileInfo fileInfo, string subpath)
 {
     _logger   = logger;
     _fileInfo = fileInfo;
     _subpath  = subpath;
 }
コード例 #32
0
 private void ResetSystemsSelection()
 {
     //Reset systems selection
     GameSystems      = EmulationService.Systems;
     SelectedGameFile = null;
 }
コード例 #33
0
 public async Task <AsyncDisposableStream> OpenFileStream(ElementReference elementReference, int index, IFileInfo fileInfo)
 {
     return(new InteropFileStream(await OpenReadAsync(elementReference, index), fileInfo, this));
 }
コード例 #34
0
        public object Post([FromBody] dynamic model)
        {
            if (model == null)
            {
                throw new ApiArgumentException("model");
            }
            if (model.parent == null)
            {
                throw new ApiArgumentException("parent");
            }
            if (!(model.parent is JObject))
            {
                throw new ApiArgumentException("parent", ApiArgumentException.EXPECTED_OBJECT);
            }

            //
            // Check Id
            string parentUuid = DynamicHelper.Value(model.parent.id);

            if (parentUuid == null)
            {
                throw new ApiArgumentException("parent.id");
            }

            FileId fileId = FileId.FromUuid(parentUuid);

            if (!_provider.DirectoryExists(fileId.PhysicalPath))
            {
                throw new NotFoundException("parent");
            }

            //
            // Check Name
            string name = DynamicHelper.Value(model.name);

            if (!PathUtil.IsValidFileName(name))
            {
                throw new ApiArgumentException("model.name");
            }

            //
            // Check Type
            string type = DynamicHelper.Value(model.type);

            FileType fileType;

            if (type == null || !Enum.TryParse(type, true, out fileType))
            {
                throw new ApiArgumentException("model.type");
            }

            DateTime?created      = DynamicHelper.To <DateTime>(model.created);
            DateTime?lastAccess   = DynamicHelper.To <DateTime>(model.last_access);
            DateTime?lastModified = DynamicHelper.To <DateTime>(model.last_modified);

            var creationPath = Path.Combine(fileId.PhysicalPath, name);

            if (_provider.DirectoryExists(creationPath) || _provider.FileExists(creationPath))
            {
                throw new AlreadyExistsException("name");
            }

            IFileInfo info = fileType == FileType.File ? _provider.CreateFile(creationPath) : _provider.CreateDirectory(creationPath);

            _provider.SetFileTime(info.Path, lastAccess, lastModified, created);

            dynamic file = _helper.ToJsonModel(info);

            return(Created(FilesHelper.GetLocation(file.id), _helper.ToJsonModel(info)));
        }
コード例 #35
0
 public IEnumerable <FileVersionInfo> GetFileVersions(IFileInfo file)
 {
     Requires.NotNull("file", file);
     return(CBO.FillCollection <FileVersionInfo>(DataProvider.Instance().GetFileVersions(file.FileId)));
 }
コード例 #36
0
        /// <summary>
        /// Get site root path.
        /// </summary>
        /// <param name=""></param>
        /// <param name="fileName"></param>
        /// <returns></returns>
        public static string GetRootPath(this Site site, WcmsAppContext appctx)
        {
            IFileInfo filInf = appctx?.HostingEnvironment?.WebRootFileProvider?.GetFileInfo($"/{site.Id}");

            return(filInf?.PhysicalPath);
        }
コード例 #37
0
ファイル: Crypto.cs プロジェクト: OpenDataSpace/CmisSync
 /// <summary>
 /// Calculates the checksum over the given stream with a former created hashAlgorithm
 /// </summary>
 /// <returns>The checksum.</returns>
 /// <param name="hashAlgorithm">Hash algorithm.</param>
 /// <param name="file">File to be hashed.</param>
 public static byte[] CalculateChecksum(string hashAlgorithm, IFileInfo file)
 {
     using (var stream = file.Open(FileMode.Open, FileAccess.Read, FileShare.Read)) {
         return(CalculateChecksum(hashAlgorithm, stream));
     }
 }
コード例 #38
0
        /// <inheritdoc/>
        public void ProcessRequest(HttpContext context)
        {
            this.SetupCulture();

            var userId = -1;
            var width  = 55;
            var height = 55;
            var size   = string.Empty;

            try
            {
                if (!string.IsNullOrEmpty(context.Request.QueryString["userid"]))
                {
                    userId = Convert.ToInt32(context.Request.QueryString["userid"]);
                }

                if (!string.IsNullOrEmpty(context.Request.QueryString["w"]))
                {
                    width = Convert.ToInt32(context.Request.QueryString["w"]);
                }

                if (!string.IsNullOrEmpty(context.Request.QueryString["h"]))
                {
                    height = Convert.ToInt32(context.Request.QueryString["h"]);
                }

                if (!string.IsNullOrEmpty(context.Request.QueryString["size"]))
                {
                    size = context.Request.QueryString["size"];
                }
            }
            catch (Exception)
            {
                Exceptions.Exceptions.ProcessHttpException(context.Request);
            }

            if (height > 128)
            {
                height = 128;
            }

            if (width > 128)
            {
                width = 128;
            }

            this.CalculateSize(ref height, ref width, ref size);

            PortalSettings settings = PortalController.Instance.GetCurrentPortalSettings();
            var            user     = UserController.Instance.GetUser(settings.PortalId, userId);

            IFileInfo photoFile   = null;
            var       photoLoaded = false;

            if (user != null && this.TryGetPhotoFile(user, out photoFile))
            {
                if (!this.IsImageExtension(photoFile.Extension))
                {
                    try
                    {
                        context.Response.End();
                    }
                    catch (ThreadAbortException) // if ThreadAbortException will shown, should catch it and do nothing.
                    {
                    }
                }

                var folder     = FolderManager.Instance.GetFolder(photoFile.FolderId);
                var extension  = "." + photoFile.Extension;
                var sizedPhoto = photoFile.FileName.Replace(extension, "_" + size + extension);
                if (!FileManager.Instance.FileExists(folder, sizedPhoto))
                {
                    lock (_locker)
                    {
                        if (!FileManager.Instance.FileExists(folder, sizedPhoto))
                        {
                            using (var fileContent = FileManager.Instance.GetFileContent(photoFile))
                                using (var sizedContent = ImageUtils.CreateImage(fileContent, height, width, extension))
                                {
                                    FileManager.Instance.AddFile(folder, sizedPhoto, sizedContent);
                                }
                        }
                    }
                }

                using (var content = FileManager.Instance.GetFileContent(FileManager.Instance.GetFile(folder, sizedPhoto)))
                {
                    switch (photoFile.Extension.ToLowerInvariant())
                    {
                    case "png":
                        context.Response.ContentType = "image/png";
                        break;

                    case "jpeg":
                    case "jpg":
                        context.Response.ContentType = "image/jpeg";
                        break;

                    case "gif":
                        context.Response.ContentType = "image/gif";
                        break;
                    }

                    using (var memoryStream = new MemoryStream())
                    {
                        content.CopyTo(memoryStream);
                        memoryStream.WriteTo(context.Response.OutputStream);
                    }

                    photoLoaded = true;
                }
            }

            if (!photoLoaded)
            {
                context.Response.ContentType = "image/gif";
                context.Response.WriteFile(context.Request.MapPath("~/images/no_avatar.gif"));
            }

            context.Response.Cache.SetCacheability(HttpCacheability.Public);
            context.Response.Cache.SetExpires(DateTime.Now.AddMinutes(1));
            context.Response.Cache.SetMaxAge(new TimeSpan(0, 1, 0));
            context.Response.AddHeader("Last-Modified", DateTime.Now.ToString("r"));
            context.ApplicationInstance.CompleteRequest();
        }
コード例 #39
0
 internal FileSystemStoreEntry(string path, IFileInfo fileInfo)
 {
     _fileInfo = fileInfo ?? throw new ArgumentNullException(nameof(fileInfo));
     _path     = path ?? throw new ArgumentNullException(nameof(path));
 }
コード例 #40
0
 internal static string GetVersionedFilename(IFileInfo file, int version)
 {
     return(string.Format("{0}_{1}.v.resources", file.FileId, version));
 }
コード例 #41
0
        private string GetLongProperty(IFileInfo info)
        {
            if (info == null)
            {
                return(null);
            }

            var stringBuilder = new StringBuilder();

            // permissions
            string sAttributes = info.GetAttributeString();

            stringBuilder.Append(sAttributes);
            stringBuilder.Append(" 1 owner group");

            // check whether info is directory
            bool isDirectory = info.IsDirectory();

            // size
            string sFileSize = info.GetSize().ToString(); // if info is directory, the size will be 1

            stringBuilder.Append(TextHelpers.RightAlignString(sFileSize, 13, ' '));
            stringBuilder.Append(" ");

            // modify time
            DateTime fileDate = info.GetModifiedTime(); //if info is directory, the modify time will be the current time

            // month
            stringBuilder.Append(TextHelpers.Month(fileDate.Month));
            stringBuilder.Append(" ");
            // day
            string sDay = fileDate.Day.ToString();

            if (sDay.Length == 1)
            {
                stringBuilder.Append(" ");
            }
            stringBuilder.Append(sDay);
            stringBuilder.Append(" ");
            // year or hour:min
            if (fileDate.Year < DateTime.Now.Year)
            {
                stringBuilder.Append(" " + fileDate.Year);
            }
            else
            {
                stringBuilder.Append(string.Format("{0:hh}:{1:mm}", fileDate, fileDate));
            }
            stringBuilder.Append(" ");

            // filename
            string path = info.Path();

            if (isDirectory)
            {
                stringBuilder.Append(FileNameHelpers.GetDirectoryName(path));
            }
            else
            {
                stringBuilder.Append(FileNameHelpers.GetFileName(path));
            }

            // end
            stringBuilder.Append("\r\n");

            return(stringBuilder.ToString());
        }
コード例 #42
0
 protected virtual Stream GetFileStream(IFileInfo fileInfo)
 {
     return(fileInfo.CreateReadStream());
 }
コード例 #43
0
 private Stream GetVersionContent(FolderProvider provider, IFolderInfo folder, IFileInfo file, int version)
 {
     return(provider.GetFileStream(folder, file, version));
 }
コード例 #44
0
 private void SaveFileProperties()
 {
     file = (IFileInfo)((FileFieldsControl)fileFieldsControl).SaveProperties();
 }
コード例 #45
0
        protected override void OnInit(EventArgs e)
        {
            try
            {
                base.OnInit(e);

                JavaScript.RequestRegistration(CommonJs.DnnPlugins);

                var fileId = Convert.ToInt32(Request.Params["FileId"]);
                file     = FileManager.Instance.GetFile(fileId, true);
                fileItem = controller.GetFile(fileId);
                folder   = FolderManager.Instance.GetFolder(file.FolderId);

                SaveButton.Click   += OnSaveClick;
                CancelButton.Click += OnCancelClick;

                if (FolderPermissionController.CanViewFolder((FolderInfo)folder))
                {
                    var mef = new ExtensionPointManager();
                    var preViewPanelExtension = mef.GetUserControlExtensionPointFirstByPriority("DigitalAssets", "PreviewInfoPanelExtensionPoint");
                    previewPanelControl = Page.LoadControl(preViewPanelExtension.UserControlSrc);
                    PreviewPanelContainer.Controls.Add(previewPanelControl);

                    var fileFieldsExtension = mef.GetUserControlExtensionPointFirstByPriority("DigitalAssets", "FileFieldsControlExtensionPoint");
                    fileFieldsControl    = Page.LoadControl(fileFieldsExtension.UserControlSrc);
                    fileFieldsControl.ID = fileFieldsControl.GetType().BaseType.Name;
                    FileFieldsContainer.Controls.Add(fileFieldsControl);

                    PrepareFilePreviewInfoControl();
                    PrepareFileFieldsControl();

                    // Tab Extension Point
                    var tabContentControlsInstances = new List <PropertiesTabContentControl>();
                    foreach (var extension in mef.GetEditPageTabExtensionPoints("DigitalAssets", "FilePropertiesTab"))
                    {
                        if (FolderPermissionController.HasFolderPermission(folder.FolderPermissions, extension.Permission))
                        {
                            var liElement = new HtmlGenericControl("li")
                            {
                                InnerHtml = "<a href=\"#" + extension.EditPageTabId + "\">" + extension.Text + "</a>",
                            };
                            liElement.Attributes.Add("class", extension.CssClass);
                            liElement.Attributes.Add("id", extension.EditPageTabId + "_tab");
                            Tabs.Controls.Add(liElement);

                            var container = new PanelTabExtensionControl {
                                PanelId = extension.EditPageTabId
                            };
                            var control = (PortalModuleBase)Page.LoadControl(extension.UserControlSrc);
                            control.ID = Path.GetFileNameWithoutExtension(extension.UserControlSrc);
                            control.ModuleConfiguration = ModuleConfiguration;
                            var contentControl = control as PropertiesTabContentControl;
                            if (contentControl != null)
                            {
                                contentControl.OnItemUpdated += OnItemUpdated;
                                tabContentControlsInstances.Add(contentControl);
                            }
                            container.Controls.Add(control);
                            TabsPanel.Controls.Add(container);
                        }
                    }
                    tabContentControls = tabContentControlsInstances.ToList();
                }
            }
            catch (Exception ex)
            {
                Exceptions.ProcessModuleLoadException(this, ex);
            }
        }
コード例 #46
0
        public async Task HashFile(bool useMemoryStream, bool offset = false)
        {
            Output = string.Empty;
            this.StateHasChanged();
            var nl = Environment.NewLine;

            foreach (var file in await fileReaderService.CreateReference(inputElement).EnumerateFilesAsync())
            {
                IFileInfo fileInfo = null;
                fileInfo = await file.ReadFileInfoAsync();

                if (DebugOutput)
                {
                    Output += $"{nameof(IFileInfo)}.{nameof(fileInfo.Name)}: {fileInfo.Name}{nl}";
                    Output += $"{nameof(IFileInfo)}.{nameof(fileInfo.Size)}: {fileInfo.Size}{nl}";
                    Output += $"{nameof(IFileInfo)}.{nameof(fileInfo.Type)}: {fileInfo.Type}{nl}";
                    Output += $"{nameof(IFileInfo)}.{nameof(fileInfo.LastModifiedDate)}: {fileInfo.LastModifiedDate?.ToString(CultureInfo.InvariantCulture) ?? "(N/A)"}{nl}";
                    Output += $"Reading file...";
                    this.StateHasChanged();
                }
                var stopWatch = new System.Diagnostics.Stopwatch();

                stopWatch.Start();
                var outputBuffer = new StringBuilder();
                using (var hash = new SHA256Managed())
                {
                    if (useMemoryStream)
                    {
                        using (var fs = UseBufferSize ?
                                        await file.CreateMemoryStreamAsync(BufferSize) :
                                        await file.CreateMemoryStreamAsync())
                        {
                            hash.ComputeHash(fs);
                        }
                    }
                    else
                    {
                        using (var fs = await file.OpenReadAsync())
                        {
                            var bufferSize = UseBufferSize ? BufferSize : 4096 * 8;
                            if (DebugOutput)
                            {
                                outputBuffer.AppendLine($"Using chunks of size {bufferSize}");
                            }

                            var targetBufferSize = bufferSize;
                            if (offset)
                            {
                                targetBufferSize = (int)fileInfo?.Size;
                            }
                            var buffer = new byte[targetBufferSize];
                            int count  = 0;

                            var targetOffset = 0;
                            var len          = offset ? Math.Min(bufferSize, (int)fileInfo.Size) : buffer.Length;
                            while ((count = await fs.ReadAsync(buffer, targetOffset, len)) != 0)
                            {
                                if (offset)
                                {
                                    targetOffset += count;
                                }
                                if (DebugOutput)
                                {
                                    outputBuffer.AppendLine($"Hashing {count} bytes. {fs.Position} / {fs.Length}");
                                }
                                if (!offset)
                                {
                                    hash.TransformBlock(buffer, 0, count, buffer, 0);
                                }

                                if (OutputString)
                                {
                                    outputBuffer.AppendLine("BEGIN BUFFER DUMP");
                                    outputBuffer.AppendLine(Encoding.UTF8.GetString(buffer));
                                    outputBuffer.AppendLine("END BUFFER DUMP");
                                }
                            }
                            if (!offset)
                            {
                                hash.TransformFinalBlock(buffer, 0, count);
                            }
                            else
                            {
                                hash.ComputeHash(buffer);
                            }
                        }
                    }
                    var sb = new StringBuilder(hash.HashSize / 4);
                    foreach (var b in hash.Hash)
                    {
                        sb.AppendFormat("{0:x2}", b);
                    }

                    stopWatch.Stop();
                    if (DebugOutput)
                    {
                        Output += $"Done hashing file {fileInfo.Name}.{nl}";
                    }

                    Output += sb.ToString();
                    if (outputBuffer.Length > 0)
                    {
                        Output += $"{nl}{nl}Debug output:{nl}";
                        Output += outputBuffer.ToString();
                    }
                }
            }

            Output += $"{nl}--DONE";
            this.StateHasChanged();
        }
コード例 #47
0
 public FileVersionInfo GetFileVersion(IFileInfo file, int version)
 {
     Requires.NotNull("file", file);
     return(CBO.FillObject <FileVersionInfo>(DataProvider.Instance().GetFileVersion(file.FileId, version)));
 }
コード例 #48
0
 internal void Init(IFileListControl fileListControl, IFileInfo p)
 {
     quickTagsUserControl1.Init(fileListControl, p);
 }
コード例 #49
0
 public async Task <IBase64Stream> OpenBase64Stream(ElementReference elementReference, int index, IFileInfo fileInfo)
 {
     return(new Base64Stream(await OpenReadAsync(elementReference, index), fileInfo, this));
 }
コード例 #50
0
        internal virtual string GetHash(IFileInfo file)
        {
            var fileManager = new FileManager();

            return(fileManager.GetHash(file));
        }
コード例 #51
0
 private bool CanCreate(IFileInfo file, string baseFolderPath)
 {
     // Can create only if the file is a child of the base folder
     return(file.FullName.Contains(baseFolderPath));
 }
コード例 #52
0
        public override void SetFileAttributes(IFileInfo file, FileAttributes fileAttributes)
        {
            Requires.NotNull("file", file);

            FileWrapper.Instance.SetAttributes(GetActualPath(file), fileAttributes);
        }
コード例 #53
0
        /// <inheritdoc />
        public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (output == null)
            {
                throw new ArgumentNullException(nameof(output));
            }

            if (AddSubresourceIntegrity != true)
            {
                await base.ProcessAsync(context, output);

                return;
            }

            string?filePath = (context.AllAttributes["src"].Value as string)?.TrimStart(Tilde);
            string?type     = context.AllAttributes["type"]?.Value?.ToString() as string;

            if (string.IsNullOrEmpty(filePath) ||
                (!string.IsNullOrEmpty(type) && !string.Equals(type, "text/javascript", StringComparison.OrdinalIgnoreCase)))
            {
                // No file or not JavaScript
                await base.ProcessAsync(context, output);

                return;
            }

            IFileInfo fileInfo = HostingEnvironment.WebRootFileProvider.GetFileInfo(filePath);

            if (!fileInfo.Exists)
            {
                // Not a local file
                await base.ProcessAsync(context, output);

                return;
            }

            string cacheKey = $"sri-hash-{fileInfo.PhysicalPath}";

            if (!Cache.TryGetValue(cacheKey, out string hash))
            {
                using (var algorithm = SHA384.Create())
                {
                    using var stream = fileInfo.CreateReadStream();
                    hash             = Convert.ToBase64String(algorithm.ComputeHash(stream));
                }

                var options = new MemoryCacheEntryOptions()
                {
                    Size = hash.Length,
                };

                Cache.Set(cacheKey, hash, options);
            }

            output.Attributes.Add("integrity", $"sha384-{hash}");
            output.Attributes.Add("crossorigin", "anonymous");
        }
コード例 #54
0
        /// <inheritdoc/>
        protected virtual Task WriteFileAsync(ActionContext context, VirtualFileResult result, IFileInfo fileInfo, RangeItemHeaderValue range, long rangeLength)
        {
            if (context == null)
            {
                throw new ArgumentNullException(nameof(context));
            }

            if (result == null)
            {
                throw new ArgumentNullException(nameof(result));
            }

            if (range != null && rangeLength == 0)
            {
                return(Task.CompletedTask);
            }

            var response = context.HttpContext.Response;

            if (range != null)
            {
                Logger.WritingRangeToBody();
            }

            if (range != null)
            {
                return(response.SendFileAsync(fileInfo,
                                              offset: range.From ?? 0L,
                                              count: rangeLength));
            }

            return(response.SendFileAsync(fileInfo,
                                          offset: 0,
                                          count: null));
        }
コード例 #55
0
 /// <summary>
 /// Get actual path to an IFileInfo
 /// </summary>
 /// <param name="file">The file</param>
 /// <returns>A windows supported path to the file</returns>
 protected virtual string GetActualPath(IFileInfo file)
 {
     return(file.PhysicalPath);
 }
コード例 #56
0
 WebAsset ToWebAsset(string path, IFileInfo fileInfo)
 => new WebAsset(
     path,
     new WebAssetMetadata(fileInfo.Name, fileInfo.Length, fileInfo.LastModified, null),
     WebAssetContent.FromStream(fileInfo.CreateReadStream())
     );
コード例 #57
0
ファイル: FileInfoExtensions.cs プロジェクト: keimpema/Usenet
 public static string ReadAllText(this IFileInfo fileInfo, Encoding encoding)
 {
     using Stream stream = fileInfo.CreateReadStream();
     using var reader    = new StreamReader(stream, encoding);
     return(reader.ReadToEnd());
 }
コード例 #58
0
 protected override IValidationResult DoValidate(IFileInfo node)
 {
     return(this.Validate(node.Name, node.FullName));
 }
コード例 #59
0
 public FileInfoCodeSource(IFileInfo fi)
 {
     _fi = fi;
 }
コード例 #60
0
        /// <summary>
        /// Get Font Awesome icon from file extension.
        /// </summary>
        /// <param name="file">Current file</param>
        /// <returns>HTLM span with icon class and title</returns>
        private string GetFileIcon(IFileInfo file)
        {
            string fileExtension = file.Extension.ToLower();
            string toggleIcon    = "fa-file-o";
            string iconTitle     = string.Format(LocalizeString("MiscFile"), fileExtension);

            switch (fileExtension)
            {
            case "bmp":
            case "gif":
            case "jpg":
            case "jpeg":
            case "png":
            case "tif":
            case "tiff":
            case "ico":
                toggleIcon = "fa-file-image-o";
                iconTitle  = string.Format(LocalizeString("ImageFile"), fileExtension, file.Width, file.Height);
                break;

            case "avi":
            case "wmv":
            case "mov":
            case "flv":
            case "mpg":
            case "mp4":
            case "vob":
            case "mkv":
                toggleIcon = "fa-file-video-o";
                iconTitle  = string.Format(LocalizeString("VideoFile"), fileExtension);
                break;

            case "wav":
            case "wma":
            case "mp3":
            case "m4a":
            case "flac":
            case "aac":
            case "ogg":
                toggleIcon = "fa-file-audioFile";
                iconTitle  = string.Format(LocalizeString("AudioFile"), fileExtension);
                break;

            case "doc":
            case "docx":
                toggleIcon = "fa-file-word-o";
                iconTitle  = string.Format(LocalizeString("WordFile"), fileExtension);
                break;

            case "xls":
            case "xlsx":
                toggleIcon = "fa-file-excel-o";
                iconTitle  = string.Format(LocalizeString("ExcelFile"), fileExtension);
                break;

            case "ppt":
            case "pptx":
                toggleIcon = "fa-file-powerpoint-o";
                iconTitle  = string.Format(LocalizeString("PowerPointFile"), fileExtension);
                break;

            case "pdf":
                toggleIcon = "fa-file-pdf-o";
                iconTitle  = string.Format(LocalizeString("PDFFile"), fileExtension);
                break;

            case "zip":
            case "gzip":
            case "rar":
            case "tar":
                toggleIcon = "fa-file-archive-o";
                iconTitle  = string.Format(LocalizeString("ArchiveFile"), fileExtension);
                break;

            case "txt":
                toggleIcon = "fa-file-text-o";
                iconTitle  = string.Format(LocalizeString("TextFile"), fileExtension);
                break;

            default:
                break;
            }

            return(string.Format("<span class='fa fa-lg {0}' title='{1}'></span>", toggleIcon, iconTitle));
        }