using System; using System.Collections; using System.ComponentModel; using System.Data; using System.Drawing; using System.Web; using System.Web.SessionState; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.HtmlControls; namespace GoogleControl { /// /// Example of HTTP control. /// Calls the Google Web API. ///

Copyright (c) 2002 Alexis Grandemange
/// Mail: alexis.grandemange@pagebox.net

///
This program is free software; you can redistribute it and/or
	/// modify it under the terms of the GNU Lesser General Public
	/// License as published by the Free Software Foundation; version
	/// 2.1 of the License.
	/// This library is distributed in the hope that it will be useful,
	/// but WITHOUT ANY WARRANTY; without even the implied warranty of
	/// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
	/// GNU Lesser General Public License for more details.
	/// A copy of the GNU Lesser General Public License lesser.txt should be
	/// included in the distribution.
///
public class WebForm1 : System.Web.UI.Page { protected System.Web.UI.WebControls.Label title; protected System.Web.UI.WebControls.TextBox term; protected System.Web.UI.WebControls.Button search; protected System.Web.UI.WebControls.Label copyright; protected System.Web.UI.WebControls.DataGrid result; protected System.Web.UI.WebControls.DataGrid detail; protected System.Web.UI.WebControls.Button clear; /// /// Dynamically created status label (used in OnSearch). /// Label labStatus = null; /// /// Array bound with the result Datagrid. /// Contains ResultItem objects. /// ArrayList results; /// /// Set by bind() and used by OnSearch(). /// Used to display Web service invocation errors. /// string bindError = null; public WebForm1() { Page.Init += new System.EventHandler(Page_Init); } /// /// Call initialize, set the title and copyright CSS classes /// and resize the table to its min value. /// private void Page_Load(object sender, System.EventArgs e) { if (!IsPostBack) { string path = Request.ServerVariables["PATH_TRANSLATED"]; string referer = getReferer(); Global.initialize(referer, path, true); RefererItem ri = null; ri = (RefererItem)Global.pages[referer]; if (ri.titleCss != null) title.CssClass = ri.titleCss; if (ri.copyrightCss != null) copyright.CssClass = ri.copyrightCss; resize(getForm(), referer, false); } } /// /// If the control was included retrieve the including page from the Session object. /// If not found in the session object (first time) use the query string if it is set /// and store in the session. /// If the control is invoked standalone (neither session or query string set) use this URL. /// /// The URL of the directory that uses the control private string getReferer() { string referer = (string)Session["referer"]; if (referer != null) return referer; referer = Request.QueryString["from"]; if (referer == null) { referer = Request.ServerVariables["HTTP_HOST"] + Request.ServerVariables["URL"]; int pos = referer.LastIndexOf('/'); if (pos == -1) return null; referer = referer.Substring(0, pos + 1); } else { int pos = referer.LastIndexOf('/'); if (pos == -1) return null; referer = referer.Substring(0, pos + 1); Session.Add("referer", referer); } return referer; } /// /// Finds the GoogleForm form in the page. /// /// The GoogleForm form private HtmlForm getForm() { IEnumerator cie = Controls.GetEnumerator(); while(cie.MoveNext()) { Object o = cie.Current; if (!(o is HtmlForm)) continue; HtmlForm hf = (HtmlForm)o; if (hf.ID.Equals("Form1")) return hf; } return null; } /// /// 1. Retrieves the consumer GoogleControl.xml info /// 2. Find the table in the form /// 3. Sets its size and CSS class /// /// GoogleForm form /// URL of the consumer directory (key in Global.pages) /// If true sets the table width to its max value. /// If false sets the table width to its min value private void resize(HtmlForm hf, string referer, bool toMax) { RefererItem ri = (RefererItem)Global.pages[referer]; if ((ri.tableMinWidth == null) || (ri.tableMaxWidth == null) || (ri.tableCss == null)) return; IEnumerator ie = hf.Controls.GetEnumerator(); while(ie.MoveNext()) { Object o = ie.Current; if (o is LiteralControl) { LiteralControl lc = (LiteralControl)o; string s = lc.Text; if (s.IndexOf("", 0) >= 0) { if (toMax) lc.Text = s.Replace("
", "
"); else lc.Text = s.Replace("
", "
"); } } } } private void Page_Init(object sender, EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); } #region Web Form Designer generated code /// /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// private void InitializeComponent() { this.search.Click += new System.EventHandler(this.OnSearch); this.clear.Click += new System.EventHandler(this.OnClear); this.result.ItemCommand += new System.Web.UI.WebControls.DataGridCommandEventHandler(this.dgResult_Select); this.Load += new System.EventHandler(this.Page_Load); } #endregion /// /// Called when the user clicks on the Search button. /// Calls bind. /// In case of success, binds the result Datagrid and set its header, /// item and alternate item CSS classes. /// private void OnSearch(object sender, System.EventArgs e) { HtmlForm hf = getForm(); if (hf == null) return; hf.Target = "_self"; ControlCollection controls = hf.Controls; if (controls == null) return; labStatus = new Label(); string referer = getReferer(); RefererItem ri = (RefererItem)Global.pages[referer]; labStatus.ID = "labStatus"; if (ri.statusCss != null) labStatus.CssClass = ri.statusCss; controls.Add(labStatus); if (term.Text.Length == 0) labStatus.Text = "You must set the search string"; else { unbindDetail(); int resultNb = bind(); if (resultNb == -1) labStatus.Text = bindError; else { resize(hf, referer, true); result.DataSource = results; result.DataBind(); labStatus.Text = "Found " + resultNb + " entries"; if (ri.dgHeaderCss != null) result.HeaderStyle.CssClass = ri.dgHeaderCss; if (ri.dgCss != null) result.ItemStyle.CssClass = ri.dgCss; if (ri.dgAltCss != null) result.AlternatingItemStyle.CssClass = ri.dgAltCss; } } } /// /// Called when the user clicks on a Sel button in the result Datagrid. /// Binds the detail Datagrid and set its header, /// item and alternate item CSS classes. /// private void dgResult_Select(object source, System.Web.UI.WebControls.DataGridCommandEventArgs e) { int sel = e.Item.ItemIndex; if (sel != -1) { string Key = (string)result.DataKeys[sel]; string[] fields = Key.Split(new char[]{ '|' }); ArrayList al = new ArrayList(); DetailItem di = new DetailItem("Summary", fields[0]); al.Add(di); di = new DetailItem("URL", fields[1]); al.Add(di); di = new DetailItem("Snippet", fields[2]); al.Add(di); di = new DetailItem("Title", fields[3]); al.Add(di); di = new DetailItem("Dir title", fields[5]); al.Add(di); di = new DetailItem("Cache size", fields[4]); al.Add(di); detail.DataSource = al; detail.DataBind(); string referer = getReferer(); RefererItem ri = (RefererItem)Global.pages[referer]; if (ri.dgHeaderCss != null) { result.HeaderStyle.CssClass = ri.dgHeaderCss; detail.HeaderStyle.CssClass = ri.dgHeaderCss; } if (ri.dgCss != null) { result.ItemStyle.CssClass = ri.dgCss; detail.ItemStyle.CssClass = ri.dgCss; } if (ri.dgAltCss != null) { result.AlternatingItemStyle.CssClass = ri.dgAltCss; detail.AlternatingItemStyle.CssClass = ri.dgAltCss; } resize(getForm(), referer, true); } } /// /// Calls the Google Web service and populates the result array list. /// Supports a special license, offline. /// If you don't the license in GoogleControl.xml or if you don't define /// GoogleControl.xml, the Web service is not called and results is populated /// with dummy entries. Useful for offline tests. /// /// Number of entries found private int bind() { string referer = getReferer(); RefererItem ri = (RefererItem)Global.pages[referer]; if (ri.license.Equals("offline")) { results = new ArrayList(10); for (int i = 0; i < 10; ++ i) { string idx = Convert.ToString(i); ResultItem resi = new ResultItem("summary" + idx, "http://localhost/home2/home.html", "snippet" + idx, "title" + idx, idx, "Directory Title" + idx); results.Add(resi); } return 10; } GoogleSearchService gss = new GoogleSearchService(); try { // gss.Discover(); GoogleSearchResult gsr = gss.doGoogleSearch(ri.license, term.Text, 0, 10, true, "", true, "", "", ""); int resultNb = gsr.resultElements.Length; results = new ArrayList(resultNb); IEnumerator ie = gsr.resultElements.GetEnumerator(); while(ie.MoveNext()) { ResultElement re = (ResultElement)ie.Current; ResultItem resi = new ResultItem(re.summary, re.URL, re.snippet, re.title, re.cachedSize, re.directoryTitle); results.Add(resi); } return resultNb; } catch(Exception e) { bindError = e.Message; } return -1; } /// /// Called when the user clicks on the Clear button. /// Shrinks the control (clear the Datagrids). /// private void OnClear(object sender, System.EventArgs e) { unbindDetail(); result.DataSource = null; result.DataBind(); string referer = getReferer(); resize(getForm(), referer, false); } /// /// Clear the detail Datagrid. /// private void unbindDetail() { detail.DataSource = null; detail.DataBind(); } } /// /// Describes a row of the result Datagrid. /// public sealed class ResultItem { /// /// Summary info returned by the Google Web service. /// public string summary; /// /// URL returned by the Google Web service. /// public string url; /// /// Snippet returned by the Google Web service. /// public string snippet; /// /// Title returned by the Google Web service. /// public string title; /// /// Cached size returned by the Google Web service. /// public string cachedSize; /// /// Title of the page in a directory returned by the Google Web service. /// public string directoryTitle; /// /// Constructor. Set the member fields. /// /// Summary info returned by the Google Web service /// URL returned by the Google Web service /// Snippet returned by the Google Web service /// Title returned by the Google Web service /// Cached size returned by the Google Web service /// Title of the page in a directory /// returned by the Google Web service public ResultItem(string summary, string URL, string snippet, string title, string cachedSize, string directoryTitle) { this.summary = summary; this.url = URL; this.snippet = snippet; this.title = title; this.cachedSize = cachedSize; this.directoryTitle = directoryTitle; } /// /// URL property. Displayed with a hyperlink. /// public string URL { get { return url; } } /// /// Title property. Displayed on a column. /// public string Title { get { return title; } } /// /// Key property. Contains all fields. Used to display details. /// public string Key { get { return summary + '|' + url + '|' + snippet + '|' + title + '|' + cachedSize + "|" + directoryTitle; } } } /// /// Describes a row in the detail Datagrid. /// public sealed class DetailItem { /// /// Name of a field - for instance Summary. /// private string name; /// /// Value of a field. /// private string val; /// /// Constructor. Set the member variables. /// /// Name of a field /// Value of a field public DetailItem(string name, string val) { this.name = name; this.val = val; } /// /// Returns the name of a field. /// public string Name { get { return name; } } /// /// Returns the value of a field, /// public string Value { get { return val; } } } }