Friday, October 25, 2013

SharePoint Online: Accessing Web Services

SharePoint Online: Accessing Web Services
http://code.msdn.microsoft.com/office/SharePoint-Online-0bdeb2ca
Note: Add Web Reference as "https://sreekanth1apps.sharepoint.com/sites/apps/_vti_bin/Lists.asmx"
and give name it as "listsWS"

using System;
using System.Net;
using System.Xml;
using System.IO;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net.Security;
using System.Reflection;
using System.Globalization;
using System.Text.RegularExpressions;
using Microsoft.SharePoint.Client;
using System.Runtime.InteropServices;
using System.Collections.Generic;

namespace SPO_AccessAWebService
{
    class Program
    {
        [STAThread]
        static void Main(string[] args)
        {
            string siteURL = "https://sreekanth1apps.sharepoint.com/sites/apps";
            Console.WriteLine("Opening Site: " + siteURL);

            using (ClientContext context = ClaimsClientContext.GetAuthenticatedContext(siteURL))
            {
                if (context != null)
                {
                    context.Load(context.Web);
                    context.ExecuteQuery();
                    Console.WriteLine(context.Web.Title);
                }
            }
            Console.WriteLine();
            CookieCollection authCookie = ClaimsClientContext.GetAuthenticatedCookies(siteURL, 700, 500);
            listsWS.Lists list = new listsWS.Lists();
            list.Url = "https://sreekanth1apps.sharepoint.com/sites/apps/_vti_bin/Lists.asmx";
            list.CookieContainer = new CookieContainer();
            list.CookieContainer.Add(authCookie);
            string listName = "Documents";
            string viewName = "";
            string rowLimit = "5";
            XmlDocument xmlDoc = new XmlDocument();
            XmlElement query = xmlDoc.CreateElement("Query");
            XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
            XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
            query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" + "<Value Type=\"Counter\">0</Value></Gt></Where>";
            viewFields.InnerXml = "<FieldRef Name =\"Title\" />";
            queryOptions.InnerXml = "<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" + "<DateInUtc>TRUE</DateInUtc>";
            XmlNode nodes = list.GetListItems(listName, viewName, query, viewFields, rowLimit, null, string.Empty);
            string ixml = list.GetList(listName).InnerXml;
            Console.WriteLine("Retreiving Items...");
            foreach (XmlNode node in nodes)
            {
                if (node.Name == "rs:data")
                {
                    for (int i = 0; i < node.ChildNodes.Count; i++)
                    {
                        if (node.ChildNodes[i].Name == "z:row")
                        {
                            if (node.ChildNodes[i].Attributes["ows_Title"] != null)
                            {
                                Console.WriteLine(node.ChildNodes[i].Attributes["ows_Title"].Value);
                            }
                            if (node.ChildNodes[i].Attributes["ows_Created_x0020_Date"] != null)
                            {
                                Console.WriteLine(node.ChildNodes[i].Attributes["ows_Created_x0020_Date"].Value);
                            }

                        }
                    }
                }
            }
            Console.ReadKey();
        }
    }

    class ClaimsClientContext
    {
        public static CookieCollection GetAuthenticatedCookies(string targetSiteUrl, int popUpWidth, int popUpHeight)
        {
            CookieCollection authCookie = null;
            using (ClaimsWebAuth webAuth = new ClaimsWebAuth(targetSiteUrl, popUpWidth, popUpHeight))
            {
                authCookie = webAuth.Show();
            }
            return authCookie;
        }

        public static ClientContext GetAuthenticatedContext(string targetSiteUrl)
        {
            return (GetAuthenticatedContext(targetSiteUrl, 0, 0));
        }

        public static ClientContext GetAuthenticatedContext(string targetSiteUrl, int popUpWidth, int popUpHeight)
        {
            CookieCollection cookies = null;
            cookies = ClaimsClientContext.GetAuthenticatedCookies(targetSiteUrl, popUpWidth, popUpHeight);
            if (cookies == null) return null;

            ClientContext context = new ClientContext(targetSiteUrl);
            try
            {
                context.ExecutingWebRequest += delegate(object sender, WebRequestEventArgs e)
                {
                    e.WebRequestExecutor.WebRequest.CookieContainer = new CookieContainer();
                    foreach (Cookie cookie in cookies)
                    {
                        e.WebRequestExecutor.WebRequest.CookieContainer.Add(cookie);
                    }
                };
            }
            catch
            {
                if (context != null) context.Dispose();
                throw;
            }

            return context;
        }
    }

    class ClaimsWebAuth : IDisposable
    {
        #region Construction
        public ClaimsWebAuth(string targetSiteUrl, int popUpWidth, int popUpHeight)
        {
            if (string.IsNullOrEmpty(targetSiteUrl)) throw new ArgumentException(Constants.MSG_REQUIRED_SITE_URL);
            this.fldTargetSiteUrl = targetSiteUrl;

            this.GetClaimParams(this.fldTargetSiteUrl, out this.fldLoginPageUrl, out  this.fldNavigationEndUrl);

            this.PopUpHeight = PopUpHeight;
            this.PopUpWidth = PopUpWidth;

            this.webBrowser = new WebBrowser();
            this.webBrowser.Navigated += new WebBrowserNavigatedEventHandler(ClaimsWebBrowser_Navigated);
            this.webBrowser.ScriptErrorsSuppressed = true;
            this.webBrowser.Dock = DockStyle.Fill;
        }

        #endregion

        #region private Fields
        private WebBrowser webBrowser;

        private CookieCollection fldCookies;
        private System.Windows.Forms.Form DisplayLoginForm;

        #endregion

        #region Public Properties

        private string fldLoginPageUrl;
        public string LoginPageUrl
        {
            get { return fldLoginPageUrl; }
            set { fldLoginPageUrl = value; }
        }

        private Uri fldNavigationEndUrl;
        public Uri NavigationEndUrl
        {
            get { return fldNavigationEndUrl; }
            set { fldNavigationEndUrl = value; }
        }

        private string fldTargetSiteUrl = null;
        public string TargetSiteUrl
        {
            get { return fldTargetSiteUrl; }
            set { fldTargetSiteUrl = value; }
        }

        public CookieCollection AuthCookies
        {
            get { return fldCookies; }
        }

        private bool fldIsCLAIMSite = false;
        public bool IsCLAIMSite
        {
            get { return fldIsCLAIMSite; }
        }

        private int fldPopUpWidth = 0;
        public int PopUpWidth
        {
            get { return fldPopUpWidth; }
            set { fldPopUpWidth = value; }
        }

        private int fldPopUpHeight;
        public int PopUpHeight
        {
            get { return fldPopUpHeight; }
            set { fldPopUpHeight = value; }
        }
        #endregion

        #region Public Methods

        public CookieCollection Show()
        {
            if (string.IsNullOrEmpty(this.LoginPageUrl)) throw new ApplicationException(Constants.MSG_NOT_CLAIM_SITE);

            this.webBrowser.Navigate(this.LoginPageUrl);

            DisplayLoginForm = new System.Windows.Forms.Form();
            DisplayLoginForm.SuspendLayout();

            int dialogWidth = Constants.DEFAULT_POP_UP_WIDTH;
            int dialogHeight = Constants.DEFAULT_POP_UP_HEIGHT;

            if (PopUpHeight != 0 && PopUpWidth != 0)
            {
                dialogWidth = Convert.ToInt32(PopUpWidth);
                dialogHeight = Convert.ToInt32(PopUpHeight);
            }

            DisplayLoginForm.Width = dialogWidth;
            DisplayLoginForm.Height = dialogHeight;
            DisplayLoginForm.Text = this.fldTargetSiteUrl;

            DisplayLoginForm.Controls.Add(this.webBrowser);
            DisplayLoginForm.ResumeLayout(false);

            Application.Run(DisplayLoginForm);

            return this.fldCookies;
        }


        #endregion

        #region Private Methods

        private void GetClaimParams(string targetUrl, out string loginUrl, out Uri navigationEndUrl)
        {
            HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(targetUrl);
            webRequest.Method = Constants.WR_METHOD_OPTIONS;
#if DEBUG
            ServicePointManager.ServerCertificateValidationCallback = new RemoteCertificateValidationCallback(IgnoreCertificateErrorHandler);
#endif

            try
            {
                WebResponse response = (WebResponse)webRequest.GetResponse();
                ExtraHeadersFromResponse(response, out loginUrl, out navigationEndUrl);
            }
            catch (WebException webEx)
            {
                ExtraHeadersFromResponse(webEx.Response, out loginUrl, out navigationEndUrl);
            }
        }

        private bool ExtraHeadersFromResponse(WebResponse response, out string loginUrl, out Uri navigationEndUrl)
        {
            loginUrl = null;
            navigationEndUrl = null;

            try
            {
                navigationEndUrl = new Uri(response.Headers[Constants.CLAIM_HEADER_RETURN_URL]);
                loginUrl = (response.Headers[Constants.CLAIM_HEADER_AUTH_REQUIRED]);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private CookieCollection ExtractAuthCookiesFromUrl(string url)
        {
            Uri uriBase = new Uri(url);
            Uri uri = new Uri(uriBase, "/");
            string stringCookie = CookieReader.GetCookie(uri.ToString());
            if (string.IsNullOrEmpty(stringCookie)) return null;
            stringCookie = stringCookie.Replace("; ", ",").Replace(";", ",");
            CookieContainer cookieContainer = new CookieContainer();
            cookieContainer.SetCookies(uri, stringCookie);
            return cookieContainer.GetCookies(uri);
        }
        #endregion

        #region Private Events

        private void ClaimsWebBrowser_Navigated(object sender, WebBrowserNavigatedEventArgs e)
        {
            if (fldNavigationEndUrl != null && fldNavigationEndUrl.Equals(e.Url))
            {
                this.fldCookies = ExtractAuthCookiesFromUrl(this.LoginPageUrl);
                this.DisplayLoginForm.Close();
            }
        }

        #endregion

        #region IDisposable Methods
        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

        public void Dispose(bool disposing)
        {
            if (disposing)
            {
                if (this.webBrowser != null) this.webBrowser.Dispose();

                if (this.DisplayLoginForm != null) this.DisplayLoginForm.Dispose();
            }
        }

        #endregion

        #region Utilities
#if DEBUG
        private bool IgnoreCertificateErrorHandler
           (object sender,
           System.Security.Cryptography.X509Certificates.X509Certificate certificate,
           System.Security.Cryptography.X509Certificates.X509Chain chain,
           System.Net.Security.SslPolicyErrors sslPolicyErrors)
        {

            return true;
        }
#endif
        #endregion
    }

    class Constants
    {
        public const string WR_METHOD_OPTIONS = "OPTIONS";

        public const string FED_AUTH_COOKIE_NAME = "FedAuth";

        public const string CLAIM_HEADER_RETURN_URL = "X-Forms_Based_Auth_Return_Url";
        public const string CLAIM_HEADER_AUTH_REQUIRED = "X-FORMS_BASED_AUTH_REQUIRED";

        public const string MSG_REQUIRED_SITE_URL = "The Site URL is required.";
        public const string MSG_NOT_CLAIM_SITE = "The requested site does not appear to have claims enabled or the Login Url has not been set.";

        public const int DEFAULT_POP_UP_WIDTH = 925;
        public const int DEFAULT_POP_UP_HEIGHT = 525;
    }

    internal static class CookieReader
    {
        private const int INTERNET_COOKIE_HTTPONLY = 0x00002000;

        [DllImport("wininet.dll", SetLastError = true)]
        private static extern bool InternetGetCookieEx(
            string url,
            string cookieName,
            StringBuilder cookieData,
            ref int size,
            int flags,
            IntPtr pReserved);

        public static string GetCookie(string url)
        {

            int size = 512;
            StringBuilder sb = new StringBuilder(size);
            if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
            {
                if (size < 0)
                {
                    return null;
                }
                sb = new StringBuilder(size);
                if (!InternetGetCookieEx(url, null, sb, ref size, INTERNET_COOKIE_HTTPONLY, IntPtr.Zero))
                {
                    return null;
                }
            }
            return sb.ToString();
        }
    }
}




Thank You.

No comments:

Post a Comment

Featured Post

Azure OpenAI Chat and DALL-E in C# and Python

Azure OpenAI Chat in C#: // Install the .NET library via NuGet: dotnet add package Azure.AI.OpenAI --version 1.0.0-beta.5   using System; u...

Popular posts