Ejemplo n.º 1
0
        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 += $"{listTitle}/{folderName}";

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

            // 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.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);
        }
Ejemplo n.º 2
0
        /// <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
            {
                Method     = HttpMethod.Post,
                RequestUri = new Uri(ApiEndpoint + "web/getFolderByServerRelativeUrl('" + EscapeApostrophe(serverRelativeUrl) + "')/Files/add(url='"
                                     + EscapeApostrophe(name) + "',overwrite=true)"),
                Headers =
                {
                    { "Accept", "application/json" }
                }
            };

            // 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);
        }
Ejemplo n.º 3
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;
            }

            string relativeUrl = $"/{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;

            if (_statusCode != HttpStatusCode.OK && _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
            {
                string jsonString = await response.Content.ReadAsStringAsync();
            }
        }
Ejemplo n.º 4
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);
        }
Ejemplo n.º 5
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);
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Rename a file
        /// </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='{newServerRelativeUrl}', flags=1)";

            HttpRequestMessage endpointRequest = new HttpRequestMessage(HttpMethod.Post, url);

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

            // 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);
        }
Ejemplo n.º 7
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 (documentTemplateUrlTitle == null)
            {
                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;

            // 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);
        }
Ejemplo n.º 8
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);
            }

            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);
        }