Display User field in search result

How to display custom user field in search result .

This includes two steps field definition and create a managed metadata property.

1. Field Definition

<Field ID=”{AE6EFA2E-DF0E-4EF5-8AB7-309FBC5465B9}”

Group=”My Columns”
Mult=”FALSE”
UserSelectionMode=”0″
Type=”UserMulti” List=”UserInfo”
Name=”helloauthor” DisplayName=”helloauthor”
SourceID=”http://schemas.microsoft.com/sharepoint/v3&#8243;
StaticName=”helloauthor”

/>

2. Before creating managed property add some data to the field may be in your
documents library or custom list etc… and then crawl the search , once
your property is propagated  then create managed property.

Now re crawl your search and the perform search based on user name.

Advertisements

Upload file in SharePoint Style Library using Powershell

This Powershell code snippet upload xsl file into style library.

 

 

if ( (Get-PSSnapin -Name Microsoft.SharePoint.PowerShell -ErrorAction SilentlyContinue) -eq $null )
{
Add-PsSnapin Microsoft.SharePoint.PowerShell
}

#Script settings
$webUrl = “http://MKS&#8221;

function UploadFile( [String] $FilePath)
{
#Open web and library
$web = Get-SPWeb $webUrl

$file =Get-Item $FilePath
write-host “Started Uploading File……”$file.FullName

#Open file
$fileStream = ([System.IO.FileInfo] (Get-Item $file.FullName)).OpenRead()

$folder =  $web.getfolder(“Style Library”)

$web.GetFile($folder.Url + “/XSL Style Sheets/” + $file.Name).CheckOut()

$spFile = $folder.Files.Add($folder.Url + “/XSL Style Sheets/” + $file.Name, [System.IO.Stream]$fileStream, $true)

$spFile.CheckIn(“Checkin by Powershell”)
$spFile.Publish(“Published by Powershell”)

write-host $webUrl”/”$folder.Url”/XSL Style Sheets/”$file.Name

write-host “Successfully Copyied file ” $file.Name

$fileStream.Close();

$web.Dispose()
}

UploadFile -FilePath “C:\***.xsl”

How to create a Lookup Field From Sub-Site List to Root-Site Collection List (Cross-Site Lookup)

This solution is based on power shell script for creating cross site look up field.

For example there is a sub site http://mksportal/site1 which contains a list “Product Name”  and
there is another sub site http://mksportal/site2/site3.
In order to make cross site look up field available to sub site through content type,
this can be achieved by using power shell script.

There are couple of things mandatory, when cross site look up is created on that time both sub site and list must exist because it is dependent on list ID.
This is basic script, one can customize further like add reference field for the same lookup field mapped to other field like ID etc.
try
{

$mksWebSite =  “http://mksPortal/Site1&#8221;

$spweb = Get-SPWeb $mksWebSite
$webids=$spweb.ID

$lst = $spweb.Lists[“Product Name”]

$fieldXML = ‘
<Field ID=”GUID”
Name=”mksField”
Group=”MKS
Type=”Lookup”
DisplayName=”mksField”
StaticName=”mksField”
List=”{‘ + $lst.ID +’}”
ShowField=”Title”
Overwrite=”TRUE”
WebId=”‘ + $webids + ‘”  ></Field>’

$field = $spweb.Site.RootWeb.Fields.AddFieldAsXml($fieldXML)
$fieldRef = $spweb.Site.RootWeb.Fields.AddFieldAsXml($mksFIELDRef)
$spweb.Site.RootWeb.Update()
$ctypeParent = $spweb.Site.RootWeb.availablecontenttypes[“My Custo CType”]
$newContentType = $spweb.Site.RootWeb.ContentTypes[$ctypeParent.ID];
$fieldLink = new-object Microsoft.SharePoint.SPFieldLink($spweb.Site.RootWeb.Fields[ $fieldInternalName])
$newContentType.FieldLinks.Add($fieldLink)
$newContentType.Update()

$spweb.Dispose()

}

catch [System.SystemException]

{

write-host “Execution stopped due to: “+$_.Message -foregroundcolor Red

}

How to revert library items to its previous working condition.

There are some scenarios in day to day development, where current changes need to revert to  its previous working condition.
This can be achieved by finding the correct Version from Version-History of the item
and restore it accordingly.
The below code snippet is just for information, for files in document library and has the same approach for List Item as well.

Sample code Snippet…..

using (SPSite mksSite = new SPSite(“http://devsp:9900/&#8221;))
{
using (SPWeb mksWeb = mksSite.OpenWeb())
{
mksWeb.AllowUnsafeUpdates = true;
SPList lst = mksWeb.Lists[“helloListName”];
IEnumerable<SPListItem> demoLib = lst.Items.OfType<SPListItem>();
SPListItemCollection demoFormCollection = lst.Items;
XmlDocument itemVersionDoc = new XmlDocument();
using (WebClient client = new WebClient())
{
for (int i = 0; i < demoFormCollection.Count; i++)
{
SPListItem item = demoFormCollection[i];
byte[] fileByte = item.File.OpenBinary(SPOpenBinaryOptions.None);

// Validate your output if this is the correct one. THEN no further action required//

if (THE OUTPUT AFTER VALIDATION IS INCORRECT THEN)
{

IEnumerable<SPFileVersion> listItems = item.File.Versions.OfType<SPFileVersion>();

var allResults = listItems.OrderByDescending(prod => prod.ID);

foreach (var vitem in allResults)
{

bool needToFindOtherVersion = true;
{
if (needToFindOtherVersion)
{
//<MOST IMPORTANT> “_vti_history” IS THE PLACE FOR ALL THE VERSIONS//

client.Credentials = CredentialCache.DefaultCredentials;
fileByte = client.DownloadData(mksWeb.Url.TrimEnd(‘/’)
+ “/_vti_history/” + vitem.ID.ToString() + “/helloListName/” + item.Title);

//NOTE: fileByte is the OUTPUT from  VERSION HISTORY//

//CHECK IF THE OUTPUT IS THE CORRECT ONE AS PER REQUIREMENT//
if (THE OUTPUT AFTER VALIDATION IS INCORRECT THEN)
{
needToFindOtherVersion = true;
}
else
{
needToFindOtherVersion = false;

item.File.Versions.RestoreByLabel(vitem.VersionLabel);
Console.WriteLine(“Correct Version Restored Successfully.“);
break;
}
}

}
}

}
mksWeb.AllowUnsafeUpdates = false;
}

Create Role Permission Dynamically

First Create SPSite and  SPWeb (web Object), assuming it is already created…

Now creating Permission Object
Assuming you have comma separated Permission for which you want to
create Role

string Perm = “AddListItems,EditListItems,ManageLists”;

Next thing is to convert the permissions in the form of string to SPBasePermissions

SPBasePermissions BP = (SPBasePermissions)Enum.Parse(typeof(SPBasePermissions),Perm.TrimEnd(‘,’), true);

SPRoleDefinition def = new SPRoleDefinition();
def.Description = “MKS Role for ” + roleName;
def.BasePermissions =  BP;
def.Name = roleName;
web.FirstUniqueRoleDefinitionWeb.RoleDefinitions.Add(def);
web.FirstUniqueRoleDefinitionWeb.Update();
web.FirstUniqueRoleDefinitionWeb.Dispose();
web = web.Site.OpenWeb();

In order to update RoleDefinition

SPRoleDefinition def = web.RoleDefinitions[roleName];
def.BasePermissions = BP;
def.Description = “MKS Roles for  ” + roleName;
def.Update();
web.Update();


To Check duplicate Role

//XML of the roledefinitions
XmlDocument doc = new XmlDocument();
doc.LoadXml(web.RoleDefinitions.Xml);

XmlNode node = doc.SelectSingleNode(“//Role[@Name='” + roleName + “‘]”);
//if the search returned null, the role does not exist
if (node == null)
return false;
else
return true;

Install Solution

Install Solution

The deployment of a WSS solution to a front-end Web server or an application server is performed in two phases

1. Add wsp to Solution Store
The solution store is part of the configuration database and stores the
various .wsp files
2. Deploy Solution
Solution can be deployed to one or more WSS Web Server/Application Server

stsadm -o addsolution -filename MKSTest.wsp
stsadm.exe -o execadmsvcjobs

stsadm -o deploysolution -name MKSTest.wsp -url http://xyz.com
Note : Targeting one site collection
stsadm -o deploysolution -name MKSTest.wsp -immediate -allcontenturls -allowGacDeployment -allowCasPolicies
Note: Push  solution to every site collection available within the server farm

stsadm.exe -o execadmsvcjobs
stsadm -o installfeature -name MKSTestFeature  -force
stsadm -o activatefeature -name MKSTestFeature  -force -url http://localhost

Uninstall Solution

stsadm -o uninstallfeature -name MKSTestFeature  -force
stsadm -o deactivatefeature -name MKSTestFeature  -force -url http://localhost
stsadm -o retractsolution -name MKSTest.wsp -immediate -allcontenturls
stsadm.exe -o execadmsvcjobs
stsadm -o deletesolution -name MKSTest.wsp -override

MOSS 2007 Timer Jobs

SharePoint Timer service is similar to Windows Task or Windows Services.
Time job inherits from

Microsoft.SharePoint.Administration.SPJobDefinition

using System;
using System.Net;
using Microsoft.SharePoint;
using Microsoft.SharePoint.Administration;

namespace MKS.Demo {
  public class TestTimerJobs : SPJobDefinition {

    public TestTimerJobs() : base() { }

    public TestTimerJobs(SPWebApplication webApp)
      : base(Globals.JobName, webApp, null, SPJobLockType.ContentDatabase) {
      this.Title = Globals.JobName;
    }

public TestTimerJobs(string TimerName , SPWebApplication webApp)
      : base(TimerName , webApp, null, SPJobLockType.ContentDatabase) {
      this.Title = TimerName ;
    }

  }
}

There are three different types of locking,

  • SPJobLockType.ContentDatabase Locks the content database associated with the job.
  • SPJobLockType.Job Locks the job to prevent multiple instances of the job from running on a single server.
  • SPJobLockType.None No locking.

Override the Execute virtual method defined in the SPJobDefinition.

public override void Execute (Guid targetInstanceId)
{
//Write your custom Logic here.
}

Compile the DLL and place it into GAC.

Deploymet


    // Get the object of TestTimerJobs what is deployed in GAC
    TestTimerJobs taskLoggerJob = new TestTimerJobs("TEST TIMER JOB", site.WebApplication);
    SPMinuteSchedule schedule = new SPMinuteSchedule();
    schedule.BeginSecond = 0;
    schedule.EndSecond = 59;
    schedule.Interval = 5;
    TestTimerJobs.Schedule = schedule;
    //update the job
   TestTimerJobs.Update();
BeginSecond and EndSecond specify that timer job can start
randomly in between.

Interval is a 32-bit integer that specifies the interval in minutes. The default value is 5.