How to show search results with their url's in Umbraco 7 - search

I have implemented search in Umbraco 7 using examine and user control. Search is working fine. Now I need to show the URL of the search results displayed on the lists. Is there any index property like "BodyText" which can show the URL or do I have to do some stuff in user control?
User Control code:
public static class SiteSearchResultExtensions
{
public static string FullURL(this Examine.SearchResult sr)
{
return umbraco.library.NiceUrl(sr.Id);
}
}
public partial class SiteSearchResults : System.Web.UI.UserControl
{
#region Properties
private int _pageSize = 5;
public string PageSize
{
get { return _pageSize.ToString(); }
set
{
int pageSize;
if (int.TryParse(value, out pageSize))
{
_pageSize = pageSize;
}
else
{
_pageSize = 10;
}
}
}
private string SearchTerm
{
get
{
object o = this.ViewState["SearchTerm"];
if (o == null)
return "";
else
return o.ToString();
}
set
{
this.ViewState["SearchTerm"] = value;
}
}
protected IEnumerable<Examine.SearchResult> SearchResults
{
get;
private set;
}
#endregion
#region Events
protected override void OnLoad(EventArgs e)
{
try
{
CustomValidator.ErrorMessage = "";
if (!Page.IsPostBack)
{
topDataPager.PageSize = _pageSize;
bottomDataPager.PageSize = _pageSize;
string terms = Request.QueryString["s"];
if (!string.IsNullOrEmpty(terms))
{
SearchTerm = terms;
PerformSearch(terms);
}
}
base.OnLoad(e);
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
protected void searchResultsListView_PagePropertiesChanging(object sender, PagePropertiesChangingEventArgs e)
{
try
{
if (SearchTerm != "")
{
topDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
bottomDataPager.SetPageProperties(e.StartRowIndex, e.MaximumRows, false);
PerformSearch(SearchTerm);
}
}
catch (Exception ex)
{
CustomValidator.IsValid = false;
CustomValidator.ErrorMessage += Environment.NewLine + ex.Message;
}
}
#endregion
#region Methods
private void PerformSearch(string searchTerm)
{
if (string.IsNullOrEmpty(searchTerm)) return;
var criteria = ExamineManager.Instance
.SearchProviderCollection["ExternalSearcher"]
.CreateSearchCriteria(UmbracoExamine.IndexTypes.Content);
// Find pages that contain our search text in either their nodeName or bodyText fields...
// but exclude any pages that have been hidden.
//var filter = criteria
// .GroupedOr(new string[] { "nodeName", "bodyText" }, searchTerm)
// .Not()
// .Field("umbracoNaviHide", "1")
// .Compile();
Examine.SearchCriteria.IBooleanOperation filter = null;
var searchKeywords = searchTerm.Split(' ');
int i = 0;
for (i = 0; i < searchKeywords.Length; i++)
{
if (filter == null)
{
filter = criteria.GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
else
{
filter = filter.Or().GroupedOr(new string[] { "nodeName", "bodyText", "browserTitle", "tags", "mediaTags" }, searchKeywords[i]);
}
}
//SearchResults = ExamineManager.Instance
// .SearchProviderCollection["ExternalSearcher"]
// .Search(filter);
SearchResults = ExamineManager.Instance.SearchProviderCollection["ExternalSearcher"].Search(filter.Compile());
if (SearchResults.Count() > 0)
{
searchResultsListView.DataSource = SearchResults.ToArray();
searchResultsListView.DataBind();
searchResultsListView.Visible = true;
bottomDataPager.Visible = topDataPager.Visible = (SearchResults.Count() > _pageSize);
}
summaryLiteral.Text = "<p>Your search for <b>" + searchTerm + "</b> returned <b>" + SearchResults.Count().ToString() + "</b> result(s)</p>";
// Output the query which an be useful for debugging.
queryLiteral.Text = criteria.ToString();
}
#endregion
}
}
I have done my Examine settings like this:
ExamineIndex.Config
<IndexSet SetName="ExternalndexSet" IndexPath="~/App_Data/TEMP/ExamineIndexes/ExternalIndex/">
<IndexAttributeFields>
<add Name="id"/>
<add Name="nodeName"/>
<add Name="nodeTypeAlias"/>
<add Name="parentID" />
</IndexAttributeFields>
<IndexUserFields>
<add Name="bodyText"/>
<add Name="umbracoNaviHide"/>
</IndexUserFields>
<IncludeNodeTypes/>
<ExcludeNodeTypes/>
</IndexSet>
ExamineSettings.Config
ExamineIndexProviders
<add name="ExternalIndexer" type="UmbracoExamine.UmbracoContentIndexer, UmbracoExamine"
runAsync="true"
supportUnpublished="true"
supportProtected="true"
interval="10"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>
ExamineSearchProvide
<add name="ExternalSearcher" type="UmbracoExamine.UmbracoExamineSearcher, UmbracoExamine"
analyzer="Lucene.Net.Analysis.WhitespaceAnalyzer, Lucene.Net"
indexSet="DemoIndexSet"
/>

It was quite simple and i done some editing in the Usercontrol(SiteSearchresult.ascx)
like this
<li>
<a href="<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>">
<%# ((Examine.SearchResult)Container.DataItem).Fields["nodeName"] %>
<br >
addingvalue.webdevstaging.co.uk<%# ((Examine.SearchResult)Container.DataItem).FullURL() %>
</a>
<p><%# ((Examine.SearchResult)Container.DataItem).Fields.ContainsKey("bodyText") == true ? ((Examine.SearchResult)Container.DataItem).Fields["bodyText"] : ""%></p>
</li>

Related

.NET 6 how to add pages numbers in the view?

I am following the Microsoft tutorial :
https://learn.microsoft.com/fr-fr/aspnet/core/data/ef-mvc/sort-filter-page?view=aspnetcore-6.0
and it works but there is only the button for next and previous...
How to implement the code with the list of the pages numbers between the NEXT and PREVIOUS button?
I created thi code, but i am sure that there is a better way to accomplish this :
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.PageIndex - 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #prevDisabled">
Previous
</a>
#for (int i = 1; i < Model.TotalPages + 1; i++)
{
if (Model.PageIndex == i)
{
<b>#i.ToString()</b>
}
else
{
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#i.ToString()"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default">
#i.ToString()
</a>
}
}
<a asp-action="Index"
asp-route-sortOrder="#ViewData["CurrentSort"]"
asp-route-pageNumber="#(Model.PageIndex + 1)"
asp-route-currentFilter="#ViewData["CurrentFilter"]"
class="btn btn-default #nextDisabled">
Next
</a>
Thanks
You could try LazZiya.TagHelpers .you can find it through Nuget .
Use it in cshtml:
#addTagHelper *,LazZiya.TagHelpers
<paging page-no="Model.PageIndex"
page-size="Model.Pagesize"
total-records="Model.TotalRecords"
>
</paging>
codes in model:
public class PaginatedList<T> : List<T>
{
public int PageIndex { get; private set; }
public int TotalPages { get; private set; }
public int Pagesize { get; private set; }
public int TotalRecords { get; private set; }
public PaginatedList(List<T> items, int count, int pageIndex, int pageSize)
{
PageIndex = pageIndex;
TotalRecords = count;
Pagesize = pageSize;
TotalPages = (int)Math.Ceiling(count / (double)pageSize);
this.AddRange(items);
}
public bool HasPreviousPage
{
get
{
return (PageIndex > 1);
}
}
public bool HasNextPage
{
get
{
return (PageIndex < TotalPages);
}
}
public static async Task<PaginatedList<T>> CreateAsync(IQueryable<T> source, int pageIndex, int pageSize)
{
var count = await source.CountAsync();
var items = await source.Skip((pageIndex - 1) * pageSize).Take(pageSize).ToListAsync();
return new PaginatedList<T>(items, count, pageIndex, pageSize);
}
}
codes in controller:
public async Task<IActionResult> Index(string sortOrder,string currentFilter,string searchString,int? P)
{
ViewData["CurrentSort"] = sortOrder;
ViewData["NameSortParm"] = String.IsNullOrEmpty(sortOrder) ? "name_desc" : "";
ViewData["DateSortParm"] = sortOrder == "Date" ? "date_desc" : "Date";
if (searchString != null)
{
P = 1;
}
else
{
searchString = currentFilter;
}
ViewData["CurrentFilter"] = searchString;
var students = from s in _context.Student
select s;
if (!String.IsNullOrEmpty(searchString))
{
students = students.Where(s => s.LastName.Contains(searchString)
|| s.FirstMiddleName.Contains(searchString));
}
switch (sortOrder)
{
case "name_desc":
students = students.OrderByDescending(s => s.LastName);
break;
case "Date":
students = students.OrderBy(s => s.EnrollmentDate);
break;
case "date_desc":
students = students.OrderByDescending(s => s.EnrollmentDate);
break;
default:
students = students.OrderBy(s => s.LastName);
break;
}
int pageSize = 3;
return View(await PaginatedList<Student>.CreateAsync(students.AsNoTracking(), P ?? 1, pageSize));
}
And The result:

Some trouble with ComboBox in Ext.net

I have a Page which a FormPanel(there's a ComboBox in it) and a TreePanel(has a default root node) in it and open ViewState.
I set a value to ComboBox in GET.
When i GET the page the TreePanel's Store send a POST request(store read) before FormPane rendered in client,in this POST request the fromdata has no info about FormPane.
in the POST request recover the ComboBox.Value from ViewState,but in ComboBoxBase.LoadPostData() Ext.Net get value from formdata and cover ComboBox.Value without precondition
it's ComboBoxBase.LoadPostData() code
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
if (!this.EmptyText.Equals(text) && text.IsNotEmpty())
{
List<ListItem> items = null;
if (this.SimpleSubmit)
{
var array = state.Split(new char[] { ',' });
items = new List<ListItem>(array.Length);
foreach (var item in array)
{
items.Add(new ListItem(item));
}
}
else if(state.IsNotEmpty())
{
items = ComboBoxBase.ParseSelectedItems(state);
}
bool fireEvent = false;
if (items == null)
{
items = new List<ListItem>
{
new ListItem(text)
};
/*fireEvent = this.SelectedItems.Count > 0;
this.SelectedItems.Clear();
return fireEvent;
*/
}
foreach (var item in items)
{
if (!this.SelectedItems.Contains(item))
{
fireEvent = true;
break;
}
}
this.SelectedItems.Clear();
this.SelectedItems.AddRange(items);
return fireEvent;
}
else
{
if (this.EmptyText.Equals(text) && this.SelectedItems.Count > 0)
{
this.SelectedItems.Clear();
return true;
}
}
return false;
}
Look at Line 5 to 11,why not change like this
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
this.SuspendScripting();
this.RawValue = text;
this.ResumeScripting();
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.Value = text;
this.ResumeScripting();
Sample for this question
page file
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
</head>
<body>
<ext:ResourceManager ID="ResourceManager1" runat="server" DisableViewState="false"
AjaxViewStateMode="Enabled" ViewStateMode="Enabled"/>
<form id="form1" runat="server">
<ext:Viewport runat="server" ID="VP">
</ext:Viewport>
</form>
</body>
</html>
cs file
public partial class WebFormTest : System.Web.UI.Page
{
protected override void OnInitComplete(EventArgs e)
{
FP = new FormPanel();
FP.ID = "FP";
FP.Title = "FP";
FP.Region = Region.Center;
TF = new TextField();
TF.ID = "TF";
TF.FieldLabel = "TF";
CB = new ComboBox();
CB.ID = "CB";
CB.FieldLabel = "CB";
CB.Items.Clear();
CB.Items.Add(new ListItem("one", "1"));
CB.Items.Add(new ListItem("two", "2"));
Button test = new Button() { ID = "testbtn", Text = "test" };
test.Listeners.Click.Handler = "App.Store2.load()";
FP.TopBar.Add(new Toolbar() { Items = { test } });
FP.Items.Add(TF);
FP.Items.Add(CB);
GP = new GridPanel();
GP.ID = "GP";
GP.Title = "GP";
GP.Region = Region.East;
GP.Listeners.BeforeRender.Handler = "App.Store1.reload()";
BTN = new Button();
BTN.ID = "BTN";
BTN.Text = "click";
BTN.Icon = Icon.ArrowJoin;
BTN.DirectEvents.Click.Event += new ComponentDirectEvent.DirectEventHandler(Click);
TB = new Toolbar();
TB.Items.Add(BTN);
GP.TopBar.Add(TB);
Store1 = new Store();
Store1.ID = "Store1";
Store1.ReadData += new Store.AjaxReadDataEventHandler(WebFormTest_ReadData);
Model1 = new Model();
Model1.ID = "Model1";
Store1.Model.Add(Model1);
GP.Store.Add(Store1);
TP = new TreePanel();
TP.ID = "TP";
TP.Title = "TP";
TP.Region = Region.East;
TP.RootVisible = false;
TP.Root.Add(new Node() { NodeID = "test", Text = "test" });
Store2 = new TreeStore();
Store2.ID = "Store2";
Store2.ReadData += new TreeStoreBase.ReadDataEventHandler(Store2_ReadData);
TP.Store.Add(Store2);
VP.Items.Add(FP);
//VP.Items.Add(GP);
VP.Items.Add(TP);
if (!X.IsAjaxRequest)
{
CB.Value = "2";
TF.Value = "TEXT";
}
base.OnInitComplete(e);
}
FormPanel FP;
TextField TF;
ComboBox CB;
GridPanel GP;
Button BTN;
Toolbar TB;
Store Store1;
Model Model1;
TreePanel TP;
TreeStore Store2;
protected override void CreateChildControls()
{
base.CreateChildControls();
}
void Store2_ReadData(object sender, NodeLoadEventArgs e)
{
}
protected void Page_Load(object sender, EventArgs e)
{
//if (!X.IsAjaxRequest)
//{
// this.Store1.DataSource = this.Data;
// this.Store1.DataBind();
//}
}
protected void Refresh(object sender, DirectEventArgs e)
{
}
bool flag = false;
protected void Click(object sender, DirectEventArgs e)
{
GP.GetStore().Reload();
flag = true;
}
protected override void OnPreRender(EventArgs e)
{
if (flag)
{
TF.Value = "asdasd";
}
base.OnPreRender(e);
}
protected void WebFormTest_ReadData(object sender, StoreReadDataEventArgs e)
{
}
private object[] Data
{
get
{
return new object[]
{
new object[] { "3m Co", 71.72, 0.02, 0.03, "9/1 12:00am" },
};
}
}
}
you also can discuss in Ext.net Forums
We committed the change to the SVN trunk. It will go to the next release (v2.3).
The change is similar to your one, but we decided not to change RawValue as well. Thank you for the report and suggested fix.
Fix (ComboBoxBase LoadPostData)
protected override bool LoadPostData(string postDataKey, NameValueCollection postCollection)
{
this.HasLoadPostData = true;
string text = postCollection[this.UniqueName];
string state = postCollection[this.ValueHiddenName.IsNotEmpty() ? this.ValueHiddenName : ("_" + this.UniqueName + "_state")];
if (state == null && text == null)
{
return false;
}
this.SuspendScripting();
this.RawValue = text;
this.Value = text;
this.ResumeScripting();

How to highlight page numbers in PagedDataSource to paginate Repeater

I am using PagedDataSource To Paginate Repeater and it works fine but is there a way to highlight selected page number or make it bold. I tried css, itemcommand,and click event but no luck.
Thanks in advance
Repeater:
<asp:Repeater ID="repeaterPager" runat="server" OnItemCommand="repeaterPager_ItemCommand">
<ItemTemplate>
<asp:LinkButton CssClass="sayfaNo" ID="btnPage" CommandName="Page" CommandArgument="<%#Container.DataItem %>" runat="server">
<%# Container.DataItem %></asp:LinkButton>
</ItemTemplate>
</asp:Repeater>
CodeBehind :
private void MakeleleriGetir()
{
SqlConnection cnn = new SqlConnection(ConfigurationManager.ConnectionStrings[0].ConnectionString);
SqlDataAdapter da = new SqlDataAdapter("SELECT p.PostID,p.Title,p.DateTime,p.PostShort,p.CategoryID,i.SmallFileName,c.CategoryName From Posts as p inner join Resimler as i ON p.PostID = i.PostID inner join Categories as c On p.CategoryID = c.CategoryID", cnn);
DataTable dt = new DataTable();
da.Fill(dt);
PagedDataSource pds = new PagedDataSource();
pds.DataSource = dt.DefaultView;
pds.AllowPaging = true;
pds.PageSize = 4;
pds.CurrentPageIndex = CurrentPage;
PageCount = pds.PageCount;
btnPrevious.Enabled = !pds.IsFirstPage;
btnNext.Enabled = !pds.IsLastPage;
if (pds.PageCount > 1)
{
repeaterPager.Visible = true;
ArrayList pages = new ArrayList();
for (int i = 0; i < pds.PageCount; i++)
{
{
pages.Add((i + 1).ToString());
}
}
repeaterPager.DataSource = pages;
repeaterPager.DataBind();
}
else
{
repeaterPager.Visible = false;
}
RepeaterPosts.DataSource = pds;
RepeaterPosts.DataBind();
}
protected int CurrentPage
{
get
{ // look for current page in ViewState
object o = this.ViewState["_CurrentPage"];
if (o == null)
{
return 0; // default to showing the first page
}
else
{
return (int)o;
}
}
set
{
this.ViewState["_CurrentPage"] = value;
}
}
public int PageCount
{
get
{
if (ViewState["_PageCount"] != null)
return Convert.ToInt32(ViewState["_PageCount"]);
else
return 0;
}
set
{
ViewState["_PageCount"] = value;
}
}
protected override void OnInit(EventArgs e)
{
base.OnInit(e);
repeaterPager.ItemCommand += new RepeaterCommandEventHandler(repeaterPager_ItemCommand);
}
protected void repeaterPager_ItemCommand(object source, RepeaterCommandEventArgs e)
{
CurrentPage = Convert.ToInt32(e.CommandArgument) - 1;
MakeleleriGetir();
}
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
MakeleleriGetir();
}
protected void btnNext_Click(object sender, EventArgs e)
{
CurrentPage += 1;
MakeleleriGetir();
}
protected void btnPrevious_Click(object sender, EventArgs e)
{
CurrentPage -= 1;
MakeleleriGetir();
}
}
}
Logic:
Use ItemDataBound event and compare currentpage with current value of btnPage. You may use FindControl to get the current btnPage value.
Hope that helps!
protected void repeaterPager_ItemDataBound(object sender, RepeaterItemEventArgs e)
{
//Enabled False for current selected Page index
LinkButton lnkPage = (LinkButton)e.Item.FindControl("btnPage");
if (lnkPage.CommandArgument.ToString() == (CurrentPage+1).ToString())
{
lnkPage.Enabled = false;
lnkPage.BackColor = System.Drawing.Color.FromName("#FFCC01");
}
}

monotouch dialog multiple radiogroups on a single view (single rootelement)

I would like to use multiple radio groups within a single rootelelement with monotouch dialog. Each radiogroup would have its own section. I can't find a way to make this work because a single radiogroup can only be assigned to the rootelement
svn!
Here is my solution
public class CustomRootElement : RootElement
{
private RadioGroup _defaultGroup = new RadioGroup(0);
private Dictionary<string, RadioGroup> _groups = new Dictionary<string, RadioGroup>();
public CustomRootElement(string caption = "") : base(caption , new RadioGroup("default",0))
{
}
public CustomRootElement(string caption, Group group, Func<RootElement, UIViewController> createOnSelected) : base(caption, group)
{
var radioGroup = group as RadioGroup;
if(radioGroup != null)
{
_groups.Add(radioGroup.Key.ToLower(), radioGroup);
}
this.createOnSelected = createOnSelected;
}
public override UITableViewCell GetCell(UITableView tv)
{
var cell = base.GetCell(tv);
cell.SelectionStyle = UITableViewCellSelectionStyle.None;
return cell;
}
public int Selected(string group)
{
if (string.IsNullOrEmpty(group))
{
throw new ArgumentNullException("group");
}
group = group.ToLower();
if (_groups.ContainsKey(group))
{
return _groups[group].Selected;
}
return 0;
}
public void Select(string group, int selected)
{
if (string.IsNullOrEmpty(group))
{
throw new ArgumentNullException("group");
}
var radioGroup = GetGroup(group);
radioGroup.Selected = selected;
}
internal RadioGroup GetGroup(string group)
{
if (string.IsNullOrEmpty(group))
{
throw new ArgumentNullException("group");
}
group = group.ToLower();
if (!_groups.ContainsKey(group))
{
_groups[group] = new RadioGroup(group , 0);
}
return _groups[group];
}
internal NSIndexPath PathForRadioElement(string group, int index)
{
foreach (var section in this)
{
foreach (var e in section.Elements)
{
var re = e as SlRadioElement;
if (re != null
&& string.Equals(re.Group, group,StringComparison.InvariantCultureIgnoreCase)
&& re.Index == index)
{
return e.IndexPath;
}
}
}
return null;
}
}
public class CustomRadioElement : RadioElement
{
public event Action<CustomRadioElement> ElementSelected;
private readonly static NSString ReuseId = new NSString("CustomRadioElement");
private string _subtitle;
public int? Index { get; protected set; }
public CustomRadioElement(string caption, string group = null, string subtitle = null) :base(caption, group)
{
_subtitle = subtitle;
}
protected override NSString CellKey
{
get
{
return ReuseId;
}
}
public override UITableViewCell GetCell(UITableView tv)
{
EnsureIndex();
var cell = tv.DequeueReusableCell(CellKey);
if (cell == null)
{
cell = new UITableViewCell(UITableViewCellStyle.Subtitle , CellKey);
}
cell.ApplyStyle(this);
cell.TextLabel.Text = Caption;
if (!string.IsNullOrEmpty(_subtitle))
{
cell.DetailTextLabel.Text = _subtitle;
}
var selected = false;
var slRoot = Parent.Parent as CustomRootElement;
if (slRoot != null)
{
selected = Index == slRoot.Selected(Group);
}
else
{
var root = (RootElement)Parent.Parent;
selected = Index == root.RadioSelected;
}
cell.Accessory = selected ? UITableViewCellAccessory.Checkmark : UITableViewCellAccessory.None;
return cell;
}
public override void Selected(DialogViewController dvc, UITableView tableView, NSIndexPath indexPath)
{
var slRoot = Parent.Parent as CustomRootElement;
if (slRoot != null)
{
var radioGroup = slRoot.GetGroup(Group);
if (radioGroup.Selected == Index)
{
return;
}
UITableViewCell cell;
var selectedIndex = slRoot.PathForRadioElement(Group, radioGroup.Selected);
if (selectedIndex != null)
{
cell = tableView.CellAt(selectedIndex);
if (cell != null)
{
cell.Accessory = UITableViewCellAccessory.None;
}
}
cell = tableView.CellAt(indexPath);
if (cell != null)
{
cell.Accessory = UITableViewCellAccessory.Checkmark;
}
radioGroup.Selected = Index.Value;
var handler = ElementSelected;
if (handler != null)
{
handler(this);
}
}
else
{
base.Selected(dvc, tableView, indexPath);
}
}
private void EnsureIndex()
{
if (!Index.HasValue)
{
var parent = Parent as Section;
Index = parent.Elements.IndexOf(this);
}
}
}
Hope this help!

Telerik RadGrid Export to Excel. Missing operand before '=' operator

I am getting the error
Missing operand before '=' operator.
when I try and export and the code is running fine in the grid.
Here is the code for the web part. The error only occurs on the rebind. It works fine in the grid itself. Is there any way to narrow down the exact thing it is erroring on?
I am willing to pay for a support / solution to this problem, I just need it to work.
[Guid("5fbe4ccf-4d90-476b-af77-347de4e1176c")]
public class ParentChildGrid : Microsoft.SharePoint.WebPartPages.WebPart
{
#region
Variables
private bool _error = false;
private string _PageSize = null;
private string _ParentList = null;
private string _ParentView = null;
private string _ParentIDField = null;
private string _FirstChildList = null;
private string _FirstChildView = null;
private string _FirstChildIDField = null;
private string _FirstChildParentIDField = null;
private string _SecondChildList = null;
private string _SecondChildView = null;
private string _SecondChildIDField = null;
private string _SecondChildParentIDField = null;
protected ScriptManager scriptManager;
protected RadAjaxManager ajaxManager;
protected Panel panel;
protected SPView oView;
protected RadGrid oGrid = new RadGrid();
protected Label label;
protected DataTable ParentDataTable;
protected DataTable Child1DataTable;
protected DataTable Child2DataTable;
protected Button cmdExport = new Button();
#endregion
#region
Properties
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("Items Per Page")]
[WebDescription("# of items to include in each page.")]
public string PageSize
{
get
{
if (_PageSize == null)
{
_PageSize = "100";
}
return _PageSize.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("ParentList")]
[WebDescription("Parent List in Grid View")]
public string ParentList
{
get
{
if (_ParentList == null)
{
_ParentList = "";
}
return _ParentList.Trim();
}
set { _ParentList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("ParentView")]
[WebDescription("View for Parent List")]
public string ParentView
{
get
{
if (_ParentView == null)
{
_ParentView = "";
}
return _ParentView.Trim();
}
set { _ParentView = value.Trim(); }
}
[
Personalizable(PersonalizationScope.Shared)]
[
WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[
WebDisplayName("ParentIDField")]
[
WebDescription("ID Field in Parent List")]
public string ParentIDField
{
get
{
if (_ParentIDField == null)
{
_ParentIDField = "";
}
return _ParentIDField.Trim();
}
set { _ParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("FirstChildList")]
[WebDescription("FirstChildList Name")]
public string FirstChildList
{
get
{
if (_FirstChildList == null)
{
_FirstChildList = "";
}
return _FirstChildList.Trim();
}
set { _FirstChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildView")]
[WebDescription("First Child View Name")]
public string FirstChildView
{
get
{
if (_FirstChildView == null)
{
_FirstChildView = "";
}
return _FirstChildView.Trim();
}
set { _FirstChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildIDField")]
[WebDescription("First Child ID Field (Tyically ID)")]
public string FirstChildIDField
{
get
{
if (_FirstChildIDField == null)
{
_FirstChildIDField = "";
}
return _FirstChildIDField.Trim();
}
set { _FirstChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("FirstChildParentIDField")]
[WebDescription("First Child Parent ID Field")]
public string FirstChildParentIDField
{
get
{
if (_FirstChildParentIDField == null)
{
_FirstChildParentIDField = "";
}
return _FirstChildParentIDField.Trim();
}
set { _FirstChildParentIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildList")]
[WebDescription("Second Child List")]
public string SecondChildList
{
get
{
if (_SecondChildList == null)
{
_SecondChildList = "";
}
return _SecondChildList.Trim();
}
set { _SecondChildList = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildView")]
[
WebDescription("Second Child View")]
public string SecondChildView
{
get
{
if (_SecondChildView == null)
{
_SecondChildView = "";
}
return _SecondChildView.Trim();
}
set { _SecondChildView = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.
Category("Parent Child Properties")]
[WebDisplayName("SecondChildIDField")]
[WebDescription("Second Child ID Field (Typically ID)")]
public string SecondChildIDField
{
get
{
if (_SecondChildIDField == null)
{
_SecondChildIDField = "";
}
return _SecondChildIDField.Trim();
}
set { _SecondChildIDField = value.Trim(); }
}
[Personalizable(PersonalizationScope.Shared)]
[WebBrowsable(true)]
[System.ComponentModel.Category("Parent Child Properties")]
[WebDisplayName("SecondChildParentIDField")]
[WebDescription("Second Child ID Field")]
public string SecondChildParentIDField
{
get
{
if (_SecondChildParentIDField == null)
{
_SecondChildParentIDField = "";
}
return _SecondChildParentIDField.Trim();
}
set { _SecondChildParentIDField = value.Trim(); }
}
#endregion
private const string ByeByeIncludeScriptKey = "myByeByeIncludeScript";
private const string EmbeddedScriptFormat = "<script language=javascript>function ByeBye(){ alert('Test Code'); }</script> ";
private const string DisableAjaxScriptKey = "myDisableAjaxIncludeScript";
private const string DisableAjaxForExport = "<script language=javascript>function onRequestStart(sender, args) { if (args.get_eventTarget().indexOf(\"cmdExport\") >= 0);args.set_enableAjax(false);alert('Ajax Disabled'); }</script>";
private void WebPart_ClientScript_PreRender(object sender , System.EventArgs e )
{
if (!Page.IsClientScriptBlockRegistered(ByeByeIncludeScriptKey))
Page.RegisterClientScriptBlock(ByeByeIncludeScriptKey,
EmbeddedScriptFormat);
if (!Page.IsClientScriptBlockRegistered(DisableAjaxScriptKey))
Page.RegisterClientScriptBlock(DisableAjaxScriptKey,
DisableAjaxForExport);
//ajaxManager.ClientEvents.OnRequestStart = "onRequestStart";
}
public ParentChildGrid()
{
this.ExportMode = WebPartExportMode.All;
this.PreRender += new EventHandler(WebPart_ClientScript_PreRender);
}
private void onRequestStart()
{
ajaxManager.EnableAJAX =
false;
}
protected override void OnInit(EventArgs e)
{
try
{
base.OnInit(e);
Page.ClientScript.RegisterStartupScript(
typeof(ParentChildGrid), this.ID, "_spOriginalFormAction = document.forms[0].action;_spSuppressFormOnSubmitWrapper=true;", true);
if (this.Page.Form != null)
{
string formOnSubmitAtt = this.Page.Form.Attributes["onsubmit"];
if (!string.IsNullOrEmpty(formOnSubmitAtt) && formOnSubmitAtt == "return _spFormOnSubmitWrapper();")
{
this.Page.Form.Attributes["onsubmit"] = "_spFormOnSubmitWrapper();";
}
}
scriptManager =
ScriptManager.GetCurrent(this.Page);
if (scriptManager == null)
{
scriptManager =
new RadScriptManager();
this.Page.Form.Controls.AddAt(0, scriptManager);
}
scriptManager.RegisterPostBackControl(cmdExport);
}
catch (Exception ex)
{
HandleException(ex);
}
}
protected override void OnLoad(EventArgs e)
{
ScriptManager.GetCurrent(Page).RegisterPostBackControl(cmdExport);
if (!_error)
{
try
{
base.OnLoad(e);
this.EnsureChildControls();
base.OnLoad(e);
if (_ParentList != null)
{
if (_ParentList != "")
{
panel =
new Panel();
panel.ID =
"Panel1";
this.Controls.Add(panel);
oGrid =
new RadGrid();
DefineComplexGrid();
oGrid.GridExporting +=
new OnGridExportingEventHandler(oGrid_GridExporting);
panel.Controls.Add(oGrid);
//DefineSimpleMasterDetail();
cmdExport.Click +=
new EventHandler(cmdExport_Click);
cmdExport.Text =
"Export";
Button cmdExpandAll = new Button();
cmdExpandAll.Text =
"Expand All";
cmdExpandAll.Click +=
new EventHandler(cmdExpandAll_Click);
panel.Controls.Add(cmdExpandAll);
ajaxManager =
RadAjaxManager.GetCurrent(this.Page);
if (ajaxManager == null)
{
ajaxManager =
new RadAjaxManager();
ajaxManager.ID =
"RadAjaxManager1";
Controls.Add(ajaxManager);
this.Page.Items.Add(typeof(RadAjaxManager), ajaxManager);
}
ajaxManager.AjaxSettings.AddAjaxSetting(oGrid, panel);
panel.Controls.Add(cmdExport);
ajaxManager.AjaxRequest +=
new RadAjaxControl.AjaxRequestDelegate(ajaxManager_AjaxRequest);
this.Controls.Add(new LiteralControl("<br><br><input class='ms-SPButton' value=\'Test Code\' type=button onclick=\"ByeBye();\" >"));
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
}
void oGrid_GridExporting(object source, GridExportingArgs e)
{
//throw new NotImplementedException();
}
void ajaxManager_AjaxRequest(object sender, AjaxRequestEventArgs e)
{
ajaxManager.EnableAJAX =
false;
}
void cmdExpandAll_Click(object sender, EventArgs e)
{
try
{
foreach (GridItem item in oGrid.MasterTableView.Items)
{
item.Expanded =
true;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void cmdExport_Click(object sender, EventArgs e)
{
try
{
ajaxManager.ClientEvents.OnRequestStart =
"onRequestStart";
oGrid.ExportSettings.ExportOnlyData =
true;
oGrid.ExportSettings.IgnorePaging =
true;
oGrid.ExportSettings.OpenInNewWindow =
true;
oGrid.MasterTableView.HierarchyDefaultExpanded =
true;
if (FirstChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[0].HierarchyDefaultExpanded =
true;
if (SecondChildList.Trim() != "")
oGrid.MasterTableView.DetailTables[1].HierarchyDefaultExpanded =
true;
oGrid.Rebind();
oGrid.MasterTableView.ExportToExcel();
}
catch (Exception ex)
{
HandleException(ex);
}
}
//private void DefineSimpleGrid()
//{
// try
// {
// oGrid.ID = "Master";
// oGrid.PageSize = 10;
// oGrid.AllowPaging = true;
// oGrid.AllowSorting = true;
// oGrid.Skin = "WebBlue";
// oGrid.GroupingEnabled = true;
// oGrid.NeedDataSource += new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
// oGrid.ShowStatusBar = true;
// oGrid.ShowGroupPanel = true;
// oGrid.GroupingEnabled = true;
// oGrid.ClientSettings.AllowDragToGroup = true;
// oGrid.ClientSettings.AllowColumnsReorder = true;
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private DataTable GetDataTable(String cListName, String ViewName)
{
try
{
SPList list = SPContext.Current.Web.Lists[cListName];
SPView view = list.Views[ViewName];
SPListItemCollection items = list.GetItems(view);
if (items != null)
{
if (items.Count > 0)
return items.GetDataTable();
}
}
catch (Exception ex)
{
HandleException(ex);
}
return null;
}
//private void DefineSimpleMasterDetail()
//{
// try
// {
// oGrid.MasterTableView.DataKeyNames = new string[] { "ID" };
// oGrid.Skin = "Default";
// oGrid.Width = Unit.Percentage(100);
// oGrid.PageSize = 5;
// oGrid.AllowPaging = true;
// oGrid.MasterTableView.PageSize = 15;
// oGrid.MasterTableView.DataSource = GetDataTable(_ParentList, _ParentView);
// GridTableView tableViewOrders = new GridTableView(oGrid);
// tableViewOrders.DataSource = GetDataTable(_FirstChildList, _FirstChildView);
// tableViewOrders.DataKeyNames = new string[] { _ParentIDField };
// GridRelationFields relationFields = new GridRelationFields();
// relationFields.MasterKeyField = _FirstChildIDField;
// relationFields.DetailKeyField = _FirstChildParentIDField;
// tableViewOrders.ParentTableRelation.Add(relationFields);
// oGrid.MasterTableView.DetailTables.Add(tableViewOrders);
// }
// catch (Exception ex)
// {
// HandleException(ex);
// }
//}
private void DefineComplexGrid()
{
try
{
oGrid.ID =
"RadGrid1";
//oGrid.Width = Unit.Percentage(98);
oGrid.PageSize =
Convert.ToInt32(PageSize);
oGrid.AllowPaging =
true;
oGrid.AllowSorting =
true;
oGrid.PagerStyle.Mode =
GridPagerMode.NextPrevAndNumeric;
oGrid.ShowStatusBar =
true;
oGrid.ClientSettings.Resizing.AllowColumnResize =
true;
oGrid.DetailTableDataBind +=
new GridDetailTableDataBindEventHandler(oGrid_DetailTableDataBind);
oGrid.NeedDataSource +=
new GridNeedDataSourceEventHandler(oGrid_NeedDataSource);
oGrid.ColumnCreated +=
new GridColumnCreatedEventHandler(oGrid_ColumnCreated);
oGrid.MasterTableView.Name = _ParentList;
if (_FirstChildList != "" || _SecondChildList != "")
{
oGrid.MasterTableView.PageSize =
Convert.ToInt32(PageSize);
oGrid.MasterTableView.DataKeyNames =
new string[] { _ParentIDField };
oGrid.MasterTableView.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
}
if (_FirstChildList != "")
{
GridTableView tableViewFirstChild = new GridTableView(oGrid);
tableViewFirstChild.Width =
Unit.Percentage(100);
tableViewFirstChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewFirstChild.DataKeyNames =
new string[] { _FirstChildIDField };
tableViewFirstChild.Name = _FirstChildList;
GridRelationFields FirstChildrelationFields = new GridRelationFields();
FirstChildrelationFields.MasterKeyField = _ParentIDField;
FirstChildrelationFields.DetailKeyField = _FirstChildParentIDField;
tableViewFirstChild.ParentTableRelation.Add(FirstChildrelationFields);
tableViewFirstChild.Caption = _FirstChildList;
oGrid.MasterTableView.DetailTables.Add(tableViewFirstChild);
}
if (_SecondChildList != "")
{
GridTableView tableViewSecondChild = new GridTableView(oGrid);
tableViewSecondChild.Width =
Unit.Percentage(100);
tableViewSecondChild.HierarchyLoadMode =
GridChildLoadMode.ServerOnDemand;
tableViewSecondChild.DataKeyNames =
new string[] { _SecondChildIDField };
tableViewSecondChild.Name = _SecondChildList;
GridRelationFields SecondChildrelationFields = new GridRelationFields();
SecondChildrelationFields.MasterKeyField = _ParentIDField;
SecondChildrelationFields.DetailKeyField = _SecondChildParentIDField;
tableViewSecondChild.Caption = _SecondChildList;
tableViewSecondChild.ParentTableRelation.Add(SecondChildrelationFields);
oGrid.MasterTableView.DetailTables.Add(tableViewSecondChild);
}
oGrid.ShowStatusBar =
true;
oGrid.ShowGroupPanel =
true;
oGrid.GroupingEnabled =
true;
oGrid.ClientSettings.AllowDragToGroup =
true;
oGrid.ClientSettings.AllowColumnsReorder =
true;
oGrid.Skin =
"Web20";
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
{
try
{
//if (e.Column.HeaderText == "ID" || e.Column.HeaderText == "Created")
//{
// e.Column.Display = false;
// return;
//}
String cOwnerTable = "";
cOwnerTable = e.OwnerTableView.Name;
if (cOwnerTable.Trim() != "" && e.Column.HeaderText != "" && e.Column.HeaderText != _FirstChildParentIDField && e.Column.HeaderText != _SecondChildParentIDField)
{
SPList CurrentList = SPContext.Current.Web.Lists[e.OwnerTableView.Name];
e.Column.HeaderText = GetFieldDisplayName(e.Column.HeaderText, CurrentList);
SPField oField = CurrentList.Fields[e.Column.HeaderText];
GridBoundColumn col = (GridBoundColumn)e.Column;
switch (oField.Type)
{
case SPFieldType.Currency:
col.DataFormatString =
"{0:C}";
break;
case SPFieldType.DateTime:
SPFieldDateTime oDateTime = (SPFieldDateTime)oField;
if (oDateTime.DisplayFormat == SPDateTimeFieldFormatType.DateOnly)
col.DataFormatString =
"{0:d}";
break;
default:
break;
}
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private DataTable GetChildDataTable(GridDetailTableDataBindEventArgs e, String cChildListName, String cChildView,String cParentIDField)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
SPList FirstChildList = SPContext.Current.Web.Lists[cChildListName];
SPView oView = FirstChildList.Views[cChildView];
String cContractID = parentItem[_ParentIDField].Text;
SPQuery oChildQuery = new SPQuery();
if (Occurs(cParentIDField, oView.Query) == 2)
{
String cNewQuery = oView.Query;
Int32 iPos = cNewQuery.IndexOf(cParentIDField) + cParentIDField.Length;
String cPartOne = cNewQuery.Substring(0,cNewQuery.IndexOf(cParentIDField, iPos));
String cPartTwo = cNewQuery.Substring(cNewQuery.IndexOf(cParentIDField, iPos) + cParentIDField.Length);
cNewQuery = cPartOne + cContractID + cPartTwo;
oChildQuery.Query = cNewQuery;
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
else
{
oChildQuery.Query =
"<Where><Eq><FieldRef Name='" + cParentIDField + "' /><Value Type='Text'>" + cContractID + "</Value></Eq></Where>";
}
SPViewFieldCollection oViewFields = oView.ViewFields;
oViewFields.Add(cParentIDField);
String cViewFields = oViewFields.SchemaXml;
oChildQuery.ViewFields = cViewFields;
SPListItemCollection items = FirstChildList.GetItems(oChildQuery);
if (items != null)
{
if (items.Count > 0)
{
return items.GetDataTable();
}
}
}
catch (Exception ex)
{
//HandleException(ex);
}
return null;
}
void oGrid_DetailTableDataBind(object source, GridDetailTableDataBindEventArgs e)
{
try
{
GridDataItem parentItem = e.DetailTableView.ParentItem as GridDataItem;
if (parentItem.Edit)
{
return;
}
if (e.DetailTableView.Name == _FirstChildList)
{
Child1DataTable = GetChildDataTable(e, _FirstChildList, _FirstChildView, _FirstChildParentIDField);
e.DetailTableView.DataSource = Child1DataTable;
}
if (e.DetailTableView.Name == _SecondChildList)
{
Child2DataTable = GetChildDataTable(e, _SecondChildList, _SecondChildView, _SecondChildParentIDField);
e.DetailTableView.DataSource = Child2DataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
void oGrid_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
{
try
{
if (!e.IsFromDetailTable)
{
SPList ParentList = SPContext.Current.Web.Lists[_ParentList];
oView = ParentList.Views[_ParentView];
SPQuery ParentQuery = new SPQuery();
ParentQuery.Query = oView.Query;
ParentQuery.RowLimit = 100000;
ParentQuery.ViewFields = oView.ViewFields.SchemaXml;
SPListItemCollection oItems = SPContext.Current.Web.Lists[_ParentList].GetItems(ParentQuery);
ParentDataTable = oItems.GetDataTable();
oGrid.DataSource = ParentDataTable;
}
}
catch (Exception ex)
{
HandleException(ex);
}
}
private string GetFieldDisplayName(String cInternalName, SPList oList)
{
try
{
foreach (SPField field in oList.Fields)
{
if (field.InternalName == cInternalName)
return field.Title;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return cInternalName;
}
private Int32 Occurs(String SearchFor, String SearchIn)
{
Int32 Count = 0;
Int32 iPos = 0;
try
{
while (SearchIn.IndexOf(SearchFor, iPos) != -1)
{
Count++;
iPos = SearchIn.IndexOf(SearchFor, iPos) + 1;
}
}
catch (Exception ex)
{
HandleException(ex);
}
return Count;
}
private void HandleException(Exception ex)
{
this._error = true;
try
{
this.Controls.Clear();
this.Controls.Add(new LiteralControl(ex.Message));
}
catch
{
}
}
} //End Class
As a follow-up, it appears the problem was that there were NULL values in John's original data. These nulls were causing problems during the data export. Fixing the null values also fixed the Excel export. Original solution on Telerik.com forums:
http://www.telerik.com/community/forums/aspnet-ajax/grid/extremely-frustrated-please-help-with-radgrid-export-of-multi-tabe-view.aspx

Resources