SPQuery search doesn't work with "BeginsWith" - sharepoint

So, my problem is that my knowledge of CAML and Sharepoint is very poor.
Question: I need SPQuery for building query search, search text I have from textbox. I expect that my query returns me item(s) (for example, I type in textbox "Jo" and query returns me all items with surname "Johnson", or name "John", etc)
1)TextChanged works ok. I've check it, there is ok
2) SPGridView views items ok. Items from SPList I add to gridView - there are viewd by gridview.
3) But my query doesn't work. Please, help with links/advises
public class VisualWebPart1 : WebPart
{
SPSite site;
SPWeb web;
SPGridView gridView;
SPDataSource dataSource;
TextBox searchTextBox;
UpdatePanel panel;
SPList list;
SPList resultList;
string currentList;
// Visual Studio might automatically update this path when you change the Visual Web Part project item.
private const string _ascxPath = #"~/_CONTROLTEMPLATES/CRMSearchWebPart/VisualWebPart1/VisualWebPart1UserControl.ascx";
protected override void CreateChildControls()
{
gridView = new SPGridView();
searchTextBox = new TextBox();
panel = new UpdatePanel();
searchTextBox.AutoPostBack = true;
searchTextBox.Visible = true;
searchTextBox.Enabled = true;
searchTextBox.TextChanged += new EventHandler(searchTextBox_TextChanged);
gridView.Visible = true;
gridView.Enabled = true;
gridView.AutoGenerateColumns = false;
AddColumnToSPGridView("Surname", "Surname");
panel.UpdateMode = UpdatePanelUpdateMode.Conditional;
panel.ContentTemplateContainer.Controls.Add(searchTextBox);
panel.ContentTemplateContainer.Controls.Add(gridView);
Control control = Page.LoadControl(_ascxPath);
Controls.Add(control);
Controls.Add(panel);
}
protected override void Render(HtmlTextWriter writer)
{
panel.RenderControl(writer);
}
//Open WebSite with List "listName"
private void OpenWebSite(string listName)
{
site = SPContext.Current.Site;
web = site.OpenWeb();
list = web.Lists[listName];
}
//Add Column to gridView
private void AddColumnToSPGridView(string HeaderText, string Datafield)
{
SPBoundField boundField = new SPBoundField();
boundField.HeaderText = HeaderText;
boundField.DataField = Datafield;
gridView.Columns.Add(boundField);
}
//Build query for search; fieldName - Name of column of current List, searchQuery - our query
private string BuildQuery(string fieldRefName, string searchQuery)
{
string query = "";
switch (fieldRefName)
{
case "Surname":
query = "<Where><BeginsWith><FieldRef Name='Surname'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
case "Name":
query = query = "<Where><BeginsWith><FieldRef Name='Name'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
case "PassportNumber":
query = "<Where><BeginsWith><FieldRef Name='PassportNumber'/>" +
"<Value Type=Text>"+searchQuery+"</Value></BeginsWith></Where>";
break;
default: break;
}
return query;
}
// search in List for selected items and returns SPGridView
private void searchTextBox_TextChanged(object sender, EventArgs e)
{
dataSource = new SPDataSource();
string querySearch = searchTextBox.Text;
OpenWebSite("Surnames");
string query = BuildQuery("Surname", querySearch);
SPQuery spQuery = new SPQuery();
spQuery.ViewFields = "<FieldRef Name = 'Title'/><FieldRef Name = 'Surname'/><FieldRef Name = 'Name'/>";
spQuery.Query = query;
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
searchTextBox.Text += item["Surname"] + " ";
}
//resultList = web.Lists["TempSurnames"];
//resultList = AddItemsToSPList(resultList, items);
BindDataSource(dataSource, resultList);
//resultList = AddSPList("Result2", "Result list");
//resultList = AddItemsToSPList(resultList, items);
list = AddItemsToSPList(list, items);
//BindDataSource(dataSource, resultList);
BindDataSource(dataSource, list);
BindGridView(gridView, dataSource);
//var item = list.Items[3];
//var item = resultList.Items[1];
//searchTextBox.Text = item["Surname"].ToString();
//resultList.Delete();
}
//Binds datasource of existing gridView with SPDataSource
private void BindGridView(SPGridView gridview, SPDataSource datasource)
{
gridview.DataSource = datasource;
gridview.DataBind();
}
//Add SPListItem items to SPList
private SPList AddItemsToSPList(SPList spList, SPListItemCollection collection)
{
foreach (SPListItem item in collection)
{
var listItem = spList.AddItem();
listItem = item;
}
return spList;
}
//Binds existing SPDataSource to SPList
private void BindDataSource(SPDataSource spDataSource, SPList spList)
{
spDataSource.List = spList;
}
private SPList AddSPList(string listName, string listDescription)
{
OpenWebSite("Surnames");
SPListCollection collection = web.Lists;
collection.Add(listName, listDescription, SPListTemplateType.CustomGrid);
resultList = web.Lists[listName];
return resultList;
}
Update:
This part gives me an error:
SPListItemCollection items = list.GetItems(query);
foreach (SPListItem item in items)
{
searchTextBox.Text += item["Surname"] + " ";
}
System.ArgumentException: Value does not fall within the expected
range

You have to include the field Surname into the view fields of the query:
SPQuery query = // ...
query.ViewFields = "<FieldRef Name='Surname' />";
// ...
You can understand the view fields like the SELECT part of a SQL query.

Have you debugged your code to check the query string that is generated? Also, you have query = query = under the Name switch.
Also, you know that the switch is case sensitive, so ensure you enter your searchQuery option appropriately.

Related

Update/Change custom TaxonomyFieldValue in document library list in sharepoint using C# CSOM

list of documents thats contains custom taxonomy field column named subject.
Need to update subject of thousands records/documents.
Please any idea to update the taxonomy field such subject programtically using C# CSOM
Please try to use this method:
public void UpdateTaxonomyField(ClientContext ctx, List list,ListItem listItem,string fieldName,string fieldValue)
{
Field field = list.Fields.GetByInternalNameOrTitle(fieldName);
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = new TaxonomyFieldValue();
string[] term = fieldValue.Split('|');
termValue.Label = term[0];
termValue.TermGuid = term[1];
termValue.WssId = -1;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
ctx.Load(listItem);
ctx.ExecuteQuery();
}
public static void UpdateListofLibraryHavingTaxonomyField()
{
string siteUrl = "http://abc:55555/sites/xyz/";
string libName = "Knowledge Repos";
string strTermGuid = "Your new/update term guid";
try
{
Dictionary<string, string> dictIdsSubjectsChange = ReadFromExcel();//Here to read all records (approx 2000 records) that we want to change
ClientContext clientContext = new ClientContext(siteUrl);
List list = clientContext.Web.Lists.GetByTitle(libName);
FieldCollection fields = list.Fields;
Field field = fields.GetByInternalNameOrTitle("Subject1");
ListItemCollection listItems = list.GetItems(CamlQuery.CreateAllItemsQuery());
clientContext.Load(listItems, items => items.Include(i => i["Subject1"], i => i["ID"]));
clientContext.Load(fields);
clientContext.Load(field);
clientContext.ExecuteQuery();
TaxonomyField txField = clientContext.CastTo<TaxonomyField>(field);
TaxonomyFieldValue termValue = null;
if (dictIdsSubjectsChange != null)
{
foreach (ListItem listItem in listItems)//Loop through all items of the document library
{
string strCurrentID = "0";
try
{
strCurrentID = listItem["ID"].ToString();
}
catch (Exception) { }
if (dictIdsSubjectsChange.ContainsKey(strCurrentID))//Checking to change ot not
{
termValue = new TaxonomyFieldValue();
termValue.Label = "Special Knowledge";
termValue.TermGuid = strTermGuid;
termValue.WssId = 246;
txField.SetFieldValueByValue(listItem, termValue);
listItem.Update();
clientContext.Load(listItem);
}
}
clientContext.ExecuteQuery();
}
}
catch (Exception ex) { }
}
}

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;
}

Add values to a list contains a Lookup Field

I have a list named "Designation" that contains a Designation Code and Designation Name.
I have another list named "Employee" that contains Employee Name and Designation Name (as a Lookup Field).
I am able to insert values to "Employee" list using the following code.
protected void AddEmp(object sender, EventArgs e)
{
string emp_name = txtEmployeeName.Text;
string emp_designation = ddlDesignation.SelectedValue;
using (SPSite site = new SPSite("My Site"))
{
using (SPWeb web = site.OpenWeb())
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
web.AllowUnsafeUpdates = true;
SPList splist_employees = web.Lists["Employee"];
SPList splist_designations = web.Lists["Designations"];
SPListItemCollection splc_items = splist_employees.Items;
SPListItem spli_item = splc_items.Add();
SPFieldLookup lookup = splist_employees.Fields["Designated"] as SPFieldLookup;
string fieldName = lookup.LookupField;
spli_item["Employee Name"] = emp_name;
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations);
spli_item.Update();
});
}
}
}
public static string GetLookFieldIDS(string lookupValues, SPList lookupSourceList)
{
string id = string.Empty;
SPFieldLookupValueCollection lookupIds = new SPFieldLookupValueCollection();
SPQuery query = new Microsoft.SharePoint.SPQuery();
query.Query = "<Where><Eq><FieldRef Name='Designation' /><Value type='Text'>"+lookupValues + "</Value></Eq></Where>";
SPListItemCollection listItems = lookupSourceList.GetItems(query);
foreach (Microsoft.SharePoint.SPListItem item in listItems)
{
id = item.ID.ToString();
}
return id;
}
Here I have given the field name as 'Designation' inside the query.
But, I want to find the field name based on the value given from the user end instead of hard-coding the field name as 'Designation'.
Any help is greatly appreciated. Thanks in advance.
Not sure about your request but, you could pass SPFieldLookup.LookupField property to your GetLookFieldIDS method and use that variable instead of "Designation"
spli_item[fieldName] = GetLookFieldIDS(emp_designation, splist_designations, lookup.LookupField);

How to add multiple lookup value in sharepoint List.While adding item in sharepoint

My Task have multiple relateddocId for example RelatedDoc="3,5,2,6", now i need to add multiplevalue to the sharepoint lookup fields called related Document which is in task list. how to add this?
For ref see my code below
private static void CreateItem(SPWeb web, SPList TaskList, string FolderURL, string ItemName, string RelatedDoc)
{
var ParentURL = string.Empty;
if (!TaskList.ParentWebUrl.Equals("/"))
{
ParentURL = TaskList.ParentWebUrl;
}
SPListItem _taskList = TaskList.AddItem(ParentURL + FolderURL, SPFileSystemObjectType.File, null);
_taskList["Title"] = ItemName;
string DocName = "4,6,3,6";//Document ref id.
SPFieldLookupValue lookupvalue = new SPFieldLookupValue();
if (DocName != "")
lookupvalue = new SPFieldLookupValue(RelatedDoc, DocName);
_taskList["EYRelatedSharedDocument"] = lookupvalue;
_taskList.Update();
}
SPFieldLookupValueCollection documents = new SPFieldLookupValueCollection();
foreach ( ... )
{
documents.Add(new SPFieldLookupValue(documentId, documentTitle));
}
_taskList["EYRelatedSharedDocument"] = documents;
_taskList.Update();

SharePoint 2010: Count ListItem Attachments using Client Object Model

Does anyone know how to read the number of attachments, and the names etc for a ListItem using the Client .Net Object model in SharePoint?
Thanks
// For getting the list item field information
public void LoadPropertyInfo()
{
using (context = new ClientContext(siteCollectionUrl))
{
spWeb = context.Web;
propertiesList = spWeb.Lists.GetByTitle(listName);
FieldCollection fields = propertiesList.Fields;
context.Load(fields);
SP.CamlQuery query = new SP.CamlQuery();
query.ViewXml = string.Format("<View><Query><Where><Eq><FieldRef Name=\"{0}\" /><Value Type=\"Text\">{1}</Value></Eq></Where></Query></View>", propertyID, PropertyIDValue);
listItems = propertiesList.GetItems(query);
context.Load(listItems);
context.ExecuteQueryAsync(GetRequestSucceeded, RequestFailed);
}
}
// Pass the item id here for getting the attachments
private void GetAttchmentCollection(string id)
{
string RedirectHost = string.Empty;
string Host = string.Empty;
context = SP.ClientContext.Current;
RedirectHost = serviceUrl + "_vti_bin/Lists.asmx";
BasicHttpBinding binding = new BasicHttpBinding();
if (System.Windows.Browser.HtmlPage.Document.DocumentUri.Scheme.StartsWith("https"))
{
binding.Security.Mode = BasicHttpSecurityMode.Transport;
}
binding.MaxReceivedMessageSize = int.MaxValue;
EndpointAddress endpoint = new EndpointAddress(RedirectHost);
ServiceReference1.ListsSoapClient oClient = new ServiceReference1.ListsSoapClient(binding, endpoint);
oClient.GetAttachmentCollectionCompleted += new EventHandler<ServiceReference1.GetAttachmentCollectionCompletedEventArgs>(oClient_GetAttachmentCollectionCompleted);
oClient.GetAttachmentCollectionAsync(listName, id);
}
Your can try this link too.
http://helpmetocode.blogspot.com/2011/11/managed-client-object-models-in.html

Resources