public void RefreshDirectoryContent(IStorageProviderSession session, BaseDirectoryEntry entry)
        {
            if (entry == null)
            {
                return;
            }

            var url        = String.Format(GoogleDocsConstants.GoogleDocsContentsUrlFormat, entry.Id.ReplaceFirst("_", "%3a"));
            var parameters = new Dictionary <string, string> {
                { "max-results", "1000" }
            };

            try
            {
                while (!String.IsNullOrEmpty(url))
                {
                    var request  = CreateWebRequest(session, url, "GET", parameters);
                    var response = (HttpWebResponse)request.GetResponse();
                    var rs       = response.GetResponseStream();

                    var feedXml = new StreamReader(rs).ReadToEnd();
                    var childs  = GoogleDocsXmlParser.ParseEntriesXml(session, feedXml);
                    entry.AddChilds(childs);

                    url = GoogleDocsXmlParser.ParseNext(feedXml);
                }
            }
            catch (WebException)
            {
            }
        }
        public override bool RenameResource(IStorageProviderSession session, ICloudFileSystemEntry fsentry, string newName)
        {
            if (String.IsNullOrEmpty(newName) || GoogleDocsResourceHelper.IsNoolOrRoot(fsentry))
            {
                return(false);
            }

            var url = String.Format(GoogleDocsConstants.GoogleDocsResourceUrlFormat, fsentry.Id.ReplaceFirst("_", "%3a"));

            var request = CreateWebRequest(session, url, "PUT", null);

            request.Headers.Add("If-Match", fsentry.GetPropertyValue(GoogleDocsConstants.EtagProperty));
            GoogleDocsXmlParser.WriteAtom(request, GoogleDocsXmlParser.EntryElement(GoogleDocsXmlParser.TitleElement(newName)));

            try
            {
                var response = (HttpWebResponse)request.GetResponse();
                if (response.StatusCode == HttpStatusCode.OK)
                {
                    //check if extension added
                    if (!(fsentry is ICloudDirectoryEntry) && String.IsNullOrEmpty(Path.GetExtension(newName)))
                    {
                        newName = newName + Path.GetExtension(fsentry.Name);
                    }
                    (fsentry as BaseFileEntry).Name = newName;
                    return(true);
                }
            }
            catch (WebException)
            {
            }

            return(false);
        }
        public override IResumableUploadSession CreateUploadSession(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long bytesToTransfer)
        {
            WebRequest request;

            if (GoogleDocsResourceHelper.IsResorceId(fileSystemEntry.Id))
            {
                //request for update
                request = CreateWebRequest(session, fileSystemEntry.GetPropertyValue(GoogleDocsConstants.ResEditMediaProperty), "PUT", null, true);
                request.Headers.Add("If-Match", "*");
            }
            else
            {
                //request for create
                request = CreateWebRequest(session, fileSystemEntry.Parent.GetPropertyValue(GoogleDocsConstants.ResCreateMediaProperty) + "?convert=false", "POST", null, true);
            }

            if (GoogleDocsResourceHelper.OfGoogleDocsKind(fileSystemEntry))
            {
                ((BaseFileEntry)fileSystemEntry).Name = Path.GetFileNameWithoutExtension(fileSystemEntry.Name);
            }

            GoogleDocsXmlParser.WriteAtom(request, GoogleDocsXmlParser.EntryElement(GoogleDocsXmlParser.TitleElement(fileSystemEntry.Name)));
            request.Headers.Add("X-Upload-Content-Type", Common.Net.MimeMapping.GetMimeMapping(fileSystemEntry.Name));
            request.Headers.Add("X-Upload-Content-Length", bytesToTransfer.ToString(CultureInfo.InvariantCulture));


            var response = request.GetResponse();

            var uploadSession = new ResumableUploadSession(fileSystemEntry, bytesToTransfer);

            uploadSession["Location"] = response.Headers["Location"];
            uploadSession.Status      = ResumableUploadSessionStatus.Started;

            return(uploadSession);
        }
        public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, string Name, ICloudDirectoryEntry parent)
        {
            if (GoogleDocsResourceHelper.IsNoolOrRoot(parent) && GoogleDocsResourceHelper.IsRootName(Name))
            {
                var root = new BaseDirectoryEntry("/", 0, DateTime.Now, session.Service, session)
                {
                    Id = GoogleDocsConstants.RootFolderId
                };
                root.SetPropertyValue(GoogleDocsConstants.ResCreateMediaProperty, GoogleDocsConstants.RootResCreateMediaUrl);
                RefreshDirectoryContent(session, root);
                return(root);
            }

            if (Name.Equals("/"))
            {
                RefreshDirectoryContent(session, parent as BaseDirectoryEntry);
            }

            if (GoogleDocsResourceHelper.IsResorceId(Name))
            {
                var url     = String.Format(GoogleDocsConstants.GoogleDocsResourceUrlFormat, Name.ReplaceFirst("_", "%3a"));
                var request = CreateWebRequest(session, url, "GET", null);
                try
                {
                    var response = (HttpWebResponse)request.GetResponse();
                    var rs       = response.GetResponseStream();

                    var xml   = new StreamReader(rs).ReadToEnd();
                    var entry = GoogleDocsXmlParser.ParseEntriesXml(session, xml).FirstOrDefault();

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

                    if (parent != null)
                    {
                        (parent as BaseDirectoryEntry).AddChild(entry);
                    }

                    var dirEntry = entry as BaseDirectoryEntry;

                    if (dirEntry == null)
                    {
                        return(entry);
                    }

                    RefreshDirectoryContent(session, dirEntry);
                    return(dirEntry);
                }
                catch (WebException)
                {
                    throw new SharpBoxException(SharpBoxErrorCodes.ErrorFileNotFound);
                }
            }

            throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidFileOrDirectoryName);
        }
        public override Stream CreateUploadStream(IStorageProviderSession session, ICloudFileSystemEntry fileSystemEntry, long uploadSize)
        {
            String url;
            bool   update = false;

            String type = GetMimeType(fileSystemEntry.Name);

            if (GoogleDocsResourceHelper.IsResorceId(fileSystemEntry.Id)) //update existent
            {
                var ext = GoogleDocsResourceHelper.GetExtensionByKind(fileSystemEntry.GetPropertyValue(GoogleDocsConstants.KindProperty));
                if (!String.IsNullOrEmpty(ext))
                {
                    //for google docs kind we previously add an extension that don't needed anymore
                    var index = fileSystemEntry.Name.IndexOf('.' + ext, StringComparison.Ordinal);
                    (fileSystemEntry as BaseFileEntry).Name = fileSystemEntry.Name.Substring(0, index);
                }

                url    = fileSystemEntry.GetPropertyValue(GoogleDocsConstants.ResEditMediaProperty);
                update = true;

                if (String.IsNullOrEmpty(url))
                {
                    throw new HttpException(403, "User not authorize to update resource");
                }
            }
            else
            {
                url = fileSystemEntry.Parent.GetPropertyValue(GoogleDocsConstants.ResCreateMediaProperty) + "?convert=false";
            }

            //first initiate resumable upload request
            var initRequest = CreateWebRequest(session, url, update ? "PUT" : "POST", null);

            initRequest.Headers.Add("X-Upload-Content-Length", uploadSize.ToString(CultureInfo.InvariantCulture));
            initRequest.Headers.Add("X-Upload-Content-Type", type);
            if (update)
            {
                initRequest.Headers.Add("If-Match", "*");
            }
            GoogleDocsXmlParser.WriteAtom(initRequest, GoogleDocsXmlParser.EntryElement(null, GoogleDocsXmlParser.TitleElement(fileSystemEntry.Name)));

            var response = initRequest.GetResponse();

            //secondly create request to obtained url
            var uplRequest = CreateWebRequest(session, response.Headers["Location"], "PUT", null);

            uplRequest.ContentLength = uploadSize;
            uplRequest.ContentType   = type;
            uplRequest.Headers.Add("Content-Range", String.Format("bytes {0}-{1}/{2}", 0, uploadSize - 1, uploadSize));

            var wrStream = new WebRequestStream(uplRequest.GetRequestStream(), uplRequest, null);

            wrStream.PushPostDisposeOperation(CommitUploadOperation, session, uplRequest, fileSystemEntry);

            return(wrStream);
        }
        public override ICloudFileSystemEntry CreateResource(IStorageProviderSession session, string name, ICloudDirectoryEntry parent)
        {
            if (String.IsNullOrEmpty(name))
            {
                throw new ArgumentException("Name cannot be empty");
            }

            var url = GoogleDocsResourceHelper.IsNoolOrRoot(parent)
                          ? GoogleDocsConstants.GoogleDocsFeedUrl
                          : String.Format(GoogleDocsConstants.GoogleDocsContentsUrlFormat, parent.Id.ReplaceFirst("_", "%3a"));

            var request = CreateWebRequest(session, url, "POST", null);

            GoogleDocsXmlParser.WriteAtom(request, GoogleDocsXmlParser.EntryElement(GoogleDocsXmlParser.CategoryElement(), GoogleDocsXmlParser.TitleElement(name)));

            try
            {
                using (var response = (HttpWebResponse)request.GetResponse())
                {
                    if (response.StatusCode == HttpStatusCode.Created)
                    {
                        using (var rs = response.GetResponseStream())
                            using (var streamReader = new StreamReader(rs))
                            {
                                var xml   = streamReader.ReadToEnd();
                                var entry = GoogleDocsXmlParser.ParseEntriesXml(session, xml).First();

                                if (parent != null)
                                {
                                    (parent as BaseDirectoryEntry).AddChild(entry);
                                }

                                return(entry);
                            }
                    }
                }
            }
            catch (WebException)
            {
                throw new SharpBoxException(SharpBoxErrorCodes.ErrorCreateOperationFailed);
            }

            return(null);
        }
        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);
        }
        private void CommitUploadOperation(object[] args)
        {
            var session = args[0] as IStorageProviderSession;
            var request = args[1] as WebRequest;
            var entry   = args[2] as BaseFileEntry;

            var responce = (HttpWebResponse)request.GetResponse();
            var stream   = responce.GetResponseStream();

            var xml = new StreamReader(stream).ReadToEnd();

            var uploaded = GoogleDocsXmlParser.ParseEntriesXml(session, xml).First();

            BaseDirectoryEntry parent = null;

            if (entry.Parent != null)
            {
                parent = entry.Parent as BaseDirectoryEntry;
                parent.RemoveChild(entry); //this may be virtual one
            }

            //copy uploaded entry's info to old one
            entry.Name     = uploaded.Name;
            entry.Id       = uploaded.Id;
            entry.Length   = uploaded.Length;
            entry.Modified = uploaded.Modified;
            entry.SetPropertyValue(GoogleDocsConstants.DownloadUrlProperty, uploaded.GetPropertyValue(GoogleDocsConstants.DownloadUrlProperty));
            entry.SetPropertyValue(GoogleDocsConstants.EtagProperty, uploaded.GetPropertyValue(GoogleDocsConstants.EtagProperty));
            entry.SetPropertyValue(GoogleDocsConstants.KindProperty, uploaded.GetPropertyValue(GoogleDocsConstants.KindProperty));
            entry.SetPropertyValue(GoogleDocsConstants.ResEditMediaProperty, uploaded.GetPropertyValue(GoogleDocsConstants.ResCreateMediaProperty));

            if (parent != null)
            {
                parent.AddChild(entry);
            }
        }
        public override void UploadChunk(IStorageProviderSession session, IResumableUploadSession uploadSession, Stream stream, long chunkLength)
        {
            if (stream == null)
            {
                throw new ArgumentNullException("stream");
            }

            if (uploadSession.Status != ResumableUploadSessionStatus.Started)
            {
                throw new InvalidOperationException("Can't upload chunk for given upload session.");
            }

            var request = WebRequest.Create(uploadSession.GetItem <string>("Location"));

            request.Method        = "PUT";
            request.ContentLength = chunkLength;
            request.Headers.Add("Content-Range", string.Format("bytes {0}-{1}/{2}",
                                                               uploadSession.BytesTransfered,
                                                               uploadSession.BytesTransfered + chunkLength - 1,
                                                               uploadSession.BytesToTransfer));

            using (var requestStream = request.GetRequestStream())
            {
                stream.CopyTo(requestStream);
            }

            HttpWebResponse response;

            try
            {
                response = (HttpWebResponse)request.GetResponse();
            }
            catch (WebException exception)
            {
                if (exception.Status == WebExceptionStatus.ProtocolError && exception.Response != null && exception.Response.Headers.AllKeys.Contains("Range"))
                {
                    response = (HttpWebResponse)exception.Response;
                }
                else
                {
                    throw;
                }
            }

            if (response.StatusCode != HttpStatusCode.Created)
            {
                var uplSession = (ResumableUploadSession)uploadSession;
                uplSession.BytesTransfered += chunkLength;

                var locationHeader = response.Headers["Location"];
                if (!string.IsNullOrEmpty(locationHeader))
                {
                    uplSession["Location"] = locationHeader;
                }
            }
            else
            {
                ((ResumableUploadSession)uploadSession).Status = ResumableUploadSessionStatus.Completed;

                using (var responseStream = response.GetResponseStream())
                {
                    if (responseStream == null)
                    {
                        return;
                    }
                    string xml;
                    using (var streamReader = new StreamReader(responseStream))
                    {
                        xml = streamReader.ReadToEnd();
                    }
                    var respFile = GoogleDocsXmlParser.ParseEntriesXml(session, xml).First();
                    var initFile = (BaseFileEntry)uploadSession.File;

                    //replace old file with the file from response
                    initFile.Name     = respFile.Name;
                    initFile.Id       = respFile.Id;
                    initFile.Length   = respFile.Length;
                    initFile.Modified = respFile.Modified;
                    initFile[GoogleDocsConstants.EtagProperty]         = respFile[GoogleDocsConstants.EtagProperty];
                    initFile[GoogleDocsConstants.KindProperty]         = respFile[GoogleDocsConstants.KindProperty];
                    initFile[GoogleDocsConstants.DownloadUrlProperty]  = respFile[GoogleDocsConstants.DownloadUrlProperty];
                    initFile[GoogleDocsConstants.ResEditMediaProperty] = respFile[GoogleDocsConstants.ResEditMediaProperty];

                    var parent = initFile.Parent as BaseDirectoryEntry;
                    if (parent != null)
                    {
                        parent.RemoveChildById(initFile.Name);
                        parent.AddChild(initFile);
                    }
                }
            }

            response.Close();
        }