Saturday, September 27, 2008

URL Action parameters while creating an Custom Feature

While we have creating custom features for adding new menus in the Edit Context Menu (the menu that pops up when you place the mouse on a list item) you might need to specify the

You might notice the parameters like {SiteUrl},...here is the list of possible query string parameters and their description

{ItemUrl} - URL of the item being acted upon. Only work for documents in libraries.

{SiteUrl} - URL of the Web site (SPWeb).

{ListId} - GUID that represents the list.

{RecurrenceId} - Recurrence index. This token is not supported for use in the context menus of list items.

{ItemId} - Integer ID that represents the item within a list.

Note: You can also use the following parameters to get the link of current Site / Web without hardcoding it in the XML File

Windows SharePoint Services supports the following tokens with which to start a relative URL:

~site - Web site (SPWeb) relative link.

~sitecollection - site collection (SPSite) relative link.

Eg:

Friday, September 26, 2008

Problems with Special Characters in XSLT

Problem:
When you use Special Character like '&' and '<' during XSLT transformation, they are not rendered properly.
Eg. Expected Output:SharePoint data & SharePoint
Output:SharePoint data & SharePoint

Reason:
This is the normal behaviour if you consider the XSLT specification :
"Normally, the XML output method" (the default method)" escapes '&' and '<' (and some other characters)
when outputting text nodes" (i.e. when using or nodes). Resolution:
You can disable this feature by setting the 'disable-output-escaping' attribute to 'yes' in these nodes.

Solution :
In your xsl file, replace your:

<xsl:value-of select="@href">

To
<xsl:value-of select="@href" disable-output-escaping="yes">

This form template is browser-compatible, but it cannot be browser-enabled on the selected site

You receive the following message when you try to publish a browser-compatible InfoPath 2007 form template to a SharePoint server with or without Forms Services: "This form template is browser-compatible, but it cannot be browser-enabled on the selected site".

Reason:
Infopath is compatible to be able to display in browser , but SharePoint is not configured for the same.

Solution :

Configure Forms Services to allow users to browser-enable form templates.

Steps:
1. Open SharePoint 3.0 Central Administration.
2. On the Central Administration page, click on the Application Management tab.
3. On the Application Management page, under InfoPath Forms Services, click Configure InfoPath Forms Services.
4. On the Configure InfoPath Forms Services page, select the Allow users to browser-enable form templates checkbox.
5. Close the InfoPath 2007 client application.
6. Open the InfoPath form template again.
7. Try publishing the template again.

SharePoint Stsadm command line parameters

Configuring Multiple Authentication Providers for SharePoint 2007


http://blogs.msdn.com/sharepoint/archive/2006/08/16/configuring-multiple-authentication-providers-for-sharepoint-2007.aspx

Forms Based Authentication in Office SharePoint Server 2007 and Windows SharePoint Services 3.0

Here is the link for form authentication in wss 3.0/Moss 2007 that can helpful to integration in sharepoint.

http://blogs.msdn.com/sharepoint/archive/2007/12/17/forms-based-authentication-in-office-sharepoint-server-2007-and-windows-sharepoint-services-3-0-authoritative-technical-articles-published.aspx

Monday, September 22, 2008

DateTime in CAML Query

Caml query not using the time part in datetime. If your are doing a caml query and you see that your time is being ignored in datetime try this:

<Value Type=”DateTime” IncludeTimeValue=”TRUE”><Today /></Value>

You have to use IncludeTimeValue=”TRUE”.

You can use greator or equal like above and less or equal filter with AND operator in CAML above to work with date range.

If the date value is coming from your variable etc then you need to use SPUtility function and get the string required by CAML for date time variable.

DateTime CustomDate = DateTime.Now;
string strCustomDate = SPUtility.CreateISO8601DateTimeFromSystemDateTime(CustomDate);

This CAML Query below return the items based on MyDate with less than 10 days.
Basically using a Greator or Equal operatior and providing Today date - 10 days as a filter.

<Query>
<Where>
<Geq>
<FieldRef Name="MyDate" />
<Value Type="DateTime">
<Today OffsetDays="-10" />
</Value>
</Geq>
</Where>
</Query>

Saturday, September 20, 2008

SPListItem.Update() throws error Operation is not valid due to the current state of the object.

Problem:
When running SPListItem.Update commands inside SPSecurity.RunWithElevatedPrivileges block in the .net application in the sharepoint virtual directory environment then you get error: Operation is not valid due to the current state of the object.

When you can add the procedure in the SPSecurity.RunWithElevatedPrivileges block then some time also Call Stack error has occured.
When you can install your webpart or Usercontrol in the sharepoint page then this type error is not occurred.
Instead you should instantiate the SPSite or SPWeb there and call Update afterwards.

Monday, September 15, 2008

Get Public Key Token(PKT) in VS 2005 for signed assembly

Here is the easiest way to get public key token in the vs 2005.
1. In Visual Studio 2005, click Tools -> External Tools...
2. Click Add and enter the following into the different fields.
* Title: Get Public Key
* Command: C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\Bin\sn.exe
* Arguments: -Tp "$(TargetPath)"
* Uncheck all options, except Use Output window\

How to Restrict access to MOSS Web Services?

Here is the methode for restrict access to web services in the MOSS.

In order to restrict that we can add an entry in web.config file of that Site Collections web application.
Add the following block

<location path="_vti_bin">
<system.web>
<authorization>
<allow users="sps\user" />
<deny users="*" />
</authorization>
</system.web>
</location>






Thursday, September 11, 2008

Forms authentication and SharePoint Designer

The SharePoint designer always works with Windows authentication mode only. So, if you have converted your site to use forms authentication, you will not be able to open in the designer.

Hence, even if you are going to have an Internet facing site, the best practice would always be to have your default zone site with windows authentication and extend this for the Internet zone.

Steps to do this is available all around the place, check this for a start.

http://technet.microsoft.com/en-us/library/cc262668(TechNet.10).aspx

Wednesday, September 10, 2008

Maximum Versions Settings on Lists and Document Libraries


Versioning is a powerful feature of SharePoint-based lists and document libraries.

In document library and list,every time when change the item then it taks extra sizes so database size is increase.
Many organizations may wish to limit the amount of major versions that are kept.
However, this setting is determined by each individual list - but one can easily change this setting via the WSS.
Here is the programatically you can change the limit of the maximum version through the event handler or in your webpart.

public void VersionSettingLimit(string siteUrl)
{

SPSite site = new SPSite(siteUrl);
SPWeb web = site.OpenWeb();
web.AllowUnsafeUpdates = true;
SPListCollection listColl = web.Lists;
foreach (SPList list in listColl)
{
try
{
list.MajorVersionLimit = 2;
list.Update();
}
catch (Exception setVersionException)
{
}
}
}



Tuesday, September 9, 2008

Programmatically uploading an attachment to a list item in WSS3/MOSS 2007

If you need to upload a file into a SharePoint document library through code following code is helpful.

SPList list = web.Lists["MyList"];
if (list != null)
{
web.AllowUnsafeUpdates = true;
SPListItem item = list.Items.Add();
item["Title"] = "my title";

if (fileAttachment.PostedFile != null && fileAttachment.HasFile)
{
Stream fStream = fileAttachment.PostedFile.InputStream;

byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();
fStream.Dispose();

SPAttachmentCollection attachments = item.Attachments;
string fileName = Path.GetFileName(fileAttachment.PostedFile.FileName);
attachments.Add(fileName, contents);

}

item.Update();
web.AllowUnsafeUpdates = false;

}


Item does not exist. The page you selected contains an item that does not exist. It may have been deleted by another user.

I have created the Dataformwebpart and when click on the item then redirect to destination page.
I have passed the query string with "ID". So i found this error in the destination page.
This is the ComException related error occured because of the "ID" query string is confict with the sharpoint data.

Solution :
You can changed the query string with any character and after append ID string.
like ex. "EID".

Download files from splist

private string DownloadAttachment(int NodeID)
{
string Attachment = string.Empty;
try
{
using (SPSite site = new SPSite(ConfigurationManager.AppSettings["SiteUrl"]))
{
using (SPWeb web = site.OpenWeb())
{
SPList myList = web.Lists["Articles"];
SPListItem attItem = myList.GetItemById(NodeID);


if (attItem["Attachments"] != null)
{
Attachment = attItem.Attachments.UrlPrefix.ToString() + attItem.Attachments[0].ToString();


return Attachment;
}
}

}


}
catch (Exception ex)

{

return Attachment;
}
return Attachment;
}

Wednesday, September 3, 2008

Create a custom list form for a SharePoint list

  1. Open your site in SharePoint Designer.
  2. Browse to your list and open the 'NewForm.aspx' web form.
  3. Go File -> Save As... and give the form a new name such as 'NewForm2.aspx'.
  4. Hide the default List Form Web Part from the page (do not delete it!!).
    1. Right click the List Form Web Part -> Web Part Properties -> expand LayoutHidden. -> check
  5. Go Insert > SharePoint Controls -> Custom List Form.
  6. In the List or Document Library Form dialog, select the appropriate list, content type and type of form.
  7. Click OK and a new Data Form Web Part is added with controls representing all the fields from the list (in my environment all the controls show "Error Rendering Control" but this does not affect the final result).
  8. In the newly added Data Form Web Part, delete the rows containing fields not to be shown to the user (ensure that fields being removed are not required fields without default values as this would prevent the user from submitting the form).
  9. At this point, you can do other customisation such as rearranging the fields if you wish.
  10. Save the site.

To make the new form the default form:

1. Open the site in SharePoint Designer.
2. Right click the list in the Folder List and select Properties.
3. Go to the Supporting Files tab.
4. Use the Browse button to enter the path to your new Edit item form.

Note: To redirect after the form is submitted, use the following syntax in your misc links that point to the new form...

http://sps.com/Lists/YourList/myForm.aspx?Source=http://sps.com/help.htm

Tuesday, September 2, 2008

SPSecurity.RunWithElevatedPrivileges to update SPRoleAssignment of an SPListItem

When you write custom code in Sharepoint webparts, your code will run with your credentials.
Not everybody has Full Control, so when a user has only read rights, the code will throw an access denied error when the code needs access to objects that are not in the scope of the user credentials.... (example: add the username in the ReadBy properties of an item).

What you need is impersonation, run your code with the help of a user who has just enough rights to run it. Sharepoint has a built-in function to accomplish this: SPSecurity.RunWithElevatedPrivileges, it runs with the System Account User.

Some things you should know when using SPSecurity.RunWithElevatedPrivileges:

  • in the delegate function, you must build a new SPSite/SPWeb object (like SPSite siteColl = new SPSite(App.SITE_COLLECTION_URL)) and you can't use the SPContext.Current.Web, because the SPContext runs with the current context (with current user).
  • Also set the AllowUnsafeUpdates property of the site/web where you will be updating/accessing stuff to true, to be sure you don't get an error like "The security validation for this page is invalid" (see more below). If you don't do it, you code will work, but when returning from the delegate function, the error will arise..

Code sample:

I run the "Elevated code" when the button btn is clicked in a webpart:


void btn_Click(object sender, EventArgs e)
{
{
SPSecurity.RunWithElevatedPrivileges(TestSec);
}
catch (Exception ex)
{
throw ex;
}
}

public void TestSec()
{
SPSite siteColl = new SPSite(App.SITE_COLLECTION_URL);
SPWeb site = siteColl.AllWebs[App.WEB_NAME];
SPList list = site.Lists["Test"];

SPListItem testItem = list.GetItemById(1);
site.AllowUnsafeUpdates = true;
SPRoleDefinition roleDefinitionContributor = site.RoleDefinitions.GetByType(SPRoleType.Contributor);
SPRoleAssignment roleAssignment = new SPRoleAssignment("DOMAIN\\USERNAME", "", "", "");
roleAssignment.RoleDefinitionBindings.Add(roleDefinitionContributor);
////Check for permission inheritance, and break if necessary
if (!testItem.HasUniqueRoleAssignments)
{
testItem.BreakRoleInheritance(false); //pass true to copy role assignments from parent, false to start from scratch
}
testItem.RoleAssignments.Add(roleAssignment);
testItem.Update();
site.AllowUnsafeUpdates = false;
siteColl.Close();
site.Close();

}

Implementing TopNavigation across site collection

You can use Microsoft.SharePoint.Navigation.SPXmlContentMapProvider.

  • Add the following tag to your web.config under the sitemap/providers node.
    <add name="CustomXmlContentMapProvider" siteMapFile="_app_bin/myMenu.sitemap" type="Microsoft.SharePoint.Navigation.SPXmlContentMapProvider, Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral, PublicKeyToken=71e9bce111e9429c" />

  • In the same website, add a myMenu.sitemap file with the following contents -

<siteMap>
<siteMapNode title="Home Page" url="/">
<siteMapNode title="Lists" url="http://Mysite/_layouts/viewlsts.aspx?BaseType=1">
<siteMapNode title="Google" url="http://www.google.com"/>
</siteMapNode>
</siteMapNode>
</siteMap>


This file will control the actual content of the navigation.

  • Modify the master page, add the following inside a SharePoint:DelegateControl, preferably right next to topSiteMap declaration.
<asp:SiteMapDataSource ShowStartingNode="true" SiteMapProvider="CustomXmlContentMapProvider"
id="xmlSiteMap" runat="server" />

  • Modify the master page, and change the SharePoint:AspMenu, with ID=TopNavigationMenu, change it's DataSourceID from "topSiteMap" to "xmlSiteMap".

Save and Run - your navigation on that site is now controlled via the XML file.

Monday, September 1, 2008

Activate Search Index Facility in WSS 3.0

WSS 3.0 has a basic search feature that will allow users to search for content.

This is a big difference that previous WSS 2.0 versions, which required WSS to be configured to run on SQL Server 2000, using its Full-Text Indexing engine. Another important change is that WSS 3.0 will search in subsites , while the previous version of WSS only searched in the current site.

  • Finds information of any type, stored in the current site, or a subsite.
  • Provides free-text searching in documents, files, and all list content.

The objects indexed by Full-Text Indexing are these:

  • List items: Such as individual names in a Contact list.
  • Documents: Documents of these types: .doc, .xls, .ppt, .txt, and .html.
  • Lists: Such as Announcements, and Events.

Activate Search Indexing in WSS:

  1. Log on as an administrator,
  2. Start SharePoint's Central Administrative tool. Switch to the Operations page, then click Services on Server.

3. Make sure that the correct Server is selected, and then start Windows SharePoint Services Search service, if it's not already started. Fill in this information in the Web form: When you create a new Web application, make sure to select a search server.

  1. When the process is done, all documents and lists are also indexed and ready to be searched within five minutes. Open any WSS team site, and use the search field at the top-right corner of the page. Type a text string that you know exists in any of the lists or inside any documents stored in this team site.

Note :

If WSS was installed using SQL Express, the Search service may not be listed. If this is the case, select All on the View menu on the toolbar.

  1. Service Account: Enter the service account and its password for the search service; be sure to include the domain name
  2. Content Access Account: Enter the default user account to be used by the search service when searching content sources. You can later configure other user accounts for specific content sources.
  3. Search Database: Enter the SQL server name, plus the Database Name for the index. Use the default database and name, if you don't have a good reason not to.
  4. Indexing Schedule: Enter how often the index process will run. The default is every five minutes.
  5. Click OK to save and close the page.