Sandbox Solution
Sandbox
solutions allow you to:
1. Deploy custom code you
have developed or downloaded from the Internet.
2. Such custom code you
deploy cannot jeopardize the stability of your farm.
3. Solutions are being
deployed via web interface.
4. If you are running
SharePoint in a hosted environment you will be deploy SandBoxed solutions there
as well.
5. **Important- VS 2010 can open the
.WSP file.
6. To upgrade Sandbox
solution - Open the Existing solution(.WSP) in VS 2010 and do the modification
and upload into the Site collection Solution gallery.
7. **Important- Cant upload the Farm
solution to the Sandbox solution, It will give Partical truster caller error.
Sandbox
Solutions support the following SharePoint item types:
1. List definitions
2. List instances
3. Content Types/Fields
4. Navigation
5. Web Parts derived from
WebPart
6. Event receivers
7. Custom Workflow
Actions
8. Workflows
Where
are Assemblies in Sandboxed Solutions Deployed?
1- The assemblies in a sandboxed solution are
included in the solution package (.wsp file), and the package is
deployed to the site collection's Solutions
Gallery.
2- When
a sandboxed solution is accessed for the first time, such as when a user
navigates to a page that contains a Web Part from a sandboxed solution.
3- The default location is C:\ProgramData\Microsoft\SharePoint\UCCache;
4- The executable of this service is
SPUCHostService.exe. The server that handles the sandboxed request is not
necessarily the front-end web server that is handling the initial HTTP request:
5-
Sandboxed user process (SPUCWorkerProcess.exe)
cannot copy anything to the file system, the copying is done by the Microsoft
SharePoint Foundation Sandboxed Code Service.
10
reasons to use Sandboxed Solutions
1. It doesn't require IIS
Reset or Application Pool Recycling.
2. Central Administration
(CA) gives a way to block the sandbox solutions. In CA under System Settings
you can see the “Manage User Solutions” option
3. Sandboxed solutions
are secure.
4. Sandboxed solutions
can be monitored.
5. Sandboxed solutions do
not affect other sandboxed solutions, well at least not in other site
collections is what I mean.
6. Sandboxed solutions do
not touch the file system for the most part
7. Sandboxed solutions
skip application pool recycles, so debugging is not such a pain.
8. Sandboxed solutions
allow the site collection administrator to perform deployment and upgrades
9. Sandboxed solutions
make CAS policies look like the out of style hairstyles of 1980s
10. The Solution
validation framework for sandboxed solutions is extensible, simply inherit from
the SPSolutionValidator base class.
11. Sandboxed solutions
remove the need for line by line code reviews
12. Sandboxed solutions
allow you to offer different level of SLAs to different site collections using
Resource Quotas.
Limitation:
1. You can’t access the
Internet to make Web service calls,
2. You can’t access a
hard drive to read or write files,
3. You can’t access code
that is not marked to allow partially trusted callers.
4. You also can’t deploy
files to disk or add assemblies to the GAC in a sandboxed solution
5. Security-related
functionality, such as running RunWithElevatedPriviledges and other SPSecurity
methods, is not allowed.
Sandbox Solution vs. Form Solution:
1. Sandboxed solutions are hosted in the SharePoint user code solution worker process SPUCWorkerProcess.exe)
Farm solutions are hosted in the IIS worker process (W3WP.exe)
2. Sandboxed solutions are specific site collection
Farm solutions are run at Form level
3. Mapped folders cannot be added to the project in Sand box solutions.
4. Sandbox solutions does not support
• Visual Web Parts
1. Sandboxed solutions are hosted in the SharePoint user code solution worker process SPUCWorkerProcess.exe)
Farm solutions are hosted in the IIS worker process (W3WP.exe)
2. Sandboxed solutions are specific site collection
Farm solutions are run at Form level
3. Mapped folders cannot be added to the project in Sand box solutions.
4. Sandbox solutions does not support
• Visual Web Parts
•
Application Pages
•
Custom Action Group
•
HideCustomeActionelement
•
Web Application-scoped Features.
•
Farm-scoped features
•
Workflow with code
What is a Workflow in
SharePoint?
Ø Workflow
is a serious of activities occurs in steps which will produce an output at the final step.
Types
of Workflows:-
1. Sequential workflow
Ø Steps that execute
in order until the completion of last activity.=
2. State-Machine workflow
Ø A set of states, transitions and
actions. As sequential workflows.
Ø it does not have prescribed execution flow and need not have an end.
Default Workflow Of SharePoint various versions
v The different types of workflow in
the various versions of SharePoint present by default are listed below:
Ways for creating
workflows in SharePoint
The different ways of creating the
workflows in SharePoint are as follows:
1. In SharePoint site directly
2. SharePoint Designer
3. Microsoft Visual Studio with workflow
extensions installed (WWF-
Windows Workflow Foundation) – basically called custom workflows
What are the
pre-requisites for creating a workflow in SharePoint?
1. There should be a at least one list or
document library to create and associate a workflow.
2. If you do not have a single list or document
library in your site, you will be prompted for creating a list or
library.
3. If you want your workflow to be associated
with custom columns or settings in the site, then those changes
should be made before you create the workflow so that it will be available in
the designer.
Advantages
1.
Allow
the business activities to be automated, enabling actions such as
document review, approval, issue tracking and signature collection.
2.
Allow
the document to be routed to one person to another for approval by
assigning a task to each person. This is followed by analysis, review, and
approval and finally the document is published. Hence making the
document management easier.
3.
Also improves
the collaboration in an enterprise.
State-Machine workflows:
1-State-machine workflows
are workflows which are driven by particular events. Example:
Ø
OnTaskChanged
Ø
OnTaskCreated
Ø
OnTaskDeleted
Ø
OnWorkflowActivated
etc
2-
A state machine workflow moves from one state to another until the logic
concludes the workflow has completed.
3-
Compared to Sequential workflows State machine workflows are difficult to
design and maintain.
4-
In order to move to another event, the workflow needs to meet another state.
5-
The workflow doesn’t really have to end. It can stay in the same state for
weeks.
Sequential
workflows:
1-
It looks very simple like flow chart.
2-
Steps within the workflow execute sequentially, one after another in the
particular order.
3-
A sequential workflow always progresses forward, never going back to a previous
step.
4- Sequential workflows are
definitely much easier to design and maintain.
Out of Box Workflows:
There
are 7 out of box workflows.
1. Approval
1.
Routes a document or item to a group of people for approval.
2.
By default, the Approval workflow is associated with the
Document content type, and therefore it is automatically available in document
libraries
3.
The Approval workflow is a staged approval model (that is, the
first set of approvers can undergo the review and approval process, then the
next set of approvers, and so on). Each stage or approval set can also have its
own behavior. For example, members of the first group of approvers can do their
review in serial approval order (one after the other), members of the second
group can do their review in parallel (reviewers can provide feedback in any
order), and so on.
2. Collect Feedback
1.
Routes a document or item to a group of people for feedback.
2.
Reviewers can provide feedback, which is then compiled and sent
to the person who initiated the workflow.
3.
By default, the Collect Feedback workflow is associated with the
Document content type, and therefore it is automatically available in document
libraries.
3. Collect Signatures
1.
Routes a document that was created in a Microsoft application to
a group of people to collect their digital signatures.
2.
This workflow must be started in applications in the 2007
Microsoft Office system and the Microsoft Office 2010 suites such as Microsoft
Word.
3.
By default, the Collect Signatures workflow is associated with
the Document content type, and therefore is automatically available in document
libraries.
4.
However, the Collect Signatures workflow appears for a document in
the document library only if that document contains one or more Microsoft
Office Signature Lines.
4. Disposition Approval
1.
Manages document expiration and retention by letting
participants to decide whether to keep or delete expired documents.
2.
The Disposition Approval workflow supports record management
processes and is intended for use primarily in a Records Center site.
5. Three-State
1.
Designed to track the status of a list item through three states
(phases).
2.
It can be used to manage business processes that require
organizations to track a high volume of issues or items, such as customer
support issues, sales leads, or project tasks.
3.
SharePoint Server 2010 creates a task for the assigned user.
When the user completes the task, the workflow changes from its initial state
(Active) to its middle state (Resolved) and creates a task for the assigned
user. When the user completes the task, the workflow changes from its middle
state (Resolved) to its final state (Closed), and creates another task for the user
to whom the workflow is assigned at that time.
4.
Note that this workflow is only supported on
lists, not libraries.
6. Translation Management
1.
Manages manual document translation by creating copies of the
document to be translated and by assigning translation tasks to translators.
2.
This workflow is available only for Translation Management
libraries.
7. Issue Tracking
Routes
an issue to team members for resolution. It presents a Web page to the user who
makes possible the entry of new issues.
Ex:
customer complaints.
As
an issue progresses though different workflow states, the Web page of the user
changes to reflect appropriate events; for example, a Web page that was closed
when an issue is resolved.
Note:(Important )
1.
Before using out of box workflows you need to activate SharePoint 2007 workflow feature.
2.
All Out of Box workflows are sequential workflows only.
3.
Can we design workflows using SharePoint designer?
4.
Yes. We can design Sequential Workflows only. We can’t design
State machine workflows.
5.
State machine workflows can be designed by using visual studio.
you can design List Workflows, Reusable List Workflows and Site workflows using SharePoint designer 2010.
you can design List Workflows, Reusable List Workflows and Site workflows using SharePoint designer 2010.
.NET
Framework provides two methods Finalize and Dispose for releasing unmanaged
resources like files, database connections, COM etc.
Finalize
|
Dispose
|
1. Used
to free unmanaged resources like files, database connections, COM etc. held
by an object before that object is destroyed.
2. Internally,
it is called by Garbage Collector and cannot be called by user code.
3. It
belongs to Object class.
4. There
is performance costs associated with Finalize method.
|
1. It
is used to free unmanaged resources like files, database connections, COM
etc. at any time.
2. Explicitly,
it is called by user code and the class implementing dispose method must
implement IDisposable interface.
3. It
belongs to IDisposable interface.
4. There
is no performance costs associated with Dispose method.
|
Stages of the ASP.NET application
life cycle (IIS 7.0):
1-Request is made for an application
resource:
These
stages are represented by the RequestNotification enumeration. All requests can
be configured to take advantage of ASP.NET functionality,
2-The unified pipeline receives the
first request for the application:
1.
When
the unified pipeline receives the first request for any resource in an
application, an instance of the ApplicationManager class is created, which is the
application domain that the request is processed in. Application domains
provide isolation between applications for global variables and enable each
application to be unloaded separately.
2.
In
the application domain, an instance of the HostingEnvironment class is created, which
provides access to information about the application, such as the name of the
folder where the application is stored. During the first request, top-level
items in the application are compiled if required, which includes application
code in the App_Code folder.
3-Response objects are created for
each request:
After
the application domain has been created and the HostingEnvironment object has been instantiated,
application objects such as HttpContext, HttpRequest, and HttpResponse are created and initialized.
1.
After
all application objects have been initialized, the application is started by
creating an instance of the HttpApplication class.
2.
If
the application has a Global.asax file, ASP.NET instead creates an instance of
the Global.asax class that is
derived from the HttpApplication class. It then uses the
derived class to represent the application.
3.
Which
ASP.NET modules are loaded (such as the SessionStateModule) depends on the managed-code
modules that the application inherits from a parent application. It also
depends on which modules are configured in the configuration section of the
application's Web.config file. Modules are added or removed in the
application's Web.config modules element
in the system.webServer section.
At this stage the request are
processed and various events are called like ValidateRequest, URL Mapping,
BeginRequest, AuthenticateRequest and so on.
Stages of the Sharepoint Page Request
1. When you create a web application in
sharepoint, WSS configures the IIS
website by adding an IIS application map and creating several virtual directories. Windows SharePoint Services also
copies a global.asax file and web.config file to the root directory of the
hosting IIS Web site.Because every request targeting a Web application is
routed through aspnet_isapi.dll, the
request gets fully initialized with ASP.NET context. Furthermore, its
processing behavior can be controlled by using a custom HttpApplication object
and adding configuration elements to the web.config file.
2. First, you can see that Windows
SharePoint Services configures each Web application with a custom HttpApplication object by using the SPHttpApplication class. Note that this
class is deployed in the Windows SharePoint Services system assembly
Microsoft.SharePoint.dll.
3. In addition to including a custom
HttpApplication object, the Windows SharePoint Services architecture uses a
custom HttpHandler(SPHttpHandler) and a custom HttpModule(SPRequestModule).
These two SharePoint-specific components are integrated into the HTTP Request
Pipeline for a Web application using standard entries in the web.config file.
<configuration>
<system.web>
<httpHandlers>
<remove verb="GET,HEAD,POST" path="*" />
<add verb="GET,HEAD,POST" path="*"
type="Microsoft.SharePoint.ApplicationRuntime.SPHttpHandler,..." />
</httpHandlers>
<httpModules>
<clear />
<add name="SPRequest"
type="Microsoft.SharePoint.ApplicationRuntime.SPRequestModule,..."/>
<!--
other standard ASP.NET httpModules added back in -->
</httpModules>
</system.web>
</configuration>
|
4. ASP.NET 2.0 introduced a new pluggable component type known
as a virtual path provider. The idea behind a virtual path provider
is that it abstracts the details of where page files are stored away from the
ASP.NET runtime. By creating a custom virtual path provider, a developer can
write a custom component that retrieves ASP.NET file types, such as .aspx and
.master files, from a remote location, such as a Microsoft SQL Server database.
5. The Windows SharePoint Services team created a virtual
path provider named SPVirtualPathProvider that is integrated into every
Web application. The SPVirtualPathProvider class is integrated into
the ASP.NET request handling infrastructure by the SPRequestModule. More
specifically, the SPRequestModule component contains code to register
the SPVirtualPathProvider class with the ASP.NET Framework as it does
its work to initialize a Web application.
ASP.Net
Page life cycle.
S � Start
I � Initialize
L � Load
V � Validate
E � Event Handling
R � Render
I � Initialize
L � Load
V � Validate
E � Event Handling
R � Render
Sharepoint
page life cycle:-
Sharepoint
also having virtual directry which has same HTTP Handler HTTP Modules so that
one usually thinks that life cycle is same as ASP.NET Page Life Cycle but it's
not. Here is SharePoint 2007 Page Life
Cycle
1. User request the SharePoint Page
using http
2. ASP.NET calls the WSS File provider
3. WSS file provider returns the page
from File or Database
4. Page is parsed by SafeMode parsor if
required
5. Returned page is compiled by ASP.NET
Compiler
6. WSS File provider collects the page
layout class and complies it
7. ASP.NET engine adds SharePoint
Context Data to the site meta data and retrieves the associated master page.
8. Master page got compiled and
responded back to the user.
Webpart
page life cycle:-
1. OnInit – Configuration values set using
WebBrowsable properties and those in web part task pane are loaded into the web
part.
2. LoadViewState – The view state of the web part is
populated over here.
3. CreateChildControls – All the controls specified are
created and added to controls collection. When the page is being rendered for
the first time the method generally occurs after the OnLoad() event. In case of
4. postback, it is called before the OnLoad()
event. We can make use of EnsureChildControls() - It checks to see if the
CreateChildControls method has yet been called, and if it has not, calls it.
5.
OnLoad
6. User
Generated Event
– for e.g. button click on the web part.
7. OnPreRender – Here we can change any of the web
part properties before the control output is drawn.
8. RenderContents – Html Output is generated.
9. SaveViewState - View state of the web part is
serialized and saved.
10. Dispose
11 .UnLoad.
The
Microsoft.SharePoint.WebControls namespace of the Microsoft.SharePoint.dll contains a number of validation controls that can be used
on application pages and web parts to validate user entry in the SharePoint
controls.
1-Rich Text Box:
Register:
<%@ Register
Tagprefix="SharePoint" Namespace="Microsoft.SharePoint.WebControls"
Assembly="Microsoft.SharePoint, Version=12.0.0.0, Culture=neutral,
PublicKeyToken=71e9bce111e9429c" %>
Using:
<SharePoint:InputFormTextBox
TextMode="MultiLine" runat="server"
ID="rtct" RichTextMode="FullHtml" RichText="true"></SharePoint:InputFormTextBox>
2-SPGridView
1. The
SPGridView is similar to the asp GridView.
2. The
SPGridView is derived from the aspGridView and has additional
functionality.
3. The
SPGridView does not support the property AutoGenerateColumns,
4.
You must specify each SPBoundField.
Example: SPBoundFields such as
"BoundField" are used to display datasource columns.
Tip:
1.
Don't use DataKeyName on the SPDataGrid, it causes the error
"Unable to cast object of type 'System.Int32' to type
'System.String'.".
2.
SPDataGrid error 'Unable to cast object of
type int32 - SPDataGrid.NewPageIndex property and DataKeyNames
3.
Populating
the SPGridView Control with an ADO.NET DataTable
4.
One
advantage of using the SPGridView control in SharePoint-based solutions is
that it has been integrated with the cascading style sheets that are built
into Windows SharePoint Services 3.0.
3-People Picker
Display users from people/Group
field to People Picker Control
4-Validation controls:
1.
InputFormRequiredFieldValidator
2.
InputFormRangeValidator
3.
InputFormCompareValidator
4.
InputFormRegularExpressionValidator
5.
InputFormCheckBoxListValidator
6.
InputFormCustomValidator
E.g:-
<spuc:InputFormRequiredFieldValidator
ID="UserNameValidator" runat="server"
Display="Dynamic" SetFocusOnError="true"
ControlToValidate="CompanyNameTextBox"
BreakBefore="true" ErrorMessage="The company name is
required" />
5-Input
Controls:-
Text Box
Check Box
6-SPDatePickerControl
7-ButtonSection
8-InputFormTextBox
Notice
there are two InputFormTextBoxes shown here. One with the RichTexT property
set to true and the other set to false. So with a simple property change you
can get the nicely and shiny FullHTML textbox.
<SharePoint:InputFormTextBox
ID="ApproveMailSubject" RichText="false"
runat="server" Width="100%"/>
<SharePoint:InputFormTextBox
ID="ApproveMailContent" RichText="true"
RichTextMode="FullHtml"
runat="server"
TextMode="MultiLine"
Rows="20"/>
9-ToolBar & ToolBarButton
To use
the ToolBar in your WebPart you can load the UserControls and reference them
using this:
10- SharePoint Choice Field
Get
value collection of a SharePoint Choice Field
public
static List<string> GetChoiceFieldValues(string listName,string
fieldName, string siteCollection, string webSite)
{ List<string> fieldList;
SPSite spSite = null;
SPWeb spWeb = null;
try
{ if (siteCollection != null) spSite = new SPSite(siteCollection); else spSite = SPContext.Current.Site;
if (webSite != null)
spWeb = spSite.OpenWeb(webSite); else spWeb = spSite.OpenWeb();
SPList spList = spWeb.Lists[listName];
SPFieldChoice field = (SPFieldChoice)spList.Fields[fieldName];
fieldList = new List<string>();
foreach (string str in field.Choices)
{ fieldList.Add(str); } } catch (Exception ex) { LogException(ex); throw; } finally { if(spWeb != null) spWeb.Close();
if(spSite != null)
spSite.Close(); }
return fieldList;
} |
1. Server
Side Object Model
2. Client
Object Model
3. REST/OData
API
4.
SharePoint Web
Services
1.Server Side Object Model
1.Server Side Object Model
1.
Full trust code using C# or VB.Net
2.
We will use this option most of the times for
on-prem SharePoint projects. Since the code will run in the SharePoint server
itself. All your code bits will be deployed in SharePoint Server
3.
You need add below dlls to develop SharePoint
farm solutions
Microsoft.SharePoint.dll
Microsoft.SharePoint.Administration.dll
Microsoft.SharePoint.dll
Microsoft.SharePoint.Administration.dll
4.
You need to add below name space while
developing SharePoint solutions(Farm solutions)
Microsoft.SharePoint
Microsoft.SharePoint.Administration
Some of the class names:
Under: -Microsoft.SharePoint.Administration
-SPFarm
-SPServer
-SPWebApplication
-SPDatabase
-SPContentDatabase
Under: -Microsoft.SharePoint
-SPContext
-SPSite (To access SharePoint sites. Ex:SPSite.RootWeb() will return root site of site collection)
-SPWeb (To access all List and Libraries.Ex: SPWeb.Lists; will return all list objects)
-SPList (To access list fields, items..)
-SPField
-SPListItem
Microsoft.SharePoint
Microsoft.SharePoint.Administration
Some of the class names:
Under: -Microsoft.SharePoint.Administration
-SPFarm
-SPServer
-SPWebApplication
-SPDatabase
-SPContentDatabase
Under: -Microsoft.SharePoint
-SPContext
-SPSite (To access SharePoint sites. Ex:SPSite.RootWeb() will return root site of site collection)
-SPWeb (To access all List and Libraries.Ex: SPWeb.Lists; will return all list objects)
-SPList (To access list fields, items..)
-SPField
-SPListItem
2.Client
Object Model
1.
.Net client side object model (CSOM). Using C#
or VB.Net
You need to add:
Microsoft.SharePoint.Client.dll,Microsoft.SharePoint.Client.Runtime.dll
Microsoft.SharePoint.Client.dll,Microsoft.SharePoint.Client.Runtime.dll
2.
JavaScript Object Model (JSOM). Using javascript, jQuery
You need to add:SP.js and SP.Runtime.js
3.
SilverLight Object Model
You
need to add:
Microsoft.SharePoint.Client.dll,Microsoft.SharePoint.Client.Runtime.dll
CSOM -Will be used in on-prem environment or SharePoint App Development(Provider hosted app). We can't use SPO.
JSOM -Will be used in all environments. On-prem or SPO.
Libraries Of Client Side Model
Each client object model interacts with SharePoint through a Windows Communication Foundation (WCF)
Microsoft.SharePoint.Client.dll,Microsoft.SharePoint.Client.Runtime.dll
CSOM -Will be used in on-prem environment or SharePoint App Development(Provider hosted app). We can't use SPO.
JSOM -Will be used in all environments. On-prem or SPO.
Libraries Of Client Side Model
Managed Object Model
|
Microsoft.SharePoint.Client.dll
Microsoft.SharePoint.ClientRuntime.dll
|
ISAPI folder
|
Silverlight client object model
|
Microsoft.SharePoint.Client.Silverlight.dll
Microsoft.SharePoint.Client.Silverlight.Runtime.dll
|
LAYOUTS\ClientBin folder
|
JavaScript client object model
|
SP.js
|
LAYOUTS folder
|
Each client object model interacts with SharePoint through a Windows Communication Foundation (WCF)
service named Client.svc, which is located in the ISAPI directory. Every request sent as a single Extensible Markup Language (XML) request to the Client.svc service. The results of the server-side calls are then sent back to the calling client in the form of a JavaScript Object Notation (JSON) object.
Server object model
|
Managed Model
|
Silverlight Model
|
Javascript Model
|
SPContext
|
ClientContext
|
ClientContext
|
ClientContext
|
SPSite
|
Site
|
Site
|
Site
|
SPWeb
|
Web
|
Web
|
Web
|
SPList
|
List
|
List
|
List
|
SPListItem
|
ListItem
|
ListItem
|
ListItem
|
SPField
|
Field
|
Field
|
Field
|
The Client OM send request as an XML format and server
will return a JSON (java script Object Notation) which is converted into the appropriate
Object Model.
Client.svc:
1.
Client object
model is basically a WCF Web Service which is responsible for communication
between client Object Model and Share Point Data. Client.svc is located along
with all other SharePoint Web Services. The response from Client.svc Web
Service is sent as JSON format.
2.
Client.SVC service
has one method (ProcessQuery ) which takes SteramObject ProcessQuery method
found in Microsoft.SharePoint.Client.ServerRuntime.dll and
private c'ilass ClientRequestServiceImpl
3.
Location of client.svc service: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Client.SVC
Location of client.svc service: C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Client.SVC
Why We Use Client Object Model?
1. Share Point installation is not required on
development machine. If you want to develop a window application or any
other application, you only require dll’s.
2. Client Object Model is user-friendly as it poses less
deployment problems.
3. Flexibility in language: You can use any of
the three different languages for Client Object Model
Microsoft .NET
Silverlight
ECMA Script (JavaScript /JScript)
Microsoft .NET
Silverlight
ECMA Script (JavaScript /JScript)
4. Optimization in query speed: In Client OM,
you do not need to install the SharePoint Server which is required by the
Server Object Model. Thus, Client OM provides much ease to the end user.
3.REST/OData
API
-URL based api
-REST: Representational state transfer
-URL based protocol
-Technology and platform independent
4.SharePoint Web Services
SharePoint has provided some web services to access SharePoint data, we can use that services in client application.
-URL based api
-REST: Representational state transfer
-URL based protocol
-Technology and platform independent
4.SharePoint Web Services
SharePoint has provided some web services to access SharePoint data, we can use that services in client application.
Comparison between Server-side object model/Client object model/REST API(s) and Decision Matrix on what to use when
Server-Side Object Model
|
Client Object Model
|
REST API(s)
|
· Most extensive set of options to customize SharePoint 2010
· Any Components consuming server-side object model needs to be deployed on the server
· Slower Performance than Client OM and REST API(s)
· Synchronous
· Documentation:
|
· Client OM APIs are wrappers around a custom Web service that calls the server-side object model.
· Better Performance than server-side OM
· Asynchronous
· Execute calls in a batch of commands
· Limited options/types as compare to server-side OM
· Designed to be used in the remote client –side components
· Documentation:
|
· Limited set of REST interfaces
· Supports JSON(JavaScript Object Notation),Atom and AtomPub standards
· Based on ADO.NET Data Services
· Eliminated the need for intermediate layers between client and server by mapping Read, create, update, and delete operations directly to GET, POST, PUT, and DELETE HTTP verbs
· Interoperable
· Documentation:
|
ECMAScript Client Object Model
The JavaScript client object model consists of several JS files that are all installed into the LAYOUTS folder under the path %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS:
• SP.js/SP.debug.js
• SP.Core.js/SP.Core.debug.js
• SP.Runtime.js/SP.Runtime.debug.js
• SP.Ribbon.js/SP.Ribbon.debug.js
• JsGrid.js/JsGrid.debug.js
• JSGrid.Gantt.js/JSGrid.Gantt.debug.js
The JavaScript client object model consists of several JS files that are all installed into the LAYOUTS folder under the path %ProgramFiles%\Common Files\Microsoft Shared\web server extensions\14\TEMPLATE\LAYOUTS:
• SP.js/SP.debug.js
• SP.Core.js/SP.Core.debug.js
• SP.Runtime.js/SP.Runtime.debug.js
• SP.Ribbon.js/SP.Ribbon.debug.js
• JsGrid.js/JsGrid.debug.js
• JSGrid.Gantt.js/JSGrid.Gantt.debug.js
Advantages and Disadvantages of Client Object Model
I have been implementing Client Object Model (COM) extensively in Silverlight as well as in ECMAScript. I have failed many times in accomplishing certain tasks and succeeded many times too. You may love or hate COM but you cannot ignore it if you are a SharePoint 2010 developer.
So, I’m going to list out the advantages and disadvantages of COM that I have been facing while implementing it. Let us look at the advantages first.
Advantages:
- As mentioned everywhere using COM we can access the SharePoint data from the client side browser itself with Silverlight and ECMAScript applications.
- Web parts with very rich user interface can be developed with the help of Silverlight and jQuery. For example, we can create web parts like video and image galleries with beautiful animations where the videos and the images can be stored in the SharePoint libraries and retrieved using COM.
- COM along with JavaScript or jQuery can be implemented with just a Content Editor Web part within the browser or from the SharePoint designer without opening the Visual Studio. You can read about it here on how to do that.
- When we save your site as a template. The application developed with ECMAScript or Silverlight application implemented with Client Object Model would come along with the template which would be very helpful during migrations though we need to take care of any hard coded values.
- No IISREST is required while deploying a Silverlight or an ECMAScript application implemented with COM.
- We can have SharePoint accessed from the client desktop using Windows forms or WPF applications implemented with COM. We can develop desktop gadget kind of applications which would be displaying the new announcements added to the “Announcements” list.
- No SharePoint installation is required in the development machine. Only the dll’s are required if you are going to develop Silverlight applications.
Disadvantages:
- We cannot elevate the privilege or Impersonate in COM as in Server Object Model. That is, we cannot use the RunWithElevatedPrivilege kind of a delegate. Therefore, the results retrieved using COM will always be security trimmed by default.
- The range of classes available to access SharePoint data is very limited in COM. For example, we do not have Classes for accessing User Profiles. We need to go for SharePoint web services.
- We cannot access the objects of another site collection in COM while implementing in Silverlight or in ECMAScript. We will get “The security validation for this page is invalid.” if we try to do so. So, we cannot develop applications to read the data from another site collection.
- Silverlight web parts fail to load by giving an error message saying “Could not download the Silverlight application or the Silverlight Plugin did not load. To re-configure the Web Part or to provide a different Silverlight application (.xap), open the tool pane and then click Configure.” when it takes more than 5 seconds to load.
- We cannot retrieve recurring events from a SharePoint calendar list in Client Object Model.
Example of Client Object Model
//Method Add items into list
private void AddNewListItem()
{var: clientContext = new ClientContext(“your site URL/”);var :list = clientContext.Web.Lists.GetByTitle(“ListName”);
private void AddNewListItem()
{var: clientContext = new ClientContext(“your site URL/”);var :list = clientContext.Web.Lists.GetByTitle(“ListName”);
var: param = new ListItemCreationInformation();
var :newItem = list.AddItem(param);
newItem["Title"] = “This my new announcement”;
newItem["Body"] = “This is the body of announcement”;
newItem.Update();
newItem["Title"] = “This my new announcement”;
newItem["Body"] = “This is the body of announcement”;
newItem.Update();
clientContext.ExecuteQuery();
}
}
Some code sample:
//Server Object Model
SPSite siteCollection = SPContext.Current.Site;
string siteCollectionURL= siteCollection.Url;
//Managed Client Object Model
using (ClientContext clientContext = new ClientContext("Site URL"))
{
Site siteCollection = clientContext.Site;
clientContext.Load(siteCollection);
clientContext.ExecuteQuery();
string siteCollectionURL = siteCollection.Url;
}
//Silverlight Client Object Model
using (ClientContext clientContext = new ClientContext("Site URL"))
{
Site siteCollection = clientContext.Site;
clientContext.Load(siteCollection);
clientContext.ExecuteQuery();
string siteCollectionURL = siteCollection.Url;
}
//JavaScript Client Object Model
var siteCollection;
function getSiteCollection
{
var clientContext = new SP.ClientContext("/");
siteCollection = clientContext.get_site;
clientContext.load(site);
clientContext.executeQueryAsync(success, failure);
}
function success {
string siteCollectionURL = siteCollection.get_url;
}
function failure {
alert("Failure!");
}
How To Use Code
1. Code snippets for How to Load List and List items:
2. Code snippets for How to insert List items to a List:
3. Code snippets for update List items in List:
4. Code snippets for delete List items in List:
public void LoadList()
{
using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
{
var web = ctx.Web;
// Let's only work with the specific List object and save resources
// by not fetching any other objects
var list = ctx.Web.Lists.GetByTitle("ListName");
// Load only the list variable and execute the query
ctx.Load(list);
ctx.ExecuteQuery();
SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Name'/>
<Value Type='Text'>Shailesh</Value>
</Eq>
</Where>
</Query>
</View>";
SP.ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
//Now you can iterate listitems collection and can get listitems using foreach loop
foreach (SP.ListItem listItem in listItems)
{
//you can get value of list column from listitem as follow:
//listitem["ID"]
//listitem["Name"]
}
}
}
public void SaveListItem()
{
using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
{
var web = ctx.Web;
var list = ctx.Web.Lists.GetByTitle("ListName");
ctx.Load(list);
ctx.ExecuteQuery();
SP.ListItemCreationInformation itemCreateInfo = new SP.ListItemCreationInformation();
SP.ListItem listItem = list.AddItem(itemCreateInfo);
listItem["Name"] = "Shailesh";
listItem["Surname"] = "Soni";
listItem.Update();
ctx.ExecuteQuery();
}
}
Public void UpdateListItem()
{
using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
{
var web = ctx.Web;
// Let's only work with the specific List object and save resources
// by not fetching any other objects
var list = ctx.Web.Lists.GetByTitle("ListName");
// Load only the list variable and execute the query
ctx.Load(list);
ctx.ExecuteQuery();
SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Name'/>
<Value Type='Text'>Shailesh</Value>
</Eq>
</Where>
</Query>
</View>";
SP.ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
//Now you can iterate listitems collection and can get listitems using foreach loop
foreach (SP.ListItem listItem in listItems)
{
listitem["Address"] = “blah blah blah”;
listitem.Update();
}
ctx.ExecuteQuery();
}
}
Public void DeleteListItem()
{
using (SP.ClientContext ctx = new SP.ClientContext("SharePointSiteURL"))
{
var web = ctx.Web;
// Let's only work with the specific List object and save resources
// by not fetching any other objects
var list = ctx.Web.Lists.GetByTitle("ListName");
// Load only the list variable and execute the query
ctx.Load(list);
ctx.ExecuteQuery();
SP.CamlQuery camlQuery = new SP.CamlQuery();
camlQuery.ViewXml =
@"<View>
<Query>
<Where>
<Eq>
<FieldRef Name='Name'/>
<Value Type='Text'>Shailesh</Value>
</Eq>
</Where>
</Query>
</View>";
SP.ListItemCollection listItems = list.GetItems(camlQuery);
ctx.Load(listItems);
ctx.ExecuteQuery();
//Now you can iterate listitems collection and can get listitems using foreach loop
foreach (SP.ListItem listItem in listItems)
listItem.DeleteObject();
ctx.ExecuteQuery();
}
}
No comments:
Post a Comment