Friday, December 23, 2011

How To Redirect a Blog to Another Blog Automatically

Blog Redirecting: If you have created a New Blog or Own Blog site, ultimately you will be moving the existing blog's content to new one.
And definitely you want to get all the traffic to new Blog rather than old Blog.

Here is the best idea to divert all the users who come to old blog with search results or direct way, by redirecting from old blog to new.

Follow the below steps :
1. Go to Old Blog Dashboard -> Design -> Edit HTML -> Edit Template
2. Search for
3. Add a meta tag
<meta content="0;url=http://NEW BLOG URL" http-equiv="refresh"/>
next to the above line of code
4. Save the template html

Thats it, done. Verify it by typing your old blog url in the browser, it redirects to new blog always.

Thursday, December 22, 2011

SharePoint Batch Deleting List Items Programatically

While working on a custom SharePoint solution, I had a requirement to delete multiple list items one time rather than deleting one by one.
Example: Delete only the items from a list which doesn't have value for a custom column.

When i think of the solution i couldn't make new SPListItemCollection object out of the items which needs to be deleted, which is possible in regular c# application development.
However in SharePoint we can do the batch delete of list items using CAML script.
The CAML script needs to be generated for the items which needs to be deleted as below.

Get the list items:
SPListItemCollection items = spList.Items;
Generate CAML Script:
StringBuilder methodBuilder = new StringBuilder();

string batchFormat = "" +
"{0}"; //{0}-methodFormat

string methodFormat = "" + //{0}-Unique Value for each Item
"{1}" + //{1}-List Guid
"{2}" + //{2}-List ItemID
"Delete" +
"
";

// Build the CAML delete command script.
foreach (SPListItem item in items)
{
//get the custom column value
string customColumnValue = string.Empty;
if (null != item["CustomColumnName"])
customColumnValue = item["CustomColumnName"].ToString();

//check whether custom column is empty
if (string.IsNullOrEmpty(customColumnValue))
{
methodBuilder.AppendFormat(methodFormat, item.ID, item.ParentList.ID, item.ID);
}
}

//batch delete script.
string batchDeleteScript = string.Format(batchFormat, methodBuilder.ToString());
Execute CAML Script:
spWeb.ProcessBatchData(batchDeleteScript);
Similarly batch updating script can also be generated. Look at the detailed post here for code.

SharePoint Batch Updating List Items Programatically

While working on a custom SharePoint solution, I had a requirement to update multiple list items one time rather than updating one by one.
Example: Update only the items in a list which doesn't have value for a custom column (update with some value).

When i think of the solution i couldn't make new SPListItemCollection object out of the items which needs to be updated, which is possible in regular c# application development.
However in SharePoint we can do the batch update of list items using CAML script.
The CAML script needs to be generated for the items which needs to be updated as below.

Get the list items:
SPListItemCollection items = spList.Items;
Generate CAML Script:
StringBuilder methodBuilder = new StringBuilder();

string batchFormat = "" +
"{0}"; //{0}-methodFormat

string methodFormat = "" + //{0}-Unique Value for each Item
"{1}" + //{1}-List Guid
"Save" +
"{2}" + //{2}-List ItemID
"{4}" + //{3}-Column Name, {4}-Column Value
"";

// Build the CAML update command script.
foreach (SPListItem item in items)
{
    //get the custom column value
    string customColumnValue = string.Empty;
    if (null != item["CustomColumnName"])
        customColumnValue = item["CustomColumnName"].ToString();
    
    //check whether custom column is empty
    if (string.IsNullOrEmpty(customColumnValue))
    {
        methodBuilder.AppendFormat(methodFormat, item.ID, item.ParentList.ID, item.ID, "CustomColumnName", "New Updated Value");
    }
}

//batch update script.  
string batchUpdateScript = string.Format(batchFormat, methodBuilder.ToString());
Execute CAML Script:
spWeb.ProcessBatchData(batchUpdateScript);

Similarly batch deleting script can also be generated. Look at the detailed post here for code.

Tuesday, December 20, 2011

JavaScript Find Absolute Position of element

Scenario: Get coordinates of a element (X, Y) to display overlay message immediate next or immediate below the element.
Based on the coordinates set the absolute position of the control (overlay) to display it accordingly. The overlay can be started any side/corner of the element.

Get the element object using JavaScript:
var obj = document.getElementById("controlelement");
Get the position of the element from Left
function findPosLeft(obj) 
{
var posLeft = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
posLeft += obj.offsetLeft;
obj = obj.offsetParent;
}
}
else if (obj.x)
{
posLeft += obj.x;
}

return posLeft;
}
Get the position of the element from Top
function findPosTop(obj) 
{
var posTop = 0;
if (obj.offsetParent)
{
while (obj.offsetParent)
{
posTop += obj.offsetTop;
obj = obj.offsetParent;
}
}
else if (obj.y)
{
posTop += obj.y;
}
return posTop;
}
Get the position of the element from Bottom
function findPosBottom(obj) 
{
var posBottom = 0;
if (obj.offsetParent)
{
posBottom += obj.offsetHeight;
while (obj.offsetParent)
{
posBottom += obj.offsetTop;
obj = obj.offsetParent;
}
}
else if (obj.y)
{
posBottom += obj.y;
posBottom += obj.height;
}
return posBottom;
}
Get the position of the element from Right
function findPosRight(obj) 
{
var posRight = 0;
if (obj.offsetParent)
{
posRight += obj.offsetWidth;
while (obj.offsetParent)
{
posRight += obj.offsetLeft;
obj = obj.offsetParent;
}
}
else if (obj.x)
{
posRight += obj.x;
posRight += obj.width;
}
return posRight;
}

JQuery Find Absolute Position of element

Scenario: Get coordinates of a element(X, Y) to display overlay message immediate next or immediate below the element.
Based on the coordinates set the absolute position of the control (overlay) to display it accordingly. The overlay can be started any side/corner of the element.

Get the element object using JQuery:
var obj = $('[id$=controlelement]');
Get the position of the element from Left
function findPosLeft(obj) 
{
var pos = obj.offset();
var left = pos.left;
return left;
}
Get the position of the element from Top
function findPosTop(obj) 
{
var pos = obj.offset();
var top = pos.top;
return top;
}
Get the position of the element from Bottom
function findPosBottom(obj) 
{
var pos = obj.offset();
var top = pos.top;
var height = obj.height();
var bottom = top + height;
return bottom;
}
Get the position of the element from Right
function findPosRight(obj) 
{
var pos = obj.offset();
var left = pos.left;
var width = obj.width();
var right = left + width;
return right;
}

SharePoint Check Memory Leaks in Custom Solution Development

In any SharePoint custom solution development, it is very important to make sure there are no memory leaks in the code. If there are any memory leaks the performance will be down and might face unnecessary issues at run-time.
While developing the code every developer ensures that SPSite and SPWeb objects are disposed either way (using clause or dispose method). But in a bigger solutions there are always chances for missing them in manual verification.

How good if there is a tool available to verify whether our solution (code) has any memory leaks, which can be checked in seconds of time. Yes there is a tool for the same. You can download it from SPDisposeChecker.

Even you can make this Tool as part of your visual studio Tools. Follow the simple 3 steps.

SharePoint Read Resource File Programatically

SharePoint custom solution development might requires some dynamic or configuration values. Generally the high level configurations can be stored in web.config(Ex: external connection string). But if there are more number of configurations required (Es: List columns, Content type names etc.,) we cannot store them in .config file as it is not safe.

So here the resource file comes into picture. Resource file is XML-Based file which holds the data in key-value pair. Resource file is generally used to store huge configurations for re-usability & consistency and Localization.

Resource file (.resx) should be added to 12\Resources directory in the solution as a new item.
The name format is SampleResourceFile.en-US.resx

Usage:
If the solution provides provisioning of lists or libraries with multiple columns programatically using either code or xml, All the column names can be stored in Resource file as a Key-Value pair.

Read Resource File: XML
The resource value for a key can be read in XML as below.
Read Resource File: C# Code
The resource value for a key can be read in c# as below.
string customColumnNameKey = SPUtility.GetLocalizedString("$Resources:CustomColumnNameKey", SampleResourceFile, (uint)CultureInfo.CurrentCulture.LCID); //LCIT is current local languare
To read the resource file programatically, a common wrapper class can be created to read the resource file throughout the solution by passing the key.
public class Resources
{
/// Resource File Name.
/// Filename can be configured in web.configured or can be used as constant.
private const string RESOURCE_FILE_NAME = "SampleResourceFile";

/// Method to get the singleton instance.
public static string GetValue(string key)
{
return SPUtility.GetLocalizedString("$Resources:" + key, RESOURCE_FILE_NAME, (uint)CultureInfo.CurrentCulture.LCID);
}
}

string customColumnName = Resources.GetValue("CustomColumnNameKey");

Friday, August 26, 2011

How To Download Folder from SharePoint Document Library or List

Scenario: SharePoint document library download folder

Generally SharePoint is used for Content & Document Management System. If it is more of Document Management System, users will upload and download files and documents quite often to/from document library or list.

Downloading a single document or file is straight forward, by clicking on the file. But there is no straight way to download folder from SharePoint document library. And downloading one by one file from a library is hectic if it has has more number of files (say 100s).

However a folder with all the files can be downloaded easily by following the below steps:
1. Go to the document library or list.
2. Open Explorer View of the respective document library.
3. Drag & Drop the folder from library to local drive.
                               OR
    Select the folder -> right click -> copy, then paste it on the local drive.

Tuesday, August 23, 2011

How To Install IIS7 on Windows7 and Windows Vista

I have faced issues in configuring/installing II7 on my machine (which has windows 7 installed) from Control Panel -> Program Files -> Turn Windows features on or off. It is always throwing an error message "one or more components are not installed".

To address this i found a nice(microsoft) tool Microsoft Web Platform Installer, which installs II7 in a single click.
And also it provides many other microsoft related features installation/configuration.


How To Repair SUSPECT Database

Sometimes we see a SharePoint error "Cannot connect to the configuration database". One of the reasons for this could be the Respective DataBase is set to SUSPECT mode.

Reasons for database SUSPECT state:
1. Database corruption.
2. Not enough space for the SQL Server to recover the database during startup.
3. Insufficient memory or disk space.
4. Unexpected SQL Server Shutdown, Power failure or a Hardware failure.

Follow the below steps to repair the SUSPECT database:
1. Identify all the databases which are in SUSPECT mode
USE master
GO
SELECT NAME,STATE_DESC FROM SYS.DATABASES
WHERE STATE_DESC='SUSPECT'
GO
Note:Check the latest log for the database which is marked as suspect.
SQL Server -> Management -> SQL Server Logs

2. Get the database first into EMERGENCY mode to repair it
USE master
GO
ALTER DATABASE "databasename" SET EMERGENCY
GO
Note: The EMERGENCY database is one way which means read-only.

3. Repair the Database in emergency mode
DBCC checkdb('databasename')
ALTER DATABASE "databasename" SET SINGLE_USER WITH ROLLBACK IMMEDIATE
DBCC CheckDB ('databasename', REPAIR_ALLOW_DATA_LOSS)
ALTER DATABASE "databasename" SET MULTI_USER

Thursday, August 11, 2011

SharePoint Feature Activation Dependency

Scinario:
While provisiong two dependent(one on the other) content/solutions through different features, it is that one of the features might need the resources of other while gettting activated. In this scinario the first feature should be activated before the second, to avoid the dependency issues.

Example:
Feature 1. Custom Content Type
Feature 2. Page with Custom Content Type (dependent on custom content type)

To make sure the same through feature provisioning instead manually, we have feature activation dependency attribute which can be specified in feature.xml file. Which doesn't allow to get activated unless until the dependency feature(s) is activated.




Title="Feature Dependency: Page with Custom Content Type"

Description="Feature Activation Dependency: Page with Custom Content Type."

Version="1.0.0.0"

Hidden="FALSE"

Scope="Web"

DefaultResourceFile="core"

xmlns="http://schemas.microsoft.com/sharepoint/">


































Note: Multiple dependencies can be specified for one feature.

SharePoint PageViewer WebPart Resize Issue

SharePoint OTB PageViewer works fine to display a static web page. But it has a Resizing issue when the source web page has some links which redirects to some other target pages (of more dimentions than source page) within the PageViewer webpart.

Issue/Scinario:
1. A custom search page of height 500x300 is added to pageviewer.
2. The results page with 2 results resize to 300x200.
Now say the result item link redirects to new web page of dimensions 600x500. As pageviewer doesn't support resizing the new page will be shown in 300x200 dimensions.

Solution:
A Content Editor WebPart instead PageViewer WebPart can be used with below iframe and source script to address the resize issue.

Limitations:
The content editor webpart height and width should be set to fixed values(for best page view).







Wednesday, August 10, 2011

SharePoint Copy Survey from One Server to Another

Migrating the survey list from one location(server) to another location(server) is very simple, if we go for list template. But this process doesn't work if the requirement demands for the existing responses along with survey details.

Though it copies all the survey details and responses details, the responded user(created by and modified by) and datetime (created and modified) details are replaced with current user (who is creating the survey with the template) and current datetime details.

To copy the survey as is (all questions and responses) i found a nice codeplex tool SharePoint Content Deployment Wizard. The post has the detailed documentation on what it can do and how can be used.

This also works with limitations:
The settings of the source Survey should be set as follows before copying.
Go to Survey list -> Survey Settings
1. Allow multiple responses (Yes)(Advanced Settings)
2. Edit access: Specify which responses users can edit
All responses (Yes)(Title, Description and Navigation)
After copying the survey, the settings can be again changed to earlier state.

It also helps in copying the following as well.
- site collections
- webs
- lists
- folders
- list items (including files)

Tuesday, August 9, 2011

How To Get SharePoint List form URLs Programatically

Getting the SharePoint List Item form URLs (New / Edit / View) dynamically respect to the context instead of hard-coding.

SPListItem listItem = SPList.GetItemById(itemID);

// New form full url
string newFormFullUrl = string.Format("{0}{1}?ID={2}", listItem.Web.Url, listItem.ParentList.Forms[PAGETYPE.PAGE_NEWFORM].ServerRelativeUrl, listItem.ID);

// Edit form full url
string editFormFullUrl = string.Format("{0}{1}?ID={2}", listItem.Web.Url, listItem.ParentList.Forms[PAGETYPE.PAGE_EDITFORM].ServerRelativeUrl, listItem.ID);

// Display form full url
string displayFormFullUrl = string.Format("{0}{1}?ID={2}", listItem.Web.Url, listItem.ParentList.Forms[PAGETYPE.PAGE_DISPLAYFORM].ServerRelativeUrl, listItem.ID);

//Relative Url
string newFormRelativeUrl = string.Format("{0}?ID={1}", listItem.ParentList.Forms[PAGETYPE.PAGE_NEWFORM].ServerRelativeUrl, listItem.ID);

Wednesday, April 20, 2011

C# FileName Remove Special Characters not Allowed in FileName

While generating a filename programatically/dynamically by accepting the filename as user input, it is mandatory to make the raw filename valid by removing the special characters if given.

The following are the special characters which are not allowed in filename.
\/:*?"<>|#%&.{}~
Note: Period(.) is allowed but as filename can't be start or end with it and consecutive periods(.. or ...) are not allowed, considering it as invalid char for filename.
using System;

using System.Linq;

private static string GetValidFileName(string rawFileName)

{

string fileName = rawFileName;

//special chars not allowed in filename

string specialChars = @"\/:*?""<>|#%&.{}~";

//Replace special chars in raw filename with empty spaces to make it valid

Array.ForEach(specialChars.ToCharArray(), specialChar => fileName = fileName.Replace(specialChar, ' '));

fileName = fileName.Replace(" ", string.Empty);//Recommended to remove the empty spaces in filename

return fileName;

}


To know more about filename constraints, look at the detailed post here.

Wednesday, March 30, 2011

SharePoint Error Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack

One of the scenarios of getting this exception is with improper usage of SPSecurity.RunWithElevatedPrivileges.

One of my posts here describes on proper usage of SPSecurity.RunWithElevatedPrivileges to address the same issue.

SharePoint SPSecurity.RunWithElevatedPrivileges Usage

SPSecurity.RunWithElevatedPrivileges is used to run or execute the set of code statements in the context of an Application Pool Account instead of Current Logged in User.

The below code snippet shows the implementation details.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
web.AllowUnSafeUpdates = true;
//Code to edit/delete the file in a library
web.AllowUnsafeUpdates = false;
}
}
});
SPContext.Current.Web can not be used directly with in the RunWithElevatedPrivileges block as the SPWeb object becomes a instance of current logged-in user's context and it gives the below error if tries to update any content in the same Web with READ only access.

Error : Unable to evaluate expression because the code is optimized or a native frame is on top of the call stack.

To address the issue, a new instance of SPSite and SPWeb should be cerated within the RunWithElevatedPrivileges code block as above.

SharePoint Layout Page for Only Administrator Accessible

SharePoint Layout (Application) pages are accessible by any user who has a least possible access/permissions for any of the sites in the server/farm.

A layout page access can be restricted to only Site Administrator by overriding the RequireSiteAdministrator property of LayoutsPageBase class.

The below code snippet shows sample implementation.
using Microsoft.SharePoint.WebControls;
public class MyLayoutPage : LayoutsPageBase
{
//It mmakes sure only site administrators can access this page
protected override bool RequireSiteAdministrator
{
get
{
return true;
}
}
protected void Page_Load(object sender, EventArgs e)
{
//Code goes here...
}
}
It is just one of the members, look at the post here to know about many other members/methods of LayoutsPageBase class.

SharePoint Manager Tool for Heirarchical View of Content

SharePoint Manager is a very userful and powerful tool for SharePoint developers for reverse engineering, just like .NET Reflector for .Net developers.

SharePoint Manager tool is from the same person who wrote WSPBuilder (another must have tool) in SharePoint Development.

This tool helps the developers to traverse all the content from FARM -> Web Application -> Site Collection -> Web Site -> Libraries -> List Item -> Field etc., in a heirarchical view in a explorer tree view.

It also gives the xml, data of a specific item, properties, caml query of views etc.,

Download the SharePoint Manager 2007/2010.

Tuesday, March 29, 2011

C# Code Quality Tools

Code quality is very important in delivering the reliable solutions.
But most of the developers simply write the code to implement a solution for the requirement.

I strongly recommend to analyse the code before delivering. I suggest the below code analysis tools wchich works with Visual Studio integration.

StyleCop
FxCop

These tools really helps in analysing the code and suggesting the improvements on design, localization, performance, security, naming convensions and Readability.

And also gives the report on Unused parameters in functions, Unused functions, Wrong scope (of functions, variables, enums, etc.,).

Find the list of tools for static code analysis here.

C# TimeZone Corresponding Time

In an Application (public web site) Development, TimeZone is the key if there is a time dependency for making some actions/transactions and the site is public facing across the Globe in different time zones.

TimeZoneInfo class holds the information of TimeZone properties i.e., TimeZone Display Name, TimeZone ID, All the available TimeZones and the Local TimeZone.

The below code snippet explains the real time implementation to get the TimeZone Corresponding Time.
private DateTime GetBaseDateTime(string sourceTimeZoneName)
{
  TimeZoneInfo sourceTimeZone = null;
  //loop through all the TimeZones to get source TimeZone object
  foreach (TimeZoneInfo tz in TimeZoneInfo.GetSystemTimeZones())
  {
    if (tz.DisplayName.ToUpper() == sourceTimeZoneName.ToUpper())
    {
      sourceTimeZone = tz;
      break;
    }
  }
  //TimeZoneInfo.Local gives the local timezone

  DateTime sourceTime = DateTime.MinValue;
  if (null != sourceTimeZone)
  {
    //get the source datetime based on the source timezone
    sourceTime = TimeZoneInfo.ConvertTime(DateTime.Now, sourceTimeZone);
  }
  return sourceTime;
}

Monday, March 28, 2011

Blogger Publish the Code Snippets in a Formatted View

While blogging one or more posts might need code snippet(lines of code statements) as a reference or support to the problem/solution statement.

Adding the code statements to the blog post directly renders as html where the readability might be lost.

To improve the readablity of code snippets, i recommend a nice solution which i found. The solution is simple and straight forward which can be done 3 simple steps and it allows the end-users to copy the code snippet to clipboard or get a print of that easily.

Find the detailed post here.

Friday, March 25, 2011

Magic with CSS Styling (Reverse the Full Page Text)

Type the below full STYLE tag (css elements are commented, remove comments to make it work) in any of the free text boxes and submit.
Even it works with blog post as well...

Thats it upon rendering the submitted text, the page renderes the complete html (text) in reverse order from right to left including scroll bars.

To avoid this behaviour the entered text should be encoded while submitting and should not be decoded while rendering (if decoded the page again renders the style tag instead text.

To encode the entered text use the below code statement in the business-logic.
using System.Web;
HttpContext.Current.Server.HtmlEncode(tbExtension.Text.Trim());

SharePoint Custom WebPart Load JavaScript File

To load the JavaScript file (resides in the web site or layouts folder) in a custom web part, add the below set of code statements in the CreateChildControls() method.
using System.Web.UI.HtmlControls;
protected override void CreateChildControls()
{                    
base.CreateChildControls();

string jsFilePath = "/_layouts/MyProject/MyFolder/myJsFile.js";
HtmlGenericControl jsControl = new HtmlGenericControl("script");
jsControl.Attributes.Add("type", "text/javascript");
jsControl.Attributes.Add("src", jsFilePath);
this.Page.Header.Controls.Add(jsControl);
}

SharePoint Check Current User Permissions (SPBasePermissions)

I came accross a requirement where a custom web part or page displays the Generic List fields, however hide some of the fields if the current logged-in user doesn't have edit or delete list items permission.
using Microsoft.SharePoint;
if (!SPContext.Current.Web.DoesUserHavePermissions(SPBasePermissions.EditListItems))
{ 
//hide the fields/controls which are not supposed to be shown here
}
To see the OTB available list of permissions(SPBasePermissions) have a look at the post here.

Thursday, March 24, 2011

SharePoint Update User Profile Programatically (SSP User Profiles)

Below is the code snippet to update the user profile with OTB & Custom Properties.
using Microsoft.Office.Server;
using Microsoft.Office.Server.UserProfiles;
using (SPSite site = new SPSite("http://sitecollectionurl"))
{
//User profile manager object holds the complete profile store
UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(site));

//UserProfile object holds the acount specific userprofile
UserProfile userProfile = profileManager.GetUserProfile("domain\\administrator");

//OTB property name can be assigned as below using PropertyConstants class
userProfile[PropertyConstants.FirstName].Value = "My first name";

//Custom property value can be assigned as below by hardcoding the property name
userProfile["CustomPropertyName"].Value = "Test Value";

userProfile.Commit();
}

Loop through all the user profiles available in SSP profile store.
UserProfileManager profileManager = new UserProfileManager(ServerContext.GetContext(site));
foreach(UserProfile userProfile in profileManager)
{
if(null != userProfile[PropertyConstants.FirstName].value)
lblFirstName.Text = userProfile[PropertyConstants.FirstName].value;

if(null != userProfile["CustomPropertyName"].value)
lblCustomPropertyValue.Text = userProfile["CustomPropertyName"].value;
}

Wednesday, March 16, 2011

SharePoint Webpart Load UserControl (UserControl Webpart)

Creating a webpart to load the usercontrol instead of writing the html and business logic within the webpart itself.

Follow the below four steps to create a webpart with usercontrol.
1. Create a Asp.Net UserControl (.ascx file)
The .ascx file should inherit the code behind file as namespace.
<%@ Control Language="C#" AutoEventWireup="true" Inherits="MyProject.MyUserControls.MyClassName, MyProject, Version=1.0.0.0, Culture=neutral, PublicKeyToken=681f114f2a212052" %>
2. Create .acsx.cs (code behind) class file as namespace for business logic
using System.Web.UI;
namespace MyProject.MyUserControls
{
public class MyClassName : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
//Code goes here...
}
}
}
3. Create a webpart

4. Load the UserControl in createchildcontrols() method.
Make sure that the .ascx file is deployed to layouts folder.
PlaceHolder ph;//placeholder to load the usercontrol
protected override void CreateChildControls()
{
ph = new PlaceHolder();
ph.ID = "profileUpdatePH";

string userControlFilePath = "~/_layouts/MyFolder/MyControl.ascx";
MyUserControls.MyClassName myControl = Page.LoadControl(userControlFilePath) as MyUserControls.MyClassName;

ph.Controls.Add(myControl);
this.Controls.Add(ph);
}

C# Get RelativeUrl from AbsoluteUrl

Getting relativeUrl from absoluteUrl is very simple.

We have a class System.Uri which takes absolute/full url as a parameter and gives the relative url.
using System;
private static string GetRelativeUrl(string fullUrl)
{
try
{
Uri uri = new Uri(fullUrl);//fullUrl is absoluteUrl
string relativeUrl = uri.AbsolutePath;//The Uri property AbsolutePath gives the relativeUrl

return relativeUrl;
}
catch (Exception ex)
{
return fullUrl;
//throw ex;
}
}

Tuesday, March 15, 2011

Microsoft SharePoint 2010 Contest

Microsoft SharePoint 2010 makes it easier for people to work together. Here‘s an opportunity to test your knowledge on Microsoft SharePoint 2010. Participate in the Quiz Contest and you stand a chance to win a Windows Mobile and USB Pen Drives.

Click here for more details.

SharePoint Webpart Custom Properties with Default Value

Most of the sharepiont custom development involves creating custom webparts. There could be scenarios where some of the values like connection string, site url, list/library name are configurable by Admin/End User and changeble depending on the requirement. To achieve this for SharePoint webpart, the values can be configured using webpart properties. Any number of webpart properties can be added to the webpart with one or more categories to differenciate. Property value can be modified/changed by modifying the shared webpart.

Webpart property default value can be set using DefaultValue property, as shown below. Note that to set the default value, the value should be stored in a constant variable, otherwise it doesn't work properly.
//Namespaces required

using System.ComponentModel;

using System.Web.UI.WebControls.WebParts;



const string const_listName = "ListName";

private string _listName = const_listName;

[Personalizable(PersonalizationScope.Shared)]

[WebBrowsable(true)]

[Category("My Category")]

[WebDisplayName("List Name")]

[WebDescription("Provide list name to get all the items.")]

[DefaultValue(const_listName)]

public string ListName

{

get

{

return _listName;

}

set 

{

_listName= value; 

}

}

Monday, March 14, 2011

SharePoint Write Custom Error to Log file (ULS Error Logging)

Most of the requirements in sharepoint applications needs custom development i.e., web parts, workflows, event recievers, timer jobs etc.,
And we might need to write the exception/error details to log somewhere(list or text file in the file sytem).

As all the sharpoint error details are logged in 12 hive Log files, even we can write our custom error details to the same log file by using the ULS logging.
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Reference of Microsoft.Office.Server.dll needs to be added
Microsoft.Office.Server.Diagnostics.PortalLog.LogString("My Custom Error - Message:{0} || Stack Trace:{1}", ex.Message, ex.StackTrace);
});
Note: the logging code statement should be run under RunWithElevatedPrivileges, if the code is executable by end user.

Wednesday, March 9, 2011

Javascript Get Running Formatted DateTime

To show the formatted running datetime on the browser/page there is no straight way. But using javascript we can achieve this by manipulating with each unit in the datetime.

The following is the code to show the formatted running date time.
 
Html div tag to show/render the running time.

Tuesday, March 8, 2011

SharePoint PictureLibrary Thumbnail Url Vs Picture Url

I had hard time to get the complete Url of the picture as well thumbnail directly (using any property) inserad of managing with server relative/absolute url, thumbanil folder /t and the picture name.

But we have full control through SPObject Model(SPBuiltInField class) to get the picture/thumbnail Url directly.
SPList spList = web.Lists["ImagesLibrary"];
SPListItem item = spList.Items.GetItemById(itemID);

//Thumbnail Url
string thumbnailUrl = item[SPBuiltInFieldId.EncodedAbsThumbnailUrl].ToString();

//Picture Url
string pictureUrl = item[SPBuiltInFieldId.EncodedAbsUrl].ToString();
The above Urls are the full Urls of the thumbnail and picture respectively.

To get the absolute, relative Urls of the picture the Url can be managed as below.
Uri uri = new Uri(thumbnailUrl);
string relativePath = uri.AbsolutePath;

Thursday, February 24, 2011

Webpart to render New Form dynamically for a list item

To generate/render a new form in a webpart dynamically to create/add a list item. Where the field name, type of each field will be fetched and rendered respectively. It holds the full control on all the properties of a column.
//Create the table object that we are going to add the rows and cells to for our data entry form
Table tbl = new Table();
tbl.CellPadding = 0;
tbl.CellSpacing = 0;

// Get the site that this web part is running on.
SPWeb spWeb = SPContext.Current.Web;

// Get the list we are going to work with
SPList spList = spWeb.Lists["MyList"];

// Loop through the fields
foreach (SPField spField in spList.Fields)
{
// See if this field is not hidden
if (!spField.Hidden && !spField.ReadOnlyField && spField.Type != SPFieldType.Attachments)
{
// Create the label field
FieldLabel fieldLabel = new FieldLabel();
fieldLabel.ControlMode = SPControlMode.New;
fieldLabel.ListId = spList.ID;
fieldLabel.FieldName = spField.InternalName;

// Create the form field
FormField formField = new FormField();
formField.ControlMode = SPControlMode.New;
formField.ListId = spList.ID;
formField.FieldName = spField.InternalName;

// Add the table row
TableRow tblRow = new TableRow();
tbl.Rows.Add(tblRow);

// Add the cells
TableCell tblLabelCell = new TableCell();
tblRow.Cells.Add(tblLabelCell);
TableCell tblControlCell = new TableCell();
tblRow.Cells.Add(tblControlCell);

// Add the control to the table cells
tblLabelCell.Controls.Add(fieldLabel);
tblControlCell.Controls.Add(formField);

// Set the css class of the cell for the SharePoint styles
tblLabelCell.CssClass = "ms-formlabel";
tblControlCell.CssClass = "ms-formbody";
}
}

// Create the save button
SaveButton btnSave = new SaveButton();
btnSave.ControlMode = SPControlMode.New;
btnSave.ListId = spList.ID;

// Create the row for the save button
TableRow tblButtonRow = new TableRow();
// Create the cell for the save button
TableCell tblButtonCell = new TableCell();

tblButtonCell.ColumnSpan = 2;
tblButtonRow.Cells.Add(tblButtonCell);
tbl.Rows.Add(tblButtonRow);

// Add the table to the web part controls collection
this.Controls.Add(tbl);