Update Application Pool Password using PowerShell Script

By using below script we can update Passwod of Specific User for all his assigned Application Pool

PowerShell Script:


Import-Module WebAdministration
$applicationPools = Get-ChildItem IIS:\AppPools | where { $_.processModel.userName -eq "SPServer\administrator" }
 
foreach($pool in $applicationPools)
{
    $pool.processModel.userName = "SPServer\administrator"
    $pool.processModel.password = "sp#123@admin"
    $pool.processModel.identityType = 3
    $pool | Set-Item
}
 
Write-Host "Password Sucessfully Updated." -ForegroundColor Magenta 
Write-Host "" 

log4net With SharePoint 2016

Log4net library is a tool to help the programmer output log statements to a variety of output targets.

You may use below steps to configure Log4Net in SharePoint 2016 On Premise.

For this demonstration I have used my SharePoint Site: http://sps2012:1111/Pages/default.aspx

First Create SharePoint Solution

Next select Deploy as Farm Solution as we need to Deploy Log4Net DLL on our SharePoint Server GAC.

Here I am going to create 2 separate projects. 1 For Logging Application and 2 for SharePoint Web Parts where we can create our web parts. We can modify Logging Project as per our requirement without making any kind of changes in Web Parts Project.

Next let’s install Log4Net using NuGet Package Manager

Select Project -> Right Click on Project – >Select Manage NuGet Packages

Search Or Browse for log4net by Apache Software Foundation

Click on Install

When you click on Install it will preview changes which is going to be added in project

Click on Ok and it will install log4Net in Project

After Installation we are able to see Log4Net reference in project

Next Step is to build solution

Once we build solution we are able to see log4net.dll in Debug folder of solution.

Now we need to use this DLL: log4net.dll in SharePoint Web Part Project. So that we can create web part and check Logging Functionality.

Create WebPart in SP.WebParts Projects.

I have added WebPart and also updated its information as shown in Image

Now we need to refer Log4Net.dll in project

Navigate to Project -> References -> Right Click on Add Reference

It will open window. Click on Browse and select log4Net.dll file. Make sure you select correct file which we have added in SP.Log4Net.Solution Project. You can also copy log4Net.dll from bin folder and keep it on your desired location where you can assign reference to project.

Once you click on Ok it will add reference in Web Parts Project.

For Demonstration purpose I am going to add button on Visual Web Part and on its click event going to add Log Information so that we can create log using log4Net.dll file.

I have added button into web part and added Log Information. Now we are able to deploy this solution on SharePoint.

Also we need to keep in mind that Log4Net.Dll is also needs to deploy with Visual Web Part so that SharePoint Server can refer it in application.

To add custom dll reference in SharePoint Select Package and Open it.

Navigate to Advance

Click on Add Existing Assembly (As we already have log4Net.dll)

And select log4Net.dll from your project or saved directory location

Click on OK and this will add log4Net.dll in project’s package which eventually deploys dll in GAC.

Save Project and deploy it

Till now we have added log4Net.dll into project and its reference for logging mechanism. But we also needs to configure require information for Log4Net.

We can configure Log4Net configuration in SharePoint Web Application Web.Config and global.asax File.

As you are aware that we are using our SharePoint Application: : http://sps2012:1111/Pages/default.aspx

Next Navigate to C:\inetpub\wwwroot\wss\VirtualDirectories\1111 where we are able to find global.asax and web.config file.

Add Following code in global.asax


<%@ Assembly Name="Microsoft.SharePoint"%><%@ Application Language="C#" Inherits="Microsoft.SharePoint.ApplicationRuntime.SPHttpApplication" %>
<%@ Assembly Name="log4net, Version=2.0.8.0, Culture=neutral, PublicKeyToken=669e0ddf0bb1aa2a" %>
<%@ Import Namespace="log4net" %>
<%@ Import Namespace="log4net.Config" %>
<%@ Import Namespace="System.IO" %>

<script language="C#" runat="server">
void Application_Start(object sender, EventArgs e)
    {      
		log4net.Config.XmlConfigurator.Configure(new FileInfo("C:\\inetpub\\wwwroot\\wss\\VirtualDirectories\\1111\\web.config"));     
    }
</script>


Note: If you are getting an error while adding log4net dll information in Global.asax then it may be due to dll is not added in GAC.
You may read my post regarding How to Add DLL in GAC and How to Get DLL Publickeytoken

Now let’s updateWeb.Config File

Open Web.config file

And add below section in “<configSections>”


<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler, log4net" requirePermission="false" />

Also Add below configuration in “<configuration>” section


<log4net>
    <appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
      <file value="C:\Program Files\Common Files\microsoft shared\Web Server Extensions\16\LOGS\log4net\Logs\ApplicationLog" />
      <appendToFile value="true" />
      <rollingStyle value="Composite" />
      <datePattern value=".yyyyMMdd-HHmm" />
      <lockingModel type="log4net.Appender.FileAppender+MinimalLock" />
      <layout type="log4net.Layout.PatternLayout">
        <conversionPattern value="%date [%thread] %-5level %logger - %message%newline" />
      </layout>
    </appender>
    <root>
      <level value="ERROR" />
      <appender-ref ref="RollingFileAppender" />
      <appender-ref ref="SmtpAppender" />
    </root>
  </log4net>

Note that you can change or update this log4Net configuration as per your own requirement.I have added Configuration value so that I can create log on each minute with dynamic file name added HHMM value.

Now we are done with all configurations and it’s time to test functionality.I have created Page named “CustomLog.aspx” and added web part Custom Log on it.

Now when we click button Add Log Information it will create log with string “Log Detail Information” on our mentioned location. Make sure here location is file Creation location which we have mentioned in web.config file for log4net configuration.

Once you click button you can see log as below

Also note that I have configured log mechanism as per each minute so that we can create or see log on each and every minute as shown in below image

From above steps we learn how we can configure log4Net with SharePoint 2016.

How to Get PublicKeyToken for DLL

We can easily get PublicKeyToken of any dll file using Powershell command (Make sure you run your powershell command prompt or any other editor as Run As Administrator)

Commnad:


([system.reflection.assembly]::loadfile("C:\Users\Administrator\Documents\log4net.dll")).FullName

In Above Example I am getting path for dll log4net.dll which is located on Path : C:\Users\Administrator\Documents\log4net.dll

C# Thread.Sleep Method With Console Foreground Text Color

We can change Console Text Color using Console.ForegroundColor propety.

Below code give an idea and usage of System.Thread in application.

 
using System;

namespace ConsoleApp2
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.ForegroundColor = ConsoleColor.Yellow;
            Console.WriteLine("Application Execution Process Start");

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Thread Process Start On " + DateTime.Now.ToString("ddMMyyyy  hh:mm:ss"));

            for (int i = 1; i < 6; i++)
            {
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("********************* Thread Sleep Start **********************");
                System.Threading.Thread.Sleep(5000);
                Console.ForegroundColor = ConsoleColor.Cyan;
                Console.WriteLine("Sleeping for Item " + i.ToString() + " Thread is Exexuing on Inteval of 5 Seconds " + DateTime.Now.ToString("ddMMyyyy  hh:mm:ss"));
                Console.ForegroundColor = ConsoleColor.Gray;
                Console.WriteLine("********************* Thread Sleep End ************************");
            }

            Console.ForegroundColor = ConsoleColor.Green;
            Console.WriteLine("Thread Process End On " + DateTime.Now.ToString("ddMMyyyy  hh:mm:ss"));

            Console.ForegroundColor = ConsoleColor.DarkYellow;
            Console.WriteLine("Application Execution Process End");

            Console.Read();
        }
    }
}

Output:

SharePoint Get GUID Of List and Columns

While developing SharePoint solution code we require GUID of List and Columns Id.We can easily get this using below format

Custom List:

Note that this list has 2 columns
1.Title
2.Target
To view GUID for this list Navigate to list settings.

Once we Navigate to List settings we are able to see below URL. Copy Full URL from browser

https://onsps.sharepoint.com/_layouts/15/listedit.aspx?List=%7B2CB2E87A-04CD-445A-9201-4F41FD8EF9A1%7D 

Replace the following characters as follows:
%7B to {
%2D to –
%7D to }

Once you replace above encoded character then list GUID will available which is {2CB2E87A-04CD-445A-9201-4F41FD8EF9A1}

To View all Columns and files inside this list change or append URL as below

https://onsps.sharepoint.com/_vti_bin/owssvr.dll?Cmd=ExportList&List=2CB2E87A-04CD-445A-9201-4F41FD8EF9A1

When we type above url it will open or download xml file which file has all information regarding list and its columns with GUID.

Here SourceID indicates GUID for List and ID indicates Column ID.

SharePoint: CRUD Operation using SPServices

Fill Drop Down List:

<script language="javascript" type="text/javascript">

/* ----------- Bind Dorp Down List - Country Begin -------------*/
var SPSiteURL = "https://yourSharepointsiteURL/Site";
 
        $().SPServices({
            webURL: SPSiteURL,
            operation: "GetListItems",
            async: false,
            listName: "Country",
            CAMLQuery: "<Query><OrderBy><FieldRef Name='Title'/></OrderBy><Where><Eq><FieldRef Name='Active'/><Value Type='Boolean'>1</Value></Eq></Where></Query>",
            CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /></ViewFields>",
            completefunc: function(xData, Status) {
                $(xData.responseXML).SPFilterNode("z:row").each(function() {
                    var DataTextField = $(this).attr("ows_Title");
                    var DataValueField = $(this).attr("ows_ID");
                    listItem = "<option value=" + DataValueField + ">" + DataTextField + "</option>"
                    $("#ddlCountry").append(listItem);
                });
            }
        });
/* ----------- Bind Dorp Down List - Country End -------------*/
</script>

Above Code will get items from Country DropDownList where Active = True

Save:
Bind Save Button Event & Code to Save Data.

<script language="javascript" type="text/javascript">

//Submit Button Click Event
    $("#btnSubmit").click(function() {
        return SaveEmployeeInfo();
    });

/* ----------- Save Employee Info Form Code Begin -------------*/
function SaveEmployeeInfo()

{
    console.log("Save Process Begin");
    //alert("Save Event");

    var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    console.log("City = " + City);   

    console.log("Save Process Begin");

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get Item CreationInfo 
    var itemCreateInfo = new SP.ListItemCreationInformation();

    //Add Item Object
    this.oListItem = oList.addItem(itemCreateInfo);

    //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);
	

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onSaveQuerySucceeded), Function.createDelegate(this, this.onSaveQueryFailed));

    return false;
}

function onSaveQuerySucceeded() {

    console.log('Item created: ' + oListItem.get_id());
}

function onSaveQueryFailed(sender, args) {

    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}

</script>

Update: Bind Update Button Event & Code to Update Data

<script language="javascript" type="text/javascript">


/* ----------- Update Employee Info By EmpID Code Start-------------*/
function UpdateEmployeeInfo() {
    
	//alert("Update Operation Begin");
	
    var EmpID = getParameterByName('EmpID');
	
	var EmployeeName = $("#txtEmployeeName").val();
    var City = $("#ddlCity option:selected").text();
    City = (City != '-Select-') ? City : '';
	console.log("City = " + City);  
   
	var Agreement = false;
    Agreement = $('#chkAgreement').is(':checked');
   
    var Hobbies = [];
    $('#chkHobbies input:checked').each(function() {
        Hobbies.push($(this).attr("id"));
    });
    var Hobbies = Hobbies.toString();
	
	var BirthDate = $("#txtBirthDate").val();
	if (!BirthDate) {
        BirthDate = null;
    } else {
        BirthDate = BirthDate;
    };

    //Get Client Context
    var clientContext = new SP.ClientContext.get_current();

    //Get List From Site
    var oList = clientContext.get_web().get_lists().getByTitle('EmployeeInfo');

    //Get List Item By ID 	
    this.oListItem = oList.getItemById(EmpID);

   //Set Item Values 
    oListItem.set_item('Title', 'From JavaScript Code');
    oListItem.set_item('EmployeeName', EmployeeName);
    oListItem.set_item('City', City);
    oListItem.set_item('Agreement', Agreement);   
    oListItem.set_item('Hobbies', Hobbies);
	oListItem.set_item('BirthDate', BirthDate);

    //Add Item in List
    oListItem.update();

    //Load and Execute Item Change
    clientContext.load(oListItem);

    clientContext.executeQueryAsync(Function.createDelegate(this, this.onQueryAuditUpdateSucceeded), Function.createDelegate(this, this.onQueryAuditUpdatedFailed));

    return false;


}

function onQueryAuditUpdateSucceeded() {

    console.log('Item Updated Successfully');
}

function onQueryAuditUpdatedFailed(sender, args) {

    console.log('Request failed. ' + args.get_message() + '\n' + args.get_stackTrace());
}
/* ----------- Update Employee Info By EmpID Code End-------------*/

</script>


Retrieve Employee Data : Code to Retrieve Data

<script language="javascript" type="text/javascript">

/* ----------- Retrieve Employee Data Code Starts -------------*/
function GetemployeeData(EmpID) {
    $().SPServices({
        webURL: SPARPSiteURL,
        operation: "GetListItems",
        async: false,
        listName: "EmployeeInfo",
        CAMLQuery: "<Query><Where><Eq><FieldRef Name='ID' /><Value Type='Integer'>" + EmpID + "</Value></Eq></Where></Query>",
        CAMLViewFields: "<ViewFields><FieldRef Name='Title' /><FieldRef Name='ID' /><FieldRef Name='EmployeeName' /><FieldRef Name='City' /><FieldRef Name='Agreement' /><FieldRef Name='Hobbies' /><FieldRef Name='BirthDate' /></ViewFields>",

        completefunc: function(xData, Status) {
            $(xData.responseXML).SPFilterNode("z:row").each(function() {

                console.log("ows_Title " + $(this).attr("ows_Title"));
                console.log("ID " + $(this).attr("ows_ID"));
                console.log("EmployeeName " + $(this).attr("ows_EmployeeName"));
                console.log("City " + $(this).attr("ows_City"));
                console.log("Agreement " + $(this).attr("ows_Agreement"));
                console.log("Hobbies " + $(this).attr("ows_Hobbies"));
                console.log("BirthDate " + $(this).attr("ows_BirthDate"));
              
                var City = $(this).attr("ows_City");
                $("#ddlCity").find("option:contains('" + City + "')").each(function() {
                    if ($(this).text() == City) {
                        $(this).attr("selected", "selected");
                    }
                });


                $("#txtEmployeeName").val($(this).attr("ows_EmployeeName"));

                var date = new Date($(this).attr("ows_BirthDate"));
                if (!date) {
                    var currentMonth = date.getMonth() + 1;
                    if (currentMonth < 10) {
                        currentMonth = '0' + currentMonth;
                    }
                    var currentDate = date.getDate();
                    if (currentDate < 10) {
                        currentDate = '0' + currentDate;
                    }
                    var PrePlanStartDate = (currentDate) + '/' + currentDate + '/' + date.getFullYear();
                    $("#txtBirthDatee").val(PrePlanStartDate);
                }

                if ($(this).attr("ows_Agreement") == 1) {
                    $('#chkAgreement').attr('checked', 'checked');
                };

                //---------Hobbies Check Box List
                console.log("Hobbies Value " + $(this).attr("ows_Hobbies"));
                var Hobbies = $(this).attr("ows_Hobbies");

                var arrayTeam = Hobbies.split(',');
                //console.log("Array Value" + arrayTeam);

                for (var i = 0; i < arrayTeam.length; i++) {
                    var chkValue = arrayTeam[i];
                    $("#chkHobbies input:checkbox").each(
                        function() {
                            if ($(this).attr("id") == chkValue) {
                                $(this).prop("checked", true);
                            }
                        }
                    );
                }

            });
        }
    });
}
/* ----------- Retrieve Employee Data Code Ends -------------*/
</script>

How to Create and Export Self-Signed Certificate

To create Self-Signed Certificate using IIS follow below steps.

Navigate to IIS

Select Server Certificate

Click on “Create Self-Signed Certificate” link

Enter the details as shown below.

Click on OK.

Do IISRESET

Now Certificate will be available in Server Certificates.

You can check by editing any existing binding

Save Certificate :

Double click on the Certificate in IIS.

Click on Details tab and click on Copy to File.

Now Certificate Export Wizard will available.

Click Next

Click Next Give Certificate Name.

Click Next

Click Finish

It will display message “The export was successful.”

Export Certificate in Personal Exchange Format (.pfx)

Navigate to IIS

Select the Certificate which you want to export.

Click on Export

Give Certificate Export Location and Certificate Name

Enter Password and Confirm Password.

Click on OK.

It will Export Certificate in PFX format.