Friday, January 19, 2024

Sent Email in C#

Sent Email in C#:

//Option 1:
using System;
using System.Net.Mail;
using System.Security;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Start....");
            string password = "password"; //ConfigurationManager.AppSettings["EmailPassword"];
            SecureString secure_passWord = new SecureString();
            foreach (char c in password.ToCharArray()) { secure_passWord.AppendChar(c); }
            System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
            client.UseDefaultCredentials = false;
            client.EnableSsl = true;
            //client.Credentials = new NetworkCredential("abc@xyz.com", secure_passWord);
            client.Credentials = new NetworkCredential("abc@xyz.com", "password");
            client.Port = 587; //replace with actual value
            client.Host = "smpt.mail.com"; //replace with actual value
            //client.DeliveryMethod = SmtpDeliveryMethod.Network;
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("abc@xyz.com");
            mail.To.Add("def@xyz.com");
            mail.Subject = "Test Mail";
            mail.Body = "Test body";
            mail.BodyEncoding = Encoding.UTF8;
            mail.IsBodyHtml = true;
            client.Send(mail);
            Console.WriteLine("End....");
        }
    }
}


//Option 2:
//https://learn.microsoft.com/en-us/azure/communication-services/quickstarts/email/send-email?tabs=windows%2Cconnection-string&pivots=programming-language-csharp
//Quickstart: How to send an email using Azure Communication Service
using Azure;
using Azure.Communication.Email;
 
namespace SendEmail
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            string connectionString = "connectionString";
            EmailClient emailClient = new EmailClient(connectionString);
            var subject = "Welcome to Azure Communication Service Email APIs.";
            var htmlContent = "<html><body><h1>Quick send email test</h1><br/><h4>This email message is sent from Azure Communication Service Email.</h4><p>This mail was sent using .NET SDK!!</p></body></html>";
            var sender = "DoNotReply@fcc11977-0b46-46c9-a657-4216db032070.azurecomm.net";
            var recipient = "abc@xyz.com";
            try
            {
                Console.WriteLine("Sending email...");
                EmailSendOperation emailSendOperation = await emailClient.SendAsync(Azure.WaitUntil.Completed, sender, recipient, subject, htmlContent);
                EmailSendResult statusMonitor = emailSendOperation.Value;
                Console.WriteLine($"Email Sent. Status = {emailSendOperation.Value.Status}");
                string operationId = emailSendOperation.Id;
                Console.WriteLine($"Email operation id = {operationId}");
            }
            catch (RequestFailedException ex)
            {
                Console.WriteLine($"Email send operation failed with error code: {ex.ErrorCode}, message: {ex.Message}");
            }
        }
    }
}


//Option 3:
using Microsoft.Identity.Client;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            //Required Azure Application Permissions : Mail.Send
            string clientId = "clientId";
            string clientSecret = "clientSecret";
            string tenantId = "tenantId";
            string userEmail = "abc@xyz.com"; // The user on behalf of whom you want to send the email
 
            var confidentialClient = ConfidentialClientApplicationBuilder
                .Create(clientId)
                .WithClientSecret(clientSecret)
                .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}"))
                .Build();
 
            var authResult = await confidentialClient.
                AcquireTokenForClient(new[] { "https://graph.microsoft.com/.default" })
                .ExecuteAsync();
 
            string accessToken = authResult.AccessToken;
 
            using (var httpClient = new HttpClient())
            {
                //Required Azure Application Permissions : Mail.Send
                var apiUrl = $"https://graph.microsoft.com/v1.0/users/{userEmail}/sendMail"; //Mail.Send
 
                var message = new
                {
                    message = new
                    {
                        subject = "Subject of the email",
                        body = new
                        {
                            content = "Body of the email",
                            contentType = "Text"
                        },
                        toRecipients = new[]
                        {
                        new { emailAddress = new { address = "def@xyz.com" } }
                    }
                    }
                };
 
                var jsonContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");
                httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
 
                var response = await httpClient.PostAsync(apiUrl, jsonContent);
 
                if (response.IsSuccessStatusCode)
                {
                    Console.WriteLine("Email sent successfully.");
                }
                else
                {
                    Console.WriteLine($"Error: {response.StatusCode} - {await response.Content.ReadAsStringAsync()}");
                }
            }
        }
    }
}


//Option 4:
//https://learn.microsoft.com/en-us/entra/identity-platform/v2-oauth-ropc
Microsoft identity platform and OAuth 2.0 Resource Owner Password Credentials
 
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Net.Http.Headers;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    internal class Program
    {
        static async Task Main(string[] args)
        {
            var clientId = "clientId";
            var tenantId = "tenantId";
            var clientSecret = "clientSecret";
            var userName = "userName";
            var userPassword = "userPassword";
            var requestUri = "https://login.microsoftonline.com/" + tenantId + "/oauth2/v2.0/token";
            var apiUrl = "https://graph.microsoft.com/v1.0/me/sendmail";
 
            HttpClient client = new HttpClient();
            HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, requestUri);
            request.Headers.Add("Cookie", "fpc=AohS41ndFd5KswGP3EyyEk11dsNQAQAAADIbQ90OAAAA; stsservicecookie=estsfd; x-ms-gateway-slice=estsfd");
            List<KeyValuePair<string, string>> collection = new List<KeyValuePair<string, string>>
            {
                new KeyValuePair<string, string>("client_id", clientId),
                new KeyValuePair<string, string>("client_secret", clientSecret),
                new KeyValuePair<string, string>("username", userName),
                new KeyValuePair<string, string>("password", userPassword),
                new KeyValuePair<string, string>("grant_type", "password"),
                new KeyValuePair<string, string>("scope", "mail.send")
            };
            FormUrlEncodedContent content = new FormUrlEncodedContent(collection);
            request.Content = content;
            HttpResponseMessage response = await client.SendAsync(request);
            response.EnsureSuccessStatusCode();
            string responseContent = await response.Content.ReadAsStringAsync();
            //Console.WriteLine(responseContent);
            dynamic jsonData = JsonConvert.DeserializeObject(responseContent);
            string accessToken = jsonData.access_token;
            Console.WriteLine(accessToken);
 
            var message = new
            {
                message = new
                {
                    subject = "Subject of the email",
                    body = new
                    {
                        content = "Body of the email",
                        contentType = "Text"
                    },
                    toRecipients = new[]
                    {
                        new { emailAddress = new { address = "user1@gmail.com" } }
                    }
                }
            };
            var jsonContent = new StringContent(JsonConvert.SerializeObject(message), Encoding.UTF8, "application/json");
            client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken);
            HttpResponseMessage response1 = await client.PostAsync(apiUrl, jsonContent);
            if (response1.IsSuccessStatusCode)
            {
                Console.WriteLine("Email sent successfully.");
            }
            else
            {
                Console.WriteLine($"Error: {response1.StatusCode} - {await response1.Content.ReadAsStringAsync()}");
            }
            Console.ReadKey();
        }
    }
}


//Option 5:
Authenticate an IMAP, POP or SMTP connection using OAuth
https://learn.microsoft.com/en-us/exchange/client-developer/legacy-protocols/how-to-authenticate-an-imap-pop-smtp-application-by-using-oauth


Method 1:
using Azure.Identity;
using Microsoft.Graph;
using Microsoft.Graph.Models;
using Microsoft.Graph.Users.Item.SendMail;

public class Program
{
    public static async Task Main(string[] args)
    {
        string tenantId = "tenantid";
        string clientId = "clientid";
        string clientSecret = "secret";
        string userFromEmail = "user1@domain.com";
        string userToEmail = "user2@domain.com";

        var credential = new ClientSecretCredential(tenantId, clientId, clientSecret);
        var graphClient = new GraphServiceClient(credential);
        List<string> userToEmailList = new List<string> { userToEmail };
        var message = new Message
        {
            Subject = "Test Subject",
            Body = new ItemBody
            {
                ContentType = BodyType.Html,
                Content = "Test Body"
            },
            ToRecipients = userToEmailList.Select(email => new Recipient { EmailAddress =             new EmailAddress { Address = email } }).ToList(),
        };
        var sendMailRequest = new SendMailPostRequestBody { Message = message };
        await graphClient.Users[userFromEmail].SendMail.PostAsync(sendMailRequest);         //With out Await and Async         //var sendMailTask = graphClient.Users[userFromEmail].SendMail.PostAsync(sendMailRequest);         //sendMailTask.ConfigureAwait(false).GetAwaiter().GetResult();
        Console.ReadKey();
    }
}

Method 2:
using MailKit;
using MailKit.Net.Imap;
using MailKit.Security;
using Microsoft.Identity.Client;
using MimeKit;
 
class Program
{
    private static async Task Main(string[] args)
    {
        var clientId = "-5a53-4525-afda-";
        var tenantId = "-02f1-478e-bc6a-";
        var clientSecret = "~J2EOPVNjynt-~AHcGN";
        var userEmail = "sreekanth@.onmicrosoft.com";
        var smtpHost = "smtp.office365.com";
        var smtpPort = 587;
 
        var app = ConfidentialClientApplicationBuilder.Create(clientId)
            .WithClientSecret(clientSecret)
            .WithAuthority(new Uri($"https://login.microsoftonline.com/{tenantId}/v2.0"))
            .Build();
       
        string[] scopes = new[] { "https://outlook.office365.com/.default" };
        var authToken = await app.AcquireTokenForClient(scopes).ExecuteAsync();
        var accessToken = authToken.AccessToken;
        //Console.WriteLine("accessToken: " + accessToken);
 
        //oauth2 1
        var oauth2_1 = new SaslMechanismOAuth2(userEmail, authToken.AccessToken);
        using (var client = new ImapClient(new ProtocolLogger("imapLog.txt")))
        {
            client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
            //client.AuthenticationMechanisms.Remove("XOAUTH2");
            client.Authenticate(oauth2_1);
            var inbox = client.Inbox;
            inbox.Open(MailKit.FolderAccess.ReadOnly);
            Console.WriteLine("Total messages: {0}", inbox.Count);
            Console.WriteLine("Recent messages: {0}", inbox.Recent);
            client.Disconnect(true);
        }
 
        //oauth2 2
        var oauth2_2 = new SaslMechanismOAuth2(userEmail, authToken.AccessToken);
        var message = new MimeMessage();
        message.From.Add(new MailboxAddress("Sreekanth", userEmail)); // Your email 
        message.To.Add(new MailboxAddress("Sreekanth", userEmail)); // Replace with recipient's email 
        message.Subject = "Test Email with OAuth2";
        message.Body = new TextPart("plain")
        {
            Text = "This is a test email sent using OAuth2 authentication with SMTP."
        };
 
        using (var client = new MailKit.Net.Smtp.SmtpClient())
        {
            try
            {
                await client.ConnectAsync(smtpHost, smtpPort, SecureSocketOptions.StartTls);
                client.Authenticate(oauth2_2);
 
                await client.SendAsync(message);
                Console.WriteLine("Email sent successfully!");
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Error sending email: {ex.Message}");
            }
            finally
            {
                await client.DisconnectAsync(true);
            }
        }
 
        //oauth2 3
        var oauth2_3 = new SaslMechanismOAuth2(userEmail, authToken.AccessToken);
        using (var client = new ImapClient(new ProtocolLogger("imapLog.txt")))
        {
            client.Connect("outlook.office365.com", 993, SecureSocketOptions.SslOnConnect);
            //client.AuthenticationMechanisms.Remove("XOAUTH2");
            client.Authenticate(oauth2_3);
            var inbox = client.Inbox;
            inbox.Open(MailKit.FolderAccess.ReadOnly);
            Console.WriteLine("Total messages: {0}", inbox.Count);
            Console.WriteLine("Recent messages: {0}", inbox.Recent);
            client.Disconnect(true);
        }
        Console.ReadKey();
    }
}
 

 

Thursday, November 16, 2023

Check AD user using Get-AdUser in Multi Domain Forest

Check AD user using Get-AdUser in Multi Domain Forest

Clear-Host
$UserEmail = 'user1@domain.com'
$Domains = (Get-ADForest).Domains
$DClist = ForEach ($Domain in $Domains) {
     Write-Host "Domain " $Domain
     Get-ADDomainController -DomainName $Domain -Discover -Service PrimaryDC | Select -ExpandProperty hostname
}
$ADUsersList = ForEach ($DC in $DClist) {
     Write-Host "DC: " $DC
     $adUser = Get-ADUser -server $DC -Filter { UserPrincipalName -eq $UserEmail }
     if (!$adUser) {
          Write-Host "`t User $UserEmail not exist" -b Red
     }
     else {
          Write-Host "`t User $UserEmail exist" -b Green
     }
     #Get-ADUser -server $DC -Filter * -Properties *
}
#$ADUsersList | Export-Csv -Path C:\ADUserList.csv -NoTypeInformation
 


Thursday, November 2, 2023

Copy a List in SharePoint Online Using PowerShell

Copy a List in SharePoint Online Using PowerShell

# 1. Copy with in site
$SiteURL = "https://SiteURL/sites/Retail/"
$SourceListName = "MyDocuments"
$DestinationListName = "MyDocuments_New"
 
Try {
  Connect-PnPOnline -Url $SiteURL -Interactive
  Copy-PnPList -Identity $SourceListName -Title $DestinationListName
}
Catch {
  write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
 
 
# 2. Copy to another site with in Site Collection
$SiteURL = "https://SourceSiteUrl/sites/Retail/"
$SourceListName = "MyDocuments"
 
$DestinationSiteURL = "https://DestinationSiteURL/sites/Sales/"
$DestinationListName = "MyDocuments_New"
 
Try {
  Connect-PnPOnline -Url $SiteURL -Interactive
  Copy-PnPList -Identity $SourceListName -Title $DestinationListName -DestinationWebUrl $DestinationSiteURL
}
Catch {
  write-host "Error: $($_.Exception.Message)" -foregroundcolor Red
}
 
 
# 3. Copy to another Site Collection
$SourceSiteURL = "https://SourceSite/sites/one"
$TargetSiteURL = "https://TargetSite/sites/two"
$ListName = "TestList"
$TemplateFile = "C:\\Template.xml"
 
Connect-PnPOnline -Url $SourceSiteURL -Interactive
Get-PnPSiteTemplate -Out $TemplateFile -ListsToExtract $ListName -Handlers Lists
Add-PnPDataRowsToSiteTemplate -Path $TemplateFile -List $ListName
Connect-PnPOnline -Url $TargetSiteURL -Interactive
Invoke-PnPSiteTemplate -Path $TemplateFile

Monday, July 31, 2023

Manage Deployment Slots in App Service using Azure CLI

Manage Deployment Slots in App Service using Azure CLI

az 
az -h 

az group list --output table

resource_group=Regroup_5wlAgklxKkjC6
location=westus
plan_name=brezyweather_plan
app_name=brezyweather

az appservice plan create \
--name $plan_name \
--resource-group $resource_group \
--sku S1 \
--is-linux

az appservice plan list --query "[].name"

az webapp create \
--name $app_name \
--plan  $plan_name \
--resource-group $resource_group \
--deployment-container-image-name codewithpraveen/labs-appservice-cli:1.0

az webapp list --output table

az webapp show \
--name $app_name \
--resource-group $resource_group \
--query "defaultHostName"

az webapp deployment slot create \
--name $app_name \
--resource-group $resource_group \
--slot staging

az webapp deployment slot list \
--name $app_name \
--resource-group $resource_group \
--output table

az webapp config container set \
--name $app_name \
--resource-group $resource_group \
--slot staging \
--docker-custom-image-name codewithpraveen/labs-appservice-cli:2.0

az webapp show \
--name $app_name \
--resource-group $resource_group \
--slot staging \
--query "defaultHostName"

az webapp deployment slot swap \
--name $app_name \
--resource-group $resource_group \
--slot staging \
--target-slot production

az resource delete \
--ids $(az resource list --query "[].id" --resource-group $resource_group --output tsv) \
--verbose

az resource list --resource-group $resource_group

Saturday, April 29, 2023

Git Cheat Sheet

https://training.github.com/

 GitHub Desktop : desktop.github.com

Git for All Platforms : git-scm.com

Configure tooling

Configure user information for all local repositories

$ git config --global user.name "[name]"

Sets the name you want attached to your commit transactions

$ git config --global user.email "[email address]"

Sets the email you want attached to your commit transactions

$ git config --global color.ui auto

Enables helpful colorization of command line output

Create repositories

A new repository can either be created locally, or an existing repository can be cloned. When a repository was initialized locally, you have to push it to GitHub afterwards.

$ git init : The git init command turns an existing directory into a new Git repository inside the folder you are running this command. After using the git init command, link the local repository to an empty GitHub repository using the following command:

$ git remote add origin [url] : Specifies the remote repository for your local repository. The url points to a repository on GitHub.

$ git clone [url] : Clone (download) a repository that already exists on GitHub, including all of the files, branches, and commits

Branches

Branches are an important part of working with Git. Any commits you make will be made on the branch you’re currently “checked out” to. Use git status to see which branch that is.

$ git branch [branch-name] : Creates a new branch

$ git switch -c [branch-name] : Switches to the specified branch and updates the working directory

$ git merge [branch] : Combines the specified branch’s history into the current branch. This is usually done in pull requests, but is an important Git operation.

$ git branch -d [branch-name] : Deletes the specified branch

The .gitignore file

Sometimes it may be a good idea to exclude files from being tracked with Git. This is typically done in a special file named .gitignore. You can find helpful templates for .gitignore files at github.com/github/gitignore.

Synchronize changes

Synchronize your local repository with the remote repository on GitHub.com

$ git fetch : Downloads all history from the remote tracking branches

$ git merge : Combines remote tracking branches into current local branch

$ git push : Uploads all local branch commits to GitHub

$ git pull : Updates your current local working branch with all new commits from the corresponding remote branch on GitHub. git pull is a combination of git fetch and git merge

Make changes

Browse and inspect the evolution of project files

$ git log : Lists version history for the current branch

$ git log --follow [file] : Lists version history for a file, beyond renames (works only for a single file)

$ git diff [first-branch]...[second-branch] : Shows content differences between two branches

$ git show [commit] : Outputs metadata and content changes of the specified commit

$ git add [file] : Snapshots the file in preparation for versioning

$ git commit -m "[descriptive message]" : Records file snapshots permanently in version history

Redo commits

Erase mistakes and craft replacement history

$ git reset [commit] : Undoes all commits after [commit], preserving changes locally

$ git reset --hard [commit] : Discards all history and changes back to the specified commit

CAUTION! Changing history can have nasty side effects. If you need to change commits that exist on GitHub (the remote), proceed with caution. If you need help, reach out at github.community or contact support.

Glossary

  • git: an open source, distributed version-control system
  • GitHub: a platform for hosting and collaborating on Git repositories
  • commit: a Git object, a snapshot of your entire repository compressed into a SHA
  • branch: a lightweight movable pointer to a commit
  • clone: a local version of a repository, including all commits and branches
  • remote: a common repository on GitHub that all team members use to exchange their changes
  • fork: a copy of a repository on GitHub owned by a different user
  • pull request: a place to compare and discuss the differences introduced on a branch with reviews, comments, integrated tests, and more
  • HEAD: representing your current working directory, the HEAD pointer can be moved to different branches, tags, or commits when using git switch


Wednesday, March 15, 2023

SharePoint Edit Control Block (ECB) menu or Custom Action Menu In ListItem and Site

 SharePoint Edit Control Block (ECB) menu or Custom Action Menu In ListItem and Site:

<script
  language="javascript"
  type="text/javascript"
  src="//ajax.googleapis.com/ajax/libs/jquery/1.8.1/jquery.min.js"
></script>
<script language="javascript" type="text/javascript">
  $(document).ready(function () {
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", AddCustomUserActionToECB);
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", ModifyUserCustomAction);
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", DeleteUserCustomAction);
    SP.SOD.executeFunc("sp.js", "SP.ClientContext", CreateUserCustomActionSite);
  });

  function AddCustomUserActionToECB() {
    var clientContext = new SP.ClientContext();
    var oWeb = clientContext.get_web();
    var oList = oWeb.get_lists().getByTitle("testlist");
    var userCustomActionColl = oList.get_userCustomActions();
    var oUserCustomAction = userCustomActionColl.add();
    oUserCustomAction.set_location("EditControlBlock");
    oUserCustomAction.set_sequence(100);
    oUserCustomAction.set_title("Click Here");
    oUserCustomAction.set_url(
      "/sites/pub/Pages/Finance.aspx?ListId={ListId}&ItemId={ItemId}&amp;ItemUrl={ItemUrl}"
    );
    oUserCustomAction.update();
    clientContext.load(userCustomActionColl);
    clientContext.executeQueryAsync(QuerySuccess, QueryFailure);
  }
  function QuerySuccess() {
    console.log("Custom Action added to ECB menu.");
  }
  function QueryFailure() {
    console.log("Request failed - " + args.get_message());
  }

  function ModifyUserCustomAction() {
    var ctx = new SP.ClientContext.get_current();
    var web = ctx.get_web();
    var list = web.get_lists().getByTitle("testlist");
    var CustomActionColl = list.get_userCustomActions();
    ctx.load(list, "UserCustomActions", "Title");
    ctx.executeQueryAsync(
      function () {
        var customActionEnum = CustomActionColl.getEnumerator();
        while (customActionEnum.moveNext()) {
          var custAction = customActionEnum.get_current();
          if (custAction.get_title() == "Click Here") {
            custAction.set_title("Click Here new");
            custAction.update();
            ctx.load(custAction);
            ctx.executeQueryAsync(
              function () {
                alert(
                  "Custom action modified successfully for " + list.get_title()
                );
              },
              function (a, s) {
                alert("Error " + a.get_message());
              }
            );
          }
        }
      },
      function (a, s) {
        alert("Error " + a.get_message());
      }
    );
  }

  function DeleteUserCustomAction() {
    var ctx = new SP.ClientContext.get_current();
    var web = ctx.get_web();
    var list = web.get_lists().getByTitle("testlist");
    var CustomActionColl = list.get_userCustomActions();
    ctx.load(list, "UserCustomActions", "Title");
    ctx.executeQueryAsync(
      function () {
        var customActionEnum = CustomActionColl.getEnumerator();
        while (customActionEnum.moveNext()) {
          var custAction = customActionEnum.get_current();
          if (custAction.get_title() == "Click Here") {
            custAction.deleteObject();
            ctx.load(custAction);
            ctx.executeQueryAsync(
              function () {
                alert(
                  "Custom action deleted successfully for " + list.get_title()
                );
              },
              function (s, a) {
                alert("Error " + a.get_message());
              }
            );
          }
        }
      },
      function (a, s) {
        alert("Error " + a.get_message());
      }
    );

    function CreateUserCustomActionSite() {
      var ctx = new SP.ClientContext.get_current();
      var web = ctx.get_web();
      var CustomActionColl = web.get_userCustomActions();
      var custAction = CustomActionColl.add();
      custAction.set_location("Microsoft.SharePoint.StandardMenu");
      custAction.set_group("SiteActions");
      custAction.set_sequence(101);
      custAction.set_title("site custom action");
      custAction.set_description("Description for custom action.");
      custAction.update();
      ctx.load(web, "Title", "UserCustomActions");
      ctx.executeQueryAsync(
        function () {
          alert("Custom action created successfully for " + web.get_title());
        },
        function (sender, args) {
          alert("Error " + args.get_message());
        }
      );
    }
  }
</script>

<input type="button" value="Create User CustomAction for list" id="create"
    onclick="CreateUserCustomActionList()" /></br ></br >
<input type="button" value="Delete User CustomAction for list" id="Delete"
    onclick="DeleteUserCustomAction()" /></br ></br >
<input type="button" value="Modify User CustomAction for list" id="Modify"
    onclick="ModifyUserCustomAction()" /></br ></br >
<input type="button" value="Create User CustomAction for site" id="Create"
    onclick="CreateUserCustomActionSite()" /></br ></br >
=========================================================
<html>
  <script language="javascript" type="text/javascript">  
    function ClearListItesm(itemID) {
      var ctx = new SP.ClientContext.get_current();
      var web = ctx.get_web();
      var oList = web.get_lists().getByTitle("testlist");
      this.oListItem = oList.getItemById(itemID);
      oListItem.set_item("address", "");
      oListItem.set_item("phone", "");
      oListItem.update();
      ctx.executeQueryAsync(QuerySuccess, QueryFailure);
    }
    function QuerySuccess() {  
        console.log("QuerySuccess");
    }
    function QueryFailure() {        
        console.log("QueryFailure" + args.get_message());
    }
    function getSelectedItemIDs() {
        var items = SP.ListOperation.Selection.getSelectedItems();
        items.forEach(item => {
            console.log(item.id);
            ClearListItesm(item.id);
        });
        location.reload();
    }
  </script>
  <input type="button" value="delete" id="update" onclick="getSelectedItemIDs()"/></br>
</html>
=========================================================

Featured Post

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide

Microsoft Copilot Studio: The Complete Beginner to Advanced Guide Version: July 2026 | Audience: Beginners, Citizen Developers, Busine...

Popular posts