Showing posts with label Sharepoint. Show all posts
Showing posts with label Sharepoint. Show all posts

Wednesday, July 1, 2015

Sharepoint Powershell - Enable logging - Verbose

To view the current Log Level in Sharepoint

Get-SPLogLevel

To create a new log file

New- SPLogFile

To set the ULS logging to Verbose


Set-SpLogLevel -TraceSeverity Verbose

To set the ULS logging to VerboseEx - Verbose Extended Logs- This will captured SQL queries in the log.


Set-SpLogLevel -TraceSeverity VerboseEx 

To set Eventlog along with trace log(ULS)

Set-SpLogLevel -TraceSeverity Verbose  -EventSeverity Verbose

To Clear the Log Level

Clear-SPLogLevel

To collect logs from all the servers based on Correlation


Merge-SPLogFile -Path "C:\Logs\Log.log" -correlation <correlation id>

To collect logs from all the servers based on date & time

Merge-SPLogFile -Path "C:\Logs\Log.log" -Overwrite -StartTime "mm/dd/yyyy hh:mm" -EndTime "mm/dd/yyyy hh:mm"


Sharepoint Powershell - Add bulk items to Sharepoint lists

cls

$webURL = "http://SiteURL"
$listName = "List_Name"


$web = Get-SPWeb $webURL
  
$list = $web.Lists[$listName]

#Add 1000 items to the list

for ($i=1;$i -lt 1001; $i++) {
$newItem = $list.Items.Add()

           #Add properties to this list item

           $newItem["Title"] = "Test Item"+ $i.ToString()
            $newItem.Update()

}

Sharepoint Powershell - To set master page

To find out which master page is currently applied


$web = Get-SPWeb http://siteurl
$web.CustomMasterUrl
$web.MasterUrl



To set a custom master page to the site

$web = Get-SPWeb http://siteurl
$web.CustomMasterUrl = "/_catalogs/masterpage/custom.master"
$web.MasterUrl = "/_catalogs/masterpage/custom.master"
$web.Update() 

Sharepoint 2013 Workflow Error Invalid JWT token

I had a Sharepoint 2013 Workflow in my site. 
I have configured Workflow manager correctly.

But my workflows weren't running fine. Its status is always "Workflow Cancelled"

When I click the details, it showed the below error

RequestorId: c4f69ed9-ce23-c0b4-b587-620ae350f156. Details: System.ApplicationException: HTTP 401 {"error_description":"Invalid JWT token. Could not resolve issuer token."}


Solution

Run the timer job "Refresh Trusted Security Token Services Metadata feed" to fix the issue

Sharepoint App deployment Error - The content database on the server is temporarily unavailable

When you try to deploy an app via Visual Studio, you might get the below error

The content database on the server is temporarily unavailable

Solution

Configure Managed Metadata service application correctly.

Also make sure you have the below service applications configured correctly

1. App Management Service Application.

2. Microsoft SharePoint Foundation Subscription Settings Service Application.

Thursday, February 5, 2015

Powershell- Create folders and sub-folders in sharepoint library


The below script creates multiple folders within a document library; Each folder will have one single subfolder within it.



$webUrl = "http://<siteURL>"
$listName = "Library_Name"
$numberFoldersToCreate = 5;
$folderNamePrefix = "folder";


$web = Get-SPWeb $webUrl
$list = $web.Lists[$listName]

 $StartDateFolder = get-date

for($i=1; $i -le $numberFoldersToCreate; $i++)
{ 

 $folder = $list.AddItem("", [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "$folderNamePrefix$i")
 $folder.Update()

 Write-Output "Folder created " $folder.Url

# // Creating One subfolder within the folder

 $subFolderURL=$list.ParentWebUrl +"/" + $folder.Url;

#// if your site is a root site collection, then $list.ParentWebUrl will return "/" 
#so use the  line as  $subFolderURL=$list.ParentWebUrl  + $folder.Url; 

 $folder2 = $list.AddItem($subFolderURL, [Microsoft.SharePoint.SPFileSystemObjectType]::Folder, "Subfolder")
 $folder2.Update()

 Write-Output "Sub Folder created = " $folder2.Url
  
  
}
$EndDatefolder=get-date

 $foldercreationtime=NEW-TIMESPAN –Start $StartDateFolder  –End $EndDatefolder

 $f=[string]::Concat("Folder creation time = " ,  $foldercreationtime.Hours , ":" , $foldercreationtime.Minutes,  ":" , $foldercreationtime.Seconds   )

Write-Output   $f

$web.Dispose()

Sunday, January 18, 2015

ULS viewer is showing blank data when we use RealTime option

If your ULS viewer  (download from here ) shows blank data when you use "RealTime" as below





then try the following.

Option #1: Clear everything from logs folder

1. Go to  Services.msc
2. Stop the "Sharepoint Tracing Service"
3. Navigate to C:\Program Files\Common Files\microsoft shared\Web Server Extensions\15\LOGS and clear everything.
4. Start the "Sharepoint Tracing Service"
5. Try to open ULSViewer and check for real-time logs


In case, if you still face the issue, try the next option

Option #2 : Change the default location of ULS log

1. Go to Central admin site
2. Got to Monitoring -> Configure Diagnostic logging
3. Change the "Trace Log Path" to any folder, say C:\ULSLogs
4. Try to open ULSViewer and check for real-time logs


Hope it helps !!

Monday, December 1, 2014

Powershell to make List column optional in Sharepoint

$web = Get-SPWeb -identity "http://siteurl"

$list = $web.Lists["ListName"]
$column = $list.Fields["Title"]
$column.Required = $false
$column.Update()
$list.Update()

$web.Dispose()

Sunday, November 23, 2014

Sharepoint Custom Claims provider - Fill Resolve method implementation.


In order to have the fillresolve methods to be triggered, you need to have the property SupportsResolve to true.

We will have 2 overload methods of fillResolve in your custom claims provider. You need to implement both of these methods.

protected override void FillResolve(Uri context, string[] entityTypes, string resolveInput, List<Microsoft.SharePoint.WebControls.PickerEntity> resolved) - This method will be called when you enter name in the text box and click resolve.

and

protected override void FillResolve(Uri context, string[] entityTypes, SPClaim resolveInput, List<Microsoft.SharePoint.WebControls.PickerEntity> resolved) - This method will be called when you enter name in the people picker and click add, it will call fillresolve as it needs to resolve the name as soon as we have an entry in textbox.


You need to implement the Picker entity; Use SPClaim constructor instead of CreateClaim constructor.

private PickerEntity GetPickerEntity(string ClaimValue, string type)
{
PickerEntity pe = CreatePickerEntity();
 
/* in my case, emailaddress is the identity claim. Make sure that the last parameter TrustedProvider is correct, otherwise name resolution will not be correct. */

pe.Claim = new SPClaim("http://schemas.xmlsoap.org/ws/2005/05/identity/claims/emailaddress", ClaimValue, ClaimValueType, SPOriginalIssuers.Format(SPOriginalIssuerType.TrustedProvider, "Trusted User"));  

pe.EntityData[PeopleEditorEntityDataKeys.AccountName] = ClaimValue;
pe.EntityData[PeopleEditorEntityDataKeys.Email] = ClaimValue;
pe.DisplayText = ClaimValue;
pe.EntityData[PeopleEditorEntityDataKeys.DisplayName] = ClaimValue;
pe.EntityType = SPClaimEntityTypes.User;
pe.IsResolved = true;
return pe;
}

More Information

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.claims.spclaim.spclaim.aspx

http://blogs.technet.com/b/speschka/archive/2010/05/25/replacing-the-out-of-box-name-resolution-in-sharepoint-2010-part-2.aspx

http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.administration.claims.spclaimprovider.fillsearch.aspx

Powershell- Add or Remove User from Sharepoint Group

The below sample adds / removes list of user from a sample file.

Sample File: C:\Scripts\user.txt


domainname\user1
domainname\user2
domainname\user3


ADD USERS

$site = new-object Microsoft.SharePoint.SPSite("http://siteurl")
$web = $site.OpenWeb()

$group=$web.Groups["GroupName"]

$users=Get-Content C:\Scripts\user.txt

foreach ($user in $users) {

   write-host "adding user " $user  "to group "  $group
   $temp = $web.EnsureUser($user)
   $group.AddUser($temp)
  
}



REMOVE USERS

$site = new-object Microsoft.SharePoint.SPSite("http://siteurl")
$web = $site.OpenWeb()

$group=$web.Groups["GroupName"]

$users=Get-Content C:\Scripts\user.txt



foreach ($user in $users) {

   write-host "removing  user " $user  " from group "  $group
   $temp = $web.EnsureUser($user)
   $group.RemoveUser($temp)
  

Sunday, November 16, 2014

How to stop Silverlight videos via Javascript

I was exploring on how to stop the video that is being played within silverlight via javascript. I couldn't find any straight cut sample on stop function. However, updating or resetting source seems to do the trick !!!

You have to set id for your object tag

<object id=''videoID" ......>

Then I used jquery to set the source

$('#videoID').get(0).source = "<your xap file location>"

You can achieve the same using javascript as below

var videoElement=document.getElementById("videoID");
videoElement.source="<your xap file location>"

Sunday, March 23, 2014

Sharepoint - List all Site Level and Web Level features programmatically


The below sample is just for listing all site feature and current web level features.


static void Main(string[] args)
        {
            using (SPSite site = new SPSite("http://site collection url"))
            {
                Console.WriteLine("");
                Console.WriteLine("Site URL=" + site.Url);
                Console.WriteLine("");
                foreach (SPFeature f in site.Features)
                {
                    Console.WriteLine(f.Definition.Id + "======" + f.Definition.DisplayName + "======" + f.Definition.Parent);
                }


                using (SPWeb web = site.OpenWeb())
                {
                    Console.WriteLine("");
                    Console.WriteLine("\n\n Web URL=" + web.Url + "\n\n");
                    Console.WriteLine("");
                    foreach (SPFeature f in web.Features)
                    {
                        Console.WriteLine(f.Definition.Id + "======" + f.Definition.DisplayName + "======" + f.Definition.Parent);
                    }
                }
            }
            Console.WriteLine("");
            Console.WriteLine("Program Completed");

        }



If you want to display all web level features from all the subwebs, you need to write a recursive function to loop through all subsites and display the features.


Enable Developer Dashboard

$dash =[Microsoft.SharePoint.Administration.SPWebService]::ContentService.DeveloperDashboardSettings;
$dash.DisplayLevel = 'OnDemand';
$dash.TraceEnabled = $true;
$dash.Update() 


Disable/ Turn Off Developer Dashboard



$content = ([Microsoft.SharePoint.Administration.SPWebService]::ContentService)
$appsetting = $content.DeveloperDashboardSettings
$appsetting.DisplayLevel = [Microsoft.SharePoint.Administration.SPDeveloperDashboardLevel]::Off
$appsetting.Update()

Sharepoint Powershell - Copy Column (Fields) to list

$web = Get-SPWeb http://siteURL           
$sourcelist = $web.Lists["SourceList"]
$destlist = $web.Lists["DetinationList"]

$columns=$sourcelist.fields



foreach($col in $columns)
{
 if( $destlist.fields.ContainsField($col))
               {                                      
           # Write-Host "found" $col
               }
               else
               {
              Write-Host "Field not found ="     $col, $col.Type
              Write-Host "Adding Field" 
              $destlist.fields.Add($col)
               }


}

Write-Host "Script Completed" 

Friday, May 3, 2013

Powershell - Display Event Receivers for a specific Sharepoint List


$web=Get-SPWeb "http://siteURL"
$list=$web.Lists["ListName"]
$list.EventReceivers
$web.Dispose()

Display Names of the Event receivers 

$web=Get-SPWeb "http://SIteURL"
$list=$web.Lists["ListName"]

$list.EventReceivers |ForEach-Object {Write-host $_.Type  $_.Name}
$web.Dispose()

Powershell - Create Posts list to Blog site in Sharepoint


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

$site=new-Object Microsoft.SharePoint.SPSite("http://siteurl/sites/test/")

$web=$site.OpenWeb()

$SPTemplate = $web.ListTemplates["Posts"]


$web.Lists.Add("Posts","Description",$SPTemplate)

Powershell - Delete list from Sharepoint site



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

$site=new-Object Microsoft.SharePoint.SPSite("http://siteurl/sites/test/")

$web=$site.OpenWeb()

$list=$web.Lists["ListName"]

$list.Delete()

Friday, April 26, 2013

Get SPUser from sharepoint SPGroup


List<SPUser> usersLst = web.Groups[“GroupName”].Users.OfType<SPUser>().ToList<SPUser>();

How to fetch user from multi-valued column in ItemEventReceiver



if you have muli-valued column of type Person or Group, the afterpropeties will give results in the format
"9;#Admin;#11;#Reader;#13;#Contribute";
To get the username or group names from the above string format, use the below code.

  char[] separators = new char[] { ';', '#' };
  object objgroupNamesNew = properties.AfterProperties["UserGroup"];
  string gNew = Convert.ToString(objgroupNamesNew);
  string[] gpnameNew = gNew.Split(separators, StringSplitOptions.RemoveEmptyEntries);
  var groupNamesNew = gpnameNew.Where((gp, index) => index % 2 != 0);
  foreach (var grp in groupNamesNew)
            {
                Console.WriteLine(grp);
            }