Exception thrown when doing a SOAP call to SharePoint - c#

I am getting this exception when I try to run my application:
Exception of type 'Microsoft.SharePoint.SoapServer.SoapServerException' was thrown
I am making a soap call to SharePoint and it is choking when the soap call is being executed.
below is the code I am running any ideas why this is happening?
public string getListData()
{
Lists myservice = new Lists();
myservice.Credentials = System.Net.CredentialCache.DefaultCredentials;
try
{
/* Assign values to pass the GetListItems method*/
string listName = "*list name*";
string viewName = "*view name*";
string rowLimit = "100";
//string successtest;
//string failtest;
// 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 = "";
viewFields.InnerXml = "<FieldRef Name=\"Name\" />";
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")
{
//List<String> testList;
test = node.ChildNodes[i].Attributes["ows_Title"].Value;
//Console.WriteLine(node.ChildNodes[i].Attributes["ows_Title"].Value + "</br>");
}
}
}
}
}
catch (Microsoft.SharePoint.SoapServer.SoapServerException ex)
{
test = ex.Detail.InnerText;
//Console.WriteLine(ex.Message);
}
return test;
}

Related

Cannot change XmlDocument value?

I have a simple function which will simply change and read the value.
void ParseXml(string XmlFile)
{
string totalval = "";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(new StringReader(XmlFile));
string xmlPathPattern = "//name";
XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
foreach (XmlNode node in mynodelist)
{
XmlNode name = node.FirstChild;
name.Value = "asd";//here I am trying to change value
totalval = totalval + "Name=" + name.OuterXml + "\n";
}
xmldoc.Save(XmlFile);
print(totalval);
}
This is my .xml file.
<name>John</name>
I can successfully read the value but it is not changing the value from .xml file.After running the program it must be like this
<name>asd</name> .
Where is my mistake ?
Obviously, the XMLFile is not a file path, it is xml string. So, you should define a valid path to save it.
xmldoc.Save("samplefile.xml");
or if you want to set the XmlFile variable with modified xml;
XmlFile = xmldoc.OuterXml;
Complete codes look like;
void ParseXml(string XmlFile)
{
string totalval = "";
XmlDocument xmldoc = new XmlDocument();
xmldoc.Load(new StringReader(XmlFile));
string xmlPathPattern = "//name";
XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
foreach (XmlNode node in mynodelist)
{
XmlNode name = node.FirstChild;
name.Value = "asd";//here I am trying to change value
totalval = totalval + "Name=" + name.OuterXml + "\n";
}
//XmlFile = xmldoc.OuterXml;
xmldoc.Save("samplefile.xml");
print(totalval);
}
If I'm not wrong - you need to fire disposable to save stream. Easiest way - wrap with using
void ParseXml(string XmlFile)
{
string totalval = "";
using(XmlDocument xmldoc = new XmlDocument())
{
xmldoc.Load(new StringReader(XmlFile));
string xmlPathPattern = "//name";
XmlNodeList mynodelist = xmldoc.SelectNodes(xmlPathPattern);
foreach (XmlNode node in mynodelist)
{
XmlNode name = node.FirstChild;
name.Value = "asd";//here I am trying to change value
totalval = totalval + "Name=" + name.OuterXml + "\n";
}
xmldoc.Save(XmlFile);
print(totalval);
}
}

Why the Page_Load Event is not able to Get Updated Values from xml file in C# Asp.NET?

I am trying to build a WebPage that includes "Rating of Site". Instead of using Database i am storing two variables to compute Avg of Rating in xml file as
<?xml version="1.0" encoding="utf-8"?>
<data>
<RatingCount>6</RatingCount>
<RatingTotal>17</RatingTotal>
</data>
Here is my Logic Code Both On the Page Load and AJAX Rating Control
Page_Load()
string rootPath = Server.MapPath("~/");
if (File.Exists(rootPath + "data.xml"))
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(rootPath + "data.xml");
XmlNode ratingCount = xdoc.DocumentElement.SelectSingleNode("/data/RatingCount");
XmlNode ratingTotal = xdoc.DocumentElement.SelectSingleNode("/data/RatingTotal");
string rating = ratingTotal.InnerText;
string count = ratingCount.InnerText;
if (Convert.ToInt32(count) >= 1)
{
double resultRating = Convert.ToSingle(rating) / Convert.ToSingle(count);
Rating1.CurrentRating = Convert.ToInt32(resultRating);
lblerror.Text = resultRating + " Rating in " + count + " Totals Votes";
}
else
{
lblerror.Text = "No Votes Till Now";
}
}
Rating_Control()
string rootPath = Server.MapPath("~/");
if (File.Exists(rootPath + "data.xml"))
{
XmlDocument xdoc = new XmlDocument();
xdoc.Load(rootPath + "data.xml");
XmlNode ratingCount = xdoc.DocumentElement.SelectSingleNode("/data/RatingCount");
XmlNode ratingTotal = xdoc.DocumentElement.SelectSingleNode("/data/RatingTotal");
XmlWriterSettings settings = new XmlWriterSettings();
settings.Indent = true;
XmlWriter xwrite = XmlWriter.Create(rootPath + #"data.xml", settings);
xwrite.WriteStartDocument();
xwrite.WriteStartElement("data");
string r = (Convert.ToInt32(ratingCount.InnerText) + 1).ToString();
string t = (Convert.ToInt32(ratingTotal.InnerText) + Convert.ToInt32(e.Value)).ToString();
xwrite.WriteElementString("RatingCount", r);
xwrite.WriteElementString("RatingTotal", t);
xwrite.WriteEndElement();
xwrite.WriteEndDocument();
xwrite.Flush();
xwrite.Close();
}
else
{
lblerror.Text = "File Doesnt Exists";
}
Any Help will be Appreciated!

GetListItems() causes a 401 error but Checkout() works

I want to get the contents of a Sharepoint 2007 list via web service. I'm using this code, which I mostly copied from the MSDN page for GetListItems:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
namespace testGetListItems
{
class Program
{
static void Main(string[] args)
{
sharepoint.Lists listService = new sharepoint.Lists();
listService.Credentials = System.Net.CredentialCache.DefaultCredentials;
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions = xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
ndQueryOptions.InnerXml =
"<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" +
"<DateInUtc>TRUE</DateInUtc>";
ndViewFields.InnerXml = "<FieldRef Name='Field1' /> <FieldRef Name='Field2'/>";
ndQuery.InnerXml = "<Where><And><Gt><FieldRef Name='Field1'/>" +
"<Value Type='Number'>5000</Value></Gt><Gt><FieldRef Name='Field2'/>" +
"<Value Type= 'DateTime'>2003-07-03T00:00:00</Value></Gt></And></Where>";
try
{
bool checkoutResult=listService.CheckOutFile("http://sharepoint/sites/mysite/myFile.xlsx", "false", null);
XmlNode ndListItems =
listService.GetListItems("Test List", null, ndQuery,
ndViewFields, null, ndQueryOptions, null);
}
catch (System.Web.Services.Protocols.SoapException ex)
{
Console.WriteLine("Message:\n" + ex.Message + "\nDetail:\n" +
ex.Detail.InnerText +
"\nStackTrace:\n" + ex.StackTrace);
}
}
}
}
The call to CheckOutFile() works correctly. But the GetListItems() call gives me this error:
An unhandled exception of type 'System.Net.WebException' occurred in System.Web.Services.dll
Additional information: The request failed with HTTP status 401: Unauthorized.
I don't understand why CheckOutFile() succeeds but GetListItems() fails, especially because the document that I'm checking out is in the list that's being accessed by GetListItems().
UPDATE: This worked in a test console app, but not in my main application. Leaving this answer up for now, but I'm not going to accept it until I get this fixed.
It turned out the problem was with the URL of the web service. Even though I had added it as:
http://sharepoint/sites/mySite/_vti_bin/Lists.asmx
the app.config file had it listed as:
http://sharepoint/_vti_bin/Lists.asmx
This remained a problem even after I deleted the reference and re-added it; I had to change the app.config contents manually. Once I'd done so, the GetListItems() call succeeded.
You must set a user and password who can get the items in the library/list this way (for me it works, you could try):
public string GetIDFromList(string parameter)
{
string retorno = "";
try
{
string path = "http://www.test.com/web/";
// Reference to the SharePoint Lists web service:
WSSharePointCSCLists.Lists listsWS = new WSSharePointCSCLists.Lists();
listsWS.Url = path + "_vti_bin/lists.asmx";
listsWS.Credentials = GetUserCredential();
string listName = "MyList";
string viewName = "";
//string webID;
string rowLimit = "500";
// Web ID:
webID = "098304-9098asdf-qwelkfj-eoqiula";
XmlDocument xmlDoc = new System.Xml.XmlDocument();
// Query em CAML (SharePoint):
XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode ndViewFields =
xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
XmlNode ndQueryOptions =
xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
ndQueryOptions.InnerXml =
"<IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns>" +
"<DateInUtc>TRUE</DateInUtc>" +
"<ViewAttributes Scope=\"RecursiveAll\" />";
ndViewFields.InnerXml = #"<FieldRef Name='Title' />
<FieldRef Name='ID' />";
string caml =
String.Format(
#"<Where>
<Contains>
<FieldRef Name='MyColumn' />
<Value Type='Text'>{0}</Value>
</Contains>
</Where>",
parameter);
ndQuery.InnerXml = caml;
XmlNode retornoWS = listsWS.GetListItems(listName, null, ndQuery,
ndViewFields, rowLimit,
ndQueryOptions, webID);
retorno = retornoWS.InnerXml;
}
catch (Exception ex)
{
Debug.WriteLine("Exception: " + ex.Message);
throw;
}
return retorno;
}
public NetworkCredential GetUserCredential()
{
return new System.Net.NetworkCredential("<username>",
"<password>",
"<domain>");
}

How can i pass List<string> response as an xml document using c#

I would like to pass an List response as an xml document and want to load it as xml.
Currently i am performing it using this code :
List<string> BugWSResponseList1 = new List<string>();
BugWSResponseList1 = CreateBugs(FilePath_EXPRESS_API_BugAdd_CreateBugs_DataFile, newValue);
XmlDocument xd = new XmlDocument();
//string s = string.Join(",", BugWSResponseList2);
//xd.LoadXml(s);
string s = "<Bugs>" + string.Join(",", BugWSResponseList1) + "</Bugs>";
xd.LoadXml(s);
//Dictionary Creation for Benchmark API
XmlDocument ResponseNode_bugs = null;
ResponseNode_bugs = new DrWatsonCore().LoadXMLDocument(s);
I would like to avoid to convert the List<string> response to string first and then loading it as xml.
Please suggest how can i achieve that.
Please find the detail of my LoadXMLDocument function as follows:
public XmlDocument LoadXMLDocument(string XMLData)
{
XmlDocument doc = new XmlDocument();
try
{
doc.LoadXml(XMLData);
}
catch (Exception ex)
{
Logger.Write("\n\n" + DateTime.Now + " : " + "LoadXMLDocument : SEVERE ERROR : Failed to create XMLDocument from given string : \n\n");
Logger.Write("\n\n" + DateTime.Now + " : " + "Exception : : \n\n" + ex.Message);
Logger.Write("\n\n" + DateTime.Now + " : " + "Given String : : \n\n");
if (DrWatsonHome.doVerboseLogging)
{
Logger.Write(XMLData);
}
else
{
string Response = XMLData;
Logger.Write("\n\n" + DateTime.Now + " : " + "Response Length : " + Response.Length + " characters.");
int ResponseLengthToPrint = DrWatsonHome.VerboseLogging_Length_Chars < Response.Length ? DrWatsonHome.VerboseLogging_Length_Chars : Response.Length;
Logger.Write("\n\n" + DateTime.Now + " : " + "Response : " + Response.Substring(0, ResponseLengthToPrint) + " ...");
}
}
finally
{
}
return doc;
}
Can i achieve it after making some modifications in it.Please suggest.
I am using List now and my function is as follows:
List<XElement> Sairam(string FilePath, string Timestamp)
{
List<XElement> WSResponse = new List<XElement>();
XmlDocument XDoc = new DrWatsonCore().LoadXMLFromFile(FilePath);
XmlNode BugListNode = XDoc.SelectSingleNode("/DrWatson/Bugs");
List<Bug> BugList = new DrWatsonCore().GetBugList(BugListNode);
List<Thread> BugFtecherThreadList = new List<Thread>();
foreach (Bug bug in BugList)
{
bug.FoundInBuild = Timestamp;
string URL = new DrWatsonCore().CreateWXURL(EXPRESS_API_METHOD.bug_add, bug, REST_EndPoint, AppGUID, new WatsonUser(Username_Watson, Password_Watson));
string Response = string.Empty;
object URLobj = (object) URL;
Response = CreateBug(URLobj);
// WSResponse.Add(Response);
}
return WSResponse;
}
I would like to get the WSResponse as the final response of teh program but i am unable to fetch it. Please suggest so how can i get the response of this program from this function.

Call WCF reference type variable

I am totally new to C#.
I have one service method
//actual method
public DataTable LoadDownLoadTablesData(string strBusinessUnit, string strExecutive, string strTableName, ref string strDate, string strTerritoryCode, string strUField1, string strUField2, string strUFeild3)
{
DataTable ds = new DataTable();
try
{
XontPDAServiceDAL vu = new XontPDAServiceDAL();
if (vu.validateExecutive(strBusinessUnit, strExecutive) == true)
{
DownloadFetchBLL wmd = new DownloadFetchBLL();
strDate = DateTime.Now.ToString();
ds = wmd.LoadDownLoadTableData(strBusinessUnit, strExecutive, strTableName, strTerritoryCode, strUField1, strUField2, strUFeild3);
}
else
{
throw new FaultException("Executive Not Active in the system.");
}
}
catch (FaultException) { }
catch (Exception ex)
{
throw new FaultException("Database Server is Not Responding." + ex.Message);
}
return ds;
}
//Converting datatable to String type
public string LoadDownLoadTablesDataJson(string strBusinessUnit, string strExecutive, string strTableName, ref string strDate, string strTerritoryCode, string strUField1, string strUField2, string strUFeild3)
{
DataTable dtDownloadJson = new DataTable();
dtDownloadJson = this.LoadDownLoadTablesData(strBusinessUnit, strExecutive, strTableName, ref strDate, strTerritoryCode, strUField1, strUField2, strUFeild3);
return this.ConverTableToJson(dtDownloadJson);
}
//Converting table to json
public String ConverTableToJson(DataTable dtDownloadJson)
{
string[] StrDc = new string[dtDownloadJson.Columns.Count];
string HeadStr = string.Empty;
// if (dtDownloadJson.Columns.Count > 0)
// {
for (int i = 0; i < dtDownloadJson.Columns.Count; i++)
{
StrDc[i] = dtDownloadJson.Columns[i].Caption;
HeadStr += "\"" + StrDc[i] + "\" : \"" + StrDc[i] + i.ToString() + "¾" + "\",";
}
if (HeadStr.Length > 0)
{
HeadStr = HeadStr.Substring(0, HeadStr.Length - 1);
StringBuilder Sb = new StringBuilder();
Sb.Append("{\"" + dtDownloadJson.TableName + "\" : [");
for (int i = 0; i < dtDownloadJson.Rows.Count; i++)
{
string TempStr = HeadStr;
Sb.Append("{");
for (int j = 0; j < dtDownloadJson.Columns.Count; j++)
{
TempStr = TempStr.Replace(dtDownloadJson.Columns[j] + j.ToString() + "¾", dtDownloadJson.Rows[i][j].ToString());
}
Sb.Append(TempStr + "},");
}
Sb = new StringBuilder(Sb.ToString().Substring(0, Sb.ToString().Length - 1));
Sb.Append("]}");
return Sb.ToString();
}else
{
return "0";
}
// }else{
// return "0";
// }
}
This LoadDownLoadTablesData() reference variable is there.
I have to pass call this LoadDownLoadTablesDataJson(....) from Android,
I called like this way;
// ksoap2 calling wcf
public SoapPrimitive soapPrimitiveData(String method_name1, String soap_action1, String NAMESPACE, String APPURL ,String tablename ) throws IOException,XmlPullParserException {
SoapPrimitive responses = null;
SoapObject request = new SoapObject(NAMESPACE, method_name1); // set up
request.addProperty("strBusinessUnit", "HEMA");
request.addProperty("strExec", "4515");
request.addProperty("strTableName", "RD.AlternativeProductHeader");
// after login we will get these fields value
request.addProperty("strDate", "2000-04-29");
request.addProperty("TerritoryCode", "KAND");
request.addProperty("strUField1", "");
request.addProperty("strUField2", "");
request.addProperty("strUField3", "");
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11); // put all required data into a soap// envelope
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
AndroidHttpTransport httpTransport = new AndroidHttpTransport(APPURL);
httpTransport.debug = true;
try {
httpTransport.call(soap_action1, envelope);
responses = (SoapPrimitive) envelope.getResponse();
Log.w("log_tag", "#### 218 ####" + responses);
} catch (Exception e) {
e.printStackTrace();
}
return responses;
}
This always return "0". But when I run through dummy testing C# site, It return some result.
See
String da1 = "2000-04-29";
String s = client.LoadDownLoadTablesDataJson("HEMA", "4515", "RD.AlternativeProductHeader", ref da1, "KAND", "", "", "");
Label1.Text = s;
output is :
{"Table1" : [{"TableName" : "LoadDistributor","Description" : "Distributor ","MandatoryFlag" : "1","Status" : "","Priority" : "0"},{"TableName" : "LoadPrice","Description" : "Price ","MandatoryFlag" : "1","Status" : "","Priority" : "0"}]}
I have confuse how we want to pass reference type using Android?
Please help me..
Thanks in advance.
Should have give like this request.addProperty("strExecutive", "4515");
not request.addProperty("strExe", "4515");
I shoube be service argument name.Can't give different name
It looks like the property name in your andriod request doesn't match up with the parameter name on your .NET web service method: strExe != strExecutive.

Categories

Resources