Sunday, August 28, 2011

Insert a Sharepoint list item from web services


The following code is used to insert an item to a list using SharePoint Web Services.

        /// <summary>
        /// Method to insert picture URL to a list
        /// </summary>
        /// <param name="pictureURL">URL of the picture</param>
        /// <param name="currentlLoginID">Current logged in user</param>
        private void InsertItem(string pictureURL,string currentlLoginID)
        {
 
       /*Declare and initialize a variable for the Lists Web service.*/
            spsService.Lists listService = new spsService.Lists();

            /*Authenticate the current user by passing their default
            credentials to the Web service from the system credential cache.*/
            listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
                 
            listService.Url = "http://spsService/sites/MP/_vti_bin/Lists.asmx";

            System.Xml.XmlNode ndListView = listService.GetListAndView("Team Profiles", "");
            string listName = ndListView.ChildNodes[0].Attributes["Name"].Value;
            string viewName = ndListView.ChildNodes[1].Attributes["Name"].Value;


             XmlDocument xmlDoc = new XmlDocument();
         
            /* Declare an XmlNode object and initialize it with the XML response from the GetListItems method.*/
            System.Xml.XmlNode nodeListItems = listService.GetList(listName);

            string sBatch = string.Empty;        
            string uid = "-1;#" + currentlLoginID;

            //Query to insert data
            sBatch = "<Method ID=\"1\" Cmd=\"New\">";
            sBatch += "<Field Name=\"ID\">New</Field>";
            sBatch += "<Field Name=\"User_Picture\">" + pictureURL + "</Field>";
            sBatch += "<Field Name=\"UID\" >" + uid + "</Field>";
            sBatch += "</Method>";

            XmlElement batch_element = xmlDoc.CreateElement("Batch");
            batch_element.SetAttribute("OnError", "Continue");
            batch_element.SetAttribute("ViewName", viewName);

            batch_element.InnerXml = sBatch;
            listService.UpdateListItems(listName, batch_element);
        }

Wednesday, August 17, 2011

List all SharePoint Databases

Before migrating/moving the SharePoint database, we need to find all the database name.

We may need to find move the following database


Databases for Shared Services Providers (SSPs)
Search databases for SSPs
Content databases
Search database
Central Administration content database
Configuration database

To find all the SP database names, Go to Central Administration >> Operations >> Perform a Backup. This will take you to the page with all database listed.

Monday, August 15, 2011

Cannot find ContentPlaceHolder 'PlaceHolderPageTitle' in the master page '~masterurl/default.master', verify content control's ContentPlaceHolderID attribute in the content page

Error: "An unexpected error has occurred" in almost all the list and document library pages in SharePoint site

Cause: Changed the master page from SharePoint designer by right clicking the master page file and selecting "Set as default master page".

Resolution: By updating the callstack=true in web.config file of the web application, we got more detailed error message

Cannot find ContentPlaceHolder 'PlaceHolderPageTitle' in the master page '~masterurl/default.master', verify content control's ContentPlaceHolderID attribute in the content page


Opened the master page in the SharePoint designer and noticed that the PlaceHolderPageTitle is missing.
So replaced the below line
<Title>Our Company Intranet</Title>
with
<Title ID=onetidTitle><asp:ContentPlaceHolder id=PlaceHolderPageTitle runat="server"/></Title>


and save the master page.

Saturday, July 30, 2011

Trim the text in the multiple line of text field in a list and add a tool tip using SharePoint Designer 2007


1. This is the sample list which is currently displaying full text from multiple line of text field “Remarks"
Multiline of text

2. Open the site in SharePoint designer , navigate to the list default view page.(In this example we are using AllItems.aspx page)

3. Right click on the List View Web Part and select “Convert to XSL T Data View”. This will automatically convert settings for the current view into data view parameters.
Convert to XSLT DataView

4. After converting to XSLT, select the remarks field and switch to code view, you will see the code to display the remarks field as below

<TD Class="{$IDAWNV5H}"><div dir="{ddwrt:GetVar('Direction')}">
<xsl:value-of disable-output-escaping="yes" select="@remarks" />
</div></TD>

 We need to change the above line of code as below

<TD Class="{$IDAXNQ1G}" style="height: 22px">
<div dir="{ddwrt:GetVar('Direction')}" title="{@remarks}">
<xsl:choose >
<xsl:when test="@remarks != ''" >
<xsl:value-of disable-output-escaping="yes" select='concat((substring(@remarks,1,20)),"...")' />
</xsl:when>
<xsl:otherwise>
<xsl:value-of disable-output-escaping="yes" select="@remarks" />
</xsl:otherwise>
</xsl:choose>
</div></TD>

 5. Save the file. Now you will see the trimmed text in the default view page

Trim multi-line of text column

Monday, July 11, 2011

Error: The search request was unable to connect to the Search Service

Scenario: Recieved an error in our SharePoint site when we try to search contents

Error message: "The search request was unable to connect to the Search Service"

Resolution: 

1. Go to Central Admin > Operations > Services on Server > Office SharePoint Server Search Service
Make sure the "Use this server for serving search queries" is checked.

2. Also verify that the search account is configured in both search services
Go to Central Admin > Operations > Services on Server > Office SharePoint Server Search service
Go to Central Admin > Operations > Services on Server > Windows SharePoint Services Search

3. Make sure the search account specified in "Default content access account" is used on above settings.

Saturday, July 2, 2011

Create subsite programmatically when a new item is created in a SharePoint list

Code snippet to create sub site when a new item in list. Create a feature and bind this event handler to itemadding event.

public override void ItemAdding(SPItemEventProperties properties)
{
base.ItemAdding(properties);

string sitename = string.Empty;
string newSiteURL = string.Empty;
string siteShortName = string.Empty;
string strTemplateName = "Blank Site Template";

try
{
sitename = properties.AfterProperties["Title"].ToString();
siteShortName = GetAcronym(sitename.Trim());

if (properties.ListTitle == "Projects")
{
SPWeb website = properties.OpenWeb();
website.AllowUnsafeUpdates = true;

using (SPSite site = website.Site)
{
//to check if the site name/URL already exists
SPWeb web = site.AllWebs[website.ServerRelativeUrl + "/" + siteShortName];
int i = 0;

//if site exists, loop through with appending number at the end of site URL
while (web.Exists)
{
i = i + 1;
web = site.AllWebs[website.ServerRelativeUrl + "/" + siteShortName + i];
}

if (i != 0)
{
siteShortName = siteShortName + i;
}

//Create subsite
newSiteURL = CreateSubSite(website.Url, siteShortName, sitename, strTemplateName);

//Updating the sub site URL in the list's URL field
if (!string.IsNullOrEmpty(newSiteURL))
{
properties.AfterProperties["URL"] = newSiteURL;
}
website.AllowUnsafeUpdates = false;
web.Dispose();
}
}
}
catch (Exception ex)
{
//handle exception
}
}


/// [summary]
/// Method to create subsite
/// [summary]
/// [param name="parentSiteURL"]Parent site URL [param]
/// [param name="siteURLRequested"]site name acronym to be appended in subsite URL [param]
/// [param name="siteTitle"]Site Name [param]
/// [param name="siteTemplateName"]Site Template Name [param]
/// [returns]site URL [returns]
private string CreateSubSite(string parentSiteURL, string siteURLRequested, string siteTitle, string siteTemplateName)
{
const Int32 LOCALE_ID_ENGLISH = 1033;
string newSiteURL = string.Empty;
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite siteCollection = new SPSite(parentSiteURL))
{
using (SPSite site = new SPSite(parentSiteURL))
{
using (SPWeb parentWeb = site.OpenWeb())
{
SPWebTemplateCollection Templates = parentWeb.GetAvailableWebTemplates(Convert.ToUInt32(LOCALE_ID_ENGLISH));
SPWebTemplate siteTemplate = Templates[siteTemplateName];

//create subsite
using (SPWeb newSite = parentWeb.Webs.Add(siteURLRequested, siteTitle, "", Convert.ToUInt32(LOCALE_ID_ENGLISH), siteTemplate, false, false))
{
if (!string.IsNullOrEmpty(newSite.Url))
newSiteURL = newSite.Url.ToString();
}
}
}
}
});
return newSiteURL;
}
catch (Exception ex)
{
//handle exception
}
}


/// summary>
/// Function to get the acronym of the site name
/// summary>
/// [param name="strSiteName"]Site Name [param]
/// [returns]acronym value[/returns]
private string GetAcronym(string strSiteName)
{
string shortName = string.Empty;
string[] txtArray = strSiteName.Split(' ');
try
{
//if site name is a single word, get the first three characters of the site name
if (txtArray.Length == 1)
{
return strSiteName.Substring(0, 3);
}

//Get the first letter of each word in the site name
foreach (string word in txtArray)
{
shortName += word.Substring(0, 1);
}
return shortName;
}
catch (Exception ex)
{
// handle exception
}
}

Friday, July 1, 2011

SharePoint Useful CodePlex Tools for SharePoint

To manage where the column are displayed (e.g.: new or edit mode). To Hide columns from newform.aspx, editform.aspx and dispform.aspx etc
http://wsslistconfigurator.codeplex.com/

To add 'Only their own' permission for the document library.
http://moresharepoint.codeplex.com/

Ad Rotator WebPart
http://spadrotator.codeplex.com/

Caml Query Builder
http://spcamleditor.codeplex.com

JQuery SPServices
http://spservices.codeplex.com

Hit Counter WebPart
http://hitcounter.codeplex.com/

Cascading drop downs
http://customfieldcontrols.codeplex.com/
http://cascddlistwithfilter.codeplex.com/

To manage alerts on list or item for SharePoint groups.
http://advancedalert.codeplex.com/

Useful Sharepoint Designer Custom Workflow Activities
http://spdactivities.codeplex.com/wikipage?title=Copy%20List%20Item%20Extended%20Activity&ProjectName=spdactivities

SharePoint User Change Password
http://userchangepassword.codeplex.com/

List of users and their access
http://accesschecker.codeplex.com/

SharePoint Navigation Menu
http://spnavigationmenu.codeplex.com/