/// <summary>
        ///     The get identity.
        /// </summary>
        /// <param name="username">
        ///     The username.
        /// </param>
        /// <returns>
        ///     The <see cref="UserIdentity" />.
        /// </returns>
        internal static UserIdentity GetIdentity(string username)
        {
            using (var context = new OnlineFilesEntities())
            {
                username = Principal.GetLogin(username);
                var userIdentity = new UserIdentity();

                // Get the SecurityObject being requested.
                SecurityObject userProfile = context.GetUserValidation(username, ConfigurationManager.AppSettings["LDAP_SETTING"]).FirstOrDefault();
                if (userProfile == null)
                {
                    throw new Exception("User Not Found");
                }
                userProfile._MySecurityGroups = context.GetSecurityTokens(userProfile.SecurityObjectId).ToList();
                context.SaveChanges();
                if (userProfile.HomeFolder == null)
                {
                    Folder homeFolder = Folder.Create(userProfile.FullName, new Guid(), userProfile, true, true);
                    userProfile.HomeFolder = homeFolder.pk_FolderId;
                    context.SaveChanges();
                }
                // Ensure that the SecurityObject's Permissions are loaded.
                context.Entry(userProfile).Collection(so => so.SecurityObjectPermissions).Query().Include(sop => sop.Permission).Load();
                userIdentity.LoadUser(userProfile);
                return(userIdentity);
            }
        }
Example #2
0
        public override IWebDavFileInfo GetFileInfo()
        {
            if (_fileinfo != null)
            {
                return(_fileinfo);
            }

            using (var context = new OnlineFilesEntities())
            {
                File file = context.Files.AsNoTracking().Include(x => x.FileDatas).FirstOrDefault(d => d.pk_FileId == ObjectGuid);
                if (file == null)
                {
                    return new WebDaveSqlStoreFileInfo
                           {
                               Parent    = ParentCollection,
                               Path      = string.Empty,
                               Exists    = false,
                               Directory = false
                           }
                }
                ;

                _fileinfo = new WebDaveSqlStoreFileInfo(file.GetFileInfo(), ParentCollection, ItemPath);

                return(_fileinfo);
            }
        }
    }
        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public IWebDavStoreItem GetItemByName(string name)
        {
            string path = Path.Combine(ItemPath, name);

#if DEBUG
            Log.Warn("Parent: " + ObjectGuid + " - Requesting Item by name: " + path);
#endif
            using (var context = new OnlineFilesEntities())
            {
                Folder folder = context.Folders.AsNoTracking().FirstOrDefault(d =>
                                                                              d.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) &&
                                                                              d.fk_ParentFolderId == ObjectGuid &&
                                                                              !d.IsDeleted
                                                                              );
                if (folder != null)
                {
                    return(WebDavSqlStoreCollectionFactory.Instance.GetCollection(this, Path.Combine(ItemPath, folder.Name), RootPath, RootGuid));
                }

                File file = context.Files.AsNoTracking().FirstOrDefault(d => d.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) &&
                                                                        d.fk_FolderId == ObjectGuid && !d.IsDeleted);
                if (file != null)
                {
                    return(WebDavSqlStoreDocumentFactory.Instance.GetDocument(this, Path.Combine(ItemPath, file.Name), RootPath, RootGuid));
                }
            }

            return(null);
        }
        /// <summary>
        /// Moves the folderId to this Folder
        /// folderId is the folder to move.
        /// </summary>
        /// <param name="destination"></param>
        /// <param name="folderId"></param>
        /// <param name="destinationName"></param>
        /// <param name="user"></param>
        public static void MoveFolderHere(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 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 delete permission in the folder the item is comming from?
                    if (parentToFolderToMove.FolderSecurities.Any(d => user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId) && d.canDelete))
                    {
                        folderToMove.Name = destination.CheckFolderName(destinationName, context);
                        folderToMove.fk_ParentFolderId = destination.pk_FolderId;
                        context.SaveChanges();
                    }
                    else
                    {
                        throw new SecurityException("Not Authorized.");
                    }
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
        }
Example #5
0
        /// <summary>
        ///     Creates a new SQL Lock.
        /// </summary>
        /// <param name="inst"></param>
        /// <param name="storeItem"></param>
        /// <returns></returns>
        private static Guid CreateSqlLock(ref WebDavSqlStoreItemLockInstance inst, WebDavSqlStoreItem storeItem)
        {
            try
            {
                using (var context = new OnlineFilesEntities())
                {
                    var t = context.Files.FirstOrDefault(d => d.pk_FileId == storeItem.ObjectGuid);


                    ObjectLockInfo info = new ObjectLockInfo
                    {
                        CreateDt             = inst.CreateDate,
                        Depth                = inst.Depth,
                        ExpirationDate       = inst.ExpirationDate,
                        LockScope            = (int)inst.LockScope,
                        LockType             = (int)inst.LockType,
                        ObjectGuid           = (Guid)storeItem.ObjectGuid,
                        OwnerId              = inst.SoOwner.SecurityObjectId,
                        Path                 = storeItem.Href.ToString(),
                        RequestedLockTimeout = inst.RequestedLockTimeout,
                        isFolder             = storeItem.IsCollection
                    };

                    context.ObjectLockInfoes.Add(info);
                    context.SaveChanges();
                    inst.Token = info.Token;
                    return(info.Token);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
        public override void Apply()
        {
            using (var context = new OnlineFilesEntities())
            {
                if (Directory)
                {
                    Folder folder = context.Folders.FirstOrDefault(d => d.pk_FolderId == ObjectGuid);
                    if (folder == null)
                    {
                        return;
                    }

                    folder.SetWin32Attribute(FileAttributes.Directory, Directory);
                    folder.SetWin32Attribute(FileAttributes.Archive, Archive);
                    folder.SetWin32Attribute(FileAttributes.Compressed, Compressed);
                    folder.SetWin32Attribute(FileAttributes.Device, Device);
                    folder.SetWin32Attribute(FileAttributes.Encrypted, Encrypted);
                    folder.SetWin32Attribute(FileAttributes.Hidden, Hidden);
                    folder.SetWin32Attribute(FileAttributes.IntegrityStream, IntegrityStream);
                    folder.SetWin32Attribute(FileAttributes.Normal, Normal);
                    folder.SetWin32Attribute(FileAttributes.NoScrubData, NoScrubData);
                    folder.SetWin32Attribute(FileAttributes.NotContentIndexed, NotContentIndexed);
                    folder.SetWin32Attribute(FileAttributes.Offline, Offline);
                    folder.SetWin32Attribute(FileAttributes.ReadOnly, ReadOnly);
                    folder.SetWin32Attribute(FileAttributes.ReparsePoint, ReparsePoint);
                    folder.SetWin32Attribute(FileAttributes.SparseFile, SparseFile);
                    folder.SetWin32Attribute(FileAttributes.System, System);
                    folder.SetWin32Attribute(FileAttributes.Temporary, Temporary);
                    context.SaveChanges();
                }
                else
                {
                    File file = context.Files.FirstOrDefault(d => d.pk_FileId == ObjectGuid);
                    if (file == null)
                    {
                        return;
                    }
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Directory, Directory);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Archive, Archive);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Compressed, Compressed);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Device, Device);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Encrypted, Encrypted);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Hidden, Hidden);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.IntegrityStream, IntegrityStream);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Normal, Normal);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.NoScrubData, NoScrubData);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.NotContentIndexed, NotContentIndexed);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Offline, Offline);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.ReadOnly, ReadOnly);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.ReparsePoint, ReparsePoint);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.SparseFile, SparseFile);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.System, System);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Temporary, Temporary);
                    context.SaveChanges();
                }
            }
        }
 /// <summary>
 /// </summary>
 /// <param name="parentCollection"></param>
 /// <param name="path"></param>
 /// <param name="rootPath"></param>
 /// <param name="rootGuid"></param>
 /// <param name="store"></param>
 public WebDavSqlStoreCollection(IWebDavStoreCollection parentCollection, string path, String rootPath, Guid rootGuid, IWebDavStore store)
     : base(parentCollection, path, rootPath, rootGuid, store)
 {
     using (var context = new OnlineFilesEntities())
     {
         Folder f = context.Folders.AsNoTracking().FirstOrDefault(d => d.pk_FolderId == ObjectGuid);
         if (f != null)
             _creationDt = f.CreateDt;
     }
 }
 /// <summary>
 /// </summary>
 /// <returns></returns>
 public Stream OpenReadStream()
 {
     using (var context = new OnlineFilesEntities())
     {
         File file = context.Files.FirstOrDefault(d => d.pk_FileId == ObjectGuid);
         if (file == null)
             throw new Exception("File Object Not Found.");
         return file.OpenReadStream(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav));
     }
 }
        /// <summary>
        /// </summary>
        /// <param name="append"></param>
        /// <returns></returns>
        public Stream OpenWriteStream(bool append)
        {
            if (append)
                throw new Exception("File Stream Append Not supported.");

            using (var context = new OnlineFilesEntities())
            {
                File f = context.Files.FirstOrDefault(d => d.pk_FileId == ObjectGuid);
                return f?.OpenWriteStream(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), ItemPath);
            }
        }
        private Guid?GetObjectGuid(string path)
        {
            //Remove the \\Data
            path = path.Substring(RootPath.Length).Trim();

            using (var context = new OnlineFilesEntities())
            {
                if (path == RootPath)
                {
                    return(RootGuid);
                }

                List <string> dirpath = path.Split('\\').ToList();
                while (dirpath.Contains(""))
                {
                    dirpath.Remove("");
                }

                Folder parent = context.Folders.FirstOrDefault(d => d.pk_FolderId == RootGuid);

                if (parent == null)
                {
                    throw new Exception("No Parent");
                }

                Guid?returnValue = parent.pk_FolderId;

                for (int index = 0; index < dirpath.Count; index++)
                {
                    string s     = dirpath[index];
                    Folder child = context.Folders.FirstOrDefault(d => d.Name.Equals(s, StringComparison.InvariantCultureIgnoreCase) && d.fk_ParentFolderId == parent.pk_FolderId);
                    if (child != null)
                    {
                        parent      = child;
                        returnValue = parent.pk_FolderId;
                    }
                    else
                    {
                        if (index != dirpath.Count - 1)
                        {
                            throw new Exception("Couldn't find folder.");
                        }
                        File file = context.Files.FirstOrDefault(d => d.Name.Equals(s, StringComparison.InvariantCultureIgnoreCase) && d.fk_FolderId == returnValue && !d.IsDeleted);
                        if (file != null)
                        {
                            returnValue = file.pk_FileId;
                        }
                    }
                }

                return(returnValue);
            }
        }
 /// <summary>
 /// </summary>
 /// <param name="parentCollection"></param>
 /// <param name="path"></param>
 /// <param name="rootPath"></param>
 /// <param name="rootGuid"></param>
 /// <param name="store"></param>
 public WebDavSqlStoreCollection(IWebDavStoreCollection parentCollection, string path, String rootPath, Guid rootGuid, IWebDavStore store)
     : base(parentCollection, path, rootPath, rootGuid, store)
 {
     using (var context = new OnlineFilesEntities())
     {
         Folder f = context.Folders.AsNoTracking().FirstOrDefault(d => d.pk_FolderId == ObjectGuid);
         if (f != null)
         {
             _creationDt = f.CreateDt;
         }
     }
 }
        public override void Apply()
        {
            using (var context = new OnlineFilesEntities())
            {
                if (Directory)
                {
                    Folder folder = context.Folders.FirstOrDefault(d => d.pk_FolderId == ObjectGuid);
                    if (folder == null)
                        return;

                    folder.SetWin32Attribute(FileAttributes.Directory, Directory);
                    folder.SetWin32Attribute(FileAttributes.Archive, Archive);
                    folder.SetWin32Attribute(FileAttributes.Compressed, Compressed);
                    folder.SetWin32Attribute(FileAttributes.Device, Device);
                    folder.SetWin32Attribute(FileAttributes.Encrypted, Encrypted);
                    folder.SetWin32Attribute(FileAttributes.Hidden, Hidden);
                    folder.SetWin32Attribute(FileAttributes.IntegrityStream, IntegrityStream);
                    folder.SetWin32Attribute(FileAttributes.Normal, Normal);
                    folder.SetWin32Attribute(FileAttributes.NoScrubData, NoScrubData);
                    folder.SetWin32Attribute(FileAttributes.NotContentIndexed, NotContentIndexed);
                    folder.SetWin32Attribute(FileAttributes.Offline, Offline);
                    folder.SetWin32Attribute(FileAttributes.ReadOnly, ReadOnly);
                    folder.SetWin32Attribute(FileAttributes.ReparsePoint, ReparsePoint);
                    folder.SetWin32Attribute(FileAttributes.SparseFile, SparseFile);
                    folder.SetWin32Attribute(FileAttributes.System, System);
                    folder.SetWin32Attribute(FileAttributes.Temporary, Temporary);
                    context.SaveChanges();
                }
                else
                {
                    File file = context.Files.FirstOrDefault(d => d.pk_FileId == ObjectGuid);
                    if (file == null)
                        return;
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Directory, Directory);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Archive, Archive);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Compressed, Compressed);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Device, Device);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Encrypted, Encrypted);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Hidden, Hidden);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.IntegrityStream, IntegrityStream);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Normal, Normal);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.NoScrubData, NoScrubData);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.NotContentIndexed, NotContentIndexed);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Offline, Offline);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.ReadOnly, ReadOnly);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.ReparsePoint, ReparsePoint);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.SparseFile, SparseFile);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.System, System);
                    file.SetWin32Attribute(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), FileAttributes.Temporary, Temporary);
                    context.SaveChanges();
                }
            }
        }
Example #13
0
 /// <summary>
 /// </summary>
 /// <returns></returns>
 public Stream OpenReadStream()
 {
     using (var context = new OnlineFilesEntities())
     {
         File file = context.Files.FirstOrDefault(d => d.pk_FileId == ObjectGuid);
         if (file == null)
         {
             throw new Exception("File Object Not Found.");
         }
         return(file.OpenReadStream(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav)));
     }
 }
Example #14
0
        /// <summary>
        /// </summary>
        /// <param name="append"></param>
        /// <returns></returns>
        public Stream OpenWriteStream(bool append)
        {
            if (append)
            {
                throw new Exception("File Stream Append Not supported.");
            }

            using (var context = new OnlineFilesEntities())
            {
                File f = context.Files.FirstOrDefault(d => d.pk_FileId == ObjectGuid);
                return(f?.OpenWriteStream(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav), ItemPath));
            }
        }
        public override IWebDavFileInfo GetFileInfo()
        {
            if (_fileinfo != null)
            {
                return(_fileinfo);
            }

            using (var context = new OnlineFilesEntities())
            {
                Folder folder = context.Folders.AsNoTracking()
                                .FirstOrDefault(d => d.pk_FolderId == ObjectGuid);
                if (folder == null)
                {
                    return new WebDaveSqlStoreFileInfo
                           {
                               Parent    = ParentCollection,
                               Path      = "",
                               Exists    = false,
                               Directory = true
                           }
                }
                ;
                return(new WebDaveSqlStoreFileInfo
                {
                    Parent = ParentCollection,
                    Path = ItemPath,
                    Exists = true,
                    CreationTime = folder.CreateDt,
                    LastAccessTime = folder.CreateDt,
                    LastWriteTime = folder.CreateDt,
                    Archive = folder.GetWin32Attribute(FileAttributes.Archive),
                    Compressed = folder.GetWin32Attribute(FileAttributes.Compressed),
                    Device = folder.GetWin32Attribute(FileAttributes.Device),
                    Directory = true,
                    Hidden = folder.GetWin32Attribute(FileAttributes.Hidden),
                    Encrypted = folder.GetWin32Attribute(FileAttributes.Encrypted),
                    IntegrityStream = folder.GetWin32Attribute(FileAttributes.IntegrityStream),
                    NoScrubData = folder.GetWin32Attribute(FileAttributes.NoScrubData),
                    Normal = folder.GetWin32Attribute(FileAttributes.Normal),
                    NotContentIndexed = folder.GetWin32Attribute(FileAttributes.NotContentIndexed),
                    Offline = folder.GetWin32Attribute(FileAttributes.Offline),
                    ReadOnly = folder.GetWin32Attribute(FileAttributes.ReadOnly),
                    ReparsePoint = folder.GetWin32Attribute(FileAttributes.ReparsePoint),
                    SparseFile = folder.GetWin32Attribute(FileAttributes.SparseFile),
                    System = folder.GetWin32Attribute(FileAttributes.System),
                    Temporary = folder.GetWin32Attribute(FileAttributes.Temporary),
                    ObjectGuid = ObjectGuid
                });
            }
        }
        /// <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;
                }
            }
        }
 /// <summary>
 ///     Retrieves all locks for the passed object
 /// </summary>
 /// <param name="storeItem">Item to look for locks for.</param>
 /// <returns></returns>
 public override List<IWebDavStoreItemLockInstance> GetLocks(IWebDavStoreItem storeItem)
 {
     try
     {
         List<IWebDavStoreItemLockInstance> items = new List<IWebDavStoreItemLockInstance>();
         using (var context = new OnlineFilesEntities())
         {
             List<ObjectLockInfo> result;
             WebDavSqlStoreCollection item = storeItem as WebDavSqlStoreCollection;
             if (item != null)
             {
                 var collection = item;
                 result = context.ObjectLockInfoes.AsNoTracking().Where(d => d.ObjectGuid == collection.ObjectGuid && d.isFolder).ToList();
             }
             else
             {
                 WebDavSqlStoreDocument storeDocument = storeItem as WebDavSqlStoreDocument;
                 if (storeDocument != null)
                 {
                     var document = storeDocument;
                     result = context.ObjectLockInfoes.AsNoTracking().Where(d => d.ObjectGuid == document.ObjectGuid && !d.isFolder).ToList();
                 }
                 else
                 {
                     throw new NotSupportedException();
                 }
             }
             items.AddRange(result.Select(lockInfo => new WebDavSqlStoreItemLockInstance(
                 PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                 lockInfo.Path,
                 (WebDavLockScope) lockInfo.LockScope,
                 (WebDavLockType) lockInfo.LockType,
                 lockInfo.Owner.ToString(),
                 lockInfo.RequestedLockTimeout,
                 lockInfo.Token,
                 new XmlDocument(),
                 lockInfo.Depth,
                 this,
                 lockInfo.CreateDt
                 )));
             return items;
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message + ex.StackTrace);
         throw;
     }
 }
Example #18
0
        private static void DownloadAdsGroupsMembership()
        {
            using (var context = new OnlineFilesEntities())
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
                    using (var groupPrincipal = new GroupPrincipalEx(ctx))
                        using (PrincipalSearcher search = new PrincipalSearcher(groupPrincipal))
                        {
                            int max = search.FindAll().Count();
                            int c   = 0;
                            foreach (var gp in search.FindAll().Select(found => found as GroupPrincipalEx))
                            {
                                Console.WriteLine("Processing " + c + " of " + max);
                                c++;
                                if (gp != null)
                                {
                                    if (gp.IsSecurityGroup != true && gp.GroupScope == GroupScope.Local)
                                    {
                                        continue;
                                    }
                                    var so = context.SecurityObjects.Include(d => d.MyGroups).FirstOrDefault(d => d.ActiveDirectoryId == gp.Guid);
                                    if (so == null)
                                    {
                                        throw new Exception("Not Possible");
                                    }

                                    context.SecurityObjectMemberships.RemoveRange(context.SecurityObjectMemberships.Where(d => d.SecurityObjectId == so.SecurityObjectId));
                                    context.SaveChanges();

                                    try
                                    {
                                        foreach (Principal grp in gp.GetGroups())
                                        {
                                            var og = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == grp.Guid);
                                            if (og != null)
                                            {
                                                context.SecurityObjectMemberships.Add(new SecurityObjectMembership {
                                                    OwnerSecurityObject = so, GroupSecurityObjectId = og.SecurityObjectId
                                                });
                                            }
                                        }
                                    }
                                    catch (Exception)
                                    {
                                    }
                                }
                                context.SaveChanges();
                            }
                        }
        }
Example #19
0
 /// <summary>
 ///     Retrieves all locks for the passed object
 /// </summary>
 /// <param name="storeItem">Item to look for locks for.</param>
 /// <returns></returns>
 public override List <IWebDavStoreItemLockInstance> GetLocks(IWebDavStoreItem storeItem)
 {
     try
     {
         List <IWebDavStoreItemLockInstance> items = new List <IWebDavStoreItemLockInstance>();
         using (var context = new OnlineFilesEntities())
         {
             List <ObjectLockInfo>    result;
             WebDavSqlStoreCollection item = storeItem as WebDavSqlStoreCollection;
             if (item != null)
             {
                 var collection = item;
                 result = context.ObjectLockInfoes.AsNoTracking().Where(d => d.ObjectGuid == collection.ObjectGuid && d.isFolder).ToList();
             }
             else
             {
                 WebDavSqlStoreDocument storeDocument = storeItem as WebDavSqlStoreDocument;
                 if (storeDocument != null)
                 {
                     var document = storeDocument;
                     result = context.ObjectLockInfoes.AsNoTracking().Where(d => d.ObjectGuid == document.ObjectGuid && !d.isFolder).ToList();
                 }
                 else
                 {
                     throw new NotSupportedException();
                 }
             }
             items.AddRange(result.Select(lockInfo => new WebDavSqlStoreItemLockInstance(
                                              PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                                              lockInfo.Path,
                                              (WebDavLockScope)lockInfo.LockScope,
                                              (WebDavLockType)lockInfo.LockType,
                                              lockInfo.Owner.ToString(),
                                              lockInfo.RequestedLockTimeout,
                                              lockInfo.Token,
                                              new XmlDocument(),
                                              lockInfo.Depth,
                                              this,
                                              lockInfo.CreateDt
                                              )));
             return(items);
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message + ex.StackTrace);
         throw;
     }
 }
 /// <summary>
 ///     Removes any expired locks
 /// </summary>
 public void CleanLocks()
 {
     try
     {
         using (var context = new OnlineFilesEntities())
         {
             context.ObjectLockInfoes.RemoveRange(context.ObjectLockInfoes.Where(d => d.ExpirationDate < DateTime.Now).ToList());
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message + ex.StackTrace);
         throw;
     }
 }
Example #21
0
 /// <summary>
 ///     Removes any expired locks
 /// </summary>
 public void CleanLocks()
 {
     try
     {
         using (var context = new OnlineFilesEntities())
         {
             context.ObjectLockInfoes.RemoveRange(context.ObjectLockInfoes.Where(d => d.ExpirationDate < DateTime.Now).ToList());
         }
     }
     catch (Exception ex)
     {
         Console.WriteLine(ex.Message + ex.StackTrace);
         throw;
     }
 }
 /// <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 #23
0
 private static void DownloadAdsGroups()
 {
     using (var context = new OnlineFilesEntities())
         using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
             using (var groupPrincipal = new GroupPrincipalEx(ctx))
                 using (PrincipalSearcher search = new PrincipalSearcher(groupPrincipal))
                 {
                     int max = search.FindAll().Count();
                     int c   = 0;
                     foreach (var gp in search.FindAll().Select(found => found as GroupPrincipalEx))
                     {
                         Console.WriteLine("Processing " + c + " of " + max);
                         c++;
                         if (gp != null)
                         {
                             if (gp.IsSecurityGroup != true && gp.GroupScope == GroupScope.Local)
                             {
                                 continue;
                             }
                             var so = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == gp.Guid);
                             if (so == null)
                             {
                                 so = new SecurityObject
                                 {
                                     ActiveDirectoryId = gp.Guid,
                                     FullName          = gp.Name,
                                     Username          = gp.SamAccountName,
                                     EmailAddress      = gp.EmailAddress ?? "",
                                     IsGroup           = true,
                                     LastLogInOn       = DateTime.Now,
                                     IsActive          = true,
                                     HomeFolder        = null
                                 };
                                 context.SecurityObjects.Add(so);
                             }
                             else
                             {
                                 so.IsGroup      = true;
                                 so.FullName     = gp.Name;
                                 so.Username     = gp.SamAccountName;
                                 so.EmailAddress = gp.EmailAddress ?? "";
                             }
                         }
                         context.SaveChanges();
                     }
                 }
 }
        /// <summary>
        /// </summary>
        /// <param name="item"></param>
        public void Delete(IWebDavStoreItem item)
        {
#if DEBUG
            Log.Info("Deleting Item: " + item.Name);
#endif
            if (IsCheckedOut(item))
            {
                throw new Exception("Item is checked out.");
            }

            using (var context = new OnlineFilesEntities())
            {
                var collection = item as WebDavSqlStoreCollection;
                if (collection != null)
                {
                    Folder folder = context.Folders.FirstOrDefault(d => d.pk_FolderId == collection.ObjectGuid);
                    if (folder == null)
                    {
                        throw new WebDavNotFoundException("Folder Not Found.");
                    }
                    folder.SetDeleted(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile);
                    context.SaveChanges();
                    WebDavSqlStoreCollectionFactory.Instance.InvalidateCollection(item.ItemPath);
                    WebDavSqlStoreCollectionFactory.Instance.InvalidateCollection(ItemPath);
                }
                else
                {
                    WebDavSqlStoreDocument document = item as WebDavSqlStoreDocument;
                    if (document == null)
                    {
                        return;
                    }
                    var  doc  = document;
                    File file = context.Files.FirstOrDefault(d => d.pk_FileId == doc.ObjectGuid);
                    if (file == null)
                    {
                        throw new WebDavNotFoundException("Folder Not Found.");
                    }
                    file.SetDeleted(PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile);
                    context.SaveChanges();
                    WebDavSqlStoreCollectionFactory.Instance.InvalidateCollection(ItemPath);
                    WebDavSqlStoreDocumentFactory.Instance.InvalidateDocumentPath(doc.ItemPath);
                }
            }
        }
        private Guid? GetObjectGuid(string path)
        {
            //Remove the \\Data
            path = path.Substring(RootPath.Length).Trim();

            using (var context = new OnlineFilesEntities())
            {
                if (path == RootPath)
                    return RootGuid;

                List<string> dirpath = path.Split('\\').ToList();
                while (dirpath.Contains(""))
                    dirpath.Remove("");

                Folder parent = context.Folders.FirstOrDefault(d => d.pk_FolderId == RootGuid);

                if (parent == null)
                    throw new Exception("No Parent");

                Guid? returnValue = parent.pk_FolderId;

                for (int index = 0; index < dirpath.Count; index++)
                {
                    string s = dirpath[index];
                    Folder child = context.Folders.FirstOrDefault(d => d.Name.Equals(s, StringComparison.InvariantCultureIgnoreCase) && d.fk_ParentFolderId == parent.pk_FolderId);
                    if (child != null)
                    {
                        parent = child;
                        returnValue = parent.pk_FolderId;
                    }
                    else
                    {
                        if (index != dirpath.Count - 1)
                        {
                            throw new Exception("Couldn't find folder.");
                        }
                        File file = context.Files.FirstOrDefault(d => d.Name.Equals(s, StringComparison.InvariantCultureIgnoreCase) && d.fk_FolderId == returnValue && !d.IsDeleted);
                        if (file != null)
                            returnValue = file.pk_FileId;
                    }
                }

                return returnValue;
            }
        }
 private static void DownloadAdsGroups()
 {
     using (var context = new OnlineFilesEntities())
     using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
     using (var groupPrincipal = new GroupPrincipalEx(ctx))
     using (PrincipalSearcher search = new PrincipalSearcher(groupPrincipal))
     {
         int max = search.FindAll().Count();
         int c = 0;
         foreach (var gp in search.FindAll().Select(found => found as GroupPrincipalEx))
         {
             Console.WriteLine("Processing " + c + " of " + max);
             c++;
             if (gp != null)
             {
                 if (gp.IsSecurityGroup != true && gp.GroupScope == GroupScope.Local)
                     continue;
                 var so = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == gp.Guid);
                 if (so == null)
                 {
                     so = new SecurityObject
                     {
                         ActiveDirectoryId = gp.Guid,
                         FullName = gp.Name,
                         Username = gp.SamAccountName,
                         EmailAddress = gp.EmailAddress ?? "",
                         IsGroup = true,
                         LastLogInOn = DateTime.Now,
                         IsActive = true,
                         HomeFolder = null
                     };
                     context.SecurityObjects.Add(so);
                 }
                 else
                 {
                     so.IsGroup = true;
                     so.FullName = gp.Name;
                     so.Username = gp.SamAccountName;
                     so.EmailAddress = gp.EmailAddress ?? "";
                 }
             }
             context.SaveChanges();
         }
     }
 }
        /// <summary>
        /// </summary>
        /// <param name="source"></param>
        /// <param name="destinationName"></param>
        /// <returns></returns>
        public IWebDavStoreItem MoveItemHere(IWebDavStoreItem source, string destinationName)
        {
            //this -> is where it wants to be moved to.
            //source is the item
            //destination name is the name they want it to be.
            IWebDavStoreItem returnitem;

            using (var context = new OnlineFilesEntities())
            {
                var sourceFolder = source as WebDavSqlStoreCollection;
                if (sourceFolder != null)
                {
                    Folder targetFolder = context.Folders.FirstOrDefault(d => d.pk_FolderId == sourceFolder.ObjectGuid);
                    if (targetFolder == null)
                    {
                        return(null);
                    }

                    Folder destination = context.Folders.FirstOrDefault(d => d.pk_FolderId == ObjectGuid);
                    destination.MoveFolderHere(targetFolder.pk_FolderId, destinationName, PrincipleFactory.Instance.GetPrinciple(FromType.WebDav));
                    context.SaveChanges();
                    WebDavSqlStoreCollectionFactory.Instance.InvalidateCollection(ItemPath);
                    WebDavSqlStoreCollectionFactory.Instance.InvalidateCollection(sourceFolder.ItemPath);
                    WebDavSqlStoreCollectionFactory.Instance.InvalidateCollection(Path.Combine(ItemPath, destinationName));
                    returnitem = WebDavSqlStoreCollectionFactory.Instance.GetCollection(this, Path.Combine(ItemPath, destinationName), RootPath, RootGuid);
                }
                else
                {
                    WebDavSqlStoreDocument document = source as WebDavSqlStoreDocument;
                    if (document == null)
                    {
                        return(null);
                    }
                    WebDavSqlStoreDocument doc = document;
                    var destFolder             = context.Folders.FirstOrDefault(d => d.pk_FolderId == ObjectGuid);
                    destFolder.MoveFileHere((Guid)document.ObjectGuid, destinationName, PrincipleFactory.Instance.GetPrinciple(FromType.WebDav));
                    WebDavSqlStoreDocumentFactory.Instance.InvalidateDocumentPath(Path.Combine(ItemPath, destinationName));
                    WebDavSqlStoreCollectionFactory.Instance.InvalidateCollection(ItemPath);
                    returnitem = WebDavSqlStoreDocumentFactory.Instance.GetDocument(this, Path.Combine(ItemPath, destinationName), RootPath, RootGuid);
                }
            }
            return(returnitem);
        }
        /// <summary>
        /// </summary>
        /// <param name="parentCollection"></param>
        /// <param name="name"></param>
        /// <param name="rootPath"></param>
        /// <param name="rootGuid"></param>
        /// <param name="store"></param>
        public WebDavSqlStoreDocument(IWebDavStoreCollection parentCollection, string name, String rootPath, Guid rootGuid, IWebDavStore store)
            : base(parentCollection, name, rootPath, rootGuid, store)
        {
            using (var context = new OnlineFilesEntities())
            {
                File file = context.Files.AsNoTracking()
                    .Include(x => x.FileDatas)
                    .FirstOrDefault(d => d.pk_FileId == ObjectGuid && !d.IsDeleted);

                if (file == null)
                    throw new Exception("Non existant file.");
                _createDate = file.CreateDt;

                FileData lastmod = file.FileDatas.OrderByDescending(d => d.Revision).FirstOrDefault();

                _modificationDate = lastmod?.CreateDt ?? file.CreateDt;
                _filesize = lastmod?.Size ?? 1;
            }
        }
Example #29
0
        /// <summary>
        ///     Refreshes an existing lock
        /// </summary>
        /// <param name="storeItem"></param>
        /// <param name="locktoken"></param>
        /// <param name="requestedlocktimeout"></param>
        /// <param name="requestDocument"></param>
        /// <returns></returns>
        public override int RefreshLock(IWebDavStoreItem storeItem, Guid?locktoken, double?requestedlocktimeout, out XmlDocument requestDocument)
        {
            try
            {
                CleanLocks();
                requestDocument = null;
                if (locktoken == null)
                {
                    throw new WebDavNotFoundException("Must have a lock to refresh.");
                }

                using (var context = new OnlineFilesEntities())
                {
                    var info = context.ObjectLockInfoes.FirstOrDefault(d => d.Token == locktoken);
                    if (info == null)
                    {
                        throw new WebDavNotFoundException("Lock Token Not Found.");
                    }

                    IWebDavStoreItemLockInstance inst = new WebDavSqlStoreItemLockInstance(
                        PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                        info.Path, (WebDavLockScope)info.LockScope, (WebDavLockType)info.LockType,
                        info.Owner.ToString(),
                        info.RequestedLockTimeout, info.Token, new XmlDocument(), info.Depth, this, info.CreateDt
                        );

                    inst.RefreshLock(requestedlocktimeout);
                    info.CreateDt             = inst.CreateDate;
                    info.ExpirationDate       = inst.ExpirationDate;
                    info.RequestedLockTimeout = inst.RequestedLockTimeout;
                    context.SaveChanges();
                    requestDocument = new XmlDocument();
                    return((int)HttpStatusCode.OK);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
 public bool IsCheckedOut(IWebDavStoreItem item)
 {
     using (var context = new OnlineFilesEntities())
     {
         List <SpDoAnyChildrenHaveLocksResult> cellData =
             context.Database.SqlQuery <SpDoAnyChildrenHaveLocksResult>
                 ($"dbo.sp_DoAnyChildrenHaveLocks '{((WebDavSqlStoreItem) item).ObjectGuid}'").ToList();
         if (cellData.Any())
         {
             if (cellData[0].Exists)
             {
                 return(true);
             }
         }
         else
         {
             throw new WebDavNotFoundException("Shouldn't get here.");
         }
         return(false);
     }
 }
Example #31
0
        /// <summary>
        /// </summary>
        /// <param name="parentCollection"></param>
        /// <param name="name"></param>
        /// <param name="rootPath"></param>
        /// <param name="rootGuid"></param>
        /// <param name="store"></param>
        public WebDavSqlStoreDocument(IWebDavStoreCollection parentCollection, string name, String rootPath, Guid rootGuid, IWebDavStore store)
            : base(parentCollection, name, rootPath, rootGuid, store)
        {
            using (var context = new OnlineFilesEntities())
            {
                File file = context.Files.AsNoTracking()
                            .Include(x => x.FileDatas)
                            .FirstOrDefault(d => d.pk_FileId == ObjectGuid && !d.IsDeleted);

                if (file == null)
                {
                    throw new Exception("Non existant file.");
                }
                _createDate = file.CreateDt;

                FileData lastmod = file.FileDatas.OrderByDescending(d => d.Revision).FirstOrDefault();

                _modificationDate = lastmod?.CreateDt ?? file.CreateDt;
                _filesize         = lastmod?.Size ?? 1;
            }
        }
Example #32
0
        /// <summary>
        ///     unlocks an existing lock
        /// </summary>
        /// <param name="storeItem"></param>
        /// <param name="locktoken"></param>
        /// <param name="owner"></param>
        /// <returns></returns>
        public override int UnLock(IWebDavStoreItem storeItem, Guid?locktoken, string owner)
        {
            try
            {
                CleanLocks();
                if (locktoken == null)
                {
//#if DEBUG
//                    WebDavServer.Log.Debug("Unlock failed, No Token!.");
//#endif
                    return((int)HttpStatusCode.BadRequest);
                }
                using (var context = new OnlineFilesEntities())
                {
                    var info = context.ObjectLockInfoes.FirstOrDefault(d => d.Token == locktoken);

                    if (info == null)
                    {
                        throw new WebDavNotFoundException("Lock Token Not Found.");
                    }

                    if (info.OwnerId != PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile.SecurityObjectId)
                    {
                        throw new WebDavUnauthorizedException("You did not create the lock.");
                    }


                    context.ObjectLockInfoes.Remove(info);
                    context.SaveChanges();
                    return((int)HttpStatusCode.NoContent);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
        public List <IWebDavStoreItem> GetItems()
        {
            List <IWebDavStoreItem> items = new List <IWebDavStoreItem>();

            using (var context = new OnlineFilesEntities())
            {
                var currentFolder = context.Folders
                                    .Include(c => c.Files)
                                    .Include(c => c.ChildFolders)
                                    .FirstOrDefault(d => d.pk_FolderId == ObjectGuid);

                if (currentFolder == null)
                {
                    return(items);
                }

                Principal p = PrincipleFactory.Instance.GetPrinciple(FromType.WebDav);

                try
                {
                    items.AddRange(context.GetChildFolders(ObjectGuid, p, true).Select(folder => WebDavSqlStoreCollectionFactory.Instance.GetCollection(this, Path.Combine(ItemPath, folder.Name), RootPath, RootGuid)));
                }
                catch (SecurityException)
                {
                }
                try
                {
                    items.AddRange(context.GetChildFiles(ObjectGuid, p, true).Select(file => WebDavSqlStoreDocumentFactory.Instance.GetDocument(this, Path.Combine(ItemPath, file.Name), RootPath, RootGuid)));
                }
                catch (SecurityException)
                {
                }
            }


            return(items);
        }
        /// <summary>
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public IWebDavStoreItem GetItemByName(string name)
        {
            string path = Path.Combine(ItemPath, name);
#if DEBUG
            Log.Warn("Parent: " + ObjectGuid + " - Requesting Item by name: " + path);
#endif
            using (var context = new OnlineFilesEntities())
            {
                Folder folder = context.Folders.AsNoTracking().FirstOrDefault(d =>
                    d.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase) &&
                    d.fk_ParentFolderId == ObjectGuid &&
                    !d.IsDeleted
                    );
                if (folder != null)
                    return WebDavSqlStoreCollectionFactory.Instance.GetCollection(this, Path.Combine(ItemPath, folder.Name), RootPath, RootGuid);

                File file = context.Files.AsNoTracking().FirstOrDefault(d => d.Name.Equals(name, StringComparison.InvariantCultureIgnoreCase)
                                                                             && d.fk_FolderId == ObjectGuid && !d.IsDeleted);
                if (file != null)
                    return WebDavSqlStoreDocumentFactory.Instance.GetDocument(this, Path.Combine(ItemPath, file.Name), RootPath, RootGuid);
            }

            return null;
        }
Example #35
0
        public override void Close()
        {
            using (var context = new OnlineFilesEntities())
            {
                Catalog catalog = context.Catalogs.FirstOrDefault(d => d.pk_CatalogId == CatalogId);
                if (catalog == null)
                {
                    throw new Exception("No Catalog.");
                }

                using (var ctx = new OnlineFiles_CatalogEntities(catalog.EntityConnectionString))
                {
                    FileCatalogEntry entry = ctx.FileCatalogEntries.FirstOrDefault(d => d.pk_FileCatalogEntryId == FileCatalogEntryId);
                    if (entry == null)
                    {
                        throw new Exception("Catalog Entry is null.");
                    }
                    entry.binaryData = ToArray();
                    ctx.SaveChanges();
                }

                FileData file = context.FileDatas.FirstOrDefault(d => d.pk_FileDataId == FileDataId);
                if (file == null)
                {
                    throw new Exception("File is null.");
                }
                file.Size = ToArray().Count();
                context.SaveChanges();

                if (WebDavSqlStoreDocumentFactoryInstance != null)
                {
                    WebDavSqlStoreDocumentFactoryInstance.InvalidateDocumentPath(Path);
                }
            }
            base.Close();
        }
        /// <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 #37
0
        private static void DownloadAdsUsers()
        {
            using (var context = new OnlineFilesEntities())
                using (PrincipalContext ctx = new PrincipalContext(ContextType.Domain))
                    using (var filter = new UserPrincipal(ctx))
                    {
                        using (PrincipalSearcher search = new PrincipalSearcher(filter))
                        {
                            int max = search.FindAll().Count();
                            int c   = 0;
                            foreach (var principal in search.FindAll())
                            {
                                Console.WriteLine("Processing " + c + " of " + max);
                                c++;
                                var user = principal as UserPrincipal;
                                if (user == null)
                                {
                                    continue;
                                }
                                if (user.StructuralObjectClass == "group" && user.Enabled != true)
                                {
                                    continue;
                                }


                                var so = context.SecurityObjects
                                         .FirstOrDefault(d => d.ActiveDirectoryId == user.Guid);
                                if (so == null)
                                {
                                    so = new SecurityObject
                                    {
                                        ActiveDirectoryId = user.Guid,
                                        FullName          = user.Name,
                                        Username          = user.SamAccountName,
                                        EmailAddress      = user.EmailAddress ?? "",
                                        IsGroup           = false,
                                        LastLogInOn       = DateTime.Now,
                                        IsActive          = true,
                                        HomeFolder        = null
                                    };
                                    context.SecurityObjects.Add(so);
                                }
                                else
                                {
                                    so.IsGroup      = false;
                                    so.FullName     = user.Name;
                                    so.Username     = user.SamAccountName;
                                    so.EmailAddress = user.EmailAddress ?? "";
                                }

                                context.SaveChanges();

                                context.SecurityObjectMemberships.RemoveRange(context.SecurityObjectMemberships.Where(d => d.SecurityObjectId == so.SecurityObjectId));
                                context.SaveChanges();

                                try
                                {
                                    foreach (Principal grp in user.GetGroups())
                                    {
                                        var og = context.SecurityObjects.FirstOrDefault(d => d.ActiveDirectoryId == grp.Guid);
                                        if (og != null)
                                        {
                                            context.SecurityObjectMemberships.Add(new SecurityObjectMembership {
                                                OwnerSecurityObject = so, GroupSecurityObjectId = og.SecurityObjectId
                                            });
                                        }
                                    }
                                }
                                catch (Exception)
                                {
                                }


                                context.SaveChanges();
                            }
                        }
                    }
        }
        /// <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>
        ///     Refreshes an existing lock
        /// </summary>
        /// <param name="storeItem"></param>
        /// <param name="locktoken"></param>
        /// <param name="requestedlocktimeout"></param>
        /// <param name="requestDocument"></param>
        /// <returns></returns>
        public override int RefreshLock(IWebDavStoreItem storeItem, Guid? locktoken, double? requestedlocktimeout, out XmlDocument requestDocument)
        {
            try
            {
                CleanLocks();
                requestDocument = null;
                if (locktoken == null)
                    throw new WebDavNotFoundException("Must have a lock to refresh.");

                using (var context = new OnlineFilesEntities())
                {
                    var info = context.ObjectLockInfoes.FirstOrDefault(d => d.Token == locktoken);
                    if (info == null)
                        throw new WebDavNotFoundException("Lock Token Not Found.");

                    IWebDavStoreItemLockInstance inst = new WebDavSqlStoreItemLockInstance(
                        PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                        info.Path, (WebDavLockScope) info.LockScope, (WebDavLockType) info.LockType,
                        info.Owner.ToString(),
                        info.RequestedLockTimeout, info.Token, new XmlDocument(), info.Depth, this, info.CreateDt
                        );

                    inst.RefreshLock(requestedlocktimeout);
                    info.CreateDt = inst.CreateDate;
                    info.ExpirationDate = inst.ExpirationDate;
                    info.RequestedLockTimeout = inst.RequestedLockTimeout;
                    context.SaveChanges();
                    requestDocument = new XmlDocument();
                    return (int) HttpStatusCode.OK;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
        /// <summary>
        ///     Locks the object passed.
        /// </summary>
        /// <param name="storeItem"></param>
        /// <param name="lockscope"></param>
        /// <param name="locktype"></param>
        /// <param name="lockowner"></param>
        /// <param name="requestedlocktimeout"></param>
        /// <param name="locktoken"></param>
        /// <param name="requestDocument"></param>
        /// <param name="depth"></param>
        /// <returns></returns>
        public override int Lock(IWebDavStoreItem storeItem, WebDavLockScope lockscope, WebDavLockType locktype,
            string lockowner, double? requestedlocktimeout, out Guid? locktoken, XmlDocument requestDocument, int depth)
        {
            locktoken = null;
            try
            {
                var sqlStoreItem = (WebDavSqlStoreItem) storeItem;


                CleanLocks();


                using (OnlineFilesEntities context = new OnlineFilesEntities())
                {
                    WebDavSqlStoreItemLockInstance inst;
                    if (!context.ObjectLockInfoes.Any(d => d.ObjectGuid == sqlStoreItem.ObjectGuid && d.isFolder == sqlStoreItem.IsCollection))
                    {
                        inst = new WebDavSqlStoreItemLockInstance(
                            PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                            storeItem.ItemPath,
                            lockscope, locktype, lockowner,
                            requestedlocktimeout,
                            null, requestDocument, depth, this);

                        locktoken = CreateSqlLock(ref inst, sqlStoreItem);

                        return (int) HttpStatusCode.OK;
                    }
                    switch (lockscope)
                    {
                        case WebDavLockScope.Exclusive:
//#if DEBUG
//                            WebDavServer.Log.Debug("Lock Creation Failed (Exclusive), URI already has a lock.");
//#endif

                            return 423;
                        case WebDavLockScope.Shared:
                            if (context.ObjectLockInfoes.Any(d =>
                                d.ObjectGuid == sqlStoreItem.ObjectGuid &&
                                d.isFolder == sqlStoreItem.IsCollection &&
                                d.LockScope == (int) WebDavLockScope.Exclusive))
                            {
//#if DEBUG
//                                WebDavServer.Log.Debug("Lock Creation Failed (Shared), URI has exclusive lock.");
//#endif
                                return 423;
                            }
                            break;
                    }

                    //If the scope is shared and all other locks on this uri are shared we are ok, otherwise we fail.
                    //423 (Locked), potentially with 'no-conflicting-lock' precondition code - 
                    //There is already a lock on the resource that is not compatible with the 
                    //requested lock (see lock compatibility table above).

                    //If it gets to here, then we are most likely creating another shared lock on the file.
                    inst = new WebDavSqlStoreItemLockInstance(
                        PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                        storeItem.ItemPath, lockscope, locktype, lockowner,
                        requestedlocktimeout, null, requestDocument, depth, this);

                    locktoken = CreateSqlLock(ref inst, sqlStoreItem);
                    return (int) HttpStatusCode.OK;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
        /// <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;
        }
 /// <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;
 }
        /// <summary>
        ///     unlocks an existing lock
        /// </summary>
        /// <param name="storeItem"></param>
        /// <param name="locktoken"></param>
        /// <param name="owner"></param>
        /// <returns></returns>
        public override int UnLock(IWebDavStoreItem storeItem, Guid? locktoken, string owner)
        {
            try
            {
                CleanLocks();
                if (locktoken == null)
                {
//#if DEBUG
//                    WebDavServer.Log.Debug("Unlock failed, No Token!.");
//#endif
                    return (int) HttpStatusCode.BadRequest;
                }
                using (var context = new OnlineFilesEntities())
                {
                    var info = context.ObjectLockInfoes.FirstOrDefault(d => d.Token == locktoken);

                    if (info == null)
                        throw new WebDavNotFoundException("Lock Token Not Found.");

                    if (info.OwnerId != PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile.SecurityObjectId)
                        throw new WebDavUnauthorizedException("You did not create the lock.");


                    context.ObjectLockInfoes.Remove(info);
                    context.SaveChanges();
                    return (int) HttpStatusCode.NoContent;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
        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;
            }
        }
        /// <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();
            }
        }
        /// <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
                    };
                }
            }
        }
        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;
        }
Example #48
0
        private static void Main(string[] args)
        {
            try
            {
                Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
                config.AppSettings.Settings["LDAP_SETTING"].Value = ActiveDirectory.RootPath;
                ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, "Application is linked to the Domain: " + config.AppSettings.Settings["LDAP_SETTING"].Value);

                if (config.ConnectionStrings.ConnectionStrings["OnlineFilesEntities"] == null || config.ConnectionStrings.ConnectionStrings["OnlineFilesEntities"].ConnectionString == "")
                {
                    ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Connection String (OnlineFilesEntities) is not set in the WebConfig.");
                    ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                    Console.ReadKey();
                    return;
                }

                config.Save(ConfigurationSaveMode.Full);

                using (var context = new OnlineFilesEntities())
                {
                    bool hadError = false;
                    if (!context.CatalogCollections.Any())
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "No Online Catalog Collections Created.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, "Please create an entry in the 'CatalogCollection' and 'Catalog' tables.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"insert into [CatalogCollection] ([Name]) values ('Default Catalog Collection');");
                        hadError = true;
                    }
                    if (!context.Catalogs.Any())
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, @"Missing a default catalog in the database.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"
insert into [Catalog] ([fk_CatalogCollectionId], [Name], [Offline], [Server], [DatabaseName], [UserName], [Password], [fk_CatalogStatusId])
select 
		pk_CatalogCollectionID					[fk_CatalogCollectionId],
		'Default Catalog'						[Name],
		0										[Offline],
		'Name of SQL Server'					[Server],
		'Name of the Database for the Catalog'	[DatabaseName],
		'Username to connect as'				[UserName],
		'Password to use'						[Password],
		1										[fk_CatalogStatusId]
from
	CatalogCollection;"    );
                        hadError = true;
                    }
                    if (hadError)
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                        Console.ReadKey();
                        return;
                    }

                    if (!context.Folders.Any(d => d.pk_FolderId == new Guid()))
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, @"The Root Folder does not exist!");

                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"
insert into [Folder]
(pk_FolderId, fk_ParentFolderId, Name, CreateDt, fk_CatalogCollectionId, Win32FileAttribute, isDeleted, DeletedDt, DeletedBy, Owner, CreatedBy)
select top 1
	'00000000-0000-0000-0000-000000000000',
	null,
	'Root',
	getdate(),
	pk_CatalogCollectionID,
	16,
	0,
	null,
	null,
	'00000000-0000-0000-0000-000000000000',
	'00000000-0000-0000-0000-000000000000'
from 
	[CatalogCollection];"    );

                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                        Console.ReadKey();
                        return;
                    }
                    if (!context.SecurityObjects.Any() && !args.Contains("-SyncADS", StringComparer.CurrentCultureIgnoreCase))
                    {
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, @"Active Directory has not been Syncronized.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Yellow, @"Run the program with option '-SyncADS'.");
                        ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                        Console.ReadKey();
                        return;
                    }
                }

                // if install was a command line flag, then run the installer at runtime.
                if (args.Contains(" - install", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeInstall <ServiceImplementation>();
                }

                // if uninstall was a command line flag, run uninstaller at runtime.
                else if (args.Contains("-uninstall", StringComparer.InvariantCultureIgnoreCase))
                {
                    WindowsServiceInstaller.RuntimeUnInstall <ServiceImplementation>();
                }

                // otherwise, fire up the service as either console or windows service based on UserInteractive property.
                else
                {
                    if (args.Contains("-SyncADS", StringComparer.CurrentCultureIgnoreCase))
                    {
                        ActiveDirectory.Syncrhonize();
                    }

                    var implementation = new ServiceImplementation();

                    // if started from console, file explorer, etc, run as console app.
                    if (Environment.UserInteractive)
                    {
                        ConsoleHarness.Run(args, implementation);
                    }

                    // otherwise run as a windows service
                    else
                    {
                        Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory);
                        ServiceBase.Run(new WindowsServiceHarness(implementation));
                    }
                }
            }

            catch (Exception ex)
            {
                ConsoleHarness.WriteToConsole(ConsoleColor.Red, "An exception occurred in Main(): {0}", ex);
                ConsoleHarness.WriteToConsole(ConsoleColor.Red, "Hit Any Key to Exit");
                Console.ReadKey();
            }
        }
        /// <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;
        }
        /// <summary>
        ///     Creates a new SQL Lock.
        /// </summary>
        /// <param name="inst"></param>
        /// <param name="storeItem"></param>
        /// <returns></returns>
        private static Guid CreateSqlLock(ref WebDavSqlStoreItemLockInstance inst, WebDavSqlStoreItem storeItem)
        {
            try
            {
                using (var context = new OnlineFilesEntities())
                {
                    var t = context.Files.FirstOrDefault(d => d.pk_FileId == storeItem.ObjectGuid);


                    ObjectLockInfo info = new ObjectLockInfo
                    {
                        CreateDt = inst.CreateDate,
                        Depth = inst.Depth,
                        ExpirationDate = inst.ExpirationDate,
                        LockScope = (int) inst.LockScope,
                        LockType = (int) inst.LockType,
                        ObjectGuid = (Guid) storeItem.ObjectGuid,
                        OwnerId = inst.SoOwner.SecurityObjectId,
                        Path = storeItem.Href.ToString(),
                        RequestedLockTimeout = inst.RequestedLockTimeout,
                        isFolder = storeItem.IsCollection
                    };

                    context.ObjectLockInfoes.Add(info);
                    context.SaveChanges();
                    inst.Token = info.Token;
                    return info.Token;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
Example #51
0
        /// <summary>
        ///     Locks the object passed.
        /// </summary>
        /// <param name="storeItem"></param>
        /// <param name="lockscope"></param>
        /// <param name="locktype"></param>
        /// <param name="lockowner"></param>
        /// <param name="requestedlocktimeout"></param>
        /// <param name="locktoken"></param>
        /// <param name="requestDocument"></param>
        /// <param name="depth"></param>
        /// <returns></returns>
        public override int Lock(IWebDavStoreItem storeItem, WebDavLockScope lockscope, WebDavLockType locktype,
                                 string lockowner, double?requestedlocktimeout, out Guid?locktoken, XmlDocument requestDocument, int depth)
        {
            locktoken = null;
            try
            {
                var sqlStoreItem = (WebDavSqlStoreItem)storeItem;


                CleanLocks();


                using (OnlineFilesEntities context = new OnlineFilesEntities())
                {
                    WebDavSqlStoreItemLockInstance inst;
                    if (!context.ObjectLockInfoes.Any(d => d.ObjectGuid == sqlStoreItem.ObjectGuid && d.isFolder == sqlStoreItem.IsCollection))
                    {
                        inst = new WebDavSqlStoreItemLockInstance(
                            PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                            storeItem.ItemPath,
                            lockscope, locktype, lockowner,
                            requestedlocktimeout,
                            null, requestDocument, depth, this);

                        locktoken = CreateSqlLock(ref inst, sqlStoreItem);

                        return((int)HttpStatusCode.OK);
                    }
                    switch (lockscope)
                    {
                    case WebDavLockScope.Exclusive:
//#if DEBUG
//                            WebDavServer.Log.Debug("Lock Creation Failed (Exclusive), URI already has a lock.");
//#endif

                        return(423);

                    case WebDavLockScope.Shared:
                        if (context.ObjectLockInfoes.Any(d =>
                                                         d.ObjectGuid == sqlStoreItem.ObjectGuid &&
                                                         d.isFolder == sqlStoreItem.IsCollection &&
                                                         d.LockScope == (int)WebDavLockScope.Exclusive))
                        {
//#if DEBUG
//                                WebDavServer.Log.Debug("Lock Creation Failed (Shared), URI has exclusive lock.");
//#endif
                            return(423);
                        }
                        break;
                    }

                    //If the scope is shared and all other locks on this uri are shared we are ok, otherwise we fail.
                    //423 (Locked), potentially with 'no-conflicting-lock' precondition code -
                    //There is already a lock on the resource that is not compatible with the
                    //requested lock (see lock compatibility table above).

                    //If it gets to here, then we are most likely creating another shared lock on the file.
                    inst = new WebDavSqlStoreItemLockInstance(
                        PrincipleFactory.Instance.GetPrinciple(FromType.WebDav).UserProfile,
                        storeItem.ItemPath, lockscope, locktype, lockowner,
                        requestedlocktimeout, null, requestDocument, depth, this);

                    locktoken = CreateSqlLock(ref inst, sqlStoreItem);
                    return((int)HttpStatusCode.OK);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message + ex.StackTrace);
                throw;
            }
        }
        /// <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;
                }
            }
        }
        /// <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;
            }
        }
 /// <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;
 }
        /// <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;

        }