Property Bag in SharePoint

In SharePoint we can store a property value like a Hash table (key- value pair) using custom coding.
This property can be used to set and retrieve at various objects of SharePoint like (SPSite, SPWeb)

Following is a small sample piece of code to set the property value

try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//open the web and set the property
using (SPSite spSite = new SPSite(strWebUrl))
{
using (SPWeb spweb = spSite.OpenWeb())
{
spweb.AllowUnsafeUpdates = true;
bool isPropertyFound = spweb.Properties.ContainsKey(propertyKey);
if (isPropertyFound)
{
spweb.Properties[propertyKey] = propertyValue;
}
else
{
spweb.Properties.Add(propertyKey, propertyValue);
}
spweb.Properties.Update();
spweb.Update();
spweb.AllowUnsafeUpdates = false;
}
}
});
}
catch (Exception ex)
{
throw ex;
}

How to Remove automatic web.config backup files in SharePoint using PowerShell

During SharePoint solution deployment, SharePoint takes a backup copy of the web.config with the name as web_.bak. Since SharePoint is taking the backup everytime when we deploy a solution during development of any webparts/any solution package, the files in the IIS physical folder will be keep on going, and its no longer required (in case of development/test).

I have created a small script in Powershell to delete the web.config backup files. Please note that this script is intended for development/test environment and dont directly use it in production environments. Also note that i am considering the default zone url of the web application. This script can be saved as .ps1 file (like RemoveSharePointWebconfigbackup.ps1) and can be schedule with windows scheduler to remove automatically, may be every day at 12AM.

Caution: Please Take the backup of IIS Folder before running at first time and second time

PowerShell Script :

Add-PSSnapin Microsoft.SharePoint.PowerShell -ErrorAction “SilentlyContinue”
[System.Reflection.Assembly]::LoadWithPartialName(“Microsoft.SharePoint”)
$WebApplication =”http://webapplicationurl”
$SPSite = New-Object Microsoft.SharePoint.SPSite($WebApplication)
$webApp = $SPSite.WebApplication
#get the IIS path
$IISSettings = $webApp.IisSettings[[Microsoft.SharePoint.Administration.SPUrlZone]::Default]

Write-Host ‘Displaying IIS path $IISSettings.Path’
$stIISPath = $IISSettings.Path.FullName
Write-Host $stIISPath
#write $WebApplication
$WebConfigBackFiles = Get-ChildItem $stIISPath web_*.bak
#Write-Host ‘ Files count =’
#Write-Host $WebConfigBackFiles
foreach ($tempFile in $WebConfigBackFiles)
{
 $t = “$stIISPath\$tempFile”
if($t.EndsWith(“.bak”))
{
   #Write-Host $t
    Remove-Item $t
}
}

CAML Query with more than two conditions

If we need to check more than 2 conditions in CAML Query then put Tag inside the original condition

Say for e.g. The following is the way for checking  more than 2 conditions in CAML Query

<Where>

     <And>

            <And>

                      <Eq><FieldRef Name=’ADId’ /><Value Type=’Text’>domain\user1</Value></Eq>

                     <Eq><FieldRef Name=’PopulationYear’ /><Value Type=’Text’>2011</Value></Eq>

           </And>

           <Eq><FieldRef Name=’RecordType’ /><Value Type=’Text’>Birthday</Value></Eq>

     </And>

 </Where>

SharePoint Discussion Forum Get url using CAML Query

Sometime we may need to get the Discussion forum list item url (folder url), we can use CAML Query to get that.

we can set the viewfields of the caml query with the below.

string stViewFields = “<FieldRef Name=’ID’/><FieldRef Name=’FileRef’ /><FieldRef Name=’Title’/><FieldRef Name=’Body’ />”;

add  the viewfields of the camlquery with FileRef field that will give the folder relative url

SPQuery camlQuery = new SPQuery();

camlQuery.Query = strQuery;

camlQuery.ViewFields = stViewFields;

SPListItemCollection ItemColl = currentWeb.Lists[“DiscussionListName”].GetItems(camlQuery);

The above list item collection will return the discussion list with folder relative url.

CAML Query to filter items with current logged in user

In CAML Query we may need to filter records based on the current logged in user, in list view we can use the [Me] to filter, the same functionality we can achieve using CAML query

Below is the query which will return all tasks assigned to current logged in user and the task is not completed.

<Where>
<And>
<Eq>
<FieldRef Name=’AssignedTo’></FieldRef><Value Type=’Integer’><UserID Type=’Integer’ /></Value>
</Eq>
<Neq>
<FieldRef Name=’Status’/>
<Value Type=’Text’>Completed</Value>
</Neq>
</And>
</Where>

How to log SharePoint custom webpart errors into ULS folder

When we use the custom webpart and deployed to SharePoint, sometime the webpart may throw some error and administrator needs to know when and from where the error is throwing.

To log the error in SharePoint 12 hive (or SharePoint root in 2010), we need to use the following command in the catch block of the webpart/custom code.

sample code

try

{

// do something that will throw error

}

catch (Exception ex)

{

Microsoft.Office.Server.Diagnostics.PortalLog.LogString(” Error occured in Custom xyz control ” + ex.Message + ex.Source + ex.StackTrace);

}

To compile the webpart/custom code we need to include the reference assembly Microsoft.Office.Server.dll from ISAPI Folder from Sharepoint 12 hive (or Sharepoint root).

Now compile the code and deploy and when the code throws some error we can check the ULS log to get the details about the error.


SharePoint Browser Cache safe url

In SharePoint we can use the layouts folder to place the images/css/js files so that it can cache for 365 days(default settings of IIS pointing to the layouts folder), this has advantage that it can cache the files for 365 days. But sometimes we can modify the files at that time we need to ensure that the client browser must read the updated file instead of serving from the local browser cache (of client machine)

This can be achieved by developing a small piece of custom code (probably a user control and refer it in the master page). This usercontrol will get some property of the file (css/js) and we can use the SPUtility.MakeBrowserCacheSafeLayoutsUrl(“filename.ext”,false). And we can use a literal control to generate the appropriate tags.

This basically generate a url like http://websitename/_layouts/filename.ext?rev=MlFHGUOJpQLunJnOWiGaog%3D%3D

The querystring rev will be generated based on the timestamp of the file and append to the filename.ext, so that everytime the new copy of the file is posted the token will be generated freshly.

Note: We need to do IIS reset to make sure that the new token will be generated otherwise the old token will be served from the server.

SharePoint XSLT filter for lookup column

In SharePoint XSLT Data view webpart with multiple values lookup column to filter based on querystring values can be achieved using XSLT Filtering

Here is XSLT
filter to do the this, it filters out the rows based on the query
string parameter.
[contains(concat(@Category,’;’),concat($QuerystringParameter,’;’))]
Here
we are appending the value with a character (for example ‘;’) because
the result of both functions [contains(‘1′,’1’) and contains(‘1′,’11’)]
returns true but using [contains(‘1;’,’1;’)] solves the problem.

Thanks to the post

SharePoint Event Handler cancel the item adding without throwing error

In SharePoint Event handler its possible to cancel the event but it will automatically throws an error (when we use properties.cancel = true; code).

To avoid this error, we can set the status property of the event.

//sample code
properties.Cancel = true;
properties.Status = SPEventReceiverStatus.CancelNoError; //This will suppress the error

Moss How to remove My settings in Welcome Menu

Sometime you may want to hide the MySettings menu item from the Welcome control of SharePoint
You can follow the steps below:

1. Take a copy of Welcome.ascx file (under 12 hive\Template\ControlTemplates folder)
2. Rename it as CustWelcome.ascx
3. Find the tag with Personalization For Eg:

<SharePoint:MenuItemTemplate runat=”server” id=”ID_PersonalInformation”
Text=”<%$Resources:wss,personalactions_personalinformation%>”
Description=”<%$Resources:wss,personalactions_personalinformationdescription%>”
MenuGroupId=”100″
Sequence=”100″
ImageUrl=”/_layouts/images/menuprofile.gif”
UseShortId=”true”
Visible=”true”
/>
Change the Visible to false (if visible is missing add it and set it as false)

<SharePoint:MenuItemTemplate runat=”server” id=”ID_PersonalInformation”
Text=”<%$Resources:wss,personalactions_personalinformation%>”
Description=”<%$Resources:wss,personalactions_personalinformationdescription%>”
MenuGroupId=”100″
Sequence=”100″
ImageUrl=”/_layouts/images/menuprofile.gif”
UseShortId=”true”
Visible=”false”
/>

Now go to the master page and change the reference from welcome.ascx file to CustWelcome.ascx