Friday, June 17, 2011

Changing service account passwords - The Service is unavailable

Problem: Browsers return the following error "Service Unavailable  Http Error 503.  The Service is unavailable." on all SharePoint websites including central admin.

Initial Hypothesis: I changed my password yesterday causing the app polls to fail when logging in.  The domain account used on my development machine required a password change.  Starting the machine causes all the IIS web sites to display the error message "Service Unavailable".  I run various services and application polls using my domain account.  The services can no longer log on.  Application pool cannot be started after the reboot/iisreset.

Resolution:  Change the log on details for the application pools used by IIS that run using the domain account that's password was reset.  Also start the Windows services that run using the windows domain account.



Ensure the SharePoint services running

Tuesday, June 14, 2011

3 ways to find SharePoint list field’s Internal name !

While working with caml query there may be cases where we may need to refer internal name of a sharepoint list and in some of the cases the display name and internal name may be different. If you try to access this list we will get object not found error.

We can find out the sharepoint field’s internal name using any of the following ways

1. Using browser (it applies to custom fields only)

Go to list settings -> Edit column. Then you can see field name from the query string

2. Object model (it applies for custom fields as well as system fields)

string siteUrl = "http://mysite";
SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
SPList list = web.Lists["my forum"];
for (int i = 0; i < list.Fields.Count; i++)
Console.WriteLine(list.Fields[i].Title + "..." + list.Fields[i].InternalName + "...");
Console.ReadLine();

3. Powershell (it applies for custom fields as well as system fields)

[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://mysite")
$web=$site.OpenWeb()
$list=$web.Lists["my forum"]
$list.Fields |select title, internalname| more

3 ways for adding new column in SharePoint list !

In this post we will see 3 different methods for adding columns in SharePoint list or document library or discussion board.

using browser

Go to the list which you want to add column

On the page that displays the list, click list’s settings and create columns.

Type a name for the column, choose the column type and click OK.

using Object model

 
SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
 
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
 
SPList list = web.Lists["mylist"];
SPFieldText fldName = (SPFieldText)list.Fields.CreateNewField(SPFieldType.Text.ToString(), "mycolumn");
fldName.Required = true;
fldName.MaxLength = 50;
list.Fields.Add(fldName);
list.Update();
 
site.AllowUnsafeUpdates = false;
web.AllowUnsafeUpdates = false;

using PowerShell


 
[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://mysite")
$web=$site.OpenWeb()
$list=$web.Lists["mylist"]
$list.Fields.Add("mycolumn", "Text", 0)

Highlight SharePoint List rows conditionally using jQuery !

In this article we will see how to Change the row Background color based on the value of a column in a sharepoint list and we will be doing it using jQuery.

Below is a screenshot of a Task Tracker whose rows are highlighted based on the percentage complete.

Here is how you can do it.

1. Create Sharepoint list

2. Edit allitems.aspx page and add a content editor web part and copy the below jQuery code to that webpart.

<script type="text/javascript">
$(document).ready(function(){
$Text = $("td .ms-vb2:contains('Not Started')");
$Text.parent().css("background-color", "#461B7E");
var myelement = $Text.parent().parent();
$Text = $("td .ms-vb2:contains('Completed')");
$Text.parent().css("background-color", "#4CC417");
$Text = $("td .ms-vb2:contains('In Progress')");
$Text.parent().css("background-color", "#EAC117");
});
</script>

Highlight a SharePoint List row on mouse over using jQuery !

In this article we will see how to highlight list a row on mouse over using jQuery.

Lets get started

1. Create a Sharepoint list

2. Edit allitems.aspx page and add a content editor web part and copy the below jquery and mouser over style to that webpart.

 
<script type="text/javascript">
$(document).ready(function()
{
$('td.ms-vb2').hover(function() {
$(this).parent().addClass("highlight");
// On mouseout, remove classes
}, function() {
$(this).parent().removeClass("highlight");
});
 
}); </script>
<style>
.highlight {background-color:#9AFEFF}
</style>

Display two columns with same label in newform.aspx of SharePoint list !

SharePoint does not allow creating two columns with the same name. If you still try to create more than 1 column with the same name then you will be prompted with an error message.

“The column name that you are entered is already use or reserved. Choose another name.”

But in many cases we may need two columns with same label. In this post we can see a work around for creating two labels with same text. Below is what we are going to achieve.

  1. Create the second column with a special character(City#)
  2. Edit the Newform.aspx and Editform.aspx page and insert a content editor web part in the below of the list web part.

    Note: you can append the following query string ?pageview=shared&toolpaneview=2 to the URL (http://mysite/ Lists/job/NewForm.aspx?pageview=shared&toolpaneview=2) to open in edit mode.
  3. Copy and paste the below code in the content editor web part using source editor.
<script type="text/javascript">// <![CDATA[
var tables;
tables = document.getElementById('ctl00_m_g_a3ac2436_2405_4e04_8afd_fa6f84b65d1b_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_TextField').parentNode.parentNode.parentNode.parentNode.parentNode;
var i;
var str;
for(i=0;i
<tables.rows.length;i++)  {  str = tables.rows[i].cells[0].innerHTML;  if(str.indexOf('#') > 1)
tables.rows[i].cells[0].innerHTML =str.replace("#", "");
}
}
// ]]></script>

Note: In the above code ctl00_m_g_a3ac2436_2405_4e04_8afd_fa6f84b65d1b_ctl00_ctl04_ctl08_ctl00_ctl00_ctl04_ctl00_ctl00_TextField is the ID one of the column in that list, for identifying parent table. (You can get it by viewing the Source code of the page).

Hide a required field in SharePoint list while adding new item !

There may be cases when we need to a hide required field while adding a new item to a list but at the same time you may want to show it while editing the item.

The above case looks tricky but it is easily achievable using some extra bit of code or PowerShell

C#

string siteUrl = "http://mysite";
SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
site.AllowUnsafeUpdates = true;
web.AllowUnsafeUpdates = true;
SPList list = web.Lists["mylist"];
SPField fldName = list.Fields["Name"];
fldName.ShowInNewForm = false;
fldName.Update();
list.Update();

PowerShell

[system.reflection.assembly]::loadwithpartialname("microsoft.sharepoint")
$site= New-Object Microsoft.SharePoint.SPSite ("http://d-dev1:1234/gp")
$web=$site.OpenWeb()
$list=$web.Lists["mylist"]
$field = $list.Fields["Name"]
$field.ShowInNewForm = $false
$field.Update()

If you want to hide this field in edit form, you can use below command

fldName.ShowInEditForm = false;

If you want to hide this field in display form, you can use below command

fldName.ShowInDisplayForm = false;

If you want to hide this field in list settings, you can use below command

fldName.ShowInListSettings = false;

If it is not a required filed then you can hide the item using Jquery in client side.

<script type="text/javascript">// <![CDATA[
$(document).ready(function() {
$('nobr:contains("Name")').closest('tr').hide();
});
// ]]></script>

Read data from a content editor webpart !

In this article we will see how we can to get data from a content editor webpart from one page and display it in another page using a custom webpart.


Add the following code in the RenderWebPartmethod of the webpart you are creating. The code and comments are self explanatory. Please pose a comment if you have any problem in understanding the code.

SPSite site = new SPSite("http://mysite">http://mysite"); // create object of the site
SPWeb web;
Microsoft.SharePoint.WebPartPages.SPLimitedWebPartManager mgr = null;
web = site.OpenWeb();
mgr = web.GetLimitedWebPartManager("Pages/mypage.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.User);//http://mysite/Pages/mypage.aspx will be the URL of the source page
foreach (System.Web.UI.WebControls.WebParts.WebPart wp in mgr.WebParts)
{
if (wp.Title ==  "My RichTextEditor") //My RichTextEditor is the webpart title
{
SPWebPartPages.ContentEditorWebPart webPart =    (SPWebPartPages.ContentEditorWebPart)wp;
output.Write(webPart.Content.InnerText);
}
}

Webpart Development part : validating Custom Web Part Properties!

In this article we will see how to validate the values entered by the user in custom property of web part.

In last blog post we added a text box in tool part pane of web part. In the below code we are trying to validate whether the text, enter by the user, is more than 10 characters.

public string text;
[Category("Advanced Settings"),
Personalizable(PersonalizationScope.Shared),
WebBrowsable, WebDisplayName("Text"),
WebDescription("Enter your text")]
public string Text
{
get { return text; }
set {
// Validate input
if(value.Length < 10)
throw new WebPartPageUserException("Enter minimum 10 charectors in text field.");
text = value;
}
} 

As you can see in the above code, you can write your own conditions in the set method of the property of the control and throw WebPartPageUserException if error an occurs or if it is an invalid entry.

In coming articles we will see how to deploy custom web part in master page

Wednesday, June 8, 2011

Sharepoint 2010 - Show web part in Master Page !

Displaying a webpart (your own custom made or any of the OOTB ones) in the master page of your site might not be directly supported by the GUI, but requires minimal effort and no coding.

The easiest way is to add the web part to a normal page (not within a zone), open this page in Sharepoint Designer and steal the generated code. This code can then be inserted into the masterpage where you want it displayed, and then finally add the tag prefix in the header of the masterpage to reference the webpart assembly.

Here's an example:

The following code is the generated markup for my SubSiteTitleWebPart.


1
<WpNs0:SubSiteTitleWebPart runat="server" ID="g_d2f29a1f_146b_450e_aec1_81a20e6a9646" Description="My WebPart" Title="SubSiteTitleWebPart" __MarkupType="vsattributemarkup" __WebPartId="{A44A399D-8D5B-419B-B5E2-71BD0B35EC67}" WebPart="true" __designer:IsClosed="false"></WpNs0:SubSiteTitleWebPart>

Take note of the "WpNso" prefix, this is the one that references to the webpart assembly. You will find the reference at the top of the page, looking a little something like this:

1
<%@ Register TagPrefix="WpNs0" Namespace="SubsiteTitleBar.SubSiteTitleWebPart" Assembly="SubsiteTitleBar, Version=1.0.0.0, Culture=neutral, PublicKeyToken=3f987c92d971a0fb">

Just copy the same tag prefix to the masterpage and you're done!

Webpart Development : Creating Custom Web Part Properties

In this blog post we will see how to add custom properties for SharePoint web part. There are several properties available in SharePoint web part for setting its look and feel like Title, Height and Width etc.. In this example we will see how to add Dropdown, Check box and a Text box in webPart tool pane.

  1. Open Visual studio and create a new web part project
  2. Open the .cs file
  3. import the name space System.ComponentModel;
  4. To define the XML namespace to be used for the Custom WebPart, add the below code just above the class declaration. (These values can be whatever you choose and aren’t related to the class name.)
    [DefaultProperty("Text"), ToolboxData("<{0}:WPwithBGcolr runat=server></{0}:DisplayLatestPosts"), XmlRoot(Namespace = "WPwithBGcolr")]
  5. Change the base class from System.Web.UI.WebControls.WebParts.WebParttoMicrosoft.SharePoint.WebPartPages.WebPart
  6. For adding a text box in tool part pane, add the below property in the class
    public string text;
    [Category("Advanced Settings"),
    Personalizable(PersonalizationScope.Shared),
    WebBrowsable, WebDisplayName("Text"),
    WebDescription("Enter your text")]
    public string Text
    {
    get { return text; }
    set { text = value; }
    }
  7. For adding a checkbox in tool part pane you need to add the blow code
    public Boolean border;
    [Category("Advanced Settings"),
    Personalizable(PersonalizationScope.User),
    WebBrowsable, WebDisplayName("Border"),
    WebDescription("Do you want border")]
    public Boolean Border
    {
    get { return border; }
    set { border = value; }
    }
  8. For adding a dropdown in tool part pane , first declare an enum variable and create the property using this new variable as shown in the below code.
    public enum ColorByEnum { Red, Blue, Green };
    protected ColorByEnum colorBy;
    [Category("Advanced Settings"),
    Personalizable(PersonalizationScope.User),
    WebBrowsable,
    WebDisplayName("Background Color"),
    WebDescription("Choose a background color for your webpart")]
    public ColorByEnum ColorBy
    {
    get { return colorBy; }
    set { colorBy = value; }
    }
    
  9. You can retrieve the value, entered by the user, using the below code.
    protected override void RenderWebPart(HtmlTextWriter output)        {        output.Write(this.text  );         }
  10. For expanding the custom category default we need to override the function ‘GetToolParts’.�
    public override ToolPart[] GetToolParts()
    {
    ToolPart[] toolpart = new ToolPart[3];
    CustomPropertyToolPart custom = new CustomPropertyToolPart();
    custom.Expand("Advanced Settings");
    WebPartToolPart Wptp = new WebPartToolPart();
    Wptp.FrameState = FrameState.Normal;
    Wptp.FrameType = FrameType.Default;
    toolpart[0] = Wptp;
    toolpart[1] = custom;
    return toolpart;
    }

The following properties can be added to costom controls in the tool part pane.

The custom property will be displayed automatically in the default property pane based on the property type string, bool, int or enum. The following table describes how each of these property types is displayed in the property pane.

In the coming articles we will see how to validate custom controls in tool part pane.

Download the sample source code here.

Embedding css file in custom Webpart in Sharepoint 2010

This article will show us how to use the Datalist in a webpart and embedding CSS file and classes in the webpart.




First we are creating the webpart. For that follow the below steps



Create a webpart solution

Create a child controls and add the related code in webpart cs file like below



DataList dlNews;

Label lblNewsTitle;

protected override void CreateChildControls()

{

// Create and add the controls that compose the

// user interface of the Web Part.

Controls.Clear();



dlNews = new DataList();



//CSS link calling as object

Microsoft.SharePoint.WebControls.CssLink cssLink = new Microsoft.SharePoint.WebControls.CssLink();

cssLink.DefaultUrl = "/_layouts/1033/styles/News.css";

this.Page.Header.Controls.Add(cssLink);

// Create the Datatable

DataTable dtItem = new DataTable();

// send the Data items from this datatable

//News Datalist view

fillResultsDatalist(dtItem);



}

private void fillResultsDatalist(DataTable dtItem)

{

// Create an instance of the DataGrid and set its

// DataSource property to the supplied DataSet.

dlNews = new DataList();

dlNews.DataSource = dtItem;

dlNews.CellPadding = 0;

dlNews.CellSpacing = 0;

dlNews.BorderWidth = 0;

dlNews.RepeatDirection = RepeatDirection.Vertical;

// Calling the Itemplete for data list bound columns

dlNews.ItemTemplate = new DatalistLabelColumn();

// Bind the data to the DataGrid.

dlNews.DataBind();

//Add the DataGrid to the controls.

Controls.Add(dlNews);

}





Add/Create the the ITemplate class

///

/// Intialize the Container controls

///


///

public void InstantiateIn(Control container)

{

Label lblNewsTitle = new Label();

lblNewsTitle.DataBinding += new EventHandler(this.BindLabelColumn);

container.Controls.Add(lblNewsTitle);



Label lblNewsText = new Label();



lblNewsText.DataBinding += new EventHandler(this.BindLabelColumn1);

container.Controls.Add(lblNewsText);



LinkButton lnkButton = new LinkButton();

lnkButton.DataBinding += new EventHandler(this.BindLabelColumn2);

container.Controls.Add(lnkButton);

}

///

/// BindLabelColumn for Title of the News

///


///

///

public void BindLabelColumn(object sender, EventArgs e)

{

Label lblTitle = (Label)sender;

DataListItem container = (DataListItem)lblTitle.NamingContainer;

String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Titre"));

lblTitle.Text = "
> " + strVals + "
";

}

///

/// BindLabelColumn1 for news Description label

///


///

///

public void BindLabelColumn1(object sender, EventArgs e)

{

Label lblText = (Label)sender;

DataListItem container = (DataListItem)lblText.NamingContainer;

String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Text"));

strVals = Regex.Replace(strVals, @"<(.
\n)*?>", string.Empty);

strVals = RetComments(strVals);

lblText.Text = "
" + strVals + "
";



}

///

/// BindLabelColumn2 for Link button

///


///

///

public void BindLabelColumn2(object sender, EventArgs e)

{

LinkButton lnkButton = (LinkButton)sender;

DataListItem container = (DataListItem)lnkButton.NamingContainer;

String strVals = Convert.ToString(DataBinder.Eval(((DataListItem)container).DataItem, "Link"));

lnkButton.Text = @"
";

lnkButton.PostBackUrl = strVals;

}

///

/// Substring the text upto 60 characters

///


///

///

public string RetComments(string strCompanyName)

{

string sComments = string.Empty;

if (strCompanyName.Length > 50)

{

sComments = strCompanyName.Substring(0, 50).Trim() + "...";

}

else if (strCompanyName.Length == 0)

{

sComments = "--";

}

else

{

sComments = strCompanyName;

}

return sComments;

}





Create the CSS page News.css.



.HomeNewsTitle,.HomeNewsSubTitle,.HomeNewsLink,.HomeSeperator,.HomeNewsTitle2,.HomeNewsLink1,.HomeNewsLink2{

font-family: Trebuchet MS;

position: relative;

float: left;

left: 0px;

width: 172px;

}

.HomeNewsTitle,.HomeNewsTitle2{

color: #0099cc;

font-size: 13px;

}

.HomeNewsTitle2{

top:4px;

}

.HomeNewsSubTitle{

color: #333333;

font-size: 12px;

line-height:15px;

}

.HomeNewsLink,.HomeNewsLink1,.HomeNewsLink2{

color: #0099cc;

font-size: 11px;

text-decoration:underline;

text-align:right;

padding-bottom:1px;

}

.HomeNewsLink1{

padding-bottom:10px;

}

.HomeNewsLink2{

bottom:5px;

}



Add/Place the CSS file in to below folder

C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\1033\STYLES



you have to call the Default URL of the CSS file path like "/_layouts/1033/styles/News.css";

Now you can able to use embedded CSS classes and datalist in webpart.



I hope this will be useful for sharepoint developers.



Enjoy!







Showing which list items have tags or notes in SharePoint 2010

One of the great areas of functionality added in SharePoint 2010 is Social Feedback – the ability for users to add tags and notes to content as part of the managed metadata service. As has been discussed many times this is a fantastic feature to increase the classification of content and the overall findability of content. The out-of-the-box My Site includes some great features such as the Activity Feed and the Tag Cloud to help surface some of the information captured by tags and notes – and it works really well. One question that was put to me in a recent engagement however was:
How do I see which items in a list or library have tags and notes?
Without selecting each individual item and viewing the tags and notes dialog for each it seems that it’s just not possible. I won’t go into the long discussions we had about the different ways we could surface both the tags and notes information and the context of that information – but I will show you this screenshot of a library which adds a Tags And Notes Column so that at a glance it’s possible to see which items have tags or notes.
Tags And Notes Column


The steps to recreate this for a document library are:
  1. Create a new column on a library named Tags And Notes
    1. The type isn’t actually important, but I used a simple text field
  2. Add a web part to a page, e.g. your Team Site home page, and then modify the view to include the newly added column
  3. Upload the script (found below) into a suitable location, e.g. the Site Assets library
  4. Reference the script in a Content Editor Web Part (CEWP) added to the page
How It Works

What is happening here, is that the CEWP is loading both jQuery and my custom script on a page (the jQuery could/ should obviously be local). The script then goes away and looks for a table on the page that includes a TH cell with the text Tags And Notes in it. If it finds one it goes through each row and puts in the icon for tags and notes into the last column.
Then, it takes the URL of the item in the title column and passes that through to a function which makes a SOAP request to the SharePoint web services to get any tags on that specific URL. The success method then either repeats the process to find comments (if it found no tags) or simply swaps out the source for the tags and notes icon with the source for a has tags and notes icon.
Next steps and Limitations

I’m fairly happy with the result that this script and technique gives, although there are some nagging annoyances. Whilst investigating this I tried to repeat the same behaviour as the Tags And Notes icon found in the ribbon, i.e. it would be nice to be able to click on the icons and view/ add tags and notes for the individual items. Unfortunately I found that by adding in the functions to open up the dialog with multiple instances on a page it would always refer to the first item clicked. I tried various things here like giving unique identifiers but with no success. I’m still looking into this as this is what I’d really like it to do!
Also, I think there’s something in the way that I’m referencing my scripts that is resulting in a javascript error. I’m trying to track this down. No doubt the code could be tidied up in general too, such as by adding a function for the on error event of the ajax call etc.
In terms of next steps this would obviously be a bit of a pain to repeat many times across an environment and so I would be looking to create a custom site column that could simply be added to a list or library to replicate this behaviour. That step may be a bit beyond my basic coding skills though :)
The Script

Here is the script I used. Hopefully the comments are sufficient to make this readable:

Showing which list items have tags or notes in SharePoint 2010