Friday, March 31, 2017

SQL Server - SQL Server Management Studio for SQL Server 2016?

 

The option on the SQL Server 2016 Installation Center takes you to a web download. You can also download the SQL Server at Download SQL Server Management Studio (SSMS). After the download has completed you can run the installation standalone without a connection to the Internet.

Thursday, March 30, 2017

PowerShell - Enumerates through all site collections for a given web application, then enumerates through all subsites within each site collection and deactivate the given web level feature

 

Add-PsSnapin Microsoft.SharePoint.PowerShell

## SharePoint DLL

[void][System.Reflection.Assembly]::LoadWithPartialName("Microsoft.SharePoint")

$webApplicationURL = "webApplicationURL"

$webApp = Get-SPWebApplication $webApplicationURL

$featurefolder = "FollowingContent"

if($webApp -ne $null)

{

foreach($site in $webApp.Sites)

{

if($site -ne $null)

{

foreach($subWeb in $site.AllWebs)

{

      if($subWeb -ne $null)

      {

           Try

           {

           Disable-SPFeature -identity $featurefolder -Confirm:$false –URL  $subWeb.url -ErrorAction Stop

            Write-Output $subWeb " : Following Content Feature is Deactivated"

           }

          Catch

          {

          Write-Output $subWeb " : already Deactivated"

          }

    $subWeb.Dispose()

}

}        

$site.Dispose()

}}}

Remove-PsSnapin Microsoft.SharePoint.PowerShell

PowerShell – Download installed farm solution in SharePoint , Remove Orphaned installed Farm Feature

 

Download installed farm solution in

Add-PsSnapin Microsoft.SharePoint.PowerShell

$frm = Get-SPFarm

$file = $frm.Solutions.Item("wsp").SolutionFile

$file.SaveAs("D:\Wsps\wsp")

Remove Orphaned installed Farm Feature

In Power Shell run below command and get feature IDs

$feature = Get-SPFeature | ? { $_.Scope -eq $null }

$feature

In Command prompt run the sts command and remove that feature by its id.

cd C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\BIN

stsadm -o uninstallfeature –id <GUID> -force

Tuesday, March 28, 2017

Sharepoint - Search - Error while crawling LOB contents. ( Database Connector has throttled the response. The response from database contains more than '2000' rows. The maximum number of rows that can be read through Database Connector is '2000'. The limit can be changed via the 'Set-SPBusinessDataCatalogThrottleConfig' cmdlet. )

 

Solution

$bcs = Get-SPServiceApplicationProxy | where{$_.GetType().FullName -eq (‘Microsoft.SharePoint.BusinessData.SharedService.’ + ‘BdcServiceApplicationProxy’)}

$BCSThrottle = Get-SPBusinessDataCatalogThrottleConfig -Scope database -ThrottleType items -ServiceApplicationProxy $bcs

$BCSThrottle

Set-SPBusinessDataCatalogThrottleConfig -Identity $BCSThrottle -Maximum 1000000 -Default 400000

$BCSThrottle = Get-SPBusinessDataCatalogThrottleConfig -Scope database -ThrottleType items -ServiceApplicationProxy $bcs

$BCSThrottle

Friday, March 24, 2017

Windows Server - UAC Folder problem - "Access is Denied" as Windows Administrator - Domain Administrators permissions

 

Solution -

regedit - HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System\EnableLUE=0 worked for me to resolve this.

Friday, March 17, 2017

SharePoint 2016 - New-SPConfigurationDatabase Server role parameter is required when creating or joining a farm

 

While installing SharePoint 2016, I got the below error which says New-SPConfigurationDatabase Server role parameter is required when creating or joining a farm. The error comes when I run New-SPConfigurationDatabase through SharePoint 2016 Management Shell

While installing SharePoint 2016, I got the below error which says New-SPConfigurationDatabase Server role parameter is required when creating or joining a farm. The error comes when I run New-SPConfigurationDatabase through SharePoint 2016 Management Shell

Solution:

In SharePoint Server 2016 MinRole you need to give while installing, this can be used to specify the role that should be assigned to a specific server when configuring SharePoint Products and Technologies. The MinRole can be like below:

New-SPConfigurationDatabase –DatabaseName SharePoint_Config –DatabaseServer WIN-JC2B1V15KM5 –AdministrationContentDatabaseName SharePoint_Content –Passphrase (ConvertTo-SecureString ‘Passphrase’ –AsPlaintext –Force) –FarmCredentials (Get-Credential) -localserverrole SingleServerFar

Here -localserverrole SingleServerFarm is the main parameter. 

Hope this will be helpful.

Monday, March 13, 2017

C# - Client Object model to Delete the file, upload file , Check in and Publish it in to sharepoint Document library

 

 

    string FileName = Path.GetFileName(“FileLocation”");
    string docLibName = "Site Collection Documents";
    string spPath = siteUrl + "/SiteCollectionDocuments/SaleRanking.xlsx";

    // get the server relative URL
    Uri filename = new Uri(@spPath);
    string server = filename.AbsoluteUri.Replace(filename.AbsolutePath, "");
    string serverrelative = filename.AbsolutePath;

    try
    {      
            Microsoft.SharePoint.Client.File f = null;
            SP.ClientContext ctx = new SP.ClientContext(siteUrl);
            Web web = ctx.Web;
            List docs = web.Lists.GetByTitle(docLibName);
            f = web.GetFileByServerRelativeUrl(serverrelative);
            ctx.Load(f);
            f.DeleteObject();ctx.ExecuteQuery(); // Delete file here but throw Exception       
            ctx.ExecuteQuery(); // Delete file here but throw Exception
           
            FileCreationInformation newFile = new FileCreationInformation();
            newFile.Content = System.IO.File.ReadAllBytes(@FileLocation);
            newFile.Url = spPath;
            Microsoft.SharePoint.Client.File uploadFile = docs.RootFolder.Files.Add(newFile);
            ctx.Load(uploadFile);
            ctx.ExecuteQuery(); // Add new file here    

            f.CheckIn(string.Empty, CheckinType.MajorCheckIn);  // Check in File
            ctx.ExecuteQuery(); // Check in File             

             f.Publish("file published");
             ctx.ExecuteQuery(); // Publish File 

      }catch (Exception ex)   {
      }

Wednesday, March 8, 2017

Powershell - Update web config file from all servers under farm

 

- Take back up of Existing Web Config

- Check if appSettings node is there then throw exception

- If property node is then delete it and recreate with new node.

 

Add-PSSnapin Microsoft.SharePoint.PowerShell
$serverInfo = get-spserver | ? { $_.Role -eq "Application" }
$serverInfo.Name
#$Folderpath = '\C$\Program Files\Common Files\Microsoft Shared\Web Server Extensions\15\WebServices\SecurityToken';
$Folderpath ='\C$\inetpub\wwwroot\wss\VirtualDirectories\'

$webappName = @("abc443\")
$PropertyName = @("HostName","PortNumber)
$PropertyValue = @("abc","636)

for($j=0 ; $j -lt $serverInfo.count ; $j++)
{
        write-host*****************************"  -foreground Green
        write-host " Server :  " + $serverInfo[$j].Name -foreground Green
        write-host "*************************************************" -foreground Green
  
    for($i=0 ; $i -lt $webappName.count ; $i++)
        { 
        $path = '\\'+$serverInfo[$j].Name + $Folderpath
        write-host $path
        $webConfig = $path+$webappName[$i]+'Web.config'
        write-host "Updatng Web Config for " + $webConfig
        if(Test-Path $webConfig -PathType Any)
        {
            $backup = $path+$webappName[$i]+ 'web_'+ (get-date).tostring("yyyy_MM_dd_hh_mm_ss")+'.bak';
            write-host "Taking Back up for Web Config "   +  $backup -foreground Green
            copy-item $webConfig -destination $backup

            for($k=0 ; $k -lt $PropertyName.count ; $k++)
                {
                Set-ApplicationSettingConfigProperty $webConfig $PropertyName[$k] $PropertyValue[$k] ;
                Function Set-ApplicationSettingConfigProperty
                {
                    param (
                        [parameter(Mandatory = $true)][ValidateScript ({Test-Path $_})][string] $PathToConfigFile,
                        [parameter(Mandatory = $true)][string] $PropertyName,
                        [parameter(Mandatory = $true)][string] $PropertyValue,
                        [Parameter(Mandatory = $false)][Validatescript ({(Get-Service $_) -ne $null})][string] $NameOfServiceToRestart = $null)
   

                    $configurationAppSettingXmlPath = "//configuration/appSettings"

                    [xml] $configurationDocument = Get-Content $PathToConfigFile
                    $appSettingsNode = $configurationDocument.SelectSingleNode($configurationAppSettingXmlPath)
   
                    if($appSettingsNode -eq $null)
                    {
                       # $(throw "App Settings Does not Exists! Invalid Configuration File.")
                       write-host "App Settings Does not Exists! Invalid Configuration File." -foreground red
                    }

                    $nodeToUpdate = $configurationDocument.SelectSingleNode($configurationAppSettingXmlPath+"/add[@key='$PropertyName']")
                    if($nodeToUpdate -ne $null)
                    {
                        Write-Host "[$PropertyName] Already exists, Removing it to re-set its value." -foreground red
                        $removedElement = $appSettingsNode.RemoveChild($nodeToUpdate)
                    }

                    Write-Host "Creating new Configuration Node." -foreground Green
                    $newPropertyNode = $configurationDocument.CreateNode("element", "add","")
                    $newPropertyNode.SetAttribute("key", $PropertyName)
                    $newPropertyNode.SetAttribute("value", $PropertyValue)
                    $appSettingsNode = $configurationDocument.SelectSingleNode($configurationAppSettingXmlPath).AppendChild($newPropertyNode)
                    Write-Host "Adding new property into the configuration file."  -foreground Green
                    $configurationDocument.Save($PathToConfigFile)
                    Write-Host "Property was Successfully Updated." -foreground Yellow
                    Write-Host "---------------------------------------------------------------------------" -foreground Yellow
                    Write-Host "---------------------------------------------------------------------------" -foreground Yellow

                    if([string]::IsNullOrWhiteSpace($NameOfServiceToRestart) -eq $false)
                    {
                        Write-Host "Service [$NameOfServiceToRestart] was defined.., Restarting it"
                        Restart-Service -Name $NameOfServiceToRestart
                        Write-Host "Service was Restarted..."
                    }
                }
            }
        }
    }
}

Powershell–Create User in Sharepoint 2013 user profile

 

Add-PSSnapin Microsoft.SharePoint.PowerShell

$siteUrl = "Site URL"
#$accountName = "i:0#.f|fba|test" # Account name if FBA user
$accountName = "Domaine\UserID"

$site = Get-SPSite $siteUrl
$context = Get-SPServiceContext($site)
$pm = new-object Microsoft.Office.Server.UserProfiles.UserProfileManager($context)

# If user profile doesn't exist create new one
if ($pm.UserExists($accountName)) {
    $userProfile = $pm.GetUserProfile($accountName)
} else  {
    $userProfile = $pm.CreateUserProfile($accountName)
}
# Update user profile properties
$userProfile["FirstName"].Value = "FName"
$userProfile["LastName"].Value = "LName"
$userProfile["WorkPhone"].Value = "PhNo"
$userProfile["Title"].Value = "Developer"
$userProfile["WorkEmail"].Value = abc@abc.com  
$userProfile["Department"].Value = "Sales"
$userProfile["SPS-MUILanguages"].Value = "en-us"

# Commit changes
$userProfile.Commit()

#Clear our User Profile Cache

Use-CacheCluster
Restart-CacheCluster

Tuesday, March 7, 2017

Powershell Script to Create Seach service applicaiton in Sharepoint 2013

 

1) Clean up inactive Query/Crawl topology from SSA

foreach($ssa in Get-SPEnterpriseSearchServiceApplication){

    $ssa | get-SPenterpriseSearchCrawlTopology | where {$_.state -eq “Inactive”} | Remove-SPEnterpriseSearchCrawlTopology -confirm:$false

    $ssa | get-SPenterpriseSearchQueryTopology | where {$_.state -eq “Inactive”} | Remove-SPEnterpriseSearchQueryTopology -confirm:$false

}

2) Setting up some initial variables.

$SSAName = "SSA1"

$SVCAcct = "contoso\spsvc"

$SSI = Get-SPEnterpriseSearchServiceInstance -local

$err = $null

3) Start Services search services for SSI

Start-SPEnterpriseSearchServiceInstance -Identity $SSI

4) Create an Application Pool.

$AppPool = new-SPServiceApplicationPool -name $SSAName"-AppPool" -account $SVCAcct

5) Create the SearchApplication and set it to a variable  ( This might take couple minutes)

$SearchApp = New-SPEnterpriseSearchServiceApplication -Name $SSAName -applicationpool $AppPool -databasename $SSAName"_AdminDB"

6) Create search service application proxy

$SSAProxy = new-spenterprisesearchserviceapplicationproxy -name $SSAName"ApplicationProxy" -Uri $SearchApp.Uri.AbsoluteURI

7) Provision Search Admin Component. ( This might take couple minutes)

Set-SPEnterpriseSearchAdministrationComponent -searchapplication $SearchApp  -searchserviceinstance $SSI

8) Create a new Crawl Topology.

$CrawlTopo = $SearchApp | New-SPEnterpriseSearchCrawlTopology

9) Set Crawl Store variable.

$CrawlStore = $SearchApp | Get-SPEnterpriseSearchCrawlDatabase

10) Create a new Crawl Component.

New-SPEnterpriseSearchCrawlComponent -CrawlTopology $CrawlTopo -CrawlDatabase $CrawlStore -SearchServiceInstance $SSI

11) Activate the Crawl Topology. ( This might take couple minutes)

do

{

    $err = $null 

    $CrawlTopo | Set-SPEnterpriseSearchCrawlTopology -Active -ErrorVariable err

    if ($CrawlTopo.State -eq "Active")

    {

        $err = $null

    }

    Start-Sleep -Seconds 10

}

until ($err -eq $null)

12) Create a new Query Topology.

$QueryTopo = $SearchApp | New-SPenterpriseSEarchQueryTopology -partitions 1

13) Set Query Partition variable

$Partition1 = ($QueryTopo | Get-SPEnterpriseSearchIndexPartition)

14) Create a Query Component.

New-SPEnterpriseSearchQueryComponent -indexpartition $Partition1 -QueryTopology $QueryTopo -SearchServiceInstance $SSI

15) Create a variable for the Property Store DB.

$PropDB = $SearchApp | Get-SPEnterpriseSearchPropertyDatabase

16) Set the Query Partition to use the Property Store DB.

$Partition1 | Set-SPEnterpriseSearchIndexPartition -PropertyDatabase $PropDB

17) Activate the Query Topology. ( This might take couple minutes)

do

{

    $err = $null

    $QueryTopo | Set-SPEnterpriseSearchQueryTopology -Active -ErrorVariable err -ErrorAction SilentlyContinue

    Start-Sleep -Seconds 10

    if ($QueryTopo.State -eq "Active")

        {

            $err = $null

        }

}

until ($err -eq $null)

Write-host "Your search application $SSAName is now ready"

18) Remember to start SQSS service to make crawl and query work.

Monday, March 6, 2017

C# - code to send email from SMTP with an attachments

 

string smtpServer = “SMTP Server”;
string fromAddress = “SMTP From Address”;
mailMessage.From = new MailAddress(“SMTP Email Address”);
mailMessage.Bcc.Add(toAddress);Dictionary<byte[], string> fileCollection = svc.getAttchmentDetails(MessageID);
mailMessage.Subject = emailSubject;
mailMessage.IsBodyHtml = IsBodyHtml;

// get the file from SQL DB

Dictionary<byte[], string> fileCollection = svc.getAttchmentDetails(MessageID);

   if (IsBodyHtml)
    emailBody = Regex.Replace(emailBody, @"(<img\/?[^>]+>)", @"", RegexOptions.IgnoreCase);

   foreach (KeyValuePair<byte[], string> entry in fileCollection)
          {
          string fileName = entry.Value.ToString();
          byte[] objContext = (byte[])entry.Key;
          MemoryStream memoryStreamOfFile = new MemoryStream(objContext);
         mailMessage.Attachments.Add(new System.Net.Mail.Attachment(memoryStreamOfFile, fileName, MimeMapping.GetMimeMapping(fileName)));
          }
mailMessage.Body = emailBody;
if(msgPriority.Contains("True"))
mailMessage.Priority = MailPriority.High;
smtpClient = new SmtpClient(smtpServer);
smtpClient.Send(mailMessage);
file.WriteLine("Email Send Out Successfully");
msgStatus[0] = "Success";

Friday, March 3, 2017

Powershell to Extend sharepoint web application, Add https binding to web application, Assign Existing Certificate to that binding

 

Add-PSSnapin Microsoft.SharePoint.PowerShell

$MachineName = [system.environment]::MachineName
$MachineNameFQDN = (Get-WmiObject win32_computersystem).DNSHostName+"."+(Get-WmiObject win32_computersystem).Domain

$WebAppAppPoolAccount = "AppPool Account"
$SiteCollectionOwner = "SiteCollection Owener Name"
$WebAppDatabaseServer = "Web App Data base (Content DB) server name"
$webApplication = "Web Application URL"

# Extend web application and Add Alternate Mappind to that Web applicaiton

$altMappingInternalURL = "http://"+$MachineNameFQDN
$webApplication | New-SPWebApplicationExtension -Name "Sharepoint Extended Web Application Name" -Port 83 -Zone "Custom" -Verbose -Url $altMappingInternalURL
Write-Host $altMappingInternalURL

# Extent Web Applicaiton

$webApplication | New-SPWebApplicationExtension -Name "Sharepoint Extended Web Applicaiton Name" -Port 121 -Zone "Internet" –Verbose

#Extend Web Application, Make that web application Form based

$webApplication = "http://Web Application URL/"
$sslProtocolURL = "Web Application URL"
$sslProtocolURL1 = "https://Web Application URL"
$ap = New-SPAuthenticationProvider -ASPNETRoleProviderName 'RolerProviderFBA' -ASPNETMembershipProvider 'MemberShipProviderFBA'
Get-SPWebApplication -Identity $webApplication | New-SPWebApplicationExtension -Name "Sharepoint Extended Web Applicaiton Name" -Port 82 -Zone "Internet"  -AuthenticationProvider $ap  -Verbose
New-SPAlternateUrl -URL $sslProtocolURL1 -WebApplication $webApplication -Zone "Internet" -Verbose

#Add WebBinding for HTTPS for Existing Web site and Assgine certificate to that biniding

$webSiteName = "Website Name";
Import-Module WebAdministration -ErrorAction SilentlyContinue
New-WebBinding -Name $webSiteName -HostHeader $sslProtocolURL -Protocol https -Port 443  -Verbose
Get-WebBinding $webSiteName
Get-ChildItem cert:\LocalMachine\My | where { $_.Subject -match "CN=CertificateName" } | select -First 1 | New-Item IIS:\SslBindings\0.0.0.0!443

Thursday, March 2, 2017

C# code to connect outlook from EWS web service

 

-Connect to EWS web service

-Get All unread email from today’s date with Email Parameter

-Get the attachment in Email and save that to local project folder

               

           bool MoreItems = true;
           int offset = 0;
           int pageSize = 1000;
           string BrandName = String.Empty;
           DateTime dateStart = DateTime.Today;
           ExchangeService Service = new ExchangeService();
           sbErrorLog.Append("Setting Web Service Parameter");
           sbErrorLog.AppendLine(); 
           Service.Url = new Uri(“Service URL”);
           sbErrorLog.Append("Web Service URL " + Service.Url.ToString());
           sbErrorLog.AppendLine(); 
           //Set service credentials. This will be the service account. 
           //.  Use the email address
           ExchangeCredentials credentials = new WebCredentials(“Account Name”,Account Password);
           Service.Credentials = credentials;
           // Setting Web Service Credentials
           //WebService Impersonating
          //Setting Up Web Service Certificate");
          Service.ImpersonatedUserId = new ImpersonatedUserId(ConnectingIdType.SmtpAddress, “SMTP Email Address”);
           System.Net.ServicePointManager.ServerCertificateValidationCallback = delegate(object sender, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors) { return true; };
           //Bind the service object to the Inbox
           //Folder inbox = Folder.Bind(service, WellKnownFolderName.Inbox);
           //Defined search filter for unread messages
           SearchFilter.ContainsSubstring SubjectFilter = new SearchFilter.ContainsSubstring(ItemSchema.Subject, "Test Email Read with attachment", ContainmentMode.Substring, ComparisonMode.IgnoreCase);
           SearchFilter greaterthanfilter = new SearchFilter.IsGreaterThanOrEqualTo(ItemSchema.LastModifiedTime, dateStart);
           SearchFilter unreadFilter =  new SearchFilter.IsEqualTo(EmailMessageSchema.IsRead, false);

           SearchFilter.SearchFilterCollection searchFilterCollection = new SearchFilter.SearchFilterCollection(LogicalOperator.And);
           // Setting Up Web Service Filter
          // Filter 1 – Greater Then today’s date and Only unread item
           searchFilterCollection.Add(greaterthanfilter);
           searchFilterCollection.Add(unreadFilter);
           //searchFilterCollection.Add(SubjectFilter);
           //Loop through the items and do whatever is required
           while (MoreItems)
           {
               try
               {
                   string fileLocation = String.Empty;
                   ItemView view = new ItemView(pageSize, offset, OffsetBasePoint.Beginning);
                   FindItemsResults<Item> findResults = Service.FindItems(WellKnownFolderName.Inbox, searchFilterCollection, view);
                   Service.LoadPropertiesForItems(findResults, new PropertySet(ItemSchema.DisplayTo, ItemSchema.Body, ItemSchema.LastModifiedName, ItemSchema.Subject, ItemSchema.Attachments));
                   foreach (Item item in findResults)
                   {
                       try
                       {
                           string Body = (item as EmailMessage).Body.ToString();
                           foreach (Microsoft.Exchange.WebServices.Data.Attachment attachment in (item as EmailMessage).Attachments)
                           {
                               if (attachment is FileAttachment)
                               {

                                   FileAttachment fileAttachment = attachment as FileAttachment;

                                   fileLocation = Directory.GetCurrentDirectory() + "\\Files\\" + fileAttachment.Name;
                                  //Get File Location
                                fileAttachment.Load(Directory.GetCurrentDirectory() + "\\Files\\" + fileAttachment.Name);
                                  }
                               else // Attachment is an item attachment.
                               {
                                   ItemAttachment itemAttachment = attachment as ItemAttachment;

                                   // Load attachment into memory and write out the subject.
                                   // This does not save the file like it does with a file attachment.
                                   // This call results in a GetAttachment call to EWS.
                                   itemAttachment.Load();

                                   sbErrorLog.Append("Item attachment name: " + itemAttachment.Name);
                                   sbErrorLog.AppendLine(); 
                               }
                           }

                                                
                       }
                       catch (Exception ex)
                       {
                           sbErrorLog.Append(ex.Message);
                      
                       }
                   }
                   if (!findResults.MoreAvailable)
                       MoreItems = false;
                   else
                   {
                       offset += findResults.Items.Count;
                   }
               }
               catch (Exception ex) {
                   sbErrorLog.Append(ex.Message);
               }
           }

SharePoint URL’s Shortcuts

 

(Remember for SharePoint 2013 you might want to add "15" after "/_layouts/" but if you don't SharePoint will take care of that for you)

Get the version of the SharePoint server (Patch level):

/_vti_pvt/Service.cnf

Application page for registering SharePoint apps

/_layouts/15/appregnew.aspx

Save Site as a template

/_layouts/savetmpl.aspx

Sign in as a different user

/_layouts/closeConnection.aspx?loginasanotheruser=true

Enable SharePoint designer

/_layouts/SharePointDesignerSettings.aspx

Welcome Page (Default page settings)

/_layouts/AreaWelcomePage.aspx

Change Site Master Page

/_layouts/ChangeSiteMasterPage.aspx

Page Layouts and Site Templates

/_Layouts/AreaTemplateSettings.aspx

Master Pages library

/_catalogs/masterpage/Forms/AllItems.aspx

User Information List

_catalogs/users/simple.aspx

Quick Deploy List

Quick%20Deploy%20Items/AllItems.aspx

Open Page in Edit Mode

?ToolPaneView=2

Taxonomy Hidden List (MMS)

Lists/TaxonomyHiddenList/AllItems.aspx

User Information List:

_catalogs/users/simple.aspx

Force displaying the user profile in the site collection:

/_layouts/userdisp.aspx?id={UserID}&Force=True

Web Part Maintenance Page:

?Contents=1

Show Page in Dialog View :

?isdlg=1

Wednesday, March 1, 2017

SharePoint Super User Account , Claim provider and Sharepoitn STS session time out - Powershell operations

 

Remove Super user account PowerShell Script

$wa = Get-SPWebApplication -Identity "Web App URL"

$wa.Properties.Remove("portalsuperuseraccount")

$wa.Properties.Remove("portalsuperreaderaccount")

$wa.Update()

iisreset

Add Super User Account PowerShell Script

stsadm -o setproperty -pn portalsuperreaderaccount -pv "account_name_as_it_appears_in_webapp_user_policy" -url https://www.url.com

stsadm -o setproperty -pn portalsuperuseraccount -pv "account_name_as_it_appears_in_webapp_user_policy" -url "https://www.url.com"

Or

https://www.url.com

$wa = Get-SPWebApplication -Identity "https://www.url.com"

$su = New-SPClaimsPrincipal “User Account” -IdentityType WindowsSamAccountName

$sr = New-SPClaimsPrincipal “User Account” -IdentityType WindowsSamAccountName

$wa.Properties["portalsuperuseraccount"] = ($su.ToEncodedString())

$wa.Properties["portalsuperreaderaccount"] = ($sr.ToEncodedString())

$wa.update()

iisreset

Ex

$wa = Get-SPWebApplication -Identity "https://www.url.com"

$wa.Properties["portalsuperuseraccount"] = “User Account”

$wa.Properties["portalsuperreaderaccount"] = “User Account”

$wa.Update()

iisreset

Find Current Supper User Account Information

$wa = Get-SPWebApplication -Identity "https://www.url.com"

$wa.Properties["portalsuperuseraccount"]

$wa.Properties["portalsuperreaderaccount”]

See the claims in Current Environment

$cpm = Get-SPClaimProviderManager

$cpm.ClaimProviders

Change Default Claim Provider to False

$cpm = Get-SPClaimProviderManager

$cpm.ClaimProviders

$cp = $cpm.ClaimProviders[5]

$cp.IsUsedByDefault = $false

$cp.IsEnabled =$false

$cpm.Update()

See Intranet Zone Information

$intranet = $wa.IisSettings.Item("Intranet")

$intranet

Set Claim Provider to Intranet Zone

$Intranet.ClaimsProviders.Add("Role Name")

$wa.update()

See IIS settings for Intranet zone

$intranet = $wa.IisSettings.Item("Intranet")

$intranet

Remove Claim Provider from intranet zone

$Intranet.ClaimsProviders.Remove("Role Name")

$wa.update()

Set Claim Provider to Default Zone

$default= $wa.IisSettings.Item("Default")

$Default

$Default.ClaimsProviders.Add("Role Name")

$wa.update()

STS Session Time Out

$sts = Get-SPSecurityTokenServiceConfig

$sts.FormsTokenLifeTime = (New-TimeSpan -minutes 5000)

$sts.Update()

Get-SPSecurityTokenServiceConfig

$sts = Get-SPSecurityTokenServiceConfig

$sts.CookieLifetime = (New-TimeSpan -minutes 5000)

$sts.Update()

Get-SPSecurityTokenServiceConfig

//Not Require

$sts = Get-SPSecurityTokenServiceConfig

$sts.LogonTokenCacheExpirationWindow = (New-TimeSpan -minutes 6000)

$sts.Update()

Get-SPSecurityTokenServiceConfig

$web = Get-SPWeb https://www.url.com

$su = New-SPClaimsPrincipal ‘UserID’ -IdentityType WindowsSamAccountName

$Token=$web.GetUserToken($su.ToEncodedString())

$bin=$token.BinaryToken

$hex=[bitconverter]::ToString($bin)

$hex.Replace("-","") > c:\Results.txt

Powershell Script to Disable Web part – Enable Webpart – Create page in to Page Library – Add Web part in to Page – Publish that page

 


Add-PsSnapin Microsoft.SharePoint.PowerShell

$rootURL = “Your Web Application URL”

$Feature = “Your Feature GUID  ex – https://yourwebappurl
$webPartTitle = “Web Part Name”;
$custwebPartTitle =”Web Part Title”;
$PageName = “Page Name you want to Create in Page Library – Ex – Test.aspx ”
$PageTitle = “Page Title”

// Below variable to create this page and add webpart in to that page in to all site collection

//ex Test:Pages – Pages is the libarry you want to create page in to

$MarketPlaceNamelist = @(
                    "Test:Pages", "Test1:Pages"

)


foreach($MarketPlaceName in $MarketPlaceNamelist)
{
    $arr=$MarketPlaceName.ToString().Split(":")
    $siteURL = $rootURL +"/portal/"+$arr[0]
    Write-Host("Updating " + $siteURL ) -ForegroundColor Yellow ;
    $lstSitePagesName = $arr[1]
   
    # Initialize the Site Object
    $Site = Get-SPSite($SiteUrl)

    Write-Host("Disabling Feature WebPart") -ForegroundColor Yellow ;
    Disable-SPFeature -identity $Feature -URL $siteURL -confirm:$false
    Write-Host("Enabling Feature WebPart") -ForegroundColor Yellow ;
    Enable-SPFeature -identity $Feature -URL $siteURL 
    Write-Host("Adding Page in to Page Library") -ForegroundColor Yellow ;

    function Add-WebPartToPage($web,$pageUrl, $webpartzone,$index,$fileName,$custWPTitle,$ChromeType)
    {
        $Webp=$site.RootWeb
       # $webPartGallery = $Webp.Lists[$lstWebPartGalleryName]
   
        #Write-Host "Searching webpart $fileName in web part gallery" -ForegroundColor Yellow
        #if($webPartGallery -eq $null)
        #{
        #    Write-Host("Unable to retrieve Webpartgallery");
        #}
        $webpart = $null;
        #$webpart=$webPartGallery.Items | ? { $_.Title -eq $fileName}

        $wpCatlog =[Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog
        $spList = $Webp.GetCatalog([Microsoft.SharePoint.SPListTemplateType]::WebPartCatalog)        
       
        foreach ($spItem in $spList.Items)
        {            
            if($spItem.Title.Contains($webPartTitle))
        {          
            $webpart = $spItem;
        }
        }
        
        if($webpart -eq $null) {
            Write-Host("Unable to retrieve webpart: $fileName") -ForegroundColor Red
        }
        else {   
        Write-Host("----------Adding Webpart--------")-ForegroundColor Yellow
        Write-Host $webpart.Title -ForegroundColor Yellow
        $webpartmanager=$web.GetLimitedWebPartManager($pageUrl, [System.Web.UI.WebControls.WebParts.PersonalizationScope]::Shared)
        $errorMsg = "";
        $xmlReader = New-Object System.Xml.XmlTextReader($webpart.File.OpenBinaryStream());
            $webpart = $webpartmanager.ImportWebPart($xmlReader,[ref]"Error")
            $webpart.Title = $custWPTitle;
            $webpart.ChromeType = $ChromeType
        $webpartmanager.AddWebPart($webpart, $webpartzone, $index);
   
           }   

        $Webp.Dispose()
    }


    function CreatePage($web,$PageLayoutRelUrl,$PageName,$PageTitle)
    {

         # Get the Publishing Site based on the SPSite
         $PubSite = New-Object Microsoft.SharePoint.Publishing.PublishingSite($Site)
    
         # Initialize the PublishingWeb based on the SPWeb
         $PubWeb = [Microsoft.SharePoint.Publishing.PublishingWeb]::GetPublishingWeb($Web)
  
         # Get the PageLayouts Installed on the Publishing Site
         $Layouts = $PubSite.GetPageLayouts($False)

    
 
         # Get our PageLayout
         $PageLayout = $Layouts[$PageLayoutRelUrl]
  
         # Create a new publishing page.
         $Page = $PubWeb.AddPublishingPage($PageName, $PageLayout)
 
         # Assign the Title for the Page
         $Page.Title = $PageTitle
 
         # Update the Page
         $Page.Update();
    
         #Write-Host $PageURL
         return $Page

    }

    function PublishPage($Page)
    {
        TRY
        {
            # Check in the Page with Comments
             $Page.CheckIn("Checked in using powershell")
 
             # Publish the Page With Comments
             $Page.ListItem.File.Publish("Publish using powershell")
         }
         CATCH
         { }

    }

    $web=$site.RootWeb

     # Get the blank webpart PageLayout
    $PageLayoutRelUrl = "_catalogs/masterpage/BlankWebPartPage.aspx"
   
    $Page=CreatePage $web $PageLayoutRelUrl $PageName $PageTitle
    $PageURL=$Page.Uri.ToString()
    Add-WebPartToPage $web $PageURL "Header" 0 $webPartTitle $custwebPartTitle "None"
    PublishPage($Page)
    $web.Update()
    $web.Dispose()
    $site.Dispose()
    Write-Host("All Updates Are done") -ForegroundColor Green ;
    Write-Host("-----------------------------------------------------------") -ForegroundColor Green ;
    Write-Host("-----------------------------------------------------------") -ForegroundColor Green ;

}