Esempio n. 1
0
        private void Application_BeginRequest(Object source, EventArgs e)
        {
            // Create HttpApplication and HttpContext objects to access
            // request and response properties.
            HttpApplication application = (HttpApplication)source;
            HttpContext context = application.Context;
            if (context.Request.HttpMethod == "PROPFIND" || context.Request.HttpMethod == "OPTIONS")
            {
                Uri url = context.Request.Url;
                if (IsWebDavRootFolderRequest(context.Request))
                {
                    WebDavAbstractFactory factory = new WebDavAbstractFactory();
                    WebDavElementStorageProvider storageProvider = factory.Create<WebDavElementStorageProvider>(ObjectTypes.Folder);
                    if (storageProvider != null)
                    {
                        WebDavApplication.DefaultProvider = storageProvider;
                        WebDavTicketRequest request = new WebDavTicketRequest(context.Request, ePluginToken.webdav);
                        WebDavTicketResponse response = new WebDavTicketResponse(context.Response);
                        WebDavApplication.ProcessRequest(request, response);
                        context.Response.End();
                    }

                }
            }
        }
Esempio n. 2
0
        private void Application_BeginRequest(Object source, EventArgs e)
        {
            // Create HttpApplication and HttpContext objects to access
            // request and response properties.
            HttpApplication application = (HttpApplication)source;
            HttpContext     context     = application.Context;

            if (context.Request.HttpMethod == "PROPFIND" || context.Request.HttpMethod == "OPTIONS")
            {
                Uri url = context.Request.Url;
                if (IsWebDavRootFolderRequest(context.Request))
                {
                    WebDavAbstractFactory        factory         = new WebDavAbstractFactory();
                    WebDavElementStorageProvider storageProvider = factory.Create <WebDavElementStorageProvider>(ObjectTypes.Folder);
                    if (storageProvider != null)
                    {
                        WebDavApplication.DefaultProvider = storageProvider;
                        WebDavTicketRequest  request  = new WebDavTicketRequest(context.Request, ePluginToken.webdav);
                        WebDavTicketResponse response = new WebDavTicketResponse(context.Response);
                        WebDavApplication.ProcessRequest(request, response);
                        context.Response.End();
                    }
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Gets the active locked webdav resources.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable<WebDavLockInfo> GetActiveLocksInfo()
        {
            WebDavAbstractFactory factory = new WebDavAbstractFactory();
            foreach (WebDavStorageElementPropertiesRow row in WebDavStorageElementPropertiesRow.List())
            {
                WebDavElementStorageProvider provider = factory.Create<WebDavElementStorageProvider>(row.ObjectTypeId);
                ResourceInfo resInfo = GetResourceInfoFromPropertyRow(row);
                if (resInfo != null)
                {
                    foreach (ActiveLockElement activeLockEl in provider.GetActiveLocks(resInfo))
                    {
                        OpaqueLockToken lockToken = OpaqueLockToken.Parse(activeLockEl.LockToken.InnerText);
                        McLockElement mcLockEl = GetMcLockElement(lockToken, provider.GetProperties(resInfo));

                        WebDavLockInfo retval = new WebDavLockInfo();
                        retval.WebDavElementPropertyId = row.PrimaryKeyId.Value;
                        retval.FileName = resInfo.Name;
                        retval.ContentTypeId = ContentTypeResolver.GetContentTypeId(resInfo.ContentType);
                        retval.StartLocking = new DateTime(mcLockEl.CreationDate * TimeSpan.TicksPerSecond);
                        retval.Duration = DateTime.UtcNow - retval.StartLocking;
                        UserLight user = UserLight.Load(activeLockEl.Owner);
                        if (user != null)
                        {
                            retval.LockedBy = user.DisplayName;
                        }
                        else
                        {
                            retval.LockedBy = "Unknow";
                        }

                        yield return retval;
                    }
                }
            }
        }
Esempio n. 4
0
        /// <summary>
        /// Gets the file locked user id.
        /// </summary>
        /// <param name="fileUrl">The file URL.</param>
        /// <returns></returns>
        public static UserLight GetFileLockedUserId(string fileUrl)
        {
            UserLight retVal = null;
            try
            {
                WebDavTicket ticket = WebDavUrlBuilder.GetWebDavTicket(fileUrl);
                WebDavAbstractFactory factory = new WebDavAbstractFactory();
                WebDavPropertyStorage provider =
                                       factory.Create<WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType) as WebDavPropertyStorage;
                if (provider != null)
                {
                    WebDavElementInfo elInfo = provider.GetElementInfo(ticket.ToString());
                    foreach (ActiveLockElement activeLock in provider.GetActiveLocks(elInfo))
                    {
                        UserLight user = UserLight.Load(activeLock.Owner);
                        if (user != null)
                        {
                            retVal = user;
                            break;
                        }
                    }
                }

            }
            catch (System.Exception)
            {

            }

            return retVal;
        }
Esempio n. 5
0
        /// <summary>
        /// Gets the file locked user id.
        /// </summary>
        /// <param name="fileUrl">The file URL.</param>
        /// <returns></returns>
        public static UserLight GetFileLockedUserId(string fileUrl)
        {
            UserLight retVal = null;

            try
            {
                WebDavTicket          ticket   = WebDavUrlBuilder.GetWebDavTicket(fileUrl);
                WebDavAbstractFactory factory  = new WebDavAbstractFactory();
                WebDavPropertyStorage provider =
                    factory.Create <WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType) as WebDavPropertyStorage;
                if (provider != null)
                {
                    WebDavElementInfo elInfo = provider.GetElementInfo(ticket.ToString());
                    foreach (ActiveLockElement activeLock in provider.GetActiveLocks(elInfo))
                    {
                        UserLight user = UserLight.Load(activeLock.Owner);
                        if (user != null)
                        {
                            retVal = user;
                            break;
                        }
                    }
                }
            }
            catch (System.Exception)
            {
            }

            return(retVal);
        }
Esempio n. 6
0
        /// <summary>
        /// Unlocks the webdav resource.
        /// </summary>
        /// <param name="resource">The resource.</param>
        public static void UnlockResource(int webDavElementPropertyId)
        {
            WebDavAbstractFactory             factory     = new WebDavAbstractFactory();
            WebDavStorageElementPropertiesRow propertyRow = null;

            try
            {
                propertyRow = new WebDavStorageElementPropertiesRow(webDavElementPropertyId);
            }
            catch
            {
                return;
            }
            ResourceInfo resInfo = GetResourceInfoFromPropertyRow(propertyRow);

            if (resInfo != null)
            {
                WebDavTicket ticket = WebDavTicket.Parse(resInfo.AbsolutePath);
                WebDavElementStorageProvider storageProvider =
                    factory.Create <WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType);

                foreach (ActiveLockElement activeLockEl in storageProvider.GetActiveLocks(resInfo))
                {
                    OpaqueLockToken lockToken = OpaqueLockToken.Parse(activeLockEl.LockToken.InnerText);
                    storageProvider.Unlock(resInfo, lockToken);
                }
            }
        }
Esempio n. 7
0
        private static ResourceInfo GetResourceInfoFromPropertyRow(WebDavStorageElementPropertiesRow propertyRow)
        {
            if (propertyRow == null)
            {
                throw new ArgumentNullException("propertyRow");
            }
            ResourceInfo          retVal  = null;
            WebDavAbstractFactory factory = new WebDavAbstractFactory();

            //For MetaData stored int hash for Guid value is not possible restore back from hash to Guid
            if ((ObjectTypes)propertyRow.ObjectTypeId != ObjectTypes.File_MetaData)
            {
                WebDavElementStorageProvider provider = factory.Create <WebDavElementStorageProvider>(propertyRow.ObjectTypeId);
                WebDavAbsolutePath           absPath  = WebDavAbsolutePath.CreateInstance((ObjectTypes)propertyRow.ObjectTypeId);
                absPath.UniqueId = propertyRow.ObjectId;
                absPath.FileName = "file";
                WebDavTicket ticket = WebDavTicket.CreateInstance(ePluginToken.webdav, Guid.Empty, absPath);
                try
                {
                    retVal = provider.GetElementInfo(ticket.ToString()) as ResourceInfo;
                }
                catch (Exception)
                {
                }
            }
            return(retVal);
        }
Esempio n. 8
0
        /// <summary>
        /// Gets the active locked webdav resources.
        /// </summary>
        /// <returns></returns>
        public static IEnumerable <WebDavLockInfo> GetActiveLocksInfo()
        {
            WebDavAbstractFactory factory = new WebDavAbstractFactory();

            foreach (WebDavStorageElementPropertiesRow row in WebDavStorageElementPropertiesRow.List())
            {
                WebDavElementStorageProvider provider = factory.Create <WebDavElementStorageProvider>(row.ObjectTypeId);
                ResourceInfo resInfo = GetResourceInfoFromPropertyRow(row);
                if (resInfo != null)
                {
                    foreach (ActiveLockElement activeLockEl in provider.GetActiveLocks(resInfo))
                    {
                        OpaqueLockToken lockToken = OpaqueLockToken.Parse(activeLockEl.LockToken.InnerText);
                        McLockElement   mcLockEl  = GetMcLockElement(lockToken, provider.GetProperties(resInfo));

                        WebDavLockInfo retval = new WebDavLockInfo();
                        retval.WebDavElementPropertyId = row.PrimaryKeyId.Value;
                        retval.FileName      = resInfo.Name;
                        retval.ContentTypeId = ContentTypeResolver.GetContentTypeId(resInfo.ContentType);
                        retval.StartLocking  = new DateTime(mcLockEl.CreationDate * TimeSpan.TicksPerSecond);
                        retval.Duration      = DateTime.UtcNow - retval.StartLocking;
                        UserLight user = UserLight.Load(activeLockEl.Owner);
                        if (user != null)
                        {
                            retval.LockedBy = user.DisplayName;
                        }
                        else
                        {
                            retval.LockedBy = "Unknow";
                        }

                        yield return(retval);
                    }
                }
            }
        }
Esempio n. 9
0
        public void ProcessRequest(HttpContext context)
        {
            //try
            //{
            //проверяем есть ли в ticket-е идентификатор сессии
            WebDavTicket ticket = WebDavUrlBuilder.GetWebDavTicket(context.Request.Url.ToString());
            if (ticket == null)
                throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI.");

            if (!WebDavAuthHelper.WebDavAuthentificate(context, ticket))
            {
                //Используем стандартный механизм аутентификации
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            //throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized");
            WebDavAbstractFactory factory = new WebDavAbstractFactory();
            WebDavElementStorageProvider storageProvider =
                                    factory.Create<WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType);
            if (storageProvider == null)
                throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI.");

            //Запускаем механизм обработки web dav запроса
            WebDavTicketRequest request = new WebDavTicketRequest(context.Request, ePluginToken.webdav);
            WebDavTicketResponse response = new WebDavTicketResponse(context.Response);
            WebDavApplication.DefaultProvider = storageProvider;

            try
            {
                bool enableTrace = Convert.ToBoolean(ConfigurationManager.AppSettings[ConstEnableTrace]);
                if (enableTrace)
                {
                    WebDavTracer.TraceBinaryBody = false;
                    WebDavTracer.EnableTrace = true;
                }
            }
            catch (FormatException)
            {
            }

            if (request.HttpMethod == WebDavHttpMethod.GET)
            {
                //для get запросов выключаем буферизацию для работы с большими файлами
                context.Response.BufferOutput = false;
                //Некоторые браузеры кешируют результаты GET запроса при редактировании на сервере.
                //Установка expires равную текущей дате позволят указать браузеру что кеширование не требуется
                HttpCachePolicy cache = HttpContext.Current.Response.Cache;
                cache.SetExpires(DateTime.Now);

                //Если для запрошенного файла стоит флаг ForceDownload и не включен фдаг WebDav
                //то вернуть как attachment для выбора пользователем приложения для работы с документом
                if (!string.IsNullOrEmpty(ticket.AbsolutePath.FileName))
                {
                    string fileExtension = Path.GetExtension(ticket.AbsolutePath.FileName);
                    if (!ContentTypeResolver.IsWebDAVSupportedExtension(fileExtension) &&
                        ContentTypeResolver.IsAllowForceDownload(fileExtension))
                    {
                        context.Response.AddHeader("Content-Disposition", "attachment;" + "filename=" + ticket.AbsolutePath.FileName);
                    }
                }
            }

            WebDavApplication.ProcessRequest(request, response);

            //}
            //catch (HttpException ex)
            //{
            //    // Http Exception
            //    context.Response.Clear();

            //    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    context.Response.StatusCode = ex.GetHttpCode();
            //    context.Response.StatusDescription = ex.Message;
            //}
            //catch (Exception ex)
            //{
            //    // Global Exception
            //    context.Response.Clear();

            //    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            //    context.Response.StatusDescription = ex.Message;

            //    byte[] errorBuffer = System.Text.Encoding.UTF8.GetBytes(ex.ToString());
            //    context.Response.OutputStream.Write(errorBuffer, 0, errorBuffer.Length);
            //}

            //context.Response.Flush();
        }
Esempio n. 10
0
        public void ProcessRequest(HttpContext context)
        {
            //try
            //{
            //проверяем есть ли в ticket-е идентификатор сессии
            WebDavTicket ticket = WebDavUrlBuilder.GetWebDavTicket(context.Request.Url.ToString());

            if (ticket == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI.");
            }

            if (!WebDavAuthHelper.WebDavAuthentificate(context, ticket))
            {
                //Используем стандартный механизм аутентификации
                System.Web.Security.FormsAuthentication.RedirectToLoginPage();
                return;
            }
            //throw new HttpException((int)HttpStatusCode.Unauthorized, "Unauthorized");
            WebDavAbstractFactory        factory         = new WebDavAbstractFactory();
            WebDavElementStorageProvider storageProvider =
                factory.Create <WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType);

            if (storageProvider == null)
            {
                throw new HttpException((int)HttpStatusCode.BadRequest, "Incorrect URI.");
            }


            //Запускаем механизм обработки web dav запроса
            WebDavTicketRequest  request  = new WebDavTicketRequest(context.Request, ePluginToken.webdav);
            WebDavTicketResponse response = new WebDavTicketResponse(context.Response);

            WebDavApplication.DefaultProvider = storageProvider;

            try
            {
                bool enableTrace = Convert.ToBoolean(ConfigurationManager.AppSettings[ConstEnableTrace]);
                if (enableTrace)
                {
                    WebDavTracer.TraceBinaryBody = false;
                    WebDavTracer.EnableTrace     = true;
                }
            }
            catch (FormatException)
            {
            }


            if (request.HttpMethod == WebDavHttpMethod.GET)
            {
                //для get запросов выключаем буферизацию для работы с большими файлами
                context.Response.BufferOutput = false;
                //Некоторые браузеры кешируют результаты GET запроса при редактировании на сервере.
                //Установка expires равную текущей дате позволят указать браузеру что кеширование не требуется
                HttpCachePolicy cache = HttpContext.Current.Response.Cache;
                cache.SetExpires(DateTime.Now);

                //Если для запрошенного файла стоит флаг ForceDownload и не включен фдаг WebDav
                //то вернуть как attachment для выбора пользователем приложения для работы с документом
                if (!string.IsNullOrEmpty(ticket.AbsolutePath.FileName))
                {
                    string fileExtension = Path.GetExtension(ticket.AbsolutePath.FileName);
                    if (!ContentTypeResolver.IsWebDAVSupportedExtension(fileExtension) &&
                        ContentTypeResolver.IsAllowForceDownload(fileExtension))
                    {
                        context.Response.AddHeader("Content-Disposition", "attachment;" + "filename=" + ticket.AbsolutePath.FileName);
                    }
                }
            }

            WebDavApplication.ProcessRequest(request, response);

            //}
            //catch (HttpException ex)
            //{
            //    // Http Exception
            //    context.Response.Clear();

            //    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    context.Response.StatusCode = ex.GetHttpCode();
            //    context.Response.StatusDescription = ex.Message;
            //}
            //catch (Exception ex)
            //{
            //    // Global Exception
            //    context.Response.Clear();

            //    context.Response.ContentEncoding = System.Text.Encoding.UTF8;
            //    context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;
            //    context.Response.StatusDescription = ex.Message;

            //    byte[] errorBuffer = System.Text.Encoding.UTF8.GetBytes(ex.ToString());
            //    context.Response.OutputStream.Write(errorBuffer, 0, errorBuffer.Length);
            //}

            //context.Response.Flush();
        }
Esempio n. 11
0
 private static ResourceInfo GetResourceInfoFromPropertyRow(WebDavStorageElementPropertiesRow propertyRow)
 {
     if (propertyRow == null)
     {
         throw new ArgumentNullException("propertyRow");
     }
     ResourceInfo retVal = null;
     WebDavAbstractFactory factory = new WebDavAbstractFactory();
     //For MetaData stored int hash for Guid value is not possible restore back from hash to Guid
     if ((ObjectTypes)propertyRow.ObjectTypeId != ObjectTypes.File_MetaData)
     {
         WebDavElementStorageProvider provider = factory.Create<WebDavElementStorageProvider>(propertyRow.ObjectTypeId);
         WebDavAbsolutePath absPath = WebDavAbsolutePath.CreateInstance((ObjectTypes)propertyRow.ObjectTypeId);
         absPath.UniqueId = propertyRow.ObjectId;
         absPath.FileName = "file";
         WebDavTicket ticket = WebDavTicket.CreateInstance(ePluginToken.webdav, Guid.Empty, absPath);
         try
         {
             retVal = provider.GetElementInfo(ticket.ToString()) as ResourceInfo;
         }
         catch (Exception)
         {
         }
     }
     return retVal;
 }
Esempio n. 12
0
        /// <summary>
        /// Unlocks the webdav resource.
        /// </summary>
        /// <param name="resource">The resource.</param>
        public static void UnlockResource(int webDavElementPropertyId)
        {
            WebDavAbstractFactory factory = new WebDavAbstractFactory();
            WebDavStorageElementPropertiesRow propertyRow = null;
            try
            {
                propertyRow = new WebDavStorageElementPropertiesRow(webDavElementPropertyId);
            }
            catch
            {
                return;
            }
            ResourceInfo resInfo = GetResourceInfoFromPropertyRow(propertyRow);
            if (resInfo != null)
            {
                WebDavTicket ticket = WebDavTicket.Parse(resInfo.AbsolutePath);
                WebDavElementStorageProvider storageProvider =
                                    factory.Create<WebDavElementStorageProvider>(ticket.AbsolutePath.StorageType);

                foreach (ActiveLockElement activeLockEl in storageProvider.GetActiveLocks(resInfo))
                {
                    OpaqueLockToken lockToken = OpaqueLockToken.Parse(activeLockEl.LockToken.InnerText);
                    storageProvider.Unlock(resInfo, lockToken);
                }
            }
        }
Esempio n. 13
0
 /// <summary>
 /// Creates the instance.
 /// </summary>
 /// <param name="storageType">Type of the storage.</param>
 /// <param name="str">The STR.</param>
 /// <returns></returns>
 public static WebDavAbsolutePath CreateInstance(ObjectTypes storageType, byte [] byteArr)
 {
     WebDavAbstractFactory factory = new WebDavAbstractFactory();
     return factory.Create<WebDavAbsolutePath>(storageType, byteArr);
 }