public static string GetName(this WebDavResource item) { var normalizedUri = item.Uri.TrimEnd('/'); var lastSlashIndex = normalizedUri.LastIndexOf('/'); return(normalizedUri.Substring(lastSlashIndex + 1)); }
/// <summary> /// Creates a resource with a specified name. /// </summary> /// <param name="name">Name of the new resource.</param> /// <returns>Newly created resource.</returns> public IResource CreateResource(string name) { var resource = new WebDavResource(); try { resource.SetHref(new Uri(Href.AbsoluteUri + name)); var credentials = (NetworkCredential)_credentials; string auth = "Basic " + Convert.ToBase64String( Encoding.Default.GetBytes(credentials.UserName + ":" + credentials.Password)); var request = (HttpWebRequest)WebRequest.Create(resource.Href); request.Method = "PUT"; request.Credentials = credentials; request.ContentType = "text/xml"; request.Accept = "text/xml"; request.Headers["translate"] = "f"; request.Headers.Add("Authorization", auth); using (var response = (HttpWebResponse)request.GetResponse()) { if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.NoContent) { Open(Href); resource = (WebDavResource)GetResource(name); resource.SetCredentials(_credentials); } } } catch (Exception e) { } return(resource); }
private IEnumerable <WebDavResource> Convert(IEnumerable <SystemFile> files, Uri baseUri) { var convertResult = new List <WebDavResource>(); var credentials = new NetworkCredential(ScpContext.User.Login, _cryptography.Decrypt(ScpContext.User.EncryptedPassword), WebDavAppConfigManager.Instance.UserDomain); foreach (var file in files) { var webDavitem = new WebDavResource(); webDavitem.SetCredentials(credentials); webDavitem.SetHref(baseUri.Append(ScpContext.User.OrganizationId).Append(file.RelativeUrl.Replace("\\", "/"))); webDavitem.SetItemType(file.IsDirectory? ItemType.Folder : ItemType.Resource); webDavitem.SetLastModified(file.Changed); webDavitem.ContentLength = file.Size; webDavitem.AllocatedSpace = file.FRSMQuotaMB; webDavitem.Summary = file.Summary; convertResult.Add(webDavitem); } return(convertResult); }
private BaseFsEntry Convert(WebDavResource resource, bool hasDirectories) { if (resource.IsCollection) { return(new DirectoryEntry { CanRead = true, CanWrite = true, HasSubDirectories = hasDirectories, LastModified = resource.LastModifiedDate ?? new DateTime(), Name = resource.DisplayName, Path = GetRelativePath(Root, resource.Uri), ParentPath = GetRelativePath(Root, GetParentPath(resource.Uri)) }); } else { return(new FileEntry { CanRead = true, CanWrite = true, LastModified = resource.LastModifiedDate ?? new DateTime(), Name = resource.DisplayName, Path = GetRelativePath(Root, resource.Uri), ParentPath = GetRelativePath(Root, GetParentPath(resource.Uri)), Size = resource.ContentLength ?? 0, Md5Hash = resource.ETag }); } }
/// <summary> /// Creates a resource with a specified name. /// </summary> /// <param name="name">Name of the new resource.</param> /// <returns>Newly created resource.</returns> public IResource CreateResource(string name) { var resource = new WebDavResource(); try { resource.SetHref(new Uri(Href.AbsoluteUri + name)); var credentials = (NetworkCredential) _credentials; string auth = "Basic " + Convert.ToBase64String( Encoding.Default.GetBytes(credentials.UserName + ":" + credentials.Password)); var request = (HttpWebRequest) WebRequest.Create(resource.Href); request.Method = "PUT"; request.Credentials = credentials; request.ContentType = "text/xml"; request.Accept = "text/xml"; request.Headers["translate"] = "f"; request.Headers.Add("Authorization", auth); using (var response = (HttpWebResponse) request.GetResponse()) { if (response.StatusCode == HttpStatusCode.Created || response.StatusCode == HttpStatusCode.NoContent) { Open(Href); resource = (WebDavResource) GetResource(name); resource.SetCredentials(_credentials); } } } catch (Exception e) { } return resource; }
/// <summary> /// Gets the specified resource from server. /// </summary> /// <param name="name">Name of the resource.</param> /// <returns>Resource corresponding to requested name.</returns> public IResource GetResource(string name) { IHierarchyItem item = _children.Single(i => i.DisplayName.ToLowerInvariant().Trim('/') == name.ToLowerInvariant().Trim('/')); var resource = new WebDavResource(); resource.SetCredentials(_credentials); resource.SetHierarchyItem(item); return(resource); }
public WebDavResourceNode(WebDavResource resource) { Uri = resource.Uri; RelUri = resource.Uri; ETag = resource.ETag; LastModifiedDate = resource.LastModifiedDate.Value.ToUniversalTime(); ContentLength = resource.ContentLength; IsCollection = resource.IsCollection; Children = new List <WebDavResourceNode>(); }
/// <summary> /// Gets the specified resource from server. /// </summary> /// <param name="name">Name of the resource.</param> /// <returns>Resource corresponding to requested name.</returns> public IResource GetResource(string name) { IHierarchyItem item = this._children.Where(i => i.ItemType == ItemType.Resource && i.DisplayName == name).Single(); WebDavResource resource = new WebDavResource(); resource.SetCredentials(this._credentials); resource.SetHierarchyItem(item); return(resource); }
public WebDavRemoteProperty(WebDavResource resource, string baseDirectory) { _resource = resource; //Find the resource Type _type = _resource.IsCollection == true ? SyncElementType.Directory : SyncElementType.File; _relativePath = _resource.Uri.Replace(baseDirectory, ""); //Cut of Tailing slash, does not exist in convention in order //to be able to compare paths _relativePath = _relativePath.RemoveTailingSlashes(); _decodedRelativePath = _relativePath.UrlDecode(); }
public void LockFile(string path) { var resource = new WebDavResource(); var fileUrl = new Uri(WebDavAppConfigManager.Instance.WebdavRoot) .Append(ScpContext.User.OrganizationId) .Append(path); resource.SetHref(fileUrl); resource.SetCredentials(new NetworkCredential(ScpContext.User.Login, _cryptography.Decrypt(ScpContext.User.EncryptedPassword))); resource.Lock(); }
public async Task <OcsDirectoryInfo> GetDirectoryInfo(string name) { PropfindResponse response = await this.webDav.Propfind(name) .ConfigureAwait(false); if (!response.IsSuccessful) { return(null); } WebDavResource resource = response.Resources .OrderBy(r => r.Uri.Length) .FirstOrDefault(); if (resource == null) { return new OcsDirectoryInfo { Name = name } } ; WebDavProperty usedProperty = resource.Properties.FirstOrDefault(p => p.Name.LocalName == "quota-used-bytes"); WebDavProperty availableProperty = resource.Properties.FirstOrDefault(p => p.Name.LocalName == "quota-available-bytes"); long used, avail; if (usedProperty == null || !long.TryParse(usedProperty.Value, out used)) { used = long.MinValue; } if (availableProperty == null || !long.TryParse(availableProperty.Value, out avail)) { avail = long.MinValue; } long?quota = null; if (used != long.MinValue && avail != long.MinValue) { quota = used + avail; } return(new OcsDirectoryInfo { Name = name, QuotaBytes = quota, SizeBytes = used != long.MinValue ? used : default(long?) }); }
public void UploadFile(string path, Stream stream) { var resource = new WebDavResource(); var fileUrl = new Uri(WebDavAppConfigManager.Instance.WebdavRoot) .Append(WspContext.User.OrganizationId) .Append(path); resource.SetHref(fileUrl); resource.SetCredentials(new NetworkCredential(WspContext.User.Login, _cryptography.Decrypt(WspContext.User.EncryptedPassword))); var bytes = ReadFully(stream); resource.Upload(bytes); }
public void UploadFile(string path, HttpPostedFileBase file) { var resource = new WebDavResource(); var fileUrl = new Uri(WebDavAppConfigManager.Instance.WebdavRoot) .Append(ScpContext.User.OrganizationId) .Append(path) .Append(Path.GetFileName(file.FileName)); resource.SetHref(fileUrl); resource.SetCredentials(new NetworkCredential(ScpContext.User.Login, _cryptography.Decrypt(ScpContext.User.EncryptedPassword))); file.InputStream.Seek(0, SeekOrigin.Begin); var bytes = ReadFully(file.InputStream); resource.Upload(bytes); }
public WebDavFile(WebDavResource resource, string rootUri) { Uri = resource.Uri; RelUri = resource.Uri; if (RelUri.StartsWith(rootUri)) { RelUri = RelUri.Remove(0, rootUri.Length); while (RelUri.StartsWith("/")) { RelUri = RelUri.Remove(0, 1); } } ETag = resource.ETag; LastModifiedDate = resource.LastModifiedDate.Value.ToUniversalTime(); ContentLength = resource.ContentLength.Value; if (resource.IsCollection) { throw new Exception("Kan ikke lage en fil av en collection"); } }
async private Task DownloadFile(WebDavResource fileResource, string destinationDir, int fileInDirNo, int filesinDirCount) { string decodedResourceUri = HttpUtility.UrlDecode(fileResource.Uri); string newFilePath = Path.Combine(destinationDir, Path.GetFileName(decodedResourceUri)); FileInfo fileinfo = new FileInfo(newFilePath); if (fileinfo.Exists && fileinfo.Length == fileResource.ContentLength) { return; } if (fileinfo.Exists) { await DownloadFileFromLastPosition(fileinfo, fileInDirNo, filesinDirCount, fileResource); } else { await DownloadFileFromBeginning(fileinfo, fileInDirNo, filesinDirCount, fileResource); } }
/// <summary> /// Processes the response from the server. /// </summary> /// <param name="response">The raw response from the server.</param> private void ProcessResponse(string response) { try { var XmlDoc = new XmlDocument(); XmlDoc.LoadXml(response); XmlNodeList XmlResponseList = XmlDoc.GetElementsByTagName("D:response"); if (XmlResponseList.Count == 0) { XmlResponseList = XmlDoc.GetElementsByTagName("d:response"); } var children = new WebDavResource[XmlResponseList.Count]; int counter = 0; foreach (XmlNode XmlCurrentResponse in XmlResponseList) { var item = new WebDavResource(); item.SetCredentials(_credentials); foreach (XmlNode XmlCurrentNode in XmlCurrentResponse.ChildNodes) { switch (XmlCurrentNode.LocalName) { case "href": string href = XmlCurrentNode.InnerText; if (!Regex.Match(href, "^https?:\\/\\/").Success) { href = _path.Scheme + "://" + _path.Host + href; } item.SetHref(href, _path); break; case "propstat": foreach (XmlNode XmlCurrentPropStatNode in XmlCurrentNode) { switch (XmlCurrentPropStatNode.LocalName) { case "prop": foreach (XmlNode XmlCurrentPropNode in XmlCurrentPropStatNode) { switch (XmlCurrentPropNode.LocalName) { case "creationdate": item.SetCreationDate(XmlCurrentPropNode.InnerText); break; case "getcontentlanguage": item.SetProperty( new Property( new PropertyName("getcontentlanguage", XmlCurrentPropNode.NamespaceURI), XmlCurrentPropNode.InnerText)); break; case "getcontentlength": item.SetProperty( new Property( new PropertyName("getcontentlength", XmlCurrentPropNode.NamespaceURI), XmlCurrentPropNode.InnerText)); break; case "getcontenttype": item.SetProperty( new Property( new PropertyName("getcontenttype", XmlCurrentPropNode.NamespaceURI), XmlCurrentPropNode.InnerText)); break; case "getlastmodified": item.SetLastModified(XmlCurrentPropNode.InnerText); break; case "resourcetype": item.SetProperty( new Property( new PropertyName("resourcetype", XmlCurrentPropNode.NamespaceURI), XmlCurrentPropNode.InnerXml)); break; //case "lockdiscovery": //{ // if (XmlCurrentPropNode.HasChildNodes == false) // { // break; // } // foreach (XmlNode activeLockNode in XmlCurrentPropNode.FirstChild) // { // switch (activeLockNode.LocalName) // { // case "owner": // item.SetProperty( // new Property( // new PropertyName("owner", // activeLockNode.NamespaceURI), // activeLockNode.InnerXml)); // break; // case "locktoken": // var lockTokenNode = activeLockNode.FirstChild; // item.SetProperty( // new Property( // new PropertyName("locktoken", // lockTokenNode.NamespaceURI), // lockTokenNode.InnerXml)); // break; // } // } // break; //} } } break; case "status": break; } } break; } } if (item.DisplayName != String.Empty) { children[counter] = item; counter++; } else { SetItemType(ItemType.Folder); SetHref(item.Href.AbsoluteUri, item.Href); SetCreationDate(item.CreationDate); SetComment(item.Comment); SetCreatorDisplayName(item.CreatorDisplayName); SetLastModified(item.LastModified); foreach (Property property in item.Properties) { SetProperty(property); } } } int childrenCount = 0; foreach (IHierarchyItem item in children) { if (item != null) { childrenCount++; } } _children = new IHierarchyItem[childrenCount]; counter = 0; foreach (IHierarchyItem item in children) { if (item != null) { _children[counter] = item; counter++; } } } catch (XmlException e) { } }
public async Task <IEnumerable <TweakDatabaseSyncFile> > CheckForUpdates(string localPath) { var client = CreateClient(TweakDatabaseLoginTypes.ReadOnlyAll); var syncFiles = new List <TweakDatabaseSyncFile>(); WebDavResource resTopFolder = null; var checkedFiles = new List <string>(); bool responseSuccessfull = false; async Task checkOutFolder(string remotePath) { var response = await client.Propfind(remotePath, new PropfindParameters() { ApplyTo = ApplyTo.Propfind.ResourceAndAncestors }); if (resTopFolder is null && response.IsSuccessful && response.Resources.Any()) { resTopFolder = response.Resources.ElementAtOrDefault(0); responseSuccessfull = true; } if (responseSuccessfull && response.Resources.Count > 1) { for (int i = 1, loopTo = response.Resources.Count - 1; i <= loopTo; i++) { var res = response.Resources.ElementAtOrDefault(i); bool isFolder = res.Uri.EndsWith("/"); if (!isFolder) { TweakDatabaseSyncAction?syncAction = default; string localFile = string.Empty; string remoteFile = string.Empty; // Get remote file path remoteFile = res.Uri; // Get local file path localFile = Path.Combine(localPath, Uri.UnescapeDataString(res.Uri.Substring(resTopFolder.Uri.Length)).Replace("/", @"\")); // Check action if (File.Exists(localFile)) { if (File.GetLastWriteTime(localFile) < res.LastModifiedDate == true) { syncAction = TweakDatabaseSyncAction.UpdatedFile; } } else { syncAction = TweakDatabaseSyncAction.NewFile; } // Add to list checkedFiles.Add(localFile); if (syncAction is object) { syncFiles.Add(new TweakDatabaseSyncFile((TweakDatabaseSyncAction)syncAction, localFile, remoteFile)); } } } } }; // Check for new & updated files await checkOutFolder(Preferences.CategoryPaths[TweakDatabaseCategories.Reviewed]); // Find all old files to remove if (responseSuccessfull) { var allLocalFiles = Directory.GetFiles(localPath, "*", SearchOption.AllDirectories); foreach (string lf in allLocalFiles) { bool isKnown = false; foreach (string checkedFile in checkedFiles) { if (!isKnown && (checkedFile ?? "") == (lf ?? "")) { isKnown = true; } } if (!isKnown) { syncFiles.Add(new TweakDatabaseSyncFile(TweakDatabaseSyncAction.RemovedFile, lf, string.Empty)); } } } return(syncFiles); }
/// <summary> /// Gets the specified resource from server. /// </summary> /// <param name="name">Name of the resource.</param> /// <returns>Resource corresponding to requested name.</returns> public IResource GetResource(string name) { IHierarchyItem item = _children.Single(i => i.DisplayName.ToLowerInvariant().Trim('/') == name.ToLowerInvariant().Trim('/')); var resource = new WebDavResource(); resource.SetCredentials(_credentials); resource.SetHierarchyItem(item); return resource; }
/// <summary> /// Gets the specified resource from server. /// </summary> /// <param name="name">Name of the resource.</param> /// <returns>Resource corresponding to requested name.</returns> public IResource GetResource(string name) { IHierarchyItem item = this._children.Where(i => i.ItemType == ItemType.Resource && i.DisplayName == name).Single(); WebDavResource resource = new WebDavResource(); resource.SetCredentials(this._credentials); resource.SetHierarchyItem(item); return resource; }
private IEnumerable<WebDavResource> Convert(IEnumerable<SystemFile> files, Uri baseUri) { var convertResult = new List<WebDavResource>(); var credentials = new NetworkCredential(WspContext.User.Login, _cryptography.Decrypt(WspContext.User.EncryptedPassword), WebDavAppConfigManager.Instance.UserDomain); foreach (var file in files) { var webDavitem = new WebDavResource(); webDavitem.SetCredentials(credentials); webDavitem.SetHref(baseUri.Append(WspContext.User.OrganizationId).Append(file.RelativeUrl.Replace("\\","/"))); webDavitem.SetItemType(file.IsDirectory? ItemType.Folder : ItemType.Resource); webDavitem.SetLastModified(file.Changed); webDavitem.ContentLength = file.Size; webDavitem.AllocatedSpace = file.FRSMQuotaMB; webDavitem.Summary = file.Summary; convertResult.Add(webDavitem); } return convertResult; }
public void UploadFile(string path, HttpPostedFileBase file) { var resource = new WebDavResource(); var fileUrl = new Uri(WebDavAppConfigManager.Instance.WebdavRoot) .Append(WspContext.User.OrganizationId) .Append(path) .Append(Path.GetFileName(file.FileName)); resource.SetHref(fileUrl); resource.SetCredentials(new NetworkCredential(WspContext.User.Login, _cryptography.Decrypt(WspContext.User.EncryptedPassword))); file.InputStream.Seek(0, SeekOrigin.Begin); var bytes = ReadFully(file.InputStream); resource.Upload(bytes); }
public static FileSystemInfoContract ToFileSystemInfoContract(this WebDavResource item) => item.IsCollection ? new DirectoryInfoContract(WebUtility.UrlDecode(item.Uri), WebUtility.UrlDecode(item.GetName()), item.CreationDate ?? DateTimeOffset.FromFileTime(0), item.LastModifiedDate ?? DateTimeOffset.FromFileTime(0)) as FileSystemInfoContract : new FileInfoContract(WebUtility.UrlDecode(item.Uri), WebUtility.UrlDecode(item.GetName()), item.CreationDate ?? DateTimeOffset.FromFileTime(0), item.LastModifiedDate ?? DateTimeOffset.FromFileTime(0), (FileSize)(item.ContentLength ?? -1), item.ETag) as FileSystemInfoContract;
async private Task DownloadFileFromBeginning(FileInfo fileinfo, int fileInDirNo, int filesinDirCount, WebDavResource fileResource) { long downloadSize = fileResource.ContentLength ?? 0; using (var response = await Client.GetRawFile(fileResource.Uri)) { using (var fileStream = fileinfo.Create()) { await WriteWebDavToFile(downloadSize, response.Stream, fileinfo, fileInDirNo, filesinDirCount, fileStream); } } }
async private Task DownloadFileFromLastPosition(FileInfo fileinfo, int fileInDirNo, int filesinDirCount, WebDavResource fileResource) { long starPos = (fileinfo.Length / BLOCK_SIZE) * BLOCK_SIZE; var downloadParameters = new GetFileParameters { Headers = new List <KeyValuePair <string, string> > { new KeyValuePair <string, string>("Range", "bytes=" + starPos.ToString() + "-" + fileResource.ContentLength) }.AsReadOnly() }; using (var response = await Client.GetRawFile(fileResource.Uri, downloadParameters)) { using (var fileStream = fileinfo.OpenWrite()) { fileStream.Position = starPos; long downloadSize = (fileResource.ContentLength ?? 0) - starPos; await WriteWebDavToFile(downloadSize, response.Stream, fileinfo, fileInDirNo, filesinDirCount, fileStream); } } }