Categories
Skip Navigation Links

Connect to SharePoint Online, On premise and Extranet using CSOM

In this article, we have demonstrated how you can connect to SharePoint On-premises, Online, and Extranet using C# code. We have provided easy and ready to use code that you can directly utilize in your program.

Connect to SharePoint environment using C#

Here, we have provided a single class file which takes Site URL, Username, Password, and Environment as parameters and based on these details, it authenticates the user and gives context object which can be used to access various SharePoint objects using C# code.

We have provided comments wherever is needed which makes the code self-explanatory.

You can also check some very useful operations using C# code in SharePoint which you can be utilized after the authentication method provided here.

Create Console application in Visual Studio

  1. Open Visual Studio. I have used Visual Studio 2017. This can also work in the older version.
  2. Create a New Project. I have used .Net Framework 4.6.1 and have created Console Application as shown in the screenshot below
  3. create new project in visual studio
  4. Below are the references added to the project.Microsoft.SharePoint.Client;Microsoft.SharePoint.Client.Runtime;
  5. Entire Program.cs file is copied below. You can use it as it is and your code should work.
    • using System;
    • using System.Linq;
    • using System.Security;
    • using System.Net;
    • using Microsoft.SharePoint.Client;
    •  
    • namespace CSOMAuthentication
    • {
    •     class Program
    •     {
    •         static void Main(string[] args)
    •         {
    •             // Provide Site URL
    •             string SiteURL = "SiteURL";
    •  
    •             // Provide the environment in which the site resides. One of the below options.
    •             // (i) onpremises (ii) o365 (iii) extranet
    •             string Environmentvalue = "o365";
    •             string username = "UserName";
    •             string password = "Password";
    •             AuthenticateUser(new Uri(SiteURL), Environmentvalue, username, password);
    •         }
    •  
    •         private static void AuthenticateUser(Uri TargetSiteUrl, string Environmentvalue, string username, string password)
    •         {
    •             try
    •             {
    •                 // Based on the environmentvalue provided it execute the function.
    •                 if (string.Compare(Environmentvalue, "onpremises", StringComparison.OrdinalIgnoreCase) == 0)
    •                 {
    •                     ClientContext Context = LogOn(username, password, TargetSiteUrl);
    •                     // isAuthenticated = true;
    •                      // You can write additional methods here which you want to use after authentication
    •                 }
    •                 else if (string.Compare(Environmentvalue, "o365", StringComparison.OrdinalIgnoreCase) == 0)
    •                 {
    •                     ClientContext Context = O365LogOn(username, password, TargetSiteUrl);
    •                     // isAuthenticated = true;
    •                      // You can write additional methods here which you want to use after authentication
    •                 }
    •                 else if (string.Compare(Environmentvalue, "extranet", StringComparison.OrdinalIgnoreCase) == 0)
    •                 {
    •                     ClientContext Context = ExtranetLogOn(username, password, TargetSiteUrl);
    •                     // isAuthenticated = true;
    •                      // You can write additional methods here which you want to use after authentication
    •                 }
    •             }
    •             catch (Exception ex)
    •             {
    •                 // log error               
    •             }
    •         }
    •  
    •         private static ClientContext LogOn(string userName, string password, Uri url)
    •         {
    •             ClientContext clientContext = null;
    •             ClientContext ctx;
    •             try
    •             {
    •                 clientContext = new ClientContext(url);
    •  
    •                 // Condition to check whether the user name is null or empty.
    •                 if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
    •                 {
    •                     SecureString securestring = new SecureString();
    •                     password.ToCharArray().ToList().ForEach(s => securestring.AppendChar(s));
    •                     clientContext.Credentials = new System.Net.NetworkCredential(userName, securestring);
    •                     clientContext.ExecuteQuery();
    •                 }
    •                 else
    •                 {
    •                     clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
    •                     clientContext.ExecuteQuery();
    •                 }
    •  
    •                 ctx = clientContext;
    •             }
    •             finally
    •             {
    •                 if (clientContext != null)
    •                 {
    •                     clientContext.Dispose();
    •                 }
    •             }
    •  
    •             return ctx;
    •         }
    •  
    •         private static ClientContext O365LogOn(string userName, string password, Uri url)
    •         {
    •             ClientContext clientContext = null;
    •             ClientContext ctx = null;
    •             try
    •             {
    •                 clientContext = new ClientContext(url);
    •  
    •                 // Condition to check whether the user name is null or empty.
    •                 if (!string.IsNullOrEmpty(userName) && !string.IsNullOrEmpty(password))
    •                 {
    •                     SecureString securestring = new SecureString();
    •                     password.ToCharArray().ToList().ForEach(s => securestring.AppendChar(s));
    •                     clientContext.Credentials = new SharePointOnlineCredentials(userName, securestring);
    •                     clientContext.ExecuteQuery();
    •                 }
    •                 else
    •                 {
    •                     clientContext.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials;
    •                     clientContext.ExecuteQuery();
    •                 }
    •                 ctx = clientContext;
    •             }
    •             finally
    •             {
    •                 if (clientContext != null)
    •                 {
    •                     clientContext.Dispose();
    •                 }
    •             }
    •             return ctx;
    •         }
    •  
    •         private static ClientContext ExtranetLogOn(string userName, string password, Uri url)
    •         {
    •             ClientContext clientContext = null;
    •             ClientContext ctx;
    •             try
    •             {
    •                 clientContext = new ClientContext(url);
    •  
    •                 // Condition to check whether the user name is null or empty.
    •                 if (!string.IsNullOrEmpty(userName))
    •                 {
    •                     NetworkCredential networkCredential = new NetworkCredential(userName, password);
    •                     CredentialCache cc = new CredentialCache();
    •                     cc.Add(url, "NTLM", networkCredential);
    •                     clientContext.Credentials = cc;
    •                     clientContext.ExecuteQuery();
    •                 }
    •                 else
    •                 {
    •                     CredentialCache cc = new CredentialCache();
    •                     cc.Add(url, "NTLM", System.Net.CredentialCache.DefaultNetworkCredentials);
    •                     clientContext.Credentials = cc;
    •                     clientContext.ExecuteQuery();
    •                 }
    •                 ctx = clientContext;
    •             }
    •             finally
    •             {
    •                 if (clientContext != null)
    •                 {
    •                     clientContext.Dispose();
    •                 }
    •             }
    •             return ctx;
    •         }
    •     }
    • }

Apart from using C# to interact with SharePoint, you can also leverage JavaScript Object Model, REST-API and PnP PowerShell examples as well.

Conclusion:

We went through a very useful piece of code to check whether a particular user is authenticated or not against provided Site URL and environment.


We value your Feedback:

Page URL:

Name:

 

Email:

 
 

Suggestion:

 

© 2020 Code SharePoint