/// <summary>
        ///     Gets all the files in the trash bin.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="p"></param>
        /// <returns></returns>
        public static List <File> GetTrashBinFile(this OnlineFilesEntities context, Principal p)
        {
            List <File> found;
            bool        createdContext = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }
            try
            {
                found = context.Files.Where(d => d.IsDeleted && d.OwnerId == p.UserProfile.SecurityObjectId)
                        .ToList();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                if (createdContext)
                {
                    context.Dispose();
                    context = null;
                }
            }
            return(found);
        }
Example #2
0
        /// <summary>
        /// Moves the fileId to this Folder
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="fileId"></param>
        /// <param name="destinationName"></param>
        /// <param name="user"></param>
        public static void MoveFileHere(this Folder destination, Guid fileId, string destinationName, Principal user)
        {
            using (var context = new OnlineFilesEntities())
            {
                var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId);

                //Can the user create files in the destinatioin folder?
                if (destSecurity.Any(d => d.canCreateFiles && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId)))
                {
                    File fileToMove = context.Files.FirstOrDefault(d => d.pk_FileId == fileId);
                    if (fileToMove == null)
                    {
                        throw new Exception("Cannot move a non existant file");
                    }


                    Folder parentToFileToMove = context.Folders.Include(x => x.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == fileToMove.fk_FolderId);
                    if (parentToFileToMove == null)
                    {
                        throw new Exception("No parent to folder being moved.");
                    }

                    //Can the user delete from the folder that the file starts in?
                    if (parentToFileToMove.FolderSecurities.Any(d => user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId) && d.canDelete))
                    {
                        var locks = context.ObjectLockInfoes.Where(d => d.ObjectGuid == fileId);
                        if (locks.Count() > 0)
                        {
                            if (locks.Any(d => d.OwnerId == user.UserProfile.SecurityObjectId))
                            {
                                context.ObjectLockInfoes.RemoveRange(context.ObjectLockInfoes.Where(d => d.ObjectGuid == fileId));
                                context.SaveChanges();
                            }
                            else
                            {
                                throw new SecurityException("File is Locked by another user.");
                            }
                        }
                    }
                    else
                    {
                        throw new SecurityException("Not Authorized.");
                    }


                    fileToMove.Name        = destination.CheckFolderName(destinationName, context);
                    fileToMove.fk_FolderId = destination.pk_FolderId;
                    context.SaveChanges();
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
        }
        /// <summary>
        /// Purges the Folder and all it's children from the system
        /// </summary>
        /// <param name="context"></param>
        /// <param name="folderId"></param>
        private static void HardDeleteFolder(this OnlineFilesEntities context, Guid folderId)
        {
            bool createdContext = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }
            try
            {
                //Little bit of recursion here
                var children = context.Folders.Where(x => x.fk_ParentFolderId == folderId).Select(c => c.pk_FolderId).ToList();
                foreach (var f in children)
                {
                    context.HardDeleteFolder(f);
                }



                Folder folder = context.Folders
                                .Include(x => x.FolderSecurities)
                                .Include(x => x.Files)
                                .FirstOrDefault(d => d.pk_FolderId == folderId);

                if (folder == null)
                {
                    throw new FileNotFoundException("File Not found with: " + folderId);
                }

                //Delete all the files.
                foreach (File file in folder.Files.ToList())
                {
                    context.HardDeleteFile(file.pk_FileId);
                }

                context.FolderSecurities.RemoveRange(folder.FolderSecurities);
                context.Folders.Remove(folder);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                if (createdContext)
                {
                    context.SaveChanges();
                    context.Dispose();
                    context = null;
                }
            }
        }
Example #4
0
        /// <summary>
        ///     Marks the File object as deleted, don't forget to commitchanges.
        /// </summary>
        /// <param name="deletedBy"></param>
        public void SetDeleted(Principal deletedBy)
        {
            using (var context = new OnlineFilesEntities())
                if (!(context.FileSecurities.AsNoTracking().Any(x => deletedBy.UserProfile.mySecurityGroups.Contains(x.SecurityObjectId) && x.CanDelete)))
                {
                    throw new SecurityException("Not Authorized.");
                }

            IsDeleted   = true;
            DeletedDt   = DateTime.Now;
            DeletedById = deletedBy.UserProfile.SecurityObjectId;
        }
Example #5
0
        public void RestoreDeleted(SecurityObject undeletedBy)
        {
            using (var context = new OnlineFilesEntities())
                if (!(context.FileSecurities.AsNoTracking().Any(x => undeletedBy.mySecurityGroups.Contains(x.SecurityObjectId) && x.CanDelete)))
                {
                    throw new SecurityException("Not Authorized.");
                }

            IsDeleted   = false;
            DeletedDt   = DateTime.Now;
            DeletedById = undeletedBy.SecurityObjectId;
        }
        /// <summary>
        /// Purges the file and all it's data from the system.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="fileId"></param>
        private static void HardDeleteFile(this OnlineFilesEntities context, Guid fileId)
        {
            bool createdContext = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }
            try
            {
                File file = context.Files
                            .Include(c => c.FileSecurities)
                            .Include(c => c.FileDatas.Select(d => d.Catalog))
                            .FirstOrDefault(x => x.pk_FileId == fileId);
                if (file == null)
                {
                    throw new FileNotFoundException("File Not found with: " + fileId);
                }

                //Remove the data from the catalog.
                foreach (FileData data in file.FileDatas)
                {
                    using (var cfd = new OnlineFiles_CatalogEntities(data.Catalog.EntityConnectionString))
                    {
                        cfd.FileCatalogEntries.Remove(cfd.FileCatalogEntries.FirstOrDefault(d => d.pk_FileCatalogEntryId == data.fk_ContentId));
                        cfd.SaveChanges();
                    }
                }

                //Remove Pointer records to data
                context.FileDatas.RemoveRange(file.FileDatas);
                //Remove File Security Records.
                context.FileSecurities.RemoveRange(file.FileSecurities);

                context.Files.Remove(file);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                if (createdContext)
                {
                    context.SaveChanges();
                    context.Dispose();
                    context = null;
                }
            }
        }
Example #7
0
 /// <summary>
 ///     Sets a bit flag to a file attribute.
 /// </summary>
 /// <param name="user"></param>
 /// <param name="attrib"></param>
 /// <param name="value"></param>
 public void SetWin32Attribute(Principal user, FileAttributes attrib, bool value)
 {
     using (var context = new OnlineFilesEntities())
         if (!(context.FileSecurities.Where(d => d.fk_FileId == pk_FileId).ToList().Any(x => user.UserProfile.mySecurityGroups.Contains(x.SecurityObjectId) && x.canWrite)))
         {
             throw new SecurityException("Not Authorized.");
         }
     if (value)
     {
         Win32FileAttribute = (int)FlagsHelper.Set(((FileAttributes)Win32FileAttribute), attrib);
     }
     else
     {
         Win32FileAttribute = (int)FlagsHelper.Unset(((FileAttributes)Win32FileAttribute), attrib);
     }
 }
Example #8
0
        private long _Size(Guid folderId)
        {
            long size = 0;

            using (var context = new OnlineFilesEntities())
            {
                foreach (Folder folder in context.Folders.Where(d => d.fk_ParentFolderId == folderId && !d.IsDeleted).ToList())
                {
                    size += folder._Size(folder.pk_FolderId);//Recursively get the size of the children folders.
                }
                foreach (File file in  context.Files.Where(d => d.fk_FolderId == folderId && !d.IsDeleted).ToList())
                {
                    size += file.FileSize;//Get the size of each file
                }
            }
            return(size);
        }
Example #9
0
        /// <summary>
        ///     Opens a READ only stream to the file data.
        /// </summary>
        /// <param name="user"></param>
        /// <returns></returns>
        public Stream OpenReadStream(Principal user)
        {
            using (var context = new OnlineFilesEntities())
            {
                var sec = context.FileSecurities.Where(d => d.fk_FileId == pk_FileId && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId));
                if (!sec.Any(d => d.canRead))
                {
                    throw new SecurityException("Not Authorized.");
                }

                FileData filedata = context.FileDatas.AsNoTracking()
                                    .Include(x => x.Catalog)
                                    .Where(d => d.fk_FileId == pk_FileId)
                                    .OrderByDescending(d => d.Revision)
                                    .FirstOrDefault();

                if (filedata == null)
                {
                    return new MemoryStream(_emptyBytes.ToArray())
                           {
                               Position = 0
                           }
                }
                ;

                using (var ctx = new OnlineFiles_CatalogEntities(filedata.Catalog.EntityConnectionString))
                {
                    FileCatalogEntry filecat = ctx.FileCatalogEntries.AsNoTracking()
                                               .FirstOrDefault(d => d.pk_FileCatalogEntryId == filedata.fk_ContentId);

                    if (filecat == null)
                    {
                        return new MemoryStream(_emptyBytes.ToArray())
                               {
                                   Position = 0
                               }
                    }
                    ;
                    return(new MemoryStream(filecat.binaryData)
                    {
                        Position = 0
                    });
                }
            }
        }
Example #10
0
        public void RestoreDeleted(SecurityObject undeletedBy)
        {
            List <FolderSecurity> perm;

            using (var context = new OnlineFilesEntities())
                perm = context.FolderSecurities.AsNoTracking().Where(d => d.fk_FolderId == pk_FolderId).ToList();

            if (perm.Any(d => d.canDelete && undeletedBy.mySecurityGroups.Contains(d.SecurityObjectId)))
            {
                IsDeleted   = false;
                DeletedDt   = DateTime.Now;
                DeletedById = undeletedBy.SecurityObjectId;
            }
            else
            {
                throw new SecurityException("Not Authorized.");
            }
        }
        /// <summary>
        ///     Gets all the files in a folder.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="folderkey"></param>
        /// <param name="p"></param>
        /// <param name="readOnly"></param>
        /// <returns></returns>
        public static List <File> GetChildFiles(this OnlineFilesEntities context, Guid?folderkey, Principal p, bool readOnly = false)
        {
            List <File> found;
            bool        createdContext = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }
            try
            {
                var folder = context.Folders.Include(x => x.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderkey);
                if (folder == null)
                {
                    throw new SecurityException("No Access");
                }
                if (!folder.FolderSecurities.Any(x => p.UserProfile.mySecurityGroups.Contains(x.SecurityObjectId) && x.canListObjects))
                {
                    throw new SecurityException("No Access");
                }


                DbQuery <File> source = readOnly ? context.Files.AsNoTracking() : context.Files;

                found = source.Where(d => d.fk_FolderId == folderkey && !(d.IsDeleted) && (d.OwnerId == p.UserProfile.SecurityObjectId ||
                                                                                           d.FileSecurities.Any(x => x.canRead && p.UserProfile.mySecurityGroups.Contains(x.SecurityObjectId))))
                        .ToList();
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                if (createdContext)
                {
                    context.Dispose();
                }
            }
            return(found);
        }
Example #12
0
        public static File Rename(Guid?fileId, Guid?folderId, string name, SecurityObject createdBy)
        {
            using (var context = new OnlineFilesEntities())
            {
                if (folderId == null)
                {
                    throw new Exception("Bad Guid.");
                }

                var folder = context.Folders
                             .Include(x => x.FolderSecurities)
                             .FirstOrDefault(d => d.pk_FolderId == folderId);
                if (folder == null)
                {
                    throw new Exception("Folder Not Found.");
                }

                if (!folder.FolderSecurities.Any(x => createdBy.mySecurityGroups.Contains(x.SecurityObjectId) && x.canCreateFiles))
                {
                    throw new SecurityException("No Access.");
                }

                var filechk = context.Files
                              .Include(x => x.FileSecurities)
                              .FirstOrDefault(d => d.Name == name);
                if (filechk != null)
                {
                    throw new Exception("File Name already used.");
                }
                var file = context.Files
                           .Include(x => x.FileSecurities)
                           .FirstOrDefault(d => d.pk_FileId == fileId);
                if (file != null)
                {
                    file.Name = name;
                }

                context.Files.AddOrUpdate(file);
                context.SaveChanges();

                return(file);
            }
        }
Example #13
0
        /// <summary>
        ///     Returns the FileInfo
        /// </summary>
        /// <returns></returns>
        public SqlStoreFileInfo GetFileInfo()
        {
            FileData lastdata;

            if (FileDatas == null)
            {
                using (var context = new OnlineFilesEntities())
                    lastdata = context.FileDatas.OrderByDescending(d => d.Revision).FirstOrDefault();
            }
            else
            {
                lastdata = FileDatas.OrderByDescending(d => d.Revision).FirstOrDefault();
            }

            var fileinfo = new SqlStoreFileInfo
            {
                Parent            = null,
                Path              = null,
                Exists            = true,
                CreationTime      = CreateDt,
                LastAccessTime    = CreateDt,
                LastWriteTime     = lastdata?.CreateDt ?? CreateDt,
                Directory         = false,
                Archive           = GetWin32Attribute(FileAttributes.Archive),
                Compressed        = GetWin32Attribute(FileAttributes.Compressed),
                Device            = GetWin32Attribute(FileAttributes.Device),
                Encrypted         = GetWin32Attribute(FileAttributes.Encrypted),
                NotContentIndexed = GetWin32Attribute(FileAttributes.NotContentIndexed),
                Offline           = GetWin32Attribute(FileAttributes.Offline),
                System            = GetWin32Attribute(FileAttributes.System),
                Hidden            = GetWin32Attribute(FileAttributes.Hidden),
                IntegrityStream   = GetWin32Attribute(FileAttributes.IntegrityStream),
                NoScrubData       = GetWin32Attribute(FileAttributes.NoScrubData),
                Normal            = GetWin32Attribute(FileAttributes.Normal),
                ReadOnly          = GetWin32Attribute(FileAttributes.ReadOnly),
                ReparsePoint      = GetWin32Attribute(FileAttributes.ReparsePoint),
                SparseFile        = GetWin32Attribute(FileAttributes.SparseFile),
                Temporary         = GetWin32Attribute(FileAttributes.Temporary),
                ObjectGuid        = pk_FileId
            };

            return(fileinfo);
        }
        /// <summary>
        /// Retrieves all the Child Folders for the folder
        /// </summary>
        /// <param name="context"></param>
        /// <param name="Key"></param>
        /// <param name="p"></param>
        /// <param name="ReadOnly"></param>
        /// <returns></returns>
        public static List <Folder> GetChildFolders(this OnlineFilesEntities context, Guid?Key, Principal p, bool ReadOnly = false)
        {
            List <Folder> found          = new List <Folder>();
            bool          createdContext = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }
            try
            {
                DbQuery <Folder> source = ReadOnly ? context.Folders.AsNoTracking() : context.Folders;

                if (Key == new Guid())
                {
                    found = source.Where(d => d.fk_ParentFolderId == Key && !(d.IsDeleted) &&
                                         (d.OwnerId == p.UserProfile.SecurityObjectId)).ToList();
                }
                else
                {
                    found = source.Where(d => d.fk_ParentFolderId == Key && !(d.IsDeleted) &&
                                         (d.OwnerId == p.UserProfile.SecurityObjectId ||
                                          d.FolderSecurities.Any(x => x.canListObjects && p.UserProfile.mySecurityGroups.Contains(x.SecurityObjectId))
                                         )).ToList();
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                throw;
            }
            finally
            {
                if (createdContext)
                {
                    context.Dispose();
                    context = null;
                }
            }
            return(found);
        }
Example #15
0
 /// <summary>
 ///     Checks to see if the file is checked out by anyone
 /// </summary>
 /// <param name="file"></param>
 /// <returns></returns>
 public static bool IsCheckedOut(this File file)
 {
     using (var context = new OnlineFilesEntities())
     {
         List <SpDoAnyChildrenHaveLocksResult> cellData =
             context.Database.SqlQuery <SpDoAnyChildrenHaveLocksResult>($"dbo.sp_DoAnyChildrenHaveLocks '{file.pk_FileId}'").ToList();
         if (cellData.Any())
         {
             if (cellData[0].Exists)
             {
                 return(true);
             }
         }
         else
         {
             throw new WebDavNotFoundException("Shouldn't get here.");
         }
     }
     return(false);
 }
Example #16
0
        public static void RestoreFolderHere(this Folder destination, Guid folderId, string destinationName, Principal user)
        {
            using (var context = new OnlineFilesEntities())
            {
                var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId);

                //Can the user create folders at the destination location?
                if (destSecurity.Any(d => d.canCreateFolders && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId)))
                {
                    Folder folderToRestore = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderId);
                    if (folderToRestore == null)
                    {
                        throw new Exception("Cannot restore a non existant folder");
                    }

                    Folder parentToFolderToMove = context.Folders.Include(x => x.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderToRestore.fk_ParentFolderId);
                    if (parentToFolderToMove == null)
                    {
                        throw new Exception("No parent to folder being moved.");
                    }

                    //Does the user have delete permission in the folder the item is comming from?
                    if (parentToFolderToMove.FolderSecurities.Any(d => user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId) && d.canDelete))
                    {
                        folderToRestore.RestoreDeleted(PrincipleFactory.Instance.GetPrinciple().UserProfile);
                        folderToRestore.Name = destination.CheckFolderName(destinationName, context);
                        folderToRestore.fk_ParentFolderId = destination.pk_FolderId;
                        context.SaveChanges();
                    }
                    else
                    {
                        throw new SecurityException("Not Authorized.");
                    }
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
        }
 /// <summary>
 ///     Gets all the files in a folder
 /// </summary>
 /// <param name="context"></param>
 /// <param name="folder"></param>
 /// <param name="p"></param>
 /// <param name="readOnly"></param>
 /// <returns></returns>
 public static List <File> GetChildFiles(this OnlineFilesEntities context, Folder folder, Principal p, bool readOnly = false)
 {
     return(GetChildFiles(context, folder.pk_FolderId, p, readOnly));
 }
Example #18
0
        /// <summary>
        ///     Set the permission on a file for the target User.
        /// </summary>
        /// <param name="fileId"></param>
        /// <param name="user"></param>
        /// <param name="targetUser"></param>
        /// <param name="canRead"></param>
        /// <param name="canWrite"></param>
        /// <param name="canDelete"></param>
        /// <param name="context"></param>
        /// <param name="dbcxtransaction"></param>
        public static void SetPermissions(Guid fileId, Principal user, Principal targetUser, bool canRead, bool canWrite, bool canDelete, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null)
        {
            bool createdContext     = false;
            bool createdTransaction = false;
            bool didRollback        = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }


            if (dbcxtransaction == null)
            {
                dbcxtransaction    = context.Database.BeginTransaction();
                createdTransaction = true;
            }
            try
            {
                File targetfile = context.Files
                                  .Include(d => d.FileSecurities)
                                  .FirstOrDefault(d => d.pk_FileId == fileId);
                if (targetfile == null)
                {
                    throw new Exception("File does not exist.");
                }

                Folder target = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == targetfile.fk_FolderId);
                if (target == null)
                {
                    throw new Exception("Parent Folder does not exist.");
                }


                //Can the user Change Permissions
                if (target.FolderSecurities.Any(d => d.canChangePermissions && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId)))
                {
                    var secRecord = targetfile.FileSecurities.FirstOrDefault(d => d.SecurityObjectId == targetUser.UserProfile.SecurityObjectId);
                    if (secRecord == null)
                    {
                        secRecord = new FileSecurity
                        {
                            fk_FileId        = targetfile.pk_FileId,
                            CanDelete        = canDelete,
                            canRead          = canRead,
                            canWrite         = canWrite,
                            SecurityObjectId = targetUser.UserProfile.SecurityObjectId
                        };
                        targetfile.FileSecurities.Add(secRecord);
                    }
                    else
                    {
                        secRecord.canRead   = canRead;
                        secRecord.CanDelete = canDelete;
                        secRecord.canWrite  = canWrite;
                    }
                    context.SaveChanges();
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
            catch (Exception)
            {
                if (!createdTransaction)
                {
                    throw;
                }
                didRollback = true;
                dbcxtransaction.Rollback();
                throw;
            }

            finally
            {
                if (createdTransaction)
                {
                    if (!didRollback)
                    {
                        dbcxtransaction.Commit();
                    }
                    dbcxtransaction.Dispose();
                }
                if (createdContext)
                {
                    context.Dispose();
                }
            }
        }
Example #19
0
        /// <summary>
        ///     Creates a new File Object.
        /// </summary>
        /// <param name="folderId"></param>
        /// <param name="name"></param>
        /// <param name="createdBy"></param>
        /// <param name="inheritSecurity"></param>
        /// <returns></returns>
        public static File Create(Guid?folderId, string name, SecurityObject createdBy, bool inheritSecurity = true)
        {
            using (var context = new OnlineFilesEntities())
            {
                if (folderId == null)
                {
                    throw new Exception("Bad Guid.");
                }

                var folder = context.Folders
                             .Include(x => x.FolderSecurities)
                             .FirstOrDefault(d => d.pk_FolderId == folderId);
                if (folder == null)
                {
                    throw new Exception("Folder Not Found.");
                }

                if (!folder.FolderSecurities.Any(x => createdBy.mySecurityGroups.Contains(x.SecurityObjectId) && x.canCreateFiles))
                {
                    throw new SecurityException("No Access.");
                }


                var file = new File
                {
                    fk_FolderId  = (Guid)folderId,
                    IsDeleted    = false,
                    isRevisioned = true,
                    Name         = name,
                    MimeType     = MimeMapping.GetMimeMapping(name),
                    CreatedById  = createdBy.SecurityObjectId,
                    CreateDt     = DateTime.Now,
                    OwnerId      = createdBy.SecurityObjectId
                };
                context.Files.Add(file);
                context.SaveChanges();

                FileSecurity fileSecurity = new FileSecurity
                {
                    CanDelete        = true,
                    canRead          = true,
                    canWrite         = true,
                    fk_FileId        = file.pk_FileId,
                    SecurityObjectId = createdBy.SecurityObjectId
                };
                context.FileSecurities.Add(fileSecurity);
                context.SaveChanges();

                foreach (FolderSecurity security in folder.FolderSecurities)
                {
                    fileSecurity = context.FileSecurities.FirstOrDefault(d => d.SecurityObjectId == security.SecurityObjectId && d.fk_FileId == file.pk_FileId);
                    if (fileSecurity == null)
                    {
                        fileSecurity = new FileSecurity
                        {
                            CanDelete        = security.canDelete,
                            canRead          = security.canListObjects,
                            canWrite         = security.canCreateFiles,
                            fk_FileId        = file.pk_FileId,
                            SecurityObjectId = security.SecurityObjectId
                        };
                        context.FileSecurities.Add(fileSecurity);
                    }
                    else
                    {
                        fileSecurity.CanDelete = security.canDelete;
                        fileSecurity.canRead   = security.canListObjects;
                        fileSecurity.canWrite  = security.canCreateFiles;
                    }
                }


                context.SaveChanges();
                return(file);
            }
        }
Example #20
0
        /// <summary>
        /// Copies the folderId to this Folder
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="folderId"></param>
        /// <param name="destinationName"></param>
        /// <param name="user"></param>
        /// <param name="context"></param>
        /// <param name="recursive"></param>
        /// <param name="dbcxtransaction"></param>
        public static void CopyFolderHere(this Folder destination, Guid folderId, string destinationName, Principal user, OnlineFilesEntities context = null, bool recursive = true, DbContextTransaction dbcxtransaction = null)
        {
            bool createdContext     = false;
            bool createdTransaction = false;
            bool didRollback        = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }


            if (dbcxtransaction == null)
            {
                dbcxtransaction    = context.Database.BeginTransaction();
                createdTransaction = true;
            }
            try
            {
                var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId);

                //Can the user create folders at the destination location?
                if (destSecurity.Any(d => d.canCreateFolders && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId)))
                {
                    Folder folderToMove = context.Folders.Include(d => d.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderId);
                    if (folderToMove == null)
                    {
                        throw new Exception("Cannot move a non existant folder");
                    }

                    Folder parentToFolderToMove = context.Folders.Include(x => x.FolderSecurities).FirstOrDefault(d => d.pk_FolderId == folderToMove.fk_ParentFolderId);
                    if (parentToFolderToMove == null)
                    {
                        throw new Exception("No parent to folder being moved.");
                    }

                    //Does the user have read permission in the folder the item is comming from?
                    if (parentToFolderToMove.FolderSecurities.Any(d => user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId) && d.canListObjects))
                    {
                        Folder newFolder = Folder.Create(destinationName, destination.pk_FolderId, user.UserProfile, true);
                        context.SaveChanges();
                        if (recursive)
                        {
                            //Get all the files that are in the folder being copied.
                            var files = context.Files.Where(d => d.fk_FolderId == folderToMove.pk_FolderId);
                            foreach (File file in files)
                            {
                                newFolder.CopyFileHere(file.pk_FileId, file.Name, user, context, dbcxtransaction);
                            }
                            //Get all the folders inside the folder we are moving.
                            var folders = context.Folders.Where(d => d.fk_ParentFolderId == folderToMove.pk_FolderId);
                            //Copy the folders to the new location
                            foreach (var folder in folders)
                            {
                                newFolder.CopyFolderHere(folder.pk_FolderId, folder.Name, user, context, recursive, dbcxtransaction);
                            }
                        }
                        context.SaveChanges();
                    }
                    else
                    {
                        throw new SecurityException("Not Authorized.");
                    }
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
            catch (Exception)
            {
                if (createdTransaction)
                {
                    didRollback = true;
                    dbcxtransaction.Rollback();
                }
                throw;
            }

            finally
            {
                if (createdTransaction)
                {
                    if (!didRollback)
                    {
                        dbcxtransaction.Commit();
                    }
                    dbcxtransaction.Dispose();
                }
                if (createdContext)
                {
                    context.Dispose();
                }
            }
        }
Example #21
0
        /// <summary>
        /// Copies the fileId to this Folder.
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="fileId"></param>
        /// <param name="destinationName"></param>
        /// <param name="user"></param>
        /// <param name="context"></param>
        /// <param name="dbcxtransaction"></param>
        public static void CopyFileHere(this Folder destination, Guid fileId, string destinationName, Principal user, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null)
        {
            bool createdContext     = false;
            bool createdTransaction = false;
            bool didRollback        = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }
            if (dbcxtransaction == null)
            {
                dbcxtransaction    = context.Database.BeginTransaction();
                createdTransaction = true;
            }
            try
            {
                var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId);

                //Can the user create files at the destination location?
                if (destSecurity.Any(d => d.canCreateFiles && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId)))
                {
                    var file = context.Files
                               .Include(x => x.FileSecurities)
                               .Include(x => x.FileDatas)
                               .FirstOrDefault(d => d.pk_FileId == fileId);

                    //Can the user Read the file to be copied?
                    if (file.FileSecurities.Any(f => user.UserProfile.mySecurityGroups.Contains(f.SecurityObjectId) && f.canRead))
                    {
                        File newFile = File.Create(destination.pk_FolderId, file.Name, user.UserProfile, true);
                        context.SaveChanges();

                        //Copy the file data
                        using (Stream s = file.OpenReadStream(user))
                            using (Stream d = newFile.OpenWriteStream(user))
                                s.CopyTo(d);

                        //Copy the file Security
                        foreach (FileSecurity security in file.FileSecurities)
                        {
                            FileSecurity nsec = context.FileSecurities.FirstOrDefault(d => d.fk_FileId == newFile.pk_FileId && d.SecurityObjectId == security.SecurityObjectId);
                            if (nsec == null)
                            {
                                nsec = new FileSecurity()
                                {
                                    canRead          = security.canRead,
                                    canWrite         = security.canWrite,
                                    CanDelete        = security.CanDelete,
                                    fk_FileId        = newFile.pk_FileId,
                                    SecurityObjectId = security.SecurityObjectId
                                };
                                context.FileSecurities.Add(nsec);
                            }
                            else
                            {
                                nsec.canRead   = nsec.canRead || security.canRead;
                                nsec.CanDelete = nsec.CanDelete || security.CanDelete;
                                nsec.canWrite  = nsec.canWrite || security.canWrite;
                            }
                        }
                        context.SaveChanges();
                    }
                    else
                    {
                        throw new SecurityException("Not Authorized.");
                    }
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
            catch (Exception)
            {
                //If we got an error and we created the transaction, roll it back.
                if (createdTransaction)
                {
                    dbcxtransaction.Rollback();
                    didRollback = true;
                }
                throw;
            }

            finally
            {
                if (createdTransaction)
                {
                    //If we didn't roll back the transaction, commit it.
                    if (!didRollback)
                    {
                        dbcxtransaction.Commit();
                    }
                    dbcxtransaction.Dispose();
                }
                if (createdContext)
                {
                    context.Dispose();
                }
            }
        }
Example #22
0
 /// <summary>
 ///     Validates that the file name is valid.
 /// </summary>
 /// <param name="parent"></param>
 /// <param name="filename"></param>
 /// <param name="context"></param>
 /// <returns></returns>
 public static string CheckFileName(this Folder parent, string filename, OnlineFilesEntities context = null)
 {
     return(filename);
 }
Example #23
0
        /// <summary>
        ///     Opens a WRITE stream to the file.
        /// </summary>
        /// <param name="user"></param>
        /// <param name="itemPath"></param>
        /// <param name="webDavSqlStoreDocumentFactoryInstance"></param>
        /// <returns></returns>
        public Stream OpenWriteStream(Principal user, string itemPath = null, object webDavSqlStoreDocumentFactoryInstance = null)
        {
            using (var context = new OnlineFilesEntities())
            {
                if (!(context.FileSecurities.Where(d => d.fk_FileId == pk_FileId).ToList().Any(x => user.UserProfile.mySecurityGroups.Contains(x.SecurityObjectId) && x.canWrite)))
                {
                    throw new SecurityException("Not Authorized.");
                }


                int revision = 0;

                FileData fd = context.FileDatas.Include(x => x.Catalog).Where(d => d.fk_FileId == pk_FileId).OrderByDescending(d => d.Revision).FirstOrDefault();
                if (fd != null)
                {
                    revision = fd.Revision;
                }

                revision++;


                Catalog catalog;
                if (fd == null || fd.Catalog.fk_CatalogStatusId != CatalogStatus.Open)
                {
                    Folder f = context.Folders.FirstOrDefault(d => d.pk_FolderId == fk_FolderId);
                    if (f == null)
                    {
                        throw new Exception("Null ptr");
                    }

                    CatalogCollection t = context.CatalogCollections.Include(d => d.Catalogs).FirstOrDefault(d => d.pk_CatalogCollectionId == f.fk_CatalogCollectionId);
                    if (t == null)
                    {
                        throw new Exception("Cat col is null");
                    }
                    catalog = t.Catalogs.FirstOrDefault(d => d.fk_CatalogStatusId == CatalogStatus.Open);
                    if (catalog == null)
                    {
                        throw new Exception("No Catalog Available.");
                    }
                }
                else
                {
                    catalog = fd.Catalog;
                }


                if (catalog == null)
                {
                    throw new Exception("No Catalog Available for file.");
                }

                using (var ctx = new OnlineFiles_CatalogEntities(catalog.EntityConnectionString))
                {
                    FileCatalogEntry fce = new FileCatalogEntry
                    {
                        binaryData = _emptyBytes.ToArray()
                    };
                    ctx.FileCatalogEntries.Add(fce);

                    ctx.SaveChanges();

                    FileData filedata = new FileData
                    {
                        fk_FileId    = pk_FileId,
                        Revision     = revision,
                        Size         = 0,
                        CreateDt     = DateTime.Now,
                        fk_CatalogId = catalog.pk_CatalogId,
                        fk_ContentId = fce.pk_FileCatalogEntryId
                    };

                    context.FileDatas.Add(filedata);

                    context.SaveChanges();

                    Stream stream = new SqlStoreFileStream
                    {
                        CatalogId          = catalog.pk_CatalogId,
                        FileCatalogEntryId = fce.pk_FileCatalogEntryId,
                        Path       = itemPath,
                        FileDataId = filedata.pk_FileDataId,
                        WebDavSqlStoreDocumentFactoryInstance = webDavSqlStoreDocumentFactoryInstance
                    };

                    return(stream);
                }
            }
        }
Example #24
0
        /// <summary>
        /// Creates a new Folder object.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentFolderGuid"></param>
        /// <param name="createdBy"></param>
        /// <param name="inheritSecurity"></param>
        /// <param name="isSystemCreate"></param>
        /// <returns></returns>
        public static Folder Create(string name, Guid?parentFolderGuid, SecurityObject createdBy, bool inheritSecurity = true, bool isSystemCreate = false)
        {
            using (var context = new OnlineFilesEntities())
            {
                //Get Folder object for parent folder
                Folder parentFolder = context.Folders
                                      .Include(x => x.CatalogCollection)
                                      .Include(x => x.FolderSecurities)
                                      .FirstOrDefault(d => d.pk_FolderId == parentFolderGuid);

                if (!isSystemCreate)
                {
                    if (!(parentFolder.FolderSecurities.Any(x => createdBy.mySecurityGroups.Contains(x.SecurityObjectId) && x.canCreateFolders)))
                    {
                        throw new SecurityException("Not Authorized.");
                    }
                }


                //Check Name
                name = parentFolder.CheckFolderName(name);

                //If Parent Folder is null, throw exception
                if (parentFolder == null)
                {
                    throw new Exception("Folder is null");
                }


                //Create Folder
                Folder f = new Folder
                {
                    fk_ParentFolderId = parentFolderGuid,
                    Name     = name,
                    CreateDt = DateTime.Now,
                    fk_CatalogCollectionId = parentFolder.fk_CatalogCollectionId,
                    Win32FileAttribute     = (int)FileAttributes.Directory,
                    IsDeleted   = false,
                    DeletedDt   = null,
                    DeletedBy   = null,
                    OwnerId     = createdBy.SecurityObjectId,
                    CreatedById = createdBy.SecurityObjectId
                };
                try
                {
                    context.Folders.Add(f);
                    context.SaveChanges();
                    var pfs = new FolderSecurity()
                    {
                        canDelete            = true,
                        canListObjects       = true,
                        canCreateFiles       = true,
                        canCreateFolders     = true,
                        canChangePermissions = true,
                        fk_FolderId          = f.pk_FolderId,
                        SecurityObjectId     = createdBy.SecurityObjectId
                    };
                    context.SaveChanges();


                    if (inheritSecurity)
                    {
                        foreach (FolderSecurity fs in parentFolder.FolderSecurities)
                        {
                            FolderSecurity folderSecurity = new FolderSecurity()
                            {
                                SecurityObjectId     = fs.SecurityObjectId,
                                fk_FolderId          = f.pk_FolderId,
                                canCreateFolders     = fs.canCreateFolders,
                                canDelete            = fs.canDelete,
                                canChangePermissions = fs.canChangePermissions,
                                canCreateFiles       = fs.canCreateFiles,
                                canListObjects       = fs.canListObjects
                            };
                            context.FolderSecurities.Add(folderSecurity);
                        }

                        context.SaveChanges();

                        FolderSecurity us = context.FolderSecurities.FirstOrDefault(d => d.fk_FolderId == f.pk_FolderId && d.SecurityObjectId == createdBy.SecurityObjectId);
                        if (us == null)
                        {
                            us = new FolderSecurity()
                            {
                                canListObjects       = true,
                                canChangePermissions = true,
                                canCreateFiles       = true,
                                canCreateFolders     = true,
                                canDelete            = true,
                                fk_FolderId          = f.pk_FolderId,
                                SecurityObjectId     = createdBy.SecurityObjectId
                            };
                            context.FolderSecurities.Add(us);
                        }
                        else
                        {
                            us.canListObjects       = true;
                            us.canChangePermissions = true;
                            us.canCreateFolders     = true;
                            us.canCreateFiles       = true;
                            us.canDelete            = true;
                        }
                        context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to create new folder.", ex);
                }
                return(f);
            }
        }
Example #25
0
        /// <summary>
        /// Will set the permissions for the targetUser, use recursive if you want it to propagate to child file and folders.
        /// context & dbcxtransaction should be null.
        /// </summary>
        /// <param name="FolderId"></param>
        /// <param name="user"></param>
        /// <param name="targetUser"></param>
        /// <param name="canListObjects"></param>
        /// <param name="canCreateFiles"></param>
        /// <param name="canCreateFolders"></param>
        /// <param name="canDelete"></param>
        /// <param name="canChangePermissions"></param>
        /// <param name="recursive"></param>
        /// <param name="context"></param>
        /// <param name="dbcxtransaction"></param>
        public static void SetPermissions(Guid FolderId, Principal user, Principal targetUser, bool canListObjects, bool canCreateFiles, bool canCreateFolders, bool canDelete, bool canChangePermissions, bool recursive = false, OnlineFilesEntities context = null, DbContextTransaction dbcxtransaction = null)
        {
            bool createdContext     = false;
            bool createdTransaction = false;
            bool didRollback        = false;

            if (context == null)
            {
                createdContext = true;
                context        = new OnlineFilesEntities();
            }


            if (dbcxtransaction == null)
            {
                dbcxtransaction    = context.Database.BeginTransaction();
                createdTransaction = true;
            }
            try
            {
                Folder target = context.Folders
                                .Include(d => d.FolderSecurities)
                                .FirstOrDefault(d => d.pk_FolderId == FolderId);

                //Can the user Change Permissions
                if (target.FolderSecurities.Any(d => d.canChangePermissions && user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId)))
                {
                    var secRecord = target.FolderSecurities.FirstOrDefault(d => d.SecurityObjectId == targetUser.UserProfile.SecurityObjectId);
                    if (secRecord == null)
                    {
                        secRecord = new FolderSecurity()
                        {
                            SecurityObjectId     = targetUser.UserProfile.SecurityObjectId,
                            canChangePermissions = canChangePermissions,
                            canListObjects       = canListObjects,
                            canCreateFolders     = canCreateFolders,
                            canCreateFiles       = canCreateFiles,
                            canDelete            = canDelete,
                            fk_FolderId          = target.pk_FolderId
                        };
                        target.FolderSecurities.Add(secRecord);
                    }
                    else
                    {
                        secRecord.canListObjects       = canListObjects;
                        secRecord.canChangePermissions = canChangePermissions;
                        secRecord.canCreateFiles       = canCreateFiles;
                        secRecord.canCreateFolders     = canCreateFolders;
                        secRecord.canDelete            = canDelete;
                    }
                    foreach (File source in context.Files.Where(d => d.fk_FolderId == target.pk_FolderId))
                    {
                        File.SetPermissions(source.pk_FileId, user, targetUser, canListObjects, canCreateFiles, canDelete, context, dbcxtransaction);
                    }

                    context.SaveChanges();
                    if (recursive)
                    {
                        foreach (Folder folder in context.Folders.Where(d => d.fk_ParentFolderId == target.pk_FolderId))
                        {
                            SetPermissions(folder.pk_FolderId, user, targetUser, canListObjects, canCreateFiles, canCreateFolders, canDelete, canChangePermissions, recursive, context, dbcxtransaction);
                        }
                    }
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
            catch (Exception)
            {
                if (createdTransaction)
                {
                    didRollback = true;
                    dbcxtransaction.Rollback();
                }
                throw;
            }

            finally
            {
                if (createdTransaction)
                {
                    if (!didRollback)
                    {
                        dbcxtransaction.Commit();
                    }
                    dbcxtransaction.Dispose();
                }
                if (createdContext)
                {
                    context.Dispose();
                }
            }
        }