/// <summary>
        /// Rename a file.  Note that this only works for files with relatively short names due to the max URL length.  It may be possible to allow that to work by using @variables in the URL.
        /// </summary>
        /// <param name="url"></param>
        /// <returns></returns>
        public async Task <bool> RenameFile(string oldServerRelativeUrl, string newServerRelativeUrl)
        {
            bool               result          = false;
            string             url             = $"{ApiEndpoint}web/GetFileByServerRelativeUrl('{EscapeApostrophe(oldServerRelativeUrl)}')/moveto(newurl='{EscapeApostrophe(newServerRelativeUrl)}', flags=1)";
            HttpRequestMessage endpointRequest = new HttpRequestMessage(HttpMethod.Post, url);


            // make the request.
            var response = await _Client.SendAsync(endpointRequest);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                result = true;
            }
            else
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", response.StatusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);
                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }

            return(result);
        }
Exemplo n.º 2
0
        /// <summary>
        /// Create Folder
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task CreateFolder(string listTitle, string folderName)
        {
            // return early if SharePoint is disabled.
            if (!IsValid())
            {
                return;
            }

            folderName = FixFoldername(folderName);

            string relativeUrl = EscapeApostrophe($"/{listTitle}/{folderName}");

            HttpRequestMessage endpointRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(ApiEndpoint + $"web/folders/add('{relativeUrl}')"),
                Headers    =
                {
                    { "Accept", "application/json" }
                }
            };

            //string jsonString = "{ '__metadata': { 'type': 'SP.Folder' }, 'ServerRelativeUrl': '" + relativeUrl + "'}";

            StringContent strContent = new StringContent("", Encoding.UTF8);

            strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");

            endpointRequest.Content = strContent;

            // make the request.

            var response = await _Client.SendAsync(endpointRequest);

            HttpStatusCode _statusCode = response.StatusCode;

            // check to see if the folder creation worked.
            if (!(_statusCode == HttpStatusCode.OK || _statusCode == HttpStatusCode.Created))
            {
                string _responseContent;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }
            else
            {
                string jsonString = await response.Content.ReadAsStringAsync();
            }
        }
        public async Task <bool> DeleteFolder(string listTitle, string folderName)
        {
            // return early if SharePoint is disabled.
            if (!IsValid())
            {
                return(false);
            }

            bool result = false;
            // Delete is very similar to a GET.
            string serverRelativeUrl = "";

            if (!string.IsNullOrEmpty(WebName))
            {
                serverRelativeUrl += $"{WebName}/";
            }

            serverRelativeUrl += Uri.EscapeUriString(listTitle) + "/" + Uri.EscapeUriString(folderName);

            HttpRequestMessage endpointRequest =
                new HttpRequestMessage(HttpMethod.Post, ApiEndpoint + "web/getFolderByServerRelativeUrl('" + EscapeApostrophe(serverRelativeUrl) + "')");


            // We want to delete this folder.
            endpointRequest.Headers.Add("IF-MATCH", "*");
            endpointRequest.Headers.Add("X-HTTP-Method", "DELETE");

            // make the request.
            var response = await client.SendAsync(endpointRequest);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                result = true;
            }
            else
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", response.StatusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }

            return(result);
        }
Exemplo n.º 4
0
        /// <summary>
        /// Upload a file
        /// </summary>
        /// <param name="fileName"></param>
        /// <param name="listTitle"></param>
        /// <param name="folderName"></param>
        /// <param name="fileData"></param>
        /// <param name="contentType"></param>
        /// <returns>Uploaded Filename, or Null if not successful.</returns>
        public async Task <string> UploadFile(string fileName, string listTitle, string folderName, byte[] data, string contentType)
        {
            string result = null;

            if (IsValid())
            {
                folderName = FixFoldername(folderName);
                fileName   = GetTruncatedFileName(fileName, listTitle, folderName);

                string serverRelativeUrl = GetServerRelativeURL(listTitle, folderName);
                string requestUriString  = GenerateUploadRequestUriString(serverRelativeUrl, fileName);

                HttpRequestMessage endpointRequest = new HttpRequestMessage
                {
                    Method     = HttpMethod.Post,
                    RequestUri = new Uri(requestUriString),
                    Headers    =
                    {
                        { "Accept", "application/json" }
                    }
                };

                ByteArrayContent byteArrayContent = new ByteArrayContent(data);
                byteArrayContent.Headers.Add(@"content-length", data.Length.ToString());
                endpointRequest.Content = byteArrayContent;

                // make the request.
                var response = await _Client.SendAsync(endpointRequest);

                if (response.StatusCode == HttpStatusCode.OK)
                {
                    result = fileName;
                }
                else
                {
                    string _responseContent = null;
                    var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", response.StatusCode));
                    _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                    ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                    ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                    endpointRequest.Dispose();
                    if (response != null)
                    {
                        response.Dispose();
                    }
                    throw ex;
                }
            }
            return(result);
        }
Exemplo n.º 5
0
        public async Task <Object> UpdateDocumentLibrary(string listTitle)
        {
            // return early if SharePoint is disabled.
            if (!IsValid())
            {
                return(null);
            }

            HttpRequestMessage endpointRequest =
                new HttpRequestMessage(HttpMethod.Put, $"{ApiEndpoint}web/Lists");


            var library = CreateNewDocumentLibraryRequest(listTitle);


            string        jsonString = JsonConvert.SerializeObject(library);
            StringContent strContent = new StringContent(jsonString, Encoding.UTF8);

            strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            endpointRequest.Content        = strContent;

            // make the request.
            var response = await _Client.SendAsync(endpointRequest);

            HttpStatusCode _statusCode = response.StatusCode;

            if (_statusCode != HttpStatusCode.Created)
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }
            else
            {
                jsonString = await response.Content.ReadAsStringAsync();
            }

            return(library);
        }
        /// <summary>
        /// Upload a file
        /// </summary>
        /// <param name="name"></param>
        /// <param name="listTitle"></param>
        /// <param name="folderName"></param>
        /// <param name="fileData"></param>
        /// <param name="contentType"></param>
        /// <returns></returns>
        public async Task <bool> UploadFile(string name, string listTitle, string folderName, Stream fileData, string contentType)
        {
            if (!IsValid())
            {
                return(false);
            }
            bool result = false;

            // Delete is very similar to a GET.
            string serverRelativeUrl = GetServerRelativeURL(listTitle, folderName);

            HttpRequestMessage endpointRequest =
                new HttpRequestMessage(HttpMethod.Post, ApiEndpoint + "web/getFolderByServerRelativeUrl('" + EscapeApostrophe(serverRelativeUrl) + "')/Files/add(url='"
                                       + EscapeApostrophe(name) + "',overwrite=true)");
            // convert the stream into a byte array.
            MemoryStream ms = new MemoryStream();

            fileData.CopyTo(ms);
            Byte[]           data             = ms.ToArray();
            ByteArrayContent byteArrayContent = new ByteArrayContent(data);

            byteArrayContent.Headers.Add(@"content-length", data.Length.ToString());
            endpointRequest.Content = byteArrayContent;

            // make the request.
            var response = await client.SendAsync(endpointRequest);

            if (response.StatusCode == HttpStatusCode.OK)
            {
                result = true;
            }
            else
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", response.StatusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }
            return(result);
        }
Exemplo n.º 7
0
        public async Task <bool> DeleteFile(string serverRelativeUrl)
        {
            bool result = false;
            // Delete is very similar to a GET.

            HttpRequestMessage endpointRequest = new HttpRequestMessage
            {
                Method     = HttpMethod.Delete,
                RequestUri = new Uri(ApiEndpoint + "web/GetFileByServerRelativeUrl('" + EscapeApostrophe(serverRelativeUrl) + "')"),
                Headers    =
                {
                    { "Accept", "application/json" }
                }
            };

            // We want to delete this file.
            endpointRequest.Headers.Add("IF-MATCH", "*");
            endpointRequest.Headers.Add("X-HTTP-Method", "DELETE");

            // make the request.
            var response = await _Client.SendAsync(endpointRequest);

            if (response.StatusCode == HttpStatusCode.NoContent)
            {
                result = true;
            }
            else
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", response.StatusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }

            return(result);
        }
        /// <summary>
        /// Create Folder
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task <Object> CreateFolder(string listTitle, string folderName)
        {
            HttpRequestMessage endpointRequest =
                new HttpRequestMessage(HttpMethod.Post, ApiEndpoint + "web/folders");


            var folder = CreateNewFolderRequest($"{WebName}/{listTitle}/{folderName}");


            string        jsonString = JsonConvert.SerializeObject(folder);
            StringContent strContent = new StringContent(jsonString, Encoding.UTF8);

            strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            endpointRequest.Content        = strContent;

            // make the request.
            var response = await client.SendAsync(endpointRequest);

            HttpStatusCode _statusCode = response.StatusCode;

            if (_statusCode != HttpStatusCode.Created)
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }
            else
            {
                jsonString = await response.Content.ReadAsStringAsync();
            }

            return(folder);
        }
Exemplo n.º 9
0
        /// <summary>
        /// Create Folder
        /// </summary>
        /// <param name="name"></param>
        /// <returns></returns>
        public async Task <Object> CreateDocumentLibrary(string listTitle, string documentTemplateUrlTitle = null)
        {
            // return early if SharePoint is disabled.
            if (!IsValid())
            {
                return(null);
            }

            HttpRequestMessage endpointRequest =
                new HttpRequestMessage(HttpMethod.Post, ApiEndpoint + "web/Lists");

            if (string.IsNullOrEmpty(documentTemplateUrlTitle))
            {
                documentTemplateUrlTitle = listTitle;
            }
            var library = CreateNewDocumentLibraryRequest(documentTemplateUrlTitle);


            string        jsonString = JsonConvert.SerializeObject(library);
            StringContent strContent = new StringContent(jsonString, Encoding.UTF8);

            strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
            endpointRequest.Content        = strContent;
            // fix for bad request
            endpointRequest.Headers.Add("odata-version", "3.0");

            // make the request.
            var response = await _Client.SendAsync(endpointRequest);

            HttpStatusCode _statusCode = response.StatusCode;

            if (_statusCode != HttpStatusCode.Created)
            {
                string _responseContent = null;
                var    ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await response.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(endpointRequest, null);
                ex.Response = new HttpResponseMessageWrapper(response, _responseContent);

                endpointRequest.Dispose();
                if (response != null)
                {
                    response.Dispose();
                }
                throw ex;
            }
            else
            {
                jsonString = await response.Content.ReadAsStringAsync();

                var ob = Newtonsoft.Json.JsonConvert.DeserializeObject <DocumentLibraryResponse>(jsonString);

                if (listTitle != documentTemplateUrlTitle)
                {
                    // update list title
                    endpointRequest = new HttpRequestMessage(HttpMethod.Post, $"{ApiEndpoint}web/lists(guid'{ob.d.Id}')");
                    var type    = new { type = "SP.List" };
                    var request = new
                    {
                        __metadata = type,
                        Title      = listTitle
                    };
                    jsonString = JsonConvert.SerializeObject(request);
                    strContent = new StringContent(jsonString, Encoding.UTF8);
                    strContent.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json;odata=verbose");
                    endpointRequest.Headers.Add("IF-MATCH", "*");
                    endpointRequest.Headers.Add("X-HTTP-Method", "MERGE");
                    endpointRequest.Content = strContent;
                    response = await _Client.SendAsync(endpointRequest);

                    jsonString = await response.Content.ReadAsStringAsync();

                    response.EnsureSuccessStatusCode();
                }
            }

            return(library);
        }
Exemplo n.º 10
0
        /// <summary>
        /// Get file details list from SharePoint filtered by folder name and document type
        /// </summary>
        /// <param name="listTitle"></param>
        /// <param name="folderName"></param>
        /// <param name="documentType"></param>
        /// <returns></returns>
        public async Task <List <FileDetailsList> > GetFileDetailsListInFolder(string listTitle, string folderName, string documentType)
        {
            // return early if SharePoint is disabled.
            if (!IsValid())
            {
                return(null);
            }

            folderName = FixFoldername(folderName);

            string serverRelativeUrl = "";

            // ensure the webname has a slash.
            if (!string.IsNullOrEmpty(WebName))
            {
                serverRelativeUrl += $"{WebName}/";
            }

            serverRelativeUrl += Uri.EscapeUriString(listTitle);
            if (!string.IsNullOrEmpty(folderName))
            {
                serverRelativeUrl += "/" + Uri.EscapeUriString(folderName);
            }

            string             _responseContent = null;
            HttpRequestMessage _httpRequest     = new HttpRequestMessage
            {
                Method     = HttpMethod.Get,
                RequestUri = new Uri(ApiEndpoint + "web/getFolderByServerRelativeUrl('" + EscapeApostrophe(serverRelativeUrl) + "')/files"),
                Headers    =
                {
                    { "Accept", "application/json" }
                }
            };

            // make the request.
            var _httpResponse = await _Client.SendAsync(_httpRequest);

            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            if ((int)_statusCode != 200)
            {
                var ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, null);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);

                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            else
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync();
            }

            // parse the response
            JObject responseObject = null;

            try
            {
                responseObject = JObject.Parse(_responseContent);
            }
            catch (JsonReaderException jre)
            {
                throw jre;
            }
            // get JSON response objects into a list
            List <JToken> responseResults = responseObject["value"].Children().ToList();
            // create file details list to add from response
            List <FileDetailsList> fileDetailsList = new List <FileDetailsList>();

            // create .NET objects
            foreach (JToken responseResult in responseResults)
            {
                // JToken.ToObject is a helper method that uses JsonSerializer internally
                FileDetailsList searchResult = responseResult.ToObject <FileDetailsList>();
                //filter by parameter documentType
                int fileDoctypeEnd = searchResult.Name.IndexOf("__");
                if (fileDoctypeEnd > -1)
                {
                    string fileDoctype = searchResult.Name.Substring(0, fileDoctypeEnd);
                    if (fileDoctype == documentType)
                    {
                        searchResult.DocumentType = documentType;
                    }
                }
                fileDetailsList.Add(searchResult);
            }
            fileDetailsList = fileDetailsList.Where(f => string.IsNullOrEmpty(documentType) || f.DocumentType == documentType).ToList();
            return(fileDetailsList);
        }
        /// <summary>
        /// Get file details list from SharePoint filtered by folder name and document type
        /// </summary>
        /// <param name="listTitle"></param>
        /// <param name="folderName"></param>
        /// <param name="documentType"></param>
        /// <returns></returns>
        public async Task <List <FileDetailsList> > GetFileDetailsListInFolder(string listTitle, string folderName, string documentType)
        {
            string             serverRelativeUrl = $"{WebName}/" + Uri.EscapeUriString(listTitle) + "/" + Uri.EscapeUriString(folderName);
            string             _responseContent  = null;
            HttpRequestMessage _httpRequest      =
                new HttpRequestMessage(HttpMethod.Post, ApiEndpoint + "web/getFolderByServerRelativeUrl('" + EscapeApostrophe(serverRelativeUrl) + "')/files");
            // make the request.
            var _httpResponse = await client.SendAsync(_httpRequest);

            HttpStatusCode _statusCode = _httpResponse.StatusCode;

            if ((int)_statusCode != 200)
            {
                var ex = new SharePointRestException(string.Format("Operation returned an invalid status code '{0}'", _statusCode));
                _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false);

                ex.Request  = new HttpRequestMessageWrapper(_httpRequest, null);
                ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent);

                _httpRequest.Dispose();
                if (_httpResponse != null)
                {
                    _httpResponse.Dispose();
                }
                throw ex;
            }
            else
            {
                _responseContent = await _httpResponse.Content.ReadAsStringAsync();
            }

            // parse the response
            // parse the response
            JObject responseObject = null;

            try
            {
                responseObject = JObject.Parse(_responseContent);
            }
            catch (JsonReaderException jre)
            {
                throw jre;
            }
            // get JSON response objects into a list
            List <JToken> responseResults = responseObject["d"]["results"].Children().ToList();
            // create file details list to add from response
            List <FileDetailsList> fileDetailsList = new List <FileDetailsList>();

            // create .NET objects
            foreach (JToken responseResult in responseResults)
            {
                // JToken.ToObject is a helper method that uses JsonSerializer internally
                FileDetailsList searchResult = responseResult.ToObject <FileDetailsList>();
                //filter by parameter documentType
                int fileDoctypeEnd = searchResult.Name.IndexOf("__");
                if (fileDoctypeEnd > -1)
                {
                    string fileDoctype = searchResult.Name.Substring(0, fileDoctypeEnd);
                    if (fileDoctype == documentType)
                    {
                        searchResult.DocumentType = documentType;
                        fileDetailsList.Add(searchResult);
                    }
                }
            }

            return(fileDetailsList);
        }