Thursday, January 26, 2012

SharePoint 2010 SPQuery Paging

For better performance you can do paging in SharePoint without returning all items. But There you can only arrows prev and next page, you cannot use numbering page.

This sample code of paging:

<asp:DropDownList ID="DropDownListSortColumns" runat="server"
onselectedindexchanged="DropDownListSortColumns_SelectedIndexChanged" AutoPostBack=true>
<asp:ListItem>IDasp:ListItem>
<asp:ListItem>Titleasp:ListItem>
<asp:ListItem>Createdasp:ListItem>
<asp:ListItem>Modifiedasp:ListItem>

asp:DropDownList>
<asp:DropDownList ID="DropDownListSortOrder" runat="server"
onselectedindexchanged="DropDownListSortOrder_SelectedIndexChanged" AutoPostBack=true>
<asp:ListItem Value="True">Ascendingasp:ListItem>
<asp:ListItem Value="False">Descendingasp:ListItem>
asp:DropDownList>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns=true class="style1">
asp:GridView>

<table style="float:right; width:100px">
<tr>
<td>
<asp:LinkButton ID="LinkButtonPrevious" runat="server"
onclick="LinkButtonPrevious_Click"><<asp:LinkButton>
td>
<td>
<asp:Label ID="LabelPaging" runat="server" Text="Label">asp:Label>td>
<td>
<asp:LinkButton ID="LinkButtonNext" runat="server"
onclick="LinkButtonNext_Click">>>asp:LinkButton>
td>
tr>
table>


Step Two:

Now we need to handle the data load events , sort column change events and the paging buttons events . For that we need to write event handlers

protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
LoadData(1);
}
}

private void LoadData(int currentPage)
{
ViewState["CurrentPage"] = currentPage;
FillData(ViewState["Next"] as string, DropDownListSortColumns.SelectedValue,Convert.ToBoolean( DropDownListSortOrder.SelectedItem.Value));
}

private void FillData(string pagingInfo, string sortColumn, bool sortAscending)
{
int currentPage = Convert.ToInt32(ViewState["CurrentPage"]);
uint rowCount = 5;
string columnValue;
string nextPageString = "Paged=TRUE&p_ID={0}&p_" + sortColumn + "={1}";
string PreviousPageString = "Paged=TRUE&PagedPrev=TRUE&p_ID={0}&p_" + sortColumn + "={1}";
SPListItemCollection collection;

//first make a call to fetch the desired result set
//here is the actual call to the dal function
collection = DAL.GetTestItems(sortColumn, sortAscending, pagingInfo, rowCount);
DataTable objDataTable = collection.GetDataTable();
GridView1.DataSource = objDataTable;
GridView1.DataBind();

//now we need to identify if this is a call from next or first

if (null != collection.ListItemCollectionPosition)
{
if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
{
columnValue = SPEncode.UrlEncode( Convert.ToDateTime(collection[collection.Count - 1][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
}
else
{
columnValue = SPEncode.UrlEncode( Convert.ToString(collection[collection.Count - 1][sortColumn]));
}

nextPageString = string.Format(nextPageString, collection[collection.Count - 1].ID, columnValue);
}
else
{
nextPageString = string.Empty;
}

if (currentPage > 1)
{

if (collection.Fields[sortColumn].Type == SPFieldType.DateTime)
{
columnValue = SPEncode.UrlEncode(Convert.ToDateTime(collection[0][sortColumn]).ToUniversalTime().ToString("yyyyMMdd HH:mm:ss"));
}
else
{
columnValue =SPEncode.UrlEncode( Convert.ToString(collection[0][sortColumn]));
}

PreviousPageString = string.Format(PreviousPageString, collection[0].ID, columnValue);
}
else
{
PreviousPageString = string.Empty;
}


if (string.IsNullOrEmpty(nextPageString))
{
LinkButtonNext.Visible = false;
}
else
{
LinkButtonNext.Visible = true;
}


if (string.IsNullOrEmpty(PreviousPageString))
{
LinkButtonPrevious.Visible = false;
}
else
{
LinkButtonPrevious.Visible = true;
}


ViewState["Previous"] = PreviousPageString;
ViewState["Next"] = nextPageString;
LabelPaging.Text = ((currentPage - 1) * rowCount) + 1 + " - " + currentPage * rowCount;
}

protected void LinkButtonPrevious_Click(object sender, EventArgs e)
{
LoadData(Convert.ToInt32(ViewState["CurrentPage"]) - 1);
}

protected void LinkButtonNext_Click(object sender, EventArgs e)
{
LoadData(Convert.ToInt32(ViewState["CurrentPage"]) + 1);
}

protected void DropDownListSortColumns_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState.Remove("Previous");
ViewState.Remove("Next");
LoadData(1);
}

protected void DropDownListSortOrder_SelectedIndexChanged(object sender, EventArgs e)
{
ViewState.Remove("Previous");
ViewState.Remove("Next");
LoadData(1);
}


Step 3

Now the last step is to add the DAL class for this solution to complete

public class DAL
{

public static SPListItemCollection GetTestItems(string sortBy, bool sortAssending, string pagingInfo, uint rowLimit)
{
SPWeb objWeb = SPContext.Current.Web;
SPListItemCollection collection;
SPQuery objQuery = new SPQuery();
objQuery.RowLimit = rowLimit;
objQuery.Query = "";
objQuery.ViewFields = "";
if (!string.IsNullOrEmpty(pagingInfo))
{
SPListItemCollectionPosition position = new SPListItemCollectionPosition(pagingInfo);
objQuery.ListItemCollectionPosition = position;
}

collection = objWeb.Lists["Test"].GetItems(objQuery);
return collection;
}
}

Saturday, January 21, 2012

Use User Task WebPart to display Site Collections Tasks

Out of the box SharePoint ships with the User Tasks Web Part which allows you to display tasks assigned to the current user in the current Site.

If you want to display all Tasks in SiteCollection you can use CQWP or DataView. But there is an easy way to do that for the same user experience. The best approach is to change the value of a hidden property of the User Tasks Web Part QuerySiteCollection. This property is hidden and cannot be modified through the UI.

First export User Tasks WebPart and add property:

<QuerySiteCollection xmlns="http://schemas.microsoft.com/WebPart/v2/Aggregation">true</QuerySiteCollection>

before the </WebPart> tag

And import again. Check the result.

This will work with SharePoint 2007/SharePoint 2010.


Friday, January 20, 2012

Editing contents of a WSP (SharePoint 2010)

In Solution file WSP in SharePoint 2010, you can see the contents of the WSP by changing the file extension to CAB. You can then open the file like a ZIP file within Windows Explorer, or via WinRAR.

But you cannot modify it using one of these items:

  • Creating a new archive file within Windows Explorer – and changing to CAB or WSP extension.
  • Trying to delete or drag into an archive shown in Windows Explorer.
  • Creating a new archive with WinRAR – and/or dragging into a CAB file using WinRAR.
  • Using MAKECAB.EXE to create an archive via command line is difficult.

I found tool (IZArc) solve this problem. Steps involved to update the WSP are as follows :

  1. Rename the WSP to CAB
  2. Extract all contents to a folder – using Windows Explorer, or WinZip, WinRAR, or whatever
  3. Change the items you want.
  4. Create a new CAB file with the updated contents, using IZARC. (IZARC support many types Archived type must be CAB and include subfolders)
  5. Rename the newly created CAB to WSP
  6. Install to SharePoint


Thursday, January 19, 2012

SharePoint 2010 Sandbox Visual WebPart

When you use sandbox Visual Web Part and TemplateControl.LoadControl method is not working in a sandbox solution?
The reason is quite simple – your code in a sandbox solution actually executes in a console application – the SPUCWorkerProcess.exe. It is a console application has created an HttpContext and a Page instance, in which your web part class is also instantiated on that page. You don’t have some crucial asp.net pieces as the HostingEnvironment and the VirtualPathProvider – without these two the LoadControl method simply won’t work. And it is not that you don’t have access to the file system, even if you had, the LoadControl method still wouldn’t work because there wouldn’t be a VirtualPathProvider to provide the file to the asp.net compiler. The bad news is that the same holds for the TemplateControl.ParseControl method too.

Microsoft create template supports Visual Web Parts in the sandbox from Visual Studio 2010 you can use when download Visual Studio 2010 Sharepoint Power Tools



SharePoint 2010 Sandbox Form Post limitation

When try to use form created in sandbox solution. I found error when post data more than 128 KB. It is one limitation of more limitations in sandbox solutions.

We need to increase size to increase this limit requestlengthdiskthreshold.

Sandbox processes use SPUCHostService.exe/SPUCHostService.exe. which has extra web.config (C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\UserCode\web.config), When you updated requestlengthdiskthreshold value in this web.config problem will be solved. But this solution would not work on a hosting provider. There would be little chance they would change their UserCode settings for me.


Thursday, November 10, 2011

SharePoint Publising Page Problem MOSS Page Setting Error - Value does not fall within the expected range

When try to access publishing page or page setting getting error “Value does not fall within the expected range” . This error only happens when you copy an aspx page using SharePoint designer from one server to another severs (development server to production server). Also if you copy pages in the same server and changed alternate access mapping url.

Solutions:

  1. You cannot copy and paste the aspx page using SharePoint designer. First, export the aspx page using SharePoint designer to a physical file.
  2. Open the aspx page with notepad and search on the “mso:PublishingPageLayout”. You will notice your development portal URL is there.
    <mso:PublishingPageLayout msdt:dt=”string”>http://xxxdevelopmenturl/_catalogs/masterpage/BlankWebPartPage.aspx, Blank Web Part Page</mso:PublishingPageLayout>
  3. Replace your development URL (xxxdevelopmenturl) to the production URL or remove http://xxxdevelopmentur and save it.
  4. Open your production site with SharePoint Designer and import the modified aspx page.

If you found this error in production server open site using SharePoint Designer go to TaskPane-->Hyperlinks and edit hyperlinks of layouts like above sample:
Replace:http://xxxdevelopmenturl/_catalogs/masterpage/BlankWebPartPage.aspx
By: /_catalogs/masterpage/BlankWebPartPage.aspx

Also you can fix programmatically check url:

http://support.microsoft.com/kb/953445

Also Check this if you found your any modifications Navigation setting aren't saved.
or an error like image below:

Thursday, June 9, 2011

Failure trying to synch site for ContentDB WebApp

Problem:
Periodical errors in the event log of a SharePoint 2010 server with the following error event descriptions:
Failure trying to synch site for ContentDB WebApp . Exception message was Cannot insert duplicate key row in object 'dbo.UserMemberships' with unique index 'CX_UserMemberships_RecordId_MemberGroupId_SID'. The statement has been terminated.
Cause:

Old references to non existing content databases in the synchronization job list.

Fix:
List databases which are not synced for more than two days
stsadm -o sync -listolddatabases 2

Delete old database references from the config db
stsadm -o sync -deleteolddatabases 2