Monday, August 5, 2019

Get the mail address from a FieldUserValue OR CreatedBy OR Author in CSOM

Code to get user Email from SharePoint ListItem - Created By


 //var Author = fieldVals["Author"];


FieldUserValue Author = (FieldUserValue)item["Author"];var user = postPageCtx.Web.EnsureUser(Author.LookupValue);
// load the data with the context             
postPageCtx.Load(user);
postPageCtx.ExecuteQuery();
var createdBy = user.Email;



Reference Links:

Get the mail address from a FieldUserValue Client Side vs Server Side

http://crawlspaceofprogramming.blogspot.com/2015/08/get-mail-address-from-fielduservalue.html?_sm_au_=iVVVTVW7sq4PQnWM


USING Powershell

https://www.sharepointdiary.com/2016/05/powershell-to-get-created-by-user-field-values-in-sharepoint.html




{"Autodiscover blocked a potentially insecure redirection to https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload."}


Error Message : - 


{"Autodiscover blocked a potentially insecure redirection to https://autodiscover-s.outlook.com/autodiscover/autodiscover.xml. To allow Autodiscover to follow the redirection, use the AutodiscoverUrl(string, AutodiscoverRedirectionUrlValidationCallback) overload."}


Solution :


Comment Below line 
 // service.AutodiscoverUrl(MailUser);

then add below code
service.AutodiscoverUrl(MailUser, (a) =>
                {
                    return true;
                });


Send Email using Outlook Exchange Web Service (EWS) - C# Console Application Example

In this blog, I am explaining how to send mail on any domain using an exchange server. You can implement an exchange server following this step.
Step 1 - Create a Console application.


Step 2 - Add "Microsoft.Exchange" library reference in your console application.
Reference -> Manage Nuget Package--> Add below package
Microsoft.Exchange.WebServices
Description:

The Exchange Web Services (EWS) Managed API provides a .NET Framework interface to EWS in Exchange Online, Exchange Online as part of Office 365, and versions of Exchange starting with Exchange Server 2007 Service Pack 1 (SP1). 

You can use this version of the EWS Managed API to evaluate the library for your application needs, to compare it to directly using XML or the auto-generated proxy library, and to create production-ready applications.


or Add via PowerShell commad

PM>Install-Package Microsoft.Exchange.WebServices

Step 3: add "System.Configuration" library in your console app


Thereafter create a method to create mailing concept using exchange server.

using System;
using System.Configuration;
using System.Net;
using Microsoft.Exchange.WebServices.Data;

namespace SendmailByEWS
{
    class Program
    {
        static void Main(string[] args)
        {
            string MailUser =ConfigurationManager.AppSettings["MailUser"];
            string MailPass = ConfigurationManager.AppSettings["mailPass"].ToString();
            string MailTo = ConfigurationManager.AppSettings["MailTo"].ToString();
            var isSentEmail = SendMail(MailUser, MailPass, MailTo);
        }
        public static bool SendMail(string MailUser,string MailPass,string MailTo)
        {
            try
            {
                ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2013_SP1);
                service.Credentials = new NetworkCredential(MailUser, MailPass);
                service.AutodiscoverUrl(MailUser, (a) =>
                {
                    return true;
                });
               // service.AutodiscoverUrl(MailUser);

                EmailMessage emailMessage = new EmailMessage(service);
                emailMessage.Subject ="Profanity Alert! | Profanity Found | Review";
                emailMessage.Body = new MessageBody("Hi Admin, profanity found, please review and take further action");
                emailMessage.ToRecipients.Add(MailTo);
                emailMessage.SendAndSaveCopy();
                return true;
            }
            catch (Exception ex)
            {
                return false;
            }

        }
    }
}


Dont forget to Configuration values in App.config file

<configuration>

  <appSettings>
    <add key="MailUser" value="girishkumar.s@{Tenant}.onmicrosoft.com"/>
    <add key="mailPass" value="********"/>
    <add key="MailTo" value="abc@{Tenant}.onmicrosoft.com"/>

  </appSettings>

    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.6.1" />
    </startup>

</configuration>

Put Tenant name

Send Email using Outlook Exchange Web Service (EWS) - C# Console Application Example






Newtonsoft.Json.Linq.JArray to string array C#

While getting this error "Cannot implicitly convert type 'Newtonsoft.Json.Linq.JArray' to 'string[]'"

MenuJson=

SharePoint Online List Item 

 dynamic jsonString = JsonConvert.DeserializeObject(mylanProfanityItem.FieldValues["MenuJson"].ToString());
return jsonString.Words.ToObject<string[]>();



Monday, June 17, 2019

MakePostRequest using HTTPCLIENT


JObject MakePostRequest(Dictionary<string,string> dict, string url )
        {
            try
            {
                HttpClient client = new HttpClient();
                client.DefaultRequestHeaders.Add("Authorization", "Bearer " + token);
                var body = new StringContent(JsonConvert.SerializeObject(dict), Encoding.UTF8, "application/json");
                var response = client.PostAsync(url, body).GetAwaiter().GetResult();
                var responseString = response.Content.ReadAsStringAsync().GetAwaiter().GetResult();
                return JObject.Parse(responseString);
            }
            catch (Exception e)
            {
                Console.WriteLine("Error : " + e.ToString());
            }
            return JObject.Parse("{}");

        }

Get All Tenant Site Designs and Save last ID + SharePoint Online

           

/*Get All site designs and noting recent ID */


var customeSiteDesignID = new System.Guid();
using (var tenantContext = new ClientContext(tenentWebUrl))            {
                tenantContext.Credentials = new SharePointOnlineCredentials(uName, securePassword);
                tenantContext.RequestTimeout = Timeout.Infinite;
                //get the tenant object
                Tenant tenant = new Tenant(tenantContext);
                //customeSiteDesignID = tenant.GetSiteDesign(tenantContext, customeSiteDesignID);

                var tenantdesigns = tenant.GetSiteDesigns();
                tenantContext.Load(tenantdesigns);
                tenant.RefreshLoad();

                /*loop All site designs & get oSiteDesign ID -  */
                try
                {
                    tenantContext.ExecuteQuery();
                    foreach (TenantSiteDesign oSiteDesign in tenantdesigns)
                    {
                        customeSiteDesignID = oSiteDesign.Id;
                    }
                }
                catch (Exception ex)
                {
                    log.Info("Error Occured in Getting Site Designs - " + ex.Message);
                }

}




Reference Link :

https://docs.microsoft.com/en-us/previous-versions/office/sharepoint-csom/mt846005(v%3doffice.15)


https://docs.microsoft.com/en-us/previous-versions/office/sharepoint-csom/mt846003(v=office.15)



Steps to Delete sites collections on SharePoint Online using Powershell script by importing CSV file


Steps to Delete sites collections using Powershell script by importing CSV file

$cred = Get-Credential
Connect-SPOService $adminSiteUrl -Credential $cred

$filepath="C:\GK\PowerShell Scripts\Deletion of Site Collections in CSV\Updated Gidc sites.csv"
$CSVData = Import-CSV -path $filepath
$SiteUrl="https://tenant.sharepoint.com/sites/TestSiteUsingAF";

Remove only one site
Remove-SPOSite -Identity $SiteUrl -NoWait
Remove-SPOSite -Identity  $SiteUrl -confirm:$false

Remove multiple sites which are listed CSV
foreach($row in $CSVData)
 {
 write-host "Deleteing Site " + $row.Url
 Remove-SPOSite -Identity $row.Url -confirm:$false
 }

Below command will get all site collections under Bin folder
Get-SPODeletedSite

Friday, April 5, 2019

Get ID of an inserted list item via CSOM



// Get library columns collection.  
                        var libFields = list.Fields;
                        clientContext.Load(libFields);
                        clientContext.ExecuteQuery();

                        Microsoft.SharePoint.Client.File newFile = clientContext.Web.GetFileByServerRelativeUrl(fileUrl);
                        ListItem item1 = newFile.ListItemAllFields;
                        var fileN = fileName;
                        clientContext.Load(item1);//Load the new item
                        clientContext.ExecuteQuery();
                       // Console.WriteLine("ID of new item:{0}", newItem.Id);//Get ID 

item1.Id

You can refer below sample:
ClientContext context = new ClientContext("http://SiteUrl"); 
List listObj = context.Web.Lists.GetByTitle("ListName"); 
ListItemCreationInformation itemCreateInfo = new ListItemCreationInformation(); 
ListItem newItem = listObj.AddItem(itemCreateInfo); 
newItem["Title"] = "My New Item!"; 
newItem.Update(); 
context.Load(newItem);//Load the new item
context.ExecuteQuery();  
Console.WriteLine("ID of new item:{0}", newItem.Id);//Get ID 

Wednesday, January 23, 2019

Caml & Get access to SP using tokenhelper in webapi

//camlQuery.ViewXml = @"<View Scope='Recursive'><Query></Query></View>";// to get only files
                    //camlQuery.ViewXml = @"<View Scope='RecursiveAll'><Query></Query></View>"; // to get all folders with files
                    //ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllFoldersQuery());




[HttpGet]
        [Route("api/GetRootFolders")]
        public List<SPItem> GetRootFolders()
        {
            //first connect to sharepoint online
            List<SPItem> allItems = new List<SPItem>();
            //first connect to sharepoint online
            string spSiteURL = ConfigurationManager.AppSettings["SharePointURL"];
            Uri siteUrl = new Uri(spSiteURL);
            string realm = TokenHelper.GetRealmFromTargetUrl(siteUrl);
            string accessToken = TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, siteUrl.Authority, realm).AccessToken;

            try
            {
                using (var clientContext = TokenHelper.GetClientContextWithAccessToken(siteUrl.ToString(), accessToken))
                {

                    Web web = clientContext.Web;
                    // We want to retrieve the web's properties.
                    clientContext.Load(web);
                    clientContext.Load(web);
                    clientContext.ExecuteQuery();
                    clientContext.Load(web.CurrentUser);
                    clientContext.ExecuteQuery();
                    string username = web.CurrentUser.LoginName;
                    string webName = web.Title;
                    var list = web.Lists.GetByTitle(ConfigurationManager.AppSettings["LibName"]);
                    clientContext.Load(list);
                    clientContext.ExecuteQuery();
                    CamlQuery camlQuery = new CamlQuery();
                 
                    ListItemCollection listItems = list.GetItems(camlQuery);
                    clientContext.Load<ListItemCollection>(listItems);
                    clientContext.ExecuteQuery();
                    foreach (var item in listItems)
                    {
                        if (item.FileSystemObjectType != FileSystemObjectType.File)
                        {
                            SPItem itemCol = new SPItem();
                            itemCol.Name = item["FileLeafRef"].ToString();
                            itemCol.IsFolder = "Yes";
                            allItems.Add(itemCol);
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                var errmsg = ex.Message;
            }
            return allItems;
        }

Friday, January 4, 2019

Azure SharePoint WebApi Example code

using System;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Configuration;
using System.Threading.Tasks;
using Microsoft.SharePoint.Client;
using System.Security;
using System.IO;
using System.Text;
using SpoWebApi.Models;
using System.Collections;
using Newtonsoft.Json;
using System.Web.Script.Serialization;

namespace SpoWebApi.Controllers
{
    public class SparksController : ApiController
    {
        [HttpGet]
        [Route("api/hello")]
        public HttpResponseMessage HelloWorld()
        {
            string result = "Hello world! Time is: " + DateTime.Now;
            var resp = new HttpResponseMessage(HttpStatusCode.OK);
            resp.Content = new StringContent(result, System.Text.Encoding.UTF8, "text/plain");
            return resp;
        }
        [HttpGet]
        [Route("api/UpdateSharePoint")]
        public IHttpActionResult GetSparksDataUpdateSharePointList()
        {
            // this should process the order asynchronously
            var tasks = new[]
            {
            Task.Run(() => processMethod())
            };
            return Ok("ok");
        }
        public void processMethod()
        {
            string sharePointUrl = ConfigurationManager.AppSettings["SharePointURL"];
            var requestUrl = ConfigurationManager.AppSettings["getResourceUri"];
            var _sparkVMSKey = ConfigurationManager.AppSettings["vmsAppKey"];
            var _sparkServiceReqKey = ConfigurationManager.AppSettings["serviceReqResKey"];
            //var _sparksrcAppKey = ConfigurationManager.AppSettings["srcAppKey"];
            string _spUserName = ConfigurationManager.AppSettings["userName"];
            string _spPwd = ConfigurationManager.AppSettings["Password"];
            string _spListName = ConfigurationManager.AppSettings["listName"];
            Stream dataStream;
            WebResponse response;
            string responseFromServer;
            StreamReader reader;
            responseFromServer = "";
            reader = null;
            dataStream = null;
            response = null;
            var serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            var _ErrorLogPath = "/TestMapPath";
            var returnMessage = "";
            ArrayList myAL = new ArrayList();
            string postData = string.Format("destAppKey=" + _sparkVMSKey + "&resKey=" + _sparkServiceReqKey);//required for sendTO + "&srcAppKey=" + _sparksrcAppKey

            try
            {
                ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };
                WebRequest request = WebRequest.Create(requestUrl);
                request.Method = "POST";
                // string postData = dataPost;
                byte[] byteArray = Encoding.UTF8.GetBytes(postData);
                request.ContentType = "application/x-www-form-urlencoded";
                request.ContentLength = byteArray.Length;
                dataStream = request.GetRequestStream();
                dataStream.Write(byteArray, 0, byteArray.Length);
                dataStream.Close();
                response = request.GetResponse();
                dataStream = response.GetResponseStream();
                reader = new StreamReader(dataStream);
                responseFromServer = reader.ReadToEnd();
                Result sparksResult = Newtonsoft.Json.JsonConvert.DeserializeObject<Result>(responseFromServer);
                string webTitle = "";
                if (sparksResult.sparksResponse.status)
                {
                    foreach (Datum outData in sparksResult.sparksResponse.data)
                    {
                        Resdata sparksResData = Newtonsoft.Json.JsonConvert.DeserializeObject<Resdata>(outData.resdata);
                        //if status is true , please update SP list - 3 columns , Update list item depends on ProcessType
                        //VisitorRequestID ( CabRequestRaised ,  ITRequestRaised ,  FacilitiesReqRaised ) either YES OR NO
                        string spItemID = sparksResData.VisitorRequestID;
                        if (sparksResData.status == "true" && sparksResData.processType.Contains("AdhocCab"))
                        {
                            try
                            {
                                using (ClientContext clientContext = new ClientContext(sharePointUrl))
                                {
                                    var passWord = new SecureString();
                                    foreach (char c in _spPwd.ToCharArray()) passWord.AppendChar(c);
                                    clientContext.Credentials = new SharePointOnlineCredentials(_spUserName, passWord);
                                    Web web = clientContext.Web;
                                    List oList = clientContext.Web.Lists.GetByTitle(_spListName);
                                    ListItem oListItem = oList.GetItemById(spItemID);// spItemID);
                                    oListItem["CabRequestRaised"] = "1";
                                    oListItem["VisitorRequestID"] = sparksResData.requestId;
                                    oListItem["SSMsg"] = sparksResData.message;
                                    oListItem["PendingWith"] = sparksResData.pendingWith;
                                    oListItem.Update();
                                    clientContext.ExecuteQuery();
                                    clientContext.Load(web);
                                    clientContext.ExecuteQuery();
                                    webTitle = web.Title;
                                    myAL.Add(spItemID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var errmsg = ex.Message;
                            }

                            returnMessage += sparksResData.message + webTitle;
                        }
                        else if (sparksResData.status == "true" && sparksResData.processType.Contains("ITSupport"))
                        {
                            //update ITRequestRaised;
                            try
                            {
                                using (ClientContext clientContext = new ClientContext(sharePointUrl))
                                {
                                    var passWord = new SecureString();
                                    foreach (char c in _spPwd.ToCharArray()) passWord.AppendChar(c);
                                    clientContext.Credentials = new SharePointOnlineCredentials(_spUserName, passWord);
                                    Web web = clientContext.Web;
                                    List oList = clientContext.Web.Lists.GetByTitle(_spListName);
                                    ListItem oListItem = oList.GetItemById(spItemID);
                                    oListItem["ITRequestRaised"] = "1";
                                    oListItem["VisitorRequestID"] = sparksResData.requestId;
                                    oListItem["SSMsg"] = sparksResData.message;
                                    oListItem["PendingWith"] = sparksResData.pendingWith;
                                    oListItem.Update();
                                    clientContext.ExecuteQuery();
                                    myAL.Add(spItemID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var errmsg = ex.Message;
                            }
                        }
                        else if (sparksResData.status == "true" && sparksResData.processType.Contains("Facilities"))
                        {
                            //update FacilitiesReqRaised
                            try
                            {
                                using (ClientContext clientContext = new ClientContext(sharePointUrl))
                                {
                                    var passWord = new SecureString();
                                    foreach (char c in _spPwd.ToCharArray()) passWord.AppendChar(c);
                                    clientContext.Credentials = new SharePointOnlineCredentials(_spUserName, passWord);
                                    Web web = clientContext.Web;
                                    List oList = clientContext.Web.Lists.GetByTitle(_spListName);
                                    ListItem oListItem = oList.GetItemById(spItemID);
                                    oListItem["FacilitiesReqRaised"] = "1";
                                    oListItem["VisitorRequestID"] = sparksResData.requestId;
                                    oListItem["SSMsg"] = sparksResData.message;
                                    oListItem["PendingWith"] = sparksResData.pendingWith;
                                    oListItem.Update();
                                    clientContext.ExecuteQuery();
                                    myAL.Add(spItemID);
                                }
                            }
                            catch (Exception ex)
                            {
                                var errmsg = ex.Message;
                            }
                        }

                    }
                }
            }
            catch (Exception e)
            {
                var error = e.InnerException;
                ErrorLog errorLog = new ErrorLog();
                errorLog.message = "Something Went Wrong";
                errorLog.status = false;
                returnMessage = JsonConvert.SerializeObject(errorLog);
                System.IO.File.AppendAllText(System.Web.HttpContext.Current.Server.MapPath(_ErrorLogPath), e.Message + Environment.NewLine);
            }

            try
            {
                //ArrayList myDeleteIds = new ArrayList();
                //myDeleteIds.Add("12346781_Facilities");
                if (myAL.Count > 0)
                {
                    JavaScriptSerializer jss = new JavaScriptSerializer();
                    string output = jss.Serialize(myAL);
                    string postData1 = string.Format("destAppKey=" + _sparkVMSKey + "&resKey=" + _sparkServiceReqKey + "&dataIds=" + output);
                    string requestDeleteUrl = ConfigurationManager.AppSettings["deleteReports"];
                    ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) => { return true; };
                    WebRequest request = WebRequest.Create(requestDeleteUrl);
                    request.Method = "POST";
                    byte[] byteArray = Encoding.UTF8.GetBytes(postData1);
                    request.ContentType = "application/x-www-form-urlencoded";
                    request.ContentLength = byteArray.Length;
                    dataStream = request.GetRequestStream();
                    dataStream.Write(byteArray, 0, byteArray.Length);
                    dataStream.Close();
                    response = request.GetResponse();
                    dataStream = response.GetResponseStream();
                    reader = new StreamReader(dataStream);
                    responseFromServer = reader.ReadToEnd();
                }
            }
            catch (Exception ex)
            {
                var errmsg = ex.Message;
            }
        }
    }
}

Building Secure Azure AI Foundry Agents with Managed Identity

  The credential problem nobody wants to own Every team that connects an Azure AI Foundry agent to Microsoft Graph, SharePoint, Outlook, or...