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.