Tuesday, August 13, 2019

Getting the Page URL of a File in CSOM If title & Name was different in Site Pages Library

postPageCtx.Credentials = new SharePointOnlineCredentials(un, securePwd);
var list = postPageCtx.Web.Lists.GetByTitle(pageLibName);
var item = list.GetItemById(pageItemID);
postPageCtx.Load(item);
postPageCtx.ExecuteQuery();
var fieldVals = item.FieldValues;
var postPageUrl = pageSiteUrl + "/SitePages/" + fieldVals["FileLeafRef"].ToString();

LIST OF INTERNAL NAMES FOR SHAREPOINT FIELDS

In order to reference a column or field using the SharePoint object model, you often need to know its internal name. For example, when creating a CAML query, you can specify the field on which to search by providing its internal name. As opposed to the display name, which can be changed in the UI, the internal name is immutable. While the default display name and the internal name are often identical or similar, they can also be very different. The difference isn’t always consistent. For example, spaces in the display name can be removed, such as IsCheckedoutToLocal, or replaced with the hexadecimal equivalent, such as HTML_x0020_File_x0020_Type. Furthermore, the display name can be the same for more than one fields, so the internal name is the only way to distinguish between them.
You can quickly determine the internal name of a field using the UI:
  1. Open the List Settings page
  2. Under the Columns section, select a column to view the Edit Column page
  3. The URL of this page includes the internal name in the query string. For example, the URL for the Created By field includes the following query string List=%7BF641CEF1%2DCDE2%2D49E1%2D9800%2D861A408EF890%7D&Field=Author. The value for the Field parameter, Author, is the internal name for Created By.
However, this approach isn’t always convenient. If the column you want doesn’t already belong to the list, you’d have to first add it.
For reference purpose, below is the list of the display name and corresponding internal name for the default fields of a Document Library.
TITLEINTERNAL NAME
Approval Status_ModerationStatus
Approver Comments_ModerationComments
Check In Comment_CheckinComment
Checked Out ToCheckoutUser
Checked Out ToCheckedOutTitle
Checked Out ToLinkCheckedOutTitle
Content TypeContentType
Content Type IDContentTypeId
Copy Source_CopySource
CreatedCreated
CreatedCreated_x0020_Date
Created ByAuthor
Document Created ByCreated_x0020_By
Document Modified ByModified_x0020_By
EditEdit
Edit Menu Table End_EditMenuTableEnd
Edit Menu Table Start_EditMenuTableStart
Effective Permissions MaskPermMask
Encoded Absolute URLEncodedAbsUrl
File SizeFile_x0020_Size
File SizeFileSizeDisplay
File TypeFile_x0020_Type
GUIDGUID
Has Copy Destinations_HasCopyDestinations
Html File Linkxd_ProgID
HTML File TypeHTML_x0020_File_x0020_Type
IDID
ID of the User who has the item Checked OutCheckedOutUserId
Instance IDInstanceID
Is Checked out to localIsCheckedoutToLocal
Is Current Version_IsCurrentVersion
Is Signedxd_Signature
Item TypeFSObjType
Level_Level
MergeCombine
ModifiedModified
ModifiedLast_x0020_Modified
Modified ByEditor
NameFileLeafRef
NameLinkFilenameNoMenu
NameLinkFilename
NameBaseName
OrderOrder
owshiddenversionowshiddenversion
PathFileDirRef
ProgIdProgId
Property BagMetaInfo
RelinkRepairDocument
ScopeIdScopeId
SelectSelectTitle
SelectSelectFilename
Server Relative URLServerUrl
Shared File Index_SharedFileIndex
Source Name (Converted Document)ParentLeafName
Source Url_SourceUrl
Source Version (Converted Document)ParentVersionString
Template LinkTemplateUrl
TitleTitle
TypeDocIcon
UI Version_UIVersion
Unique IdUniqueId
URL PathFileRef
Version_UIVersionString
Virus StatusVirusStatus
Workflow Instance IDWorkflowInstanceID
Workflow VersionWorkflowVersion
In my case, I’m interested in the Name field. I wouldn’t have guessed that it would be mapped to FileLeafRef.
Referenced Link : 
My code for CSOM as given Below.
postPageCtx.Credentials = new SharePointOnlineCredentials(userName, secureUsrPwd);
                    var list = postPageCtx.Web.Lists.GetByTitle(pageLibName);
                    var item = list.GetItemById(pageItemID);
                    postPageCtx.Load(item);
                    postPageCtx.ExecuteQuery();
                    var fieldVals = item.FieldValues;
var postPageUrl = pageSiteUrl + "/SitePages/" + fieldVals["FileLeafRef"].ToString();

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)



How to Deploy Your HTML Website on a Linux Server (Apache + SFTP)

Launching a simple HTML website on your own Linux server is easier than you might think. Whether you're sharing a static landing page or...