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

Friday, July 8, 2011

Remove all survey response from web service

Well I ran into a trouble when I needed to remove all responses from survey. It is far easy to remove all items from the list when you have the permission to access the UI. However when it even comes to the survey responses, there is a big problem. There is no way to edit response in data sheet. Only way is to go to the content and structure in site settings, locate the survey list and then increase the limit to 1000 items and keep deleting in the bunch of 1000 items.

Again the problem is what if you have got more than 50,000 responses. You will end up spending hours removing 1000 items 50 times. This is definitely something which is not worth doing.

Read following posts and you will also come to know about some other stuff.

Delete List Item using web service


Remove all response from SharePoint survey

You can treat this post as continuation of above links.

In this post, I am going to show you a way to remove all responses from survey with the help of web service. Yes web service has come to a rescue as far as removing all responses from survey is concern.

I am writing one function and on button click I am calling that function. Take a list reference from the SharePoint URL interest of you and then start wiring up below code.


public static ArrayList GetListIDs(String ListName)
{
Lists.Lists ListReference = new Lists.Lists();
ListReference.Credentials = System.Net.CredentialCache.DefaultCredentials;
ListReference.Url =
"web site url/_vti_bin/Lists.asmx";

XmlDocument xmlDoc = new System.Xml.XmlDocument();

XmlNode ndViewFields =
xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
ndViewFields.InnerXml = "<FieldRef Name='ID' />";

XmlNode ndListItems =
ListReference.GetListItems(ListName, null, null,
ndViewFields, "20000", null, null);

//convert String to XMLReader
XmlReaderSettings readersettings = new XmlReaderSettings();
readersettings.ConformanceLevel = ConformanceLevel.Fragment;
readersettings.IgnoreWhitespace = true;
readersettings.IgnoreComments = true;
XmlReader xmlreader =
XmlReader.Create(new StringReader(ndListItems.OuterXml), readersettings);

ArrayList lstID = new ArrayList();

while (xmlreader.Read())
{
if (xmlreader.Name == "z:row")
lstID.Add(xmlreader.GetAttribute("ows_ID").ToString());
}

return lstID;
}




Above function is used to get All IDs of items that are there in the survey. Remember 20000 is the item limit, increase this number as many items as you would like to return.


public static void DeleteItems(String ListName, ArrayList lstID)
{
try
{
Lists.Lists ListReference = new Lists.Lists();
ListReference.Credentials = System.Net.CredentialCache.DefaultCredentials;
ListReference.Timeout = 300000;
ListReference.Url =
" web site url/_vti_bin/Lists.asmx ";


string strBatch = "";

foreach (String ID in lstID)
{
strBatch += "<Method ID='1' Cmd='Delete'><Field Name='ID'>" + ID + "</Field></Method>";
}

XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlElement elBatch = xmlDoc.CreateElement("Batch");

elBatch.InnerXml = strBatch;

ListReference.UpdateListItems(ListName, elBatch);
}
catch (Exception ex)
{
throw ex;
}
}




And above code takes those IDs as a reference and deletes them from the list. The above code may not be the perfect way to do this job but it certainly better than one approach which is looping through 1 to 50000 items and delete one by one. Rather mentioned approach is better to construct a string and then pass that entire string as a one single batch to perform the operation.

Just take care that you need to increase the time out property based on the number of items that you have. Otherwise you may get a server timeout exception.

Hope this helps.

Tuesday, June 28, 2011

Delete List Item using web service

We might need this when you want to remove any list item from the list but from remote location, from other client.

Well, here is a simple way to do it. I am just taking an example of client server application button click. Code remains same where ever you want to use it.

Take the web service reference into your project from the SharePoint site.



protected void Button1_Click(object sender, EventArgs e)
{
Lists.Lists ListReference = new Lists.Lists();

ListReference.Credentials = System.Net.CredentialCache.DefaultCredentials;

ListReference.Url = "site_url/_vti_bin/Lists.asmx";

try
{

System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

elBatch.SetAttribute("OnError", "Continue");
elBatch.SetAttribute("ListVersion", "1");

string strBatch = "<Method ID='1' Cmd='Delete'>" +
"<Field Name='ID'>" + "4" + "</Field></Method>";

elBatch.InnerXml = strBatch;
ListReference.UpdateListItems("List Name", elBatch);


}
catch (Exception ex)
{
Response.Write(ex.Message);

}
}


All we need to do is include the ID in the query. In our case, we are deleting item with the ID 4. ID is the item ID that you want to delete from the list.

Read Remove all survey response from web service for some interesting stuff.

Tuesday, December 21, 2010

Create folders in document librrary using web service

Hi All,

A very simple requirement of creating folder in the document library using web service comes many a times. So here is a simple three liner example that creates a folder in the document library.

All you need to do is add reference to the _vti_bin/DWS.asmx. Document workspace is the web service that manages all related to document workspace or even creating folder in normal team site document libraries.

DWorkSpace is webservice instance reference name.

DWorkSpace.Dws dwspace = new DWorkSpace.Dws();
dwspace.Credentials = System.Net.CredentialCache.DefaultCredentials;
dwspace.Url = "{your_site}/_vti_bin/DWS.asmx";
dwspace.CreateFolder("Shared Documents/DemoFolder");

That is it. You have just created DemoFolder inside Shared Documents library of your site url.

Tuesday, December 14, 2010

Updating list to be on quick launch through web service

Hi All,

We all know that we can create SharePoint list or library from web service provided by SharePoint web services. However there are no full blown functionalities in it which can be achieved so easily from object model.

So basic question that comes in when we create a list or library from web service, there is no direct way to set it up to show in the quick launch bar.

So here is a sample code which shows how to create a list, how to add fields in it and how to display that list in the quick launch from web service.

So here we will get to know three things although two of them are covered separately in earlier posts.

WebListsService.Lists listService = new WebListsService.Lists();

listService.Credentials = System.Net.CredentialCache.DefaultCredentials;

listService.Url = "{list_asmx_url}";

XmlNode xnNewLists = listService.AddList("Products", "This is products list created by web service", 100);
XmlDocument xmlDoc = new XmlDocument();
XmlNode xnNewFields = xmlDoc.CreateNode(XmlNodeType.Element, "Fields", "");

xnNewFields.InnerXml +=
"<Method ID='1'>" +
"<Field Type='Text' Title='ProductName' DisplayName = 'Product Name' Required='TRUE' Description = 'Name of the Product'/>" +
"</Method>";
xnNewFields.InnerXml +=
"<Method ID='2'>" +
"<Field Type='Text' DisplayName='Price'/>" +
"</Method>";
xnNewFields.InnerXml +=
"<Method ID='3'>" +
"<Field Type='Number' DisplayName='Product Code'/>" +
"</Method>";

XmlNode xnProperties = xmlDoc.CreateNode(XmlNodeType.Element, "List", "");
XmlAttribute xnQuickLaunchAttribute = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "OnQuickLaunch", "");
xnQuickLaunchAttribute.Value = "True";
xnProperties.Attributes.Append(xnQuickLaunchAttribute);

XmlAttribute xnEnableversioningAttribute = (XmlAttribute)xmlDoc.CreateNode(XmlNodeType.Attribute, "EnableVersioning", "");
xnEnableversioningAttribute.Value = "True";
xnProperties.Attributes.Append(xnEnableversioningAttribute);

XmlNode updateList = listService.UpdateList("Products", xnProperties, xnNewFields, null, null, null);

And that's it. your job is done. your list or library is now on quick launch through web service.

Wednesday, May 26, 2010

Download attachments from list item using web service

Hi All,

In this post, I will show you the way how to get the list attachments using SharePoint web services. There can be one or more attachment attached to the list item of any list in the site.

For example, I have one Dummy List in the site and I have one list item with two attachments. See the figure below.



Now write down the following code. DownloadListItems is the lists.asmx web service of SharePoint. Change the site url reference for your code.

private void button8_Click(object sender, EventArgs e)
{
DownloadListItems.Lists objLists = new EncryptAndDecrypt.DownloadListItems.Lists();

objLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

objLists.Url = "{site-url}/_vti_bin/lists.asmx";

XmlNode node = objLists.GetAttachmentCollection("DummyList", "7");

DataSet ds = new DataSet();
using (XmlNodeReader reader = new XmlNodeReader(node))
{
ds.ReadXml(reader);
}


DataTable dtAttachment = ds.Tables[0];

for (int iCnt = 0; iCnt <= dtAttachment.Rows.Count - 1; iCnt++)
{
string sourceUrl = Convert.ToString(dtAttachment.Rows[iCnt]["Attachment_Text"]);

int strLastIndx = sourceUrl.LastIndexOf(@"/");

string FileName = sourceUrl.Substring(strLastIndx + 1);


using (WebClient client = new WebClient())
{
client.UseDefaultCredentials = true;
byte[] response = client.DownloadData(sourceUrl);

FileStream fStream = new FileStream(@"C:\DummyListAttachments\" + FileName, FileMode.Create, FileAccess.ReadWrite);
fStream.Write(response, 0, response.Length);
fStream.Close();

}


}


}


As you can see first we have taken the reference of the Lists.asmx service and then passed the credentials. Change it to your credentials according to your need. Then we called getattachmentcollection method, and simple got the attachments in the form of XMLNode.

We actually get path only, not the real attachments. For simplicity I have converted that XMlnode into to data table so that we get the Attachment table and attachment_xml column with values as direct path to the attachment with complete URL of the site.



And then finally we use WebClient method to pull those documents to our local drive.

Very simple and easy way to get the attachments from list item. What say?

Monday, May 24, 2010

Attach file to list item programmatically using web service

Hi All,

In SharePoint if we want to attach a file to any existing list item and we are in any other asp.net or client / server application or just any other console application, then we can use SharePoint web services to attach a file to existing list item.

Here is a sample code to attach a file to existing list item.

Write down the below code and you are good to go. Just see the argument of addattachment method of lists.asmx web service. In my case, I am attaching my file to item which has ID 7.

See image before running this code.



private void button7_Click(object sender, EventArgs e)
{
string strFilePath= textBox1.Text;

if (!File.Exists(strFilePath))
{
throw new ArgumentException(String.Format("{0} does not exist",
strFilePath), "srcUrl");
}

FileStream Stream = File.OpenRead(strFilePath);
string fileName = Stream.Name.Substring(3);
byte[] contents = new byte[Stream.Length];
Stream.Read(contents, 0, (int)Stream.Length);
Stream.Close();


DownloadListItems.Lists objLists = new EncryptAndDecrypt.DownloadListItems.Lists();

objLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

objLists.Url = "{site url}/_vti_bin/lists.asmx";

try
{
string addAttach = objLists.AddAttachment("DummyList", "7", fileName, contents);

}

catch (System.Web.Services.Protocols.SoapException ex)
{

}


}


See below image after running above code.



That is it. you have just attached your file to the existing list item.

Wednesday, May 12, 2010

Adding list item to List using web service

Hi All,

In this post, I will show you how to add list item to the list using SharePoint web service.

I am writing a code in Windows Application and I have taken reference of Lists.asmx of respective site.

I have DummyList as list in my site and in that I have three columns. Name of the columns are title, group which is Choice column (GroupA,groupB,groupC) and Price which is number.

private void button6_Click(object sender, EventArgs e)
{
string strQuery = "<Method ID='1' Cmd='New'>" +
"<Field Name='Title'>" + "Title Test" + "</Field>" +
"<Field Name='Price'>" + 12000 + "</Field>" +
"<Field Name='Group'>" + "GroupB" + "</Field></Method>";

DownloadListItems.Lists objLists = new EncryptAndDecrypt.DownloadListItems.Lists();

objLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

objLists.Url = "{site url}/_vti_bin/lists.asmx";

String listName = "DummyList";

XmlDocument xmlDoc = new System.Xml.XmlDocument();

System.Xml.XmlElement elBatch = xmlDoc.CreateElement("Batch");

elBatch.SetAttribute("OnError", "Continue");

elBatch.SetAttribute("ListVersion", "1");

elBatch.InnerXml = strQuery;

XmlNode ndReturn = objLists.UpdateListItems(listName, elBatch);

string result = ndReturn.OuterXml.ToString();


}


Just make sure that you pass proper credentials to the web service. Rest the code itself is self explanatory.

Just observe the result string above, and see ErrorCode element in it, it should be 0x00000000. If it is, then it is a success, else there is some error and item has not been added.

That is it. You have just added list item using web service.


------Modified on 21-05-2010-----------

Let us explore bit more on the same post. We will now add lookup field through web service. Yes, this is bit different than adding the simple field using web service.

We will take the same example as we show above.

I have made a little change in the list settings. I removed the Group column and recreated the same with lookup column to another list with same values. I have another list which has GroupA, GroupB and GroupC as title values in it. And then in DummyList I’ve created that lookup field.

So now let us move on. There are two ways you can insert lookup field through web service. Either you can mention in Field tag that this is the lookup field or you can directly reference that look up value by mentioning; # sign in between.

Below are the examples that describe both the ways.

1) "<Field Name='Group' Type='Lookup'>" + 2 + "</Field></Method>";

2) "<Field Name='Group'>" + "2;#GroupB" + "</Field></Method>";


Where first is mentioning field is lookup and second mentioning ID + ItemName in it. ID is the ID for the item in master list from which we have taken the reference. In my case GroupB’s ID in master list is two.

Modify the above code and then let’s run this sample now. See the result. Make sure that if anything is wrong, observe the result and in that check the ErrorCode element, you will see some error code in that. If there is not error, then as I mentioned earlier it will return you 0x00000000.

One interesting fact is, I don’t know how accurate this is but even in second way, you write like “2;#GoupC”, then also it will insert GroupB as it takes ID as the main value. Does it mean that we can specify any value after ;# sign as far as that value is present in the master list and that will not impact on what you want to insert??

Humm..interesting. I recommend make sure to query your master list with lookup value and get the ID and then combince that ID + “;#” + value and thenuse it in this method to populate your list lookup column.


I'll keep you all posted on what's more with List Item using SharePoint web service.

Monday, May 10, 2010

Upload document to document library using web service

Hi All,

Today we will see how to upload document to the document library using its web services. May times we need this feature from any ASP.NET application or just any other java application to upload document to the document library.

That is why SharePoint web services come into the picture.

Here is a simple way you can upload the document.

I have one windows application created and for demo purpose, I am writing a code directly in button click event.

You need to reference copy.aspx web service. Here DownLoadSharePointDocument is the name of web reference name.

private void button5_Click(object sender, EventArgs e)
{
DownloadSharePointDocument.Copy copyService = new EncryptAndDecrypt.DownloadSharePointDocument.Copy();

copyService.Url = "{url}/" + "_vti_bin/copy.asmx";

copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

string[] DestinationUrl = (“url goes here” };
string strSource = @"C:\SmartSurvey.pdf";


DownloadSharePointDocument.CopyResult FirstResult = new DownloadSharePointDocument.CopyResult();
DownloadSharePointDocument.CopyResult SecondResult = new DownloadSharePointDocument.CopyResult();
DownloadSharePointDocument.CopyResult[] ArrayOfResult = { FirstResult, SecondResult };
DownloadSharePointDocument.FieldInformation fFiledInfo = new DownloadSharePointDocument.FieldInformation();
fFiledInfo.DisplayName = "Description";
fFiledInfo.Type = DownloadSharePointDocument.FieldType.Text;
fFiledInfo.Value = "This is the test description";
DownloadSharePointDocument.FieldInformation[] fFiledInfoArray = { fFiledInfo };

FileStream objStream = new FileStream(strSource, FileMode.Open, FileAccess.Read);
byte[] Contents = new Byte[objStream.Length];
byte[] r = new Byte[objStream.Length];
int Read= objStream.Read(Contents, 0, Convert.ToInt32(objStream.Length));
objStream.Close();

uint copyresult = copyService.CopyIntoItems(strSource, DestinationUrl, fFiledInfoArray, Contents, out ArrayOfResult);

}


Make sure that you pass proper administrative credentials while passing the network credentials.

return value of uint should be zero to indicate a success. if it is not zero, then something is wrong and document will not upload successfully.

That is it. You have just uploaded the document to the document library.

Friday, May 7, 2010

Download all documents recursively from document library using web service

Hi All,

A SharePoint web service is such a fantastic mean of providing a value to the non SharePoint using applications.

When in any ASP.Net or just any other application needs to use SharePoint library or any other feature, they can use SharePoint web services. And classic example and a common requirement are to download al documents in all folders recursively using web services.

Well, how difficult it is? Answer is that the question is wrong. Ask how easy it is? Well, very easy.

Just take the reference of SharePoint Web Service that you want to work with.

Just for the demo, I have created windows application and used a Lists.asmx web services to pull all documents from all folders within document library.

Here is a simple code for this. On one button click I am copying all files from document library. Just make sure that you change appropriate URL of your site. Also make sure if it is the sub site, then your lists.asmx should point till the sub site path. That means {subsite url} + “/vti_bin/Lists.asmx”;

private void button3_Click(object sender, EventArgs e)
{
XmlDocument xmldoc = new System.Xml.XmlDocument();

string URL = "";

string FileName = "";

DownloadListItems.Lists objLists = new EncryptAndDecrypt.DownloadListItems.Lists();

objLists.Credentials = System.Net.CredentialCache.DefaultCredentials;

objLists.Url = "{siteurl}/_vti_bin/lists.asmx";

XmlDocument xmlDoc = new System.Xml.XmlDocument();

XmlNode xmlQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");

XmlNode xmlViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");

XmlNode xmlQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");

xmlQueryOptions.InnerXml = "<ViewAttributes Scope='RecursiveAll' IncludeRootFolder='True' />";

xmlViewFields.InnerXml = "";

xmlQuery.InnerXml = "";

try
{

XmlNode xmlListItems = objLists.GetListItems("Shared Documents", null, xmlQuery, xmlViewFields, null, xmlQueryOptions, null); //change the document library name to your document library

XmlNodeList oNodes = xmlListItems.ChildNodes;

foreach (XmlNode node in oNodes)
{
XmlNodeReader Reader = new XmlNodeReader(node);

while (Reader.Read())
{
if (Reader["ows_EncodedAbsUrl"] != null && Reader["ows_LinkFilename"] != null)
{
URL = Reader["ows_EncodedAbsUrl"].ToString();

FileName = Reader["ows_LinkFilename"].ToString();

CopyAndSaveAttachment(URL, FileName);
}

}

}

Console.ReadLine();
}

catch (System.Web.Services.Protocols.SoapException ex)
{
throw ex;
}

}



public static void CopyAndSaveAttachment(string URL, string FileName)
{

HttpWebRequest request;

HttpWebResponse response = null;

try
{

request = (HttpWebRequest)WebRequest.Create(URL);

request.Credentials = System.Net.CredentialCache.DefaultCredentials;

request.Timeout = 10000;

request.AllowWriteStreamBuffering = false;

response = (HttpWebResponse)request.GetResponse();

Stream s = response.GetResponseStream();

//Write to disk

FileStream fs = new FileStream(@"C:\DownLoads\" + FileName, FileMode.Create);

byte[] read = new byte[4096];

int count = s.Read(read, 0, read.Length);

while (count > 0)
{

fs.Write(read, 0, count);

count = s.Read(read, 0, read.Length);

}

//Close everything

fs.Close();

s.Close();

response.Close();

}

catch (Exception ex)
{
throw ex;

}

}



That is it. You are done with downloading all documents from document library recursively.

Wednesday, May 5, 2010

Download document from SharePoint library using web service

Hi All,

Many times we come across to a situation where in we need to download the document, PowerPoint files, excel files or just any other file from SharePoint.

However we are not on the server or let’s say we need to show those documents in some ASP.Net application and show their content on some ASP.Net page.

At that time we need to use the web service provided by SharePoint and then we are able to download any document from any document library in the site.

Following is the simple code that you need to write to pull the document to your local machine.

First add the web reference and then add URL of your SharePoint server + “_vti_bin/copy.asmx"”.

Then give it a proper name, so that you can reference in the code.

Then write down simple code shown below. In this example I am downloading simple ppts file from SharePoint server and copying it in C drive. I am passing default credential as I am in the same domain connected with windows authentication. However if you are not connected, then pass the user name and password of administrator who has a permission over the site.

Here DownloadSharePointDocument is the name of my web reference proxy class.

DownloadSharePointDocument.Copy copyService = new EncryptAndDecrypt.DownloadSharePointDocument.Copy();

copyService.Url = "https://intranet.eclipsnet.com/" + "_vti_bin/copy.asmx";

copyService.Credentials = System.Net.CredentialCache.DefaultCredentials;

string sourceUrl = “{server url} + {document lib name} + {file name}”;
string destinationUrl = @"C:\\Downloaded.ppsx"; // location where file to be downloaded

DownloadSharePointDocument.FieldInformation fieldInfo = new DownloadSharePointDocument.FieldInformation();

DownloadSharePointDocument.FieldInformation[] fieldInfoArray = { fieldInfo };
DownloadSharePointDocument.CopyResult cResult1 = new DownloadSharePointDocument.CopyResult();
DownloadSharePointDocument.CopyResult cResult2 = new DownloadSharePointDocument.CopyResult();
DownloadSharePointDocument.CopyResult[] cResultArray = { cResult1, cResult2 };

byte[] fileContents = new Byte[4096];
copyService.GetItem(sourceUrl, out fieldInfoArray, out fileContents);
FileStream fStream = new FileStream(destinationUrl, FileMode.Create, FileAccess.ReadWrite);
fStream.Write(fileContents, 0, fileContents.Length);
fStream.Close();


That is it. now you have the document in your machine.

Tuesday, March 23, 2010

Consuming web service in workflow

Hi All,

Workflow gives us very decent and useful activity for fetching web service from your local computer, network or even from internet.

Let’s us directly dive in to the way how we can achieve calling web service from the workflow. We do not have to write any custom activity or write some code to call web service method. All is given by the built in activity called Invoke web service.

To demonstrate the example here, I have created one small ASP.Net web service project which calculates the square root for the given number. Now I know. This is not something very useful in real world. As I said earlier as well, that I believe in giving simple example and then leave user to play with complex example. Most welcome for any query.

The moment you drop the Invoke Web Service activity on designer surface, it opens up the window asking you for the web service URL, it is very similar to what you see when you add web reference in normal ASP.NeT project.

I have web service in my own machine so I chose find in machine option, if you have to use any of the service residing anywhere in the world, give that as a URL and fetch the web service.

Workflow does all the work for you for creating proxy class ready for you to use and call the methods.

(You can take console workflow as test project here)

Interesting part of this activity is, it knows about the parameter binding. Now there can be one or more parameters for the specific method. Now I have default Helloworld method and my own method called GetSquareRoot which takes parameter of type double.

Moment you are done with setting the web reference with your web service, you can see the red circle error showing you that the MethodName is not set. Hence we are going to go ahead and set the MethodName to my own method.





Now as you can see we have been asked for setting the number value which is the parameter for the GetQuareRoot method. Also notice return value at the top in property window. There has to be a return value after calculating the square root. So go ahead and click on each one of them and bind it to new properties.

Just make sure that you create properties, not fields.





Now go ahead and add two more code activities. One before invokewebservice activity and one after that as shown in figure below.



Double click on Code Activity1 and write following code. Here we are setting the value of our input parameter that we have given as input to the method.

private void codeActivity1_ExecuteCode_1(object sender, EventArgs e)
{
this.InputNumber = 49;
}


And then double click on Code Activity2 and write following code. Here we are fetching the value from the web service and storing the result of the return value from web service method and then writing a simple statement so that we can come to know the output.

private void codeActivity2_ExecuteCode(object sender, EventArgs e)
{
Console.WriteLine("Square root of " + this.InputNumber + " is : " + this.ReturnNumber);
Console.Read();

}


See the result. In this way we have now consumed web service from the workflow with the help of very helpful InvokeWebservice activity.

Friday, February 6, 2009

Geting SharePoint web service response in DataTable c#

Hi all,
Few days before I was exploring how to get SharePoint web service response in DataTable instead of XMLNode?. for example you are using SharePoint List.asmx web service and try to get all SharePoint List collection get this response in DataTable.
here is code snippet.


/// <summary>
/// Get SharePoint List collections using SharePoint web service
/// Instead of Xml response it return DataTable.
/// remove XML name space from web service response.
/// </summary>
/// <returns></returns>
public DataTable GetSharePointListCollection()
{
try
{
//ListService is SharePoint List.asmx List Instance.
XmlNode ndSPLists = ListService.GetListCollection();
//to remove xml Name spance.
Regex StripXmlnsRegex =new Regex(@"(xmlns:?[^=]*=[""][^""]*[""])",RegexOptions.IgnoreCase|RegexOptions.Multiline|RegexOptions.Compiled| RegexOptions.CultureInvariant);

//to find and replace short XmlNameSpace like z:,rs: from xmlresponse by GetListItems method
Regex removeShortNameSpace = new Regex(@"(?<lessthan><)(?<closetag>[/])?(?<shortname>\w+:)\s*", RegexOptions.IgnoreCase|RegexOptions.Multiline|RegexOptions.Compiled|RegexOptions.CultureInvariant);

//remove namespace xmlnls from result xml..
string xmlResponse = StripXmlnsRegex.Replace(ndSPLists.InnerXml, "");

//find and replace short XmlNameSpace like z:,rs: from responce with space..
xmlResponse = removeShortNameSpace.Replace(xmlResponse, delegate(Match m)
{
Group closetag = m.Groups["closetag"];
if (closetag.Length != 0)
{
return "</";
}
else
{
return "<";
}

});
//load xml from removed XmlNameSpace and short name of XmlNameSpace..
//XDocument xmlDoc = new XDocument();
//xmlDoc = XDocument.Parse(xmlResponse);
xmlResponse = "<Lists>" + xmlResponse + "</Lists>";
XDocument xdoc = XDocument.Parse(xmlResponse);

using (StringReader reader = new StringReader(xdoc.ToString()))
{
DataSet dsSPLists = new DataSet();
dsSPLists.ReadXml(reader);
if (dsSPLists.Tables.Count > 0)
{
return dsSPLists.Tables[0];
}
}

return null;
}
catch
{
throw;
}
}

Monday, December 15, 2008

Iterate SharePoint list items using SharePoint web service

Hi all,
here is some chunks of that will help you out to iterate list item in SharePoint list using SharePoint web service. to parse all list items you should know XmlNameSpace from result xml schema,but here in this case I have remove that XmlNameSpace using Regx.so it is easy to iterate result xml schema.

Following example will fetch all list items from SharePoint list and show all title to console.

for better result copy the code and paste it in your console application add necessary assemblies,
include SharePoint list.asmx webrefrence name this reference as "ListService".


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
//List service proxy
using SharePointKingsDemo.ListService;
using System.Net;
using System.Xml;
using System.Xml.Linq;
using System.Xml.XPath;

namespace SharePointKingsDemo
{
///


/// Created By:Jayesh Prajapati.
/// Purpose:how to use SharePoint web service.,how to iterate each row in SharePoint list.
/// iterate each SharePoint list item without xmlname space.
/// This demo will work on .NET framework 3.5
///

class Program
{
//find replace xmlnamespace..
private static readonly Regex StripXmlnsRegex =
new Regex(@"(xmlns:?[^=]*=[""][^""]*[""])",
RegexOptions.IgnoreCase RegexOptions.Multiline RegexOptions.Compiled RegexOptions.CultureInvariant);

//to find and replace short XmlNameSpace like z:,rs: from xmlresponse by GetListItems method
private static readonly Regex removeShortNameSpace = new Regex
(@"(?<lessthan><)(?<closetag>[/])?(?<shortname>\w+:)\s*", RegexOptions.IgnoreCase RegexOptions.Multiline RegexOptions.Compiled RegexOptions.CultureInvariant);


static void Main(string[] args)
{
//list webservice proxy instance..
ListService.Lists listService = new Lists();
CredentialCache credential = new CredentialCache();
//credentials username,password,domain..
NetworkCredential networkCredential = new NetworkCredential("username", "password","domain");
credential.Add(new Uri("http://localhost"),"NTLM",networkCredential);
listService.Credentials = credential;
listService.Url = "http://localhost/_vti_bin/lists.asmx";

//xmldocument to create necessary nodes for getalllistitems method..
XmlDocument xdoc =new XmlDocument();
XmlNode queryNode =xdoc.CreateNode(XmlNodeType.Element,"Query","");

//get all list items whose id is greater than zero i.e all list item..
string strQuery = @"<Where><Gt><FieldRef Name='ID'/><Value Type='Counter'>0</Value></Gt></Where>";
queryNode.InnerXml=strQuery;
XmlNode viewNode = xdoc.CreateNode(XmlNodeType.Element,"ViewFields","");
string strViewFields = "<FieldRef Name=\"ID\" /><FieldRef Name=\"Title\" />";
viewNode.InnerXml=strViewFields;
XmlNode nodeQueryOption = xdoc.CreateNode(XmlNodeType.Element,"QueryOptions","");
nodeQueryOption.InnerXml="<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc>";
string rowlimit = "100";
string webid = "";

//get items from test sharepoint list..
XmlNode result = listService.GetListItems("test","", queryNode, viewNode, rowlimit, nodeQueryOption, webid);

//remove namespace xmlnls from result xml..
string xmlResponse = StripXmlnsRegex.Replace(result.InnerXml, "");

//find and replace short XmlNameSpace like z:,rs: from responce with space..
xmlResponse = removeShortNameSpace.Replace(xmlResponse, delegate(Match m)
{
Group closetag = m.Groups["closetag"];
if (closetag.Length !=0)
{
return "</";
}
else
{
return "<";
}

});

//load xml from removed XmlNameSpace and short name of XmlNameSpace..
XDocument xmlDoc = new XDocument();
xmlDoc = XDocument.Parse(xmlResponse);

//iterate each row in sharepoint list.
//in result xml each row is in element "row"
var Items = from item in xmlDoc.XPathSelectElements("//row")
select new
{
//get Title Field of SharePoint list...
Title = Convert.ToString(item.Attribute("ows_Title").Value)
};
//display each item in title field in console..
Array.ForEach(Items.ToArray(), item => Console.WriteLine(item.Title));
Console.ReadLine();


}
}
}

give your comments on this post, for alternate approch to parse web service response using xpath see following article..

http://www.sharepointkings.com/2008/11/how-to-iterate-sharepoint-list-fields.html


Wednesday, December 3, 2008

How to add a new list item to SharePoint using the List Item web service

How to add a new list item to SharePoint using the List Item web service ?

Problem Statement:
I want to add data into the "SalesReport" List on a sharepoint Site.

Solution:



Right click on the references folder and then ‘Add Web Reference…”.
WebService Reference: http:///_vti_bin/Lists.asmx

Type in the url to sites webservice you wish to call in the next box,
give it an appropriate name (we have given it as SharePointkingsWebService ) and click ok.

Create a method and place the below code.

try
{

SharePointkingsWebService.Lists list = new SharePointkingsWebService.Lists();
list.Credentials = System.Net.CredentialCache.DefaultCredentials;
list.Credentials = new System.Net.NetworkCredential("SharePointkings", "Password", "SharePointkings");
XmlDocument doc = new XmlDocument();
XmlElement batch_element = doc.CreateElement("Batch");
string item = "" + "New" + "This is a test by Sharepoint Team" + "";
batch_element.InnerXml = item;
list.UpdateListItems("SalesReport", batch_element);

return true;
}
catch (Exception ex)
{
return false;
}


....And the job is done!!!



Share your SharePoint Experiences with us...
As good as the SharePointKings is, we want to make it even better. One of our most valuable sources of input for our Blog Posts comes from ever enthusiastic Visitors/Readers. We welcome every Visitor/Reader to contribute their experiences with SharePoint. It may be in the form of a code stub, snippet, any tips and trick or any crazy thing you have tried with SharePoint.
Send your Articles to sharepointkings@gmail.com with your Profile Summary. We will Post them. The idea is to act as a bridge between you Readers!!!

If anyone would like to have their advertisement posted on this blog, please send us the requirement details to sharepointkings@gmail.com