Showing posts with label sharepoint webservices. Show all posts
Showing posts with label sharepoint webservices. Show all posts

Wednesday, November 16, 2011

Upload a File to a SharePoint Document Library


using System;
using System.Collections;
using System.Collections.Generic;
using System.Text;
using System.Net;
using System.IO;
using System.Xml;


namespace DevHoleDemo
{
    class Program
    {
        static void Main(string[] args)
        {
            DocLibHelper docLibHelper = new DocLibHelper();
            Dictionary<string, object> properties = new Dictionary<string, object>();
            properties.Add("Title", "Test Title");
            //Create or overwrite text file test.txt in 'Docs' document library creating folder 'Test Folder' as required.
            docLibHelper.Upload("http://localhost/Docs/Test Folder/test.txt", System.Text.Encoding.ASCII.GetBytes("Test text."), properties);
        }
    }
 
    public class DocLibHelper
    {
        ListsService.Lists m_listService;
        ICredentials m_credentials;
        ListInfoCollection m_lists;
 
        public DocLibHelper()
        {
            m_credentials = CredentialCache.DefaultCredentials;
            m_listService = new ListsService.Lists();
            m_listService.Credentials = m_credentials;
            m_lists = new ListInfoCollection(m_listService);
        }

Friday, November 4, 2011

Create Simple Web Service in Visual Studio 2008 / 2010

1. Create the Web Service


First create new project and select "New ASP.NET Web Service Application" and I'm giving the name "MyFirstWebService" to it, you can give any name to your project.


Now you can see auto generated code that you can add methods to create your web service. You can see simple method "HelloWorld" and in this sample code I have removed it.

I'm going to add simple method called "simpleMethod" which takes a string as an input and add "Hello" to beginning of that string. Now the code will appear like bellow.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
namespace MyFirstWebService
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        [WebMethod]
        public string simpleMethod(String srt)
        {
            return "Hello "+srt;
        }
        [WebMethod]
        public int anotherSimpleMethod(int firstNum, int secondNum)
        {
            return firstNum + secondNum;
        }
    }
}

Then you can run your code and you can see the resulting page as bellow.


2. Create the Client Program


We have created our simple web service and we have to create small
client program to use this web service. There you can open another
instant of Visual Studio and create new "Console Application" project.


Then you have to add Service Reference so that you can access your web service. Here are the screen-shots.




Here you have to give the URL of the web service we created earlier.
As I said before previously created web service application should be
running on another instant of Visual Studio.


Note that I have set the "Web reference name" as "TestWeb".


Now you can update your client program using following code. Note the line 5 "using WebServiceTest.TestWeb;".
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using WebServiceTest.TestWeb;
namespace WebServiceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            Service1 webservice = new Service1();
            string srt = webservice.simpleMethod("Saranga Rathnayake");
            Console.WriteLine(srt);
            Console.WriteLine(webservice .anotherSimpleMethod(4,3));
        }
    }
}
Now you can run the client program to see the result.


3. Publish Our Web Service in Internet Information Service (IIS)


Let's see how we can publish our web service in IIS. There first stop the web service application and go to the Solution Explore and Right Click on the project. Then select "Publish...".


Then the following window will appear and there you can directly publish to the IIS by selecting "Web Deploy" as the publishing method. But here I'm going to use the "File System as the publishing method. There you have to provide the target location. I have created new folder called "MyApp" in my D drive and selected it.


Now click "Publish" and check the "MyApp" folder. There you will be able to see Service1.asmx file, Web.config file and bin folder which contains the DLL file has been generated.

Now enable IIS in your computer and open IIS Manager. I'm going to add my service to Default Web Site. There Right Click on the "Default Web Site" and click "Add Application...".


There you will get following window. Now you can provide appropriate Alias (I have given testservice) and select the physical path of your application. There you can provide the path to the folder we created previously as following figure and click Ok.

You have to make sure that the application pool identity has Read access to the physical path. So it is better if you copy your files to the "wwwroot" folder other than keep it in separate partition. Please check the following screen-shot



Now restart the IIS and goto http://localhost/testservice/Service1.asmx. You will be able to see the Web Service running.


Now you have published your web service in IIS and you can update the Client Program by giving the new Web Reference URL using Properties Window.


Getting list item using sharepoint web service GetListItems

public void getListData()
{
    WS_Lists.Lists myservice = new WS_Lists.Lists();
    myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
    try
    {
        /* Assign values to pass the GetListItems method*/
        string listName = "{5C65CB1A-2E1B-488A-AC07-B115CD0FC647}";
        string viewName = "{75E689B4-5773-43CB-8324-58E42E1EB885}";
        string rowLimit = "100";
 
        // Instantiate an XmlDocument object
        System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
        System.Xml.XmlElement query = xmlDoc.CreateElement("Query");
        System.Xml.XmlElement viewFields = xmlDoc.CreateElement("ViewFields");
        System.Xml.XmlElement queryOptions = xmlDoc.CreateElement("QueryOptions");
 
        /*Use CAML query*/
        query.InnerXml = "<Where><Gt><FieldRef Name=\"ID\" />" +
        "<Value Type=\"Counter\">0</Value></Gt></Where>";
        viewFields.InnerXml = "<FieldRef Name=\"Title\" />";
        queryOptions.InnerXml = "";
 
        System.Xml.XmlNode nodes = myservice.GetListItems(listName, viewName, query, viewFields, rowLimit, null, null);
 
        foreach (System.Xml.XmlNode node in nodes)
        {
            if (node.Name == "rs:data")
            {
                for (int i = 0; i < node.ChildNodes.Count; i++)
                {
                    if (node.ChildNodes[i].Name == "z:row")
                    {
                        Response.Write(node.ChildNodes[i].Attributes["ows_Title"].Value + "</br>");
                    }
                }
            }
        }
    }
    catch (Exception ex)
    {
        Response.Write(ex.Message);
    }
}

List of all web services available in sharepoint

1) Administration Web Service (http://<site>/_vti_bin/Admin.asmx):
The Administration Web service provides methods that can beused to manage Windows SharePoint Services such as creating or deleting site collections. Following are the main methods provided by this service:
  • CreateSite
  • DeleteSite
  • GetLanguages
  • RefreshConfigCache
2) Alerts Web Service (http://<Site>/_vti_bin/Alerts.asmx):
The alerts web service provides methods for working with alert subscriptions for the listitems in a SharePoint site remotely. Alert subscriptions specify when and how notifications are sent to users when changes are made to content stored on the server. Following are the two main methods provided by this service:
  • GetAlerts
  • DeleteAlerts
3) Copy Web Service (http://<Site>/_vti_bin/Copy.asmx):
This web service provides capability to move files from one list to another within a SharePoint site or between different SharePoint sites. Following are the main methods provided by this service:
  • GetItem
  • CopyIntoItems
  • CopyIntoItemsLocal
4) Document Workspace Web Service (http://<Site>/_vti_bin/Dws.asmx):
This web service provides methods for managing Document Workspace sites and the data they contain. Following are the main methods provided by this service:
a) Managing Document Workspace sites
  • CanCreateDwsUrl
  • CreateDws
  • RenameDws
  • DeleteDws
b) Managing data for the Document Workspace site
  • GetDwsData
  • GetDwsMetaData
  • UpdateDwsData
c) Managing folders in the Document Workspace site
  • CreateFolder
  • DeleteFolder
d) Managing documents in the Document Workspace site
  • FindDwsDoc
e) Managing site users for the Document Workspace site
  • RemoveDwsUser
5) Forms Web Service (http://<Site>/_vti_bin/Forms.asmx):
The Forms service provides methods for returning forms that are used in the user interface when working with the contents of a list. There are following two methods available:
  • GetForm 
  • GetFormCollection
6) Imaging Web Service (http://<Site>/_vti_bin/Imaging.asmx):The Imaging service provides methods that enable you to create and manage picture libraries. There are following methods that can be utilized with the imaging web service:
  • CheckSubwebAndList
  • CreateNewFolder
  • Delete
  • Download
  • Edit
  • GetItemsByIds
  • GetItemsXMLData
  • GetListItems
  • ListPictureLibrary
  • Rename
  • Upload 
7) Lists Web Service (http://<site>/_vti_bin/Lists.asmx):

The Lists Web service provides methods for working with SharePoint lists, content types, list items, and files. There are following methods that can be utilized with the Lists web service:
  • AddAttachment
  • AddDiscussionBoardItem
  • AddList
  • AddListFromFeature
  • ApplyContentTypeToList
  • CheckInFile
  • CheckOutFile
  • CreateContentType
  • DeleteAttachment
  • DeleteContentType
  • DeleteContentTypeXmlDocument
  • DeleteList
  • GetAttachmentCollection
  • GetList
  • GetListAndView
  • GetListCollection
  • GetListContentType
  • GetListContentTypes
  • GetListItemChanges
  • GetListItemChangesSinceToken
  • GetListItems
  • GetVersionCollection
  • UndoCheckOut
  • UpdateContentType
  • UpdateContentTypeXmlDocument
  • UpdateList
  • UpdateListItems
8) Meetings Web Service (http://<Site>/_vti_bin/Meetings.asmx):

This web service enables you to create and manage Meeting Workspace sites. Following are the main methods available in the web service:
  • AddMeeting
  • AddMeetingFromICal
  • CreateWorkspace
  • DeleteWorkspace
  • GetMeetingWorkspaces
  • GetMeetingsInformation
  • RemoveMeeting
  • RestoreMeeting
  • SetAttendeeResponse
  • SetWorkspaceTitle
  • UpdateMeeting
  • UpdateMeetingFromICal
9) People Web Service (http://<Site>/_vti_bin/People.asmx):
This service provides methods that can be used to associate user identifiers (IDs) with security groups for SharePoint Web site permissions. It contains following methods:
  • GetPrincipalsInGroup
  • ResolvePrincipals
  • SearchPrincipals
10) Permissions Web Service (http://<site>/_vti_bin/Permissions.asmx):

Permissions Web service provides methods for working with SharePoint list and site permissions. Following are the various methods available in this service:
  • AddPermission
  • AddPermissionCollection
  • GetListItemPermissionsByUser
  • GetListPermissionsByUser
  • GetPermissionCollection
  • GetPermissionsByToken
  • GetPermissionsByUser
  • RemovePermission
  • RemovePermissionCollection
  • UpdatePermission
11) SharePoint Directory Management Service (http://<Site>/_vti_bin/sharepointemailws.asmx):
This service provides methods for managing Active Directory e-mail distribution groups and their membership. It provides following main methods:
  • CreateContact
  • DeleteContact
  • ModifyContact
  • CreateDistributionGroup
  • DeleteDistributionGroup
  • ModifyDistributionGroup
  • RenameDistributionGroup
  • ChangeContactsMembershipInDistributionGroup
  • ChangeUsersMembershipInDistributionGroup 
12) Site Data Web Service (http://<Site>/_vti_bin/SiteData.asmx):
The Site Data service provides methods that return metadata or list data from sites or lists in Microsoft Windows SharePoint Services. This web service is read only. Following are the main methods provided by this service:
  • GetList
  • GetListCollection
  • GetListItems 
  • EnumerateFolder
  • GetAttachments
  • GetChanges
  • GetContent
  • GetSite
  • GetWeb 
  • GetSiteAndWeb
  • GetSiteUrl
  • GetURLSegments 
13) Sites Web Service (http://<Site>/_vti_bin/Sites.asmx):
The Sites service provides a method for returning information about the collection of site templates on the virtual server. Following are the main methods provided by this service:
  • ExportWeb
  • ImportWeb
  • GetSiteTemplates
  • GetUpdatedFormDigest
14) Search Web Service (http://<site>/_vti_bin/search.asmx):
The QueryService can be used to query the search indexes in the same way that you would search from the home page of a SharePoint site. Main methods available in this service are as below:
  • Query
  • QueryEx
  • GetPortalSearchInfo
  • GetSearchMetadata
  • Registration
  • Status 
15) Users and Groups Web Service (http://<Site>/_vti_bin/usergroup.asmx):
The Users and Groups Web service provides methods for working with users, role definitions, and groups. It provides huge number of methods which are listed below:
  • AddGroup
  • AddGroupToRole
  • AddRole
  • AddRoleDef
  • AddUserCollectionToGroup
  • AddUserCollectionToRole
  • AddUserToGroup
  • AddUserToRole
  • GenerateXmlMappings 
  • GetAllUserCollectionFromWeb
  • GetGroupCollection
  • GetGroupCollectionFromRole
  • GetGroupCollectionFromSite
  • GetGroupCollectionFromUser
  • GetGroupCollectionFromWeb
  • GetGroupInfo
  • GetHashCode 
  • GetLifetimeService 
  • GetRoleCollection
  • GetRoleCollectionFromGroup
  • GetRoleCollectionFromUser
  • GetRoleCollectionFromWeb
  • GetRoleInfo
  • GetRolesAndPermissionsForCurrentUser
  • GetRolesAndPermissionsForSite
  • GetUserCollection
  • GetUserCollectionFromGroup
  • GetUserCollectionFromRole
  • GetUserCollectionFromSite
  • GetUserCollectionFromWeb
  • GetUserInfo
  • GetUserLoginFromEmail
  • RemoveGroup
  • RemoveGroupFromRole
  • RemoveRole
  • RemoveUserCollectionFromGroup
  • RemoveUserCollectionFromRole
  • RemoveUserCollectionFromSite
  • RemoveUserFromGroup
  • RemoveUserFromRole
  • RemoveUserFromSite
  • RemoveUserFromWeb
  • UpdateGroupInfo
  • UpdateRoleDefInfo
  • UpdateRoleInfo
  • UpdateUserInfo 
16) Versions Web Service (http://<site>/_vti_bin/Versions.asmx):
Versions Web service provides methods for working with file versions in SharePoint document libraries. Methods included in this service:
  • DeleteAllVersions 
  • DeleteVersion 
  • GetVersions 
  • RestoreVersion 
17) Views Web Service (http://<site>/_vti_bin/Views.asmx):
Views Web service provides methods for creating, deleting, or updating list views. Methods included in this service are as below:
  • AddView
  • DeleteView
  • GetView 
  • GetViewCollection 
  • GetViewHtml 
  • UpdateView 
  • UpdateViewHtml
18) Web Part Pages Web Service (http://<Site>/_vti_bin/WebPartPages.asmx):
Web Part Pages service provides methods for working with Web Parts. Following are the various methods provided by this service:
  • AddWebPart
  • AddWebPartToZone
  • AssociateWorkflowMarkup
  • ConvertWebPartFormat
  • DeleteWebPart
  • ExecuteProxyUpdates
  • FetchLegalWorkflowActions
  • GetCustomControlList
  • GetDataFromDataSourceControl
  • GetFormCapabilityFromDataSourceControl
  • GetWebPart
  • GetWebPart2
  • GetWebPartCrossPageCompatibility
  • GetWebPartPage
  • GetWebPartPageConnectionInfo
  • GetWebPartPageDocument
  • GetWebPartProperties
  • GetWebPartProperties2
  • GetXmlDataFromDataSource
  • RemoveWorkflowAssociation
  • RenderWebPartForEdit
  • SaveWebPart
  • SaveWebPart2
  • ValidateWorkflowMarkupAndCreateSupportObjects 
19) Webs Web Service (http://<Site>/_vti_bin/Webs.asmx):
Webs service provides methods for working with sites and subsites. Following are the various methods provided by this service:
  • CreateContentType
  • CustomizeCss
  • DeleteContentType
  • GetActivatedFeatures
  • GetAllSubWebCollection
  • GetColumns
  • GetContentType
  • GetContentTypes
  • GetCustomizedPageStatus
  • GetListTemplates
  • GetWeb
  • GetWebCollection
  • RemoveContentTypeXmlDocument
  • RevertAllFileContentStreams
  • RevertCss
  • RevertFileContentStream
  • UpdateColumns
  • UpdateContentType
  • UpdateContentTypeXmlDocument
  • WebUrlFromPageUrl

Monday, August 8, 2011

REST web services

WEB SERVICES IN SHREPOINT

Rest Web Service can be used for

1: To get the List Items: This is possible by using REST web service of SharePoint server. We can get all the list items in xml by giving list name as parameter in the URL.

Syntax: http ://< site name>/_vti_bin/listdata.svc/

Ex: http://sharepoint-webaddress/_vti_bin/listdata.svc/Expertise

2: To get the List in Sorted Order: List items can be sorted by using the following syntax: http:///_vti_bin/listdata.svc/?$orderby=Title desc, Name asc (returns List with Title in descending order and Name in ascending)

Sorting with “$orderby” keyword

Ex: http://sharepoint-webaddress/_vti_bin/listdata.svc/Expertise?$orderby=Title asc, Discipline desc

3: To Filter list item: List items can be filtered by using the following Syntax: http:///_vti_bin/listdata.svc/?$filter=Title eq 'Title_Name' (returns List with Title = 'Title_Name')

Ex: http://sharepoint-webaddress/_vti_bin/listdata.svc/Expertise?$filter=Title eq 'soft'

Filtering with “$filter” keyword in URL/Query string.

4: To retrieve items on page wise:

Syntax: http ://< site name>/_vti_bin/listdata.svc/? $skip=[n]&$top=[n]&$orderby=Title

The $skip and $top parameters are ideal for implementing a paging mechanism. The $skip=[n] parameter allows you to skip the first n options, the $top=[n] parameter allows you to return the next n items. Typically, you will use this in conjunction with the $orderby parameter (appended using the & (ampersand) symbol).

Ex: http://sharepoint-webaddress/_vti_bin/listdata.svc/Expertise? $skip=5&$top=1&$orderby=Title

5: To select specific column:

Syntax: http:///_vti_bin/listdata.svc/?$ select = ,,..

EX: http://sharepoint-webaddress/_vti_bin/listdata.svc/Expertise?$select = Title

Resource: http://www.lcbridge.nl/vision/2010/rest.htm

6: To limit on number of rows returned – In SharePoint, Site Collection Administrator can set the limit of number of rows returned & also programmers can override this value as per their requirements.

Resource: 1: http://msdn.microsoft.com/en-us/library/gg985387.aspx

2: https://willhlaw.wordpress.com/tag/sharepoint-2010/

Consuming REST Service with Linq in Visual Studio Application:

1) To consume a Restful web service in Visual Studio, you can go to the Data menu and click Add New Data Source.
2) In the Add Service Reference dialog, add the Url to a SharePoint 2010 web site.
3) Go to the Data menu again and this time, select Show data sources and select List
4) Add Reference

Using RestDemo.ServiceReference1;

Using System.Net;

Create a new class-level variable to hold the data context

TeamSiteDataContext context = new TeamSiteDataContext (new Uri(http://sp2010a/teamsite/_vti_bin/listdata.svc));

5) Next, in the Form_Load event, add the following two lines.

context.Credentials = CredentialCache.DefaultCredentials;

contactsBindingSource.DataSource = context.Contacts;

The first line will authenticate to SharePoint using your current logged-in account. Of course, other login methods are available. The second references the Contacts entity. The contactsBindingSource is an object automatically created by Visual Studio when you added the Contacts list to your form. The data source for the GridView automatically points to this data source.

We’ve seen above that REST allows you filter and sort. What if you wanted to be more efficient and filter and sort in application? You can and one way you can do this is with LINQ:

var q = from c in context.Contacts

where c.ID > 100

orderby c.FirstName

select new { c.FirstName, c.LastName, c.EMailAddress, c.BusinessPhone };

contactsBindingSource.DataSource = q;

Featured Posts

Kali Linux Remote Desktop: Access GNOME from Windows Using Native RDP

  Kali Linux + GNOME 50 + GNOME Remote Desktop + Windows Remote Desktop (MSTSC) Getting a full GNOME desktop remotely on Kali Linux can be ...