Showing posts with label Web Service. Show all posts
Showing posts with label Web Service. 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.

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.

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.

Thursday, April 1, 2010

Access denied error when I use web services in InfoPath

Hi All,
When I use user profile service or any other web service in InfoPath and run it on my local server it works fine and when I deploy same form on production server where there is SharePoint farm it fails to run and give access denied error. I have used host header for SharePoint site and I refer that host header to open that site.
The solution for this problem is to disable the loopback check on each SharePoint server in farm.
To set the DisableLoopbackCheck registry key yourself, follow these steps:
Set the DisableStrictNameChecking registry entry to
  1. For more information about how to do this, click the following article number to view the article in the Microsoft Knowledge Base:
    (http://support.microsoft.com/kb/281308/ ) Connecting to SMB share on a Windows 2000-based computer or a Windows Server 2003-based computer may not work with an alias name
  2. Click Start, click Run, type regedit, and then click OK.
  3. In Registry Editor, locate and then click the following registry key:
    HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Lsa
  4. Right-click Lsa, point to New, and then click DWORD Value.
  5. Type DisableLoopbackCheck, and then press ENTER.
  6. Right-click DisableLoopbackCheck, and then click Modify.
  7. In the Value data box, type 1, and then click OK.
  8. Quit Registry Editor, and then restart your computer.
    And run IISRESET on each server
    Reference: http://support.microsoft.com/kb/896861

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.

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


Sunday, November 16, 2008

How to iterate SharePoint List Fields using SharePoint web service?

How to iterate SharePoint List Fields using SharePoint web service?
Hi All,
Here is some code snippet that will help you out to get rid of it.
Here is a scenario where I need to iterate fields and populate these fields in dropdown list for selected SharePoint list in dropdown list.
Reference from link http://www.codeguru.com/csharp/csharp/cs_webservices/tutorials/print.php/c8805__2/

private XmlNodeList RunXPathQuery(XmlNode XmlNodeToQuery, string XPathQuery)
{
// load the complete XML node and all its child nodes into an
// XML document
XmlDocument Document = new XmlDocument();

Document.LoadXml(XmlNodeToQuery.OuterXml);


// all the possible namespaces used by SharePoint and a randomly
// choosen prefix
const string SharePointNamespacePrefix = "sp";
const string SharePointNamespaceURI =
"http://schemas.microsoft.com/sharepoint/soap/";
const string ListItemsNamespacePrefix = "z";
const string ListItemsNamespaceURI = "#RowsetSchema";
const string PictureLibrariesNamespacePrefix = "y";
const string PictureLibrariesNamespaceURI =
"http://schemas.microsoft.com/sharepoint/soap/ois/";
const string WebPartsNamespacePrefix = "w";
const string WebPartsNamespaceURI =
"http://schemas.microsoft.com/WebPart/v2";
const string DirectoryNamespacePrefix = "d";
const string DirectoryNamespaceURI =
"http://schemas.microsoft.com/sharepoint/soap/directory/";
const string DataRowSetNameSpacePrefix = "rs";
const string DataRowSetNameSpaceURI = "urn:schemas-microsoft- com:rowset";

// now associate with the xmlns namespaces (part of all XML
// nodes returned from SharePoint), a namespace prefix that
// we then can use in the queries
XmlNamespaceManager NamespaceMngr =
new XmlNamespaceManager(Document.NameTable);
NamespaceMngr.AddNamespace(SharePointNamespacePrefix,
SharePointNamespaceURI);
NamespaceMngr.AddNamespace(ListItemsNamespacePrefix,
ListItemsNamespaceURI);
NamespaceMngr.AddNamespace(PictureLibrariesNamespacePrefix,
PictureLibrariesNamespaceURI);
NamespaceMngr.AddNamespace(WebPartsNamespacePrefix,
WebPartsNamespaceURI);
NamespaceMngr.AddNamespace(DirectoryNamespacePrefix,
DirectoryNamespaceURI);
NamespaceMngr.AddNamespace(DataRowSetNameSpacePrefix, DataRowSetNameSpaceURI);

// run the XPath query and return the result nodes
return Document.SelectNodes(XPathQuery, NamespaceMngr);
}

When you click button you need to populate fields of “MySharePoint List” to dropdown list.
protected void Button1_Click(object sender, EventArgs e)
{
//List Web service instance.
ListService.Lists listService = new ListService.Lists();
System.Net.NetworkCredential cred = new System.Net.NetworkCredential("admin", "admin");
System.Net.CredentialCache cache=new System.Net.CredentialCache();
cache.Add(new Uri("http://localhost:80"),"NTLM",cred);
listService.Credentials=cache;
listService.Url = "http://localhost:80/_vti_bin/lists.asmx";
//Provide SharePoint List name
XmlNode list = listService.GetList("MySharePointList");
//here “//sp:Field” is XPath query we need to pass.
XmlNodeList nodes = RunXPathQuery(list, "//sp:Field");
foreach (XmlNode node in nodes)
{
try
{
bool hidden = false;
bool ReadOnly = false;
string ID = node.Attributes["ID"].Value;
string Name = node.Attributes["Name"].Value;
try{hidden=Convert.ToBoolean(node.Attributes["Hidden"].Value);}catch{}
try { ReadOnly = Convert.ToBoolean(node.Attributes["ReadOnly"].Value); }
catch { }
if (!string.IsNullOrEmpty(ID) && !string.IsNullOrEmpty(Name))
{
if(!hidden || !ReadOnly)
//ddlField is dropdown list which we need to populate.
ddlField.Items.Add(new ListItem(Name, ID));
}
}
catch { }

}
}

Thursday, June 12, 2008

InfoPath using Web Service Data connection

Hi,

Read the following scenario you probably come across while development InfoPath using Web Service Data Connection. (Here I assume you know how to create Web Service Data connection using InfoPath 2007)

I have created one InfoPath form in my local machine, where I am filling dropdown from web service of my local machine,

For that I am creating data connection library, but it takes design time web service URL reference in data connection.

Now I want to publish this form to server, but on server it is not working because it considers local web service URL.

On server I have created same data connection library and change the web service reference in all .udcx file but still form template take web reference which I have added design time.

Because In my local machine web service URL is different and on server web service URL is different.

When I try to see preview of my InfoPath template on server it shows following message

"One or more data connection in your form are specified with server-relative link, but no published location has been defined for the form. Data connection will retrieve data from the server specified in design time. To enable server-relative link publish your form to Microsoft Office server"

I have divided this solution in two parts.

1. Create Web service Project (i.e. here I have created web service as Library it will generate .dll file assembly for web service not web service as web application) .Here we will use Web Service Template if you don’t have install this template please download it to create Web Service Project. You can see template in picture.


Now create project like this


Give Strong name to this Assembly.

Deploy it into a GAC .Now open MyService.asmx file in Notepad and replace <%@WebsService /> Tag with following according to your project here is one sample.

<%@ WebService Language="C#" Class="SharePointKings.MyService, SharePoiintKings, Version=1.0.0.0, Culture=Neutral, PublicKeyToken=bce3f92a230905aa" %>

Now create one Directory in 12/Template/Layouts Directory Name in Our case we will create

Directory “SharePointKings” under this directory put .dll from your project in our case it will be SharePointKings.dll.

Now from RUN write “inetmgr” now suppose your site Directory name is “2020” expand this site go to Layouts under Layouts now you will find directory called “SharePointKings” as we created it under 12/Template/Layouts so it will listed here. Now create virtual directory SharePointKings from here.

In first part we have created our web service as Assembly and configure it to use in InfoPath Web service data connection.

2. Now here I assume you know how to create Web service data connection and you want to populate dropdown list from web service.

When you open InfoPath Code Project and from this code project right click on project add Web Reference.

As we have assume that our site port is “2020” so our site URL is like this “http://servername:2020” and add reference http://servername:2020/_layouts/SharePointKings/Myservice.asmx now all web methods will be listed there. Name this web reference “MyService”

Ok now as you add this web reference you will find few additional files created in your InfoPath Code Project in which one is “Reference.cs” open this file you will find default constructor now add second additional constructor which take parameters for Web Reference URL.

public MYService(string WebseriveUrl)

{

this.Url = WebseriveUrl;

if ((this.IsLocalFileSystemWebService(this.Url) == true))

{

this.UseDefaultCredentials = true;

this.useDefaultCredentialsSetExplicitly = false;

}

else

{

this.useDefaultCredentialsSetExplicitly = true;

}

}

Now in your InfoPath Form Load Event Write Following code.

First we Create Dynamic URL For WebService like this so it works for our testing server as well in production server we don’t need to change any thing in code so, here we are creating dynamic URL though we have given hard coded refrecnce while adding web referce.

public void FormEvents_Loading(object sender, LoadingEventArgs e)

{

try

{

string webserviceurl = string.Empty;

webserviceurl = SPContext.Current.Site.Url + "/_layouts/SharePointKings/MYService.asmx"; ExecuteConnection("YourConnectionName",webserviceurl);

}catch(Exception ex){throw ex;}

}

private void ExecuteConnection(string ConnectionName,string WebServiceUrl)

{

WebServiceConnection cn = (WebServiceConnection)this.DataConnections[ConnectionName];

string url = WebServiceUrl;

UriBuilder uri = new UriBuilder(url);

cn.ServiceUrl = uri.Uri;

cn.Timeout = 60;

cn.Execute();

}

This way you can execute Web service connection yousing dynamic web service URL.you don’t need to change any code while deploying your code to production server .

download in word format




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