SharePoint 2010: show hidden columns with WebService - c#

I create a list, add 2 columns and insert 2 items via c# Webservice. In SharePoint I cannot see the 2 columns, only Title. When I edit the items, I see the other columns. In SharePoint I can change the view to see the 2 columns. But how to change the view with Webservice?
I try this:
private void SetView(string listName, string viewName, String[] arr)
{
AllViews.Views viewService = new AllViews.Views();
viewService.Credentials = System.Net.CredentialCache.DefaultCredentials;
//from msdn
//string strQuery1 = "<Where><Gt><FieldRef Name=\"Title\" />" +
// "<Value Type=\"Title\"></Value>" + "</Gt></Where>" +
// "<OrderBy><FieldRef Name=\"Title\" /></OrderBy>";
string strQuery = "<Query><Where><IsNotNull><FieldRef Name=\"Title\" />" +
"</IsNotNull></Where></Query>";
string strRowLimit = "150";
string strViewFields = "";
int count = arr.Length;
for (int i = 0; i < count; i++)
{
strViewFields += "<FieldRef Name=\'" + arr[i] + "\'/>";
}
System.Xml.XmlDocument xmlDoc = new System.Xml.XmlDocument();
System.Xml.XmlNode ndQuery = xmlDoc.CreateNode(XmlNodeType.Element, "Query", "");
System.Xml.XmlNode ndRowLimit = xmlDoc.CreateNode(XmlNodeType.Element, "RowLimit", "");
System.Xml.XmlNode ndViewFields = xmlDoc.CreateNode(XmlNodeType.Element, "ViewFields", "");
ndQuery.InnerXml = strQuery;
ndRowLimit.InnerXml = strRowLimit;
ndViewFields.InnerXml = strViewFields;
XmlNode retNode = viewService.AddView(listName, viewName, ndViewFields, ndQuery, ndRowLimit, "HTML", false)
}
All without error, but columns hidden in the list. Maybe the query is wrong. Or the way that I use. Any tipps for me? Searching results are all about the SharePoint.dll, but I need a way with Webservice.

Solution
Change strQuery to:
string strQuery = "<Where><IsNotNull><FieldRef Name=\"Title\" />" +
"</IsNotNull></Where>";
// is in Node ndQuery, dont need it again. Maybe a dirty trick to hide new Columns
Set the new View as default with UpdateView. Be sure to use the GUID from the view.
For viewProperties only the prop that you want to change
string strProp = "DefaultView =\"TRUE\"";
All works fine. Have a nice weekend.

Related

c# asmx web service. How to read in post data from aspx page

I am writing a web service for my company using c#. So I have a test page default.aspx.
From the aspx page I have an input name="zip" which i need to pass to the webservice.
I can't figure out how to get the posted data. Webservice will run an sql statement based on the zip code passed as xml. then returns the zipcode xml as a response.
code from aspx page below.
string sendXml = String.Format(#"<?xml version=""1.0"" encoding=""utf-8""?>,
<zip>{0}</zip>",
Request["zip"]);
string postXml = "xmlRequest=" + HttpUtility.UrlEncode(sendXml);
HttpWebRequest req = (HttpWebRequest)WebRequest.Create("http://localhost:51857/zipfinder.asmx/showRecords");
req.Method = "POST";
req.ContentLength = postXml.Length;
req.ContentType = "application/x-www-form-urlencoded";
using (StreamWriter writer = new StreamWriter(req.GetRequestStream()))
{
writer.Write(postXml);
writer.Close();
}
var result = "";
try
{
using (StreamReader reader = new StreamReader(req.GetResponse().GetResponseStream()))
{
string getResult = reader.ReadToEnd();
Response.Write(getResult);
}
}
catch (Exception ex)
{
Response.Write("error: " + ex.ToString());
}
then on the .asmx page
[ScriptMethod(ResponseFormat = ResponseFormat.Xml)]
public DataSet getZip() {
DataSet dataSet = db.QueryDataRows("*", "zip_codes_simple", "zip = '00501' or zip = '00544'", "", "zip_codes_simple");
return dataSet;
}
[WebMethod]
public XmlDocument showRecords(){
DataSet dataSet = getZip();
string recs = "";
XmlDocument doc = new XmlDocument();
XmlDeclaration dec = doc.CreateXmlDeclaration("1.0", null, null);
doc.AppendChild(dec);
XmlNode root = doc.CreateElement("zipcodes");
doc.AppendChild(root);
XmlElement zip = doc.CreateElement("zip");
XmlElement type = doc.CreateElement("type");
XmlElement primaryCity = doc.CreateElement("primaryCity");
XmlElement state = doc.CreateElement("state");
XmlElement latitude = doc.CreateElement("latitude");
XmlElement longitude = doc.CreateElement("longitude");
foreach (DataTable dt in dataSet.Tables)
{
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
zip.InnerText = dr["zip"].ToString();
root.AppendChild(zip);
type.InnerText = dr["type"].ToString();
root.AppendChild(type);
primaryCity.InnerText = dr["primary_city"].ToString();
root.AppendChild(primaryCity);
state.InnerText = dr["state"].ToString();
root.AppendChild(state);
latitude.InnerText = dr["latitude"].ToString();
root.AppendChild(latitude);
longitude.InnerText = dr["longitude"].ToString();
root.AppendChild(longitude);
//recs = "<p>" + dr["zip"] + ", " + dr["primary_city"] + "</p>";
//Response.Write("<p>" + dr["zip"] + " in " + dr["state"]);
}
}
else
{
//recs = "<p style='color: red;'>Invalid user name or password</p>";
}
}
return doc;
}
How can i get the zip code from the aspx page to pass to the query where zip = ''
I am looking for something to read in the formatted string and extract the zip code from the incoming xml document.
any help appreciated.
thanks
If I understood it right, you want to get the value from the <input type='text' name='zip' /> in your page. Since it is not an asp:TextBox, you should get it using Request.Form, so your code would look like this:
string sendXml = String.Format(#"<?xml version=""1.0"" encoding=""utf-8""?>,
<zip>{0}</zip>",
Request.Form["zip"]);
But there is another solution: Instead of doing this:
<input type='text' name='zip' />
You could use an ASP.NET Webform control:
<asp:TextBox runat='server' ID='zip' />
And then you could get the value with zip.Text.
Is there any reason why you're not doing this?

Sharepoint Web Service Query ignoring Query Paramaters

I am trying to query Sharepoint 2010 via the Web Service using CalmQuery.
I created the calmQuery through a calmquery buidler, so im pretty sure the query is correct, however the GetListItems() ignore this query and just gets every item in the list:
here is my code:
/* Query */
XmlDocument calmDocument = new XmlDocument();
XmlNode camlNode = calmDocument.CreateElement("Query");
camlNode.InnerText = "<Where>" +
"<Eq>" +
"<FieldRef Name='Office_x0020_Staff' />" +
"<Value Type='Boolean'>Yes</Value>" +
"</Eq>" +
"</Where>";
XmlNode Test = GetService().GetListItems("Staff", null, camlNode, null, null, null, null);
for (int i = 0; i < Test.ChildNodes[1].ChildNodes.Count; i++)
{
if (Test.ChildNodes[1].ChildNodes[i].Attributes != null)
{
MessageBox.Show(Test.ChildNodes[1].ChildNodes[i].Attributes["ows_Title"].InnerText;
}
}
Solved it. Silly me:
"<Value Type='Boolean'>1</Value>" +

Can't get inner text from FQL using Xpath C#

I'm trying to get the inner text from a XML tag called sharecount, I need to get it by the normalized_url tag like so:
string ShareCount;
string Url = "'" + "http://www.example.com/Article.aspx?id=" + GuideID + "'";
XmlNode Node;
try
{
//return Share count (using Xpath).
XmlDoc.SelectSingleNode("fql_query_response/link_stat[normalized_url=" + Url + "]/share_count");
ShareCount = XmlDoc.InnerText;
int.TryParse(ShareCount, out Value); //Turn string to int.
return Value;
}
catch
{
return 0;
}
and this is the XML:
<fql_query_response xmlns="http://api.facebook.com/1.0/" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" list="true">
<link_stat>
<url>http://www.example.com/Article.aspx?id=1909</url>
<normalized_url>http://www.example.com/Article.aspx?id=1909</normalized_url>
<share_count>11</share_count>
<like_count>3</like_count>
<comment_count>0</comment_count>
<total_count>14</total_count>
<commentsbox_count>8</commentsbox_count>
<comments_fbid>10150846665210566</comments_fbid>
<click_count>0</click_count>
</link_stat>
</fql_query_response>
<link_stat>
<url>http://www.example.com/Article.aspx?id=1989</url>
<normalized_url>http://www.example.com/Article.aspx?id=1989</normalized_url>
<share_count>11</share_count>
<like_count>3</like_count>
<comment_count>0</comment_count>
<total_count>14</total_count>
<commentsbox_count>8</commentsbox_count>
<comments_fbid>10150846665210566</comments_fbid>
<click_count>0</click_count>
</link_stat>
</fql_query_response>
The thing is i got in the return value: "www.example.com/Article.aspx?id=1132http://www.example.com/Article.aspx?id=190900000101502138970422760" what am i doing wrong? thanks!
The problem is you are Selecting a single node but obtaining the content from the root element. On top of that, you have a root namespace, therefore use of NameSpaceManger for searches is required. Try this sample:
string GuideID = "1989";
string Url = "'" + "http://www.example.com/Article.aspx?id=" + GuideID + "'";
var XmlDoc = new XmlDocument();
XmlDoc.Load(new FileStream("XMLFile1.xml",FileMode.Open,FileAccess.Read));
var nsm = new XmlNamespaceManager(XmlDoc.NameTable);
nsm.AddNamespace("s", "http://api.facebook.com/1.0/");
var node = XmlDoc.SelectSingleNode("s:fql_query_response/s:link_stat[s:normalized_url=" + Url + "]/s:share_count", nsm);
var ShareCount = node.InnerText;
And here is the LINQ way with same namespace manager and an XPathSelector.
XDocument xdoc = XDocument.Load(new FileStream("XMLFile1.xml", FileMode.Open, FileAccess.Read));
var lnode = xdoc.XPathSelectElements("s:fql_query_response/s:link_stat[s:normalized_url=" + Url + "]/s:share_count",nsm).First();
var ret = lnode.Value;

Ignore the value of an empty Attributes in the element LINQ C#

I'm trying to retrieve values from an XML file and I find some values are empty.
textBox6, textBox7, textBox14 corresponding element attribute values are empty/null. The error message is Null reference error was unhanded . How can fix this??
private void DisplayFile(string path)
{
var doc = XDocument.Load(path);
var ns = doc.Root.GetDefaultNamespace();
var conn = doc.Root.Element(ns + "connection");
textBox1.Text = conn.Element(ns + "sourceId").Value;
var doc1 = XDocument.Load(path);
var ns1 = doc.Root.GetDefaultNamespace();
var conn1 = doc.Root.Element(ns1 + "connectionContext");
}
If a given element is not present in the XML foo.Element("someNode") will return null. When accessing .Value you get a NullReferenceException.
In order to avoid this NullReferenceException you need to check if the element is not null.
Example with contextType:
var contextType = conn1.Element(ns + "contextType");
if (contextType != null)
{
textBox15.Text = contextType.Value;
}
Update:
You try to load the connectionContext node from the root element. But this node is a child of the source node. You need to first load this node:
var source = doc.Root.Element(ns + "source");
var conn1 = source.Element(ns + "connectionContext");
I find your problem try this (i use string cause didn't want to make textboxes)
var doc = XDocument.Load("C:\\Test\\stovfl.xml");
var ns = doc.Root.GetDefaultNamespace();
var conn = doc.Root.Element(ns + "connection");
string s1 = conn.Element(ns + "sourceId").Value;
string s2 = conn.Element(ns + "username").Value;
var conn1 = doc.Root.Element("source");
var conn2 = conn1.Element("connectionContext");
string s6 = conn2.Element(ns + "organization").Value;
string s7 = conn2.Element(ns + "field").Value;
string s14 = conn2.Element(ns + "description").Value;
string s15 = conn2.Element(ns + "contextType").Value;
problem was that you have connectionContext in source, but try to find it in Root

Programatically changing field order in Sharepoint 2007 list

I'm adding in two new fields into an already existing Sharepoint list programmatically through a feature. The fields are being added successfully but I have been unable to adjust the column order.
This task is done simply through the UI by going to List Settings and then Column Ordering, but I have been unable to achieve the task programmatically.
Through some research I've seen that you can use the SPContentType of the form to change the ordering of the FieldLinks (as follows):
SPList list = web.Lists["Example List"];
if (list.ContentTypes.Count > 0) {
SPContentType ct = list.ContentTypes[0];
string[] names = {"Example_x0020_One", "Example_x0020_Two", "Example_x0020_Three"};
ct.FieldLinks.Reorder(names);
ct.Update();
}
In this example, I the list would already have "Example One" and "Example Three" columns, and I would add "Example Two" later and then try to order them.
However this approach did not work for me, so if anyone has input on it, that would be appreciated.
The next item I saw is manually changing the SchemaXml of the list to have the proper order of the fields, but I wanted to see if this was the best method.
Any input would be appreciated, thank you for your help.
I took a look at the source of the Column ordering page (formEdt.aspx), it looks like they use web services, not the object model:
function DoBuildAndSubmit()
{
var numFound, currentSelect, selectValue;
var form = document.forms.aspnetForm;
var numFields = form["numSelects"].value;
var xml = "<Fields>";
numFound = 0;
while(numFound < numFields)
{
for(x = 0; x < numFields; x++)
{
currentSelect = form["FormPosition" + x];
if(currentSelect.selectedIndex == numFound)
{
selectValue = currentSelect.options[numFound].value;
xml = xml + "<Field Name=\"" + selectValue + "\"/>" + "\n";
numFound++;
}
}
}
for(x = numFields ; x < 67; x++)
xml = xml + "<Field Name=\"" + form["FormPosition" + x].value + "\"/>" + "\n";
xml = xml + "</Fields>";
document.frmLayoutSubmit["ReorderedFields"].value=xml;
document.frmLayoutSubmit.action = "http://local/_vti_bin/owssvr.dll?CS=65001";
document.frmLayoutSubmit.submit();
}
Now, it might be possible to do through the object model, but I don't have a good feeling about it when the UI is punting.
Here's a powershell version:
# Moves "FieldToBeMoved" after "Description" field
$list = $web.Lists["Documents"]
$ct = $list.ContentTypes[0] # Or find the desired CT
$newOrder = #()
foreach ($field in $ct.Fields)
{
if ($field.StaticName -ne "FieldToBeMoved")
{
$newOrder += $field.StaticName
}
if ($field.StaticName -eq "Description")
{
$newOrder += "FieldToBeMoved"
}
}
$ct.FieldLinks.Reorder($newOrder)
$ct.Update();
I used the code from your answer, except I programmatically examined the content types and fields for the list I wanted to re-order.
//Step 1 (optional): List out the content types and fields for your list to see what is in the list
SPList list = web.Lists[strListName];
string strRet="";
foreach (SPContentType spct in list.ContentTypes)
{
strRet += "<strong>Content Type: </strong>" + spct.Name + ", <strong>Fields</strong>: <br />";
foreach (SPField field in spct.Fields)
{
if (strFieldInfo != "")
{
strFieldInfo += ", ";
}
strFieldInfo += "\"" + field.StaticName + "\"";
}
strRet += strFieldInfo + "<br />-----<br />";
}
//Output the results
lblOutput.Text = strRet;
Now, you'll have an idea of how many content types your list has and what fields are in the list.
By default, if content type management is not enabled, you'll have one content type that has all the fields.
Sample output from the above code:
Content Type: Event, Fields:
"ContentType", "Title", "Location", "EventDate", "EndDate", "Description", "fAllDayEvent", "fRecurrence", "WorkspaceLink", "EventType", "UID", "RecurrenceID", "EventCanceled", "Duration", "RecurrenceData", "TimeZone", "XMLTZone", "MasterSeriesItemID", "Workspace", "Course", "CourseLocation"
Next Step 2 is to change the order of the content type. You can cut and paste from the output from step 1, re-order it, and add "{" and "};" around it to create the string array for the ordering you want.
if (list.ContentTypes.Count > 0)
{
SPContentType ct = list.ContentTypes[0]; //Specify the content type here, if you have more than one content type in your list.
string[] fieldnames = { "ContentType", "Title", "Course", "CourseLocation", "EventDate", "EndDate", "Description", "fAllDayEvent", "fRecurrence", "WorkspaceLink", "EventType", "UID", "RecurrenceID", "EventCanceled", "Duration", "RecurrenceData", "TimeZone", "XMLTZone", "MasterSeriesItemID", "Workspace", "Location"};
ct.FieldLinks.Reorder(fieldnames);
web.AllowUnsafeUpdates = true;
ct.Update(true);
web.AllowUnsafeUpdates = false;
}

Categories

Resources