Tuesday, August 13, 2019

Function APP Authentication



Azure Function APP Authentication  &  trigger this azure Function in SPFx webpart

Identity providers

App Service uses federated identity, in which a third-party identity provider manages the user identities and authentication flow for you. Five identity providers are available by default:
ProviderSign-in endpoint
Azure Active Directory/.auth/login/aad
Microsoft Account/.auth/login/microsoftaccount
Facebook/.auth/login/facebook
Google/.auth/login/google
Twitter/.auth/login/twitter





Reference Link :

https://docs.microsoft.com/en-us/azure/app-service/overview-authentication-authorization


and Call above function in SPFx webpart as below

public async _makeAzureCMRequest(): Promise<string>{
      return new Promise<string>((resolve, reject) => {
      const body: string = JSON.stringify({
        '_siteUrl': this.spfxContext.pageContext.web.absoluteUrl,
        '_pageItemID':this.spfxContext.pageContext.listItem.id
        });
     
        const requestHeaders: Headers = new Headers();
        requestHeaders.append('Content-type', 'application/json');
        requestHeaders.append('Cache-Control', 'no-cache');
      
        const httpClientOptions: IHttpClientOptions = {
          body: body,
          headers: requestHeaders
        };
      this.spfxContext.aadHttpClientFactory 
          .getClient(strings.clientId) 
          .then((client: AadHttpClient): void => { 
              client 
              .post(strings.azureContentAPI, AadHttpClient.configurations.v1,httpClientOptions) 
              .then((response: SPHttpClientResponse) => response.json())
              .then((response: any) => {
              if (response) {
                  console.log(response)
              let varitems =response.Result;
                  resolve(varitems)
              console.log(response.Row);     
              }
          });
          }); 

      });




How to Send email via SharePoint Client Context - SendMailViaCtx

How to Send email via SharePoint Context,


Get User Name, Password, Hub Manager email, User email, From an email  from Config as per your requirements.



 try
                            {
                                SecureString secPwd = new SecureString();
                                foreach (var p in password)
                                {
                                    secPwd.AppendChar(p);
                                }
                                secPwd.MakeReadOnly();
                                using (var clientContext = new ClientContext("https://{Tenant}.sharepoint.com"))
                                {
                                    clientContext.Credentials = new SharePointOnlineCredentials(userName, secPwd);
                                    var emailp = new EmailProperties();
                                    emailp.BCC = new List<string> { user.Email };
                                    emailp.To = new List<string> { hubManagersEmail };
                                    emailp.From = userName;
                                    emailp.Body = "<b>Hi Moderators, <p>Please review the the Page data as tool found blocked words in page</p><p>Regards,</p><p>Admin Team</p></b>";
                                    emailp.Subject = "Profanity Alert! ! Found blocked words in page";
                                    Utility.SendEmail(clientContext, emailp);
                                    clientContext.ExecuteQuery();
                                    log.Info("Sent Email on Blocked words");
                                }

                            }
                            catch (Exception)
                            {
                                log.Info("Error while Sending email");
                            }


OUTPUT EMAIL LOOKS AS BELOW:



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 

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...