/// <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);
            }
        }
        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();
                }
            }
        }
        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 #4
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 #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;
            }
        }
        /// <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);
                }
            }
        }
Example #7
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="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);
        }
Example #9
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;
            }
        }
Example #10
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;
            }
        }
Example #11
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();
        }
        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();
                }
            }
        }
        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();
                    }
                }
            }
        }
        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>
        ///     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>
        /// Creates a new Folder object.
        /// </summary>
        /// <param name="name"></param>
        /// <param name="parentFolderGuid"></param>
        /// <param name="createdBy"></param>
        /// <param name="inheritSecurity"></param>
        /// <param name="isSystemCreate"></param>
        /// <returns></returns>
        public static Folder Create(string name, Guid? parentFolderGuid, SecurityObject createdBy, bool inheritSecurity = true, bool isSystemCreate = false)
        {
            using (var context = new OnlineFilesEntities())
            {
                //Get Folder object for parent folder
                Folder parentFolder = context.Folders
                    .Include(x => x.CatalogCollection)
                    .Include(x => x.FolderSecurities)
                    .FirstOrDefault(d => d.pk_FolderId == parentFolderGuid);

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


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

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


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


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

                        context.SaveChanges();

                        FolderSecurity us = context.FolderSecurities.FirstOrDefault(d => d.fk_FolderId == f.pk_FolderId && d.SecurityObjectId == createdBy.SecurityObjectId);
                        if (us == null)
                        {
                            us = new FolderSecurity()
                            {
                                canListObjects = true,
                                canChangePermissions = true,
                                canCreateFiles = true,
                                canCreateFolders = true,
                                canDelete = true,
                                fk_FolderId = f.pk_FolderId,
                                SecurityObjectId = createdBy.SecurityObjectId
                            };
                            context.FolderSecurities.Add(us);
                        }
                        else
                        {
                            us.canListObjects = true;
                            us.canChangePermissions = true;
                            us.canCreateFolders = true;
                            us.canCreateFiles = true;
                            us.canDelete = true;
                        }
                        context.SaveChanges();
                    }
                }
                catch (Exception ex)
                {
                    throw new Exception("Unable to create new folder.", ex);
                }
                return f;
            }



        }
        /// <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);
                }
            }
        }
        /// <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;
            }
        }
Example #19
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();
                            }
                        }
                    }
        }
 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>
        /// 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.");
                }
            }
        }
        /// <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;
                }
            }
        }
        /// <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 static void RestoreFileHere(this Folder destination, Guid fileId, string destinationName, Principal user)
        {
            using (var context = new OnlineFilesEntities())
            {
                var destSecurity = context.FolderSecurities.Where(d => d.fk_FolderId == destination.pk_FolderId);

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


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

                    //Can the user delete from the folder that the file starts in?
                    if (parentToFileToMove.FolderSecurities.Any(d => user.UserProfile.mySecurityGroups.Contains(d.SecurityObjectId) && d.canDelete))
                    {
                        var locks = context.ObjectLockInfoes.Where(d => d.ObjectGuid == fileId);
                        if (locks.Count() > 0)
                        {
                            if (locks.Any(d => d.OwnerId == user.UserProfile.SecurityObjectId))
                            {
                                context.ObjectLockInfoes.RemoveRange(context.ObjectLockInfoes.Where(d => d.ObjectGuid == fileId));
                                context.SaveChanges();
                            }
                            else
                            {
                                throw new SecurityException("File is Locked by another user.");
                            }
                        }
                    }
                    else
                    {
                        throw new SecurityException("Not Authorized.");
                    }
                    fileToRestore.RestoreDeleted(PrincipleFactory.Instance.GetPrinciple().UserProfile);
                    fileToRestore.Name = destination.CheckFolderName(destinationName, context);
                    fileToRestore.fk_FolderId = destination.pk_FolderId;
                    context.SaveChanges();
                }
                else
                {
                    throw new SecurityException("Not Authorized.");
                }
            }
        }
        /// <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;
            }
        }
        /// <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;
        }