Problem in SharePoint Object model when accessing the sharepoint list items? - sharepoint

just i wrote
using (SPSite site = SPContext.Current.Site)
{
using (SPWeb web = site.OpenWeb())
{
//SPList lst = web.Lists["ManagerInfo"];
SPList lst = web.Lists[strlist];
SPQuery getUserNameQuery = new SPQuery();
// getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"Region\" /><Value Type=\"Text\">" + strRegion + "</Value></Eq><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></And></Where>";
// getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></Where>";
getUserNameQuery.Query = "<Where><Eq><FieldRef Name=\"PM_x0020_Name\" /><Value Type=\"Text\">" + loginName + "</Value></Eq></Where>";
SPListItemCollection items = lst.GetItems(getUserNameQuery);
foreach (SPListItem item in items)
{
managerFName = item["Manager Name"].ToString();
strAccounting = item["Accounting"].ToString();
managerFName = managerFName.Replace(".", " ");
strAccounting = strAccounting.Replace(".", " ");
// isFound = true;
XPathNavigator managerName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtManagerName", NamespaceManager);
managerName.SetValue(managerFName);
XPathNavigator accountingName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtAccountingName", NamespaceManager);
accountingName.SetValue(strAccounting);
}
}
}
i used this code in infopath this infopath is using by all users.os when the current login user have no permissions to the list it showing error.when the current login user have full Permission it is working.
So Please advise me what can i do inorder to work them for all users.

By using this
using (SPSite site = SPContext.Current.Site){}
You are disposing of SPContext.Current.Site which you should not do. Taking Don's suggestion into consideration as well, try this
SPSecurity.RunWithElevatedPrivileges(delegate()
{
using (SPSite site = new SPSite(SPContext.Current.Site.ID))
{
using (SPWeb web = site.OpenWeb(SPContext.Current.Web.ID))
{
//SPList lst = web.Lists["ManagerInfo"];
SPList lst = web.Lists[strlist];
SPQuery getUserNameQuery = new SPQuery();
// getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"Region\" /><Value Type=\"Text\">" + strRegion + "</Value></Eq><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></And></Where>";
// getUserNameQuery.Query = "<Where><And><Eq><FieldRef Name=\"PM_x0020_First_x0020_Name\" /><Value Type=\"Text\">" + pmFName + "</Value></Eq><Eq><FieldRef Name=\"PM_x0020_Last_x0020_Name\" /><Value Type=\"Text\">" + pmLname + "</Value></Eq></And></Where>";
getUserNameQuery.Query = "<Where><Eq><FieldRef Name=\"PM_x0020_Name\" /><Value Type=\"Text\">" + loginName + "</Value></Eq></Where>";
SPListItemCollection items = lst.GetItems(getUserNameQuery);
foreach (SPListItem item in items)
{
managerFName = item["Manager Name"].ToString();
strAccounting = item["Accounting"].ToString();
managerFName = managerFName.Replace(".", " ");
strAccounting = strAccounting.Replace(".", " ");
// isFound = true;
XPathNavigator managerName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtManagerName", NamespaceManager);
managerName.SetValue(managerFName);
XPathNavigator accountingName = MainDataSource.CreateNavigator().SelectSingleNode("/my:myFields/my:txtAccountingName", NamespaceManager);
accountingName.SetValue(strAccounting);
}
}
}
});

try to surround your code logic with :
SPSecurity.RunWithElevatedPrivileges(delegate()
{
// insert code here
}

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.

Filter a sharepoint visual web part through created by column through code

I created a visual web part and loading the list in Grid. Now when User A login it has to display only the items which are created by user A. USER B it has to display only the items that belong to USER b. Here is the code which i have written.It Display all the items irrespective of the logged in user. Can any one help me on this
public void Displaylistdata()
{
// System.Diagnostics.Debugger.Break();
DataTable dt = new DataTable();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Participation at a Glance"];
string strCreatedby = SPContext.Current.Web.Author.Name;
SPQuery oQuery = new SPQuery();
oQuery.Query = "<Query><Where><Eq><FieldRef Name='Author' /><Value Type='User'>" + strCreatedby + "</Value></Eq></Where></Query>";
SPListItemCollection collListItems = oSpList.GetItems(oQuery);
DataTable dts = collListItems.GetDataTable();
if (dts != null)
{
Gridview1.GridLines = GridLines.None;
Gridview1.DataSource = dts;
Gridview1.DataBind();
Controls.Add(Gridview1);
}
else`enter code here`
{
lbl_noact.Visible = true;
lbl_noact.Text = "We apologize there are no times currently available.";
}
}
Hi I have fixed by changing my Camel query as below. Previously the data type is USER but when i changed to string it works like a charm :-)
DataTable dt = new DataTable();
var oSPWeb = SPContext.Current.Web;
SPList oSpList = oSPWeb.Lists["Participation at a Glance"];
string strCreatedby = SPContext.Current.Web.CurrentUser.Name;
SPQuery oQuery = new SPQuery();
oQuery.Query = #"<Where><Eq><FieldRef Name='Author' /><Value Type='String'>" + strCreatedby + "</Value></Eq></Where>";
SPListItemCollection collListItems = oSpList.GetItems(oQuery);

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

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.

Get the URL of a List in sharepoint using Caml Query

I am using SPSiteDataQuery to display documents from different lists. I display the documents using a Gridview. One of the columns of the Gridview is an hyperlinkfield. How can I set the url of each document since each of them comes from different different document libraries? For your information, I am using Caml Query to filter the documents.
Please help me.
here is the code:
using System;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using Microsoft.SharePoint;
using System.Data;
using Microsoft.SharePoint.Utilities;
namespace Uniway.FOD.Intranet.ControlTemplates
{
public partial class Documents : UserControl
{
protected void Page_Load(object sender, EventArgs e)
{
GridView1.DataSource = GetAllDocuments();
// Set up the field bindings.
BoundField boundField = new BoundField();
boundField.HeaderText = "File name";
boundField.DataField = "Title";//"LinkFilename";
GridView1.Columns.Add(boundField);
HyperLinkField hyperlinkField = new HyperLinkField();
hyperlinkField.HeaderText = "Link name";
hyperlinkField.DataTextField = "LinkFileName";
hyperlinkField.DataNavigateUrlFields = new[] { "LinkFileName" };
hyperlinkField.DataNavigateUrlFormatString = "{0}";
GridView1.Columns.Add(hyperlinkField);
BoundField boundField2 = new BoundField();
boundField2.HeaderText = "Link File Name";
boundField2.DataField = "LinkFilename";
GridView1.Columns.Add(boundField2);
GridView1.DataBind();
}
public DataTable GetAllDocuments()
{
SPSiteDataQuery objSPSiteDataQuery = null;
SPWeb objSPWeb = null;
DataTable objDataTable = null;
objSPWeb = SPContext.Current.Web;
objSPSiteDataQuery = new SPSiteDataQuery();
//Specify the fields to be fetched in the results.Similar to select clause of an SQL query
objSPSiteDataQuery.ViewFields = "<FieldRef Name=\"LinkFilename\"/>" +
"<FieldRef Name=\"Title\" />" +
"<FieldRef Name=\"Created\" />" +
"<FieldRef Name=\"Modified\"/>" +
"<FieldRef Name=\"Editor\"/>";
//specifying list server template=101 so that it will query only document libraries
objSPSiteDataQuery.Lists = "<Lists ServerTemplate=\"101\" BaseType=\"1\" Hidden=\"FALSE\" MaxListsLimit=\"0\"/>";
objSPSiteDataQuery.RowLimit = 1000;
objSPSiteDataQuery.Webs = "<Webs Scope=\"Recursive\"/>";
//querying all documents of the content type 'CT23December1' having version=1.0
objSPSiteDataQuery.Query = #"<Where>
<Eq>
<FieldRef Name='File_x0020_Type' />
<Value Type='Text'>doc</Value>
</Eq>
</Where><OrderBy><FieldRef Name='Modified' Ascending='False' /></OrderBy>";
objDataTable = objSPWeb.GetSiteData(objSPSiteDataQuery);
return objDataTable;
}
}
}
You can use some internal fields to build a link to the document. Here are some useful ones with an example of the data in each field:
FileRef - 1;#sites/SiteCollection/Kit/Kits Site Documents/Excel Report.xls
FileLeafRef - 1;#Excel Report.xls
FileDirRef - 1;#sites/SiteCollection/Kit/Kits Site Documents
ServerUrl - /sites/SiteCollection/Kit/Kits Site Documents/Excel Report.xls
EncodedAbsUrl - http://server/sites/SiteCollection/Kit/Kits%20Site%20Documents/Excel%20Report.xls
You'll just add one of the fields above as another viewfield to objSPSiteDataQuery.ViewFields:
objSPSiteDataQuery.ViewFields = "<FieldRef Name=\"ServerUrl\"/>" +
"<FieldRef Name=\"LinkFilename\"/>" +
"<FieldRef Name=\"Title\" />" +
"<FieldRef Name=\"Created\" />" +
"<FieldRef Name=\"Modified\"/>" +
"<FieldRef Name=\"Editor\"/>";
I did it like this:
row["AbsolutePath"] = String.Format("{0}{1}", row["EncodedAbsUrl"], row["FileRef"].ToString().Substring(row["FileRef"].ToString().IndexOf("#") + 1));

how to use caml queries for optional search values in sharepoint

I have a custom search webpart in Sharepoint which have 7 filters. I am getting data from a Sharepoint list using CAML Query. I want to write a generalized SPQuery which will filter out the data based on the search parameters. The search parameters are optional . If user enters any 2 parameters then I need to get data corresponding to those 2 parameters specified. How do I use CAML Query to achieve this? I am unable to think of a generalized approach for generating my caml query based on search parameters..
Here is a bit of code I used in Silverlight to generate a CAML query based on search parameters.
Maybe it is helpful.
private ClientContext context;
private Microsoft.SharePoint.Client.List SampleSPList;
private Microsoft.SharePoint.Client.ListItemCollection SampleSPCollection;
//Load the List
void LoadList()
{
SampleSPList = context.Web.Lists.GetByTitle("Sample");
context.Load(SampleSPList);
CamlQuery query = new Microsoft.SharePoint.Client.CamlQuery();
string camlQueryXml = "";
bool existsWhere = false;
if (searchString.Text != "")
{
camlQueryXml = camlQueryXml + "<Contains><FieldRef Name='sampleString' /><Value Type='Text'>" + searchString.Text + "</Value></Contains>";
if (existsWhere == true) {
camlQueryXml = "<And>" + camlQueryXml + "</And>";
}
existsWhere = true;
}
if (searchTextArea.Text != "")
{
camlQueryXml = camlQueryXml + "<Contains><FieldRef Name='sampleTextArea' /><Value Type='Text'>" + searchTextArea.Text + "</Value></Contains>";
if (existsWhere == true)
{
camlQueryXml = "<And>" + camlQueryXml + "</And>";
}
existsWhere = true;
}
if (existsWhere == true) { camlQueryXml = "<View><Query><OrderBy><FieldRef Name='ID' /></OrderBy><Where>" + camlQueryXml + "</Where></Query></View>"; }
else { camlQueryXml = "<View><Query><OrderBy><FieldRef Name='ID' /></OrderBy></Query></View>"; }
query.ViewXml = camlQueryXml;
SampleSPCollection = SampleSPList.GetItems(query);
context.Load(SampleSPCollection);
context.ExecuteQueryAsync(ListLoaded, ListLoadFailed);
}
actually solved the issue by writing logic to dynamically generate the spquery

Resources