giving "Microsoft sharepoint soapserver soap server exception" while getting the list items - sharepoint

I am trying to get the list items by using the webservice reference model.
I am trying to get the details of the list as this
SPSeriveReference.Lists client = new SPSeriveReference.Lists();
client.Credentials = new NetworkCredential("Administrator", "pswd","MyDomain");
XmlDocument mydoc = new XmlDocument();
XmlElement viewFileds = mydoc.CreateElement("ViewFields");
viewFileds.InnerXml = "<FieldRef Name=\"Title\" />" +
"<FieldRef Name=\"Name\" />" +
"<FieldRef Name=\"Address\" />";
XmlNode listItems = client.GetListItems("Manager", null, null, viewFileds, null, null, null); //a4af13f3-69f6-45e3-930d-8c2ce61a10fd
//XmlNode listItems = client.GetListItems("Manager", null, null, viewFileds, null, null, null);
foreach (XmlNode node in listItems)
{
if (node.Name == "rs:data")
{
for (int i = 0; i < node.ChildNodes.Count; i++)
{
if (node.ChildNodes[i].Name=="z:row")
{
string title = node.ChildNodes[i].Attributes["ows_Title"].Name;
string name = node.ChildNodes[i].Attributes["ows_Name"].Name;
string address = node.ChildNodes[i].Attributes["ows_Address"].Name;
Console.WriteLine(title + " " + name + " " + address);
}
}
}
}
But this is giving run time exception as "Microsoft.SharePoint.SoapServer.SoapServerException"
What is the solution for this one?
I verified the questions in stack overflow which were asked previously regarding the same error. But none of the provided the solution for this problem.

Related

How to validate if SharePoint list item update was successfull

I am trying to update a SharePoint list through an InfoPath form. A starting date SelectedDAM is input, and the code then calculates 6 dates. Newly calculated dates have to be updated in the original SP list.
The code below raises no exception in debug mode, and even in production. I checked that 'jobs' gets populated with data, and that le list names are as per their SharePoint name. Saddly, when I look to the SharePoint list afterward, items were not updated.
public void SetDAMButton_Clicked(object sender, ClickedEventArgs e)
{
string SelectedCEC = nav.SelectSingleNode("/my:mesChamps/my:DAMSection/my:CEC", this.NamespaceManager).Value;
string SelectedDAM = nav.SelectSingleNode("/my:mesChamps/my:DAMSection/my:DAM", this.NamespaceManager).Value;
//Query all jobs and dates from SharePoint List
XmlDocument xmlDoc = new XmlDocument();
XmlNode query = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
XmlNode viewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
query.InnerXml = "<Where>" +
"<Contains><FieldRef Name='CEC'/>" +
"<Value Type='Text'>" + SelectedCEC.Trim() + "</Value></Contains>" +
"</Where>";
viewFields.InnerXml = "<FieldRef Name='ID' />" +
"<FieldRef Name='JRS_x0020_Avant' />"+ "<FieldRef Name='JRS_x0020_Pr_x00e9_vus' />"+
"<FieldRef Name='JRS_x0020_Prevus_x0020_2' />"+ "<FieldRef Name='JRS_x0020_Avant_x0020_2' />"+
"<FieldRef Name='JRS_x0020_Pr_x00e9_vus_x0020_3' />" + "<FieldRef Name='JRS_x0020_Avant_x0020_3' />";
XmlNode listItems = sp.getListService().GetListItems(SPJobsListGlobal, null, query, viewFields, "10000000", null, null);
//Extract jobs data to an internal list
List<string[]> jobs = new List<string[]>();
for (int i = 1; i != listItems.ChildNodes[1].ChildNodes.Count; i += 2)
{
string jobId = listItems.ChildNodes[1].ChildNodes[i].Attributes[0].InnerXml;
string JRSAvant = listItems.ChildNodes[1].ChildNodes[i].Attributes[1].InnerXml;
string JRSPrevus = listItems.ChildNodes[1].ChildNodes[i].Attributes[2].InnerXml;
string JRSPrevus2 = listItems.ChildNodes[1].ChildNodes[i].Attributes[3].InnerXml;
string JRSAvant2 = listItems.ChildNodes[1].ChildNodes[i].Attributes[4].InnerXml;
string JRSPrevus3 = listItems.ChildNodes[1].ChildNodes[i].Attributes[5].InnerXml;
string JRSAvant3 = listItems.ChildNodes[1].ChildNodes[i].Attributes[6].InnerXml;
jobs.Add(new string[] { jobId.Trim(), JRSAvant.Trim(), JRSPrevus.Trim(),JRSAvant2.Trim(), JRSPrevus2.Trim(), JRSAvant3.Trim(), JRSPrevus3.Trim() });
}
jobs.RemoveAt(jobs.Count - 1);
//Update each item of SharePoint list with dates calculated from new DAM
for(int i = 0; i != jobs.Count; i++)
{
XmlDocument doc = new XmlDocument();
XmlElement batch = doc.CreateElement("Batch");
batch.InnerXml = "<Method ID='1' Cmd='Update'>" +
"<Field Name='ID'>" + SecurityElement.Escape(jobs[i][0]) + "</Field>" +
"<Field Name='DateDebut'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][1])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='DateFin'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][1])).AddDays(validateJRS(jobs[i][2])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_D_x00e9_but_x0020_2'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][3])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_Fin_x0020_2'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][3])).AddDays(validateJRS(jobs[i][4])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_D_x00e9_but_x0020_3'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][5])).ToString("yyyy-MM-dd")) + "</Field>" +
"<Field Name='Date_x0020_Fin_x0020_3'>" + SecurityElement.Escape(Convert.ToDateTime(SelectedDAM).AddDays(-validateJRS(jobs[i][5])).AddDays(validateJRS(jobs[i][6])).ToString("yyyy-MM-dd")) + "</Field>" +
"</Method>";
sp.UpdateListItems(SPJobsListGlobal, batch);
}
Why is it not working ? Is there any additionnal line I could add to confirm update.
To confirm the update you can check the return value of Lists.UpdateListItems, which is an XmlNode that contains the status of the update.
From MSDN:
Return value
An XMLDATA fragment in the following form that shows the status of each method block posted through the updates parameter and that can be assigned to a System.Xml.XmlNode object. For items successfully updated, a row fragment is returned with the updated row values.

Update a SavedQuery (View) from the SDK

I am trying to change all the Business Unit references I got after importing a solution to the ones in the Acceptance environment.
QueryExpression ViewQuery = new QueryExpression("savedquery");
String[] viewArrayFields = { "name", "fetchxml" };
ViewQuery.ColumnSet = new ColumnSet(viewArrayFields);
ViewQuery.PageInfo = new PagingInfo();
ViewQuery.PageInfo.Count = 5000;
ViewQuery.PageInfo.PageNumber = 1;
ViewQuery.PageInfo.ReturnTotalRecordCount = true;
EntityCollection retrievedViews = service.RetrieveMultiple(ViewQuery);
//iterate though the values and print the right one for the current user
int oldValues = 0;
int accValuesUpdated = 0;
int prodValuesUpdated = 0;
int total = 0;
foreach (var entity in retrievedViews.Entities)
{
total++;
if (!entity.Contains("fetchxml"))
{ }
else
{
string fetchXML = entity.Attributes["fetchxml"].ToString();
for (int i = 0; i < guidDictionnary.Count; i++)
{
var entry = guidDictionnary.ElementAt(i);
if (fetchXML.Contains(entry.Key.ToString().ToUpperInvariant()))
{
Console.WriteLine(entity.Attributes["name"].ToString());
oldValues++;
if (destinationEnv.Equals("acc"))
{
accValuesUpdated++;
Console.WriteLine();
Console.WriteLine("BEFORE:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.AccGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
Console.WriteLine();
Console.WriteLine("AFTER:");
Console.WriteLine();
Console.WriteLine(entity.Attributes["fetchxml"].ToString());
}
else
{
prodValuesUpdated++;
string query = entity.Attributes["fetchxml"].ToString();
query = query.Replace(entry.Key.ToString().ToUpperInvariant(), entry.Value.ProdGuid.ToString().ToUpperInvariant());
entity.Attributes["fetchxml"] = query;
}
service.Update(entity);
}
}
}
}
Console.WriteLine("{0} values to be updated. {1} shall be mapped to acceptance, {2} to prod. Total = {3} : {4}", oldValues, accValuesUpdated, prodValuesUpdated, total, retrievedViews.Entities.Count);
I see that the new value is corrected, but it does not get saved. I get no error while updating the record and publishing the changes in CRM does not help.
Any hint?
According to your comments, it sounds like the value you're saving the entity as, is the value that you want it to be. I'm guessing your issue is with not publishing your change. If you don't publish it, it'll still give you the old value of the FetchXml I believe.
Try calling this method:
PublishEntity(service, "savedquery");
private void PublishEntity(IOrganizationService service, string logicalName)
{
service.Execute(new PublishXmlRequest()
{
ParameterXml = "<importexportxml>"
+ " <entities>"
+ " <entity>" + logicalName + "</entity>"
+ " </entities>"
+ "</importexportxml>"
});
}

Safely return all lists in site collection that match criteria

I'm using the following code to get all "Announcement" lists in a Web Applications site collection.
Unfortunately, sometimes the current user does not have permission to that site and the page fails with an exception, even inside the try block.
What would be the right way to do the following safely for all users, where even an anonymous user would just get no results?
static public List<SPListMeta> AllSiteAnnouncementsLists()
{
var returnList = new List<SPListMeta>();
foreach (SPSite oSiteCollection in SPContext.Current.Web.Site.WebApplication.Sites)
{
var collWebs = oSiteCollection.AllWebs;
try
{
foreach (SPWeb oWebsite in collWebs)
{
using (oWebsite)
{
var collSiteLists = oWebsite.GetListsOfType(SPBaseType.GenericList);
returnList.AddRange(from SPList oList in collSiteLists where oList.Title == "Announcements" select new SPListMeta(oList));
}
}
}
catch
{
}
}
return returnList;
}
Try give your code the right permission to execute.
using Microsoft.Sharepoint.Administrator;
SPSecurity.RunWithElevatedPrivileges(delegate(){
// Your source code goes here
});
To get all items of the specific list type from the site collection you have to use SPSiteDataQuery. Each user will get only those items they have permissions.
SPWeb web = SPContext.Current.Web;
SPSiteDataQuery query = new SPSiteDataQuery();
//Ask for all lists created from the announcement template.
query.Lists = "<Lists ServerTemplate=\"104\" />";
// Get the Title field. Define here all you need.
query.ViewFields = "<FieldRef Name=\"Title\" />";
// Set the sort order.
query.Query = "<OrderBy>" +
"<FieldRef Name=\"Title\" />" +
"</OrderBy>";
// Query all Web sites in this site collection.
query.Webs = "<Webs Scope=\"SiteCollection\" />";
DataTable dt = web.GetSiteData(query);
DataView dv = new DataView(dt);
This is what ended up working for me, though I do not know if it is the best way to do this.
static public List<SPListMeta> AllSiteAnnouncementsLists()
{
var returnList = new List<SPListMeta>();
var collWebs = SPContext.Current.Web.Site.WebApplication.Sites[0].OpenWeb().GetSubwebsForCurrentUser();
if(SPContext.Current.Site.RootWeb.DoesUserHavePermissions(SPBasePermissions.Open))
{
var collSiteLists = SPContext.Current.Site.RootWeb.GetListsOfType(SPBaseType.GenericList);
returnList.AddRange(from SPList oList in collSiteLists
where oList.DoesUserHavePermissions(SPBasePermissions.ViewListItems)
&& oList.BaseTemplate == SPListTemplateType.Announcements
select new SPListMeta(oList));
}
foreach (SPWeb oWebsite in collWebs)
{
returnList.AddRange(WebRecursion.GetListsForCurrentWeb(oWebsite, SPListTemplateType.Announcements));
foreach (SPWeb oSubSite in oWebsite.Webs)
{
returnList.AddRange(WebRecursion.GetListsForCurrentWeb(oSubSite, SPListTemplateType.Announcements));
}
}
return returnList;
}
public static List<SPListMeta> GetListsForCurrentWeb(SPWeb oWebsite, SPListTemplateType type)
{
var returnList = new List<SPListMeta>();
if (oWebsite.DoesUserHavePermissions(SPBasePermissions.Open))
{
using (oWebsite)
{
var collSiteLists = oWebsite.Lists;
returnList.AddRange(from SPList oList in collSiteLists
where oList.DoesUserHavePermissions(SPBasePermissions.ViewListItems)
&& oList.BaseTemplate == type
select new SPListMeta(oList));
}
}
return returnList;
}

Get file/folder size from sharepoint using GetListItems

I am calling Sharepoint web service methond GetListItems, and don't see anything about file/folder size being returned. Am I missing something, or is there another way to get the size of the file/folder. Many thanks in advance.
the field you need is called ows_FileSizeDisplay, this returns an int for the number of bytes.
here is some code to put you on the rigth track
List<File> files = new List<File>(1);
File tempFile;
#region Get SharePointItems
SharePointListService.Lists svc = new SharePointListService.Lists();
XmlNode spItemsNode;
try
{
svc.Credentials = System.Net.CredentialCache.DefaultCredentials;
svc.Url = baseSharePointPath+"/_vti_bin/Lists.asmx";
XmlDocument xmlDoc = new System.Xml.XmlDocument();
XmlNode queryOptions =
xmlDoc.CreateNode(XmlNodeType.Element, "QueryOptions", "");
queryOptions.InnerXml = "<QueryOptions><IncludeMandatoryColumns>FALSE</IncludeMandatoryColumns><DateInUtc>TRUE</DateInUtc><Folder>" +
baseSharePointPath + "/"+ listName + "/"+ folderName + "</Folder></QueryOptions>";
XmlNode query =
xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
query.InnerXml = "<Where><Eq><FieldRef Name='Usage'/><Value Type='Text'>%%usage%%</Value></Eq></Where>";
query.InnerXml = query.InnerXml.Replace("%%usage%%", ConvertFileUsageToString(usage));
spItemsNode = svc.GetListItems(listName,
null, query, null, null, queryOptions, null);
}
finally
{
svc.Dispose();
}
// load the response into an xml document
XmlDocument xDoc = new XmlDocument();
xDoc.LoadXml(spItemsNode.OuterXml);
// create a namespace manager
XmlNamespaceManager ns = new XmlNamespaceManager(xDoc.NameTable);
// add all the special SharePoint Namespaces in
ns.AddNamespace("rs", "urn:schemas-microsoft-com:rowset");
ns.AddNamespace("z", "#RowsetSchema");
ns.AddNamespace("sp", "http://schemas.microsoft.com/sharepoint/soap/");
ns.AddNamespace("s", "uuid:BDC6E3F0-6DA3-11d1-A2A3-00AA00C14882");
ns.AddNamespace("dt", "uuid:C2F41010-65B3-11d1-A29F-00AA00C14882");
XmlNodeList Items = xDoc.SelectNodes(#"/sp:listitems/rs:data/z:row", ns);
#endregion
foreach (XmlNode currentFile in Items)
{
tempFile = new File();
tempFile.Name = currentFile.Attributes["ows_NameOrTitle"].Value;
tempFile.Type = currentFile.Attributes["ows_DocIcon"].Value;
tempFile.Usage = ConvertToFileUsage(currentFile.Attributes["ows_Usage"].Value);
tempFile.Data = getFileBytes(currentFile.Attributes["ows_RequiredField"].Value, baseSharePointPath);
files
Here is a nice code snippet that will do the job shout if you have any questions
Folder folder = getFolder(serverRelitiveURL);
FileCollection files = folder.Files;
folder.Context.Load(files);
folder.Context.ExecuteQuery();
int folderSize;
foreach(file in files)
{
ListItem li = file.ListItemAllFields;
Console.writeline(li["File_x0020_Size"]);
folderSize = li["File_x0020_Size"]+folderSize;
}
Console.writeline(folderSize);

How can I programmatically get Approval Status in SharePoint?

I wanted to programmatically get SharePoint Page Approval Status, I tried as below
public string GetApprovalStatus(string url, string listName, string fileref)
{
string result = string.Empty;
string caml = #"
" + fileref + #"
";
using (SPSite site = new SPSite(url))
{
using (SPWeb web = site.OpenWeb())
{
SPList list = web.Lists[listName];
SPQuery query = new SPQuery();
query.Query = caml;
SPListItemCollection myItems = list.GetItems(query);
if (myItems != null && myItems.Count > 0)
{
DataTable dt = myItems.GetDataTable();
result = dt.Rows[0]["_ModerationStatus"].ToString();
dt.Dispose();
}
}
}
return result;
}
And I return a number, how can I get the Approval Status in text?
Appreciate any help, thank you in advanced
The following code is from the MSDN article for SPModerationInformation.Status:
using (SPSite oSiteCollection = new SPSite("http://localhost"))
{
SPWebCollection collWebsites = oSiteCollection.AllWebs;
foreach (SPWeb oWebsite in collWebsites)
{
SPListCollection collLists = oWebsite.Lists;
foreach (SPList oList in collLists)
{
if (oList.BaseType == SPBaseType.DocumentLibrary)
{
SPDocumentLibrary oDocumentLibrary = (SPDocumentLibrary)oList;
if (!oDocumentLibrary.IsCatalog && oDocumentLibrary.EnableModeration ==
true)
{
SPQuery oQuery = new SPQuery();
oQuery.ViewAttributes =
"ModerationType='Moderator'";
SPListItemCollection collListItems =
oDocumentLibrary.GetItems(oQuery);
foreach (SPListItem oListItem in collListItems)
{
if (oListItem.ModerationInformation.Status ==
SPModerationStatusType.Pending)
{
Console.WriteLine(oWebsite.Url + "/" +
oListItem.File.Url);
oListItem.ModerationInformation.Comment =
"Automatic Approval of items";
oListItem.ModerationInformation.Status =
SPModerationStatusType.Approved;
oListItem.Update();
}
}
}
}
}
oWebsite.Dispose();
}
}
You can use the SPModerationStatusType enum SPModerationStatusType Enum - MSDN to get the text values that you want.
More info: http://spuser.blogspot.com.br/2011/03/how-to-programmatically-get-content.html
Here is the full code that gets and sets (optional) approval status (Possible values for this.oListItem.get_item('_ModerationStatus'): 0 - "Approved", 1 - "Denied", 2- "Pending"):
<script type="text/javascript" src="/jquery-1.10.2.min.js"></script>
<script src="/jquery.SPServices-2013.02a.js" type="text/javascript"></script>
<script type="text/javascript">
$(document).ready(function () { ExecuteOrDelayUntilScriptLoaded(loadConstants, "sp.js"); });
function loadConstants() {
var userid= _spPageContextInfo.userId;
var requestUri = _spPageContextInfo.webAbsoluteUrl + "/_api/web/getuserbyid(" + userid + ")";
var requestHeaders = { "accept" : "application/json;odata=verbose" };
$.ajax({
url : requestUri,
contentType : "application/json;odata=verbose",
headers : requestHeaders,
success : onSuccess,
error : onError
});
function onSuccess(data, request){
var loginName = data.d.Title;
//get current (selected) list item id
var docurl = document.URL;
var beginindex = docurl.indexOf('?ID=') + 4;
var endindex = docurl.indexOf('&Source=');
var itemid = docurl.substring(beginindex, endindex);
var ctx = new SP.ClientContext("your site url");
var oList = ctx.get_web().get_lists().getByTitle('your list name');
this.oListItem = oList.getItemById(itemid);
var appStatus = "";
ctx.load(this.oListItem);
ctx.executeQueryAsync(Function.createDelegate(this, function () {
//get approval status
appStatus = this.oListItem.get_item('_ModerationStatus');
//set approval status to Approved (0)
this.oListItem.set_item('_ModerationStatus', 0);
this.oListItem.update();
ctx.executeQueryAsync(
Function.createDelegate(this, this.onQuerySucceeded),
Function.createDelegate(this, this.onQueryFailed)
);
}), function (sender, args) { alert('Error occured' + args.get_message());});
}
function onError(error) {
alert("error");
}
}
</script>

Resources