How to remove duplicates from string

To remove duplicate from string values use below formula

<html>

<head>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script>
        $(document).ready(function() {
            $("#btn1").click(function() {
                var result = "Samsung|Galaxy;Apple|iPhone7;Samsung|Note;Apple|iPhone7";
                result = Array.from(new Set(result.split(';'))).toString();
                $("#test1").text(result);

            });

        });
    </script>
</head>

<body>
    <p id="test1">This is a paragraph.</p>    
    <button id="btn1">Check Duplicate Value </button>
</body>

</html>

INPUT STRING: Samsung|Galaxy;Apple|iPhone7;Samsung|Note;Apple|iPhone7
OUTPUT/ RESULT STRING: Samsung|Galaxy,Apple|iPhone7,Samsung|Note

Create Web API using CORS [Cross-Origin Resource Sharing]

This post will demonstrate you to create Web API, which can be, accessed across different domain also known as CORS (Cross-Origin Resource Sharing).

Create Visual Studio Solution.

Select Visual Studio Web Application Project.

I am going to keep name as Nilesh.WebAPISQLCORS as this Web API will call SQL Server Stored Procedure to Insert Data into SQL Table.

Select Project Type Empty and Core reference as Web API.

Click OK.

It will create Project Solution as shown in below image.

Now let’s add Controller Action.

Select Web API 2 Controller Empty

Click on Add. Now Add a Name for Controller. I am going to keep name as Employee

It will add controller class in folder as shown below

Now lets adds method for Get and Post Action

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;

namespace Nilesh.WebAPISQLCORS.Controllers
{
    public class DataInfo
    {
        public string Name { get; set; }
        public string Email { get; set; }
        public string ContactNumber { get; set; }
    }
    public class EmployeeController : ApiController
    {
        string connectionString = System.Configuration.ConfigurationManager.AppSettings["SQLServerConnectionString"];

        // GET: api/New
        public IEnumerable<string> Get()
        {
            return new string[] { "value1", "value2" };
        }

        // POST: api/New
        [ActionName("AddEmployee")]
        [HttpPost]
        public string Post([FromBody]DataInfo value)
        {
            using (SqlConnection con = new SqlConnection(connectionString))
            {
                SqlCommand cmd = new SqlCommand("spInsertEmployee", con);
                cmd.CommandType = CommandType.StoredProcedure;

                cmd.Parameters.AddWithValue("@Name", value.Name);
                cmd.Parameters.AddWithValue("@Email", value.Email);
                cmd.Parameters.AddWithValue("@ContactNumber", value.ContactNumber);

                con.Open();
                cmd.ExecuteNonQuery();
                con.Close();
            }

            return "Item successfully added.";
        }
    }
}

Note that I have already added SQLServerConnectionString Configuration in Web.Config File.

Now we need to add Web API Cors so that we can access it from Cross Origin in other words from other application.

To add CORS in Web API navigate to Manage Nuget Packages

Navigate to Browse and search for CORS. Select Microsoft.AspNet.WebAPI.Cors Package and Click on Install

It will show you changes which will update solution

Click on OK button

Next Accept License

Once you accept License it will Add Cors and update Dll Reference in Project you can check this progress in Output Window.

Now lets add Configuration for Cors in WebApiConfig.cs File

Add Below Code to Enable Cors


EnableCorsAttribute cors = new EnableCorsAttribute("*", "*", "*");
config.EnableCors(cors);

Note that to add EnableCorsAttribute you need to add reference for System.Web.Http.Cors

Also in EnableCorsAttribute Method, you can pass parameter for Specific Origin and action whom you want to allow from different origin for demo purpose I have added * which means allow all for everything , in real scenario you can specify parameter name as per your requirement

By applying this code now our WEB API is ready to access it from other origin, hit F5 to test it.

You can check Get Action Response using URL: http://localhost:47965/api/Employee
(You need to change application Port number from URL)

Now to check POST request let use Postman

Make sure you pass input parameter value and Action name in Poster as shown in below Image

Sample JSON Parameter Format


{ Name: "Nilesh Rathod", Email: "njrathod@gmail.com" , ContactNumber: "+919825899769" }

Once you enter all information in Postman Click on Sent button it will post all required information to WebAPI and create record using AddEmployee Action in SQL Server.You can also get Action response in Body Section as Shown in an Image.

Now lets host our Web API to any other location instead of localhost and can share its url to other application so that they can use it.

Note that this code is not for Production Purpose, as it has not implemented with other features.

For demonstration, I have hosted this Web API Project on Azure Environment.

I have taken Azure trial for demonstration Lets check our Azure Web APP.

Next Download Publishing Profile for Web APP (which we need to use in next step to publish application )

Next Click move to Visual Studio Web API Project and Click on Publish.

Pick Azure Publish Target and Import profile which we download in previous step.

Once you select profile, it will immediately start publishing.You can see its progress in Output Window

Next step is to check Get Request

We are able to receive response. Now let’s try Post Request using Postman

It confirms that Web API is working as per expectation on Production Environment.

SharePoint Online – How to Call Web API (Cross Origin)

Let’s see how to call Cross Origin Web API, which insert item in SQL Server Database.

Note that here key important thing is Web API, which accepts Cross Origin Request, and insert data into SQL Server. If you are not aware about how to create Web API using CORS, please check my article on How to Create WEB API using CORS.

This article will help you to call Web API using jQuery (web API insert Data into SQL Server Database)

I have created Page in Pages Library named “AddEmployeeSQL.aspx”

I have also created CustomScript named folder inside Style Library, which will hold webapi.txt – custom txt file, which includes jQuery and html content.

Content For webapi.txt File is as below.

<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-2.0.3.min.js"></script>

<div style="font-family:Verdana;font-size:11px">
    <h3>SharePoint Online - WebAPI - SQL Insert Operation</h3>
    <div>
        <table>
            <tr>
                <td>Name : </td>
                <td>
                    <input type="text" name="txtName" class="txtName" />
                </td>
            </tr>
            <tr>
                <td>Email : </td>
                <td>
                    <input type="text" name="txtEmail" class="txtEmail" />
                </td>
            </tr>
            <tr>
                <td>Contact No: </td>
                <td>
                    <input type="text" name="txtContact" class="txtContact" />
                </td>
            </tr>
            <tr>
                <td></td>
                <td>
                    <input type="button" value="Create" id="btnSave" />
                    <div id="loadingPanel" style="color:green; font-weight:bold;display:none;">Data Saving...</div>
                </td>
            </tr>
        </table>
    </div>
</div>
<script>
    $(document).ready(function () {

        $('#btnSave').click(function () {

            var name = $('.txtName').val();
            var email = $('.txtEmail').val();
            var contact = $('.txtContact').val();

            $.post("https://d2aa8fbe-0ee0-4-231-b9ee.azurewebsites.net/api/Employee", { Name: name, Email: email, ContactNumber: contact })
                .fail(function () {
                    alert("An Error Occured while saving record.");
                })
                .done(function (data) {
                    alert("Sucess: " + data);
                });
        });
    });
</script>

Now save this code in Webapi.txt (you can give your preferred name to file) file and upload it to Custom Script folder

Next Edit AddEmployeeSQL.aspx Page and add Content Editor Web Part.

Now Edit Content Editor Web Part and assign script reference

Save Page (check in and Publish it) and we are ready to check functionality.

Fill required Information and Click on Create Button.

You can see it will create record in SQL Server Database.

Hence, we can conclude that it’s really very easy to use Cross Origin Web API and using SharePoint Online jQuery Method.

How To Create A Hub Site in SharePoint Online

To Create Hub Site in SharePoint Online follow below steps

Crete SharePoint Site

I have created SharePoint Site URL: https://nrsharepoint.sharepoint.com/sites/Contoso

Now Open SharePoint Online Management Shell and run below commands


Connect-SPOService -Url "https://nrsharepoint-admin.sharepoint.com"    

Make Sure you need to pass admin site url in my case it is “nrsharepoint-admin” while connecting using SPOService

It will ask your Credentials for the site.

Once you are able to login add below powershell commnad to register your given site as Hub Site.


Register-SPOHubSite -Site "https://nrsharepoint.sharepoint.com/sites/Contoso"   

Once you run above command it will ask you Principals[0]: parameter value do not pass anything for that value.

After Successfully execution of commnad it will Convert or Connect Existing Site to Hub Site

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

Angular 2 : How to Pass data from Child Component to Parent Component

To Pass Data From Child Component to Parent and Parent Component to child Component use below code

I have Created 2 Component Parent and Child as shown in below Image

I added TextBox on Child Component and needs to use its value on parent Component

HTML For Child Component is as below


    <div class="container">
    <h2>Child Component</h2>
    <div class="form-group">
        <label for="email">Product Code:</label>
        <input type="text" #txtProductCode (keyup)="PassValueToParent(txtProductCode.value)">
    </div>
    <button type="submit" class="btn btn-primary">Submit</button>
    </div>


Now to pass value of txtProductCode to parent we need to get TextBox Value and and pass its value
on EventEmitter with Output Parameter

Code for child.component.ts


import { Component, OnInit ,Output, EventEmitter} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  constructor() { }

  @Output() childEmitter = new EventEmitter<string>();

  PassValueToParent(val:string)
  {    
    this.childEmitter.emit(val);
  }

  ngOnInit() {
  }

}


As shown in above code we imported Output and EventEmitter from @angular/core. Then we have created
new Event emitter @Output() childEmitter = new EventEmitter();
Here PassValueToParent gets updated txtProductCode Value on its keyup event and finaly function emit it.

We need to use same Output variable on Parent Page

Parent Page HTML will look like below code



<div class="container">
  <h2>Parent Component</h2>
  <div class="form-group">
    <label for="email">Value From Child Component :: {{parentVariable}}</label>
  </div>
</div>
<hr>
<app-child (childEmitter)='parentVariable=$event'></app-child>

Code For parent.component.ts

import { Component, OnInit } from ‘@angular/core’;

@Component({
selector: ‘app-parent’,
templateUrl: ‘./parent.component.html’,
styleUrls: [‘./parent.component.css’]
})
export class ParentComponent implements OnInit {

constructor() { }

parentVariable:string;

ngOnInit() {
}
}

In above code childEmitter is the name of emitter whhich we declare in Child Component
and parentVariable is a local variable in Parent Component

Once you implement above code you are able to pass value from Child Component to Parent Component as shown in below Image

Now Lets Pass Data From Parent Component to Child Component

Here important thing is @Input variable in Child Component which we need to declare

Code For Parent Component HTML

<div class="container">
  <h2>Parent Component</h2>
  <div class="form-group">
      <label for="text">Parent Name:</label>
      <input type="text" #txtParnetName (keyup)="SetParentName(txtParnetName.value)">
  </div>
</div>
<hr>
<app-child [childParentName]="parentName" ></app-child>
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {

  constructor() { }

  parentName:string;

  SetParentName(textValue:string)
  {
    this.parentName = textValue;    
  }

  ngOnInit() {
  }
}

As shown in above Image we can see that we have pass value of Parent Component variable parentName in [childParentName] . Here [childParentName] is @Input variable for Child Component.

Code For Child Component

import { Component, OnInit , Input} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {

  constructor() { }

  @Input() childParentName:string;

  ngOnInit() {
  }

}

HTML for Child Component

<div class="container">
  <h2>Child Component</h2>
  <div class="form-group">  
      Name comes From Parent Component : <b> {{childParentName}} </b>
    </div>
</div>

Once you implemnent above code you are able to pass value from Parent Component to Child Component
as shown below.

SharePoint Framework SPFX On SharePoint Server 2016

To use SharePoint Framework SPFX on SharePoint Server 2016 we need to install SharePoint 2016 Feature Pack 2.

SharePoint 2016 Feature Pack 2 supports SharePoint Framework client-side web parts hosted in classic SharePoint pages.

SharePoint 2016 Feature Pack 2 supports SharePoint Framework client-side web parts hosted on classic SharePoint pages built by using the SharePoint Framework v1.1.0. This means that when you are targeting the SharePoint 2016 platform, you need to use the SharePoint Framework v1.1.0 due to the server-side version dependencies.

Install following prerequisite to develop SharePoint Framework SPFX.

  • Nodejs (Download Link: https://nodejs.org/en/) Make sure you install node version 6.11.2
  • Gulp Version 3.9.1
  • Yeoman Template Generator 2.0.2
  • NPM Version 3.10.10
  • SharePoint Framework Yeoman Generator Version 1.0.2
  • Visual Studio Code or any other editor (Visual Studio Code: https://code.visualstudio.com)

Please make sure that you install Microsoft Template Generator Version 1.0.2 any other version will not work for SharePoint 2016 On Premise.

My Environment:

Installation of Yeoman Template Generator

Installed Package Version

Package Installation Command


npm install -g yo gulp


	npm install npm@3.10.10


npm install -g @microsoft/generator-sharepoint@1.0.2

Create New SPFX Solution using command


yo @microsoft/sharepoint

Give Solution Name, Web Part Name and other required information as shown in Image

Once Solution is created it will appear as shown below

Now let’s make changes in created solution. You can open it using command


code .

Once you enter command it will open in Visual Studio Code Editor.

We are going to update HTML Code in file: HelloSpfxWebPart.ts

You can reach HelloSpfxWebPart.ts file from solution location SPFX\src\webparts\helloSpfx\HelloSpfxWebPart.ts

I have added my name”Nilesh Rathod” in html text/tag.

You can make changes as per your requirement.

Now next task is to test SPFX Solution/WebPart on SharePoint Server environment.

Before that we are going to run command “gulp trust-dev-cert” so that when we run our SPFX webpart on local machine it will not give Certificate Error


gulp trust-dev-cert

After that you can add command “gulp serve” to run this SPFX Solution/WebPart on local environment.

When you run gulp serve command it will open browser with URL: https://localhost:4321/temp/workbench.html which contains modern UI for SharePoint Web Part.

Here you can insert web part as shown in image

Once you add Web Part on Page, it will appear as per our updated changes.

Now we are able to Create and Run Web Part on SharePoint Server 2016 environment.

Next step is to deploy it on SharePoint Server Environment.

Deployment of SPFX WebPart on SharePoint Server 2016

Now when we are going to deploy WebPart on SharePoint Server we also needs to keep on mind that we need to add its related js file or configuration file which is required to run that SPFX application.

When we build our WebPart it will create its configuration file which are required on server to run it without any dependency.

While working with SharePoint Framework WebPart we can assign that location name from where it can read files when we are going to deploy it on any server.

That configuration is called CDN Path which is available in Configuration -> write-manifests.json file.

I have created Document Library named MySPFXFiles on my site location http://sps2012:4444/MySPFXFiles where I can add all required files which will be my CDN Address for SPFX Web Part.

You can set your own document library on your application and can use it as CDN Address.

We can set CDN Path as shown in image

After adding CDN Path let’s ship solution by running command



gulp bundle --ship


This builds the minified assets required to upload to the CDN provider. The –ship indicates the build tool to build for distribution. You should also notice that the output of the build tools indicate the Build Target is SHIP.

Next run command


gulp package-solution --ship

This creates the updated client-side solution package in the sharepoint\solution folder.

Once we run above command it will prepare 2 locations which we needs to consideration for actual deployment on server.

  • One location is “SPFX\sharepoint\solution” where our actual app package file “spfx-soln.sppkg” is generated.
  • Another location is “SPFX\temp\deploy” where all other mandatory file to run SPFX WebPart is generated.

Note that we can easily check or configure “temp\deploy” folder location in solution copy-assets.json file which is location at SPFX\config\copy-assets.json.

Now let’s copy all files on required file from temp\deploy folder to SharePoint Serve.

Open Solution in Folder. You can open it from command prompt also using command

explorer .

Navigate to Temp Deploy Folder Location: SPFX\temp\deploy

Here SharePoint 2016 will not allow to copy JSON file to SharePoint as it is blocked by environment. To enable it please check my post for Allow JSON to SharePoint 2016.

Copy all files and upload into SharePoint CDN Location which we already mentioned in above steps.

In my case it is : http://sps2012:4444/MySPFXFiles

I have copied all files on CDN address as shown in above Image.

Once all required file is copied next step is to deploy app on SharePoint App Catalog

If you are not aware How to Configure SharePoint App Catalog or How to setup App Domain on SharePoint Server you may refer to my post.

SharePoint Server 2016 Configure APP Domain

and

SharePoint Server App Catalog Configuration

Navigate to SPFX\sharepoint\solution location

Now Upload App File spfx-soln.sppkg on SharePoint App Catalog

When you upload package it will ask us to deploy application. You can click on Deploy button and trust application. You may also check your given CDN address is also available on application.

Once you click Deploy, SPFX Solution will deploy on SharePoint Server 2016 you can also check is Deployed Column value as shown in below Image

Once Application is deployed in App Catalog Site it will available in your desired site under Your Application -> Application From your Organization

Click on that app and it will install on server. You can see Installed application as shown in below image

Now you can add SPFX WebPart on any page.

I have created page named SPFXAPP.aspx Edit Page and Click on Insert Web Part Link . You may find SPFX WebPart in “Under Development” section.

Add HelloSPFX WebPart on Page and it will appear as shown in below Image.

Check In and Publish Page.

Hence we learn How to Create SPFX Solution on SharePoint Server 2016 Environment and Deployment Of SharePoint Framework WebPart or Solution on SharePoint Server 2016.