Get the lookup field value for a list item in SharePoint 2010 using C# - sharepoint-2010

I am relatively new to sharepoint and I'm trying to write a web service to return our sharepoint inventory data as xml. It works good except that one of those list includes a lookup field and the generated xml contains "Microsoft.SharePoint.Client.FieldLookupValue" instead of the expected string value of the lookup field.
This is the code I'm using to generate the xml:
resultList = remoteWeb.Lists.GetByTitle("Cam Devices");
context.Load(resultList);
context.ExecuteQuery();
//Now its time to reach list's items
items = resultList.GetItems(new CamlQuery());
context.Load(items);
context.ExecuteQuery();
foreach (ListItem item in items)
{
rootNode.AppendChild(doc.CreateElement("ID")).InnerText = "pcat:401824";
rootNode.AppendChild(doc.CreateElement("Category")).InnerText = "Cam Devices";
rootNode.AppendChild(doc.CreateElement("Kimlik")).InnerText = Convert.ToString(item["ID"]);
rootNode.AppendChild(doc.CreateElement("Isim")).InnerText = Convert.ToString(item["Location0"]) + " >> " + Convert.ToString(item["Brand"]) + " >> " + Convert.ToString(item["ID"]);
}
item["Location"] is the lookup field and it has a value with the type FieldLookupValue, how can I get the lookup value as a string?

Ok, successfully get the lookup field's value by using following code syntax:
string Location = "";
if (item["Location0"] != null)
{
var fl = (SPFieldLookupValue)item["Location0"];
Location = fl.LookupValue;
}

Related

SSRS/ASP.NET Setting all required report input parameters but still getting:One or more parameters required to run the report have not been specified

Although this has been asked before, none of the answers provided solve my issue. I AM passing in all of the required report parameters and all have HasValidValue set in the State property of the parameter array of ExecutionInfo. I am using ReportExecution2005.asmx in my ASP.NET web application. There is no GetParameters() call method to ReportExecution2005.ReportExecutionService object.
My report is calling a subreport so the input parameters are identical to the main report and the subreport. There are 4 single value inputs (two integer, two text) and then one Multivalue text input parameter which I supply multiple values for. I have double and tripled checked that the values I'm setting in the Multivalue input parameter match exactly one of the default parameters.
Here is the code that setups up the reports and renders/writes it out to a PDF file:
protected void btnPrintReq_Tests_Click(object sender, EventArgs e)
{
string query = string.Format("SELECT PatientFName, PatientLName, Address1 + ' ' + Address2 AS Address, City, Region AS State, PostalCode, Email, Phone, Gender, DOB, CONVERT(VARCHAR, ClinicID) AS ClinicID FROM Tbl_ShippingDropShip WHERE RequestID = {0}", giRequestID.ToString());
string sClinicID = string.Empty;
try
{
//get the drop ship test order details
SqlDataReader reader = default(SqlDataReader);
reader = o_cSQL.RunSQLReturnDataReader(query);
REService.ReportExecutionService rs_ext = new REService.ReportExecutionService();
rs_ext.Credentials = System.Net.CredentialCache.DefaultCredentials;
rs_ext.Url = ConfigurationManager.AppSettings["ReportExecutionServer"];
List<string> ordereditems = new List<string> { };
ordereditems = GetOrderedItems(); //panels and profiles
int numordereditems = ordereditems.Count;
List<String> comments = new List<String>();
if (cbIce.Checked)
comments.Add("Ice");
if (cbKit.Checked)
comments.Add("Kit");
if (cbSwabs.Checked)
comments.Add("Swabs");
if (cbGoldTop.Checked)
comments.Add("Gold Top");
if (cbNeedlePack.Checked)
comments.Add("Needle Pack");
if (cbButterflyPack.Checked)
comments.Add("Butterfly Pack");
if (comments.Count == 0)
comments.Add("");
byte[] result = null;
string historyID = null;
string devInfo = null;
string encoding;
string mimeType;
string extension;
REService.Warning[] warnings = null;
string[] streamIDs = null;
//define the size of the parameter array to pass into the REService
REService.ParameterValue[] rValues = new REService.ParameterValue[4 + numordereditems];
while (reader.Read())
{
sClinicID = reader["ClinicID"].ToString();
rValues[0] = new REService.ParameterValue();
rValues[0].Name = "ClinicID";
rValues[0].Value = sClinicID;
rValues[1] = new REService.ParameterValue();
rValues[1].Name = "ReqFormID";
rValues[1].Value = giRequestID.ToString();
rValues[2] = new REService.ParameterValue();
rValues[2].Name = "DropShipID";
rValues[2].Value = giDropShipID.ToString();
rValues[3] = new REService.ParameterValue();
rValues[3].Name = "Comments";
rValues[3].Value = string.Join(",",comments.ToArray());
int j = 0;
for (int i = 4; i < rValues.Length; i++)
{
rValues[i] = new REService.ParameterValue();
rValues[i].Name = "PanelsNProfiles";
rValues[i].Label = "Panels and Profiles :";
rValues[i].Value = ordereditems[j++];
}
}
REService.ExecutionInfo res_info = new REService.ExecutionInfo();
res_info = rs_ext.LoadReport("/zReportSandbox/RequisitionDS", historyID);
res_info = rs_ext.SetExecutionParameters(rValues, "en-us");
res_info = rs_ext.GetExecutionInfo();
result = rs_ext.Render("PDF", devInfo, out extension, out encoding, out mimeType, out warnings, out streamIDs);
string pdfFile = "Requisition_" + giRequestID.ToString() + "_"+ txtPatientName_Edit.Text + ".pdf";
string sPDFSavePath = ConfigurationManager.AppSettings["Shipping_Requisitions"] + sClinicID;
//add the date pathing
sPDFSavePath = ReportHelper.CreateDateDirectories(sPDFSavePath);
//make sure the file doesn't already exist and if it does, delete it so we create a new one
ReportHelper.checkPDFfilesNDirectory(sPDFSavePath +#"\", pdfFile);
FileStream stream = File.Create(sPDFSavePath + #"\" + pdfFile, result.Length);
stream.Write(result, 0, result.Length);
stream.Close();
}
catch(Exception ex)
{
Common.CommonUtilities.FatalError(sPageName, "btnPrintReq_Tests_Click", query, ex.Message.ToString(), ex.ToString());
}
}
I have noticed that the ExecutionInfo item shows me all parameters in the array of the report, meaning the required INPUT parameters AND the INTERNAL parameters, but also noticed that for the INTERNAL parameters, the default value that was set in the report is satisfied and ExecutionInfo shows them with the State of HasValidValue.
The following list is what I know
the report works on its own, so the Main report that calls the Subreport has no issues creating the PDF
there report when run in SSRS does prompt for the 4 input parameters
I have tried the removal of the report in SSRS and redeployed it because there were many that suggested this somehow fixes issues like this.
I have tried the Insert a table, delete the columns and put subreport in one cell of table trick and still the same error.
It would be nice if the error would state what parameter it sees as not being satisfied, even if there are more than one, then simply listing the first one before erroring out would help a developer work through the issues.
The attached picture shows the values I'm passing in for the multivalue parameters (PanelsNProfiles). I'm also attaching my RDL files for the main report and the Subreport, but had to add a (.txt) file extension to them to be able to upload them.
Here is the error in the SSRS execution log:
library!ReportServer_0-57!5250!03/23/2022-09:06:27:: i INFO: RenderForNewSession('/zReportSandbox/RequisitionDS')
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: , Microsoft.ReportingServices.ReportProcessing.ReportProcessingException: One or more parameters required to run the report have not been specified.;
reportrendering!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: Throwing Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: , Microsoft.ReportingServices.ReportProcessing.RenderingObjectModelException: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS.;
processing!ReportServer_0-57!5250!03/23/2022-09:06:27:: e ERROR: An error has occurred while processing a sub-report. Details: One or more parameters were not specified for the subreport, 'RequisitionTopDS', located at: /zReportSandbox/RequisitionTopDS. Stack trace:
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.FinalizeErrorMessageAndThrow()
at Microsoft.ReportingServices.OnDemandReportRendering.SubReport.RetrieveSubreport()

multiple search in domino documents

In the onclick event of a button , I would like to search for a notes document , with multiple conditions with ssjs.
I have a form with a few fields. Now I would like to find a notes document where field a="123" and field b="456" field c="789" and field d >"A123456" , and then I would like to read the contents of field e.
If it was the search in a view I would use something like :
var tmpArray = new Array("");
var cTerms = 0;
if(viewScope.fong != null & viewScope.fong != "") {
tmpArray[cTerms++] = "(FIELD Site = \"" + viewScope.fong + "\")"
}
if(#Text(viewScope.sDate) != null & #Text(viewScope.sDate) != "") {
tmpArray[cTerms++] = "(FIELD StartDate = \"" + #Text(viewScope.sDate) + "\")"
}
qstring = tmpArray.join(" AND ").trim();
viewScope.queryString = qstring;
return qstring
If I only had 1 condition I would have used #DbLookup (and still how select documents >"A123456"?)
What's the best way of dooing this in ssjs ?
UPDATE
tried with FTSearch , but it seems in the searchkey "FIELD d > A123456" , doesn't seem to work
OTHER UPDATE
var dc = db.FTSearch("FIELD a=123 and FIELD b =456 and FIELD d =A123456");
seems to work but
var dc = db.FTSearch("FIELD a=123 and FIELD b =456 and FIELD d >A123456"); doesn't. It gives error : Exception occurred calling method NotesDatabase.FTSearch(string) null
If you want to use comparison operators > and <, then you need to use the NotesDatabase.Search method instead of FTSearch. Search is slower and can't access data in non-summary (i.e., rich text) fields, but it has all the same capabilities that you can use in a view selection formula.

How to get the datatype of column from the sharepoint list?

I want to get or retrieve the datatype of a particular column where
the list is created in a sharepoint list.
Can you help me for doing the task?
See SPField.Type (or SPField.TypeDisplayName).
SPList list = web.Lists["my list"];
SPField field = list.Fields["particular"];
SPFieldType fieldType = field.Type;
string fieldTypeName = field.TypeDisplayName;
Building off of Rich Bennema's answer (referencing the Microsoft.SharePoint.Client and Microsoft.SharePoint.Client.RunTime version 16 libriaries and using the Microsoft.SharePoint.Client name space):
using (ClientContext cont = new ClientContext(SharePointUrl))
{
cont.Credentials = new SharePointOnlineCredentials(Username, SecurePassword);
FieldCollection fields = cont.Web.Lists.GetByTitle(SharePointListName).Fields;
cont.Load(fields);
cont.ExecuteQuery();
var results =
fields.Select(
f => new
{
f.InternalName,
f.TypeDisplayName,
TextMaxLength = (f is FieldText) ? ((FieldText)f).MaxLength : 0,
FieldChoices = (f is FieldChoice) ? ((FieldChoice)f).Choices : new string[0]
}
);
}

Attributes of tables in VS by coding with C#

I have this table:
Please, don't mind because it's on my native language and it doesn't matter..
Those are all attributes in table but when I go to Visual StudioS and try to use some of this I get this one:
I see all "normal" attributes in VS but where is those FK attributes?
I need them to compare few ones and get values?
I can't use it from name of other tables [dot] attribute etc...
like for example:
I need this: table1.ID == table2.ID
and not this: table1.ID == table1.table2.ID
Where or what is FK attribute in VS that is shown in SQL table ??
public void setParametri(int desID)
{
foreach (desavanje d in DM_Class.dc.desavanje)
if (d.desavanjeID == desID)
{
//THIS FIRST 4 LINES WORKS PERFECTLY
this.naziv_des = d.naziv_des;
this.datum_po = d.datum_pocetka.ToString();
this.datum_zav = d.datum_kraja.ToString();
this.cijena = d.cijena_des;
//foreach (klijenti k in DM_Class.dc.klijenti)
//{
// if(k.klijentID == //WHAT TO PUT HERE TO COMPARE VALUE klijentID from tables klijenti with FK value in table desavanje)
// this.klijent = k.Ime + ' ' + k.Prezime;
//}
//ON THIS LINE I'M GETTING ERROR - Object reference not set to an instance of an object. but why?
//I have data on that field in DB ?
//this.grad = d.mjesto_desavanja.gradovi.naziv_grada.ToString();
//this.mjesto = d.mjesto_desavanja.naziv_objekta;
//this.organizator = d.organizator.Ime + ' ' + d.organizator.Prezime;
//this.tip = d.tip_desavanja.vrsta_des;
this.klijent = d.klijenti.Ime + ' ' + d.klijenti.Prezime;
//this.status = d.status_desavanja.naziv_statusa;
//this.br_gost = d.specifikacija_desavanja.br_osoba;
}
}
If is there other solution to get values for attributes I'm willing to try it without using another foreach loop?
Ok, I managed this.. I've used a linq query to generate data that I need and in that queries I've compared needed ID's and finally get some working stuff.

SharePoint 2010 "foreach"

I have 2 SharePoint lists, and I have to copy all items from List1 to List2.
On List1 there is a boolean field (defaults to 'no'), a text field and an associated WorkFlow which triggers on modifications.
The WokFlow simplified:
Copy current item to List2
Set my boolen field to 'yes'
Search for an item with boolen field 'no', set its text field to 'copy'
I start the process by modifing an item in List1, then it will copy itself to List2, modifies an another item, and so on... until there is any item with a boolen field set to 'no'.
This works perfectly for 10 items, but then it fails. Item 10 modified item 11's text field to 'copy', but item 11's WorkFlow does not started. I've tried it serval times, and always stopped after 10 copies.
I've Googled and MSDN'd. The best solution I've found is to pause for 1 minute in the WorkFlow. But I have thousands of items...
Has anyone any advice? I even cant find any limit in the SharePoint 2010 server that defaults to 10.
Thank You!
You are triggering a hardcoded resource throttle in SharePoint 2010 due to the speed on the workflow. It's there to prevent the system from becoming unresponsive during workflow operations. Code in an application page or timer job will get around this limit but it's not recommended to have a greedy operation that cause the system to become unresponsive to users.
You can do CAML batch methods.
somethig like this:
void UpdateList()
{
StringBuilder methodBuilder = new StringBuilder();
string batch = string.Empty;
string newValue="mmmm";
string updateColumn = "SampleColumn";
try
{
string batchFormat = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" +
"<ows:Batch OnError=\"Continue\">{0}</ows:Batch>";
string methodFormat = "<Method ID='{0}' >" +
"<SetList>{1}</SetList>" +
"<SetVar Name='Cmd'>Save</SetVar>" +
"<SetVar Name='ID'>{2}</SetVar>" +
"<SetVar Name='urn:schemas-microsoft-com:office:office#{3}'>{4}</SetVar>" +
"</Method>";
using (SPSite siteCol = new SPSite("SampleSite"))
{
using (SPWeb web = siteCol.OpenWeb())
{
// Get the list containing the items to update
SPList list = web.Lists["SampleList"];
string listGuid = list.ID.ToString();
SPListItemCollection allItems = list.GetItems();
// Build the CAML update commands.
for (int i = 0; i < allItems.Count; i++)
{
int itemID = allItems[i].ID;
methodBuilder.AppendFormat(methodFormat, itemID, listGuid, itemID, updatedColumn, newValue);
}
web.AllowUnsafeUpdates = true;
// Generate the CAML
batch = string.Format(batchFormat, methodBuilder.ToString());
// Process the batch
string batchReturn = web.ProcessBatchData(batch);
}
//done
}
}
catch (Exception ex)
{
//show the error
}
}
You can create batch methods for create , delete and update items on lists and document libraries.
Refs:
http://msdn.microsoft.com/en-us/library/office/ms437562%28v=office.15%29.aspx
http://msdn.microsoft.com/en-us/library/office/ms459050(v=office.15).aspx
if you want to change workflow concurrent execution limits ....
For check limits:
Get-SPFarmConfig | Select WorkflowPostponeThreshold
For change
Set-SPFarmConfig -WorkflowPostponeThreshold 50
Timer service process items ( workflows continuations) on batch sizes
Get-SPFarmConfig | Select WorkflowBatchSize
Set-SPFarmConfig -WorkflowBatchSize 150