Home > Web Services > How to create item in SharePoint2010 document library using SharePoint Web service

How to create item in SharePoint2010 document library using SharePoint Web service

Today, I’d like to show you how to create item in SharePoint2010 document library using SharePoint Web service. Originally, I thought I could use the WebSvcLists(list.asmx) that provides methods for working with lists and list data. However, after a bit Googling , I realize that I need to use the WebSvcCopy (copy.asmx).Here are the code used

private const string siteUrl = "http://ybbest";

private static void Main(string[] args)

{

using (CopyWSProxyWrapper copyWSProxyWrapper = new CopyWSProxyWrapper(siteUrl))

{

copyWSProxyWrapper.UploadFile("TestDoc2.pdf",

new[] {string.Format("{0}/Shared Documents/TestDoc2.pdf", siteUrl)},

Resource.TestDoc, GetFieldInfos().ToArray());

}

}

private static List GetFieldInfos()

{

var fieldInfos = new List();

//The InternalName , DisplayName and FieldType are all required to make it work

fieldInfos.Add(new FieldInformation

{

InternalName = "Title",

Value = "TestDoc2.pdf",

DisplayName = "Title",

Type = FieldType.Text

});

return fieldInfos;

}

Note: When setting the metadata of the file(FieldInformation) , you need The InternalName , DisplayName and FieldType are all required to make it work

Here is the code for the proxy wrapper.


public class CopyWSProxyWrapper : IDisposable

{

private readonly string siteUrl;

public CopyWSProxyWrapper(string siteUrl)

{

this.siteUrl = siteUrl;

}

private readonly CopySoapClient proxy = new CopySoapClient();

public void UploadFile(string testdoc2Pdf, string[] destinationUrls, byte[] testDoc,

FieldInformation[] fieldInformations)

{

using (CopySoapClient proxy = new CopySoapClient())

{

proxy.Endpoint.Address = new EndpointAddress(String.Format("{0}/_vti_bin/copy.asmx", siteUrl));

proxy.ClientCredentials.Windows.ClientCredential = CredentialCache.DefaultNetworkCredentials;

proxy.ClientCredentials.Windows.AllowedImpersonationLevel =

TokenImpersonationLevel.Impersonation;

CopyResult[] copyResults = null;

try

{

proxy.CopyIntoItems(testdoc2Pdf,

destinationUrls,

fieldInformations, testDoc, out copyResults);

}

catch (Exception e)

{

System.Console.WriteLine(e);

}

if (copyResults != null) System.Console.WriteLine(copyResults[0].ErrorMessage);

System.Console.ReadLine();

}

}

public void Dispose()

{

proxy.Close();

}

}

You can download the source code here .

******Update**********

It seems to be a bug that , you can not set the contentType when create a document item using Copy.asmx. In sp2007 the field type was Choice, however, in sp2010 it is actually Computed. I have tried using the Computed field type with no luck. I have also tried sending the ContentTypeId and this does not work.

******Update 20/04/2012**********

I was wrong in my previous update about unable to set the contenttype.As jasonkuter  points out in the comment,You can set the contentType by using the following code

fieldInfos.Add(new FieldInformation { InternalName = "ContentTypeId", Value = "0x010100866B1423D33DDA4CA1A4639B54DD464200DED91C30FFF44647AFA0F99FA6F0E2D2", DisplayName = "Content Type ID", Type = FieldType.Text });

You can find the contenttype id by using the SharePoint manager.Note: the contenttype id is the id in the document library not the content type id you defined in the site collection level.You can download the updated sourcecode here.

References:

SharePoint 2010 Web Services

SharePoint2007 Web Services

SharePoint MSDN Forum

About these ads
  1. March 23, 2012 at 7:02 am

    This should work to update the contenttype in 2010:

    FieldInformation Type=”Text” DisplayName=”Content Type ID” InternalName=”ContentTypeId”

    • ybbest
      April 21, 2012 at 1:47 pm

      Thanks , it work for content type this way.

  2. Larry Wilkinson
    May 2, 2012 at 6:12 am

    Thanks, this worked for SP2010. Now I just need to find out how to get the ID programatically; when I do, I’ll post that also

  3. Larry Wilkinson
    May 2, 2012 at 6:31 am

    calling list service with request GetListContentTypes and pointing to desired library (listName parameter)returns all Content Types – content type id is one of the returned fields

  4. dan
    August 25, 2012 at 6:14 pm

    Cool article. I’m going to use this as part of a project I’m helping work on for a work mate of mine ;)

  5. Nicolas
    September 21, 2012 at 10:35 am

    Doesn’t work for me. Content type is always default…

    • ybbest
      September 21, 2012 at 10:39 am

      Note: the contenttype id is the id in the document library not the content type id you defined in the site collection level.

  6. Nicolas
    September 21, 2012 at 10:48 am

    Yes I know. I tried the two Ids (Content Type ID and List Content Type Id). Does not work for me…

  7. Nicolas
    September 21, 2012 at 10:55 am

    Does this need a particular version of SharePoint? (SP1, hotfix etc..)

    • ybbest
      September 21, 2012 at 11:01 am

      I do not think so as it is working in sp2007 too, can you try this updated solution https://www.box.com/s/d197d13324c04e756cf1 . As I refactored the code to read the contentType id by another web servers.

  8. Nicolas
    September 21, 2012 at 6:58 pm

    Hello,

    Thanks for your help and very quick answer.
    Just tried your code and same problem. Always Fruit document is applied (default content type).
    So I suspect a version difference. I use SharePoint Server 2010 RTM 14.0.4763.1000.

  9. mahesh
    November 4, 2013 at 10:57 pm

    hi i have tried the above code i am getting the error.
    i am trying to store document in document library of office365online,
    i am getting exception at this line
    proxy.CopyIntoItems(testdoc2Pdf,destinationUrls,fieldInformations, testDoc, out copyResults);
    please can anybody tell what is this error.
    Thanking you in Advance
    Mahesh

  10. November 20, 2013 at 1:43 am

    Hi,
    Thanks great post,it help ful for me..
    I have tried above code
    my requirement is to upload the document from asp.net to office365 online site,i have tried your code to deploy to office365 Document library.
    But i am getting an error like dis can you please look into this,its urgent for me please
    I have been working/googling about this task sice 2 weeks but i am not getting
    i am new to office365 online i dont know anyting please can u explain me what is this error
    and y i am getting this error.

    Error:

    System.ServiceModel.ProtocolException: The content type text/html; charset=utf-8
    of the response message does not match the content type of the binding (text/xm
    l; charset=utf-8). If using a custom encoder, be sure that the IsContentTypeSupp
    orted method is implemented properly. The first 797 bytes of the response were:

    BODY { color: #000000; background-color: white; font-family: Ver
    dana; margin-left: 0px; margin-top: 0px; }
    #content { margin-left: 30px; font-size: .70em; padding-bottom:
    2em; }
    A:link { color: #336699; font-weight: bold; text-decoration: und
    erline; }
    A:visited { color: #6699cc; font-weight: bold; text-decoration:
    underline; }
    A:active { color: #336699; font-weight: bold; text-decoration: u
    nderline; }
    A:hover { color: cc3300; font-weight: bold; text-decoration: und
    erline; }
    P { color: #000000; margin-top: 0px; margin-bottom: 12px; font-f
    amily: Verdana; }
    pre { background-color: #e5e5cc; padding: 5px; font-family: Cour
    ier New; font’.

    Server stack trace:
    at System.ServiceModel.Channels.HttpChannelUtilities.ValidateRequestReplyResp
    onse(HttpWebRequest request, HttpWebResponse response, HttpChannelFactory factor
    y, WebException responseException, ChannelBinding channelBinding)
    at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpCha
    nnelRequest.WaitForReply(TimeSpan timeout)
    at System.ServiceModel.Channels.RequestChannel.Request(Message message, TimeS
    pan timeout)
    at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message messag
    e, TimeSpan timeout)
    at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean on
    eway, ProxyOperationRuntime operation, Object[] ins, Object[] outs, TimeSpan tim
    eout)
    at System.ServiceModel.Channels.ServiceChannel.Call(String action, Boolean on
    eway, ProxyOperationRuntime operation, Object[] ins, Object[] outs)
    at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCall
    Message methodCall, ProxyOperationRuntime operation)
    at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage message)

    Exception rethrown at [0]:
    at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage req
    Msg, IMessage retMsg)
    at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData& msgDa
    ta, Int32 type)
    at YBBEST.CreateDocumentItem.CopyWS.CopySoap.CopyIntoItems(CopyIntoItemsReque
    st request)
    at YBBEST.CreateDocumentItem.CopyWS.CopySoapClient.YBBEST.CreateDocumentItem.
    CopyWS.CopySoap.CopyIntoItems(CopyIntoItemsRequest request) in e:\systemdrivers\
    YBBEST.CreateDocumentItem\YBBEST.CreateDocumentItem\Service References\CopyWS\Re
    ference.cs:line 421
    at YBBEST.CreateDocumentItem.CopyWS.CopySoapClient.CopyIntoItems(String Sourc
    eUrl, String[] DestinationUrls, FieldInformation[] Fields, Byte[] Stream, CopyRe
    sult[]& Results) in e:\systemdrivers\YBBEST.CreateDocumentItem\YBBEST.CreateDocu
    mentItem\Service References\CopyWS\Reference.cs:line 430
    at YBBEST.CreateDocumentItem.CopyWSProxyWrapper.UploadFile(String sourceUrl,
    String[] destinationUrls, Byte[] documentBytes, FieldInformation[] fileMetadata)
    in e:\systemdrivers\YBBEST.CreateDocumentItem\YBBEST.CreateDocumentItem\CopyWSP
    roxyWrapper.cs:line 34
    File TestDoc2.pdf has successfully been uploaded to the document library

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

Follow

Get every new post delivered to your Inbox.

Join 162 other followers

%d bloggers like this: