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
}
}

SharePoint Custom webpart with SharePoint resource files

 

In SharePoint custom webpart we may need to display the message or label text from a congfiguration resource files, this article shows the how to read the resource files from the custom webpart.

The article shows the step by step with the help of visual studio 2010.

Step 1: First we need to create the visual webpart project in visual studio 2010.

Step 2: After adding the visual webpart project, in the solution explorer, right click and add new sharepoint mapped folder and refer the folder Resources.

Once the resource folder is mapped, right click and add the folder (since so many resource files are present in the 14\Resource folder used by sharepoint and we create our own folder and use it for the particular webpart /particular web application ). Lets call the folder as CustomResource folder.

Step 3: Now add the resource file by right click on the CustomResource folder and add new item, select c#, and select the resource file, name it as CustomResource.resx

Step4 : Add the key value in the resources file, say for e.g CustomSuccessMsg, and value as “Thanks for submitting the form “.

Step 5: Now we can use the resoure file in our custom webpart, by adding the below code.

uint currentLanguage = currentWeb != null ? currentWeb.Language : 1033;

string stSuccessMsg = SPUtility.GetLocalizedString(“$Resources:CustomSuccessMsg”, “CustomResource\\CustomResource”, currentLanguage );

Step 6: now compile the webpart and deploy using vs 2010 or using powershell.

Once its deployed if the site is running in english language then it will read it from CustomResource.resx file from the CustomResource folder of SharePoint Root folder.

If the language is differnet, then appropriate resource file is required. Some sample resource file name appropriate lanaguage

CustomResource.en-US.resx

CusotmResource.en-GB.resx

CustomResource.fr.resx

I hope this will help some one who try to use resource file to store the message or listname or any other configuration parameter according to the lanaguage of the site is going to be used.




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.

Hide Quick launch in SharePoint 2010

To hide the quick launch bar in sharepoint 2010, we can easily achieve using css class.

We can either include in page layout/in content editor webpart by adding the following css.

<style type=”text/css”>
/* hide the left menu */
#s4-leftpanel{
display:none; /* hide the entire quick launch content */
}
.s4-ca{
margin-left:0px; /* move the content area to left */
}

</style>

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>

Stsadm.exe Object Reference not set to an instance of an object error for administrators who is deploying a solution

In SharePoint 2010, with administrators account (not the default Sharepoint System account) users getting the object reference not set to an instance of an object.

To solve the issue, we need to give shell access permission in the SQL Server for that particular user in SharePoint_config database.

Go to SQL Management Studio -> Login  using sa account/admin login -> Select Security ->expand login -> select the user (if its not there add the user and select) -> properties

Please check the below screen for the permission

Sharepoint_SQL_shell_accesspermission

I hope this may helpful for who are always using System account to deploy the solution, even if you have another account which has admin rights.

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.