Showing posts with label SharePoint 2010. Show all posts
Showing posts with label SharePoint 2010. Show all posts

Tuesday, April 16, 2013

An exception of type Microsoft.SharePoint.Upgrade.SPUpgradeException was thrown.

I faced the following error when to run sharepoint 2010 configuration wizard in my windows 8 machine:

An exception of type Microsoft.SharePoint.Upgrade.SPUpgradeException was thrown. Additional exception information: Failed to call GetTypes on assembly Microsoft.Office.Server.Search, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c. Could not load file or assembly 'System.Web.DataVisualization, Version=3.5.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The system cannot find the file specified.

I found problem I am not installed Chart Control in my machine. Problem is solved after download and installed. Chart control can be downloaded from the following location:
http://go.microsoft.com/fwlink/?LinkID=122517

Tuesday, May 8, 2012

SharePoint Software Factory 2010

I found a free Visual Studio Extension helping SharePoint newbies, as well as experienced developers to create, manage and deploy SharePoint solutions without having to know every tiny XML and C# secret.

Key Features:
  • Get started with professional SharePoint development in less than 5 mins!
  • Use powerful wizards to create all important SharePoint artifacts
  • Fully integrated in Visual Studio
  • Refactoring of artifacts (i.e. Content Types)
  • Fully automated build system creates web solutions packages (“WSP”s) and deployment files 
  • Integrated Code quality checks in “Release” build (additional installs required)
  • All projects are self maintained, meaning that there is no dependency to having SPSF installed on the machine, when you just want to build, or continue development without SPSF
  • Standard VS2010 item templates for SharePoint development can be used together with SPSF projects, though the coding conventions have to be applied by the developers for these items
  • Extensive Help integrated in Visual Studio
  • Supports new SharePoint Visual Studio application structure but also “old” best-practice SharePoint Hive structure
  • Supports SharePoint 2007/2010 and Visual Studio 2008/2010
  • Upgrade existing SharePoint projects.
You can check this extension from link:
http://spsf.codeplex.com/

Tuesday, April 24, 2012

Error with SharePoint 2010 TaxonomyPicker.ascx

I found error in event log with machine has a SharePoint 2010 error is:


Load control template file /_controltemplates/TaxonomyPicker.ascx failed: Could not load type  'Microsoft.SharePoint.Portal.WebControls.TaxonomyPicker' from assembly 'Microsoft.SharePoint.Portal, Version=14.0.0.0, Culture=neutral,  PublicKeyToken=71e9bce111e9429c'.


Solution:
  1. open file /14/ControlTemplates/TaxonomyPicker.ascx and replace , and replace with a comma. (decoded value)
  2.  After updating service pack this solution not applicable SharePoint used another control and the above error still appear. You need to remove this file to unknown extension like TaxonomyPicker.ascx_  so that we do not try to recompile it each time the AppPool is started. T


Sunday, April 22, 2012

Configure Forms Based Authentication (FBA) with SharePoint 2010

SharePoint 2010 FBA, is different in configuration than WSS 3.0 or MOSS 2007. It needs create web applications Claims based Authentication.  
Classic Mode Authentication: It is only integrated windows authentication.
Claims Based Authentication: It is based Windows Identity Foundation. It enables authentication for any type of authentication, It is also provides the capability to have multiple authentication in a single URL.

You can convert a web application from Classic Mode Authentication to Claims Based Authentication. However, that can only be done using PowerShell commands:
http://blogs.technet.com/b/mahesm/archive/2010/04/07/configure-forms-based-authentication-fba-with-sharepoint-2010.aspx

   
    $App = get-spwebapplication “URL”
    $app.useclaimsauthentication = “True”
    $app.Update()

Here is the steps of configuring FBA. I am assume here you have already created a membership and role Manager:
  1. A. Creating web application using Central administration
    • Open Central Administration Console.
    • Click on Manage Web application Under Application Management.
    • Click on new on the Ribbon.
    • Chose Claims based Authentication From the top of the page.
    • Choose the port no for the web application.
    • Click on Enable Forms Based Authentication (FBA) Under Claims Authentication Types. Windows Authentication is enabled by default and if you dont need windows authentication then you need to remove the check the box.
    • Add the Membership Provider & Role Manager Name. I am using Membership Provider as "SQL-MembershipProvider" and Role Manager as "SQL-RoleManager". These names are case sensitive. 
  2. Modify the web.config file for Membership Provider and Role Manager:
    We need to modify 3 different web.config files for FBA to work. Web.config of FBA Web application, web.config of Central Administration Site & Web.config of STS. 
    • A. Modify web.config of FBA web application:
      Add connection string:
    • <connectionStrings>
      <add name="SQLConnectionString" connectionString="data source=SQL;Integrated Security=SSPI;Initial Catalog=SQL-Auth" />
      </connectionStrings>

      Add membership Provider and Role Manager:
      <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
      <providers>
      <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
      </roleManager>
      <membership defaultProvider="i">
      <providers>
      <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
      </membership>
      </system.web>

    • Modify web.config of STS. You can locate the STS web.config from %programfiles%\common files\Microsoft Shared\web server extensions\14\WebServices\SecurityToken:
      Add connection string:
    • <connectionStrings>
      <add name="SQLConnectionString" connectionString="data source=SQL;Integrated Security=SSPI;Initial Catalog=SQL-Auth" />
      </connectionStrings>
      Add membership Provider and Role Manager:
      <roleManager defaultProvider="c" enabled="true" cacheRolesInCookie="false">
      <providers>
      <add name="c" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthRoleProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
      </roleManager>
      <membership defaultProvider="i">
      <providers>
      <add name="i" type="Microsoft.SharePoint.Administration.Claims.SPClaimsAuthMembershipProvider, Microsoft.SharePoint, Version=14.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />
      <add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
    • Modify web.config of the Central Administration web application:
      This modification is optional. You need it only if you want give Forms User authentication through central administration.
    • <connectionStrings>
      <add name="SQLConnectionString" connectionString="data source=SQL;Integrated Security=SSPI;Initial Catalog=SQL-Auth" />
      </connectionStrings>
      Add membership Provider and Role Manager:
      <roleManager defaultProvider="AspNetWindowsTokenRoleProvider" enabled="true" cacheRolesInCookie="false">
      <providers>
      <add connectionStringName="SQLConnectionString" applicationName="/" description="Stores and retrieves roles from SQL Server" name="SQL-RoleManager" type="System.Web.Security.SqlRoleProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
      </roleManager>
      <membership defaultProvider="SQL-MembershipProvider">
      <providers>
      <add connectionStringName="SQLConnectionString" passwordAttemptWindow="5" enablePasswordRetrieval="false" enablePasswordReset="false" requiresQuestionAndAnswer="true" applicationName="/" requiresUniqueEmail="true" passwordFormat="Hashed" description="Stores and Retrieves membership data from SQL Server" name="SQL-MembershipProvider" type="System.Web.Security.SqlMembershipProvider, System.Web, Version=2.0.3600.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" />
      </providers>
      </membership>\
    Notes:
    • You should set default providers:
      • Default providers are SPClaimsAuthRoleProvider and SPClaimsAuthMembershipProvider for FBA Site and STS.
      • Default providers are AspNetWindowsTokenRoleProvider and SQL-MembershipProvider for Central Administrator.
    •  If you failed to log-in after configuration check machine key in your web site and STS site are same, else check database connection string.
    • If you want to seaech for FBA users using wildcard, add the Membership and Role providers into the PeoplePickerWildcards section of the web.config:

    • <configuration>
          …
          <SharePoint>
              …
              <PeoplePickerWildcards>
                <clear />
                <add key="SQL-RoleManager" value="%" />
                <add key="SQL-MembershipProvider" value="%" />
              </PeoplePickerWildcards>
              …
          </SharePoint>
          …
      </configuration>
  1. Give permissions to users in SQL database:
    • Access Central Administration console and click on manage web applications under Application Management.
    • Select the web application and click on user Policy on ribbon.
    • Click on Add user and select Default Zone.
    • Now type the user name, add the user to the web application by defining appropriate permission.

Friday, April 20, 2012

Update vs. SystemUpdate for SharePoint List Item

When tried to Move List items from old Site to New Site. I am not only want to create items but also want to keep information of Created Date, Modified Date, Created User, or Modified User.

 I found item.Update() is not useful. It is not only changes that are made to the list item. It also updates the ModifiedBy, ModifiedOn, or version fields as per the current logged in user and current server time.

I used item.SystemUpdate() instead of item.Update(). This will help you in updating only those fields which are specified within your code blocks. It is allow me modify properties modified date and created user.

Monday, March 5, 2012

SharePoint Customization

When I tried to build site using sandbox, I found many restrictions. The better solution for most of these problems do a workarounds using out of the box controls and Web parts of the SharePoint.

I found site give us good solutions for building some modules with small customization of out of the box SharePoint Web parts and Controls with css and javascript functions:
http://usermanagedsolutions.com/SharePoint-User-Toolkit/default.aspx
It Contains solution for SharePoint 2007 and SharePoint 2010 Sample of them:
  • Color-Coding-Calendar-List:
    Display calendar with color depend on category of item in List
  • Pie and Bar Charts (Google Connector)
    Display chart using calendar chart depend on values in List
  • Easy-Tabs
    When added to a Web Part zone, the Easy Tabs automatically generate a tabbed interface, with one tab per Web Part present in the zone.
  • Cross-Site-List-Snapshot
    This script allows you to display in a SharePoint page a view taken from another site or site collection.
  • Tasks-Lists-Rollup:
    roll-up Web Part that displays items collected from multiple lists of the same type
  • Bookmarklet-Expand-Collapse-Web-PartsOn a SharePoint page:
    adds an expand/collapse button to each Web Part, next to the title.
  • Page-Redirect:
    This script allows you to redirect your users to another Web page (specified in the Target location), when they try accessing the current page.
  • Image-Rotator:
    The image rotator allows you to display on your page a picture randomly selected from a SharePoint picture library.

    You can use solutions and add more enhancement of it.







Create Poll for Sandbox or Office 365

I want to create Poll in Shared Environment that allow to create only components using Sandbox.
Sandbox has many limitation affect building this module:
  1. Cannot run component with elevated privilege or impersonate user. (Poll Component for anonymous users)
  2. Sandbox cannot serialize cookie only can read a cookie.

For these reason cannot build solution using sandbox to build a poll. Only Customize predefined controls using SharePoint Designer to build a poll.

Steps:

  1. Create 2 Lists:
    • Poll List with Fields Question(Text), Answer1(Text), Answer2(Text), Answer3(Text), Active(Yes/No)
    • Poll Result QuestionId, Answer1Count(Number Default 0), Answer2Count(Number Default 0), Answer3Count(Number Default 0)
  2. Create Workflow When you add a Poll Item in List It will add item in Poll Result.
  3. Give Add Permission of anonymous user in Poll Result.
  4. Create Active Workflow to allow only one active poll. If We activated Poll, Deactivate others.
  5. Create DataView For Displaying a Poll:
  • DataSource read the 2 lists read active poll and its results.
  • XSLT contains 2 View:
    1. Show Poll and allow user to vote. Appears if user didn't respond on this poll.
    This contains form question as title and questions as radio buttons in Forms and button for respond.
    When user click button. It will call client object model to increase selected answer count. and set cookie using JavaScript using jquery that he answer this question.
    you can use captcha using javascript:
    http://sharepointserver-2007.blogspot.com/2012/01/capatcha-using-javascript.html
    2. Show Results display Poll Result. . Appears if user respond on this poll.
    Validation that user respond this answer check if active poll Id exists in cookie that set in previous step. You can build graph for displaying results using div and style sheets.

This is simple Poll for sandbox or Office 365 you can add more enhancement.

Saturday, March 3, 2012

SharePoint 2010 Sandboxed limitation

SharePoint 2010 define a way of packaging called sandbox because old way of packaging is not suitable for shared environment. If there is a problem of package it will effect the environment. But new packaging technique will effect only sandbox's modules was deployed in this site collection.
Components of the sandbox:
  • User Code Service (SPUCHostService.exe). This is responsible for creating the sandbox worker processes that execute individual sandboxed solutions and for allocating requests to these processes.
  • Sandbox Worker Process (SPUCWorkerProcess.exe). This is the process in which any custom code in your sandboxed solution executes.
  • Sandbox Worker Process Proxy (SPUCWorkerProcessProxy.exe). This provides a full-trust environment that hosts the SharePoint API. This enables sandboxed solutions to make calls into the subset of the SharePoint object model that is accessible to sandboxed solutions.

But Sandbox has many limitations:

  1. You can use most of SharePoint API but you can only use current site collection. All you information must be saved in current site.
  2. No Security Elevation (You cannot impersonate). You can only run with current logged in user. You must give a user actual permission to access SharePoint item.
  3. No Email Support (You cannot send email). Only workaround start workflow with activity to send the mail but take care of needed permission to start workflow.
  4. You cannot use SharePoint Web Controls.(You can use asp net controls instead of it).
  5. You cannot do WebRequest connections,(http, web services, wcf, and etc). To access those use through javascript or silverlight.
  6. No GAC Deployment (Sandbox solutions are not stored in File System, they are stored in the database) C:\ProgramData\Microsoft\SharePoint\UCCache temporary for global assembly cache.
  7. Enterprise features (Search, BCS, etc.) are not allowed.
  8. CAS does not allow you to access database. All data storage in SharePoint List.
  9. CAS does not allow you access IO:
    • Global folders like “_layout” & “resources” are not authorized. To use resource file embed it in the dlls.
    • No Visual Webparts
    • No Custom workflow
    • Allow features depend on physical files are not allowed.
  10. No Threading.
  11. No P-Invoke
  12. Sandbox work in separate domain and initialize new page serialize some information to communicate with w3wp.exe.
    Serialized Information which can use in sandbox:
    • ID's of Form, Web Part Manager, Zone, Toolpane
    • Web Part properties
    • Options and properties of the Web Part and zone, such as chrome, zone customization, width, height...
    • View state
    • Control state
    • Server Variables (except APPL_PHYSICAL_PATH and PATH_TRANSLATED)
    • Request Headers
    • Input Stream
    • Current context (List Id, Item Id)
    • Query String

    Serialized Information which can use in sandbox:
    • The Cache object
    • Cookie
    • The ScriptManager or callback
    • The ClientScriptManager
    • The HttpRequest.Files collection (work with limited size to 128KB
    • The Master Page
    • Embedded resources (these are requested by the WebResource.axd and they cannot resolve the Sandboxed assemblies from the W3WP.exe process)
    • You cannot use redirection (Response.Redirect, Server.Transfer or SPUtility.Redirect)
    • You cannot export a Sandboxed Web Part (it will just export the SPUserCodeWebPart)
    • Also you cannot access page object (you cannot control hide or show controls in page like HideCustomAction and CustomActionGroup)
  13. PropertyBags of SharePoint Object model are not accessible
  14. ASP.NET 2.0 web controls are not fully working (those that are using “WebResource.axd” for internal binaries resources, as .axd extension is not allowed). Instead of embed them upload to SharePoint and refer to them as external resources.
  15. Also Sandbox limited number of resources used and deactivate sandbox solution if they reached limited number of resources. limitation depend in number of point limitation by administrator and calculated as this table:


    Metric Name

    Description

    Units

    Resources Per Point

    Hard Limit

    AbnormalProcessTerminationCount

    Process gets abnormally terminated

    Count

    1

    1

    CPUExecutionTime

    CPU exception time

    Seconds

    200

    60

    CriticalExceptionCount

    Critical exception fired

    Number

    10

    3

    InvocationCount

    Number of times solution


    has been invoked

    Count

    N/A

    N/A

    PercentProcessorTime

    Note: # of cores not factored in

    Percentage Units of Overall Processor Consumed

    85

    100

    ProcessCPUCycles



    CPU Cycles

    1E+11

    1E+11

    ProcessHandleCount



    Windows Handles

    10,000

    5,000

    ProcessIOBytes

    (Hard Limit Only) Bytes written


    to IO

    Bytes

    1E+07

    1E+08

    ProcessThreadCount

    Number of Threads


    in Overall Process

    Threads

    10,000

    200

    ProcessVirtualBytes

    (Hard Limit Only)


    Memory consumed

    Bytes

    1E+09

    4E+09

    SharePointDatabaseQueryCount

    SharePoint DB Queries Invoked

    Number

    400

    100

    SharePointDatabaseQueryTime

    Amount of time spent waiting


    for a query to be performed

    Seconds

    20

    60

    UnhandledExceptionCount

    Unhanded Exceptions



    50

    3

    UnresponsiveprocessCount

    We have to kill the process because it has become unresponsive

    Number

    2

    1

    For more details check URL:
    http://msn.microsoft.com/en-us/library/ff798382.aspx


Sunday, February 26, 2012

Managed account is duplicate

When updated farm account with local user, I found account is duplicated.
When tried to remove this user found error:

Item has already been added. Key in dictionary.. How do I clean up service account?


I solved solution by using powershell:
Remove-SPManagedAccount -Identity DOMAIN\ServiceAcct



Register new managed account local user

When tried to register local account user I faced the following error:
The specified user 'accountname' is a local account. Local accounts should only be used in stand alone mode.
I found solution using powershell:
type $cred = Get-Credential
When prompted enter an account and password (here you can type in a local account)
type New-SPManagedAccount -Credential $cred
After finished the account is added.

Sunday, January 29, 2012

Sharepoint Designer “checked out” problem

Sometimes in Sharepoint Designer showing “checked out” even though they were not!

To solve this problem, You need to clear a local web cache. This Works in SharePoint Designer 2007 and SharePoint Designer 2010.

Areas to clear:
  • %APPDATA%\Microsoft\Web Server Extensions\Cache
  • %USERPROFILE%\AppData\Local\Microsoft\WebsiteCache\
In WInXP
  • %USERPROFILE%\Local Settings\Application Data\Microsoft\WebsiteCache

Capatcha using Javascript

Most of the websites use the technique of captcha for validation / verification purpose whenever someone tries accomplish membership or want to submit a piece of information. The generation of captcha can be done in various ways. We can use server side scripting or even we can use client side scripting.
I am need to host SharePoint 2010 in shared environment and does not allow me to deploy server side control. Then tha best way to use captcha is javascript.

Here is a sample code of capatcha using javascript:

<html>
<head>
<title>Captcha</title>

<script type="text/javascript">

//Created / Generates the captcha function
function DrawCaptcha()
{
var a = Math.ceil(Math.random() * 10)+ '';
var b = Math.ceil(Math.random() * 10)+ '';
var c = Math.ceil(Math.random() * 10)+ '';
var d = Math.ceil(Math.random() * 10)+ '';
var e = Math.ceil(Math.random() * 10)+ '';
var f = Math.ceil(Math.random() * 10)+ '';
var g = Math.ceil(Math.random() * 10)+ '';
var code = a + ' ' + b + ' ' + ' ' + c + ' ' + d + ' ' + e + ' '+ f + ' ' + g;
document.getElementById("txtCaptcha").value = code
}

// Validate the Entered input aganist the generated security code function
function ValidCaptcha(){
var str1 = removeSpaces(document.getElementById('txtCaptcha').value);
var str2 = removeSpaces(document.getElementById('txtInput').value);
if (str1 == str2) return true;
return false;

}

// Remove the spaces from the entered and generated code
function removeSpaces(string)
{
return string.split(' ').join('');
}


</script>



</head>
<body onload="DrawCaptcha();">
<table>
<tr>
<td>
Welcome To Captcha<br />
</td>
</tr>
<tr>
<td>
<input type="text" id="txtCaptcha"
style="background-image:url(1.jpg); text-align:center; border:none;
font-weight:bold; font-family:Modern" />
<input type="button" id="btnrefresh" value="Refresh" onclick="DrawCaptcha();" />
</td>
</tr>
<tr>
<td>
<input type="text" id="txtInput"/>
</td>
</tr>
<tr>
<td>
<input id="Button1" type="button" value="Check" onclick="alert(ValidCaptcha());"/>
</td>
</tr>
</table>
</body>
</html>

This is simple but you can complicate it to eliminate cracking.

SharePoint Designer 2010 Workflow does not Start Automatically, when an item is created or modified

I Create a new "List Workflow" through Sharepoint Designer 2010 and set the workflow setting with Start workflow automatically when an item is create or modified.




Then save and publish the workflow. Now goto the list and create or edit the items, the attached workflow not invoke.

I found my problem . I need to login into another non system account user.


Thursday, January 26, 2012

Use email in SharePoint 2010 Sandbox

In SharePoint 2010 Sandbox. In Sandbox Microsoft.SharePoint.Utilitiesis not avaliable. When tried to use System.Net.Mail methods available to us. SmtpClient constructor give me error.
I found another way using SharePoint Designer workflow. You can trigger a workflow to run programmatically and also supply information to the workflow and set the initiation values. Here's the code to start a workflow:


///
/// Method to handle starting the appropriate Workflow as specified by the Site Collection Workflow Name property
///

private void StartWorkflow()
{
SPWorkflowAssociation wfa = SPContext.Current.Web.WorkflowAssociations.GetAssociationByName(this.SiteCollectionWorkflowName, CultureInfo.InvariantCulture);
wfa.AssociationData = this.GetWorkflowInitiationData();
SPContext.Current.Site.WorkflowManager.StartWorkflow(null, wfa, this.GetWorkflowInitiationData(), SPWorkflowRunOptions.Asynchronous);
}


///
/// Method to construct the Workflow Initiation/Association Data
///

/// A string containing the XML schema and values necessary for the Association Data
private String GetWorkflowInitiationData()
{
String schema = "http://www.w3.org/2001/XMLSchema\" " +
"xmlns:dms=\"http://schemas.microsoft.com/office/2009/documentManagement/types\" " +
"xmlns:dfs=\"http://schemas.microsoft.com/office/infopath/2003/dataFormSolution\" " +
"xmlns:q=\"http://schemas.microsoft.com/office/infopath/2009/WSSList/queryFields\" " +
"xmlns:d=\"http://schemas.microsoft.com/office/infopath/2009/WSSList/dataFields\" " +
"xmlns:ma=\"http://schemas.microsoft.com/office/2009/metadata/properties/metaAttributes\" " +
"xmlns:pc=\"http://schemas.microsoft.com/office/infopath/2007/PartnerControls\" " +
"xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\">" +
"{0}" +
"
";



StringBuilder sb = new StringBuilder();
sb.AppendFormat("{0}", this.SendToEmailAddress);
sb.AppendFormat("{0}", this._subject.Text);
sb.AppendFormat("{0}", this._comments.Text);
sb.AppendFormat("{0}", this._email.Text);
sb.AppendFormat("{0}", this.AutoResponseSubject);
sb.AppendFormat("{0}", this.AutoResponseText);
return String.Format(schema, sb.ToString());
}




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;
}
}

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