Пример #1
0
        public async Task UT_WebDavClient_PropFind_PropName()
        {
            var mockHandler    = new MockHttpMessageHandler();
            var requestContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:propfind xmlns:D=\"DAV:\"><D:propname /></D:propfind>";

            var requestHeaders = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>(WebDavConstants.Depth, WebDavDepthHeaderValue.Infinity.ToString())
            };

            var responseContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://127.0.0.1/webdav</D:href><D:propstat><D:status>HTTP/1.1 200 OK</D:status><D:prop><D:getcontenttype/><D:getlastmodified/><D:lockdiscovery/><D:ishidden/><D:supportedlock/><D:getetag/><D:displayname/><D:getcontentlanguage/><D:getcontentlength/><D:iscollection/><D:creationdate/><D:resourcetype/></D:prop></D:propstat></D:response></D:multistatus>";

            mockHandler.When(WebDavMethod.PropFind, WebDavRootFolder).WithContent(requestContent).WithHeaders(requestHeaders).Respond(HttpStatusCode.OK, new StringContent(responseContent));

            using (var client = CreateWebDavClient(mockHandler))
            {
                PropFind pf       = PropFind.CreatePropFindWithPropName();
                var      response = await client.PropFindAsync(WebDavRootFolder, WebDavDepthHeaderValue.Infinity, pf);

                var multistatus = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                Assert.IsTrue(response.IsSuccessStatusCode);
                Assert.IsNotNull(multistatus);
            }
        }
Пример #2
0
        public async Task UT_WebDavClient_PropFind_AllPropDepthZero()
        {
            var mockHandler    = new MockHttpMessageHandler();
            var requestContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:propfind xmlns:D=\"DAV:\"><D:allprop /></D:propfind>";

            var requestHeaders = new List <KeyValuePair <string, string> >
            {
                new KeyValuePair <string, string>(WebDavConstants.Depth, WebDavDepthHeaderValue.Zero.ToString())
            };

            var responseContent = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:multistatus xmlns:D=\"DAV:\"><D:response><D:href>http://127.0.0.1/webdav</D:href><D:propstat><D:status>HTTP/1.1 200 OK</D:status><D:prop><D:getcontenttype/><D:getlastmodified>Sat, 08 Apr 2017 10:07:38 GMT</D:getlastmodified><D:lockdiscovery/><D:ishidden>0</D:ishidden><D:supportedlock><D:lockentry><D:lockscope><D:exclusive/></D:lockscope><D:locktype><D:write/></D:locktype></D:lockentry><D:lockentry><D:lockscope><D:shared/></D:lockscope><D:locktype><D:write/></D:locktype></D:lockentry></D:supportedlock><D:getetag/><D:displayname>/</D:displayname><D:getcontentlanguage/><D:getcontentlength>0</D:getcontentlength><D:iscollection>1</D:iscollection><D:creationdate>2017-04-06T09:32:20.983Z</D:creationdate><D:resourcetype><D:collection/></D:resourcetype></D:prop></D:propstat></D:response></D:multistatus>";

            mockHandler.When(WebDavMethod.PropFind, WebDavRootFolder).WithContent(requestContent).WithHeaders(requestHeaders).Respond(HttpStatusCode.OK, new StringContent(responseContent));

            using (var client = CreateWebDavClient(mockHandler))
            {
                PropFind pf       = PropFind.CreatePropFindAllProp();
                var      response = await client.PropFindAsync(WebDavRootFolder, WebDavDepthHeaderValue.Zero, pf);

                var multistatus = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                Assert.IsTrue(response.IsSuccessStatusCode);
                Assert.IsNotNull(multistatus);
            }
        }
        public void UIT_WebDavClient_Copy()
        {
            using (var client = CreateWebDavClientWithDebugHttpMessageHandler())
            {
                var testCollectionSource      = UriHelper.CombineUrl(webDavRootFolder, TestCollection, true);
                var testCollectionDestination = UriHelper.CombineUrl(webDavRootFolder, TestCollection + "2", true);
                var testFile = UriHelper.CombineUrl(testCollectionSource, TestFile, true);

                // Create source collection.
                var response             = client.MkcolAsync(testCollectionSource).Result;
                var mkColResponseSuccess = response.IsSuccessStatusCode;

                // Put file.
                using (var fileStream = File.OpenRead(TestFile))
                {
                    var content = new StreamContent(fileStream);
                    response = client.PutAsync(testFile, content).Result;
                }

                var putResponseSuccess = response.IsSuccessStatusCode;

                // Copy.
                response = client.CopyAsync(testCollectionSource, testCollectionDestination).Result;
                var copyResponseSuccess = response.IsSuccessStatusCode;

                // PropFind.
                PropFind pf = PropFind.CreatePropFindAllProp();
                response = client.PropFindAsync(testCollectionDestination, WebDavDepthHeaderValue.Infinity, pf).Result;
                var propFindResponseSuccess = response.IsSuccessStatusCode;

                var multistatus = (Multistatus)WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content).Result;

                bool collectionfound = false;

                foreach (var item in multistatus.Response)
                {
                    if (item.Href.EndsWith(TestFile))
                    {
                        collectionfound = true;
                        break;
                    }
                }

                // Delete source and destination.
                response = client.DeleteAsync(testCollectionSource).Result;
                var deleteSourceResponseSuccess = response.IsSuccessStatusCode;

                response = client.DeleteAsync(testCollectionDestination).Result;
                var deleteDestinationResponseSuccess = response.IsSuccessStatusCode;

                Assert.IsTrue(mkColResponseSuccess);
                Assert.IsTrue(putResponseSuccess);
                Assert.IsTrue(copyResponseSuccess);
                Assert.IsTrue(propFindResponseSuccess);
                Assert.IsTrue(collectionfound);
                Assert.IsTrue(deleteSourceResponseSuccess);
                Assert.IsTrue(deleteDestinationResponseSuccess);
            }
        }
Пример #4
0
        public void UIT_WebDavClient_Move()
        {
            var client = CreateWebDavClientWithDebugHttpMessageHandler();
            var testCollectionSource      = UriHelper.CombineUrl(this.webDavRootFolder, TestCollection, true);
            var testCollectionDestination = UriHelper.CombineUrl(this.webDavRootFolder, TestCollection + "2", true);
            var testFile = UriHelper.CombineUrl(testCollectionSource, TestFile, true);

            // Create source collection.
            var response             = client.MkcolAsync(testCollectionSource).Result;
            var mkColResponseSuccess = response.IsSuccessStatusCode;

            // Put file.
            var content = new StreamContent(File.OpenRead(TestFile));

            response = client.PutAsync(testFile, content).Result;
            var putResponseSuccess = response.IsSuccessStatusCode;

            // Move.
            response = client.MoveAsync(testCollectionSource, testCollectionDestination).Result;
            var moveResponseSuccess = response.IsSuccessStatusCode;

            // PropFind.
            PropFind pf = PropFind.CreatePropFindAllProp();

            response = client.PropFindAsync(this.webDavRootFolder, WebDavDepthHeaderValue.Infinity, pf).Result;
            var propFindResponseSuccess = response.IsSuccessStatusCode;

            var multistatus = (Multistatus)WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content).Result;

            bool foundCollection1 = false;
            bool foundCollection2 = false;

            foreach (var item in multistatus.Response)
            {
                if (item.Href.EndsWith(TestCollection + "/"))
                {
                    foundCollection1 = true;
                }

                if (item.Href.EndsWith(TestCollection + "2/"))
                {
                    foundCollection2 = true;
                }
            }

            // Delete source and destination.
            // Delete file.
            response = client.DeleteAsync(testCollectionDestination).Result;
            var deleteResponseSuccess = response.IsSuccessStatusCode;

            Assert.IsTrue(mkColResponseSuccess);
            Assert.IsTrue(putResponseSuccess);
            Assert.IsTrue(moveResponseSuccess);
            Assert.IsTrue(propFindResponseSuccess);
            Assert.IsFalse(foundCollection1);
            Assert.IsTrue(foundCollection2);
            Assert.IsTrue(deleteResponseSuccess);
        }
Пример #5
0
        public void UT_WebDavHelper_GetUtf8EncodedXmlWebDavRequestStringFromPropWithXmlLangAttribute()
        {
            var serializer = new XmlSerializer(typeof(PropFind));
            var propFind   = PropFind.CreatePropFindAllProp();
            var str        = WebDavHelper.GetUtf8EncodedXmlWebDavRequestString(serializer, propFind);
            var expected   = "<?xml version=\"1.0\" encoding=\"utf-8\"?><D:propfind xmlns:D=\"DAV:\"><D:allprop /></D:propfind>";

            Assert.AreEqual(expected, str);
        }
Пример #6
0
        public void UIT_WebDavClient_PropPatch()
        {
            var client   = CreateWebDavClientWithDebugHttpMessageHandler();
            var testFile = UriHelper.CombineUrl(this.webDavRootFolder, TestFile, true);

            // Put file.
            var content            = new StreamContent(File.OpenRead(TestFile));
            var response           = client.PutAsync(testFile, content).Result;
            var putResponseSuccess = response.IsSuccessStatusCode;

            // PropPatch (set).
            var propertyUpdate = new PropertyUpdate();
            var set            = new Set();
            var prop           = new Prop();

            prop.DisplayName     = "TestFileDisplayName";
            set.Prop             = prop;
            propertyUpdate.Items = new object[] { set };
            response             = client.PropPatchAsync(testFile, propertyUpdate).Result;
            var propPatchResponseSuccess = response.IsSuccessStatusCode;

            // PropFind.
            PropFind pf = PropFind.CreatePropFindWithEmptyProperties("displayname");

            response = client.PropFindAsync(testFile, WebDavDepthHeaderValue.Zero, pf).Result;
            var propFindResponseSuccess = response.IsSuccessStatusCode;
            var multistatus             = (Multistatus)WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content).Result;
            var displayName             = ((Propstat)multistatus.Response[0].Items[0]).Prop.DisplayName;
            // IIS ignores display name and always puts the file name as display name.
            var displayNameResult = "TestFileDisplayName" == displayName || TestFile == displayName;

            // PropPatch (remove).
            propertyUpdate = new PropertyUpdate();
            var remove = new Remove();

            prop                 = Prop.CreatePropWithEmptyProperties("displayname");
            remove.Prop          = prop;
            propertyUpdate.Items = new object[] { remove };
            response             = client.PropPatchAsync(testFile, propertyUpdate).Result;
            var propPatchRemoveResponseSuccess = response.IsSuccessStatusCode;

            multistatus = (Multistatus)WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content).Result;
            var multistatusResult = ((Propstat)multistatus.Response[0].Items[0]).Prop.DisplayName;

            // Delete file.
            response = client.DeleteAsync(testFile).Result;
            var deleteResponseSuccess = response.IsSuccessStatusCode;

            Assert.IsTrue(putResponseSuccess);
            Assert.IsTrue(propPatchResponseSuccess);
            Assert.IsTrue(propFindResponseSuccess);
            Assert.IsTrue(displayNameResult);
            Assert.IsTrue(propPatchRemoveResponseSuccess);
            Assert.AreEqual(string.Empty, multistatusResult);
            Assert.IsTrue(deleteResponseSuccess);
        }
        public async Task UIT_WebDavSession_UpdateItem()
        {
            // This won't work on IIS because on IIS the 'Name' is always the same as 'DisplayName'.
            // As the unit integration tests of this library are also run against ownCloud/Nextcloud on a regular basis, just skip this test for IIS.
            if (!(webDavRootFolder.Contains("nextcloud") || webDavRootFolder.Contains("owncloud")))
            {
                return;
            }

            using (var session = CreateWebDavSession())
            {
                session.BaseUrl = webDavRootFolder;
                // We need an "extended" Propfind in order to get the 'DisplayName' in the ListAsync response.
                var propFind = PropFind.CreatePropFindWithEmptyPropertiesAll();

                // Upload file.
                var responseUpload = false;

                using (var fileStream = File.OpenRead(TestFile))
                {
                    responseUpload = await session.UploadFileAsync(TestFile, fileStream);
                }

                var list = await session.ListAsync("/", propFind);

                Assert.AreEqual(1, list.Count);
                Assert.AreEqual(TestFile, list[0].Name);
                Assert.IsNull(list[0].DisplayName);

                // Proppatch set (DisplayName).
                var webDavSessionItem = list[0];
                webDavSessionItem.DisplayName = "ChangedDisplayName";
                var proppatchResult = await session.UpdateItemAsync(webDavSessionItem);

                list = await session.ListAsync("/", propFind);

                Assert.AreEqual(1, list.Count);
                Assert.AreEqual("ChangedDisplayName", list[0].DisplayName);

                // Proppatch remove (DisplayName).
                webDavSessionItem             = list[0];
                webDavSessionItem.DisplayName = null;
                proppatchResult = await session.UpdateItemAsync(webDavSessionItem);

                list = await session.ListAsync("/", propFind);

                Assert.AreEqual(1, list.Count);
                Assert.IsNull(list[0].DisplayName);

                // Delete file
                var delete = await session.DeleteAsync(TestFile);

                Assert.IsTrue(responseUpload);
                Assert.IsTrue(delete);
            }
        }
Пример #8
0
        public void UIT_WebDavClient_PropFind_PropName()
        {
            var      client   = CreateWebDavClientWithDebugHttpMessageHandler();
            PropFind pf       = PropFind.CreatePropFindWithPropName();
            var      response = client.PropFindAsync(this.webDavRootFolder, WebDavDepthHeaderValue.Infinity, pf).Result;
            var      propFindResponseSuccess = response.IsSuccessStatusCode;
            var      multistatus             = WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content).Result;

            Assert.IsTrue(propFindResponseSuccess);
            Assert.IsNotNull(multistatus);
        }
        public void UIT_WebDavClient_PropFind_AllPropDepthZero()
        {
            using (var client = CreateWebDavClientWithDebugHttpMessageHandler())
            {
                PropFind pf       = PropFind.CreatePropFindAllProp();
                var      response = client.PropFindAsync(webDavRootFolder, WebDavDepthHeaderValue.Zero, pf).Result;
                var      propFindResponseSuccess = response.IsSuccessStatusCode;
                var      multistatus             = WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content).Result;

                Assert.IsTrue(propFindResponseSuccess);
                Assert.IsNotNull(multistatus);
            }
        }
        public async Task UIT_WebDavClient_PropName()
        {
            using (var client = CreateWebDavClientWithDebugHttpMessageHandler())
            {
                PropFind pf       = PropFind.CreatePropFindWithPropName();
                var      response = await client.PropFindAsync(webDavRootFolder, WebDavDepthHeaderValue.Infinity, pf);

                var propFindResponseSuccess = response.IsSuccessStatusCode;
                var multistatus             = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                Assert.IsTrue(propFindResponseSuccess);
                Assert.IsNotNull(multistatus);
            }
        }
        public async Task UIT_WebDavClient_Mkcol()
        {
            using (var client = CreateWebDavClientWithDebugHttpMessageHandler())
            {
                var testCollection = UriHelper.CombineUrl(webDavRootFolder, TestCollection, true);

                // Create collection.
                var response = await client.MkcolAsync(testCollection);

                var mkColResponseSuccess = response.IsSuccessStatusCode;

                // PropFind.
                PropFind pf = PropFind.CreatePropFindAllProp();
                response = await client.PropFindAsync(webDavRootFolder, WebDavDepthHeaderValue.Infinity, pf);

                var propFindResponseSuccess = response.IsSuccessStatusCode;

                var multistatus = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                bool collectionFound = false;

                foreach (var item in multistatus.Response)
                {
                    if (item.Href.EndsWith(TestCollection + "/"))
                    {
                        collectionFound = true;
                        break;
                    }
                }

                // Delete collection.
                response = await client.DeleteAsync(testCollection);

                var deleteResponseSuccess = response.IsSuccessStatusCode;

                Assert.IsTrue(mkColResponseSuccess);
                Assert.IsTrue(propFindResponseSuccess);
                Assert.IsTrue(collectionFound);
                Assert.IsTrue(deleteResponseSuccess);
            }
        }
Пример #12
0
        public async Task <ResourceLoadStatus> FetchChildResourcesAsync(ResourceItem parent, CancellationToken cancellationToken, int maxLevel, int level = 0)
        {
            if (cancellationToken.IsCancellationRequested)
            {
                return(ResourceLoadStatus.OperationCanceled);
            }

            if (level > maxLevel)
            {
                return(ResourceLoadStatus.OperationCanceled);
            }

            var propfind = PropFind.CreatePropFindWithEmptyProperties(
                PropNameConstants.Name,
                PropNameConstants.DisplayName,
                PropNameConstants.IsCollection,
                PropNameConstants.ResourceType,
                PropNameConstants.GetContentLength
                );

            Debug.WriteLine("path=[" + parent.FullPath + "], level = [" + level + "] " + "ListAsync start : " + DateTime.UtcNow);
            IList <WebDavSessionListItem> result;

            try
            {
                result = await _session.ListAsync(parent.FullPath, propfind); // .TimeoutAfter(TimeSpan.FromSeconds(1), cancellationToken);
            }
            catch (OperationCanceledException)
            {
                return(ResourceLoadStatus.OperationCanceled);
            }
            catch (TimeoutException)
            {
                return(ResourceLoadStatus.OperationCanceled);
            }
            Debug.WriteLine("path=[" + parent.FullPath + "], level = [" + level + "] " + "ListAsync   end : " + DateTime.UtcNow);

            if (result != null)
            {
                var tasks = result
                            .Where(r => IsAudioFile(r) || IsFolder(r))
                            .Select(async r =>
                {
                    //Debug.WriteLine("WebDavSessionListItem = " + JsonConvert.SerializeObject(r, Formatting.Indented));

                    var resourceItem = new ResourceItem
                    {
                        Level         = level,
                        DisplayName   = r.DisplayName,
                        IsCollection  = r.IsCollection,
                        FullPath      = r.Uri,
                        ContentLength = r.ContentLength,
                        Parent        = parent
                    };

                    if (r.IsCollection && level < maxLevel)
                    {
                        await FetchChildResourcesAsync(resourceItem, cancellationToken, maxLevel, level + 1);
                    }

                    return(resourceItem);
                });

                var items = await Task.WhenAll(tasks);

                parent.Items = items.OrderBy(r => r.DisplayName).ToList();
                return(ResourceLoadStatus.Ok);
            }

            return(ResourceLoadStatus.NoResourcesFound);
        }
Пример #13
0
        /// <summary>
        /// Retrieves a list of files and directories of the directory at the <see cref="Uri"/> specified using the <see cref="PropFind"/> specified.
        /// </summary>
        /// <param name="uri">The <see cref="Uri"/> of the directory which content should be listed. Has to be an absolute URI (including the base URI) or a relative URI (relative to base URI).</param>
        /// <param name="propFind">The <see cref="PropFind"/> to use. Different PropFind  types can be created using the static methods of the class <see cref="PropFind"/>.</param>
        /// <returns>The <see cref="Task"/> representing the asynchronous operation.</returns>
        public async Task <IList <WebDavSessionListItem> > ListAsync(Uri uri, PropFind propFind)
        {
            if (propFind == null)
            {
                throw new ArgumentException("Argument propFind must not be null.");
            }

            uri = UriHelper.GetCombinedUriWithTrailingSlash(this.BaseUri, uri, true, false);
            var response = await this.webDavClient.PropFindAsync(uri, WebDavDepthHeaderValue.One, propFind);

            // Remember the original port to include it in the hrefs later.
            var port = UriHelper.GetPort(uri);

            if (response.StatusCode != WebDavStatusCode.MultiStatus)
            {
                throw new WebDavException(string.Format("Error while executing ListAsync (wrong response status code). Expected status code: 207 (MultiStatus); actual status code: {0} ({1})", (int)response.StatusCode, response.StatusCode));
            }

            var multistatus = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

            var itemList = new List <WebDavSessionListItem>();

            foreach (var responseItem in multistatus.Response)
            {
                var webDavSessionItem = new WebDavSessionListItem();

                Uri href = null;

                if (!string.IsNullOrEmpty(responseItem.Href))
                {
                    if (Uri.TryCreate(responseItem.Href, UriKind.RelativeOrAbsolute, out href))
                    {
                        var fullQualifiedUri = UriHelper.CombineUri(uri, href, true);
                        fullQualifiedUri      = UriHelper.SetPort(fullQualifiedUri, port);
                        webDavSessionItem.Uri = fullQualifiedUri;
                    }
                }

                // Skip the folder which contents were requested, only add children.
                if (href != null && WebUtility.UrlDecode(UriHelper.RemovePort(uri).ToString().Trim('/')).EndsWith(WebUtility.UrlDecode(UriHelper.RemovePort(href).ToString().Trim('/')), StringComparison.OrdinalIgnoreCase))
                {
                    continue;
                }

                foreach (var item in responseItem.Items)
                {
                    var propStat = item as Propstat;

                    // Do not items where no properties could be found.
                    if (propStat == null || propStat.Status.ToLower().Contains("404 not found"))
                    {
                        continue;
                    }

                    // Do not add hidden items.
                    if (!string.IsNullOrEmpty(propStat.Prop.IsHidden) && propStat.Prop.IsHidden.Equals("1"))
                    {
                        continue;
                    }

                    webDavSessionItem.ContentClass    = propStat.Prop.ContentClass;
                    webDavSessionItem.ContentLanguage = propStat.Prop.GetContentLanguage;

                    if (!string.IsNullOrEmpty(propStat.Prop.GetContentLength))
                    {
                        webDavSessionItem.ContentLength = long.Parse(propStat.Prop.GetContentLength, CultureInfo.InvariantCulture);
                    }

                    webDavSessionItem.ContentType = propStat.Prop.GetContentType;

                    if (propStat.Prop.CreationDateSpecified && !string.IsNullOrEmpty(propStat.Prop.CreationDate))
                    {
                        webDavSessionItem.CreationDate = DateTime.Parse(propStat.Prop.CreationDate, CultureInfo.InvariantCulture);
                    }

                    webDavSessionItem.DefaultDocument = propStat.Prop.DefaultDocument;
                    webDavSessionItem.DisplayName     = propStat.Prop.DisplayName;
                    webDavSessionItem.ETag            = propStat.Prop.GetEtag;

                    if (!string.IsNullOrEmpty(propStat.Prop.GetLastModified))
                    {
                        webDavSessionItem.LastModified = DateTime.Parse(propStat.Prop.GetLastModified, CultureInfo.InvariantCulture);
                    }

                    if (!string.IsNullOrEmpty(propStat.Prop.IsReadonly))
                    {
                        webDavSessionItem.IsReadonly = propStat.Prop.IsReadonly.Equals("1");
                    }

                    if (!string.IsNullOrEmpty(propStat.Prop.IsRoot))
                    {
                        webDavSessionItem.IsRoot = propStat.Prop.IsRoot.Equals("1");
                    }

                    if (!string.IsNullOrEmpty(propStat.Prop.IsStructuredDocument))
                    {
                        webDavSessionItem.IsStructuredDocument = propStat.Prop.IsStructuredDocument.Equals("1");
                    }

                    if (!string.IsNullOrEmpty(propStat.Prop.LastAccessed))
                    {
                        webDavSessionItem.LastAccessed = DateTime.Parse(propStat.Prop.LastAccessed, CultureInfo.InvariantCulture);
                    }

                    webDavSessionItem.Name       = propStat.Prop.Name;
                    webDavSessionItem.ParentName = propStat.Prop.ParentName;

                    if (!string.IsNullOrEmpty(propStat.Prop.QuotaAvailableBytes))
                    {
                        webDavSessionItem.QuotaAvailableBytes = long.Parse(propStat.Prop.QuotaAvailableBytes, CultureInfo.InvariantCulture);
                    }

                    if (!string.IsNullOrEmpty(propStat.Prop.QuotaUsedBytes))
                    {
                        webDavSessionItem.QuotaUsedBytes = long.Parse(propStat.Prop.QuotaUsedBytes, CultureInfo.InvariantCulture);
                    }

                    // Make sure that the IsDirectory property is set if it's a directory.
                    if (!string.IsNullOrEmpty(propStat.Prop.IsCollection))
                    {
                        webDavSessionItem.IsCollection = propStat.Prop.IsCollection.Equals("1");
                    }
                    else if (propStat.Prop.ResourceType != null && propStat.Prop.ResourceType.Collection != null)
                    {
                        webDavSessionItem.IsCollection = true;
                    }

                    // Make sure that the name property is set.
                    // Naming priority:
                    // 1. displayname (only if it doesn't contain raw unicode, otherwise there are problems with non western characters)
                    // 2. name
                    // 3. (part of) URI.
                    if (!TextHelper.StringContainsRawUnicode(propStat.Prop.DisplayName))
                    {
                        webDavSessionItem.Name = propStat.Prop.DisplayName;
                    }

                    if (string.IsNullOrEmpty(webDavSessionItem.Name))
                    {
                        webDavSessionItem.Name = propStat.Prop.Name;
                    }

                    if (string.IsNullOrEmpty(webDavSessionItem.Name) && href != null)
                    {
                        webDavSessionItem.Name = WebUtility.UrlDecode(href.ToString().Split('/').Last(x => !string.IsNullOrEmpty(x)));
                    }
                }

                itemList.Add(webDavSessionItem);
            }

            return(itemList);
        }
Пример #14
0
 /// <summary>
 /// Retrieves a list of files and directories of the directory at the URL specified.
 /// </summary>
 /// <param name="url">The URL of the directory which content should be listed. Has to be an absolute URL (including the base URL) or a relative URL (relative to base URL).</param>
 /// <param name="propFind">The <see cref="PropFind"/> to use. Different PropFind  types can be created using the static methods of the class <see cref="PropFind"/>.</param>
 /// <returns>The <see cref="Task"/> representing the asynchronous operation.</returns>
 public async Task <IList <WebDavSessionListItem> > ListAsync(string url, PropFind propFind)
 {
     return(await ListAsync(new Uri(url, UriKind.RelativeOrAbsolute), propFind));
 }
        public async Task UIT_WebDavClient_Move_Rename()
        {
            using (var client = CreateWebDavClientWithDebugHttpMessageHandler())
            {
                var testCollectionSource = UriHelper.CombineUrl(webDavRootFolder, TestCollection, true);
                var testFileToRename     = UriHelper.CombineUrl(testCollectionSource, TestFile, true);
                var testFileRenamed      = UriHelper.CombineUrl(testCollectionSource, "RenamedFile", true);

                // Create source collection.
                var response = await client.MkcolAsync(testCollectionSource);

                var mkColResponseSuccess = response.IsSuccessStatusCode;

                // Put file.
                using (var fileStream = File.OpenRead(TestFile))
                {
                    var content = new StreamContent(fileStream);
                    response = await client.PutAsync(testFileToRename, content);
                }

                var putResponseSuccess = response.IsSuccessStatusCode;

                // Move.
                response = await client.MoveAsync(testFileToRename, testFileRenamed);

                var moveResponseSuccess = response.IsSuccessStatusCode;

                // PropFind.
                PropFind pf = PropFind.CreatePropFindAllProp();
                response = await client.PropFindAsync(webDavRootFolder, WebDavDepthHeaderValue.Infinity, pf);

                var propFindResponseSuccess = response.IsSuccessStatusCode;

                var multistatus = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                bool foundRenamedFile = false;
                bool foundFile        = false;

                foreach (var item in multistatus.Response)
                {
                    if (item.Href.EndsWith("RenamedFile"))
                    {
                        foundRenamedFile = true;
                    }

                    if (item.Href.EndsWith(TestFile))
                    {
                        foundFile = true;
                    }
                }

                // Delete source and destination.
                // Delete file.
                response = await client.DeleteAsync(testCollectionSource);

                var deleteResponseSuccess = response.IsSuccessStatusCode;

                Assert.IsTrue(mkColResponseSuccess);
                Assert.IsTrue(putResponseSuccess);
                Assert.IsTrue(moveResponseSuccess);
                Assert.IsTrue(propFindResponseSuccess);
                Assert.IsTrue(foundRenamedFile);
                Assert.IsFalse(foundFile);
                Assert.IsTrue(deleteResponseSuccess);
            }
        }
        public async Task UIT_WebDavClient_PropPatch()
        {
            using (var client = CreateWebDavClientWithDebugHttpMessageHandler())
            {
                var testFile           = UriHelper.CombineUrl(webDavRootFolder, TestFile, true);
                var putResponseSuccess = false;

                // Put file.
                using (var fileStream = File.OpenRead(TestFile))
                {
                    var content     = new StreamContent(fileStream);
                    var responsePut = await client.PutAsync(testFile, content);

                    putResponseSuccess = responsePut.IsSuccessStatusCode;
                }

                // PropPatch (set).
                var propertyUpdate = new PropertyUpdate();
                var set            = new Set();

                var prop = new Prop()
                {
                    DisplayName = "TestFileDisplayName"
                };

                set.Prop             = prop;
                propertyUpdate.Items = new object[] { set };
                var response = await client.PropPatchAsync(testFile, propertyUpdate);

                var multistatusPropPatchSet = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                var propPatchResponseSuccess = response.IsSuccessStatusCode;

                // PropFind.
                PropFind pf = PropFind.CreatePropFindWithEmptyProperties(PropNameConstants.DisplayName);
                response = await client.PropFindAsync(testFile, WebDavDepthHeaderValue.Zero, pf);

                var propFindResponseSuccess = response.IsSuccessStatusCode;
                var multistatusPropFind     = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                var displayName = ((Propstat)multistatusPropFind.Response[0].Items[0]).Prop.DisplayName;
                // IIS ignores display name and always puts the file name as display name.
                var displayNameResult = "TestFileDisplayName" == displayName || TestFile == displayName;

                // PropPatch (remove).
                propertyUpdate = new PropertyUpdate();
                var remove = new Remove();
                prop                 = Prop.CreatePropWithEmptyProperties(PropNameConstants.DisplayName);
                remove.Prop          = prop;
                propertyUpdate.Items = new object[] { remove };
                response             = await client.PropPatchAsync(testFile, propertyUpdate);

                var propPatchRemoveResponseSuccess = response.IsSuccessStatusCode;
                multistatusPropFind = await WebDavResponseContentParser.ParseMultistatusResponseContentAsync(response.Content);

                var multistatusPropFindResult = string.IsNullOrEmpty(((Propstat)multistatusPropFind.Response[0].Items[0]).Prop.DisplayName);

                // Delete file.
                response = await client.DeleteAsync(testFile);

                var deleteResponseSuccess = response.IsSuccessStatusCode;

                Assert.IsTrue(putResponseSuccess);
                Assert.IsNotNull(multistatusPropPatchSet);
                Assert.IsTrue(propPatchResponseSuccess);
                Assert.IsTrue(propFindResponseSuccess);
                Assert.IsTrue(displayNameResult);
                Assert.IsTrue(propPatchRemoveResponseSuccess);
                Assert.IsTrue(multistatusPropFindResult);
                Assert.IsTrue(deleteResponseSuccess);
            }
        }
        public async Task UIT_WebDavSession_UpdateItem_WithUnknowProperty()
        {
            // This won't work on IIS because on IIS the 'Name' is always the same as 'DisplayName'.
            // As the unit integration tests of this library are also run against ownCloud/Nextcloud on a regular basis, just skip this test for IIS.
            if (!(webDavRootFolder.Contains("nextcloud") || webDavRootFolder.Contains("owncloud")))
            {
                return;
            }

            using (var session = CreateWebDavSession())
            {
                session.BaseUrl = webDavRootFolder;
                var propFind = PropFind.CreatePropFindWithEmptyPropertiesAll();

                // Add unknown property to Prop.
                // The additional property is taken from https://docs.nextcloud.com/server/12/developer_manual/client_apis/WebDAV/index.html (mark item as favorite)
                // As the additional item is part of another namespace than "DAV:", the key to access this item is a complete XElement (with namespace and name).
                XNamespace ns       = "http://owncloud.org/ns";
                var        xElement = new XElement(ns + "favorite");
                var        prop     = (Prop)propFind.Item;

                var xElementList = new List <XElement>
                {
                    xElement
                };

                prop.AdditionalProperties = xElementList.ToArray();

                // Upload file.
                var responseUpload = false;

                using (var fileStream = File.OpenRead(TestFile))
                {
                    responseUpload = await session.UploadFileAsync(TestFile, fileStream);
                }

                var list = await session.ListAsync("/", propFind);

                // Get unknown property.
                var xName = XName.Get("favorite", "http://owncloud.org/ns");
                var file  = list.Where(x => x.Name == TestFile);

                var favoriteItem = file.First().AdditionalProperties["favorite"];
                Assert.IsNotNull(favoriteItem);
                Assert.AreEqual("", favoriteItem);
                Assert.AreEqual(1, list.Count);
                Assert.AreEqual(TestFile, list[0].Name);

                // Proppatch set (favorite).
                var webDavSessionItem = list[0];
                webDavSessionItem.AdditionalProperties["favorite"] = "1";
                var proppatchResult = await session.UpdateItemAsync(webDavSessionItem);

                list = await session.ListAsync("/", propFind);

                Assert.AreEqual(1, list.Count);
                Assert.AreEqual("1", list[0].AdditionalProperties["favorite"]);

                // Proppatch remove (DisplayName).
                webDavSessionItem = list[0];
                webDavSessionItem.AdditionalProperties["favorite"] = null;
                proppatchResult = await session.UpdateItemAsync(webDavSessionItem);

                list = await session.ListAsync("/", propFind);

                file         = list.Where(x => x.Name == TestFile);
                favoriteItem = file.First().AdditionalProperties["favorite"];
                Assert.IsNotNull(favoriteItem);
                Assert.AreEqual("", favoriteItem);
                Assert.AreEqual(1, list.Count);

                // Delete file
                var delete = await session.DeleteAsync(TestFile);

                Assert.IsTrue(responseUpload);
                Assert.IsTrue(delete);
            }
        }
Пример #18
0
 /// <summary>
 /// Retrieves a list of files and directories of the directory at the <see cref="Uri"/> specified (using 'allprop').
 /// </summary>
 /// <param name="uri">The <see cref="Uri"/> of the directory which content should be listed. Has to be an absolute URI (including the base URI) or a relative URI (relative to base URI).</param>
 /// <returns>The <see cref="Task"/> representing the asynchronous operation.</returns>
 /// <remarks>This method uses a so called 'allprop'. A server should return all known properties to the server.
 /// If not all of the expected properties are return by the server, use an overload of this method specifying a <see cref="PropFind"/> explicitly.</remarks>
 public async Task <IList <WebDavSessionListItem> > ListAsync(Uri uri)
 {
     return(await ListAsync(uri, PropFind.CreatePropFindAllProp()));
 }