add

Showing posts with label Sharepoint. Show all posts
Showing posts with label Sharepoint. Show all posts

Sunday, June 14, 2009

Structure of Sharepoint Site and Navigation

SharePoint sites are always part of a site collection, which has a single parent or top - level site .

The top - level site can have any number of child sites, grandchildren, and so on, and each site will have one or more pages in a page library .

The site structure is therefore based on pages(the leaf nodes, which are viewable by end users) and sites (the containers, each of which has at least one default page to display).

Sunday, June 7, 2009

How to use RunWithElevatedPrivileges in Sharepoint

The SPSecurity class provides a static method named RunWithElevatedPrivileges that enables code to execute as system code running under the identity of SHAREPOINT\system. This allows code to run in an escalated security context to perform actions as the system.

This method should be used with care and should not expose direct access to system resources, but rather should be used when you need to perform actions on behalf of the system. The method is simple. You can either create a delegate to a public void method or simply write code within an inline delegate.

The signature looks like the following:

SPSecurity.RunWithElevatedPrivileges(delegate()
{
// Code runs as the "SharePoint\system" user
});


Note that :
Code running with the escalated privilege should use a new SPSite object for code running as the system and use the SPContext.Current property to access the actual calling user’s identity.

To modify WSS content under the System credentials, you need to create a new SPSite site collection that generates a new security context for objects referenced from the site, as in the following example. You cannot switch the security context of the SPSite once it has been created, but must instead create a new SPSite reference to switch user contexts. The following code uses the system credentials to add a list item using the profile data of the current Web user:

SPSecurity.RunWithElevatedPrivileges(
delegate() {
using (SPSite site = new SPSite(web.Site.ID)) {
using (SPWeb web2 = site.OpenWeb()) {
SPList theList = web2.Lists["visitors"];
SPListItem record = theList.Items.Add();
record["User"] = SPContext.Current.Web.CurrentUser;
record.Update();
}
}
);

How to add a SPGroup to a Site Collection- Sharepoint

Groups cannot directly be added to a site-they must be added to the site collection.
If you try to add a group to the site’s Groups collection, you get an exception stating, “You cannot add a group directly to the Groups collection. You can add a group to the SiteGroups collection.”

This situation occurs because the SPGroup is always created at the Site Collection level and assigned to the site. The following code is valid and adds the LitwareSecurityGroup to the site collection groups.

// Adds a new group to the site collection groups:
site.SiteGroups.Add("LitwareSecurityGroup", site.CurrentUser,site.CurrentUser, "A group to manage Litware Security");

However, this still does not associate the group with our site, nor would it be useful within the site without any permissions. To add the group to the site, create a new SPRoleAssignment by associating an SPRoleDefinition with the SPGroup, and then add that role assignment to the site, as in the following code sample:


SPGroup secGroup = site.SiteGroups["LitwareSecurityGroup"];
SPRoleAssignment roleAssignment = new SPRoleAssignment(secGroup);
SPRoleDefinition roleDefinition = site.RoleDefinitions["Full Control"];
roleAssignment.RoleDefinitionBindings.Add(roleDefinition);
site.RoleAssignments.Add(roleAssignment);

How to get list of SPGroups in Sharepoint Site Collection

Sharepoint Gropus (or SPGroups) are never created in the context of the site-they are always created in the context of the site collection and assigned to a site.

We can get list of groups of a site by suing site.Groups


SPSite siteCollection = new SPSite("http://localhost/litware/sales/");
SPWeb site = siteCollection.OpenWeb();

foreach(SPGroup group in site.Groups){
Console.WriteLine(group.Name);
}

Thursday, May 21, 2009

Difference between .Dwp and .Webpart

In the development of webpart, we have encountered two types of files.

1. .Dwp and 2. .Webpart.

As you may know, they are both files used for describing where the code is for a web part.

The difference is .dwp was the file extension used in version 2 of SharePoint and .webpart is a new extension used in version 3.

Inside the files, the schemas are different and it is indicated as such by the version number on the xmlns attribute.

The main difference is that all properties passed to the web part are specified with a property element and a name attribute in version 3. Version 2 uses different element names for everything.

Wednesday, May 20, 2009

Various properties of PeopleEditor:

Various properties of PeopleEditor:

The PeopleEditor control has a number of properties that allow you to configure it. In the next section, we will discuss the properties that we think are most important.

The PlaceButtonsUnderEntityEditor property decides the location of the Names and Browse buttons of the people picker. If you set it to true, the buttons are placed at the bottom right corner of the account name text box, otherwise to the right of it.

The AllowEmpty property lets you define if the user is required to fill in a value in the people picker.

The SelectionSet property allows you to define the set of users and groups the people picker can choose from. This set can consist of users, Active Directory distribution lists, Active Directory security groups, and SharePoint groups.
The MultiSelect property lets you define if a user is allowed to specify multiple user accounts. The next code fragment shows how to add a people picker to a web part and how to configure it:

objEditor = new PeopleEditor();
objEditor.AutoPostBack = true;
objEditor.PlaceButtonsUnderEntityEditor = true;
objEditor.ID = "pplEditor";
objEditor.AllowEmpty = false;
objEditor.SelectionSet = "User,SecGroup,SPGroup";
objEditor.MultiSelect = false;
Controls.Add(objEditor);

You can retrieve the values selected in the people picker by looping through the ResolvedEntities collection of the PeopleEditor object.

How to get all the values of PeopleEditor in Sharepoint

If we need to acess oll the values in the PeopleEditor control, we can iterate through the entities present in PeopleEditor:

Suppose we have a PeopleEditor control PE1 so the code will be :


ArrayList entities = PE1.ResolvedEntities;
foreach (object entity in entities)
{
PickerEntity pickerEntity = (PickerEntity)entity;
string accountName = pickerEntity.Key;
string displayName = pickerEntity.DisplayText;
// pickerEntity.EntityDate[] has other values like first name, last name, etc you might be interested in.
}

How to check if PeopleEditor is blank ?

Sometimes, we need to check whether Sharepoint PeopleEditor is blank or not. We can do that very easily by accessing Length property of that control.

Suppose we have a PeopleEditor control with Id PE1 then check for the lenght like this:

Int32 intLength = PE1.CommaSeparatedAccounts.Length;

Then put your own business logic as :

if (intLength == 0)
{.... }

How to set current user in the PeopleEditor via Code

The following code sample will set the currently logged on user to a PeopleEditor:

using (SPWeb web = SPContext.Current.Web)
{
SPUser user = web.CurrentUser;
PickerEntity entity = new PickerEntity();
entity.Key = user.LoginName.ToString();
System.Collections.ArrayList entityArrayList = new System.Collections.ArrayList();
entityArrayList.Add(entity);
PeopleEditorControl.UpdateEntities(entityArrayList);
}

How to check whether a List is a Document Library?

Many times, we face a situation where we iterate through list collection. Now if we need to check whether a list is a SPDocumentLibrary or not, we can check it in very simple manner:

Suppose we need to display list of document libraries present in a site in a dropdown control named 'lstTargetLibrary', we will iterate through list collection and check for List type:


SPWeb site = SPContext.Current.Web;
foreach (SPList list in site.Lists) {
if (list is SPDocumentLibrary && !list.Hidden) {
SPDocumentLibrary docLib = (SPDocumentLibrary)list;

lstTargetLibrary.Items.Add(
new ListItem(docLib.Title, docLib.ID.ToString()));
}
}

How to Upload a File to a SharePoint Site from a Local Folder

This code sample will show how to upload a file from your local pc to Sharepoint site using object mode:

1. Create a project and import namespaces :

using System.IO;
using Microsoft.SharePoint;


2. The UploadFile funtion code:

public void UploadFile(string srcUrl, string destUrl)
{
if (! File.Exists(srcUrl))
{
throw new ArgumentException(String.Format("{0} does not exist",
srcUrl), "srcUrl");
}

SPWeb site = new SPSite(destUrl).OpenWeb();

FileStream fStream = File.OpenRead(srcUrl);
byte[] contents = new byte[fStream.Length];
fStream.Read(contents, 0, (int)fStream.Length);
fStream.Close();

EnsureParentFolder(site, destUrl);
site.Files.Add(destUrl, contents);
}


The UploadFile method accepts two parameters. The srcUrl parameter specifies the path of the source location in the file system of the local computer, and the destUrl parameter specifies the absolute URL of the destination. A System.IO.FileStream object is used to read the source file into a byte array for use with the Add method of the SPFileCollection class.

To upload a file from a local folder on the same server that is running Windows SharePoint Services, you can use a System.IO.FileStream object instead. In this case, add a using directive for the System.IO namespace, in addition to directives for System and Microsoft.SharePoint. The following example uses the Click event handler to call an UploadFile method, which in turn calls the previously described EnsureParentFolder method.

How to delete a List from Sharepoint ?

This small code snippets will demonstrate how to delete a SPList from a sharepoint site.

To delete a list, you must specify the GUID of the list as the parameter for the Delete method. Use the ID property of the SPList class to find the GUID.

SPWeb mySite = SPContext.Current.Web;
SPListCollection lists = mySite.Lists;

SPList list = lists[ListName];
System.Guid listGuid = list.ID;

lists.Delete(listGuid);

Tuesday, May 19, 2009

Difference between Update and SystemUpdate in Sharepoint

We all know that whenever we add a list item or do some modification, we update the list. Here we have two options:

1. List.Update() and 2. List.SystemUpdate()

The main difference betwwen two is that,

List.Update() creates automatically new version of list item as Update method is called.


List.SystemUpdate() avoids SharePoint 2007 to change modified date and modifier fields. Argument false tells that no new versions are expected.

SystemUpdate takes an boolean argument that set whether new version need to be created or not.

Example using SystemUpdate() :

SPList list = web.Lists["myList"];
SPListItem item = list.Items[0];
item["myField"] = "my value";

item.SystemUpdate(false);
list.Update();

Microsoft Office Sharepoint Authentication Explained

In order for people to use a MOSS web application, the web application must validate the person’s identity. This process is known as authentication. MOSS is not a directory service and the actual authentication process is handled by IIS, not MOSS.

However, MOSS is responsible for authorization to MOSS sites and content after a user successfully authenticates. Authentication happens like this: A user points their browser at a MOSS site and IIS performs the user validation using the authentication method that is configured for the environment.

If the user authentication is successful, then MOSS renders the web pages based on the access level of the user. If authentication fails, the user is denied access to the MOSS site. Authentication methods determine which type of identity directory can be used and how users are authenticated by IIS. MOSS supports three methods of authentication: Windows, ASP.NET Forms, and Web Single Sign-On.

Windows Authentication is the most common authentication type used in MOSS intranet deployments because it uses Active Directory to validate users. When Windows Authentication is configured, IIS uses the Windows authentication protocol that is configured in IIS. NTLM, Kerberos, certificates, basic, and digest protocols are supported. When Windows authentication is configured, the security policies which are applied to the user accounts are configured within Active Directory. For example, account expiration policies, password complexity policies, and password history policies are all defined in Active Directory and not in MOSS. When a user attempts to authenticate to a MOSS web application using Windows authentication, IIS validates the user against NTFS and Active Directory, and once the validation occurs the user is authenticated and the access levels of that user are then applied by MOSS.




Anonymous access is considered to be a Windows authentication method because it associates unknown users with an anonymous user account (IUSR_MACHINENAME). Anonymous access is commonly used in internet Web sites and in situations where web site users will not have their own user accounts. Since exposing content to unknown users is risky, this configuration is disabled by default. In order to configure anonymous access to a MOSS web application, anonymous access must be enabled in IIS, enabled in the MOSS web application, and the anonymous user account must be provisioned throughout the MOSS Web application. Even when anonymous access is configured, there are still several limitations compared to a Windows user. By default, anonymous users are only allowed to read, and they are unable to edit, update, or delete content. Additionally, anonymous users are not able to utilize personalization features such as Microsoft Office integration, check-in/check-out and email alerts. The ASP.NET Forms authentication method is commonly used in situations where a custom authentication provider is required. In other words, where a custom LDAP, SQL Server, or other type of identity repository will be storing user account information. This is common in extranet environments, such as partner collaboration sites, where it is not practical to create Active Directory user accounts for users or a different type of directory is required.

The Web Single Sign-On authentication method is used in environments that have federated identity systems or single sign-on systems configured. In this type of environment, an independent identity management system integrates user identities across heterogeneous directories and provides the user validation for IIS. Some examples of identity management systems with single sign-on capability include Microsoft Identity Information Server with Active Directory Federation Services, Oracle Identity Management with Single Sign-On and Web Access Control, Sun Microsystems Java System Identity Manager, and Netegrity SiteMinder.

Large enterprises often implement federated identity models to ease the administration of user provisioning and de-provisioning for systems that span across companies. Single Sign-On systems are used to consolidate user accounts across heterogeneous systems, allowing the end user to authenticate to systems with one set of credentials, rather than to use a different set of credentials for each unique system. In MOSS, it is possible to configure web applications to use a combination of authentication methods. This provides a great deal of flexibility because it makes it possible to serve a web application to different user bases which have different identity requirements. For example, an organization may have a Project Collaboration Web site that is used by employees and partners.

For security and compliance reasons, it is necessary to store employee user accounts in Active Directory and partner user accounts in a SQL Server database. In this case, MOSS can be configured to use Windows authentication and ASP.NET Forms authentication. This is achieved by defining various zones and associated authentication methods to the zones. In the example above, an intranet zone would be configured with Windows authentication and an extranet zone would be configured with ASP.NET Forms authentication.

MOSS Object Model : Sharepoint

Detailed MOSS Object Model

Monday, May 18, 2009

How to cretae a new SPlist instance using the WSS object model

The following code provides the code to create a list instance. Before creating the list, the code checks to make sure a list of the same title doesn’t already exist. You will notice that the code enumerates through the lists within the current site, checking each list to see if there is a matching title. If a list with a matching title does not exist, the code in this application then creates a new instance of the Announcements list type and adds a link to the Quick Launch menu for easy access.

using System;
using Microsoft.SharePoint;

class Program {
static void Main() {
using (SPSite site = new SPSite("http://localhost")) {
using (SPWeb web = site.OpenWeb()) {
string listName = "Litware News";
SPList list = null;
foreach (SPList currentList in web.Lists) {
if (currentList.Title.Equals(listName,
StringComparison.InvariantCultureIgnoreCase)) {
list = currentList;
break;
}
}

if (list == null) {
Guid listID = web.Lists.Add(listName,
"List for big news items",
SPListTemplateType.Announcements);
list = web.Lists[listID];
list.OnQuickLaunch = true;
list.Update();
}
}
}
}
}


The code shows how to create a SPLit of announcements. We can create any List type:


Document library
Used for collaborating on documents with support for versioning, check-in and check-out, and workflow. Includes support for deep integration with Microsoft Office.

Form library
Used to store XML documents and forms for use with Microsoft Office InfoPath.

Wiki page library
Used for collaborative Web pages based on wiki pages, which are dynamically generated and collaboratively edited Web pages.

Picture library
A specialized document library enhanced for use with pictures. Includes support for slide shows, thumbnails, and simple editing through Microsoft Office Picture Manager.

Announcements
Used for simple sharing of timely news with support for expiration.

Contacts
A list for tracking people and contact information, with support for integration into Microsoft Office Outlook and other WSS-compatible contacts applications.

Discussions
A simple list for threaded discussions with support for approval and managing discussion threads.

Links
A list for managing hyperlinks.

Calendar
A list for tracking upcoming events and deadlines. Includes support for integration and synchronization with Office Outlook.

Tasks
A list of activity-based items that can integrate with workflow.

Project tasks
An enhanced tasks list with support for Gannt chart rendering and integration with Microsoft Office Project.

Issue tracking
A list for tracking issues and resolution, with support for prioritization.

Custom list
An empty list definition for extending with custom columns, or created using Microsoft Office Excel spreadsheets.

Saturday, May 16, 2009

Foundation book on sharepoint 2007

There are two major books for begineers :

1. Inside WSS 3.0 and 2. Inside MOSS 2007 from Mirosoft Press.

These two books will give a strong foundation to the new bie in sharepoint

Thursday, May 14, 2009

How to get distinct value from CAML query

Many times, we face a challenge to get unique rows froma CAML query. The main problem is that CAML does not have any feature to get the distinct rows in one go.

Way Around:

We all know that CAML query returns SPListItemCollection and we can convert the outcome to data table also.
We can convert the resultant datatable to dataview and again convert the dataview to datatable by using ToTable and arguments :
Distinct = true
and column name

So..
suppose we have SPWeb object as 'web' so

DataTable DT= web.GetSiteData(qry);
DataView v = new DataView(tbl);
return v.ToTable(true, "Type");


This code snippets returns the distinct rows by comparing column name "Type".

Monday, April 27, 2009

How to check whether SPList exists in Sharepoint?

Sometimes we require to check whether SPList exists or not. There is no direct method to check for it. Instead we have to use try-catch block to catch the exception and to determine the list existence:

The code is:


using (SPSite ospSite = new SPSite("http://<servername>:<portname>"))
{
using (SPWeb ospWeb = ospSite.OpenWeb())
{
try
{
SPList ospList = ospWeb.Lists["ListName"];
if (ospList != null)
return true;
}
catch(Exception ex)
{
return false;
}
}
}


This code block creates an instance of SPList object. If ospList object is not null that is list is there so it returns true.
If list does not exists, an exception will be raised and false will be returned from catch block

Tuesday, April 21, 2009

Using SPPropertybag to save value

Hi,
this small code snippet will explain how to store value to Sharepoint proerty bag and how to fetch it.

How to save value to SPProperty Bag
Here we will create an instanceof SPPropertyBag and try to add a key 'BlogImage' to the bag:

SPPropertyBag spProperties = SPContext.Current.Web.Properties;
if (spProperties.ContainsKey("BlogImage")) spProperties.Remove("BlogImage");
spProperties.Add("BlogImage", path);
spProperties.Update();
SPContext.Current.Web.Update();

NOTE: Updating SPPropertybag and SPWeb is important.

How to get value from SPProperty Bag

SPPropertyBag spProperties = ospWeb.Properties;
string blogImageValue=string.Empty;
if (spProperties["BlogImage"] != null && spProperties["BlogImage"] != "")
{
blogImageValue= spProperties["BlogImage"].Trim();
}