WebHosting

Tuesday, November 8, 2011

Get Full or Relative Url of web using Javascript Client Side


var context = new SP.ClientContext();
var relativeWebUrl = context.get_url();
Remember the get_url method will only return relative url of the site. As shown in the following table:
Site Collection UrlSite Urlcontext.get_url() response
http://site.comhttp://site.com/
http://mysite.comhttp://site.com/site1/site1
http://site.com/siteshttp://site.com/sites/site1/sites/site


function getFullWebUrl() {
    var context = new SP.ClientContext();
    var relativeWebUrl = context.get_url();
    var fullWebUrl = window.location.protocol + '//' + window.location.host + relativeWebUrl ;
    alert(fullWebUrl);
}

SharePoint Designer workflow: Move a document from one library to another


Moving a document using a SharePoint Designer workflow involves copying the document to the SharePoint document library you want to move the document to, and then deleting the document from the current document library it is in.
You can use the Copy List Item action to copy the document and the Delete itemaction to delete the document.
To create a SharePoint Designer workflow that can move a document from one document library to another:
  1. In SharePoint Designer 2007, open the SharePoint site on which the document library that contains the documents to move is located, and create a new SharePoint Designer workflow.
  2. On the Define your new workflow screen of the Workflow Designer, enter a name for the workflow, select the document library you want to attach the workflow to (this would be a document library containing documents to move), select Allow this workflow to be manually started from an item, and click Next.
  3. On the Step 1 screen of the Workflow Designer, click Actions, and then click More Actionsfrom the drop-down menu.
  4. On the Workflow Actions dialog box, select List Actions from the category drop-down list box, select Copy List Item from the actions list, and click Add. The following text is added to theWorkflow Designer:
    Copy item in this list to this list
  5. On the Step 1 screen of the Workflow Designer, click the first this list (representing the document library to copy the document from) in the text of the Copy List Item action.
  6. On the Choose List Item dialog box, leave Current Item selected, and click OK.
  7. On the Step 1 screen of the Workflow Designer, click the second this list (representing the document library to copy the document to) in the text of the Copy List Item action, and select the document library (this is the document library to where you want to move the document) from the drop-down list box that appears.
  8. On the Step 1 screen of the Workflow Designer, click Actions, and then click More Actionsfrom the drop-down menu.
  9. On the Workflow Actions dialog box, select List Actions from the category drop-down list box, select Delete Item from the actions list, and click Add. The following text is added to theWorkflow Designer:
    then Delete item in this list
  10. On the Step 1 screen of the Workflow Designer, click this list in the text of the Delete Itemaction.
  11. On the Choose List Item dialog box, leave Current Item selected and click OK. The final text for the workflow should now look like:
    Copy item in DocLib1 to DocLib2
      then Delete item in DocLib1

    where DocLib1 is the SharePoint document library containing the document to move andDocLib2 the document library to move the document to.
  12. On the Step 1 screen of the Workflow Designer, click Finish.

Testing the workflow

  1. Go to the SharePoint document library to which you attached the workflow, click on a document, and select Workflows from the drop-down menu.
  2. On the Workflows page, click the name of your SharePoint Designer workflow.
  3. On the workflow initiation page, click Start.
When the workflow completes, the document should have moved from the first SharePoint document library to the second document library.

Delete Attached File From ListItem


public void DeleteAttachedFileFromListItem(string siteUrl, string webName, int itemId, string attachmentFileName, string listName)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        //http://siteurl/lists/[listname]/attachments/[itemid]/[filename]
        string attachmentPath = string.Format("/{0}/lists/{1}/Attachments/{2}/{3}", webName, listName, itemId, Path.GetFileName(attachmentFileName));
        var file = clientContext.Web.GetFileByServerRelativeUrl(attachmentPath);
        file.DeleteObject();
        clientContext.ExecuteQuery();
    }
}

Download File from ListItem


public void DownloadAttachedFileFromListItem
( 
string siteUrl,  
string webName,  
int itemId,  
string attachmentName,  
string listName,  
string downloadLocation
)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        string attachmentPath = string.Format("/{0}/lists/{1}/Attachments/{2}/{3}"
webName, listName, itemId, Path.GetFileName(attachmentName));
        var fileInformation = File.OpenBinaryDirect(clientContext, attachmentPath);
        IList<byte> content = new List<byte>();
        int b;
        while ((b = fileInformation.Stream.ReadByte()) != -1)
        {
            content.Add((byte)b);
        }
        var downloadFileName = Path.Combine(downloadLocation, attachmentName);
        System.IO.File.WriteAllBytes(downloadFileName, content.ToArray());
        fileInformation.Stream.Close();
    }
}

Attach File to ListItem


public void AttachFileToListItem
(
string siteUrl,  
string webName, 
string listName,  
int itemId,  
string fileName, 
bool overwrite)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        FileStream fileStream = new FileStream(fileName, FileMode.Open);
        string attachmentPath = string.Format("/{0}/Lists/{1}/Attachments/{2}/{3}"
webName, listName, itemId, Path.GetFileName(fileName));
        File.SaveBinaryDirect(clientContext, attachmentPath, fileStream, overwrite);
    }
}

Delete File From Library


public void DeleteFileFormLibrary(string siteUrl, string webName, string listName, string subfolder, string attachmentFileName)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        string attachmentPath = string.Empty;
        if (string.IsNullOrEmpty(subfolder))
        {
            attachmentPath = string.Format("/{0}/{1}/{2}", webName, listName, Path.GetFileName(attachmentFileName));
        }
        else
        {
            attachmentPath = string.Format("/{0}/{1}/{2}/{3}", webName, listName, subfolder, Path.GetFileName(attachmentFileName));
        }
        var file = clientContext.Web.GetFileByServerRelativeUrl(attachmentPath);
        file.DeleteObject();
        clientContext.ExecuteQuery();
    }
}

Download File From Library


public void DownloadFileFromLibrary(string siteUrl, string webName, string libraryName, string subfolderPath, string fileName, string downloadPath)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {
        string filePath = string.Empty;
        if (!string.IsNullOrEmpty(subfolderPath))
        {
            filePath = string.Format("/{0}/{1}/{2}/{3}", webName, libraryName, subfolderPath, fileName);
        }
        else
        {
            filePath = string.Format("/{0}/{1}/{2}", webName, subfolderPath, fileName);
        }

        var fileInformation = File.OpenBinaryDirect(clientContext, filePath);
        var stream = fileInformation.Stream;
        IList<byte> content = new List<byte>();
        int b;
        while ((b = fileInformation.Stream.ReadByte()) != -1)
        {
            content.Add((byte)b);
        }
        var downloadFileName = Path.Combine(downloadPath, fileName);
        System.IO.File.WriteAllBytes(downloadFileName, content.ToArray());
        fileInformation.Stream.Close();
    }
}

SharePoint Upload File in Library


public void UploadFileInLibrary(string siteUrl, string webName, string libraryName, string subfolderPath, string fileName)
{
    using (ClientContext clientContext = new ClientContext(siteUrl))
    {

        string uploadLocation = Path.GetFileName(fileName);
        if (!string.IsNullOrEmpty(subfolderPath))
        {
            uploadLocation = string.Format("{0}/{1}", subfolderPath, uploadLocation);
        }
        uploadLocation = string.Format("/{0}/{1}/{2}", webName, libraryName, uploadLocation);
        var list = clientContext.Web.Lists.GetByTitle(libraryName);
        var fileCreationInformation = new FileCreationInformation();
        fileCreationInformation.Content = System.IO.File.ReadAllBytes(fileName);
        fileCreationInformation.Overwrite = true;
        fileCreationInformation.Url = uploadLocation;
        list.RootFolder.Files.Add(fileCreationInformation);
        clientContext.ExecuteQuery();
    }
}

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

Featured Posts

किसके हिस्से में में ये धरती

चिड़ियों का घर जल रहा है  इंसान खुश है कि ये आग दूर है अभी कभी तो आएगी घर तक  तेरा भी घर जलेगा कभी बेजुबान है कुछ बोलते नहीं है दिल में दुख ...