0

Add New Theme in Modern Site

Steps to follow change the theme in SharePoint online modern sites

Step 1:

First, make sure you have the latest version of the SharePoint Online Management Shell

Step 2:

Connect environment to power shell

 $adminUPN=”<Admin User Name>” e.g. demo@test.onmicrosoft.com 

$orgName=”<name of your Office 365 organization>” e.g. test

$userCredential = Get-Credential -UserName $adminUPN -Message “Type the password.” 

Connect-SPOService -Url https://$orgName-admin.sharepoint.com -Credential $userCredential

Step 3:

Run below command to check version of SharePoint management shell.

 Get-SPOHideDefaultThemes

If you do NOT get an error, but get either “true” or “false,” then you can continue. If you DO get an error, then uninstall your version of the SharePoint Online Management Shell and then download and install the latest version

Step 4:

Go to Microsoft’s online tool for generating Modern theme colors. Play with the sliders or enter in your own color codes for the primary, body, and text colors. Scroll down to the bottom part of the page to see how your color choices affect the UI elements.

selectcolor

powershellcode

Step 5:

Highlight and copy the Power Shell variables. (If you want a multi-colored theme, you won’t be able to make any additional custom changes to the colors in this interface, but you can copy the code into a text editor and make manual changes to the variables there.

Step 6:

Run PowerShell Command as below

$themepalette = @{

“themePrimary” = “#927098”;

“themeLighterAlt” = “#f7f5f8”;

“themeLighter” = “#ece5ed”;

“themeLight” = “#d0c1d3”;

“themeTertiary” = “#ae95b2”;

“themeSecondary” = “#98779d”;

“themeDarkAlt” = “#85648b”;

“themeDark” = “#5f4763”;

“themeDarker” = “#523d55”;

“neutralLighterAlt” = “#f8f8f8”;

“neutralLighter” = “#f4f4f4”;

“neutralLight” = “#eaeaea”;

“neutralQuaternaryAlt” = “#dadada”;

“neutralQuaternary” = “#d0d0d0”;

“neutralTertiaryAlt” = “#c8c8c8”;

“neutralTertiary” = “#d0c1d3”;

“neutralSecondary” = “#ae95b2”;

“neutralPrimaryAlt” = “#98779d”;

“neutralPrimary” = “#927098”;

“neutralDark” = “#5f4763”;

“black” = “#523d55”;

“white” = “#ffffff”;

“primaryBackground” = “#ffffff”;

“primaryText” = “#927098”;

“bodyBackground” = “#ffffff”;

“bodyText” = “#927098”;

“disabledBackground” = “#f4f4f4”;

“disabledText” = “#c8c8c8”;

}

Add-SPOTheme -Name “Your Theme Name” -Palette $themepalette -IsInverted $false

Step 6:

That’s it! This now adds the theme to your tenant, and you can access it from the “Change the look” panel. 

HaPpy Coding 🙂

 

Advertisements
0

Azure Active Directory Graph API

Demonstrates use of the AAD Grpah API to perform common read and write operations on Users, Groups, Group Membership, Roles, Tenant information, Service Principals, and Applications.

Pre-Requisites

To  make connection to your own azure active directory using the Graph API,You need to make the application and get client id and recreate key from the azure portal

Register the sample app for your own tenant

1. Sign in to the Azure management portal.
2. Click on Active Directory in the left hand nav.
3. Click the directory tenant where you wish to register the sample application
4. Click the APP Registrations tab
5. In the drawer, click New Application Registration
6. Enter friendly name to the application name
7. Select application type Web Api Or native from the given dropdown.
8.For the Sign-on URL, enter a value (NOTE: this is not used for the console app, so is only needed for     this initial configuration): “http://localhost
9.Click on Create button
10.Copy the application id from the portal and paste it in a side. we will need it in later stage as client    ID.
11.Click on settings
12.Click on Keys
13.Under the Keys section, select either a 1-year or 2-year key – the keyValue will be displayed after you save the configuration at the end – it will be displayed, and you should save this to a secure location. NOTE: The key value is only displayed once, and you will not be able to retrieve it later
14.Click on Requires Permission
15.Configure Permissions – under the “Permissions to other applications” section, you will configure permissions to access the Graph (Windows Azure Active Directory). For “Windows Azure Active Directory” under the first permission column (Application Permission:1″), select “Read directory data”. Notes: this configures the App to use OAuth Client Credentials, and have Read access permissions for the application.Select the Save button at the bottom of the screen – upon successful configuration, your Key value should now be displayed – please copy and store this value in a secure location.
16.Click on Save
17.Click on grant permission from the Global administrator or Company administrator role.
18.Once permission is granted, click on manifest
19.Find  “oauthAllowImplicitFlow” set to true and save
Open Visual Studio -> File->Project->Select Console App->Give name and location->Ok
– Add Microsoft.identityModel.Clients.ActivityDirectory to console application
Install-Package Microsoft.IdentityModel.Clients.ActiveDirectory -Version 3.19.8.

Add following constant values in to the constants.cs file

public const string TenantName = “samplesolution.onmicrosoft.com”;
public const string TenantId = “8f4455df-8ae6-454d-bd00-e53e5f87f050”;
public const string ClientId = “3db07cc2-3c44-4f13-ca43-8edcbe130a29”;
public const string ClientSecret = “ItcmltZpNj4UiRItqJUsT8P2G3Fx6HY9RCU/l9vizpQ=”;
public const string ResourceUrl = “https://graph.windows.net&#8221;;
public const string authority=”https://login.windows.net/”CommonConstants.TenantName;

ClientID = Application ID which we have store in separate file.
Secret key = key value which we have get from azure portal while generate the key.Code to create a ActiveDirectoryClient

using Microsoft.IdentityModel.Clients.ActiveDirectory;
using System;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Net.Http.Headers;
using System.Threading.Tasks;static void Main(string[] args)
{
ActiveDirectoryClient activeDirectoryClient = GetActiveDirectoryClientAsApplication();

// Get user based on email address.
// We can get the user from Azure AD using below method.We can get user based on UPN(User Principal Name,UserType) ;
Microsoft.Azure.ActiveDirectory.GraphClient.User user = (Microsoft.Azure.ActiveDirectory.GraphClient.User)activeDirectoryClient.Users.Where(u => u.Mail.Equals(mailAddress)).ExecuteAsync().Result.CurrentPage.FirstOrDefault();

// Get application from the Azure AD which we have configured earlier.
Application application = (Application)activeDirectoryClient.Applications.Where(app => app.AppId.Equals(Constants.CommonConstants.ClientId)).ExecuteAsync().Result.CurrentPage.FirstOrDefault();

// Get approle from selected application
// App role is define in to the manifest file.
AppRole appRole = application.AppRoles.Where(role => role.Id.Equals(Guid.Parse(Constants.ApplicationConstants.AppRoleID))).FirstOrDefault();

// We can create new app role from below code.
//Create App Role
AppRole appRole = new AppRole();
appRole.Id = Guid.NewGuid();
appRole.IsEnabled = true;
appRole.AllowedMemberTypes.Add(“User”);
appRole.DisplayName = “Something”;
appRole.Description = “Anything”;
appRole.Value = “policy.write”;
application.AppRoles.Add(appRole);
application.UpdateAsync().Wait();

// Get Service principal from active directory

ServicePrincipal servicePrincipal = (ServicePrincipal)activeDirectoryClient.ServicePrincipals.Where(service => service.AppId.Equals(Constants.CommonConstants.ClientId)).ExecuteAsync().Result.CurrentPage.FirstOrDefault();

// Assign user to application in azure active directory
AppRoleAssignment appRoleAssignment = new AppRoleAssignment();
appRoleAssignment.Id = appRole.Id;
appRoleAssignment.ResourceId = Guid.Parse(servicePrincipal.ObjectId);
appRoleAssignment.PrincipalType = “User”;
appRoleAssignment.PrincipalId = Guid.Parse(user.ObjectId);
user.AppRoleAssignments.Add(appRoleAssignment);
user.UpdateAsync().Wait();
}

public static ActiveDirectoryClient GetActiveDirectoryClientAsApplication()
{
ActiveDirectoryClient activeDirectoryClient = new ActiveDirectoryClient(new Uri(new Uri(Constants.AzureConstants.ResourceUrl), Constants.CommonConstants.TenantId),
async () => await AcquireTokenAsyncForApplication());
return activeDirectoryClient;

    }

public static async Task<string> AcquireTokenAsyncForApplication()
{
return GetAccessTokenAzure();
}

public static string GetAccessTokenAzure()
{
AuthenticationContext authContext = new AuthenticationContext(Constants.AzureConstants.authority, null);
ClientCredential creds = new ClientCredential(Constants.CommonConstants.ClientId, Constants.CommonConstants.ClientSecret);

AuthenticationResult authenticationResult = authContext.AcquireTokenAsync(Constants.AzureConstants.ResourceUrl, creds).Result;
string accessToken = authenticationResult.AccessToken;
return accessToken;
}

Happy Coding 🙂
3

How to show Friendly Date in SharePoint using Javascript or using Server side code

 

JAVASCRIPT

You can use following javascript code in order to show Date field value in Friendly format


var yourDate = new Date();

var friendlyDate = SP.DateTimeUtil.SPRelativeDateTime.getRelativeDateTimeString(yourDate , true, SP.DateTimeUtil.SPCalendarType.none, false)

console.log(friendlyDate);

 

Note that you need to add reference of “SP.dateTimeUtil.js” js in your page

<script type="text/javascript" src="/_layouts/15/SP.dateTimeUtil.js></script>

Following is the description about method argument:
1. Your date (Date ISO8601)
2. Specify whether want to include tiem or not(IncludeTime)
3. Calendar type (CalendarType)
4. Specify whether want to adjust time with server(AdjustToServersNowTime)
————————————————————————–
SERVER SIDE


DateTime date = DateTime.Now;
string friendlyDate = SPRelativeDateTime.GetRelativeDateString(web, date.ToUniversalTime(), date); 

I Hope it will same someone’s time.
 

0

Event Receivers fires for all lists and libraries

Issue Case – Event Receiver behaving unexpectedly

I want to add my event receiver in all the document library in whole site collection.So i added event receiver like
<?xml version=”1.0″ encoding=”utf-8″?>
<Elements xmlns=”http://schemas.microsoft.com/sharepoint/“>
<Receivers ListTemplateId=”101”>
<Receiver>
<Name>DenyToUpdateMDItemAdded</Name>
<Type>ItemAdded</Type>
<Assembly>[Assembly]</Assembly>
<Class>[Class Path]</Class>
<SequenceNumber>10000</SequenceNumber>
</Receiver>
</Receivers>
</Elements>

The scope of the feature is “Site” as i want to add event receiver in all the sub site also.

When i activated my event receiver feature, event receiver fires for all the list and libraries.

Issue Case – Event Receiver behaving unexpectedly

 

SOLUTION

By Just changing  the scope of the feature “Site” to “web” my problem was resolved

Don’t know whether its sharepoint bug or not:). Hope it will save some time

 

1

Update Master Page of SharepointSite Using PowerShell

Hi

In this post i have written about how to Update master page of any site of SharePoint.
It can also achieve through OOTB within few click, but it can also achieve using powershell

$site = Get-SPSite http://sp:2000/sites/Ex15
foreach ($web in $site.AllWebs)
{
    $web.MasterUrl = $site.RootWeb.ServerRelativeUrl +  &quot;/_catalogs/masterpage/oslo.master&quot;;
    $web.CustomMasterUrl = $site.RootWeb.ServerRelativeUrl + &quot;/_catalogs/masterpage/oslo.master&quot;;
    $web.Update();
    Write-Host $web.Url $web.MasterUrl $web.CustomMasterUrl;
}
$site.Dispose()

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue
    #Get All site collections
    $SiteCollections = Get-SPWebApplication | Get-SPSite -Limit All
    #Loop through all site collections
       foreach($Site in $SiteCollections)
        {
            #Loop throuh all Sub Sites
           foreach($Web in $Site.AllWebs)
           {
		$web.MasterUrl = $site.RootWeb.ServerRelativeUrl +  &quot;/_catalogs/masterpage/oslo.master&quot;;
		$web.CustomMasterUrl = $site.RootWeb.ServerRelativeUrl + &quot;/_catalogs/masterpage/oslo.master&quot;;
		$web.Update();
		Write-Host $web.Url $web.MasterUrl $web.CustomMasterUrl;
           }
        }

Thanks
SPS

0

Delete Site Collection Using PowerShell

Hi,

Here is Power Shell Code for Delete Site Collection from Particular webApplication

$tmpRoot = Get-SPWebApplication -Identity http://SP:2000
$tmpRootColl=$tmpRoot.Sites
#Enumerate through each site collection
for ($index=$tmpRootColl.Count-1 ; $index-ge 0 ; $index–-)
{
  Remove-SPSite -Identity $tmpRootColl.Item($index) -GradualDelete -Confirm:$false
}
Get-SPDeletedSite | Remove-SPDeletedSite

Thanks
SPS

3

Exports Site Columns Using Powershell

Hi

Here is I am  Explain you  how to export site column using Power shell

Open your notpade++  and copy past below code inthe file save file as .ps1

in this powerhsell code i have generate log file you can notice it from code snippet

just give Export location as per your convince

I assume that you are aware of how to run power shell script in SharePoint managment Shell

pass webUrl as parameter

Remarks-Change groups name with your Group name which you want toin Code


#Necessary Parameters
#Necessary Parameters
[CmdletBinding()]
param 
(
	[string] $Web
)
#/// <summary>
#/// Remove Default Group Permission
#/// </summary>
Function ExportSiteColumnXml([string] $web)
{ 
    try
	{  
      		if($web -ne "")
			{  
              
			    $sourceWeb = Get-SPWeb $web
				$xmlFilePath = "C:\Script-SiteColumns.xml"

				#Create Export Files
				New-Item $xmlFilePath -type file -force

				#Export Site Columns to XML file
				Add-Content $xmlFilePath "<?xml version=`"1.0`" encoding=`"utf-8`"?>"
				Add-Content $xmlFilePath "`n<Fields>"
				$sourceWeb.Fields | ForEach-Object {
					if ($_.Group -eq "Your Site Columns Group Name") {
						Add-Content $xmlFilePath $_.SchemaXml
					}
				}
				Add-Content $xmlFilePath "</Fields>"	                            
             }
             else
             {
                 Write-Host "Please provide proper parameters" -ForegroundColor Red
				LogInfo "Please provide proper parameters"
             }
    }
    catch
    {
      Write-Host "Something went wrong. Please check Logs for additional information" -ForegroundColor Red
        LogError $_

    }
    finally
    { 
        #Dispose your site when process end Successivly
		 if($sourceWeb -ne $null)
			{
				$sourceWeb.Dispose();
			}
			LogInfo "Process Ended"
    }
  

}

#/// <summary>
#/// Prints errors if generated
#/// </summary>
Function LogError($message)
{
     $timeStamp = Get-Date -format "dd/MM/yyyy HH:mm:ss"
     $outContent = "$timeStamp`tError`t`t$message`n"
     Add-Content $Logfile $outContent
}

#/// <summary>
#/// Prints logs in log file
#/// </summary>
Function LogInfo($message)
{
     $timeStamp = Get-Date -format "dd/MM/yyyy HH:mm:ss"
     $outContent = "$timeStamp`tInfo`t`t$message`n"
     Add-Content $Logfile $outContent
}




#/// <summary>
#/// Load the SharePoint Snapin 
#/// </summary>
#/// <returns>
#/// </returns>
Function Load-SharePoint-Powershell
{ 
    Write-Host "TEST"
	if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
	{    
	      Add-PsSnapin Microsoft.SharePoint.PowerShell -ErrorAction Stop
          
	}
     
}

$Logfile = "c:\RTED\RTED-$(get-date -f MMddyyyy_HHmmss).log";
Load-SharePoint-Powershell
ExportSiteColumnXml $web


&nbsp;
4

Get recurring event from calendar list using Angular JS

Getting recurring event from calendar list using Angular JS is some bit tricky.
I am going to implement through CEWP(Content editor web part) in SharePoint.

1. Create HTML file for display events description(Angular View)


<html ng-app="myApp">
	<head lang="en">
		<script src="jquery.min.js"></script> 
		<script src="angular.min.js"></script>
		<script type="text/javascript" src="main.js"></script> 
	</head>
	<body>
        <div ng-app="myApp" ng-controller="myCtrl">
            <div ng-repeat="result in results">   
                <div>{{result.Title}}</div>
                <div>{{result.Description}}</div>
                <div>{{result.StartTime}}</div>
                <div>{{result.Location}}</div>
            </div>
        </div>
	</body>
</html>

Give the reference of Jquery and Angular js from your SharePoint site.

If you want to display upcoming limited(suppose top 5) events then you can add condition which is inbuilt facility of Angular JS

Add condition(ng-if) in Angular repeat section

<div ng-repeat="result in results" ng-if="$index < 4">   

2. Now Create one JavaScript which will get all events from calendar event list and check event start date with current date and display only feature events only.


var app = angular.module('myApp', []);
app.controller('myCtrl', function ($scope, $http) 
{
    $scope.results = [];
	var currSiteUrl = _spPageContextInfo.siteAbsoluteUrl;
	var webUrl, calendarListName;
	webUrl= currSiteUrl;
	calendarListName='Events'; 	
	wsURL = webUrl + "/_vti_bin/Lists.asmx";	 
    $scope.request =
        "<soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'> <soap:Body>" +
        "<GetListItems xmlns='http://schemas.microsoft.com/sharepoint/soap/'>" +
        "<listName>" + calendarListName+ "</listName>" +
        "<query>" +
        "<Query>" +
        "<Where>" +
           "<DateRangesOverlap>" +
           "<FieldRef Name='EventDate' />" +
           "<FieldRef Name='EndDate' />" +
           "<FieldRef Name='RecurrenceID' />" +
           "<Value Type='DateTime'><Year/></Value>" +
           "</DateRangesOverlap>" +
        "</Where>" +
        "</Query>" +
        "</query>" +
        "<queryOptions>" +
        "<QueryOptions>" +
            "<ExpandRecurrence>TRUE</ExpandRecurrence>" +
        "</QueryOptions>" +
        "</queryOptions>" +
        "</GetListItems>" +
        "</soap:Body></soap:Envelope>";
 
	var results1 = [];
	$http({
        method: 'POST', 
        url: wsURL, 
        async: false,
        data: $scope.request, 
        headers: {
            'Content-Type': 'text/xml; charset=\"utf-8\; action="http://schemas.microsoft.com/sqlserver/reporting/2010/03/01/ReportServer"'
        }
    })
    .success(function(xData, status, headers, config){       
        if (status === 200)
        {
             var root = $(xData);
                    root.find("listitems").children().children().each(function () {
						$this = $(this);
						var ids = $this.attr("ows_UniqueId").split(";");
						var rec = $this.attr("ows_fRecurrence");
						results1.push({
							"StartTime": $this.attr("ows_EventDate"),
							"EndTime": $this.attr("ows_EndDate"),
							"Title": $this.attr("ows_Title"),
							"Recurrence": (rec === "1" ? true : false),
							"Description": $this.attr("ows_Description"),
							"Location":$this.attr("ows_Location"),
							"Guid": ids[1],
							"Id": ids[0],
						});
                });
        }
	    var filtered_item = [];
	    for (var i = 0; i < results1.length; i++) 
		{
			var current_Time = new Date().getTime()
			var Start_Time = new Date(results1[i].StartTime).getTime();
			if (Start_Time  >= current_Time) {
				filtered_item.push(results1[i]);
			}
		}
      $scope.results =  filtered_item;
    })
    .error(function(data, status, headers, config){
        console.log('In Error');
        console.log(data);
    }); 
});

To get the recurrence event we have added parameter “ExpandRecurrence” with value “True” by which we can identify that event is recurrence or not.

In output you will get Title, Description, Start time and location of event. You can customize as per your requirement and apply css also.

1

Upload Document using c# code to Share-Point library

Hello everyone,

I was facing the following exception.So i had searched and got the solution.

Exception:
Only String, int, and DateTime data types can be used as the value in Properties while adding list item in document library.

I am including following concept with this blog.

1) how to upload document in to SharePoint library from the other library.
2) pass the document metadata using hash table.
3) How to update custom field of SharePoint library with uploaded document.
4) Limitations of Files.Add() methods with hash table.

Key Concept :
What is hash Table?

  • The Hashtable class represents a collection of key-and-value pairs that are
  • organized based on the hash code of the key.
  • It uses the key to access the elements in the collection.
  • A hash table is used when you need to access elements by using key, and you can identify a useful key value.
  • Each item in the hash table has a key/value pair.
  • The key is used to access the items in the collection.

Requirements:
1)How can I upload document in to the Document library from the other document library and update Document library meta data in share point?
2)How can I update document library custom field with user type and Date time type Using c# code?
Solution:
Let’s take document library:
1) UserInformation(Destination Library)
Custom Fields : 1) DocUpdateDate: DateTime 2)DocAddedBy: User
2) BioData(Source library)

 

//Get the Source library
 SPList BioData = elevatedWeb.Lists.Cast().FirstOrDefault(l => l.id == listID);
 if (bioData!=null)
 {
 spListItem bioDataItem = bioData.GetItemById(itemID);
 if(bioDataItem!=null)
 {
 // get file from the item which you want to upload the destination.
 SpFile objFile = Item.File;
 string fileName = objFile.Name;
 //Getting latest published version file content
 byte[] fileContent = null;
 if (objFile.UIVersionLabel.Contains(".0"))
 {
 fileContent = file.OpenBinary();
 }
 else
 {
 string versionString = string.Format("{0}.0", objFile.MajorVersion.ToString());
 SPFileVersion version = objFile.Versions.GetVersionFromLabel(versionString);
 fileContent = version.OpenBinary();
 }
 // Now open the Destination library where you want to upload document.
 SpList UserInformation = elevatedWeb.Lists.Cast().FirstOrDefault(l => l.ID == listID);
 if(UserInformation!=null)
 {
 // create a hastable to stored the Document metadata.
 HashTable properties = new HashTable();
 // Add metadata key and value of the document.
 properties.Add("Key1","Value1");
 properties.Add("Key2","Value2");
 properties.Add("Key3","Value3");
 // you can number of properties as per the business requirement.
 // now upload the document in to the library.
 // to upload the file ,open the object of the SpFile.
 elevatedWeb.AllowUnsafeUpdates = true;
 SpFile uploadFile = UserInformation.RootFolder.Files.Add(fileName, fileContent, properties);
 }

 

 

Limitations of Files.Add() methods with hash table.
If I add a column of type Currency then the code will break and it won’t add the list item to the library at all.Because the function list.RootFolder.Files.Add() will not accept the properties other than the 3 types mentioned,through HashTable
This is the problem with the function. To avoid that below is the code i used and this problem went away.

 

// create a SPListItem object from the objFile.
spListItem objListItem = uploadFile.Item;
{
if(objListItem!=null)
{
objListItem[“DocUpdateDate”] = DateTime.Now;
objListItem[“DocAddedBy”]=elevatedWeb.currentUser;
// update list item
objListItem.update();
}
uploadFile.update();
}
elevatedWeb.AllowUnsafeUpdates = false;
}

 

Finally, updating the list item and updating the file to reflect the changes to the document library list items.

Please feel free to post your ideas, comments and question here.

Happy Coding 🙂