/// <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); } }
public override void RefreshResource(IStorageProviderSession session, ICloudFileSystemEntry resource) { // nothing to do for files if (!(resource is ICloudDirectoryEntry)) { return; } // build url String uriString = GetResourceUrl(session, resource, null); // get the data List <BaseFileEntry> childs = null; RequestResourceFromWebDavShare(session, uriString, out childs); // set the new childs collection BaseDirectoryEntry dirEntry = resource as BaseDirectoryEntry; dirEntry.ClearChilds(); // add the new childs if (childs != null) { dirEntry.AddChilds(childs); } }
/// <summary> /// This method removes a specific resource from a webdav share /// </summary> /// <param name="session"></param> /// <param name="entry"></param> public override Boolean DeleteResource(IStorageProviderSession session, ICloudFileSystemEntry entry) { // get the credentials ICredentials creds = session.SessionToken as ICredentials; // build url String uriString = this.GetResourceUrl(session, entry, null); Uri uri = new Uri(uriString); // create the service DavService svc = new DavService(); // create the webrequest int errorCode; WebException e; svc.PerformSimpleWebCall(uri.ToString(), WebRequestMethodsEx.WebDAV.Delete, creds.GetCredential(null, null), null, out errorCode, out e); if (!HttpUtilityEx.IsSuccessCode(errorCode)) { return(false); } else { // remove from parent BaseDirectoryEntry parentDir = entry.Parent as BaseDirectoryEntry; parentDir.RemoveChild(entry as BaseFileEntry); // go ahead return(true); } }
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 DeleteResource(IStorageProviderSession session, ICloudFileSystemEntry entry) { // build the path for resource String resourcePath = GenericHelper.GetResourcePath(entry); // request the json object via oauth var parameters = new Dictionary <string, string> { { "path", resourcePath }, { "root", GetRootToken(session as DropBoxStorageProviderSession) } }; try { // remove int code; DropBoxRequestParser.RequestResourceByUrl(GetUrlString(DropBoxDeleteItem, session.ServiceConfiguration), parameters, this, session, out code); // remove from parent BaseDirectoryEntry parentDir = entry.Parent as BaseDirectoryEntry; parentDir.RemoveChild(entry as BaseFileEntry); } catch (Exception) { return(false); } return(true); }
private void RefreshChildsOfDirectory(IStorageProviderSession session, BaseDirectoryEntry dir) { // get the location var reslocation = GetResourceUrl(session, dir, null); // ensure that we have a trailing slash reslocation = reslocation.TrimEnd('/'); reslocation = reslocation + "/"; // build the uri var resUri = new Uri(reslocation); // convert BaseDir to DirInfo var dInfo = new DirectoryInfo(resUri.LocalPath); // clear childs dir.ClearChilds(); // get all childs foreach (var fInfo in dInfo.GetFileSystemInfos()) { var f = CreateEntryByFileSystemInfo(fInfo, session); dir.AddChild(f); } }
/// <summary> /// /// </summary> /// <param name="session"></param> /// <param name="objectToRemove"></param> public static void DeleteFileSystemEntry(IStorageProviderSession session, ICloudFileSystemEntry objectToRemove) { // get the parent dir BaseDirectoryEntry parentDir = objectToRemove.Parent as BaseDirectoryEntry; // remove from parent parentDir.RemoveChild(objectToRemove as BaseFileEntry); }
public void NewBaseDirectoryEntryTest() { int random = new Random().Next(); var baseDirectoryEntry = new BaseDirectoryEntry(random, random.ToString()); Assert.Equal(baseDirectoryEntry.Number, random); Assert.Equal(baseDirectoryEntry.Directory, random.ToString()); }
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); }
private static Boolean BuildDirectyEntry(BaseDirectoryEntry dirEntry, JsonHelper jh, IStorageProviderService service, IStorageProviderSession session) { // build the file entry part if (!BuildFileEntry(dirEntry, jh)) { return(false); } // now take the content var content = jh.GetListProperty("contents"); if (content.Count == 0) { return(true); } // remove all childs dirEntry.ClearChilds(); // add the childs foreach (var jsonContent in content) { // parse the item var jc = new JsonHelper(); if (!jc.ParseJsonMessage(jsonContent)) { continue; } // check if we have a directory var isDir = jc.GetBooleanProperty("is_dir"); BaseFileEntry fentry; if (isDir) { fentry = new BaseDirectoryEntry("Name", 0, DateTime.Now, service, session); } else { fentry = new BaseFileEntry("Name", 0, DateTime.Now, service, session); } // build the file attributes BuildFileEntry(fentry, jc); // establish parent child realtionship dirEntry.AddChild(fentry); } // set the length dirEntry.Length = dirEntry.Count; // go ahead return(true); }
/// <summary> /// /// </summary> /// <param name="session"></param> /// <param name="objectToMove"></param> /// <param name="newParent"></param> public static void MoveFileSystemEntry(IStorageProviderSession session, ICloudFileSystemEntry objectToMove, ICloudDirectoryEntry newParent) { // readjust parent BaseDirectoryEntry oldParent = objectToMove.Parent as BaseDirectoryEntry; oldParent.RemoveChild(objectToMove as BaseFileEntry); BaseDirectoryEntry newParentObject = newParent as BaseDirectoryEntry; newParentObject.AddChild(objectToMove as BaseFileEntry); }
public static ICloudFileSystemEntry ParseSingleEntry(IStorageProviderSession session, String json, JsonHelper parser) { if (parser == null) { parser = CreateParser(json); } ContainsError(json, true, parser); BaseFileEntry entry; String type = parser.GetProperty("type"); if (!IsFolderType(type) && !IsFileType(type)) { throw new SkyDriveParserException("Can not retrieve entry type while parsing single entry"); } String id = parser.GetProperty("id"); String name = parser.GetProperty("name"); String parentID = parser.GetProperty("parent_id"); String uploadLocation = parser.GetProperty("upload_location"); DateTime updatedTime = Convert.ToDateTime(parser.GetProperty("updated_time")); if (IsFolderType(type)) { int count = parser.GetPropertyInt("count"); entry = new BaseDirectoryEntry(name, count, updatedTime, session.Service, session) { Id = id }; } else { int size = parser.GetPropertyInt("size"); entry = new BaseFileEntry(name, size, updatedTime, session.Service, session) { Id = id }; } entry[SkyDriveConstants.UploadLocationKey] = uploadLocation; if (!String.IsNullOrEmpty(parentID)) { entry.ParentID = parentID; } else { entry.Name = "/"; } return(entry); }
/// <summary> /// /// </summary> /// <param name="session"></param> /// <param name="Name"></param> /// <param name="modifiedDate"></param> /// <param name="parent"></param> /// <returns></returns> public static ICloudDirectoryEntry CreateDirectoryEntry(IStorageProviderSession session, string Name, DateTime modifiedDate, ICloudDirectoryEntry parent) { // build up query url var newObj = new BaseDirectoryEntry(Name, 0, modifiedDate, session.Service, session); // case the parent if possible if (parent != null) { var objparent = parent as BaseDirectoryEntry; objparent.AddChild(newObj); } return(newObj); }
/// <summary> /// This method creates a filesystem entry /// </summary> /// <param name="session"></param> /// <param name="Name"></param> /// <param name="modified"></param> /// <param name="fileSize"></param> /// <param name="parent"></param> /// <returns></returns> public static ICloudFileSystemEntry CreateFileSystemEntry(IStorageProviderSession session, string Name, DateTime modified, long fileSize, ICloudDirectoryEntry parent) { // build up query url BaseFileEntry newObj = new BaseFileEntry(Name, fileSize, modified, session.Service, session); // case the parent if possible if (parent != null) { BaseDirectoryEntry objparent = parent as BaseDirectoryEntry; objparent.AddChild(newObj); } return(newObj); }
/// <summary> /// This method request information about a resource /// </summary> /// <param name="session"></param> /// <param name="Name"></param> /// <param name="parent"></param> /// <returns></returns> public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, string Name, ICloudDirectoryEntry parent) { // build url String uriString = GetResourceUrl(session, parent, null); uriString = PathHelper.Combine(uriString, Name); // get the data List <BaseFileEntry> childs = null; BaseFileEntry requestResource = RequestResourceFromWebDavShare(session, uriString, out childs); // check errors if (requestResource == null) { return(null); } // rename the root if (Name.Equals("/")) { requestResource.Name = "/"; } // init parent child relation if (parent != null) { BaseDirectoryEntry parentDir = parent as BaseDirectoryEntry; parentDir.AddChild(requestResource); } // check if we have to add childs if (!(requestResource is BaseDirectoryEntry)) { return(requestResource); } else { BaseDirectoryEntry requestedDir = requestResource as BaseDirectoryEntry; // add the childs foreach (BaseFileEntry child in childs) { requestedDir.AddChild(child); } } // go ahead return(requestResource); }
public override ICloudFileSystemEntry CreateResource(IStorageProviderSession session, string Name, ICloudDirectoryEntry parent) { // get the parent BaseDirectoryEntry parentDir = parent as BaseDirectoryEntry; // build new folder object var newFolder = new BaseDirectoryEntry(Name, 0, DateTime.Now, this, session); parentDir.AddChild(newFolder); // build the path for resource String resourcePath = GenericHelper.GetResourcePath(newFolder); // build the json parameters var parameters = new Dictionary <string, string> { { "path", resourcePath }, { "root", GetRootToken(session as DropBoxStorageProviderSession) } }; // request the json object via oauth int code; var res = DropBoxRequestParser.RequestResourceByUrl(GetUrlString(DropBoxCreateFolder, session.ServiceConfiguration), parameters, this, session, out code); if (res.Length == 0) { parentDir.RemoveChild(newFolder); return(null); } else { // update the folder object DropBoxRequestParser.UpdateObjectFromJsonString(res, newFolder, this, session); } // go ahead return(newFolder); }
/// <summary> /// /// </summary> /// <param name="session"></param> /// <param name="Name"></param> /// <param name="parent"></param> /// <returns></returns> public override ICloudFileSystemEntry CreateResource(IStorageProviderSession session, string Name, ICloudDirectoryEntry parent) { // get the credentials ICredentials creds = session.SessionToken as ICredentials; // build url String uriString = GetResourceUrl(session, parent, null); uriString = PathHelper.Combine(uriString, Name); Uri uri = new Uri(uriString); // build the DavService DavService svc = new DavService(); // create the webrequest int errorCode; WebException e; svc.PerformSimpleWebCall(uri.ToString(), WebRequestMethodsEx.Http.MkCol, creds.GetCredential(null, null), null, out errorCode, out e); if (errorCode != (int)HttpStatusCode.Created) { return(null); } else { BaseDirectoryEntry newDir = new BaseDirectoryEntry(Name, 0, DateTime.Now, this, session); // init parent child relation if (parent != null) { BaseDirectoryEntry parentDir = parent as BaseDirectoryEntry; parentDir.AddChild(newDir); } return(newDir); } }
/// <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); } }
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 static WebDavRequestResult CreateObjectsFromNetworkStream(Stream data, String targetUrl, IStorageProviderService service, IStorageProviderSession session, NameBaseFilterCallback callback) { WebDavConfiguration config = session.ServiceConfiguration as WebDavConfiguration; WebDavRequestResult results = new WebDavRequestResult(); try { String resourceName = String.Empty; long resourceLength = 0; DateTime resourceModificationDate = DateTime.Now; DateTime resourceCreationDate = DateTime.Now; String resourceContentType = String.Empty; Boolean bIsHidden = false; Boolean bIsDirectory = false; Boolean bIsSelf = false; // build queryless uri String queryLessUri = HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator).ToString().TrimEnd('/'); // work with decoded target url String decodedTargetUrl = HttpUtility.UrlDecode(targetUrl); XmlTextReader reader = new XmlTextReader(data); while (reader.Read()) { switch (reader.NodeType) { case XmlNodeType.Element: { // we are on an element and we have to handle this elements String currentElement = reader.Name; // we found a resource name if (currentElement.Contains(":href")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // get the name String nameBase = reader.Value; // call the filter if needed if (callback != null) { nameBase = callback(targetUrl, service, session, nameBase); } /* * Just for bug fixing * * Console.WriteLine(" SVC Locator: " + config.ServiceLocator.ToString()); * Console.WriteLine("SVC Locator QL: " + HttpUtilityEx.GetPathAndQueryLessUri(config.ServiceLocator)); * Console.WriteLine(" Target Url: " + targetUrl); * Console.WriteLine(" NameBase: " + nameBase); */ // generate namebase for self check String nameBaseForSelfCheck; // remove the base url and build for selfcheck if (nameBase.StartsWith(config.ServiceLocator.ToString())) { nameBaseForSelfCheck = HttpUtility.UrlDecode(nameBase); nameBase = nameBase.Remove(0, config.ServiceLocator.ToString().Length); } else { nameBaseForSelfCheck = queryLessUri + HttpUtilityEx.PathDecodeUTF8(nameBase); } // trim all trailing slashes nameBase = nameBase.TrimEnd('/'); // work with the trailing lsahed nameBaseForSelfCheck = nameBaseForSelfCheck.TrimEnd('/'); if (targetUrl.EndsWith("/")) { nameBaseForSelfCheck += "/"; } // check if we are self if (nameBaseForSelfCheck.Equals(decodedTargetUrl)) { bIsSelf = true; } else { bIsSelf = false; } // get the last file or directory name PathHelper ph = new PathHelper(nameBase); resourceName = ph.GetFileName(); // unquote name resourceName = HttpUtility.UrlDecode(resourceName); } else if (currentElement.Contains(":ishidden")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // try to parse int iIsHidden = 0; if (!int.TryParse(reader.Value, out iIsHidden)) { iIsHidden = 0; } // convert bIsHidden = Convert.ToBoolean(iIsHidden); } else if (currentElement.Contains(":getcontentlength")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // read value if (!long.TryParse(reader.Value, out resourceLength)) { resourceLength = -1; } } else if (currentElement.Contains(":creationdate")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // parse if (!DateTime.TryParse(reader.Value, out resourceCreationDate)) { resourceCreationDate = DateTime.Now; } } else if (currentElement.Contains(":getlastmodified")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // parse if (!DateTime.TryParse(reader.Value, out resourceModificationDate)) { resourceModificationDate = DateTime.Now; } } else if (currentElement.Contains(":getcontenttype")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // go one more step reader.Read(); // parse resourceContentType = reader.Value; } else if (currentElement.Contains(":collection")) { // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(currentElement, reader)) { continue; } // set as directory bIsDirectory = true; } // go ahead break; } case XmlNodeType.EndElement: { // handle the end of an response if (!reader.Name.ToLower().Contains(":response")) { break; } // check if it is an element with valud namespace prefix if (!CheckIfNameSpaceDAVSpace(reader.Name, reader)) { continue; } // handle the end of an response, this means // create entry BaseFileEntry entry = null; if (bIsDirectory) { entry = new BaseDirectoryEntry(resourceName, resourceLength, resourceModificationDate, service, session); } else { entry = new BaseFileEntry(resourceName, resourceLength, resourceModificationDate, service, session); } entry.SetPropertyValue("CreationDate", resourceCreationDate); entry.SetPropertyValue("ContentType", resourceContentType); if (!bIsHidden) { if (bIsSelf) { results.Self = entry; } else { results.Childs.Add(entry); } } // reset all state properties resourceName = String.Empty; resourceLength = 0; resourceModificationDate = DateTime.Now; resourceCreationDate = DateTime.Now; resourceContentType = String.Empty; bIsHidden = false; bIsDirectory = false; // go ahead break; } default: { break; } } } ; if (results.Self == null) { throw new Exception("Unknown error in webrequest parser"); } } catch (Exception) { } // go ahead return(results); }
public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, String nameOrID, ICloudDirectoryEntry parent) { /* In this method name could be either requested resource name or it's ID. * In first case just refresh the parent and then search child with an appropriate. * In second case it does not matter if parent is null or not a parent because we use only resource ID. */ if (SkyDriveHelpers.HasResourceID(nameOrID) || nameOrID.Equals("/") && parent == null) //If request by ID or root folder requested { var id = SkyDriveHelpers.GetResourceID(nameOrID); var uri = id != String.Empty ? String.Format("{0}/{1}", SkyDriveConstants.BaseAccessUrl, id) : SkyDriveConstants.RootAccessUrl; if (SkyDriveHelpers.IsFolderID(id)) { var contents = new List <ICloudFileSystemEntry>(); BaseDirectoryEntry entry = null; /*var completeContent = new AutoResetEvent(false); * ThreadPool.QueueUserWorkItem(state => * { * contents.AddRange(RequestContentByUrl(session, uri + "/files")); * ((AutoResetEvent) state).Set(); * }, completeContent); * * var completeEntry = new AutoResetEvent(false); * ThreadPool.QueueUserWorkItem(state => * { * entry = RequestResourseByUrl(session, uri) as BaseDirectoryEntry; * ((AutoResetEvent) state).Set(); * }, completeEntry); * * WaitHandle.WaitAll(new WaitHandle[] {completeContent, completeEntry});*/ entry = RequestResourseByUrl(session, uri) as BaseDirectoryEntry; contents.AddRange(RequestContentByUrl(session, uri + "/files")); if (entry != null && contents.Any()) { entry.AddChilds(contents.Cast <BaseFileEntry>()); } return(entry); } return(RequestResourseByUrl(session, uri)); } else { String uri; if (SkyDriveHelpers.HasParentID(nameOrID)) { uri = String.Format(SkyDriveConstants.FilesAccessUrlFormat, SkyDriveHelpers.GetParentID(nameOrID)); } else if (parent != null) { uri = String.Format(SkyDriveConstants.FilesAccessUrlFormat, parent.GetPropertyValue(SkyDriveConstants.InnerIDKey)); } else { uri = SkyDriveConstants.RootAccessUrl + "/files"; } nameOrID = Path.GetFileName(nameOrID); var entry = RequestContentByUrl(session, uri).FirstOrDefault(x => x.Name.Equals(nameOrID)); return(entry); } }
public override ICloudFileSystemEntry RequestResource(IStorageProviderSession session, string Name, ICloudDirectoryEntry parent) { // build path String path; if (Name.Equals("/")) { path = session.ServiceConfiguration.ServiceLocator.LocalPath; } else if (parent == null) { path = Path.Combine(path = session.ServiceConfiguration.ServiceLocator.LocalPath, Name); } else { path = new Uri(GetResourceUrl(session, parent, Name)).LocalPath; } // check if file exists if (File.Exists(path)) { // create the fileinfo FileInfo fInfo = new FileInfo(path); BaseFileEntry bf = new BaseFileEntry(fInfo.Name, fInfo.Length, fInfo.LastWriteTimeUtc, this, session) { Parent = parent }; // add to parent if (parent != null) { (parent as BaseDirectoryEntry).AddChild(bf); } // go ahead return(bf); } // check if directory exists else if (Directory.Exists(path)) { // build directory info DirectoryInfo dInfo = new DirectoryInfo(path); // build bas dir BaseDirectoryEntry dir = CreateEntryByFileSystemInfo(dInfo, session, parent) as BaseDirectoryEntry; if (Name.Equals("/")) { dir.Name = "/"; } // add to parent if (parent != null) { (parent as BaseDirectoryEntry).AddChild(dir); } // refresh the childs RefreshChildsOfDirectory(session, dir); // go ahead return(dir); } else { return(null); } }
private static ICloudFileSystemEntry ParseSingleEntry(IStorageProviderSession session, String json, JsonHelper parser) { if (json == null) { return(null); } if (parser == null) { parser = CreateParser(json); } if (ContainsError(json, false, parser)) { return(null); } BaseFileEntry entry; var type = parser.GetProperty("type"); if (!IsFolderType(type) && !IsFileType(type)) { return(null); } var id = parser.GetProperty("id"); var name = parser.GetProperty("name"); var parentID = parser.GetProperty("parent_id"); var uploadLocation = parser.GetProperty("upload_location"); var updatedTime = Convert.ToDateTime(parser.GetProperty("updated_time")).ToUniversalTime(); if (IsFolderType(type)) { int count = parser.GetPropertyInt("count"); entry = new BaseDirectoryEntry(name, count, updatedTime, session.Service, session) { Id = id }; } else { var size = Convert.ToInt64(parser.GetProperty("size")); entry = new BaseFileEntry(name, size, updatedTime, session.Service, session) { Id = id }; } entry[SkyDriveConstants.UploadLocationKey] = uploadLocation; if (!String.IsNullOrEmpty(parentID)) { entry.ParentID = SkyDriveConstants.RootIDRegex.IsMatch(parentID) ? "/" : parentID; } else { entry.Name = "/"; entry.Id = "/"; } entry[SkyDriveConstants.InnerIDKey] = id; entry[SkyDriveConstants.TimestampKey] = DateTime.UtcNow.ToString(CultureInfo.InvariantCulture); return(entry); }
public static BaseFileEntry UpdateObjectFromJsonString(String jsonMessage, BaseFileEntry objectToUpdate, IStorageProviderService service, IStorageProviderSession session) { // verify if we have a directory or a file var jc = new JsonHelper(); if (!jc.ParseJsonMessage(jsonMessage)) { throw new SharpBoxException(SharpBoxErrorCodes.ErrorInvalidFileOrDirectoryName); } var isDir = jc.GetBooleanProperty("is_dir"); // create the entry BaseFileEntry dbentry; Boolean bEntryOk; if (isDir) { if (objectToUpdate == null) { dbentry = new BaseDirectoryEntry("Name", 0, DateTime.Now, service, session); } else { dbentry = objectToUpdate as BaseDirectoryEntry; } bEntryOk = BuildDirectyEntry(dbentry as BaseDirectoryEntry, jc, service, session); } else { if (objectToUpdate == null) { dbentry = new BaseFileEntry("Name", 0, DateTime.Now, service, session); } else { dbentry = objectToUpdate; } bEntryOk = BuildFileEntry(dbentry, jc); } // parse the childs and fill the entry as self if (!bEntryOk) { throw new SharpBoxException(SharpBoxErrorCodes.ErrorCouldNotContactStorageService); } // set the is deleted flag try { // try to read the is_deleted property dbentry.IsDeleted = jc.GetBooleanProperty("is_deleted"); } catch (Exception) { // the is_deleted proprty is missing (so it's not a deleted file or folder) dbentry.IsDeleted = false; } // return the child return(dbentry); }