Thursday, October 18, 2012

SP 2010 Client Object Model with Examples


Brief  discussion about the ECMA script client object model.
Client OM Architecture
Before getting to actual usage we'll take a brief look at the architecture of the Client Object Model to understand how it functions.
Image1.png

As can be seen in the above diagram all versions of the Client OM go through the WCF Web Service namedClient.svc. This Web Service is located, along with all other SharePoint Web Services, in the folder [SharePoint Root]\ISAPI. The Client OM is responsible for packaging any requests into XML and calling the Web Server, however, when this call takes place is controlled by the developer as you will see. The response from the Client.svc Web Service is sent as JSON and the Client OM is responsible for transforming this into appropriate objects for use in the environment the call was made from.

The Client.svc Web Service has one method, ProcessQuery which takes a Stream object, an XML formatted stream as indicated above, and returns a Stream, JSON formatted. The implementation for this method can be found in the assembly Microsoft.SharePoint.Client.ServerRuntime.dll and the private class ClientRquestServiceImpl. Delving into this method, the first thing you find is an authentication check.

The Client OM uses Windows Authentication by default.


ECMAScript Client OM – Is a client object model extension for using JavaScript or JScript. This API is only available for applications hosted inside SharePoint (for example, web part deployed in SharePoint site can use this JavaScript API for accessing SharePoint from browser using JavaScript). You can however use this ECMAScript Client OM in web part pages or application pages (aspx pages) by referencing a javascript file (SP.js).
To use ECMAScript Client OM, add an entry for the below in your web part ascx control (the webparts deisgn interface) or to your content editor webpart’s HTML Source.

<script src=”/_layouts/SP.js” type=”text/ecmascript”></script>

Also, if If your code modifies SharePoint content you need to add a FormDigest control inside your page.The formdigest control can be added in master page and then all content pages will get it automatically.

<SharePoint:FormDigest runat=”server” />


For quick start add a Content editor webpart to your site page and modify its HTML source. Now, add the reference to SP.JS specified above and paste in the below code. Make sure you have ‘myCustomlist’ created in your site.
FYI… To get current client context we use SP.ClientContext.get_current() and to get current web we use ctx.get_web(). See the full example below.


Adding a List item – Now lets look at something advanced than above.

<script type=”text/javascript”>

function AddItem()
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘myCustomlist’);
var listItemCreationInfo = new SP.ListItemCreationInformation();
var newItem = list.addItem(listItemCreationInfo);
newItem.set_item(‘Title’, ‘SPUser’);
newItem.update();
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
alert(‘Added!’);
}
function failed(sender, args) {
alert(‘failed. Message:’ + args.get_message());
}

Delete an item - and finally how to delete an item.
function deleteItem(ItemId)
{
var context = new SP.ClientContext.get_current();
var web = context.get_web();
var list = web.get_lists().getByTitle(‘myCustomlist’);
var itemToDelete = list.getItemById(ItemId);
itemToDelete.deleteObject();
context.executeQueryAsync(Function.createDelegate(this, this.success), Function.createDelegate(this, this.failed));
}
function success() {
alert(‘Deleted!’);
}
function failed(sender, args) {
alert(‘failed. Message:’ + args.get_message());
}</script>
<a href=”#” onclick=”Javascript:AddItem();”>Create Item</a>
<a href=”#” onclick=”Javascript:deleteItem(1);”>Delete Item</a>

Thanks  LearningSharePoint Admin.

Monday, September 3, 2012

SP 2010 - SharePoint Object Model - basic coding ex's (List, Library)


SP 2010 - SharePoint Object Model


Here we are only discussing the Server Object Model. Server Object Model classes are used for Server-side programming and will be executed on the SharePoint Server Farm.
For programming against the SharePoint items, we need to retrieve the properties and the methods to operate on them. The SharePoint Object Model provides various classes to accomplish this. In this article we can discuss the Object Model with the core classes involved with little amount of coding.

Please note that there are 2 Object Models in SharePoint 2010:
  1. Server Object Model
  2. Client Object Model
Here we are discussing only about the Server Object Model. Server Object Model classes are used for server-side programming and will be executed on the SharePoint Server Farm.

Namespace

The Server Object Model classes are residing in the Microsoft.SharePoint assembly. The general classes are available in the Microsoft.SharePoint namespace and the administration classes inside the Microsoft.SharePoint.Administration namespace.

Core Classes

Following are the important classes and their corresponding SharePoint items.
Class
SharePoint Item
SPFarm
Farm
SPServer
Server
SPSite
Site Collection
SPWeb
Web site
SPControl
Control
SPList
List
SPDocumentLibrary
Document Library
SPContentType
Content Type
SPUser
User
SPException
SharePoint Exception
Programming

Now we can start experimenting with some of the above classes. To begin we can create a SharePoint Console Application. Use the New Project > SharePoint > Console Application project item.
ShareObjM1.jpg

Accessing the List Items in a List

For proceeding with this example, create a list derived from the Contacts template and name it as "My Contacts". 

Add some items inside it with the First Name and Last Name set.

Use the following code inside the Console application and execute it.
using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet")) // Site Collection
    using (SPWeb web = site.OpenWeb()) // Site    {
        SPList list = web.Lists["My Contacts"]; // List        int i = 1;
        foreach (SPListItem item in list.Items)
        {
            Console.WriteLine("Item: " + (i++).ToString());
            Console.WriteLine(item.Name);
            Console.WriteLine(item.Title);
            Console.WriteLine(item.GetFormattedValue("First Name"));
            Console.WriteLine(item.GetFormattedValue("Last Name"));
            Console.WriteLine(string.Empty);
        }
    }
}
Console.ReadKey(false);

If you receive any build errors regarding a namespace, change the Project Properties > Target to .Net Framework 3.5.
ShareObjM2.jpg

Now try building the application and it should work fine. You will see the following output.
ShareObjM3.jpg

Please note the use of Title and Name properties and the GetFormattedValue() method.

Accessing the items in a Library

Now we can proceed with accessing the document library items programmatically. For proceeding you need to create a document library inheriting from the Document Library template and name it "My Docs". Upload one or two documents into it. We are proceeding to get the file name and length in this example.

Enter the following code in the console application.
using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet")) // Site Collection{
    using (SPWeb web = site.OpenWeb())                    // Site    {
        SPDocumentLibrary library = web.Lists["My Docs"as SPDocumentLibrary// Library        int i = 1;
        foreach (SPListItem item in library.Items)
        {
            Console.WriteLine("Item: " + (i++).ToString());
            Console.WriteLine(item.File.Name);
            Console.WriteLine(item.File.Length);
            Console.WriteLine(string.Empty);
        }
    }
}


Executing the application, you will see the following results.

ShareObjM4.jpg

SPControl

The SPControl class acts as the base class while developing server controls. It reseides in the namespace Microsoft.SharePoint.WebControls.

SPControl provides static methods that returns reference to the current site, web, web application, module. The methods are:
SPControl.GetContextSite()SPControl.GetContextWeb()SPControl.GetContextWebApplication()SPControl.GetContextModule()

SPException

The SPException class can be used to handle an exception in a try catch block. It represents the exceptions thrown by the server object model.
try{
    // Code here}
catch (SPException ex)
{
    // Handle Exception}


SPUser

The SPUser class can be used to access user information for a SharePoint site. Enter the following code to get the number of users and their names.
using (SPSite site = new SPSite("http://appes-pc/my/personal/dotnet"))
{
    using (SPWeb web = site.OpenWeb())
    {
        foreach (SPUser user in web.AllUsers)
            Console.WriteLine("User: " + user.Name);
    }
}


On running the code you will see the results based on your machine users.

ShareObjM5.jpg

Note

You can add a new list item or library item using the Items.Add() method. For updating and deleting use the item.Update() and item.Delete() methods respectively. More code coverage on these areas will be provided later.

References

http://msdn.microsoft.com/en-us/library/ms473633.aspx 
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.webcontrols.spcontrol.aspx 
http://msdn.microsoft.com/en-us/library/microsoft.sharepoint.spuser.aspx 



Summary

In this article we have explored the SharePoint Object Model and some basic coding examples with List and Library.

Sandboxed Solution Vs Farm Solution


Sandboxed Solution Vs Farm Solution


Foreword
:
Whenever you create a solution for a SharePoint you must have to specify the trust level for the solution. There  are two trust levels defined in the SP2010 i.e.
  1. Sandboxed Solution (or User Solution)
  2. Farm Solution
Figure: Trust Level options
Sandboxed Solutions:
  • Are more restrictive solutions i.e. provide limited functionality
  • A solution that runs in  secure sandbox i.e. in a separate process then wpw3.exe.
  • Are secure by default and are protected by CAS policies i.e. deploying sandboxed solution does not affect other solutions
  • Easy monitoring
  • Are deployed to Site Collection level
  • One limitation is that, they can’t access the File system
  • SPUCHostService.exe, also known as the Sandboxed Code Service, runs on each server on the farm that you are going to allow to work in the sandbox
  • SPUCWorkerprocess.exe process is the sandbox worker process, redeploying Sandboxed solution does not required to restart application pool
  • Can be validated using the sandboxed solution validation by the farm administrator
Farm Solutions:
  • Have no restrictions i.e. provide unrestricted functionality
  • A solution that runs in a wpw3.exe (process)
  • Are less secure in nature, can be protected by implementing custom CAS ploicies
  • Difficult monitoring
  • Can be deployed to any object hierarchy
  • No limitations in accessing File system
  • When deployed, they could run any kind of code and they could make any kinds of changes to the servers.


Elements of a SharePoint Solution


Elements of a SharePoint Solution.

The following items are the basic elements of any SharePoint solutions:
  • The project file
  • Project properties
  • References
  • Features folder
  • Package folder
  • Key file (strong-named key)
Solution Explorer showing Elements of SharePoint Solution
Elements of SharePoint Solution
Features Node
  • Contains one or more SharePoint project Features
  • A Feature is a ‘container’ for an additional function to SharePoint
  • Deployed to a specific scope
  • Scope can be : Farm, Web Application, Site (Collection), Web (site)
  • Project items added are also added to the feature node
  • Double-clicking the feature node displays the Feature Designer
  • Feature Designer
    • Creates Features
    • Sets Scopes
    • Establish Feature Dependencies
    • Manually edit the Feature Manifest
    • Overriding the generated manifest will disable the Designer, and then all further changes will need to be done manually
Package Node
  • Groups and view the hierarchical Package tree
  • Groups the SharePoint Items into a Solution Package
  • The Package node contains a single file that serves as the distribution mechanism for the SharePoint project.
  • This Package file is also known as a solution package, is .CAB-based with a .WSP extension.
  • A solution package is a deployable, reusable file that contains a set of features, site definitions, and assemblies that apply to SharePoint sites, and that you can enable or disable individually.
  • The Package node also always contains a file that is named Package.wspdef, an XML definition file for the package.
  • Once a package is deployed to the SharePoint server, the SharePoint administrator can install it and activate its features.
  • Double-clicking the Package node opens it in the Package Designer. You can then view or change its contents.
Key file (strong-named key)
  • Assembly signing (also called strong-name signing) gives an application or component a unique identity that other software can use to identify and refer explicitly to it.
  • A strong name consists of its simple text name, version number, culture information (if provided), plus a public/private key pair.
  • For the purpose of assembly signing, Visual Studio supports only Personal Information Exchange (.pfx) and Strong Name Key (.snk) files stored in the project system on the local computer.


Wednesday, March 14, 2012

Opening PDFs in SharePoint 2010

If you have your nice SP2010 setup you may notice that when you go to open a PDF file it prompts you to save it rather than opening.



This is really annoying and would send everyone here at the school completely bananas! Not to mention the fact that we try to get everything on SharePoint only to force people to save it to their own area!
Never fear there is a solution. It’s in central admin.

Go there and click ‘Manage Web Applications’



Click on the web app you want to change, and go to ‘General Settings’



Scroll down the list until you reach ‘Browser File Handling’
Change the radio box from Strict to Permissive.




Click ok.


Go back to your PDF document and click on it – and it will open up without forcing you to save it somewhere first.
You may have noticed in the first screen shot there was no PDF icon. Well, follow this guide to right that wrong!

Friday, March 9, 2012

SharePoint - How to change logo of site

 

Save your new logo to \14\TEMPLATE\IMAGES\RamiiBranding\mylogo.png
Now go to : Site settings -> under Look & Feel choose : Title, Description, and Icon
Logo URL and Description : /_layouts/IMAGES/RamiiBranding/mylogo.png
The Tip is relative path “/_layouts/IMAGES” actually refers to “\14\TEMPLATE\IMAGES” folder

Ramii

Sunday, May 22, 2011

ABAP - Inner Join and Outer Join (Explained)


The data that can be selected with a view depends primarily on whether the view implements an inner join or an outer join. With an inner join, you only get the records of the cross-product for which there is an entry in all tables used in the view. With an outer join, records are also selected for which there is no entry in some of the tables used in the view.
The set of hits determined by an inner join can therefore be a subset of the hits determined with an outer join.
Database views implement an inner join. The database therefore only provides those records for which there is an entry in all the tables used in the view. Help views and maintenance views, however, implement an outer join.
This graphic is explained in the accompanying text

Saturday, May 7, 2011

ABAP DICTIONARY

ABAP DICTIONARY:



User-defined types
Database objects
Provides services
Indexes
Data elements
 Structures
  Table types
 Tables
  Database views
Setting and releasing locks, defining an input help (F4 help) and attaching a field help (F1 help) to a screen field are supported.

Data elements: Describe an elementary type by defining the data type, length and possibly decimal places.
Structures: Consist of components that can have any type.
Table types: Describe the structure of an internal table


The ABAP Dictionary permits a central management of all the data definitions used in the R/3 System.

In the ABAP Dictionary you can create user-defined types (data elements, structures and table types) for use in ABAP programs or in interfaces of function modules. Database objects such as tables and database views can also be defined in the ABAP Dictionary and created with this definition in the database.

The ABAP Dictionary also provides a number of services that support program development. For example, setting and releasing locks, defining an input help (F4 help) and attaching a field help (F1 help) to a screen field are supported.

Tables and database views can be defined in the ABAP Dictionary.

These objects are created in the underlying database with this definition. Changes in the definition of a table or database view a re also automatically made in the database.

Indexes can be defined in the ABAP Dictionary to speed up access to data in a table. These indexes are also created in the database.

There are three different type categories in the ABAP Dictionary:

Data elements: Describe an elementary type by defining the data type, length and possibly decimal places.

Structures: Consist of components that can have any type.

Table types: Describe the structure of an internal table.

Any complex user-defined type can be built from these basic types.

Example: The data of an employee is stored in a structure EMPLOYEE with the components NAME, ADDRESS and TELEPHONE. Component NAME is also a structure with components FIRST NAME and LAST NAME. Both of these components are elementary, i.e. their type is defined by a data element. The type of component ADDRESS is also defined by a structure whose components are also structures. Component TELEPHONE is defined by a table type (since an employee can have more than one telephone number).

Types are used for example in ABAP programs or to define the types of interface parameters of function modules.

The ABAP Dictionary supports program development with a number of services:

Input helps (F4 helps) for screen fields can be defined with search helps.

Screen fields can easily be assigned a field help (F1 help) by creating documentation for the data element.

An input check that ensures that the values entered are consistent can easily be defined for screen fields using foreign keys.

The ABAP Dictionary provides support when you set and release locks. To do so, you must create lock objects in the ABAP Dictionary. Function modules for setting and releasing locks are automatically generated from these lock objects; these can then be linked into the application program.

The performance when accessing this data can be improved for database objects (tables, views) with buffering settings.

By logging, you can switch on the automatic recording of changes to the table entries.

The ABAP Dictionary is actively integrated in the development and runtime environments. Each change takes immediate effect in the relevant ABAP programs and screens.
Examples:

When a program or screen is generated, the ABAP interpreter and the screen interpreter access the type definitions stored in the ABAP Dictionary.

The ABAP tools and the Screen Painter use the information stored in the ABAP Dictionary to support you during program development. An example of this is the Get from Dictionary function in the Screen Painter, with which you can place fields of a table or structure defined in the ABAP Dictionary in a screen.

The database interface uses the information about tables or database views stored in the ABAP Dictionary to access the data of these objects.

The structure of the objects of application development are mapped in tables on the underlying relational database.

The attributes of these objects correspond to fields of the table.

A table consists of columns (fields) and rows (entries). It has a name and different attributes, such as delivery class and maintenance authorization.

A field has a unique name and attributes; for example it can be a key field.

A table has one or more key fields, called the primary key.

The values of these key fields uniquely identify a table entry.

You must specify a reference table for fields containing a currency (data type CURR) or quantity (data type QUAN). It must contain a field (reference field ) with the format for currency keys (data type CUKY) or the format for units (data type UNIT). The field is only assigned to the reference field at program runtime.

The basic objects for defining data in the ABAP Dictionary are tables, data elements and domains. The domain is used for the technical definition of a table field (for example field type and length) and the data element is used for the semantic definition (for example short description).

A domain describes the value range of a field. It is defined by its data type and length. The value range can be limited by specifying fixed values.

A data element describes the meaning of a domain in a certain business context. It contains primarily the field help (F1 documentation) and the field labels in the screen.

A field is not an independent object. It is table -dependent and can only be maintained within a table.

You can enter the data type and number of places directly for a field. No data element is required in this case. Instead the data type and number of places is defined by specifying a direct type .

The data type attributes of a data element can also be defined by specifying a built-in type , where the data type and number of places is entered directly.


A transparent table is automatically created on the database when it is activated in the ABAP Dictionary. At this time the database-independent description of the table in the ABAP Dictionary is translated into the language of the database system used.

The database table has the same name as the table in the ABAP Dictionary. The fields also have the same name in both the database and the ABAP Dictionary. The data types in the ABAP Dictionary are converted to the corresponding data types of the database system.

The order of the fields in the ABAP Dictionary can differ from the order of the fields on the database. This permits you to insert new fields without having to convert the table. When a new field is added, the adjustment is made by changing the database catalog (ALTER TABLE). The new field is added to the database table, whatever the position of the new field in the ABAP Dictionary.


ABAP programs can access a transparent table in two ways. One way is to access the data contained in the table with OPEN SQL (or EXEC SQL). With the other method, the table defines a structured type that is accessed when variables (or more complex types) are defined.

You can also create a structured type in the ABAP Dictionary for which there is no corresponding object in the database. Such types are called structures. Structures can also be used to define the types of variables.

Structures can be included in tables or other structures to avoid redundant structure definitions.

A table may only be included as an entire table.

A chain of includes may only contain one database table. The table in which you are including belongs to the include chain. This means that you may not include a transparent table in a transparent table.

Includes may contain further includes.

Foreign key definitions are generally imparted from the include to the including table. The attributes of the foreign key definition are passed from the include to the including table so that the foreign key depends on the definition in the include.

You must maintain the technical settings when you define a transparent table in the ABAP Dictionary.

The technical settings are used to individually optimize the storage requirements and accessing behavior of database tables.

The technical settings can be used to define how the table should be handled when it is created on the database, whether the table should be buffered and whether changes to entries should be logged.

The table is automatically created on the database when it is activated in the ABAP Dictionary. The storage area to be selected (tablespace) and space allocation settings are determined from the settings for the data class and size category.

The settings for buffering define whether and how the table should be buffered.

You can define whether changes to the table entries should be logged.

The data class logically defines the physical area of the database (for ORACLE the tablespace) in which your table should be stored. If you choose the data class correctly, the table will automatically be created in the appropriate area on the database when it is activated in the ABAP Dictionary.

The most important data classes are master data, transaction data, organizational data and system data.

Master data is data that is rarely modified. An example of master data is the data of an address file, for example the name, address and telephone number.

Transaction data is data that is frequently modified. An example is the material stock of a warehouse, which can change after each purchase order.

Organizational data is data that is defined during customizing when the system is installed and that is rarely modified thereafter. The country keys are an example.

System data is data that the R/3 System itself needs. The program sources are an example.

Further data classes, called customer data classes (USR, USR1), are provided for customers. These should be used for customer developments. Special storage areas must be allocated in the database.

The size category describes the expected storage requirements for the table on the database.

An initial extent is reserved when a table is created on the database. The size of the initial extent is identical for all size categories. If the table needs more space for data at a later time, extents are added. These additional extents have a fixed size that is determined by the size category specified in the ABAP Dictionary.

You can choose a size category from 0 to 4. A fixed extent size, which depends on the database system used, is assigned to each category.

Correctly assigning a size category therefore ensures that you do not create a large number of small extents. It also prevents storage space from being wasted when creating extents that are too large.

Modifications to the entries of a table can be recorded and stored using logging.

To activate logging, the corresponding field must be selected in the technical settings. Logging, however, only will take place if the R/3 System was started with a profile containing parameter 'rec/client'. Only selecting the flag in the ABAP Dictionary is not sufficient to trigger logging.


Parameter 'rec/client' can have the following settings:
rec/client = ALL All clients should be logged.
rec/client = 000[...] Only the specified clients should be logged.
rec/client = OFF Logging is not enabled on this system.

The data modifications are logged independently of the update. The logs can be displayed with the Transaction Table History (SCU3).

Logging creates a 'bottleneck' in the system:

Additional write access for each modification to tables being logged.

This can result in lock situations although the users are accessing different application tables!v