Sunday 24 March 2013

SharePoint Shortcut URL’s


Below is the list of pages & their paths which can be accessed from URL :

· Add web parts to any page: append ?PageView=Shared&ToolPaneView=2
· Create New Site Content /_layouts/create.aspx
· Create New Site: _layouts/NewsbWeb.aspx
· List Template Gallery: _catalogs/lt/Forms/AllItems.aspx
· Master Page Gallery: _catalogs/masterpage/Forms/AllItems.aspx
· Manage your Alerts _layouts/SubEdit.aspx
· Create New Alert: _layouts/SubChoos.aspx
· Manage Site Collection Administrators /_layouts/mngsiteadmin.aspx
· Manage Sites and Workspaces /_layouts/mngsubwebs.aspx
· Manage People /_layouts/people.aspx
· Manage User Permissions /_layouts/user.aspx
· Modify Navigation /_layouts/AreaNavigationSettings.aspx
· Modify Site Navigation: _layouts/SiteNavigationSettings.aspx
· Recycle Bin /_layouts/AdminRecycleBin.aspx
· Site Directory _layouts/SiteDirectorySettings.aspx
· Save Site as Template: _layouts/savetmpl.aspx
· Site Settings page: _layouts/settings.aspx
· Create New Web Part Page: _layouts/spcf.aspx
· Site Template Gallery : _catalogs/wt/Forms/Common.aspx
· Site Column Gallery /_layouts/mngfield.aspx
· Site Content Types /_layouts/mngctype.aspx
· Site Content and Structure Manager /_layouts/sitemanager.aspx
· Site Usage Summary /_layouts/SpUsageWeb.aspx
· User Alerts /_layouts/sitesubs.aspx
· View All Site Content /_layouts/viewlsts.aspx
· Web Part Gallery: _catalogs/wp/Forms/AllItems.aspx
· Web part maintenance mode: append ?contents=1 to the URL of the page
· Open the page in Edit Mode: In Address bar, Type "javascript:MSOLayout_ToggleLayoutMode();"
or "javascript:MSOTlPn_ShowToolPane(’2′);" in the Address bar
· Add Web Parts Pane: ?ToolPaneView=2

Monday 11 March 2013

JQuery to add html controls dynamically during runtime

I want to add a textbox controls dynamically during runtime. At the same time I should be able to remove the added controls one by one. Below is the JQuery to achieve the same. For the below script to run I will need the reference of the jquery-1.3.2.min.js file.

<script type="text/javascript" src="Path/jquery-1.3.2.min.js"></script>

<script type="text/javascript" language="javascript">
$(document).ready(function () {
var counter = 2;
$("#addtextarea").click(function () {
if (counter1 > 5) {
alert("Only 5 textboxes are allowed");
return false;
}
else
 {
var newTextAreaDiv = $(document.createElement('div')).attr("id", 'TextAreaDiv' + counter);
newTextAreaDiv.after().html('<textarea name="TextArea' + counter + '" id=" TextArea ' + counter + '" value="" ></textarea><br/><br/>');
newTextAreaDiv.appendTo("#TextGroup");
counter++;
}
});
$("#removetextarea").click(function () {
if (counter == 2) {
alert("No more textbox to remove");
return false;
}
else
 {
 counter1--;
 $("#TextAreaDiv" + counter).remove();
 }
 });
 });
 </script>


The above script will check the ID’s of DIV tags & accordingly add/remove the controls i.e. the new DIV tags inside the main DIV group. On click on the “Add” anchor tag the new DIV tag is created & the control inside the DIV tag is added & this DIV tag is added in the DIV Group one below the other. Same way the “Remove” anchor tag will remove the DIV tags with its controls in decending order one by one. Here while adding the controls I have restricted the user to add controls upto 5.


<div id="TextGroup">
    <div id="TextAreaDiv">
        <textarea name="TextArea" id=" TextArea "></textarea>
        <br />
    </div>
</div>
<div>
    <a id="addtextarea" href="#">Add</a>&nbsp;/&nbsp;<a id="removetextarea" href="#">Remove</a>
</div>

Programmatically Display List data in Web part getting List Name & filed Name from Edit Web Part Properties Drop Down in SharePoint 2010

To display the list data in a web part, open Visual Studio 2010 & create a Web Part Solution. The Web Part solution will appear as shown below




Now in the above solution add a class file which will contain the code to create a dropdown in the Edit Web Part Properties. 
I will declare this class file to work as a tool part as shown below

class DisplayListToolPart : Microsoft.SharePoint.WebPartPages.ToolPart

In this class file I will write the following code


class DisplayListToolPart : Microsoft.SharePoint.WebPartPages.ToolPart
{
#region Controls Declaration
Panel toolPartPanel;
DropDownList ddlAllLists;
DropDownList ddlAllListFields;
TextBox txtItemCount;
#endregion
protected override void CreateChildControls()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
#region Creating instances of Toolpart Controls
//Add Panel
toolPartPanel = new Panel();
toolPartPanel.GroupingText = "<b>List Display Configuration</b>";
//Add List Drop Down
ddlAllLists = new DropDownList();
ddlAllLists.Width = Unit.Pixel(200);
//Add List Item Fields Drop Down
ddlAllListFields = new DropDownList();
ddlAllListFields.Width = Unit.Pixel(200);
//Add List Item Count Text Box
txtItemCount = new TextBox();
txtItemCount.Width = Unit.Pixel(200);
ddlAllLists = new DropDownList();
ddlAllLists.ID = "ddlAllLists";
ddlAllLists.AutoPostBack = true;
ddlAllLists.Width = Unit.Pixel(200);
//Function to Add All List Fields in ddlAllListFields dropdown on selected item changed
ddlAllLists.SelectedIndexChanged += new EventHandler(ddlAllLists_SelectedIndexChanged);
#endregion
//Function to add All Lists in the ddlAllLists dropdown
populateToolPartControls();
#region Adding all control to toolpart stack
toolPartPanel.Controls.Add(new LiteralControl("Select List Name"));
toolPartPanel.Controls.Add(new LiteralControl("</br>"));
toolPartPanel.Controls.Add(ddlAllLists);
toolPartPanel.Controls.Add(new LiteralControl("Select  List Item To Display"));
toolPartPanel.Controls.Add(new LiteralControl("</br>"));
toolPartPanel.Controls.Add(ddlAllListFields);
toolPartPanel.Controls.Add(new LiteralControl("Select Number of Items to Display"));
toolPartPanel.Controls.Add(new LiteralControl("</br>"));
toolPartPanel.Controls.Add(txtItemCount);
//Add Panel Control to Edit Web Part Properties
Controls.Add(toolPartPanel);
base.CreateChildControls();
#endregion
}
}
});
}
catch (Exception ex)
{
//Log
}
}
//Function to add all lists from the current Site
public void populateToolPartControls()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
ddlAllLists.Items.Clear();
//Fetch all Lists & Display in ddlAllLists Dropdown
foreach (SPList list in web.Lists)
{
ddlAllLists.Items.Add(new ListItem(list.Title));
}
ddlAllLists.Items.Insert(0, "--Select--");
}
}
});
}
catch (Exception ex)
{
//Log
}
}
void ddlAllLists_SelectedIndexChanged(object sender, EventArgs e)
{
try
{
populateAllListItemsControl();
}
catch (Exception ex)
{
//Log
}
}
//Function to add all list items of the Selected List
public void populateAllListItemsControl()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.Url))
{
using (SPWeb web = site.OpenWeb())
{
//Get Selected List
SPList lstList = web.Lists[ddlAllLists.SelectedItem.Text];
ddlAllListFields.Items.Clear();
foreach (SPField field in lstList.Fields)
{
//Populate list Columns Dropdown
ddlAllListFields.Items.Add(new ListItem(field.Title, field.InternalName));
}
}
}
});
}
catch (Exception ex)
{
//Log
}
}
//Function to send the selected values to the web part class file.
public override void ApplyChanges()
{
try
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Create object of web part class file
ListDisplayWebPart.ListDisplayWebPart eventList = (ListDisplayWebPart.ListDisplayWebPart)this.ParentToolPane.SelectedWebPart;
eventList.listName = ddlAllLists.SelectedItem.Text;
eventList.fieldName = ddlAllListFields.SelectedValue;
eventList.numberofItems = txtItemCount.Text;
});
}
catch (Exception ex)
{
//Log
}
}
}


Now in the web part class file I will first declare the class to work as a web part as shown below

public class ListDisplayWebPart : Microsoft.SharePoint.WebPartPages.WebPart

Now declare the controls to load in the web part & to get the values from the tool part class file.


public string listName { get; set; }
public string fieldName { get; set; }
public string numberofItems { get; set; }


Also to add custom properties to the tool part I will create a new instance of the tool part class file as shown below

//Function to fetch values from Edit Web Part Properties i.e from ToolPart
public override ToolPart[] GetToolParts()
{
ToolPart[] allToolParts = new ToolPart[3];
WebPartToolPart standardToolParts = new WebPartToolPart();
CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();
allToolParts[0] = standardToolParts;
allToolParts[1] = customToolParts;
allToolParts[2] = new DisplayListToolPart();
return allToolParts;
}


Now I will create controls

private Label instructionsLabel;
private Label listNameLabel;
private Label listItemsLabel;


Below is the code in the web part class file


public class ListDisplayWebPart : Microsoft.SharePoint.WebPartPages.WebPart
{
#region get controls to load
public string listName { get; set; }
public string fieldName { get; set; }
public string numberofItems { get; set; }
#endregion

//Function to fetch values from Edit Web Part Properties i.e from ToolPart
public override ToolPart[] GetToolParts()
{
ToolPart[] allToolParts = new ToolPart[3];
WebPartToolPart standardToolParts = new WebPartToolPart();
CustomPropertyToolPart customToolParts = new CustomPropertyToolPart();

allToolParts[0] = standardToolParts;
allToolParts[1] = customToolParts;
allToolParts[2] = new DisplayListToolPart();
return allToolParts;
}
//Controls
private Label instructionsLabel;
private Label listNameLabel;
private Label listItemsLabel;

protected override void CreateChildControls()
{
try
{
//Create the Instructions label
instructionsLabel = new Label();
instructionsLabel.Text = "Edit this Web Part to select the list to display";
//Create the List Contents label
listNameLabel = new Label();
//Create the label that displays the items
listItemsLabel = new Label();

if (listName != String.Empty && listName != null)
{
if (listName == "--Select--")
{
listNameLabel.Text = "Please Select List";
listNameLabel.ForeColor = System.Drawing.Color.Red;
}
else
{
listNameLabel.Text = "ListName: " + listName;
listNameLabel.ForeColor = System.Drawing.Color.Blue;
instructionsLabel.Text = "";
listItemsLabel.Text = fillListLabel(listName, fieldName, numberofItems);
}
}
else
{
listNameLabel.Text = "";
}

listNameLabel.Font.Bold = true;
listNameLabel.Font.Size = 11;

this.Controls.Add(instructionsLabel);
this.Controls.Add(listNameLabel);
this.Controls.Add(listItemsLabel);
}
catch (Exception ex)
{
//Log
}
}

protected override void Render(HtmlTextWriter writer)
{
try
{
instructionsLabel.RenderControl(writer);
writer.Write("<br /><br />");
listNameLabel.RenderControl(writer);
writer.Write("<br /><br />");
listItemsLabel.RenderControl(writer);
}
catch (Exception ex)
{
//Log
}
}

//Get the Items from the selected list
private string fillListLabel(string listname, string fieldname, string numberofitems)
{
string labelHTML = String.Empty;
int itemcount = 0;
try
{
itemcount = Convert.ToInt32(numberofitems);
using (SPWeb currentWeb = SPContext.Current.Web)
{
SPList list = currentWeb.Lists[listname];
if (list != null)
{
//Show total items
labelHTML += "<b>Total Items: " + list.Items.Count + "</b><br /><br />";

//I want to display names of selected field of selected number of items.
int i = 0;
foreach (SPListItem item in list.Items)
{
if (i < itemcount)
{
labelHTML += item[fieldname] + "<br /><br />";
i++;
}
else
{
break;
}
}
}
}
}
catch (Exception ex)
{
labelHTML = "<span style='color:red;'>Please Enter a valid Number to display List Items </b><br />" + ex.Message + "</span>";
}
return labelHTML;
}
}


Build & deploy the solution. In the Web Part Properties of this web part I will get all the Lists of that site in the drop down. After selecting specific list name the event is fired & all the respective field names are populated in the other drop down. We can select the field name from this drop down which we want to display in the web part.

Sunday 10 March 2013

Script to Open SharePoint Page in Dialogue Box in SharePoint 2010

<div>
<a href="javascript:OpenDialog(‘../SitePages/NewPage.aspx’);">Open Page In Dialogue Box</a>
 </div>


<style type="text/css">
.MyLinkDialog {
    MIN-HEIGHT: 100px; HEIGHT: auto !important
}
IMG.ms-newgif {
    DISPLAY: none
}
</style>


<script type="text/javascript">
//Dialog opening
function OpenDialog(url) {
var options = SP.UI.$create_DialogOptions();
options.url = url;
options.width = 450;
options.style="MyLinkDialog";
options.allowMaximize = false;
options.dialogReturnValueCallback = Function.createDelegate(null, CloseCallback);
SP.UI.ModalDialog.showModalDialog(options);
}
var messageId;
// Dialog callback
function CloseCallback(result, target) {
if (result == SP.UI.DialogResult.OK) {
//Get id
messageId = SP.UI.Notify.addNotification("<img src='_layouts/images/loading.gif'> Creating list <b>" + target + "</b>...", true, "Dialog response", null);
//Create list using client OM
//createList(target);
}
if (result == SP.UI.DialogResult.cancel) {
SP.UI.Notify.addNotification("Operation was cancelled...", false, "", null);
}
}
</script>

Programmatically Display List data in Web part getting List Name & filed Name from Edit Web Part Properties textbox in SharePoint 2010

To display the list data in a web part, open Visual Studio 2010 & create a Web Part Solution. The Web Part solution will appear as shown below


Now in the .cs file i.e. “DisplayListData.cs” file of the web part, we will declare a Personalizable Control which creates a Text box in the Edit Web Part Properties. If we want multiple values we can declare it again & save the value in other string as shown below

//Create a textbox in the Edit Web Part Properties to get the List Name
[Category("Custom Properties"),
Personalizable(PersonalizationScope.User),
WebBrowsable(true),
WebDisplayName("List Name"),
WebDescription("Enter List Name")]
//Get the value from the textbox & save it in the string
public string sListName { get; set; }

//Create another textbox in the Edit Web Part Properties to get the field name
 [Category("Custom Properties"),
Personalizable(PersonalizationScope.User),
WebBrowsable(true),
WebDisplayName("Column Name"),
WebDescription("Enter List Column Name")]
//Get the value from the textbox & save it in the string
public string sListColumnName { get; set; }


Now create the Label Controls to display the items in the web part

Literal ltrl = new Literal();
Label lblListName = new Label();
Label lblColumnName = new Label();
Label lblDisplayError = new Label();

protected override void CreateChildControls()
{
ltrl.Text = "";
lblListName.Text = "List Name entered : " + sListName;
lblListName.Font.Bold = true;
lblColumnName.Text = "List Column Name entered : " + sListColumnName;
lblColumnName.Font.Bold = true;
lblDisplayError.Text = "";
this.Controls.Add(lblListName);
this.Controls.Add(lblColumnName);
this.Controls.Add(lblDisplayError);
try
{
if (sListName != null && sListColumnName != null)
{
using (SPWeb currentWeb = SPContext.Current.Web)
{
SPList oList = currentWeb.Lists[sListName];
if (oList != null)
{
ltrl.Text = "Title<hr style='width:100px;text-align:left;'>";
foreach (SPListItem item in oList.Items)
{
ltrl.Text += "<i>" + item[sListColumnName] + "</i><br>";
}
}
}
}
else
{
lblDisplayError.Text = "Edit the Webpart and enter list name";
}
this.Controls.Add(ltrl);
}
catch (Exception ex)
{
lblDisplayError.Text = ex.Message.ToString();
}
}
protected override void Render(HtmlTextWriter writeHtml)
{
try
{
lblListName.RenderControl(writeHtml);
writeHtml.Write("<br /><br />");
lblColumnName.RenderControl(writeHtml);
writeHtml.Write("<br /><br />");
ltrl.RenderControl(writeHtml);
}
catch (Exception ex)
{
//Log
}
}


Now bulid the Solution & deploy in your web application. Add our custom created web part on the page & go to “Edit Web Part Properties” of that web part. Here we can see our custom created text boxes.

Wednesday 6 March 2013

Programmatically Get the Names of all fields in a list using Console Application in SharePoint 2010



To get the list of all the fields in the list we can create a simple console application. In this console application we can pass the site URL & provide the Name of the list of whose field details we want to use.

string siteUrl = "http://sitename ";
// ClientContext object is used to get the context for the SharePoint objects
string ListName = "/ListName";
//ClientContext clientcontext = new ClientContext(siteUrl);
SPSite site = new SPSite(siteUrl);
Console.WriteLine(site.ToString() + "\n");
SPWeb web = site.OpenWeb();
SPList list = web.GetList(string.Concat(web.Url, ListName));
Console.WriteLine(list.ToString() + "\n");
//SPList list = web.Lists["Users"];
foreach (SPField f in list.Fields)
{
    Console.WriteLine(f.StaticName.ToString() + " - " + f.TypeDisplayName.ToString() + "\n");
}
Console.ReadLine();

Programmatically Copy Items from one Discussion Board to other including Replies in SharePoint 2010

The Discussion Board Template contains two content types attached with it viz. 1) “Discussion” Content Type whose parent Content Type is “Folder” & 2) “Message” Content Type whose parent Content Type is “Item”. The “Discussion” Content Type works as a folder & the “Message” content Type works as the items in the Folder. Hence moving items from Discussion Board same as Other Lists will copy only the folder & not the replies within the folder. Hence to copy the items from one Discussion Board to other with all its corresponding replies, we have to first copy the items from the Discussion Content Type & after that we have to read all the replies of that item & copy each reply in the Destination list one by one. Here during copying we have to copy the items from the default fields as it is as we should know the name who had replied to the discussion & also the name of the creator of the Discussion.
Below is the code for the same.


public void MoveToList(string siteUrl, string Sourcelist, string Destinationlist)
{
try
{
using (SPSite rootSite = new SPSite(siteUrl))
{
using (SPWeb spWeb = rootSite.OpenWeb())
{
string camlquery = string.Empty;
camlquery = "<Where>"
+ "<Lt>"
+ "<FieldRef Name='Expiry_x0020_Date' />"
+ "<Value IncludeTimeValue='FALSE' Type='DateTime' ><Today /></Value>"
+ "</Lt>"
+ "</Where>";
SPQuery qry = new SPQuery();
qry.Query = camlquery;
///Get the Collection of SourceListItem by Caml Query
SPList _sourcelist = spWeb.Lists[Sourcelist];
string rootfolder = _sourcelist.RootFolder.Name.ToString();
SPListItemCollection Srccollitem;                       
Srccollitem = _sourcelist.GetItems(qry);
SPList destlib;
destlib = spWeb.Lists[Destinationlist];
//Check whether the list is of Discussion Board template
if (_sourcelist.BaseTemplate == SPListTemplateType.DiscussionBoard)
{
///Start of For Loop to move items one by one from Source List to Destination List
for (int i = Srccollitem.Count - 1; i >= 0; i--)
{
//Read single item from item collection
 SPListItem item;
item = Srccollitem[i];
SPListItem targetItem;
targetItem = destlib.Items.Add();
//Get the name of the item which is stored as Folder in Discussion Board
SPFolder fldrDiscussion = item.Folder;
//get destination list items
SPListItemCollection listCol = destlib.Items;
//create a new discussion item in the destination list with the title from source list
SPListItem discussion = SPUtility.CreateNewDiscussion(listCol, item[SPBuiltInFieldId.Title].ToString());
//Copy the content from body column from source list to destination
discussion[SPBuiltInFieldId.Body] = item[SPBuiltInFieldId.Body];
//Copy the Author from source to destination
discussion[SPBuiltInFieldId.Author] = item[SPBuiltInFieldId.Author];
//Copy the Editor i.e. "Modified By" from source to destination
discussion[SPBuiltInFieldId.Editor] = item[SPBuiltInFieldId.Editor];
//Copy the name of Created By from source to destination
discussion[SPBuiltInFieldId.Created] = item[SPBuiltInFieldId.Created];
//Copy the content from custom columns created by the user
discussion["Initiated By"] = item["Initiated By"];
discussion["Shared Members"] = item["Shared Members"];
discussion["Expiry Date"] = item["Expiry Date"];
//Update the discussion item
discussion.Update();
//Now we need to copy all the replies of the selected discussion item
SPQuery q = new SPQuery();
q.Query = "<OrderBy><FieldRef Name='Title'/></OrderBy>";
//fire query on the specific discussion item i.e on the specific folder
//The discussion item is stored under Folder Content Type

q.Folder = fldrDiscussion;
//Get collection of replies for specific discussion
SPListItemCollection folderlistcoll = _sourcelist.GetItems(q);
//iterate through each reply to copy them in destination list for that particular discussion
foreach (SPListItem li in folderlistcoll)
{
//Each reply is read as a list item as it is stored in the Message Content Type
//Item content type is the parent of Message content type

SPListItem reply = SPUtility.CreateNewDiscussionReply(discussion);
//Copy the content from reply/body column from source list to destination
reply[SPBuiltInFieldId.Body] = li[SPBuiltInFieldId.Body];
//Copy the author from source list to destination
reply[SPBuiltInFieldId.Author] = li[SPBuiltInFieldId.Author];
//Copy the editor i.e. Modified By from source list to destination
reply[SPBuiltInFieldId.Editor] = li[SPBuiltInFieldId.Editor];
//Copy the name of Created By from source to destination
reply[SPBuiltInFieldId.Created] = li[SPBuiltInFieldId.Created];
//Update the reply in the discussion item
reply.Update();
}
//After updating every reply now update the whole discussion item
discussion.Update();

Console.WriteLine("MoveToList() : ItemName=" + item.Name + ", SiteUrl=" + siteUrl + ", Source=" + Source list+ ", Destination=" + Destinationlist);
}//Now read next discussion item from source list to move it to destination list
}///End of For Loop.
}
}
}
catch (Exception ex)
{
}
}