예제 #1
0
        public SharePointOutput UpdateList(string listName, string id, Dictionary <string, string> fields)
        {
            SharePointOutput result = new SharePointOutput();

            try
            {
                var listItemFullName = GetLIFullName(listName);
                if (!listItemFullName.Success)
                {
                    throw listItemFullName.Exception;
                }
                if (_spo == null)
                {
                    _spo = SpoAuthUtility.Create(new Uri(_siteUrl), _username, WebUtility.HtmlEncode(_password), false);
                }

                string odataQuery = $"/_api/web/lists/GetByTitle('{listName}')/items({id})";

                var jsonDataString = string.Format("{{ '__metadata': {{ 'type': '{1}' }}, {0} }}", ConvertDictionaryToJsonFormat(fields), listItemFullName.SPRestData.d.ListItemEntityTypeFullName);

                byte[] content = ASCIIEncoding.ASCII.GetBytes(jsonDataString);

                string digest = _spo.GetRequestDigest();

                Uri url = new Uri(String.Format("{0}/{1}", _spo.SiteUrl, odataQuery));

                // Set X-RequestDigest
                var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                webRequest.Headers.Add("X-RequestDigest", digest);
                webRequest.Headers.Add("X-HTTP-Method", "MERGE");
                webRequest.Headers.Add("IF-MATCH", "*");


                // Send a json odata request to SPO rest services to fetch all list items for the list.
                var response = HttpHelper.SendODataJsonRequest(url, "POST", content, webRequest, _spo);
                if (!response.Success)
                {
                    result.Success   = false;
                    result.Exception = new Exception($"Failed to process the action on Sharepoint. HTTP Staus Code - {response.Status} ");
                }
                else
                {
                    var responseJson = Encoding.UTF8.GetString(response.Response, 0, response.Response.Length);

                    // Response from Sharepoint REST API is 0 byte length (surprise :O)
                    // So no meaning of converting any thing from here..
                    // If you want the full list item to return, do a service call again over here and return the obj..
                }
            }
            catch (Exception ex)
            {
                result.Success   = false;
                result.Exception = ex;
            }
            return(result);
        }
예제 #2
0
        public static SpoAuthUtility Create(Uri spSiteUrl, string username, string password, bool useIntegratedWindowsAuth)
        {
            var             utility = new SpoAuthUtility(spSiteUrl, username, password, useIntegratedWindowsAuth);
            CookieContainer cc      = utility.GetCookieContainer();
            var             cookies = from Cookie c in cc.GetCookies(spSiteUrl) where c.Name == "FedAuth" select c;

            if (cookies.Count() > 0)
            {
                //current = utility;
                return(utility);
            }
            else
            {
                throw new Exception("Could not retrieve Auth cookies");
            }
        }
예제 #3
0
        public SharePointOutput GetLIFullName(string listName)
        {
            SharePointOutput result = new SharePointOutput();

            if (_spo == null)
            {
                _spo = SpoAuthUtility.Create(new Uri(_siteUrl), _username, WebUtility.HtmlEncode(_password), false);
            }

            string odataQuery = $"_api/web/lists/GetByTitle('{listName}')";

            string digest = _spo.GetRequestDigest();

            Uri url = new Uri(String.Format("{0}/{1}", _spo.SiteUrl, odataQuery));

            // Set X-RequestDigest
            var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);

            webRequest.Headers.Add("X-RequestDigest", digest);

            // Send a json odata request to SPO rest services to fetch all list items for the list.
            var response = HttpHelper.SendODataJsonRequest(url, "GET", null, webRequest, _spo);

            if (!response.Success)
            {
                result.Success   = false;
                result.Exception = new Exception($"Failed to process the action on Sharepoint. HTTP Staus Code - {response.Status} ");
            }
            else
            {
                var responseJson         = Encoding.UTF8.GetString(response.Response, 0, response.Response.Length);
                SharepointRestData spObj = null;
                try
                {
                    spObj = Searilizer.DeserilizeSPJsonString(responseJson);
                }
                catch (Exception ex)
                {
                    result.Success   = false;
                    result.Exception = new Exception("Failed to deserialize Sharepoint REST Json string. Please see Inner Exception", ex);
                    return(result);
                }
                result.SPRestData = spObj;
            }
            return(result);
        }
        /// <summary>
        /// Sends a JSON OData request appending SPO auth cookies to the request header.
        /// </summary>
        /// <param name="uri">The request uri</param>
        /// <param name="method">The http method</param>
        /// <param name="requestContent">A stream containing the request content</param>
        /// <param name="clientHandler">The request client handler</param>
        /// <param name="authUtility">An instance of the auth helper to perform authenticated calls to SPO</param>
        /// <param name="headers">The http headers to append to the request</param>
        public static HttpWebResponseExt SendODataJsonRequest(Uri uri, String method, byte[] requestContent, HttpWebRequest clientHandler, SpoAuthUtility authUtility, Dictionary <string, string> headers = null)
        {
            if (clientHandler.CookieContainer == null)
            {
                clientHandler.CookieContainer = new CookieContainer();
            }

            CookieContainer cookieContainer = authUtility.GetCookieContainer(); // get the auth cookies from SPO after authenticating with Microsoft Online Services STS

            foreach (Cookie c in cookieContainer.GetCookies(uri))
            {
                clientHandler.CookieContainer.Add(uri, c); // apppend SPO auth cookies to the request
            }

            return(SendHttpRequest(
                       uri,
                       method,
                       requestContent,
                       "application/json;odata=verbose;charset=utf-8", // the http content type for the JSON flavor of SP REST services
                       clientHandler,
                       headers));
        }
예제 #5
0
        public SharePointOutput CreateListItem(string listName, Dictionary <string, string> fields)
        {
            SharePointOutput result = new SharePointOutput();

            try
            {
                var listItemFullName = GetLIFullName(listName);
                if (!listItemFullName.Success)
                {
                    throw listItemFullName.Exception;
                }
                if (_spo == null)
                {
                    _spo = SpoAuthUtility.Create(new Uri(_siteUrl), _username, WebUtility.HtmlEncode(_password), false);
                }

                //string odataQuery = $"/_api/web/lists/GetByTitle('Leads from Flow')/items({id})";
                string odataQuery = $"_api/web/lists/GetByTitle('{listName}')/items";

                var jsonDataString = string.Format("{{ '__metadata': {{ 'type': '{1}' }}, {0} }}", ConvertDictionaryToJsonFormat(fields), listItemFullName.SPRestData.d.ListItemEntityTypeFullName);

                byte[] content = ASCIIEncoding.ASCII.GetBytes(jsonDataString);

                string digest = _spo.GetRequestDigest();

                Uri url = new Uri(String.Format("{0}/{1}", _spo.SiteUrl, odataQuery));

                // Set X-RequestDigest
                var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                webRequest.Headers.Add("X-RequestDigest", digest);

                //var webRequest = (HttpWebRequest)HttpWebRequest.Create(url);
                //webRequest.Headers.Add("X-RequestDigest", digest);
                //webRequest.Headers.Add("X-HTTP-Method","MERGE");
                //webRequest.Headers.Add("IF-MATCH", "*");


                // Send a json odata request to SPO rest services to fetch all list items for the list.
                var response = HttpHelper.SendODataJsonRequest(url, "POST", content, webRequest, _spo);
                if (!response.Success)
                {
                    result.Success   = false;
                    result.Exception = new Exception($"Failed to process the action on Sharepoint. HTTP Staus Code - {response.Status} ");
                }
                else
                {
                    var responseJson = Encoding.UTF8.GetString(response.Response, 0, response.Response.Length);

                    SharepointRestData spObj = null;
                    try
                    {
                        spObj = Searilizer.DeserilizeSPJsonString(responseJson);
                    }
                    catch (Exception ex)
                    {
                        result.Success   = false;
                        result.Exception = new Exception("Failed to deserialize Sharepoint REST Json string. Please see Inner Exception", ex);
                        return(result);
                    }
                    result.SPRestData = spObj;
                }
            }
            catch (Exception ex)
            {
                result.Success   = false;
                result.Exception = ex;
            }
            return(result);
        }