public bool RemoveResource(IStorageProviderSession session, ICloudFileSystemEntry resource, RemoveMode mode)
        {
            String url;
            Dictionary<String, String> parameters = null;

            if (mode == RemoveMode.FromParentCollection)
            {
                var pId = (resource.Parent != null ? resource.Parent.Id : GoogleDocsConstants.RootFolderId).ReplaceFirst("_", "%3a");
                url = String.Format("{0}/{1}/contents/{2}", GoogleDocsConstants.GoogleDocsFeedUrl, pId, resource.Id.ReplaceFirst("_", "%3a"));
            }
            else
            {
                url = String.Format(GoogleDocsConstants.GoogleDocsResourceUrlFormat, resource.Id.ReplaceFirst("_", "%3a"));
                parameters = new Dictionary<string, string> {{"delete", "true"}};
            }

            var request = CreateWebRequest(session, url, "DELETE", parameters);
            request.Headers.Add("If-Match", "*");

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                    return true;
            }
            catch (WebException)
            {
            }

            return false;
        }
        public override bool DeleteResource(IStorageProviderSession session, ICloudFileSystemEntry entry)
        {
            // get the creds
            ICredentials creds = ((GenericNetworkCredentials) session.SessionToken).GetCredential(null, null);

            // generate the loca path
            String uriPath = GetResourceUrl(session, entry, null);

            // removed the file
            if (entry is ICloudDirectoryEntry)
            {
                // we need an empty directory
                foreach (ICloudFileSystemEntry child in (ICloudDirectoryEntry) entry)
                {
                    DeleteResource(session, child);
                }

                // remove the directory
                return _ftpService.FtpDeleteEmptyDirectory(uriPath, creds);
            }
            else
            {
                // remove the file
                return _ftpService.FtpDeleteFile(uriPath, creds);
            }
        }
 public static String GetResourcePath(ICloudFileSystemEntry parent, String nameOrId)
 {
     String path = parent != null ? parent.Id.Trim('/') : String.Empty;
     if (!String.IsNullOrEmpty(nameOrId) && !nameOrId.Equals("/"))
         path = String.Format("{0}/{1}", path, nameOrId.Trim('/'));
     return path.Trim('/');
 }
        public override void RefreshResource(IStorageProviderSession session, ICloudFileSystemEntry resource)
        {
            // nothing to do for files
            if (!(resource is ICloudDirectoryEntry))
                return;

            // Refresh schild
            RefreshChildsOfDirectory(session, resource as ICloudDirectoryEntry);
        }
        public void RefreshResource(IStorageProviderSession session, ICloudFileSystemEntry resource)
        {
            var cached = FsCache.Get(GetSessionKey(session), GetCacheKey(session, null, resource), null) as ICloudDirectoryEntry;

            if (cached == null || cached.HasChildrens == nChildState.HasNotEvaluated)
            {
                _service.RefreshResource(session, resource);
                FsCache.Add(GetSessionKey(session), GetCacheKey(session, null, resource), resource);
            }
        }
 public static String GetResourcePath(ICloudFileSystemEntry parent, String nameOrId)
 {
     nameOrId = !String.IsNullOrEmpty(nameOrId) ? nameOrId.Trim('/') : String.Empty;
     var parentId = parent != null ? parent.Id.Trim('/') : String.Empty;
     if (String.IsNullOrEmpty(parentId))
         return nameOrId;
     if (String.IsNullOrEmpty(nameOrId))
         return parentId;
     return parentId + "/" + nameOrId;
 }
Esempio n. 7
0
 public static void CopyProperties(ICloudFileSystemEntry src, ICloudFileSystemEntry dest)
 {
     if (!(dest is BaseFileEntry) || !(src is BaseFileEntry)) return;
     
     var destBase = dest as BaseFileEntry;
     var srcBase = src as BaseFileEntry;
     destBase.Name = srcBase.Name;
     destBase.Id = srcBase.Id;
     destBase.Modified = srcBase.Modified;
     destBase.Length = srcBase.Length;
     destBase[SkyDriveConstants.UploadLocationKey] = srcBase[SkyDriveConstants.UploadLocationKey];
     destBase.ParentID = srcBase.ParentID;
 }
Esempio n. 8
0
        public override bool MoveResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
        {
            if (fsentry == null || newParent == null || GoogleDocsResourceHelper.IsNoolOrRoot(fsentry))
            {
                return(false);
            }

            if (RemoveResource(session, fsentry, RemoveMode.FromParentCollection) && AddToCollection(session, fsentry, newParent))
            {
                if (fsentry.Parent != null)
                {
                    (fsentry.Parent as BaseDirectoryEntry).RemoveChild(fsentry as BaseFileEntry);
                }
                (newParent as BaseDirectoryEntry).AddChild(fsentry as BaseFileEntry);

                return(true);
            }

            return(false);
        }
Esempio n. 9
0
        /// <summary>
        /// This functions allows to download a specific file
        ///
        /// Valid Exceptions are:
        ///  SharpBoxException(nSharpBoxErrorCodes.ErrorFileNotFound);
        /// </summary>
        /// <param name="parent"></param>
        /// <param name="name"></param>
        /// <param name="targetPath"></param>
        /// <param name="delProgress"></param>
        /// <returns></returns>
        public void DownloadFile(ICloudDirectoryEntry parent, String name, String targetPath, FileOperationProgressChanged delProgress)
        {
            // check parameters
            if (parent == null || name == null || targetPath == null)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidParameters);
            }


#if !WINDOWS_PHONE && !ANDROID
            // expand environment in target path
            targetPath = Environment.ExpandEnvironmentVariables(targetPath);
#endif
            // get the file entry
            ICloudFileSystemEntry file = parent.GetChild(name, true);
            using (var targetData = new FileStream(Path.Combine(targetPath, file.Name), FileMode.Create, FileAccess.Write, FileShare.None))
            {
                file.GetDataTransferAccessor().Transfer(targetData, nTransferDirection.nDownload, delProgress, null);
            }
        }
Esempio n. 10
0
        /// <summary>
        /// This method build up a valid resource url
        /// </summary>
        /// <param name="session"></param>
        /// <param name="fileSystemEntry"></param>
        /// <param name="additionalPath"></param>
        /// <returns></returns>
        public virtual string GetResourceUrl(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, string additionalPath)
        {
            // build the url
            String targeturl = PathHelper.Combine(session.ServiceConfiguration.ServiceLocator.ToString(), GenericHelper.GetResourcePath(fileSystemEntry));

            // finalize the url
            if (!(fileSystemEntry is ICloudDirectoryEntry))
            {
                targeturl = targeturl.TrimEnd('/');
            }

            // add the additional Path
            if (additionalPath != null)
            {
                targeturl = PathHelper.Combine(targeturl, additionalPath);
            }

            // go ahead
            return(targeturl);
        }
        public override void RefreshResource(IStorageProviderSession session, ICloudFileSystemEntry resource)
        {
            //not refresh if resource was requested recently
            var timestamp     = resource.GetPropertyValue(SkyDriveConstants.TimestampKey);
            var refreshNeeded = DateTime.Parse(timestamp, CultureInfo.InvariantCulture) + TimeSpan.FromSeconds(5) < DateTime.UtcNow;

            if (refreshNeeded)
            {
                //Request resource by ID and then update properties from requested
                var current = RequestResource(session, resource.GetPropertyValue(SkyDriveConstants.InnerIDKey), null);
                SkyDriveHelpers.CopyProperties(current, resource);
            }

            var directory = resource as ICloudDirectoryEntry;

            if (directory != null && !refreshNeeded && directory.HasChildrens == nChildState.HasNotEvaluated)
            {
                RefreshDirectoryContent(session, directory);
            }
        }
        public override bool DeleteResource(IStorageProviderSession session, ICloudFileSystemEntry entry)
        {
            if (GoogleDocsResourceHelper.IsNoolOrRoot(entry))
            {
                return(false);
            }

            if (RemoveResource(session, entry, RemoveMode.Delete))
            {
                var parent = entry.Parent as BaseDirectoryEntry;
                if (parent != null)
                {
                    parent.RemoveChildById(entry.Id);
                }

                return(true);
            }

            return(false);
        }
        public override Stream CreateDownloadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry)
        {
            var url = fileSystemEntry.GetPropertyValue(GoogleDocsConstants.DownloadUrlProperty);

            var format = GoogleDocsResourceHelper.GetStreamExtensionByKind(fileSystemEntry.GetPropertyValue(GoogleDocsConstants.KindProperty));

            if (!String.IsNullOrEmpty(format))
            {
                url = String.Format("{0}&exportFormat={1}", url, format);
                if (format.Equals("docx"))
                {
                    url += "&format=" + format;
                }
            }

            var request  = CreateWebRequest(session, url, "GET", null, true);
            var response = (HttpWebResponse)request.GetResponse();

            if (fileSystemEntry.Length > 0)
            {
                return(new BaseFileEntryDownloadStream(response.GetResponseStream(), fileSystemEntry));
            }

            var isChukedEncoding = string.Equals(response.Headers.Get("Transfer-Encoding"), "Chunked", StringComparison.OrdinalIgnoreCase);

            if (!isChukedEncoding)
            {
                ((BaseFileEntry)fileSystemEntry).Length = response.ContentLength;
                return(new BaseFileEntryDownloadStream(response.GetResponseStream(), fileSystemEntry));
            }

            var tempBuffer = new FileStream(Path.GetTempFileName(), FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.Read, 8096, FileOptions.DeleteOnClose);

            using (var stream = response.GetResponseStream())
            {
                stream.CopyTo(tempBuffer);
            }
            tempBuffer.Flush();
            tempBuffer.Seek(0, SeekOrigin.Begin);
            return(tempBuffer);
        }
Esempio n. 14
0
        protected ICloudFileSystemEntry GetFileById(object fileId)
        {
            ICloudFileSystemEntry entry = null;
            Exception             e     = null;

            try
            {
                entry = GoogleDriveProviderInfo.Storage.GetFile(MakePath(fileId), RootFolder());
            }
            catch (Exception ex)
            {
                e = ex;
            }
            if (entry == null)
            {
                //Create error entry
                entry = new ErrorEntry(e, fileId);
            }

            return(entry);
        }
Esempio n. 15
0
        public override bool MoveResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
        {
            // build the path for resource
            String resourcePath = GenericHelper.GetResourcePath(newParent);

            resourcePath = PathHelper.Combine(resourcePath, fsentry.Name);

            // Move
            if (MoveOrRenameItem(session as DropBoxStorageProviderSession, fsentry as BaseFileEntry, resourcePath))
            {
                // set the new parent
                fsentry.Parent = newParent;

                // go ahead
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public bool AddToCollection(IStorageProviderSession session, ICloudFileSystemEntry resource, ICloudDirectoryEntry collection)
        {
            var url     = String.Format(GoogleDocsConstants.GoogleDocsContentsUrlFormat, collection.Id.ReplaceFirst("_", "%3a"));
            var request = CreateWebRequest(session, url, "POST", null);

            GoogleDocsXmlParser.WriteAtom(request, GoogleDocsXmlParser.EntryElement(null, GoogleDocsXmlParser.IdElement(resource.Id.ReplaceFirst("_", "%3a"))));

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.Created)
                {
                    return(true);
                }
            }
            catch (WebException)
            {
            }

            return(false);
        }
Esempio n. 17
0
        public override bool CopyResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
        {
            // build the targte url
            var uriStringTarget = GetResourceUrl(session, newParent, null);

            uriStringTarget = PathHelper.Combine(uriStringTarget, fsentry.Name);

            if (!CopyResource(session, fsentry, uriStringTarget))
            {
                return(false);
            }

            var newParentObject = newParent as BaseDirectoryEntry;

            if (newParentObject != null)
            {
                newParentObject.AddChild(fsentry as BaseFileEntry);
            }

            return(true);
        }
 public override string GetResourceUrl(IStorageProviderSession session, ICloudFileSystemEntry entry, string path)
 {
     if (!String.IsNullOrEmpty(path))
     {
         var id    = path;
         var index = id.LastIndexOf("/");
         if (index != -1)
         {
             id = id.Substring(index + 1);
         }
         if (GoogleDocsResourceHelper.IsResorceId(id))
         {
             return(id);
         }
     }
     else if (entry != null)
     {
         return(entry.Id);
     }
     return(base.GetResourceUrl(session, null, path));
 }
Esempio n. 19
0
        internal static void DeleteFile(Form1 form, ICloudDirectoryEntry directory, String fileName)
        {
            if (!ConfigUtil.GetBoolParameter("EnableDropboxDelete"))
            {
                return;
            }

            String question = String.Format(LanguageUtil.GetCurrentLanguageString("SureDeleteFile", className), fileName);

            if (WindowManager.ShowQuestionBox(form, question) == DialogResult.No)
            {
                return;
            }

            ICloudFileSystemEntry file = directory.GetChild(fileName);

            if (!form.DropboxCloudStorage.DeleteFileSystemEntry(file))
            {
                WindowManager.ShowAlertBox(form, LanguageUtil.GetCurrentLanguageString("WarningDeleting", className));
            }
        }
        public override ICloudFileSystemEntry CreateResource(IStorageProviderSession session, string name, ICloudDirectoryEntry parent)
        {
            // build the full url
            var resFull = GetResourceUrl(session, parent, name);
            var uri     = new Uri(resFull);

            // create the director
            var dinfo = Directory.CreateDirectory(uri.LocalPath);

            // create the filesystem object
            ICloudFileSystemEntry fsEntry = CreateEntryByFileSystemInfo(dinfo, session);

            // add parent child
            if (parent != null)
            {
                (parent as BaseDirectoryEntry).AddChild(fsEntry as BaseFileEntry);
            }

            // go ahead
            return(fsEntry);
        }
Esempio n. 21
0
        public File SaveFile(File file, Stream fileStream)
        {
            if (fileStream == null)
            {
                throw new ArgumentNullException("fileStream");
            }
            ICloudFileSystemEntry entry = null;

            if (file.ID != null)
            {
                entry = SharpBoxProviderInfo.Storage.GetFile(MakePath(file.ID), null);
            }
            else if (file.FolderID != null)
            {
                var folder = GetFolderById(file.FolderID);
                try
                {
                    //Check existense
                    if (SharpBoxProviderInfo.Storage.GetFileSystemObject(file.Title, folder) != null)
                    {
                        throw new ArgumentException(string.Format(Web.Files.Resources.FilesCommonResource.Error_FileAlreadyExists, file.Title));
                    }
                }
                catch (ArgumentException)
                {
                    throw;
                }
                catch (Exception)
                {
                }

                entry = SharpBoxProviderInfo.Storage.CreateFile(folder, file.Title);
            }
            if (entry != null)
            {
                entry.GetDataTransferAccessor().Transfer(fileStream, nTransferDirection.nUpload);
                return(ToFile(entry));
            }
            return(null);
        }
        /// <summary>
        /// This method renames a given filesystem object (file or folder)
        /// </summary>
        /// <param name="fsentry"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public bool RenameFileSystemEntry(ICloudFileSystemEntry fsentry, string newName)
        {
            // save the old name
            var renamedId = fsentry.Id;

            // rename the resource
            if (Service.RenameResource(Session, fsentry, newName))
            {
                // get the parent
                var p = fsentry.Parent as BaseDirectoryEntry;

                // remove the old childname
                p.RemoveChildById(renamedId);

                // readd the child
                p.AddChild(fsentry as BaseFileEntry);

                // go ahead
                return(true);
            }
            return(false);
        }
        /// <summary>
        /// Renames a webdave file or folder
        /// </summary>
        /// <param name="session"></param>
        /// <param name="fsentry"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, string newName)
        {
            // build the targte url
            String uriStringTarget = this.GetResourceUrl(session, fsentry.Parent, null);

            uriStringTarget = PathHelper.Combine(uriStringTarget, newName);

            if (MoveResource(session, fsentry, uriStringTarget))
            {
                // rename the fsentry
                BaseFileEntry fentry = fsentry as BaseFileEntry;
                fentry.Name = newName;

                // go ahead
                return(true);
            }
            else
            {
                // go ahead
                return(false);
            }
        }
        /// <summary>
        /// This method allows to upload the data from a given filestream into a target file
        /// </summary>
        /// <param name="uploadDataStream"></param>
        /// <param name="targetFileName"></param>
        /// <param name="targetContainer"></param>
        /// <param name="delProgress"></param>
        /// <returns></returns>
        public ICloudFileSystemEntry UploadFile(Stream uploadDataStream, String targetFileName, ICloudDirectoryEntry targetContainer, FileOperationProgressChanged delProgress)
        {
            // check parameters
            if (String.IsNullOrEmpty(targetFileName) || uploadDataStream == null || targetContainer == null)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidParameters);
            }

            // create the upload file
            ICloudFileSystemEntry newFile = CreateFile(targetContainer, targetFileName);

            if (newFile == null)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorFileNotFound);
            }

            // upload data
            newFile.GetDataTransferAccessor().Transfer(uploadDataStream, nTransferDirection.nUpload, delProgress, null);

            // go ahead
            return(newFile);
        }
Esempio n. 25
0
        public static String GetResourcePath(ICloudFileSystemEntry entry)
        {
            var current = entry;
            var path = "";

            while (current != null)
            {
                if (current.Name != "/")
                {
                    if (path == String.Empty)
                        path = current.Id;
                    else
                        path = current.Id + "/" + path;
                }
                else
                    path = "/" + path;

                current = current.Parent;
            }

            return path;
        }
        public void RefreshResource(IStorageProviderSession session, ICloudFileSystemEntry resource)
        {
            var cacheKey  = GetSessionKey(session);
            var refreshed = FsCache.Get(cacheKey, GetCacheUrl(session, null, resource), null) as BaseFileEntry;

            if (refreshed == null || ((refreshed is BaseDirectoryEntry) && (refreshed as BaseDirectoryEntry).HasChildrens == nChildState.HasNotEvaluated))
            {
                _service.RefreshResource(session, resource);
                //TODO: Optimize caching we don't need to stroe whole resource for it. Only a flag that it's already refreshed not so long time ago
                //Do cache it here
                FsCache.Add(cacheKey, GetCacheUrl(session, null, resource), resource);
            }
            //else if (!ReferenceEquals(refreshed,resource))
            //{
            //TODO: Leave blanc for now.
            //var resourseBase = resource as BaseFileEntry;
            //if (resourseBase!=null)
            //{
            //    //Merge changes
            //    resourseBase.Parent = refreshed.Parent;
            //    resourseBase.IsDeleted = refreshed.IsDeleted;
            //    resourseBase.Length = refreshed.Length;
            //    resourseBase.Modified = refreshed.Modified;
            //    resourseBase.Name = refreshed.Name;

            //    if (resource is BaseDirectoryEntry && refreshed is BaseDirectoryEntry)
            //    {
            //        //Merge childs
            //        ((BaseDirectoryEntry) resource).ClearChilds();
            //        var resourseDir = ((BaseDirectoryEntry) resource);
            //        foreach (var child in ((BaseDirectoryEntry)refreshed).GetSubdirectoriesWithoutRefresh())
            //        {
            //            resourseDir.AddChild((BaseFileEntry)child);
            //        }
            //    }
            //}
            //}
            //If equal reference then ok
        }
Esempio n. 27
0
        protected string MakeId(ICloudFileSystemEntry entry)
        {
            var path = string.Empty;

            if (entry != null && !(entry is ErrorEntry))
            {
                try
                {
                    path = SharpBoxProviderInfo.Storage.GetFileSystemObjectPath(entry);
                }
                catch (Exception ex)
                {
                    Global.Logger.Error("Sharpbox makeId error", ex);
                }
            }
            else if (entry != null)
            {
                path = entry.Id;
            }

            return(string.Format("{0}{1}", PathPrefix, string.IsNullOrEmpty(path) || path == "/" ? "" : ("-" + path.Replace('/', '|'))));
        }
        public override void RefreshResource(IStorageProviderSession session, ICloudFileSystemEntry resource)
        {
            var path = GetResourceUrlInternal(session, DropBoxResourceIDHelpers.GetResourcePath(resource));

            int code;
            var res = DropBoxRequestParser.RequestResourceByUrl(path, this, session, out code);

            if (res.Length == 0)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotRetrieveDirectoryList);
            }

            // build the entry and subchilds
            DropBoxRequestParser.UpdateObjectFromJsonString(res, resource as BaseFileEntry, this, session);

            var hash = resource.GetPropertyValue("hash");

            if (!string.IsNullOrEmpty(hash))
            {
                DropBoxRequestParser.Addhash(path, hash, res, session);
            }
        }
        public override bool MoveResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
        {
            var oldPath = DropBoxResourceIDHelpers.GetResourcePath(fsentry);
            var path    = DropBoxResourceIDHelpers.GetResourcePath(newParent, fsentry.Name);

            if (MoveOrRenameItem(session as DropBoxStorageProviderSession, fsentry as BaseFileEntry, path))
            {
                // set the new parent
                if (fsentry.Parent != null && fsentry.Parent is BaseDirectoryEntry)
                {
                    (fsentry.Parent as BaseDirectoryEntry).RemoveChildById(oldPath);
                }
                if (newParent != null && newParent is BaseDirectoryEntry)
                {
                    (newParent as BaseDirectoryEntry).AddChild(fsentry as BaseFileEntry);
                }

                return(true);
            }

            return(false);
        }
        public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry entry, String newName)
        {
            if (entry.Name.Equals("/") || newName.Contains("/"))
            {
                return(false);
            }

            String uri  = String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, entry.Id);
            String data = String.Format("{{name: \"{0}\"}}", newName);
            String json = PerformRequest(session, uri, "PUT", data);

            if (json != null && !SkyDriveJsonParser.ContainsError(json, false))
            {
                var entryBase = entry as BaseFileEntry;
                if (entryBase != null)
                {
                    entryBase.Name = newName;
                }
                return(true);
            }

            return(false);
        }
Esempio n. 31
0
        internal static String GetFileFromDropbox(ICloudDirectoryEntry directory, String fileName, out bool fileExists)
        {
            fileExists = false;
            if (!ExistsChildOnDropbox(directory, fileName))
            {
                return(String.Empty);
            }

            ICloudFileSystemEntry file = directory.GetChild(fileName);

            String content;

            using (Stream streamFile = file.GetDataTransferAccessor().GetDownloadStream())
            {
                using (StreamReader reader = new StreamReader(streamFile, Encoding.UTF8))
                {
                    content = reader.ReadToEnd();
                }
            }

            fileExists = true;
            return(content);
        }
Esempio n. 32
0
        public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry entry, String newName)
        {
            if (entry.Name.Equals("/") || newName.Contains("/"))
            {
                return(false);
            }

            var uri  = String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, entry.GetPropertyValue(SkyDriveConstants.InnerIDKey));
            var data = String.Format("{{name: \"{0}\"}}", newName);
            var json = SkyDriveRequestHelper.PerformRequest(session, uri, "PUT", data, false);

            if (!SkyDriveJsonParser.ContainsError(json, false))
            {
                var entryBase = entry as BaseFileEntry;
                if (entryBase != null)
                {
                    entryBase.Name = newName;
                }
                return(true);
            }

            return(false);
        }
Esempio n. 33
0
        /// <summary>
        /// This method moves a resource from one webdav location to an other
        /// </summary>
        /// <param name="session"></param>
        /// <param name="fsentry"></param>
        /// <param name="newParent"></param>
        /// <returns></returns>
        public override bool MoveResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
        {
            // build the targte url
            String uriStringTarget = this.GetResourceUrl(session, newParent, null);

            uriStringTarget = PathHelper.Combine(uriStringTarget, fsentry.Name);

            if (MoveResource(session, fsentry, uriStringTarget))
            {
                // readjust parent
                BaseDirectoryEntry oldParent = fsentry.Parent as BaseDirectoryEntry;
                oldParent.RemoveChild(fsentry as BaseFileEntry);

                BaseDirectoryEntry newParentObject = newParent as BaseDirectoryEntry;
                newParentObject.AddChild(fsentry as BaseFileEntry);

                return(true);
            }
            else
            {
                return(false);
            }
        }
        public bool RemoveResource(IStorageProviderSession session, ICloudFileSystemEntry resource, RemoveMode mode)
        {
            String url;
            Dictionary <String, String> parameters = null;

            if (mode == RemoveMode.FromParentCollection)
            {
                var pId = (resource.Parent != null ? resource.Parent.Id : GoogleDocsConstants.RootFolderId).ReplaceFirst("_", "%3a");
                url = String.Format("{0}/{1}/contents/{2}", GoogleDocsConstants.GoogleDocsFeedUrl, pId, resource.Id.ReplaceFirst("_", "%3a"));
            }
            else
            {
                url        = String.Format(GoogleDocsConstants.GoogleDocsResourceUrlFormat, resource.Id.ReplaceFirst("_", "%3a"));
                parameters = new Dictionary <string, string> {
                    { "delete", "true" }
                };
            }

            var request = CreateWebRequest(session, url, "DELETE", parameters);

            request.Headers.Add("If-Match", "*");

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    return(true);
                }
            }
            catch (WebException)
            {
            }

            return(false);
        }
        public override bool DeleteResource(IStorageProviderSession session, ICloudFileSystemEntry entry)
        {
            // get the creds
            var creds = ((GenericNetworkCredentials)session.SessionToken).GetCredential(null, null);

            // generate the loca path
            var uriPath = GetResourceUrl(session, entry, null);

            // removed the file
            if (entry is ICloudDirectoryEntry)
            {
                // we need an empty directory
                foreach (var child in (ICloudDirectoryEntry)entry)
                {
                    DeleteResource(session, child);
                }

                // remove the directory
                return(_ftpService.FtpDeleteEmptyDirectory(uriPath, creds));
            }

            // remove the file
            return(_ftpService.FtpDeleteFile(uriPath, creds));
        }
Esempio n. 36
0
 protected File ToFile(ICloudFileSystemEntry fsEntry)
 {
     return(fsEntry == null ? null
                : new File
     {
         ID = MakeId(fsEntry),
         Access = FileShare.None,
         ContentLength = fsEntry.Length,
         CreateBy = SharpBoxProviderInfo.Owner,
         CreateOn = fsEntry.Modified,
         FileStatus = FileStatus.None,
         FolderID = MakeId(fsEntry.Parent),
         ModifiedBy = SharpBoxProviderInfo.Owner,
         ModifiedOn = fsEntry.Modified,
         NativeAccessor = fsEntry,
         ProviderId = SharpBoxProviderInfo.ID,
         ProviderName = SharpBoxProviderInfo.ProviderName,
         Title = MakeTitle(fsEntry),
         RootFolderId = MakeId(RootFolder()),
         RootFolderType = SharpBoxProviderInfo.RootFolderType,
         RootFolderCreator = SharpBoxProviderInfo.Owner,
         Version = 1
     });
 }
 public static bool IsNoolOrRoot(ICloudFileSystemEntry dir)
 {
     return dir == null || ((dir is ICloudDirectoryEntry) && dir.Id.Equals(GoogleDocsConstants.RootFolderId));
 }
 public static bool IsFileEntry(ICloudFileSystemEntry entry)
 {
     return !(entry is ICloudDirectoryEntry);
 }
 public bool DeleteFileSystemEntry(ICloudFileSystemEntry fsentry)
 {
     return _provider.DeleteFileSystemEntry(fsentry);
 }
Esempio n. 40
0
 protected File ToFile(ICloudFileSystemEntry fsEntry)
 {
     return fsEntry == null ? null
                : new File
                      {
                          ID = MakeId(fsEntry),
                          Access = FileShare.None,
                          ContentLength = fsEntry.Length,
                          CreateBy = SharpBoxProviderInfo.Owner,
                          CreateOn = fsEntry.Modified,
                          FileStatus = FileStatus.None,
                          FolderID = MakeId(fsEntry.Parent),
                          ModifiedBy = SharpBoxProviderInfo.Owner,
                          ModifiedOn = fsEntry.Modified,
                          NativeAccessor = fsEntry,
                          ProviderId = SharpBoxProviderInfo.ID,
                          ProviderName = SharpBoxProviderInfo.ProviderName,
                          Title = MakeTitle(fsEntry),
                          RootFolderId = MakeId(RootFolder()),
                          RootFolderType = SharpBoxProviderInfo.RootFolderType,
                          RootFolderCreator = SharpBoxProviderInfo.Owner,
                          Version = 1
                      };
 }
Esempio n. 41
0
        protected String MakeTitle(ICloudFileSystemEntry fsEntry)
        {
            if (fsEntry is ICloudDirectoryEntry && IsRoot(fsEntry as ICloudDirectoryEntry))
            {
                return SharpBoxProviderInfo.CustomerTitle;
            }

            return Web.Files.Classes.Global.ReplaceInvalidCharsAndTruncate(fsEntry.Name);
        }
 /// <summary>
 /// This method removes a given filesystem object from the cloud storage
 /// </summary>
 /// <param name="fsentry"></param>
 /// <returns></returns>
 public bool DeleteFileSystemEntry(ICloudFileSystemEntry fsentry)
 {
     return _Service.DeleteResource(_Session, fsentry);
 }
        private bool CopyResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, String newTargetUrl)
        {
            var config = session.ServiceConfiguration as WebDavConfiguration;
            var creds = session.SessionToken as ICredentials;

            var uriString = PathHelper.Combine(config.ServiceLocator.ToString(), GenericHelper.GetResourcePath(fsentry));

            var uri = new Uri(uriString);
            var uriTarget = new Uri(newTargetUrl);

            var errorCode = new DavService().PerformCopyWebRequest(uri.ToString(), uriTarget.ToString(), creds.GetCredential(null, null));

            return errorCode == HttpStatusCode.Created || errorCode == HttpStatusCode.NoContent;
        }
Esempio n. 44
0
 /// <summary>
 /// This method deletes a resource in the storage provider service
 /// </summary>
 /// <param name="session"></param>
 /// <param name="fsentry"></param>
 /// <param name="newParent"></param>
 /// <returns></returns>
 public abstract bool MoveResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent);
 public bool RenameFileSystemEntry(ICloudFileSystemEntry fsentry, string newName)
 {
     return _provider.RenameFileSystemEntry(fsentry, newName);
 }
        /// <summary>
        /// This method returns the filesystem path (UNIX style) of a specific object
        /// </summary>
        /// <param name="fsObject"></param>
        /// <returns></returns>
        public virtual String GetFileSystemObjectPath(ICloudFileSystemEntry fsObject)
        {
            if (fsObject is ICloudDirectoryEntry)
                return GenericHelper.GetResourcePath(fsObject);

            return GenericHelper.GetResourcePath(fsObject.Parent) + "/" + fsObject.Id;
        }
        /// <summary>
        /// This method renames a given filesystem object (file or folder)
        /// </summary>
        /// <param name="fsentry"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public bool RenameFileSystemEntry(ICloudFileSystemEntry fsentry, string newName)
        {
            // save the old name
            String renamedId = fsentry.Id;

            // rename the resource
            if (_Service.RenameResource(_Session, fsentry, newName))
            {
                // get the parent
                BaseDirectoryEntry p = fsentry.Parent as BaseDirectoryEntry;

                // remove the old childname
                p.RemoveChildById(renamedId);

                // readd the child
                p.AddChild(fsentry as BaseFileEntry);

                // go ahead
                return true;
            }
            else
                return false;
        }
 /// <summary>
 /// This method moves a specifc filesystem object from his current location
 /// into a new folder
 /// </summary>
 /// <param name="fsentry"></param>
 /// <param name="newParent"></param>
 /// <returns></returns>
 public bool CopyFileSystemEntry(ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
 {
     return _Service.CopyResource(_Session, fsentry, newParent);
 }
 public static void UpdateResourceByXml(IStorageProviderSession session, out ICloudFileSystemEntry resource, String xml)
 {
     var parsed = GoogleDocsXmlParser.ParseEntriesXml(session, xml).Single();
     resource = parsed;
 }
 private bool CopyFileSystemEntry(ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
 {
     return _provider.CopyFileSystemEntry(fsentry, newParent);
 }
 public static bool OfGoogleDocsKind(ICloudFileSystemEntry entry)
 {
     var kind = entry.GetPropertyValue(GoogleDocsConstants.KindProperty);
     return kind.Equals("document") || kind.Equals("presentation") || kind.Equals("spreadsheet") || kind.Equals("drawing");
 }
Esempio n. 52
0
 protected string MakeId(ICloudFileSystemEntry entry)
 {
     var path = string.Empty;
     if (entry != null && !(entry is ErrorDirectoryEntry))
     {
         path = SharpBoxProviderInfo.Storage.GetFileSystemObjectPath(entry);
     }
     return string.Format("{0}{1}", PathPrefix, string.IsNullOrEmpty(path) || path == "/" ? "" : ("-" + path.Replace('/', '|')));
 }
 public BaseFileEntryDataTransfer(ICloudFileSystemEntry fileSystemEntry, IStorageProviderService service, IStorageProviderSession session)
 {
     _fsEntry = fileSystemEntry;
     _session = session;
     _service = service;
 }
 public string GetFileSystemObjectPath(ICloudFileSystemEntry fsObject)
 {
     return _provider.GetFileSystemObjectPath(fsObject);
 }
        /// <summary>
        /// Renames a webdave file or folder
        /// </summary>
        /// <param name="session"></param>
        /// <param name="fsentry"></param>
        /// <param name="newName"></param>
        /// <returns></returns>
        public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, string newName)
        {
            // build the targte url
            String uriStringTarget = this.GetResourceUrl(session, fsentry.Parent, null);
            uriStringTarget = PathHelper.Combine(uriStringTarget, newName);

            if (MoveResource(session, fsentry, uriStringTarget))
            {
                // rename the fsentry
                BaseFileEntry fentry = fsentry as BaseFileEntry;
                fentry.Name = newName;

                // go ahead
                return true;
            }
            else
                // go ahead
                return false;
        }
        public override Stream CreateDownloadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry)
        {
            // build the url 
            string url = GetResourceUrl(session, fileSystemEntry, null);

            // get the session creds
            ICredentials creds = session.SessionToken as ICredentials;

            // Build the service
            DavService svc = new DavService();

            // create the webrequest
            WebRequest request = svc.CreateWebRequest(url, WebRequestMethodsEx.Http.Get, creds.GetCredential(null, null), false, null);

            // create the response
            WebResponse response = svc.GetWebResponse(request);

            // get the data 
            Stream orgStream = svc.GetResponseStream(response);

            BaseFileEntryDownloadStream dStream = new BaseFileEntryDownloadStream(orgStream, fileSystemEntry);

            // put the disposable on the stack
            dStream._DisposableObjects.Push(response);

            // go ahead
            return dStream;
        }
        public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long uploadSize)
        {
            // build the url 
            string url = GetResourceUrl(session, fileSystemEntry, null);

            // get the session creds
            ICredentials creds = session.SessionToken as ICredentials;

            // Build the service
            DavService svc = new DavService();

            // get the service config
            WebDavConfiguration conf = (WebDavConfiguration) session.ServiceConfiguration;

            // build the webrequest                        
            WebRequest networkRequest = svc.CreateWebRequestPUT(url, creds.GetCredential(null, null), conf.UploadDataStreambuffered);

            // get the request stream
            WebRequestStream requestStream = svc.GetRequestStream(networkRequest, uploadSize);

            // add disposal opp
            requestStream.PushPostDisposeOperation(CommitUploadStream, svc, networkRequest, fileSystemEntry, requestStream);

            // go ahead
            return requestStream;
        }
        public override bool CopyResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
        {
            // build the targte url            
            String uriStringTarget = this.GetResourceUrl(session, newParent, null);
            uriStringTarget = PathHelper.Combine(uriStringTarget, fsentry.Name);

            if (!CopyResource(session, fsentry, uriStringTarget))
                return false;

            var newParentObject = newParent as BaseDirectoryEntry;
            if (newParentObject != null)
            {
                newParentObject.AddChild(fsentry as BaseFileEntry);   
            }

            return true;
        }
Esempio n. 59
0
 /// <summary>
 /// This method deletes a resource in the storage provider service
 /// </summary>
 /// <param name="session"></param>
 /// <param name="fsentry"></param>
 /// <param name="newParent"></param>
 /// <returns></returns>
 public virtual bool CopyResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, ICloudDirectoryEntry newParent)
 {
     throw new NotSupportedException("This operation is not supported");
 }
        public override void CommitStreamOperation(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, nTransferDirection Direction, Stream NotDisposedStream)
        {

        }