Thursday, December 31, 2009

Creating a Export to Excel link in SharePoint

Hi All,

I came across to an interesting query. When we open a document library or a list AllItems.aspx we have an option to export the data into spreadsheet. However there is no direct link given. We do not have any URL for the Export to Excel option that comes under actions menu.

However, when you want to place a link for Export to excel in your web part or your webpage, then here is a way to go for it.

{siteurl}/_vti_bin/owssvr.dll?CS=109&Using=_layouts/query.iqy&List={GUID of list}&View={GUID of view}&CacheControl=1

As you can see all you need to do is replace the respective place holders.

{siteurl} is your site url.

{GUID of list} is the GUID of the list for which you want to export the data to spreadsheet.

{GUID of view} is the GUID of the view for which you want to export the data to spreadsheet.

Where will you get these GUIDs? Well, you will find it when you click on List Settings.



And then click on the view name for which you want the data



You can use the same formula at places where there is no option to export to spreadsheet. For example, if you see on people and group permission page, you will not find this. You the same formula and you will be able to export it to the spreadsheet.

That’s it. Your job is done.

Wednesday, December 16, 2009

Limiting the number of responses in survey

Hi All,

In this article, I am going to share one very important aspect of survey. Many times we require limiting number of responses from survey. However SharePoint does not provide us with the facility to limit the number of responses.

Ok, then how to achieve this? Here we go, follow these simple steps and you are good to go.

(1) Write one web part and write one code which checks for the total responses for specific survey. Add this web part on NewForm.aspx and overview.aspx, all responses and graphical summary of the survey. You get NewForm.aspx when you click on respond to the survey button.

(2) Write down simple code, check URL, if NewForm word exist, then just count the total number of item in survey and if it exceeds let’s say 30 responses, and then redirect back to Source parameter.

(3) If in URL overview, allitems or summary exist, just count the total number of item in survey and if it exceeds let’s say 30 responses then write a statement saying you are not allowed to respond because it has already reached to the maximum responses.

Your job is done.

Friday, December 4, 2009

Add Choice column to list programmatically

Hi All,

Some days back person asked me as a question that you have a post for how to add data in the choice column programmatically however you do not have any article on how to add choice column itself to the list programmatically.

So of course, taking the suggestion positively here is a way you can add choice column programmatically to the list or document library.

Considering lstCustomList is your list object and you have set AllowUnsafeUpdate() to true for the web object. We are adding two choices in the choice column.

First we will add choice column itself to the list and then we will add the choices in that column and update the field. The main point to taken in to consideration is that it is SPFieldChoice not the SPField.

lstCustomList.Fields.Add("ABC", SPFieldType.Choice, false);
lstCustomList.Update();
SPFieldChoice objChoiceCol = (SPFieldChoice)lstCustomList.Fields["ABC"];
string[] strdata = new string[2];
strdata[0] = "Open";
strdata[1] = "Close";
objChoiceCol.Choices.Add(strdata[0]);
objChoiceCol.Choices.Add(strdata[1]);
objChoiceCol.Update();
lstCustomList.Update();


That is it. Your job is done.

Saturday, November 28, 2009

How SharePoint Works with Survey

Recently we are having requirement that how to access Survey List Programmatically in SharePoint.

First we think that there should be some object like SPSurvey just same as Document library list SPDocumentLibrary, but sadly that object is not there.

But rather than thinking long we can access Survey same as simple list as SPList only :)

Simple…

But what we found is somewhat new to everyone, at least for us.

SharePoint Survey is storing data in reverse manner as what we think.

Each question that we are entering for survey is created as column and all the answer stored as row value.

Let’s show you Example

Question of survey is : Do you like this?

Answer choice (in radio button or dropdown) are : Yes, No, Don’t know

So you will get SPList.Items.GetDatatable(); like below

So it’s a little confusing right.

But anyway that will help you whether you should take any task to work on Survey programmatically or not?

Tuesday, October 20, 2009

Coloring Events in SharePoint calendar

Hi All,

We all are familiar with coloring events in Outlook calendar. Question is can we have the same deal with SharePoint calendar and the answer is yes we can have. In this article, I am going to share few tips on how to achieve this functionality.

To achieve this, first create one field in Calendar list. For example, give it a name “Category”. Your each event is divided in some category. Give it as choice column and enter following categories for selection choice.



So, your each event is divided in these two categories. So now, go ahead and add two entries in calendar. One of Sports and other is of important meeting category.



Also create one more calculated column called “CatTitle”



And change the calendar view to this



And now we will add one content editor web part below calendar web part. So Edit the page and add one content editor web part and add the following line of code. This will color the different events.

<script>

var SEPARATOR = "|||";

var nodes, category;

nodes = document.getElementsByTagName("a");


for(var i = 0; i < nodes.length; i++)
{

if(nodes[i].innerText.indexOf(SEPARATOR) != -1)
{



UpdateCalendarEntryText(nodes[i]);


var foundNode = nodes[i];
var trap = 0;

while(foundNode.nodeName.toLowerCase() != "td")
{
foundNode = foundNode.parentNode;

trap++;
if(trap > 10)
{
break; // don't want to end up in a loop

}
}

var colour = GetCalendarColour(category);



if(colour != "")

foundNode.style.background = colour;
}
}

function UpdateCalendarEntryText(anchorNode)
{

var children = anchorNode.childNodes;
for(var i = 0; i < children.length; i++)
{

if(children[i].nodeType == 3 && children[i].nodeValue.indexOf(SEPARATOR) != -1)
{
var parts = children[i].nodeValue.split(SEPARATOR);

category = parts[0];
children[i].nodeValue = parts[1];
}

else
UpdateCalendarEntryText(children[i]);
}
}

function GetCalendarColour(desc)
{

var colour;

switch(desc.toLowerCase())
{

case "sports event":
colour = "#3399FF";
break;

case "important meeting":
colour = "#FF33FF";
break;


default:
colour = "";
}

return colour;

}

</script>




I would like to thank Mark Wilson for this wonderful trick.

That's it. your job is done.

Thursday, October 15, 2009

Hiding field in SharePoint through JavaScript

Hi All,

Many times we require to hide specific field in new form, disp form and edit form. This time we will do it with the help of javascript. We can do the same thing with the help of SharePoint API. However we will cover here that how to achieve the same with the help of JavaScript.

Let us go to calendar and click on new. You will now be on Newform.aspx. We can see here one field named “WorkSpace”. If we don’t want user to create any workspace here, then we can hide this field with the help of JavaScript code.



To hide a specific field, insert one content editor web part on the page and then just copy and paste the following code. Insert this web part below the new form web part.

<script type="text/javascript">
function HideField(title){
var header_h3=document.getElementsByTagName("h3") ;

for(var i = 0; i <header_h3.length; i++)
{
var el = header_h3[i];
var foundField ;
if(el.className=="ms-standardheader")
{
for(var j=0; j<el.childNodes.length; j++)
{
if(el.childNodes[j].innerHTML == title || el.childNodes[j].nodeValue == title)
{
var elRow = el.parentNode.parentNode ;
elRow.style.display = "none"; //and hide the row
foundField = true ;
break;
}
}
}
if(foundField)
break ;
}
}

HideField("Workspace");

</script>


After you’ve inserted this code, just look at the result shown below.



That’s it. Your job is done. You can apply the same code in disp and edit form as well.

Monday, October 12, 2009

Sharepoint’s “!New” indicator duration.

Hi folks,

Here we are explaining a way, how to change “!New” indicator time span.

Below is the command to change the time of “!New” label of SharePoint Item

stsadm.exe -o setproperty -pn days-to-show-new-icon -pv <> -url [Your Virtual Server's URL]


To turn off the “!New” icon, set the number of days to zero

Here is the MSDN KB link for the same.

The change is for ALL list items (not just documents) on the virtual server
Good thing is it does not required IISRESET

Saturday, October 10, 2009

'' is not recognized as an internal or external command

Hi All,
I face a problem when i create .bat file in Visual studio it add an extran non-ASCII character in my bat file and i am getting error '' is not recognized as an internal or external command,
it is because it is UTF-8 format

so to fix it Use notepad++ and paste your .bat code in it and go to Format Menu select ASCII format and save it it will work like charm :)


Happy SharePointing....


SharePointKings

Tuesday, October 6, 2009

Office SharePoint Search Service hangs does not start

Hi All,
I have faced one strange problem i was restarting Office SharePoint Search Service on my farm environment and suddenly it got hanged it is showing me in starting state there is no stop,start or restart option in services.msc console. I have restarted my machine but still error was as it is.
I tried following command also

stsadm -o osearch -action start
stsadm -o osearch -action stop
net stop oSearch
net start oSearch
nothing was working for me it shows me operation time out as osearch service is in starting state.

I fixed it by
psconfig -cmd services -install
and configure SharePoint search again and it works for me.

warning: follow above instruction at your risk on production environment :)

SharePointKings

Sunday, October 4, 2009

MOSS 2007 Master Page DOCTYPE Issue

Hi All,
Today i would like to discuss an issue which i think most of us would have faced when we try to add a declaration in the top of the master page like:

<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">


This is a standard declaration you will see on any aspx page and we all know why it is required.

But when you add this declaration in a SharePoint master page...you are inviting trouble..why..simply because of the reason that SharePoint master page is XHTML non-compliant.
You will ask me why you need a DOCTYPE in a master page?
Reason being the fact that i am using a AJAX modal pop up in the master page and we all know what happens when you add a ajax control in a master page without a doctype declaration..The page looks weird and the structure breaks from many places.

The only solution i know in this case is to choose from one of the following options:

1. Remove the AJAX modal pop up and hence the DOCTYPE declaration and use some other pop up . A javascript pop up may be
2. Keep the DOCTYPE declaration and modify the style of the elements whose structure is broken as an effect of adding doctype.

Hmm...you can't refuse clients requirement , and hence you have to go with option 2.

Consider for example after adding DOCTYPE the quick launch menu started looking weird, You tried changing the style sheet class attributes but no use.
The reason being the fact that the master page is no longer taking the out of the box style sheet classes like ms-navheader !
Follow the steps mentioned below and get rid of this problem:
1. Create a new class in your style sheet (Note: Do not make change in CORE.css)
and copy the attributes you were using previously in it e.g if the previous class name was ms-navheader then create a new class by name such as leftnavheader and copy the attributes under its declaration. Similarly create other classes.
2. Open the master page in the designer and replace the old class name with new one at all the places.
3. Save and publish the master page and you will see the changes are visible now.

Go ahead and follow the same procedure at all the places. I know its strange but can't help it.

If you have some better way of solving this issue or facing any problem understanding this post please let us know at sharepointkings@gmail.com

Happy Coding !!

Monday, September 28, 2009

Hide Content Place Holder Programmatically

I was working on replacing a control from the master page by a custom web part. Initially i commented everything inside the content place holder and added my web part. If you want to know how to add a web part in the master page, have a look at my previous post at :

http://www.sharepointkings.com/2009/09/add-web-part-inside-master-page-in-moss.html

Later on i moved the web part reference out of the content place holder and made the visible attribute of the content place holder to false.

But now the requirement is to dynamically turn it ON and OFF (i.e through code)

Lets follow the steps given below to achieve this:

1. Go to the page_load method of the web part.
2. Write the following lines of code.


if (!Page.IsPostBack)
{
ContentPlaceHolder contPlcHolder = (ContentPlaceHolder)Page.Master.FindControl("PlaceHolderGlobalNavigation");
contPlcHolder.Visible = false;

//Rest of the code

}


If there is any nested content place holder then append that number of FindControl("ControlName") to the above code where we are finding the control.

That's it. Save the code and deploy the latest web part code.

If you are facing any issue then email us at sharepointkings@gmail.com

Sunday, September 13, 2009

Add Web Part inside a Master Page in MOSS 2007

Imagine that you are designing a master page for your MOSS site and you have a requirement to have a functionality that is not possible out of the box. You brain storm on it and concludes that only custom web part can solve your problem.
But now your concern is how you can make this custom web part as part of your master page?
It’s easy! Just follow the steps given below to add a web part inside a master page.

1. Deploy the web part in your web application as you do normally.
2. Check whether the web part is showing up in the web part gallery.
3. Create a web part page by navigating to the site settings, create web part page.
4. Add your custom web part on the web part page.
5. Start SharePoint designer and open the newly created web part page.
6. You will now find two entries corresponding to the web part you added on the page
i. In the page declaration you will find a entry which looks something like this:


<%@ Register TagPrefix="WpNs0" Namespace="MyNamespace.MyClass" Assembly=" MyNamespace.MyClass, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"%>

ii. Click on the web part section in the page and you will see an entry like this:


<WpNs0:WebPartName runat="server" ID="g_34cdbb90_38c6_4561_9182_8fbc0d2423a6" ExportMode="All" Title="WebPartTitle" __MarkupType ……………..

7. Copy these entries in separate notepad, and close the page opened in the SharePoint designer.
8. Now open the master page in SharePoint designer and add the first entry in the declaration section and second entry at the place where you want to add the web part to.
9. Save the page, check in and publish it and that’s it. Your job is done.


Do let us know in case you are facing any issue following the steps mentioned.
You can email us at sharepointkings@gmail.com

Sunday, September 6, 2009

Creating and working with Survey in SharePoint - Part 5

Hi All,

In this article we will discuss about how to hide the save button. You may wonder why we should hide the save button. We will hide the save button to avoid one big issue of the survey.

If you have not gone through the survey articles, I would recommend you to read them all first before you read further.

Creating and working with Survey in SharePoint - Part 1

Creating and working with Survey in SharePoint - Part 2

Creating and working with Survey in SharePoint - Part 3

Creating and working with Survey in SharePoint - Part 4

When you have any question that has branching, SharePoint automatically places the next question on the second page and gives you an option to save your response so that later you can edit it. If you have the long survey that has many branching questions, then SharePoint does this splitting of page between the questions. Here we have one big problem. When responder saves the response, you will see that number of response increases. If you have five responders and all five of them have saved the respond, not completed the respond, then first thing you will notice is you can see total number of responses as five, but when you will actually go to the survey and find out then you won’t see even a single response. So where are all those responses?

Well, answer to this question is really simple. Even though you have full rights on survey or even you are a site administrator or site collection administrator, nobody can see those responses except a person who has saved the response. Only he can see his saved response. So bottom line is check columns named “Completed” in “All Responses” view, you will find only those responses whose status is yes. If a person has saved response, he will see status as “no” in “Completed” column.

Now why we are talking about hiding the save button is because there can be a reason where in you want responders to respond the survey in specific days. If they don’t then you want to send mail to them one more time to indicate that look, you need to fill this. Now to know this that how many people have not responded to survey yet, is don’t allow to save the response so that you can have exact number of responses.

Ok, so let us go ahead and add the content editor web part in every page of your questions, so that save button doesn’t appear on each and every page of survey. So now responder has no choice but to fill in the survey at one go.

In content editor web part, place the following code.

<script language="JavaScript">
var ClassName;
ClassName = 'ms-toolbar';

var elements = new Array();

var elements = document.getElementsByTagName('td');

for(var e=0;e<elements.length;e++)
{
if(elements[e].className == ClassName)
{

elements[e].innerHTML = elements[e].innerHTML.replace('value=Save','value=Save style=visibility:hidden ');



}

}

</script>


Your job is done. Now see the effect of above code.



That's it.

Saturday, September 5, 2009

Creating and working with Survey in SharePoint - Part 4

Hi All,

Here I am going to discuss something interesting especially on overview.aspx of survey list. If you have not gone through the survey articles, I would recommend you to read them all first before you read further.

Creating and working with Survey in SharePoint - Part 1

Creating and working with Survey in SharePoint - Part 2

Creating and working with Survey in SharePoint - Part 3

and

Creating and working with Survey in SharePoint - Part 5


One question came in my mind. Why any responder of survey should care about knowing when survey was created and how many number of responses has come so far. If we have set the permission in advance settings of survey that user can only see their response, and then also responder can see how many responses have come so far.

If we do not want to allow any responder to see when survey was created and how many responses has come so far, then do one very easy thing. Just add one more content editor web part on the overview.aspx page of survey and copy and paste the below code and there you go, you have each and every option just like you have in normal survey web part on overview.aspx. The only difference is that here you cannot see number of responses and date created. Make sure that you hide the default web part on that page by modifying that web part and setting hidden to true under layout option. So simple…isn’t it.

Just make sure that you replace the {siteurl} for HREF in below code. Just place your site url there and you should be good to go.


<table class="ms-menutoolbar" cellpadding="2" cellspacing="0" border="0" id="ctl00_m_g_c84f415c_dba8_4240_b34d_263e596c7eed_ctl00_ctl00_toolBarTbl" width="100%" >
<tr> <td class="ms-toolbar" nowrap="true">
<div class="ms-buttoninactivehover" onmouseover="this.className='ms-buttonactivehover'" onmouseout="this.className='ms-buttoninactivehover'"><a id="ctl00_m_g_c84f415c_dba8_4240_b34d_263e596c7eed_ctl00_ctl00_toolBarTbl_RptControls_ctl00_diidIONewItem" accesskey="N" title="Respond to this Survey" onclick="javascript:NewItem('\u002fsites\u002fTest\u002fLists\u002fSharePoint\u002520site\u002520survey\u002fNewForm.aspx');return false;" href="javascript:__doPostBack('ctl00$m$g_c84f415c_dba8_4240_b34d_263e596c7eed$ctl00$ctl00$toolBarTbl$RptControls$ctl00$diidIONewItem','');"><img align='absmiddle' alt="Respond to this Survey" src="/_layouts/images/NewItem.gif" style='border-width:0px;'>&nbsp;Respond to this Survey</a></div>
</td>
<td class=ms-separator><img src='/_layouts/images/blank.gif' alt=''></td>
<td class="ms-toolbar" nowrap="true">


<span style="display:none"><menu type='ServerMenu' id="zz13_RptControls" largeIconMode="true"><ie:menuitem id="zz14_ExportToSpreadsheet" type="option" iconSrc="/_layouts/images/MenuSpreadsheet.gif" onMenuClick="javascript:EnsureSSImporter();javaScript:ExportList('\u002fsites\u002fTest\u002f_vti_bin\u002fowssvr.dll?CS=65001\u0026Using=_layouts\u002fquery.iqy\u0026List=\u00257BA1B0E302\u00252D497E\u00252D45B9\u00252D9994\u00252D9F0E0171A380\u00257D\u0026View=\u00257BC84F415C\u00252DDBA8\u00252D4240\u00252DB34D\u00252D263E596C7EED\u00257D\u0026RootFolder=\u00252Fsites\u00252FTest\u00252FLists\u00252FSharePoint\u002520site\u002520survey\u0026CacheControl=1')" text="Export to Spreadsheet" description="Analyze items with a spreadsheet application." menuGroupId="800"></ie:menuitem><ie:menuitem id="ctl00_m_g_c84f415c_dba8_4240_b34d_263e596c7eed_ctl00_ctl00_toolBarTbl_RptControls_ctl01_ctl00_ctl03" type="separator"></ie:menuitem><ie:menuitem id="zz15_ViewRSS" type="option" iconSrc="/_layouts/images/MenuRSS.gif" onMenuClick="window.location = '/sites/Test/_layouts/listfeed.aspx?List=%7BA1B0E302%2D497E%2D45B9%2D9994%2D9F0E0171A380%7D';" text="View RSS Feed" description="Syndicate items with an RSS reader." menuGroupId="800"></ie:menuitem><ie:menuitem id="zz16_SubscribeButton" type="option" iconSrc="/_layouts/images/MenuAlert.gif" onMenuClick="window.location = '/sites/Test/_layouts/SubNew.aspx?List=%7BA1B0E302%2D497E%2D45B9%2D9994%2D9F0E0171A380%7D&amp;Source=http%3A%2F%2Fsharepointkings%3A7777%2Fsites%2FTest%2FLists%2FSharePoint%2520site%2520survey%2Foverview%2Easpx';" text="Alert Me" description="Receive e-mail notifications when items change." menuGroupId="800"></ie:menuitem></menu></span><span title="Open Menu"><div id="zz17_ListActionsMenu_t" class="ms-menubuttoninactivehover" onmouseover="MMU_PopMenuIfShowing(this);MMU_EcbTableMouseOverOut(this, true)" hoverActive="ms-menubuttonactivehover" hoverInactive="ms-menubuttoninactivehover" onclick=" MMU_Open(byid('zz13_RptControls'), MMU_GetMenuFromClientId('zz17_ListActionsMenu'),event,false, null, 0);" foa="MMU_GetMenuFromClientId('zz17_ListActionsMenu')" oncontextmenu="this.click(); return false;" nowrap="nowrap"><a id="zz17_ListActionsMenu" accesskey="C" href="#" onclick="javascript:return false;" style="cursor:hand;white-space:nowrap;" onfocus="MMU_EcbLinkOnFocusBlur(byid('zz13_RptControls'), this, true);" onkeydown="MMU_EcbLinkOnKeyDown(byid('zz13_RptControls'), MMU_GetMenuFromClientId('zz17_ListActionsMenu'), event);" onclick=" MMU_Open(byid('zz13_RptControls'), MMU_GetMenuFromClientId('zz17_ListActionsMenu'),event,false, null, 0);" oncontextmenu="this.click(); return false;" menuTokenValues="MENUCLIENTID=zz17_ListActionsMenu,TEMPLATECLIENTID=zz13_RptControls" serverclientid="zz17_ListActionsMenu">Actions<img src="/_layouts/images/blank.gif" border="0" alt="Use SHIFT+ENTER to open the menu (new window)."/></a><img align="absbottom" src="/_layouts/images/menudark.gif" alt="" /></div></span>
</td>
<td class=ms-separator><img src='/_layouts/images/blank.gif' alt=''></td>
<td class="ms-toolbar" nowrap="true">


<span style="display:none"><menu type='ServerMenu' id="zz18_RptControls" largeIconMode="true"><ie:menuitem id="zz19_AddQuestions" type="option" onMenuClick="window.location = '/sites/Test/_layouts/qstNew.aspx?List=%7BA1B0E302%2D497E%2D45B9%2D9994%2D9F0E0171A380%7D&amp;Source=http%3A%2F%2Fsharepointkings%3A7777%2Fsites%2FTest%2FLists%2FSharePoint%2520site%2520survey%2Foverview%2Easpx';" text="Add Questions" description="Add an additional question to this survey." menuGroupId="100"></ie:menuitem><ie:menuitem id="zz20_ListSettings" type="option" iconSrc="/_layouts/images/MenuListSettings.gif" onMenuClick="window.location = '/sites/Test/_layouts/survedit.aspx?List=%7BA1B0E302%2D497E%2D45B9%2D9994%2D9F0E0171A380%7D';" text="Survey Settings" description="Manage questions and settings for this survey." menuGroupId="200"></ie:menuitem></menu></span><span title="Open Menu"><div id="zz21_ListSettingsMenu_t" class="ms-menubuttoninactivehover" onmouseover="MMU_PopMenuIfShowing(this);MMU_EcbTableMouseOverOut(this, true)" hoverActive="ms-menubuttonactivehover" hoverInactive="ms-menubuttoninactivehover" onclick=" MMU_Open(byid('zz18_RptControls'), MMU_GetMenuFromClientId('zz21_ListSettingsMenu'),event,false, null, 0);" foa="MMU_GetMenuFromClientId('zz21_ListSettingsMenu')" oncontextmenu="this.click(); return false;" nowrap="nowrap"><a id="zz21_ListSettingsMenu" accesskey="I" href="#" onclick="javascript:return false;" style="cursor:hand;white-space:nowrap;" onfocus="MMU_EcbLinkOnFocusBlur(byid('zz18_RptControls'), this, true);" onkeydown="MMU_EcbLinkOnKeyDown(byid('zz18_RptControls'), MMU_GetMenuFromClientId('zz21_ListSettingsMenu'), event);" onclick=" MMU_Open(byid('zz18_RptControls'), MMU_GetMenuFromClientId('zz21_ListSettingsMenu'),event,false, null, 0);" oncontextmenu="this.click(); return false;" menuTokenValues="MENUCLIENTID=zz21_ListSettingsMenu,TEMPLATECLIENTID=zz18_RptControls" serverclientid="zz21_ListSettingsMenu">Settings<img src="/_layouts/images/blank.gif" border="0" alt="Use SHIFT+ENTER to open the menu (new window)."/></a><img align="absbottom" src="/_layouts/images/menudark.gif" alt="" /></div></span>
</td>

<td width="99%" class="ms-toolbar" nowrap><IMG SRC="/_layouts/images/blank.gif" width=1 height=18 alt=""></td>


<td class="ms-toolbar" nowrap="true">

<table border=0 cellpadding=0 cellspacing=0 style='margin-right: 4px'>
<tr>
<td nowrap class="ms-toolbar" id="topPagingCellWPQ2">
<td>
</tr>
</table>

</td>
<td class=ms-separator> </td>
<td class="ms-toolbar" nowrap="true">

<table border=0 cellpadding=0 cellspacing=0 style='margin-right: 4px'>
<tr>
<td nowrap class="ms-listheaderlabel">View:&nbsp;</td>
<td id="ctl00_m_g_c84f415c_dba8_4240_b34d_263e596c7eed_ctl00_ctl00_toolBarTbl_RightRptControls_ctl01_ctl00_onetViewSelector" nowrap="nowrap" class="ms-viewselector" onmouseover="this.className='ms-viewselectorhover'" onmouseout="this.className='ms-viewselector'">
<span style="display:none"><menu type='ServerMenu' id="zz22_ViewSelectorMenu" CompactMode="true"><ie:menuitem id="zz23_DefaultView" type="option" onMenuClick="window.location = '/sites/Test/Lists/SharePoint site survey/overview.aspx';" text="Overview" menuGroupId="100"></ie:menuitem><ie:menuitem id="zz24_View1" type="option" onMenuClick="window.location = '/sites/Test/Lists/SharePoint site survey/AllItems.aspx';" text="All Responses" menuGroupId="300"></ie:menuitem><ie:menuitem id="zz25_View2" type="option" onMenuClick="window.location = '/sites/Test/Lists/SharePoint site survey/summary.aspx';" text="Graphical Summary" menuGroupId="300"></ie:menuitem></menu></span><span title="Open Menu"><div id="zz26_ViewSelectorMenu_t" class="ms-viewselector" onmouseover="MMU_PopMenuIfShowing(this);MMU_EcbTableMouseOverOut(this, true)" hoverActive="ms-viewselectorhover" hoverInactive="ms-viewselector" onclick=" MMU_Open(byid('zz22_ViewSelectorMenu'), MMU_GetMenuFromClientId('zz26_ViewSelectorMenu'),event,true, 'ctl00_m_g_c84f415c_dba8_4240_b34d_263e596c7eed_ctl00_ctl00_toolBarTbl_RightRptControls_ctl01_ctl00_onetViewSelector', 0);" foa="MMU_GetMenuFromClientId('zz26_ViewSelectorMenu')" oncontextmenu="this.click(); return false;" nowrap="nowrap"><a id="zz26_ViewSelectorMenu" accesskey="W" href="#" onclick="javascript:return false;" style="cursor:hand;white-space:nowrap;" onfocus="MMU_EcbLinkOnFocusBlur(byid('zz22_ViewSelectorMenu'), this, true);" onkeydown="MMU_EcbLinkOnKeyDown(byid('zz22_ViewSelectorMenu'), MMU_GetMenuFromClientId('zz26_ViewSelectorMenu'), event);" onclick=" MMU_Open(byid('zz22_ViewSelectorMenu'), MMU_GetMenuFromClientId('zz26_ViewSelectorMenu'),event,true, 'ctl00_m_g_c84f415c_dba8_4240_b34d_263e596c7eed_ctl00_ctl00_toolBarTbl_RightRptControls_ctl01_ctl00_onetViewSelector', 0);" oncontextmenu="this.click(); return false;" menuTokenValues="MENUCLIENTID=zz26_ViewSelectorMenu,TEMPLATECLIENTID=zz22_ViewSelectorMenu" serverclientid="zz26_ViewSelectorMenu">Overview<img src="/_layouts/images/blank.gif" border="0" alt="Use SHIFT+ENTER to open the menu (new window)."/></a><img align="absbottom" src="/_layouts/images/blank.gif" alt="" /></div></span>
</td>

</tr>
</table>

</td>

</tr>
</table>


<TABLE class="ms-summarystandardbody" cellpadding=0 cellspacing=0 width=600px style="margin: 10px;" border=0 rules=rows> <TR> <TD class="ms-formlabel" width=190px ID="overview01">Survey Name:</TD> <TD class="ms-formbody" >Movie knowledge survey</TD> </TR> <TR> <TD class="ms-formlabel" valign="top" ID="overview02">Survey Description:</TD> <TD class="ms-formbody">This is the startbold Hindi endbold as well as the startitalic English movie enditalic Knowledge survey. linebreak

we would like to know how much people are startunderline aware about the Hindi and English movies endunderline</TD> </TR> <TR> <TD><IMG SRC="/_layouts/images/blank.gif" width=1 height=1 alt=""></TD> </TR> </TABLE>
<TABLE border=0 style="margin: 0px 8px 0px 8px;">
<tr><td><img src="/_layouts/images/blank.gif" width=1 height=4 alt=""></td></tr>
<tr>
<td nowrap>
<img src="/_layouts/images/rect.gif" alt=""><span class=ms-toolbar>&nbsp;</span>
<a class="ms-toolbar" ACCESSKEY=R ID=diidSurveyResults HREF="{siteurl}/Lists/SharePoint site survey/summary.aspx"><!-- _locID_text="overview05" _locComment="{StringCategory=TXT}"-->Show a graphical summary of responses</a>
<span class=ms-toolbar>&nbsp;</span>
</td>
</tr>
<tr>
<td nowrap>
<img src="/_layouts/images/rect.gif" alt=""><span class=ms-toolbar>&nbsp;</span>
<a class="ms-toolbar" ACCESSKEY=U ID=diidResultsByUser HREF="{siteurl}Lists/SharePoint site survey/AllItems.aspx"><!-- _locID_text="overview06" _locComment="{StringCategory=TXT}"-->Show all responses</a>
<span class=ms-toolbar>&nbsp;</span>
</td>
</tr>
</TABLE>


And see the effect of the above code.




That's it.

Creating and working with Survey in SharePoint - Part 3

Hi All,

We are going to discuss more on survey in this article. If you have not gone through the previous articles, I would suggest you to go through those articles first and then proceed for reading.

If you haven't gone through the previous articles of this series, i would highly recommend to read following articles before proceeding.

Creating and working with Survey in SharePoint - Part 1

Creating and working with Survey in SharePoint - Part 2

and

Creating and working with Survey in SharePoint - Part 4

Creating and working with Survey in SharePoint - Part 5

Now, that we have survey list already created and if you see the description of the survey on the overview.aspx, there is a difference in the survey description in the webpart and survey description below survey name. Check this out.



The difference is the line break. If you observe, survey description in the web part is written as it is without any line break however survey description under the name of survey breaks two separates sentences into two different lines because when we created the survey we gave it like that.

So in this article we will discuss two important things that will help you not only for the survey but also for any other list and any other document library as well.

Here we will remove the survey description below the name of the survey because we can already see the description in the web part and also we will include the HTML in the description now. It is very much similar to what we have learnt in previous articles just a class name change and that will do our job. Let us see in detail.

Ok, Edit the overview page and place the content editor web part below to the original web part.



Ok, first let us go and change the description of survey. Go to settings, survey settings, title and description and change the description to the following.

This is the startbold Hindi endbold as well as the startitalic English movie enditalic Knowledge survey. linebreak


we would like to know how much people are startunderline aware about the Hindi and English movies endunderline.

Ok, now go back to the overview view of the survey and observe the survey description.



As you can see those words start appearing in the description, so we need to get rid of it and replace them with the actual HTML behavior and that is what we did in previous articles. So go ahead and modify the content editor web part and place the following code in that. Note one important line in the below code and that line is where we assign “ms-formbody’ class. Earlier we assigned “ms-formlabel” in previous articles to add HTML in questions.

<script language="JavaScript">
var ClassName;
ClassName = 'ms-formbody';

var elements = new Array();

var elements = document.getElementsByTagName('td');

for(var e=0;e<elements.length;e++)
{
if(elements[e].className == ClassName)
{
elements[e].innerHTML = elements[e].innerHTML.replace('linebreak','<br/>');

elements[e].innerHTML = elements[e].innerHTML.replace('startunderline','<u>');

elements[e].innerHTML = elements[e].innerHTML.replace('endunderline','</u>');

elements[e].innerHTML = elements[e].innerHTML.replace('startitalic','<i>');

elements[e].innerHTML = elements[e].innerHTML.replace('enditalic','</i>');

elements[e].innerHTML = elements[e].innerHTML.replace('startbold','<b>');

elements[e].innerHTML = elements[e].innerHTML.replace('endbold','</b>');

}

}

</script>



And there you go, see the effect of it.



Ok, look good now. But there is a problem here, still look at the survey description above the web part. It still shows the words (startbold, endbold etc). They have not been replaced yet.

How to replace them? Ok, here is the answer. Just add one more content editor web part below the previous content editor web part and copy the same HTML content above, just make two changes. Change the class name and getElemtByID from TD to Div as this description is in the div tag, not in the TD tag.

ClassName = 'ms-listdescription'
var elements = document.getElementsByTagName('div');


and there you go, see the magic.



Actually for this specific survey type of list, we don’t need this to be here as on the same page, we can see the survey description in the web part. So let us go and remove the description of survey below the name of the survey from overview.aspx.

Modify the last content editor web part and paste the following code inside it.

<script language="JavaScript">
var ClassName;
ClassName = 'ms-listdescription';

var elements = new Array();

var elements = document.getElementsByTagName('div');

for(var e=0;e<elements.length;e++)
{
if(elements[e].className == ClassName)
{

elements[e].innerHTML = '';
}

}

</script>


And see the effect of above code. Survey description is gone.



Remember one very important point. You need to place this last content editor web part in every view page. We placed it only in overview.aspx. Just try and change the view to “All responses” and “Graphical summary”. Survey description will appear there, so just make sure that you place the last content editor web part on each view page separately as well.

Sunday, August 30, 2009

Creating and working with Survey in SharePoint - Part 2

Hi All,

Here I am back with some more interesting stuff in survey list. In previous post we discussed about the advantages of survey list. But it is not true in every case. It has got many other limitations as well. Here in this article, we are going to discuss about one basic difficulty about survey.

I would first suggest you to read Creating and working with Survey in SharePoint - Part 1 of the series.

For further reading read Creating and working with Survey in SharePoint - Part 3

Creating and working with Survey in SharePoint - Part 4

Creating and working with Survey in SharePoint - Part 5

If you want to have some HTML in survey’s question, then we cannot insert that. Sometimes we may require making some font bold, something italic and we want to underline something. We need to increase the font size, we may require to add hyperlink in question, then we cannot do it.

So anyways we have to overcome this problem anyhow. So here is a way how you can insert HTML in the question of survey.

First make a note of one very important point, you have to repeat these steps for each and every page that you have for the survey. Means if you have branching question then you get more than one page to respond.

Before getting actually in to this, you first need to understand that how we will replace the normal text with HTML text.

Ok, let us go back to our first question. Open the question and add the following words before and after Department.



See the effect of this change on questions. We can clearly read startitalic and enditalic in first question.



We have added these words and we will replace this word with startitalic with <i> and enditalic </i> in content editor web part. You can use whatever word that you want, we only need to replace those words in the web apart. Let us see how we will do this now.

Go ahead and add one content editor web part below the questions. Edit the page and add the content editor web part.

Click on modify shared web part, click on source editor and write the code as shown in below.

<script language="JavaScript">
var ClassName;
ClassName = 'ms-formlabel';

var elements = new Array();

var elements = document.getElementsByTagName('td');

for(var e=0;e<elements.length;e++)
{
if(elements[e].className == ClassName)
{

elements[e].innerHTML = elements[e].innerHTML.replace('startitalic','<i>');

elements[e].innerHTML = elements[e].innerHTML.replace('enditalic','</i>');


}

}

</script>



Let us have a look on this above code. Here what we have done is that we have first taken out ms-formlable class as questions belong to this class in SharePoint architecture. We then take all ID because all questions are in TD tag and then we find our forcefully entered two words and replace them with proper HTML tag and there you go. See the effect of the above code.



Let us go ahead and change our third question. Make the following change in it.



Now again go ahead and change the existing editor web part with following addition with above code.

elements[e].innerHTML = elements[e].innerHTML.replace('linebreak','<br/>');

elements[e].innerHTML = elements[e].innerHTML.replace('startunderline','<u>');

elements[e].innerHTML = elements[e].innerHTML.replace('endunderline','</u>');


The effect of the above code is shown below. We have also broken question in two lines.



Now let us go and create hyperlink in the same question. Here is a trick to add hyperlink to the question. Let us say for example we want to have a hyperlink on “like” word and that should take to the Home page link and it should open in new page. In addition to this, it should be of bigger size than other words.

So here is a simple answer of the tuff question. Add just one more line to your content editor web part.

elements[e].innerHTML = elements[e].innerHTML.replace('like','<a href="/sites/Test/default.aspx" target="_blank" style ="font-size:14pt" >like</a>');


and see the effect of above code.



I hope that now you have the clear picture. All it takes is the knowledge of HTML and you can insert anything, almost anything with HTML in the questions.

I will soon come up with part 3. keep reading it.

Creating and working with Survey in SharePoint -Part 1

Hi All,

Today we will learn about SharePoint Survey list. A very useful and very interesting list with many advantage and bit of limitations as well. First let us understand the advantage.

Whenever you want to collect the responses from various people, across your organization about any event, any activity or any other thing, Survey is best suited list. It allows you to collect the responses in various ways. You can ask the questions and they can answer those questions and then result can be analyzed by taking it to the excel sheet or through graphical summary or by watching all responses at once.

You can have as many questions as you want and the format of their answers can also be of great varieties. For example, you may want to ask one question whose answer is simple text or multiple line of text with formatting. You can also have a question whose answer is choice (selection in terms of radio buttons, check boxes, drop downs). You can have question whose answer can be a date. We can have all these with built in survey list.

Another advantage of survey is that you can also add branching logic in it. That means, let us say, you have one question which depends upon the answer of some other question. To show or not to show a question depends upon the answer of previous question. This kind of branching can also be done in survey list.

So all and all at very basic level, if we would like to collect responses from people, survey is the best choice.

Let’s see the basic steps involved in the creating Survey List. Go to Create and select the Survey under tracking category. Give the name and description like shown below. Observe that you have one setting which says allow multi responses. If you want to collect multiple responses from individual person, then you should allow this else don’t allow this. This basically allows responder to respond to survey more than one time.



So we are going to create movie quiz. Once you are done with the creation of the survey list, we now need to add questions to add and have to decide what kind of answer each question has.

I know many people may not like this survey as it seems funny. But my main intension is to let you know how we can create it and what are the options available for answers and how branching can be done.

So go ahead and add the questions to it. Click on settings -> Add Question and add the first question. Click next question after creating each question.

1) Your Department -> Single line of text
2) Your Location -> Single line of text
3) What kind of movies do you like? -> Multiple lines of text and plain text.

Ok, now we are going to give user a choice. Either he can go for Hindi quiz or he can go for English quiz.

So go ahead and create one question, again by selecting settings->Add Question.

4) Which movie quiz would you like to give? -> Choice, Type: Radio button and add Hindi and English in the text box provided.

Now we actually want to branch the user directly to the questions of Hindi cinema and English Cinema depending on user’s choice. We cannot branch the question right now. That can be done after adding all questions and that will be done from the survey settings page. So now we will move ahead and add the Hindi cinema questions.

Go ahead and add question.

5) Rate yourself in Hindi Cinema.>Rating scale. Here we can define the sub questions and each question can have rating scales. So add following questions to it.
a. Old year movies (1950-1970)
b. Medium year movies (1971-2000)
c. Latest movies (2000-2009)


6) Add next question. Name the actor whose famous dialogue is “Kitne Aadmi the?” Choice, drop down and add following options. Jay, Gabbar, Veeru

7) Add next question. Name the upcoming movie of Akshay Kumar which is said to be captured under water. Single line of text.

8) Add next question. Rate yourself in English Movies.>Rating scale. Here we can define the sub questions and each question can have rating scales. So add following questions to it.
a. Old year movies (1950-1970)
b. Medium year movies (1971-2000)
c. Latest movies (2000-2009)


9) Add next question. Name the actor who was gifted God power in the movie "Bruce Almighty'. Single line of text.

10) Add next question. What was the version number mention in the latest movie of “Die Hard" series? Choice and options are 3.0, 4.0, and 3.5.

11) Last we will ask about the suggestion. Add question “Any suggestions that you want to give…” Multi lines of text.

If you want to have page break and then want to ask next question in next page, then add page separator and then add the next question so that this question will come on next page and not one the same page.

After adding these questions, your settings page should look something like this



Now, open the main page of survey list. It should look like below image and it shows description of the survey, number of responses when it was created and click to see all responses and show a graphical summary.



Ok, now go to survey settings and see that Branching logic column is empty as we have yet not defined any branching. We want to branch the question as per the question in which we asked that what movie quiz you would like to give. If user selects Hindi, then we want to jump to the Hindi questions without asking for English movie questions and if user selects English, we need to jump to the English movie questions without asking for Hindi movie questions.

So go ahead and click the question which asks for the selection of movie quiz and select like shown below. This defines that when user clicks on Hindi he will be redirected to the first Hindi question else he will be redirected to English question.



Add one more branching with the question which asks about Akshay Kumar’s upcoming movie and add branching logic as shown below. We need to add this branch because if user selects Hindi, then all questions of English movie will also come and we don’t want that so we will branch to the last question from this Akshay Kumar’s question so that no English questions asked. Here what we have done is whatever the response is, we will jump to the last question.



Now go back and click on respond to this survey. You will see that it asks only up to the question whose answer branches the next question.



Fill the details, select Hindi and click next, then as you can see you are presented with a screen where you get the Hindi movie questions and one interesting thing is save button in between. That means if you have very long survey and it has many branching logic, then you can save the survey and then continue at your own convenience at any time.



Click next and finally fills up the final text box and there you go, you are done with responding your first survey. If you observe the column Completed, you will find “yes” because we have completed the survey. If you would have saved it in between somewhere, you would have find it “No”, that means it is partially saved. You get “Yes” only when somebody fills the entire survey.

I will discuss bit deep about this in my coming articles of survey series. If you now click on respond to survey, you will get an error saying that you cannot give response for more than one time. If you have saved your survey, then you can click on the survey and complete that survey again.

One very important thing to note here is that person who creates the survey has to make sure that whether to allow user to see only his response or he can see everybody’s response. Same goes for editing options, should he allows to change other’s response or his own only. These settings are very important, if these options are set, then even user clicks on View all responses, he will be able to see only his response. Same is true in the case of graphical summary. He cannot see other responses from other people.

This is basically called Item level security. To set this on survey, go to Settings->Survey settings->advanced settings. Here you will find an option to set these properties. There you can also set to allow these responses to be a part of SharePoint search.

You can also export the result into excel as the option is available in the action menu.

Read Creating and working with Survey in SharePoint -Part-2

and

Creating and working with Survey in SharePoint - Part 3

Creating and working with Survey in SharePoint - Part 4

Creating and working with Survey in SharePoint - Part 5

for further interesting reading.

Thursday, August 27, 2009

SQL query on SharePoint content database: Step by Step 1

After a very long time we are back with fetching information directly from sharepoint content database with the help of SQL query.

check our previous post(s) here

But for this time we are going step by step.

First of all each and every web application has its own content database.


site collection(s)

To find the information about site collection there is a table called “Sites”
--This table content information of site collection(s)
select * from sites

--Number Site collection in a web application
select count(*) as 'Total Number OF Site Collection' from sites


Useful fields in sites table are ‘ID’ and ‘RootWebID’


Sites (a.k.a SPWeb)

To find the information about all the web in web application (that includes all the site collection) there is a table called “Web”
--This table content information of all the web
select * from webs
ID field of webs table is foreign key from rootwebid of sites table
So you can have relation like
--Relation of sites and web
Select * from webs inner join Sites on Webs.Id = Sites.RootWebId
Below are the useful fields.
Select
id,--unique ID
siteid,--site collection ID
parentwebid,--Null if top level site otherwise ID of webs
fullurl,--relative url
title,--web Title
description,--Web Description
masterurl,--Master page URL
custommasterurl,--Custom master page URL
sitelogourl,--site logo URL
sitelogodescription
from webs
inner join Sites on Webs.Id = Sites.RootWebId


This is the relation between web application, site collection, and then web from the database architectural point of view.

We will go further with list and libraries, and items but that will be step by step

Disclaimer

Running Direct queries on Sharepoint Database is not recommended by Microsoft.
Simply it's not for the faint of heart. Directly querying or modifying the database can place extra load on a server, or can expose information to users in a way that violates security policies or personal information management policies.We highly recommend doing all testing in a non-production environment and only for R & D purpose.

Saturday, August 15, 2009

Changing sequence and adding new menu items in SharePoint

Hi All,

As I have explained you in my previous post about the menu items in the toolbar on AllItems.aspx page. We will take the same code and sample here and I will explain you today how to play with the Menu items inside the menus.

So this post is all about changing the sequence of menu items and adding new menu items.

First let me show you how you can change the position of individual items in the menu. Considering we are playing with Actions menu and we want to change the “View RSS Feed” to appear with the Edit in Datasheet option.

Ok, let me clarify one thing very clearly. We should not change the default place of menu items as they are actually categorized properly and they have been placed in respective group items. For example, it doesn’t make sense if you place Alert Me option with Edit in Datasheet option. Does it make sense to have this option with Datasheet option? Answer is absolutely no.

But this is just for fun purpose and also to give you an idea about how to do that. Before we actually go in to the code, I would like to share here that each of these menu options fall under MenuGroupID.

First observe the below figure closely. See Red circle, Bur circle and green circle.



Now see the below image of menu items



See, There is only one red circle because see the first category. We have only one single item here which is EditInDatasheet. See two blue circles, we have two items in the menu category (Export to Spreadsheet and Open with Access) and last we have again two circles shown in green color represents last two options. (View RSS Feed and Alert Me). As you can see all belongs to MenuGroupId. First item has id number 200; second two items have id number 400 and last two items have id number 500.

So now we will play the trick and we will move View RSS Feed with EditinDatasheet. All we need to do is just change the MenuGroupId of RSS Feed from 500 to 200 so that it will come with ExportinDatasheet.

foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.ActionsMenu".ToUpper())
{

ActionsMenu Menu = (ActionsMenu)childControl;
Menu.Visible = true;

if (Menu.GetMenuItem("ViewRSS") != null)
{
Menu.GetMenuItem("ViewRSS").MenuGroupId = 200;
}

break;
}
CheckControl(childControl);
}


See the effect of this code,



If we want View RSS Feed to appear first and Datashet option to come second, then just a little modification will do this for us. We only need to add one single line only.

if (Menu.GetMenuItem("ViewRSS") != null)
{
Menu.GetMenuItem("ViewRSS").MenuGroupId = 200;
Menu.GetMenuItem("ViewRSS").Sequence = 0;
}




This is the way you can change the menu item from one place to the other place.

Now how about adding a menu item template to Menu? Let us go ahead and add menu item template to the Actions menu.

MenuItemTemplate objTemplate = Menu.AddMenuItem("MailMeID", "Mail Me From Hotmail",
"/_layouts/images/SPSPROFL.GIF",
"This will take you to hotmail", "", strClientURL);

objTemplate.MenuGroupId = 200;





Once you click on this item, it will take you to hotmail.com. Ok, now how about adding a client side code to it? As you can see in my previous code, I kept the last parameter blank. That is where we need to right the client event.

Just to demonstrate you, I have used the built in Client Click of RSS feed and assigned it to our new menu item.


if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.ActionsMenu".ToUpper())
{
ActionsMenu Menu = (ActionsMenu)childControl;
Menu.Visible = true;
string strClientURL = "window.location = '/sites/Test/_layouts/listfeed.aspx?List=%7BA6B5F63B%2DB860%2D418F%2DBEB0%2D8DAFC72C1C6B%7D';";
MenuItemTemplate objTemplate = Menu.AddMenuItem("MailMeID", "Mail Me From Hotmail",
"/_layouts/images/SPSPROFL.GIF",
"This will take you to hotmail", "", strClientURL);


objTemplate.MenuGroupId = 200;

break;
}


You can change this url to your desired page in the site. Once you click on Mail me from Hotmail, it will take you to RSS Feed page.



If you add one more single line of code which is shown below, we get that new menu item with separator. It separates it with the other menu items with one line. Note that we have commented the MenuGroupID assignment, so that it becomes a separate group.

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.ActionsMenu".ToUpper())
{

ActionsMenu Menu = (ActionsMenu)childControl;
Menu.Visible = true;

string strClientURL = "window.location = '/sites/Test/_layouts/listfeed.aspx?List=%7BA6B5F63B%2DB860%2D418F%2DBEB0%2D8DAFC72C1C6B%7D';";

MenuItemTemplate objTemplate = Menu.AddMenuItem("MailMeID", "Mail Me From Hotmail",
"/_layouts/images/SPSPROFL.GIF",
"This will take you to hotmail", "", strClientURL);

Menu.AddMenuItemSeparator();

//objTemplate.MenuGroupId = 200;

break;
}




Ok, now once again let us get the DesigntimeHTML and see what the new things that we have got,



Check out the new menu item added. I have highlighted it with blue underline and also see the new MenuGroupID that we got. It is 2147483647. So now we know that if any other menu item we want to add with the same group, we need to assign this number to the new MenuItemtemplate as we saw in the beginning of this post.

I am finding more interesting about this, I will be eager to share it with you all-time supportive readers.

Hiding / Removing Menu and Menu items in SharePoint

Hi All,

Today we are going to discuss something on tool bar action. We all know that we get toolbar where we have New menu, action menu available when we are in AllItems.aspx.

Let us see how we can remove the toolbar specific item, means sometime we may require removing NewMenu and sometimes we may want to remove ActionMenu or even from Settings menu, then here is a way we can do this.

We can also hide specific item from New Menu, Action Menu or Settings menu. First we need to iterate through all controls on AllItems.aspx and once we find the specific menu we are looking for, then we can cast that control in to specific menu and then call visible method to set it to true and false.

First let me give you a highlight on what are these classes.

Microsoft.SharePoint.WebControls.NewMenu
Microsoft.SharePoint.WebControls.ActionsMenu
Microsoft.SharePoint.WebControls.SettingsMenu


So to demonstrate, go ahead and create one class which inherit from web part class and write down the following code in createchildcontrol event. Deploy it on your site and edit the AllItems page that you want to work with and add the webpart above AllItems web part (form web part).

protected override void CreateChildControls()
{
foreach (Control ctrl in this.Page.Controls)
{
CheckControl(ctrl);
}
base.CreateChildControls();
}


Now, in this code we will check each control on the page and once we find our required control, then we will cast that control and set the visible property.

private void CheckControl(Control ParentControl)
{
try
{
foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.NewMenu".ToUpper())
{
NewMenu Menu = (NewMenu)childControl;
Menu.Visible = false;

if (Menu.GetMenuItem("NewFolder") != null)
Menu.GetMenuItem("NewFolder").Visible = false;
break;
}
CheckControl(childControl);
}
}
}


Above code will iterate all controls till it finds the New Menu and once it gets the New Menu, we cast the control in the NewMenu class object and set its property to false, means we cannot see NewMenu.

Below figure shows the result of above code.



Same way, if we run the below code

foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.ActionsMenu".ToUpper())
{

ActionsMenu Menu = (ActionsMenu)childControl;
Menu.Visible = false;
break;
}
CheckControl(childControl);
}


Then, you can see the result as shown in the below screen



Similarly, if you write the below code,

foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.SettingsMenu".ToUpper())
{
SettingsMenu Menu = (SettingsMenu)childControl;
Menu.Visible = false;
break;
}
CheckControl(childControl);
}


Then, you can see the result as shown in the below screen.



Ok, let us proceed. From the List Settings option, I have enabled to new folder option.



So ideally you will find New Folder option when you click in New from the tool bar. However if you write the following code, then it will hide the New Folder option.

foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.NewMenu".ToUpper())
{
NewMenu Menu = (NewMenu)childControl;
Menu.Visible = true;

if (Menu.GetMenuItem("NewFolder") != null)
Menu.GetMenuItem("NewFolder").Visible = false;
break;
}
CheckControl(childControl);
}




Ok, same goes for the other menu items in the other menu as well. For example, let’s remove the Alert Me option from Actions menu. Question is how to do that? In above example, we used NewFolder as MenuItem and found it. But what needs to be passed as parameter in GetMenuItem method?

Let me give you a wonderful trick. Even I was not aware about this. I worked on it and find out that it’s the ID of the MenuItem. Where to find that ID, I’ll tell you how I found it. See the below figure. Once, you come in the IF condition of your menu option, set a break point and then observe the following red circle marks. This is the Menu.GetDesignTimeHTML() method that you can check in local window or immediate window. I have taken this HTML after my debug point crossed the code that makes “Alert Me” visible false, that is the reason you cannot find Alert Me text here. If you observe this HTML before the code gets execute from that point, you will be able to see that as well.



Use the ID of the menu item in code. Just remember avoid everything including _ character in the ID and take the rest of all character and pass it to the GetMenuItem method.

And now see the below code

foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.ActionsMenu".ToUpper())
{

ActionsMenu Menu = (ActionsMenu)childControl;
Menu.Visible = true;

if (Menu.GetMenuItem("SubscribeButton") != null)
Menu.GetMenuItem("SubscribeButton").Visible = false;

break;
}
CheckControl(childControl);
}


So, from where I come to know that I have to pass “SubscribeButton” as parameter? Yes, its from the designtimHTML. Once you get all the code, then you can use it.

So after executing the above code, see the result below.” Alert me” menu item is not there in Actions menu.



So if I want to hide View RSs Feed, I will use the ID “ViewRSS” and run the code and I will get the result. (Check the red circle in the DesigntimeHTML figure).

foreach (Control childControl in ParentControl.Controls)
{

if (childControl.ToString().ToUpper() == "Microsoft.SharePoint.WebControls.ActionsMenu".ToUpper())
{

ActionsMenu Menu = (ActionsMenu)childControl;
Menu.Visible = true;

if (Menu.GetMenuItem("ViewRSS") != null)
Menu.GetMenuItem("ViewRSS").Visible = false;

break;
}
CheckControl(childControl);
}





Same way you can check the DesignTimeHTML for Settings menu and play with the MenuItem under Settings Menu.

Hope you’ve liked my research. Thank you in advance. :)



Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com