Translate

Saturday, October 13, 2012

Using SPFolder SharePoint Object


Using SPFolder SharePoint Object

SPFolder is one of the SharePoint object and it is a folder in the SharePoint list.To access 
an SPFolder object, first we need to retrieve an SPListItem object and use
the Folder property of that "SPListItem" which will return an SPFolder if the list item is a folder,
or else it  will returns null. 


Following are some of the properties which SPFolder exposed.

S.No.
Property Name
Description
1.
Name
Name of the folder
2.
Url
This return the site-relative URL of the folder
3.
Files
This returns an SPFileCollection object that contains SPFile
objects representing all the files found in the folder
4.
Item
Returns the SPListItem object that corresponds to the folder
5.
SubFolders
This returns an SPFolderCollection object that contains
SPFolder objects for all the subfolders contained within the
folder
6.
Exists
This returns a bool value that indicates whether the folder
exists
7.
Delete()
This method that deletes the folder
8.
CopyTo(string)
It Copies the folder and its contents to the URL specified by
the string parameter
9.
MoveTo(string)
Moves the folder and its contents to the URL specified by
the string parameter
10.
ItemCount
The count of children of this folder including
subfolders
11.
ServerRelativeUrl
This return the server-relative URL for the folder


The following WebPart  shows how to access the SPFolder object using SharePoint Object Model.



using System;
using System.ComponentModel;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;
using System.Linq;
using System.Text;
using System.Collections;
using System.Collections.Generic;
using System.Data;


namespace SPFolderDemo
{

 [ToolboxItemAttribute(false)]
    public class SPFolerSample : WebPart
    {

      StringBuilder spFolderSb = new StringBuilder();
        Literal SpLiteral = new Literal();
     


 protected override void CreateChildControls()
        {

            try
            {
SPList list=null
using(SPWeb web=SPContext.Current.Web)
{
list=web.List["SharedDocuments"];
}
SPListItem item=list.item[0];//for testing pointing to index "0"
SPFolder folder=item.Folder;
spFolderSb.Append("Folder Details");
spFolderSb.Append("Folder url:");
spFolderSb.Append(folder.Url);
spFolderSb.Append("Folder contains file");
spFolderSb.Append(folder.Files.Count);
spFolderSb.Append("Is Folder contains sub folder");
spFolderSb.Append(folder.SubFolder.Co);

SpLiterall.Text = spFolderSb.ToString();
this.Controls.Add(SpLiteral);


            }
            catch (Exception ex)
            {
                String.Format("Exception. ", ex);
            }

       }
    }









Monday, October 8, 2012

List E-mail Events and SPEmailEventReceiver

List E-mail Events and SPEmailEventReceiver

The class SPEmailEventReceiver has only one method " EmailReceived  " which is used trap the event when a list receives an email message.

To implement "EmailReceived" this method we need to create a class by inheriting the SPEmailEventReciever class.


The method "EmailReceived" accepts three parameters  (SPList,SPEmailMessage,String)
1. SPList
The SPList parameter actually represents the list that received the e-mail message which can be any List Type.

2. SPEmailMessage
SPEmailMessage is the actual e-mail that was send to the target list,We can use this parameter to get to the parts of the e-mail message and read the sender information, body of the e-mail, and any attachments ect.

3.String value.


The last parameter which is of String data type which is also called as receiverData , is a string and it contains the event receiver definition data.


sample code


 public class SampleEmailReceivedDemo: SPEmailEventReceiver
    {
        public override void EmailReceived(SPList targetList,SPEmailMessage SpMessage,string receiverData)
        {
            SPListItem listItem = targetList.Items.Add();
            listItem["Subject"] = SpMessage.Headers["Subject"];
            listItem["MessageBody"] = SpMessage.HtmlBody;
            listItemUpdate();
        }
    }






Sunday, October 7, 2012

Using SPAlert in SharePoint

Using SPAlert in SharePoint

In SharePoint Alerts are very important ,alert can be an email  message send to end user or it may be Short Message Service(SMS) from the SharePoint.In many situations it is required to configure alerts for the Lists/Libraries in SharePoint.

For example let us say you have a Quality Assurance SharePoint Site which has a document library related to documents about the process and other documents,and it is a mandatory to all the employees to follow the Quality process and even if there is any change or added new process,in this it is required for employee to alert if there is any modifications/added any new documents to this library.

Using SharePoint Model it is possible to know about the user's alerts using SPAlert class.

The Following code samples shows how to user's alert using SPAlert class.



SPSite mySiteCollection=null;
SPWeb mySPweb=null;
   Try
       {
//Get the SPSite by passing the url
mySiteCollection = new SPSite("http://QualityAssuranceSite /")
mySPweb = mySiteCollection.OpenWeb("Quality")
SPUserCollection  users = mySPweb .Users;
       //Iterate through each users in site
         foreach (SPUser user in users)
            {
              //Get alerts collections for the individual user
             SPAlertCollection alerts = user.Alerts;
         foreach (SPAlert alert in alerts)
            {
             
           // you can access the properties and methods from the alert object "alert"
//Title
string alertTitle=alert.Title;
//AlertFrequency
alert.AlertFrequency = Microsoft.SharePoint.SPAlertFrequency.Immediate;
       alert.Update();

            }
           }

}
Catch(SPExecption exception)
{
    Throw exception
}
Finally
{
    mySiteCollection.Dispose();
    mySPweb.Dispose();
}

Property Name
More Information/Description
AlertTemplate
Gets or sets the alert template which defines the content and format of an alert message which can be an e-mail version of the alert, it also defines the style and rendering.
AlertTemplateName
 The alert template name.
AlertTime
Date and time for sending the alert.
AlertType
Which can be a list or document library, a list item or document, or a custom object?
AlwaysNotify
It can be a daily or weekly alert is always sent, even if there is no matching event.
DeliveryChannels
The delivery method of the alert.
DynamicRecipient
It defines the event data to used to populate the e-mail recipient field in the alert.
EventType
Type of event to which the alert applies.
ID
ID of the alert.
Item
The list item or document to which the alert applies.
ItemID
The list item or document to which an alert applies in the parent collection of list items.
List
The list or document library to which the alert applies.
ListID
The GUID of the list or document library to which the alert applies.
ListUrl
The site-relative URL of the list to which the alert applies.
MatchId
Gets or sets the pre-filtering GUID for an externally matched alert.
UserId
Gets or sets the ID of the user who created the alert.

Friday, October 5, 2012

Different Types of Libraries in the SharePoint

Different Types of Libraries in the SharePoint


The following are the different types of libraries available in the SharePoint.


Document library: These are the standard library type used for the majority of file types.This is the most commonly used library type.

Form library:  It is being designed to forms created using InfoPath. When we create a form in InfoPath 2010 and it is possible to publish to a form library

Wiki page library: It is used to stores wiki pages which is mainly used Wiki page Site.

Picture library. It is mainly used to stores images.

Note: All these library types store files. Each type enables versioning to be specified, but

they differ in the kinds of files that they are designed to store

Difference between a List and a Library in SharePoint

Difference between a List and a Library in SharePoint


The main difference between a Library and a List is that an item in a Library must
contain a file.

The document library mainly it used to store files and it is accompanied by metadata for the respective items in the document library.

The Custom Lists/List type is used mainly to store the data/information.

The Document Library always provides the version  of the files which the items are created in the document library.

In both the cases the content types can be associated.


Thursday, October 4, 2012

How to create Custom Field Types in SharePoint

How to create Custom Field Types in SharePoint



There are situation in which it is required that we need to create controls which can be combination of one or more controls,usually controls are .net controls and SharePoint controls,in SharePoint also provides to create SharePoint custom field types by inheriting from one of the  builrt-in field type classes, such as SPFieldText, SPFieldNumber, SPFieldDateTime, and SPFieldMultiColumn. 

For Example
public class EmployeeJoinDate : SPFieldDateTime {
//Code comes here custom field type implementation
}

public class EmployeePANNumber : SPFieldText {
//Code comes here custom field type implementation
}
public class EmployeeSkills : SPFieldMultiColumn {
// custom field type implementation
}
public class EmployeementStatus : SPFieldText {
// custom field type implementation
}

Wednesday, October 3, 2012

Using ClientContext in SharePoint

Using ClientContext in SharePoint

In SharePoint context object provides an entry point into the associated application programming interface (API) that can be used to gain access to other objects.When we have access to the objects, we may interact with the scalar properties like Name, Title, Url of the object.

The ClientContext class can be used in both the managed and Silverlight object models which  inherits from the ClientContextRuntime class. With the help of ClientContext class, we can get a valid run-time context
by passing in the Uniform Resource Locator (URL) of a site.
It also provides several members that are required to access data and invoke methods on the server.
In SharePoint SP.ClientContext class which used in the JavaScript client object model is actually inherits from the SP.Client.ContextRuntime class which provides equivalent functionality to the ClientContext class found in the managed and Silverlight client object models. 

It is possible to get a run-time context in the JavaScript model using the SP.ClientContext class
and  can pass a URL. Which is different in managed and Silverlight models

Sample code shows different ways to access the sharepoint objects in client object model

1.Using Managed Code

//Managed Client Object Model
using (ClientContext context = new ClientContext("http://DemoSite"))
{
Site siteCollections = context.Site;
context.Load(siteCollections);
context.ExecuteQuery();
//access  scalar properties
string url = siteCollection.Url;
}

2.Using Silverlight Client Object Model
using (ClientContext context = new ClientContext("http://DemoSite"))
{
Site siteCollections =context .Site;
context .Load(siteCollections);
context .ExecuteQuery();
}

3.Using JavaScript Client Object Model

var siteCollections;
function getMySiteCollection
{
var context = new SP.ClientContext("/");
siteCollections = context.get_site;
context.load(site);
context.executeQueryAsync(Issuccess, Isfailure);
}
function Issuccess {
string url = siteCollection.get_url;
alert(url);
}
function Isfailure {
alert("It is Failed!");
}

Friday, September 21, 2012

SharePoint 2013 Perview Ribbon new look

SharePoint 2013 Perview Ribbon new look















SharePoint 2013 has new options in page edit ribbon

few of the them
1.Popularity trends
2.Page History
3,Format Text( format the content)
4,Insert ( allows to add Tables ,Media,Links,Parts, Embedded code)

Wednesday, September 19, 2012

Using SPUser in SharePoint

Using SPUser in SharePoint

SharePoint Object Model using SPUser Class


SPUser is actually derived from SPPrinciple, SPUser is main base class which allows in extending its functionality by exposing its member and different properties.SharePoint object model has provided the provision to add the user programatically to sharepoint group or  permissions to user to a list,and it is possible to update the user information or fetch the user information.

The following sample code shows about how to display user permission is he in admin group or normal user
also it has the code to update the user information or giving the permission to a list


WebPart

using System;
using System.ComponentModel;
using System.Web;
using System.Data;
using System.Text;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using Microsoft.SharePoint.WebControls;

namespace SPUserDemo
{
    [ToolboxItemAttribute(false)]
    public class SPUserDemoWebPart: WebPart
    {
protected override void CreateChildControls()
        {
         }
protected override void RenderContents(HtmlTextWriter writer)
{
//Get the user  information
  GetUser(writer)
}
private void GetUser(HtmlTextWriter writer)
{
SPUser SPuser = SPContext.Current.Web.CurrentUser;
if(SPuser.IsSiteAdmin)
writer.Write("<p>Ohh you are Super  admin user'</p>");
else
writer.Write("<p>No you are a normal user </p>");
}

}
}

 //Add  permissions to SharePoint list
Private void AddNewUser()
{
               const string listUsers = @"Users ";
               SPList  Users= null;
                SPSecurity.RunWithElevatedPrivileges(
            delegate {
                          using (SPSite spSsite= new SPSite(“http://sitedemo”)) {
                                     using (SPWeb  spWeb= spSsite.OpenWeb) {
                                                spWeb.AllowUnsafeUpdates = true;
                                              Guid listGuidID = spWeb.Lists.Add listUsers,
                                             "Members", SPListTemplateType.GenericList);
                                              Users = spWeb.Lists[listGuidID];
                                             Users.Fields.Add("User", SPFieldType.User, true);
                                            Users.WriteSecurity = 4;
                                            Users.Update();
                                            spWeb.Update();
                                                                                                      }
                                                                                           }
                         });
}

                   //update user email information
                         using (SPSite spSsite=new SPSite(“http://sitedemo”)) {
                              using (SPWeb  spWeb= spSsite.OpenWeb) {
                                        SPUser spUser = spWeb.AllUsers["ABCUser"];
                                              spUser.Email = " E-mail_Address";
                                                  spUser.Update();
                                                                                                 }
                                                                                                         }


Using SPQuery with ContentIterator.MaxItemsPerQuery in SharePoint

Using SPQuery with ContentIterator.MaxItemsPerQuery



1.       Using SPQuery with RowLimit or with ContentIterator.MaxItemsPerQuery
When we query the SharePoint list and libraries we use SPQuery and some situations because of threshold value limit in sharepoint does not allow the user to query more than or equal to 5000 items,If we use SPQuery  with RowLimit still it is not sure to get the items, but  there is still SharePoint has provide one more way can do it through using ContentIterator.MaxItemsPerQuery.

We also need to use different keywords using depends upon the requirement ContentIterator.ItemEnumerationOrderByID, ContentIterator.ItemEnumerationOrderByPath, or ContentIterator.ItemEnumerationOrderByNVPField.

Sample Code


SPQuery myQuery = new SPQuery();
myQuery.Query =
"<Where><Eq><FieldRef Name=\"Name\"/><Value Type=\"Text\">FieldValue</Value></Eq></Where>"
+ ContentIterator. ItemEnumerationOrderByID;
ContentIterator citerator = new ContentIterator();
citerator.ProcessItemsInList(query,
    delegate(SPListItem item)
    {
        // Code for update or move the list item from one list to another or    //any operation
    },
   // Return true so that ContentIterator rethrows the exception.
    delegate(SPListItem item, Exception e)
    {
        // Handle an exception that was thrown while iterating.
        return true;
    }
);




SharePoint 2013 preview in Cloud Share

SharePoint 2013 preview in the Cloud Share

Using SharePoint in the Cloud Computing

http://www.cloudshare.com/products/proplus/getstarted


http://www.cloudshare.com/products/proplus/getstarted site is really a good to start using SharePoint 2013 in Cloud Share ,there is a free 14 days trail version Cloud SharePoint 2013 preview.
This is really amazing site,this cloud system has got everything

Server has the following software's got installed 
1.SharePoint 2013 preview
2.Visual Studio 2012
3.SharePoint Designer 2012
4.SQL Server.

other softwares like PDF and other office tools.



Sunday, September 16, 2012

Creating Site Collection in SharePoint 2013 Preview

Creating Site Collection in SharePoint 2013 Preview

What is new features in SharePoint 2013 Preview


This is my first post on SharePoint 2013 preview,the following are the steps to create new site collection in SharePoint 2013,Microsoft has provided more features and enhancements in SharePoint 2013 than the SharePoint 2010.

Please follow the steps to create a new site collection in SharePoint 2013

1.Go to Central Admin and click on create site collection.
2.Screen will appear to create a new site collection,it is found that now it has a provision to create new web application on site collection creation screen as shown in the screen shot.
2. There is new option to select the template type based on SharePoint 2010 and SharePoint 2013 also provided with more number of templates like one is “Developer  Site” and other as shown in the following picture.

3.Select the template which is required to create the site


4. Add the Site Collection Administrator account in primary site collection Administrator and secondary Site Collection Administrator




There is new feature in People picker, more advanced can be able to search people by Active directory,NT Account or even Claim Based User as shown in the following screens shots



Now Microsoft has provided one more feature by displaying the “Sorry to keep you waiting
as shown in the screen shot


Finally 5.Now new site collection is create successfully.


SPList.GetItemById and SPList.GetItemByIdSelectedFields

Using SPList.GetItemById and SPList.GetItemByIdSelectedFields

Difference between SPList.GetItemById and SPList.GetItemByIdSelectedFields


It is very important to consider about the performance when we are query the SPList using SharePoint Object Model, it is not recommended to fetch all items when you are using only one column SharePoint has provided the GetItemByIdSelectedFields which takes the arguments as ID and Field Names which is required.

SPList.GetItemByIdSelectedFields(ID,"Field 1","Field 2","Field3"... so on)

GetItemById method fetches the full item from SPListItemCollection, with all its columns of metadata,even though it may be not required for the any purpose of extra columns still SPListItem hold that values too. So it is required to use in more better way of both GetItemByIdSelectedFields and GetItemById based on the requirements

The following example shows the Employee List which is being query by using GetItemByIdSelectedFields

Let us say the Employee List has three columns

Employee List

Column Name
Type
Employee Number
Number
Employee Salary
Number
Employee Designation
Single Line Of Text


ID
Employee Number
Employee Salary
Employee Designation
1
1123
24000
Senior Software Engineer
2
1124
12000
Trainee
3
1125
50000
Project Manager

The following code fetches

using (SPSite site = new SPSite("http://sampledemo /"))
{
using (SPWeb web = site.OpenWeb()) {
SPList employeeList = web.Lists["Employee List"];
SPListItem  employeeItem= employeeList.GetItemByIdSelectedFields (2,” Employee Salary”);
}
}

Using ReadSecurity and WriteSecurity members in SharePoint

Using ReadSecurity and WriteSecurity members in SharePoint

ReadSecurity and WriteSecurity

ReadSecurity
Using the ReadSecurity we can specify the list permission as read only access to list created through programmatically, it will restrict the users for modifications to the items which they are not owners of that items.
WriteSecurity
Using  WriteSecurity we can allow the users to do modifications to list items which they are owners of the items when we create the list by using the SharePoint Object Model programmatically.
Sample demo code explains about the ReadSecurity  and WriteSecurity by creating reimbursement expense list in which employee who wants to claim their expanses will have the permission which they item and others will not have an access ,Creating it through console application.
//Create the SPSite by passing the url
Using(SPSite spSite=new SPSite(“http://demo/sites/HR”);
{
//Create new GUID
Guid  newListGuid=spWeb.Lists.Add(“ExpensesReimbursement”,” Expenses Reimbursement List”,SPListTemplateType. GenericList );
//open  site

Using (SPWeb spWeb=spSite.OpenWeb())
{
//Create new SPList by passing new GUID
SPList newInstanceList  =  spWeb.Lists[newListGuid];
}
}

Saturday, September 15, 2012

Using SPSite and SPWeb Objects in Sharepoint

Using SPSite and SPWeb Objects in SharePoint


SPSite is the most fundamental object of the SharePoint Object Model,SPSite object can be created using the overloaded constructors or it can be referenced by using unique ID GUID, or with URL
Overloaded methods
SPSite(Guid id)
SPSite(string requestUrl)
SPSite(Guid id, SPUrlZone zone)
SPSite(Guid id, SPUserToken userToken)
SPSite(string requestUrl, SPUserToken userToken)
SPSite(Guid id, SPUrlZone zone, SPUserToken userToken)
SPSite is the only through which we can access the SPWeb  because SPWeb does not have a constructor, There are way with which we can get the instance of SPWeb is through using “SPControl” and “SPContext
Some of the important members of SPWeb are
1.       Users
2.       Title
3.       Update
4.       Delete
5.       ContentTypes
6.       AllUnsafeUpdates
7.       List
8.       ID
9.       GetSiteData
And so on.

Sample code shows how to access the SPWeb using SPSite and display the title of the site collection and update the specific  Subsite Tilte
namespace SampleDemo
{
    [ToolboxItemAttribute(false)]
    public class Sample : WebPart
    {
protected override void CreateChildControls()
        {
        }

       protected override void RenderContent(HtmlTextWriter writer)
        {
SPSite mySiteCollection=null;
SPWeb mySPweb=null;
              Try
{
//Get the SPSite by passing the url
mySiteCollection = new SPSite("http://demoSite /")
Writer.Write(“I am in Site Collection”);
//print /display the current site collection title
Writer.Write ("My Current Site  Exist here: ", mySiteCollection.Url);
mySPweb = mySiteCollection.OpenWeb("MySubSite")
//Update the subsite title
                                mySPweb.Title = mySPweb.Title + " Hey I have changed the Title";
mySPweb.Update();
}
Catch(SPExecption exception)
{
Throw exception
}
Finally
{
mySiteCollection.Dispose();
mySPweb.Dispose();
}
        }

     }
}