This is a migrated thread and some comments may be shown as answers.

RadGrid Row Select not working

5 Answers 391 Views
Grid
This is a migrated thread and some comments may be shown as answers.
John
Top achievements
Rank 1
John asked on 03 Aug 2010, 03:29 PM
Hi all:

I have a web project I just porrted to VS 2010 and the "Q12010 NET40" RadControls. Now for some reason row selection in the grids, which was working fine in the project, has stopped working. I have pasted the code for the grid below, and I did not make any changes to the grid code in teh new project...

Can anyone offer any suggestions?

<telerik:RadGrid runat="server" AllowPaging="True" PageSize="15" ID="grdFilteredHotels" OnNeedDataSource="grdFilteredHotels_NeedDataSource"
Width="1020px" Height="365px" OnRowDrop="grdFilteredHotels_RowDrop" AllowMultiRowSelection="true" AllowSorting="True" BackColor="White"
Style="z-index: 103; left: 0px; position: absolute; top: 27px">
<PagerStyle Mode="NumericPages"></PagerStyle>
<MasterTableView DataKeyNames="Hotel" Width="100%" CellSpacing="-1">
</MasterTableView>
              <ClientSettings AllowRowsDragDrop="True">
                <Selecting AllowRowSelect="True" />
                <ClientEvents OnRowDropping="onRowDropping" />
                <Scrolling AllowScroll="True" UseStaticHeaders="True" />
              </ClientSettings>
              </telerik:RadGrid>

5 Answers, 1 is accepted

Sort by
0
Tsvetoslav
Telerik team
answered on 05 Aug 2010, 08:44 AM
Hello John,

Can you give more details on what is not working in the new version? Is it related to the header SelectAll check box?

Best wishes,
Tsvetoslav
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
John
Top achievements
Rank 1
answered on 05 Aug 2010, 02:16 PM
Hi:

Thanks for your note. What is not working is that I cannot select rows at all on the grids. So starting at "search6.png", this is the version from VS2005 and the older Telerik tools. I can select rows from either grid with mouse clicks, and by holding "shift" or "ctrl" I can select ranges of rows. I can then drag rows to the top grid to move them, this is shown in the next screens.

Search7.png shows what the customer wants. They want to be able to drag rows from the bottom grid, and drop them onto any place in the top grid and have the rows move, but this does not work and is the reason why I tried to port the project to the latest tools, to see if this would enable dropping anywhere. Right now if I drop the dragged rows into the whitespace and drop (as shown in "search7.png"), nothing happens.

The way it works now (in the old version, the new does not work at all) is shown by "search8.png"; dragged rows actually have to touch existing data rows before they will move. "search9.png" shows the end result.

Search3.png shows a screen of what is happenning in the VS2010 version. I cannot select any rows at all with mouse-clicks, and when I tried to hold the shift key and select a range, I got the result shown in Search3.png. The code in teh VS 2010 version is exactly the same as the Vs2005 version on the client side and matches the drag and drop example on the Telerik site.

John.
0
Tsvetoslav
Telerik team
answered on 10 Aug 2010, 03:55 PM
Hello John,

Is it possible that you paste your complete mark-up and code-behind (please, use the code-formatter tool of the ticket editor to make the code snippets readable).

Regards,
Tsvetoslav
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
0
John
Top achievements
Rank 1
answered on 10 Aug 2010, 04:36 PM
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="afgrids.aspx.cs" Inherits="afgrids" %>
<%@ Register assembly="Telerik.Web.UI" namespace="Telerik.Web.UI" tagprefix="telerik" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<head id="Head1" runat="server">
    <title>API Hotels Search</title>
    <script language="javascript" type="text/javascript">
        PageMethods.AbandonSession();   
    </script>
</head>
<body onunload="HandleClose()">
    <form id="form1" runat="server">
    <div>
        <asp:ScriptManager runat="server" ID="ScriptManager1" EnablePageMethods="true"></asp:ScriptManager>
   <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server" />
    <telerik:RadAjaxManager runat="server" ID="radAjax" DefaultLoadingPanelID="RadAjaxLoadingPanel1">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="grdNonFilteredHotels">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="grdNonFilteredHotels" />
                    <telerik:AjaxUpdatedControl ControlID="grdFilteredHotels" />
                    <telerik:AjaxUpdatedControl ControlID="msg" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="grdFilteredHotels">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="grdFilteredHotels" />
                    <telerik:AjaxUpdatedControl ControlID="msg" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManager>
  
        <telerik:RadScriptBlock runat="server" ID="scriptBlock">
            <script type="text/javascript">
                <!--
                function onRowDropping(sender, args) {
                    //                        if (sender.get_id() == "<%=grdNonFilteredHotels.ClientID %>")
                    //                        {
                    //                            var node = args.get_destinationHtmlElement(); 
                    //                            if(!isChildOf('<%=grdFilteredHotels.ClientID %>', node) && !isChildOf('<%=grdNonFilteredHotels.ClientID %>', node) )
                    //                            { 
                    //                                args.set_cancel(true); 
                    //                            }
                    //                        }
                    //                        else
                    //                        { 
                    //                            var node = args.get_destinationHtmlElement(); 
                    //                            if(!isChildOf('trashCan', node))
                    //                            { 
                    //                                args.set_cancel(true); 
                    //                            }
                    //                            else
                    //                            {
                    //                                if (confirm("Are you sure you want to delete this order?"))
                    //                                    args.set_destinationHtmlElement($get('trashCan'));
                    //                                else
                    //                                   args.set_cancel(true); 
                    //                            }
                    //                        }
                }
  
                function isChildOf(parentId, element) {
                    while (element) {
                        if (element.id && element.id.indexOf(parentId) > -1) {
                            return true;
                        }
                        element = element.parentNode;
                    }
                    return false;
                }
                    -->
            </script>
  
        </telerik:RadScriptBlock>
        <div class="exWrap">        
          <asp:Panel ID="pnlFiltered" runat="server" Height="365px" Width="1020px"
          Style="z-index: 1102; left: 0px; position: absolute; top: 0px" BackColor="White">
            <asp:ImageButton ID="cmdSendRFPs" runat="server" ImageUrl="~/images/email_icon.PNG"
            OnClick="cmdSendRFPs_Click" Style="z-index: 100; left: 834px; position: absolute;top: 4px" />
            <asp:Label ID="Label1" runat="server" Font-Size="Medium" Style="z-index: 101; left: 531px;
              position: absolute; top: 7px" Text="Click here to send the RFP to the selected Hotels"></asp:Label>
            <asp:Label ID="lblFilteredHotels" runat="server" Style="z-index: 102; left: -1px;
              position: absolute; top: 0px" Text="Filtered Hotels" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Large" ForeColor="Green"></asp:Label>
            <telerik:RadGrid runat="server" AllowPaging="True" PageSize="15" ID="grdFilteredHotels" OnNeedDataSource="grdFilteredHotels_NeedDataSource"
              Width="1020px" Height="365px" OnRowDrop="grdFilteredHotels_RowDrop" AllowMultiRowSelection="true" AllowSorting="True" BackColor="White"
              Style="z-index: 103; left: 0px; position: absolute; top: 27px">
                <PagerStyle Mode="NumericPages"></PagerStyle><MasterTableView DataKeyNames="Hotel" Width="100%" CellSpacing="-1">
                </MasterTableView>
              <ClientSettings AllowRowsDragDrop="True">
                <Selecting AllowRowSelect="True" />
                <ClientEvents OnRowDropping="onRowDropping" />
                <Scrolling AllowScroll="True" UseStaticHeaders="True" />
              </ClientSettings>
              </telerik:RadGrid>
          </asp:Panel>
  
          <asp:Panel ID="pnlNonFiltered" runat="server" Height="360px" Width="1020px"
          Style="z-index: 1103; left: 2px; position: absolute; top: 393px" BackColor="White">
            <asp:Label ID="lblNonFilteredHotels" runat="server" Style="z-index: 100; left: 0px;
              position: absolute; top: 0px" Text="Non-Filtered Hotels" Font-Bold="True" Font-Names="Verdana" Font-Size="X-Large" ForeColor="#C00000"></asp:Label>
            <telerik:RadGrid runat="server" AllowPaging="True" PageSize="15" ID="grdNonFilteredHotels"   
              OnNeedDataSource="grdNonFilteredHotels_NeedDataSource"
              Width="1020px" Height="355px" 
              OnRowDrop="grdNonFilteredHotels_RowDrop" AllowMultiRowSelection="true"
              AllowSorting="True" Style="z-index: 101; left: 0px; position: absolute; top: 27px">
                <MasterTableView DataKeyNames="Hotel" Width="100%" CellSpacing="-1">
                </MasterTableView>
                <ClientSettings AllowRowsDragDrop="True">
                  <Selecting AllowRowSelect="True" />
                  <ClientEvents OnRowDropping="onRowDropping" />
                  <Scrolling AllowScroll="true" UseStaticHeaders="true" SaveScrollPosition="true" ></Scrolling>
                </ClientSettings>
              <PagerStyle Mode="NumericPages"></PagerStyle>
            </telerik:RadGrid>
            <asp:TextBox ID="txtDebug" runat="server" Height="98px" Style="z-index: 103; left: 0px;
              position: absolute; top: 181px" TextMode="MultiLine" Width="900px" Visible="False"></asp:TextBox>
          </asp:Panel>
          <div style="z-index: 102; left: 935px; width: 363px; position: absolute; top: 59px;
            height: 342px">
            <asp:Label ID="lblBidCode" runat="server" Style="z-index: 101; left: 0px; position: absolute;
              top: 36px" Text="Label" Width="124px"></asp:Label>
            <asp:Label ID="lblCloseDate" runat="server" Style="z-index: 102; left: 3px; position: absolute;
              top: 64px" Text="Label" Width="115px"></asp:Label>
            <asp:Label ID="lblDaysRemaining" runat="server" Style="z-index: 103; left: 6px; position: absolute;
              top: 91px" Text="Label"></asp:Label>
            <asp:Label ID="lblAirportGuid" runat="server" Style="z-index: 104; left: 8px; position: absolute;
              top: 117px" Text="Label"></asp:Label>
            <asp:Label ID="lblAirportName" runat="server" Style="z-index: 105; left: 9px; position: absolute;
              top: 144px" Text="Label"></asp:Label>
            <asp:Label ID="lblAirlineCode" runat="server" Style="z-index: 106; left: 11px; position: absolute;
              top: 169px" Text="Label"></asp:Label>
            <asp:Label ID="lblRfpGuid" runat="server" Style="z-index: 107; left: 0px; position: absolute;
              top: 0px" Text="Label"></asp:Label>
               
            <asp:Label ID="lblOwnerId" runat="server" Style="z-index: 109; left: 12px; position: absolute;
              top: 201px" Text="Label"></asp:Label></div>
        </div>
    </div>
    <div class="exMessage" runat="server" id="msg" visible="false" enableviewstate="false">
      Hotel(s) successfully deleted!
    </div>    
    </form>
</body>
</html>



using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Common;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Text;
using System.Data.SqlClient;
using System.Data.Sql;
using System.IO;
using System.Web.Services.Protocols;
using System.Web.Services;
using System.Web.Configuration;
using System.Net;
using System.Net.Mail;
using System.Web.Mail;
using Telerik.Web.UI;
using ApiCrmSdk;
  
    //string strDataFile = @"App_Data\" + theRfp.new_airport + "_nonfilteredhotels.xml";
    //DataSet ds = new DataSet();
    //ds.ReadXmlSchema(HttpContext.Current.Server.MapPath(strDataFile));
    //ds.ReadXml(HttpContext.Current.Server.MapPath(@"App_Data\nonfilteredhotels.xml"));
    //grdNonFilteredHotels.DataSource = ds;
  
  
public partial class afgrids : System.Web.UI.Page
{
  public static Random RandomClass = new Random();
  
  //ref alistHotelNamesCityMatches, ref alistHotelIdsCityMatches
  
  #region variables
  //public static string strConStr = "data source=crm-srv-01;initial catalog=Accommodations_Plus_International_MSCRM;persist security info=False;user id=Administrator;Password=pass@word1;packet size=4096";
  
  IList<objHotel> nonFilteredResults = new List<objHotel>();
  IList<objHotel> FilteredResults = new List<objHotel>();
  
  ArrayList alistHotelIdsCityMatches = new ArrayList();
  ArrayList alistHotelNamesCityMatches = new ArrayList();
  
  ArrayList alistRfpHotels = new ArrayList();
  ArrayList alistRfpHotelNames = new ArrayList();
  
  ArrayList alistLongList = new ArrayList();
  
  //SqlDataAdapter cityAdapter = new SqlDataAdapter();
  //DataTable cityTable = new DataTable();
  
  public CheckBox[] dynamicCheckboxes;
  string strState = "";
  string strCountry = "";
  
  //ArrayList alistAllCities = new ArrayList();          
  //ArrayList alistAllCitiesIds = new ArrayList();
  
  //ArrayList alistAirportCodes = new ArrayList();
  //ArrayList alistAirportCodesIds = new ArrayList();    
  
  ////Vars for City names and IDs in the FetchXML string, used to build the query
  //ArrayList alistCities = new ArrayList();          //City Names
  //ArrayList alistCityMatchIds = new ArrayList();    //City IDs
  
  ////var for Hotel IDs that match the city query
  //static ArrayList alistHotelIdsCityMatches = new ArrayList();
  //static ArrayList alistHotelNamesCityMatches = new ArrayList();
  
  ////var for Hotel IDs that match the full query
  //ArrayList alistHotelIDsFullMatches = new ArrayList();
  //ArrayList alistHotelNamesFullMatches = new ArrayList();
  //ArrayList alistHotelEmailsFullMatches = new ArrayList();
  
  
  //This is the base starting query the rest of which is built in the code
  //string strCityQuery = "Select * from New_HotelBase INNER JOIN New_HotelExtensionBase " +
  //                      "ON New_HotelBase.New_HotelId = New_HotelExtensionBase.New_HotelId " +
  //                      "where ((New_HotelExtensionBase.new_nearmajorcityid = '";
  string strCityQuery = "SELECT new_hotname, new_hotstreet1, new_nearmajorcityid, new_numofrooms, new_markettier, new_airportcode, new_airportdistance, new_localtel, new_email2, new_hotelid FROM New_HotelExtensionBase where ((New_HotelExtensionBase.new_nearmajorcityid = '";
  
  bool bCountry = false;
  
  //public string strConStr = "data source=MOSS;initial catalog=Accommodations_Plus_International_MSCRM;persist security info=False;user id=sa;Password=pass@word1;packet size=4096";
  //public string strConStr = "Provider=SQLOLEDB;Data Source=MOSS;Initial Catalog=Accommodations_Plus_International_MSCRM;Integrated Security=SSPI;"; 
  //public string strConStr = "Server=MOSS;Database=Accommodations_Plus_International_MSCRM;Trusted_Connection=True;"; 
  //public string strConStr = ConfigurationSettings.AppSettings("SqlConnString");
  public string strConStr = ConfigurationManager.ConnectionStrings["MOSS_SqlConnString"].ConnectionString;
  
  public string strAirlineCode;
  
  public string strRfpGuid = "";
  public string strRfpName = "";
  public string strFetchXML = "";
  public string strAirportSavedQuery = "";
  public string strAirportFetchXml = "";
  public string strRfpSavedQuery = "";
  public string strRfpFetchXml = "";
  public string strEmail = "";
  
    
  
  Guid rfpGuid;
  new_rfpprogram theRFP;
  
  //StreamWriter sw1;
  
  
  string strUniqueName = "";
  string strOrgName = "";
  string strServerName = "";
  
  string[] strMarketTiers = new string[] { "Luxury", "Upscale", "Moderate", "Economy", "Budget", "N/A" };
  
  
  
  #endregion
  
  [WebMethod]
  public static void AbandonSession()
  {
    HttpContext.Current.Session.Abandon();
  }
  
  //===============================================================================================
  //===============================================================================================
  public bool IsNumeric(string s)
  {
    try
    {
      Int32.Parse(s);
    }
    catch
    {
      return false;
    }
    return true;
  }
  
  //===============================================================================================
  //===============================================================================================
  public string removeNonNumerics(string sInput)
  {
    string sResult = "";
    int iPos, iTemp;
    iPos = 0;
    iTemp = sInput.Length;
    while (iPos < iTemp)
    {
      if (IsNumeric(sInput.Substring(iPos, 1)))
        sResult += sInput.Substring(iPos, 1);
      iPos += 1;
    }
    return sResult;
  }
  
  //===============================================================================================
  //===============================================================================================
  protected void grdNonFilteredHotels_ColumnCreated(object sender, GridColumnCreatedEventArgs e)
  {
    e.Column.SortAscImageUrl = "SortAsc.gif";
    e.Column.SortDescImageUrl = "SortDesc.gif";
  }
  
  //===============================================================================================
  //===============================================================================================
  protected void grdNonFilteredHotels_SortCommand(object source, Telerik.Web.UI.GridSortCommandEventArgs e)
  {
    //txtDebug.Text += "\n\ngrdNonFilteredHotels_SortCommand";
    ArrayList lstHotels = new ArrayList();
    if (Session["NonFilteredSortDir"] == "ASC")
    {
      Session["NonFilteredSortDir"] = "DESC";
      grdNonFilteredHotels.DataSource = NonFilteredHotels;
      grdNonFilteredHotels.DataBind();
    }
    else
    {
      Session["NonFilteredSortDir"] = "ASC";
      grdNonFilteredHotels.DataSource = NonFilteredHotels;
      grdNonFilteredHotels.DataBind();
    }
    //for (int i = 0; i < gridLongList.Items.Count; i++)
    //{
    //  for (int j = 0; j < gridLongList.Items[i].Cells.Count; j++)
    //    txtDebug2.Text += "Col " + j.ToString() + ": " + gridLongList.Items[i].Cells[j].ToString() + "\n";
    //  txtDebug2.Text += "\n\n";
    //  //LongListItem llI = new LongListItem(gridLongList.Items[i].Cells[
    //}
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected void Page_Load(object sender, EventArgs e)
  {
    if (!IsPostBack)
    {
      Guid guidRfpGuid = new Guid(Request["id"]);
  
      NonFilteredHotels = null;
      FilteredHotels = null;
  
      try
      {
        #region webservices
        //Get the CRM varaibles from the web.config file
        strUniqueName = WebConfigurationManager.AppSettings["UniqueName"].ToString();
        strOrgName = WebConfigurationManager.AppSettings["OrgName"].ToString();
        strServerName = WebConfigurationManager.AppSettings["ServerName"].ToString();
  
        //Initialize CRM web services============
        //CrmAuthenticationToken token;
        //token = Microsoft.Crm.Sdk.CrmAuthenticationToken.ExtractCrmAuthenticationToken(Context, strOrgName);
        //token.OrganizationName = "AccommodationsPlusInternationa";       
        CrmAuthenticationToken token = new CrmAuthenticationToken();
        token.OrganizationName = strOrgName;
        token.AuthenticationType = 0;
        //token.CallerId = new Guid("33A3DB94-2D5C-DE11-8FE7-0003FFFEF7A2");
  
        CrmService theService = new CrmService();
        //CrmService service = new CrmService();
        //service.Url = "http://moss:5555/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=accommodationsplusinternationa";       
        //theService.Credentials = System.Net.CredentialCache.DefaultCredentials;
        theService.Credentials = new NetworkCredential("Administrator", "pass@word1", "Contoso.com");
        theService.CrmAuthenticationTokenValue = token;
        theService.Url = "http://" + strServerName + "/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=" + strUniqueName;
        //End Initialize CRM web services========
        #endregion
  
        #region rfpdataLabels
        //retrieve the RFP and set the hidden labels with data
  
        ColumnSet rfpCols = new ColumnSet();
        rfpCols.Attributes = new string[] { 
        "new_rfpprogramid", "new_bidcode", "new_rfpclosedate", "new_daysremaining", "new_airportid", "new_airport", 
        "new_airlinecode", "new_longlist", "new_numofrooms", 
        "new_hoteltype_allsuite", "new_hoteltypeallsuite", "new_restaurant",   "new_airportdistance",  "new_markettier", 
        "new_hoteltypebb", "new_hoteltypecabin", "new_hoteltypecondominium", "new_hoteltypeconferencecenter",
        "new_hoteltypeconvention", "new_hoteltypecorptransient", "new_hoteltypeextendedstay", "new_hoteltypeextstay",
        "new_hoteltypefullservice", "new_hoteltypehotel", "new_hoteltypeinn", "new_hoteltypelimitedservice",
        "new_hoteltypemotel", "new_hoteltyperesidential", "new_hoteltyperesort", "new_searchrun"};
  
        new_rfpprogram theRfpProgram = (new_rfpprogram)theService.Retrieve(EntityName.new_rfpprogram.ToString(), guidRfpGuid, rfpCols);
        //new_rfpprogram theRfpProgram = (new_rfpprogram)service.Retrieve(EntityName.new_rfpprogram.ToString(), guidRfpGuid, new AllColumns());
  
        //txtDebug.Text += theRfpProgram.new_numofrooms.Value.ToString() + "\n";
   
        lblRfpGuid.Text = theRfpProgram.new_rfpprogramid.Value.ToString();
        lblBidCode.Text = theRfpProgram.new_bidcode;
        DateTime dtCloseDate = DateTime.Parse(theRfpProgram.new_rfpclosedate.Value.ToString());
        lblCloseDate.Text = dtCloseDate.ToShortDateString();
        lblDaysRemaining.Text = theRfpProgram.new_daysremaining.Value.ToString();
        lblAirportGuid.Text = theRfpProgram.new_airportid.Value.ToString();
        lblAirportName.Text = theRfpProgram.new_airport;
        lblAirlineCode.Text = theRfpProgram.new_airlinecode;
        //lblRfpRooms.Text = theRfpProgram.new_numofrooms.Value.ToString();
        #endregion
  
        #region datagrids
        GetNonFilteredHotels(ref alistHotelNamesCityMatches, ref alistHotelIdsCityMatches, ref theRfpProgram);
        if (NonFilteredHotels.Count == 0)
          nonFilteredResults.Add(new objHotel("", "", "", "", 0, "", "", ""));
        grdNonFilteredHotels.DataSource = NonFilteredHotels;
        //txtDebug.Text += "After GetNonFilteredHotels\n";
        //txtDebug.Text += "Hotel Names City Matches length: " + alistHotelNamesCityMatches.Count.ToString() + "\n";
        //txtDebug.Text += "Hotel IDs City Matches length: " + alistHotelIdsCityMatches.Count.ToString() + "\n";
  
        GetFilteredHotels(ref FilteredResults, ref nonFilteredResults, ref alistHotelIdsCityMatches, ref theRfpProgram);
        grdFilteredHotels.DataSource = FilteredHotels;
        //txtDebug.Text += "After GetFilteredHotels\n";
        //txtDebug.Text += "Hotel Names City Matches length: " + alistHotelNamesCityMatches.Count.ToString() + "\n";
        //txtDebug.Text += "Hotel IDs City Matches length: " + alistHotelIdsCityMatches.Count.ToString() + "\n";
        #endregion
  
        #region long list entities
        /*
        //The next code will check the "Search Run" flag, and if it is set to fasle, 
        //will create a lsit of Long List entities
        //It will first loop through the nonFiltered results and then the 
        //filtered results.
        if (theRfpProgram.new_searchrun == null || theRfpProgram.new_searchrun.Value == false)
        {
          if ( theRfpProgram.new_searchrun == null)
            txtDebug.Text += theRfpProgram.new_bidcode + " Search run value is null";
          else
            txtDebug.Text += theRfpProgram.new_bidcode + "Search run value: " + theRfpProgram.new_searchrun.Value.ToString();
          for (int i = 0; i < nonFilteredResults.Count; i++)
          {
            //txtDebug.Text += "Inside CreateLongList loop\n";
  
            objHotel nH = (objHotel)nonFilteredResults[i];
            // Create the query object.
            QueryByAttribute query = new QueryByAttribute();
            query.ColumnSet = new AllColumns();
            query.EntityName = EntityName.new_hotel.ToString();
            query.Attributes = new string[] { "new_hotname" };
            query.Values = new string[] { nH.Hotel };
            //txtDebug.Text += "Count " + i.ToString() + ": Hotel Name " + nH.HotelName + "\n";
  
            // Execute the retrieval.
            BusinessEntityCollection retrieved = theService.RetrieveMultiple(query);
  
            //txtDebug.Text += "Length of retrieved list: " + retrieved.BusinessEntities.Length.ToString() + "\n";
  
            new_hotel theHotel = (new_hotel)retrieved.BusinessEntities[0];
            new_longlist newLL = new new_longlist();
            alistLongList.Add(newLL);
            newLL.new_name = nH.Hotel;
            newLL.new_hotelid = new Lookup();
            newLL.new_hotelid.Value = theHotel.new_hotelid.Value;
            newLL.new_rfpprogramid = new Lookup();
            //newLL.new_rfpprogramid.Value = theRFP.new_rfpprogramid.Value;
            newLL.new_rfpprogramid.Value = new Guid(lblRfpGuid.Text);
            newLL.new_rfpstatus = new Picklist();
            newLL.new_rfpstatus.Value = 4;
            theService.Create(newLL);
          }
          for (int i = 0; i < FilteredResults.Count; i++)
          {
            //txtDebug.Text += "Inside CreateLongList loop\n";
  
            objHotel nH = (objHotel)FilteredResults[i];
            // Create the query object.
            QueryByAttribute query = new QueryByAttribute();
            query.ColumnSet = new AllColumns();
            query.EntityName = EntityName.new_hotel.ToString();
            query.Attributes = new string[] { "new_hotname" };
            query.Values = new string[] { nH.Hotel };
            //txtDebug.Text += "Count " + i.ToString() + ": Hotel Name " + nH.HotelName + "\n";
  
            // Execute the retrieval.
            BusinessEntityCollection retrieved = theService.RetrieveMultiple(query);
  
            //txtDebug.Text += "Length of retrieved list: " + retrieved.BusinessEntities.Length.ToString() + "\n";
  
            new_hotel theHotel = (new_hotel)retrieved.BusinessEntities[0];
            new_longlist newLL = new new_longlist();
            alistLongList.Add(newLL);
            newLL.new_name = nH.Hotel;
            newLL.new_hotelid = new Lookup();
            newLL.new_hotelid.Value = theHotel.new_hotelid.Value;
            newLL.new_rfpprogramid = new Lookup();
            //newLL.new_rfpprogramid.Value = theRFP.new_rfpprogramid.Value;
            newLL.new_rfpprogramid.Value = new Guid(lblRfpGuid.Text);
            newLL.new_rfpstatus = new Picklist();
            newLL.new_rfpstatus.Value = 4;
            theService.Create(newLL);
          }
          theRfpProgram.new_searchrun = new CrmBoolean();
          theRfpProgram.new_searchrun.Value = true;
          theService.Update(theRfpProgram);
        }
        */
        #endregion
      }  
      catch (System.Web.Services.Protocols.SoapException soapEx)
      {
        txtDebug.Text += "SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString();
      }
      catch (Exception ex)
      {
        txtDebug.Text += "General exception: " + ex.StackTrace.ToString() + "\n" + ex.ToString();
      }
    }
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected IList<objHotel> NonFilteredHotels
  {
    get
    {
      try
      {
        object obj = Session["NonFilteredHotels"];
        if (obj == null)
        {
          //obj = GetNonFilteredHotels();
          obj = nonFilteredResults;
          if (obj != null)
          {
            Session["NonFilteredHotels"] = obj;
          }
          else
          {
            obj = new System.Collections.Generic.List<objHotel>();
          }
        }
        return (IList<objHotel>)obj;
      }
      catch
      {
        Session["NonFilteredHotels"] = null;
      }
      return new List<objHotel>();
    }
    set { Session["NonFilteredHotels"] = value; }
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected IList<objHotel> FilteredHotels
  {
    get
    {
      try
      {
        object obj = Session["FilteredHotels"];
        if (obj == null)
        {
          //obj = GetFilteredHotels(ref FilteredResults, ref nonFilteredResults, ref alistHotelIdsCityMatches);
          obj = FilteredResults;
          if (obj != null)
          {
            Session["FilteredHotels"] = obj;
          }
          else
          {
            obj = new System.Collections.Generic.List<objHotel>();
          }
        }
        return (IList<objHotel>)obj;
      }
      catch
      {
        Session["FilteredHotels"] = null;
      }
      return new List<objHotel>();
    }
    set { Session["FilteredHotels"] = value; }
    //get
    //{
    //  try
    //  {
    //    object obj = Session["FilteredHotels"];
    //    if (obj == null)
    //    {
    //      Session["FilteredHotels"] = obj = new List<Hotel>();
    //    }
    //    return (IList<Hotel>)obj;
    //  }
    //  catch
    //  {
    //    Session["FilteredHotels"] = null;
    //  }
    //  return new List<Hotel>();
    //}
    //set { Session["FilteredHotels"] = value; }
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected IList<objHotel> GetFilteredHotels(ref IList<objHotel> iListFiltered, ref IList<objHotel> iListNonFiltered, 
                                           ref ArrayList alistNonFilteredIds, ref new_rfpprogram theRfp)
  {
    //for (int i = 0; i < alistNonFilteredIds.Count; i++)
    //{
    //  txtDebug.Text += alistNonFilteredIds[i].ToString() + "\n";
    //}
  
    //txtDebug.Text += "RFP: " + theRfp.new_rfpprogramid.Value.ToString() + "\n"; ;
    //txtDebug.Text += "RFP Rooms: " + theRfp.new_numofrooms.Value.ToString() + "\n"; ;
  
    try
    {
      //This ArrayList will hold thenames of hotels that match the full query
      //and so must be removed from the Non-Filtered List
      ArrayList alistHotelsToRemove = new ArrayList();
  
      #region webservices
      //Get the CRM varaibles from the web.config file
      strUniqueName = WebConfigurationManager.AppSettings["UniqueName"].ToString();
      strOrgName = WebConfigurationManager.AppSettings["OrgName"].ToString();
      strServerName = WebConfigurationManager.AppSettings["ServerName"].ToString();
  
      //Initialize CRM web services============
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      token.AuthenticationType = 0;
      //token.OrganizationName = "AccommodationsPlusInternationa";
      token.OrganizationName = strOrgName;
      //token.CallerId = new Guid("33A3DB94-2D5C-DE11-8FE7-0003FFFEF7A2");
  
      CrmService service = new CrmService();
      //service.Url = "http://moss:5555/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=accommodationsplusinternationa";
      service.Url = "http://" + strServerName + "/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=" + strUniqueName;
      service.CrmAuthenticationTokenValue = token;
      //service.Credentials = System.Net.CredentialCache.DefaultCredentials;
      service.Credentials = new NetworkCredential("Administrator", "pass@word1", "Contoso");
      //End Initialize CRM web services========
      #endregion
  
    #region filteredquerysearch
    //The next code must loop through the list of City matches and retrieve the hotels to see which ones
    //match the query built for the RFP
    //The code must also account for teh requirement that if a Hotel matches the filtered query,
    //it should not be included in teh City Matches list
    //The process is:
    //Loop through the Hotels names/ids in the City matches list box
    //use the web services to retieve each Hotel object
    //test the retrieved hotel against the filtered query
    //if it matches, add teh Hotel to the filtered arraylsit, and remove the hotel from the
    //CityMatches array list
    //When the process completes, clear the City Matches (non-filtered) list box
    //The final step is to populate the lsit boxes from teh ArrayLists
  
    //if (alistHotelIdsCityMatches.Count > 0)
    //if (lstCityMatches.Items.Count > 0)
    //nonFilteredResults.Add(new Hotel(strHotelName, strHotelStreet, strHotelCity, strLocalTel, strEmail, strNumRooms, strMarketTier, strAirportCode, strAirportDist));
    //if (alistHotelIdsCityMatches.Count > 0)
    if (alistNonFilteredIds.Count > 0)
    {
      //txtDebug.Text += "Count: " + alistNonFilteredIds.Count.ToString() + "\n";   
      for (int i = 0; i < alistNonFilteredIds.Count; i++)
      {       
        bool bFail = false;
  
        //txtDebug.Text += alistHotelNamesCityMatches[i].ToString() + " " + alistHotelIdsCityMatches[i].ToString() + "\n";
  
        //Get the hotel GUID
        //Guid hotelGuid = new Guid(alistHotelIdsCityMatches[i].ToString());
        Guid hotelGuid = new Guid(alistNonFilteredIds[i].ToString());
        // Retrieve the hotel.
        ColumnSet hotelCols = new ColumnSet();
        //hotelCols.Attributes = new string[] {"new_hotname", "new_hotstreet1", "new_nearmajorcityid", "new_localtel", 
        //                                     "new_email2", "new_numofrooms", "new_markettier", "new_airportcode", "new_airportdistance" };
        //new_hotel tH = new new_hotel();
        hotelCols.Attributes = new string[] {"new_hotname", "new_hotstreet1", "new_nearmajorcityid", "new_hoteltype_allsuite", "new_hoteltype_bedbreakfast", 
                                             "new_hoteltype_cabinbungalow","new_hoteltype_condominium","new_numofrooms",
                                             "new_hoteltype_conferencecenter","new_hoteltype_extendedstay", 
                                             "new_hoteltype_cabinbungalow","new_hoteltype_condominium","new_numofrooms",
                                             "new_hoteltype_conferencecenter","new_hoteltype_hotel",
                                             "new_doesthehotelhaveashuttle1","new_restaurantname4","new_hoteltype_innlodge",
                                             "new_hoteltype_motel","new_hoteltype_resort","new_markettier",
                                             "new_airportdistance", "new_localtel", "new_email2",
                                             "new_markettier", "new_airportcode", "new_airportdistance" };
        new_hotel theHotel = (new_hotel)service.Retrieve(EntityName.new_hotel.ToString(), hotelGuid, hotelCols);
        //txtDebug.Text += theHotel.new_hotname + "\n"; 
  
        //txtDebug.Text += theHotel.new_hotname + "\n"; 
  
        //Check the requirements marked on the RFP
        //first check to be sure the RFP element is not null, and if not, check if
        //the value is true
        //if the item is selected on the RFP, then the hotel must have that feature
        //check if the hotel element is null, if not, check to see if it is
        //false
        //If so, mark bFail as "true"
  
        //Note that if no additional query items are selected, then all hotels found via
        //the city search should be put in the "filtered" results.
        string sTest = "";
        if (theRfp.new_hoteltypeallsuite != null && theRfp.new_hoteltypeallsuite.Value == true)
          if (theHotel.new_hoteltype_allsuite == null || theHotel.new_hoteltype_allsuite.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on AllSuite";
          }
        //else
        //  sTest += theHotel.new_hoteltype_allsuite.Value.ToString();
  
        if (theRfp.new_hoteltypebb != null && theRfp.new_hoteltypebb.Value == true)
          if (theHotel.new_hoteltype_bedbreakfast == null || theHotel.new_hoteltype_bedbreakfast.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on BB";
            //else
            //  sTest += " " + theHotel.new_hoteltype_bedbreakfast.Value.ToString();
          }
  
        if (theRfp.new_hoteltypecabin != null && theRfp.new_hoteltypecabin.Value == true)
          if (theHotel.new_hoteltype_cabinbungalow == null || theHotel.new_hoteltype_cabinbungalow.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on Cabin";
            //else
            //  sTest += " " + theHotel.new_hoteltype_cabinbungalow.Value.ToString();
          }
  
        if (theRfp.new_hoteltypecondominium != null && theRfp.new_hoteltypecondominium.Value == true)
          if (theHotel.new_hoteltype_condominium == null || theHotel.new_hoteltype_condominium.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on Condo";
            //else
            //  sTest += " " + theHotel.new_hoteltype_condominium.Value.ToString();
          }
  
        if (theRfp.new_numofrooms != null && theRfp.new_numofrooms.Value != null)
        {
          if (theHotel.new_numofrooms != null && theHotel.new_numofrooms.Value != null)
          {
            int iRfpNumRooms = theRfp.new_numofrooms.Value;
            int iHotelNumRooms = theHotel.new_numofrooms.Value;
            if (iHotelNumRooms < iRfpNumRooms)
            {
              bFail = true;
              //txtDebug.Text += theHotel.new_hotname + " Fails on Num rooms";
            }
          }
          else
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on Num rooms";
          }
        }
  
        if (theRfp.new_hoteltypeconferencecenter != null && theRfp.new_hoteltypeconferencecenter.Value == true)
        {
          if (theHotel.new_hoteltype_conferencecenter == null || theHotel.new_hoteltype_conferencecenter.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on conference center";
          }
        }
  
        if (theRfp.new_hoteltypeextstay != null && theRfp.new_hoteltypeextstay.Value == true)
        {
          if (theHotel.new_hoteltype_extendedstay == null || theHotel.new_hoteltype_extendedstay.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on ext stay";
          }
        }
  
        if (theRfp.new_hoteltypehotel != null && theRfp.new_hoteltypehotel.Value == true)
        {
          if (theHotel.new_hoteltype_hotel == null || theHotel.new_hoteltype_hotel.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on hotel";
          }
        }
  
        if (theRfp.new_doeshotelhaveashuttle != null && theRfp.new_doeshotelhaveashuttle.Value == 1)
        {
          if (theHotel.new_doesthehotelhaveashuttle1 == null || theHotel.new_doesthehotelhaveashuttle1.Value != 1)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on shuttle";
          }
        }
  
        if (theRfp.new_restaurant != null && theRfp.new_restaurant.Value == true)
          if (theHotel.new_restaurantname4 == null)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on rest name";
          }
  
        if (theRfp.new_hoteltypeinn != null && theRfp.new_hoteltypeinn.Value == true)
          if (theHotel.new_hoteltype_innlodge == null || theHotel.new_hoteltype_innlodge.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on Inn";
          }
  
        if (theRfp.new_hoteltypemotel != null && theRfp.new_hoteltypemotel.Value == true)
          if (theHotel.new_hoteltype_motel == null || theHotel.new_hoteltype_motel.Value != true)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on motel";
          }
  
        if (theRfp.new_hoteltyperesort != null && theRfp.new_hoteltyperesort.Value == true)
          if (theHotel.new_hoteltype_resort == null || theHotel.new_hoteltype_resort.Value != true)
          {
            //txtDebug.Text += theHotel.new_hotname + " Fails on resort";
            bFail = true;
          }
  
        if (theRfp.new_markettier != null && theRfp.new_markettier.Value > 0)
          if (theHotel.new_markettier == null || theHotel.new_markettier.Value == 0)
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on market tier";
          }
  
        if (theRfp.new_airportdistance != null)
          if (theHotel.new_airportdistance != null)
          {
            int iRfpDist = Convert.ToInt32(removeNonNumerics(theRfp.new_airportdistance));
            int iHotelDist = Convert.ToInt32(removeNonNumerics(theHotel.new_airportdistance));
            if (iHotelDist > iRfpDist)
            {
              bFail = true;
              //txtDebug.Text += theHotel.new_hotname + " Fails on airport distance";
            }
          }
          else
          {
            bFail = true;
            //txtDebug.Text += theHotel.new_hotname + " Fails on airport distance";
          }
  
        //if bFail is false, the hotel has all the features requested
        //in the rfp, so add to the short list
        if (!bFail)
        {
          //ref IList<Hotel> iListFiltered, ref IList<Hotel> iListNonFiltered, ref ArrayList alistNonFilteredIds)
          iListFiltered.Add(iListNonFiltered[i]);
          alistHotelsToRemove.Add(iListNonFiltered[i].Hotel);
          //iListNonFiltered.RemoveAt(i);
            
  
            
          ////lstFullQueryMatches.Items.Add(alistHotelNamesCityMatches[i].ToString());
          ////alistHotelNamesFullMatches.Add(alistHotelNamesCityMatches[i].ToString());
          ////strHotelName for Display only!
          //string strHotelName = theHotel.new_hotname;
          ////while ( strHotelName.Length <100)
          ////  strHotelName += "1";
  
          ////txtDebug.Text += strHotelName;
  
          //alistHotelNamesFullMatches.Add(theHotel.new_hotname);
          //alistHotelIDsFullMatches.Add(theHotel.new_hotelid.Value.ToString());
  
          ////If the hotel has pased the filtered query, we must remove it from the City matches list
          ////i.e. a hotel should not be in both lists
          //for (int ii = 0; ii < alistHotelNamesCityMatches.Count; ii++)
          //{
          //  //  txtDebug.Text += alistHotelNamesCityMatches[ii].ToString() + " " + alistHotelNamesCityMatches.Count.ToString() + "\n";
          //  if (theHotel.new_hotname.Equals(alistHotelNamesCityMatches[ii].ToString()))
          //  {
          //    alistHotelNamesCityMatches.RemoveAt(ii);
          //    alistHotelIdsCityMatches.RemoveAt(ii);
          //    //ii = alistHotelNamesCityMatches.Count + 1;
          //  }
          //}
  
          ////GridView1.da
  
          //if (theHotel.new_hotemail != null) // Hotel Email
          //{
          //  strEmail = theHotel.new_hotemail.ToString();
          //  //txtDebug.Text += strEmail;
          //}
          //else if (strEmail == "" && theHotel.new_email != null) // GM Email
          //  strEmail = theHotel.new_email.ToString();
          //else if (strEmail == "" && theHotel.new_email1 != null) // Email 1
          //  strEmail = theHotel.new_email1.ToString();
          //else if (strEmail == "" && theHotel.new_email2 != null) // Email 2
          //  strEmail = theHotel.new_email2.ToString();
          //else if (strEmail == "" && theHotel.new_email3 != null) // Email 3
          //  strEmail = theHotel.new_email3.ToString();
          //else if (strEmail == "" && theHotel.new_email4 != null) // Email 4
          //  strEmail = theHotel.new_email4.ToString();
          //alistHotelEmailsFullMatches.Add(strEmail);
            
        }
  
        //Populate the lsit box that shows Hotels that match the City, State, Country, query.
        //for (int z = 0; z < alistHotelNamesCityMatches.Count; z++)
        //{
        //  ListItem newItem = new ListItem(alistHotelNamesCityMatches[z].ToString(), alistHotelIdsCityMatches[z].ToString());
        //  lstCityMatches.Items.Add(newItem);
        //  txtDebug.Text += alistHotelNamesCityMatches[z].ToString() + "\n";
        //}
      }
  
      //lstCityMatches.Items.Clear();
  
      ////Populate the list box that shows city matches
      //for (int y = 0; y < alistHotelNamesCityMatches.Count; y++)
      //{
      //  ListItem newItem3 = new ListItem(alistHotelNamesCityMatches[y].ToString(), alistHotelIdsCityMatches[y].ToString());
      //  //alistHotelNamesCityMatches.Add(reader[0].ToString());
      //  //alistHotelIdsCityMatches.Add(reader[1].ToString());
      //  lstCityMatches.Items.Add(newItem3);
      //}
  
  
      ////Populate the list box that shows full query matches
      //for (int z = 0; z < alistHotelNamesFullMatches.Count; z++)
      //{
      //  ListItem newItem2 = new ListItem(alistHotelNamesFullMatches[z].ToString(), alistHotelIDsFullMatches[z].ToString());
      //  lstFullQueryMatches.Items.Add(newItem2);
      //  //txtDebug.Text += alistHotelNamesFullMatches[z].ToString() + "\n";
      //}
    }
    else
    {
      //sw1.WriteLine("***ERROR*** - alistHotelIdsCityMatches empty");
      txtDebug.Text += "***ERROR*** - alistHotelIdsCityMatches empty";
    }
    #endregion
  
      //txtDebug.Text += "Hotels to remove: " + alistHotelsToRemove.Count.ToString() + "\n";
      for (int z = 0; z < alistHotelsToRemove.Count; z++)
      {
        //txtDebug.Text += alistHotelsToRemove[z].ToString() + "\n";
        for (int zz = 0; zz < iListNonFiltered.Count; zz++)
        {
          if ( alistHotelsToRemove[z].ToString() == iListNonFiltered[zz].Hotel)
            iListNonFiltered.RemoveAt(zz);
        }
      }   
    }
    catch (System.Web.Services.Protocols.SoapException soapEx)
    {
      txtDebug.Text += "SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString();
    }
    catch (Exception ex)
    {
      txtDebug.Text += "General exception: " + ex.StackTrace.ToString() + "\n" + ex.ToString();
    }
    return FilteredResults;
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected IList<objHotel> GetNonFilteredHotels(ref ArrayList alistHNCMs, ref ArrayList alistHICMs, 
                                              ref new_rfpprogram theRfp)
  {
    ArrayList alistAllCities = new ArrayList();
    ArrayList alistAllCitiesIds = new ArrayList();
    ArrayList alistAirportCodes = new ArrayList();
    ArrayList alistAirportCodesIds = new ArrayList();
    //Vars for City names and IDs in the FetchXML string, used to build the query
    ArrayList alistCities = new ArrayList();          //City Names
    ArrayList alistCityMatchIds = new ArrayList();    //City IDs
    //ArrayList alistHotelIDsFullMatches = new ArrayList();
    //ArrayList alistHotelNamesFullMatches = new ArrayList();
    ArrayList alistHotelEmailsFullMatches = new ArrayList();
    ArrayList alistSavedQueries = new ArrayList();
  
    //strConStr = GetConnectionString("MOSS_SqlConnString");
    //Get connection string from Web.Config
    //strConStr = ConfigurationSettings.AppSettings ("MOSS_SqlConnString");
    //strConStr = ConfigurationSettings.AppSettings ("MOSS_SqlConnString");
    //conn.ConnectionString = ConfigurationManager.ConnectionStrings("YourConnectionString").ConnectionString  
    //strConStr = ConfigurationManager.ConnectionStrings["MOSS_SqlConnString"].ConnectionString;  
  
    string strAirportNameQuery;
    string strAirportCode;
  
    //if (!IsPostBack)
    //{
    //Error log file
    //sw1 = File.AppendText("C://ApiLogs//API_AF_Page_Load_Log.txt");
  
    #region clear
    /*
    //Clear all the arraylists and lsit boxes
    alistCities.Clear();
    alistCityMatchIds.Clear();
    alistHotelEmailsFullMatches.Clear();
    alistHotelIdsCityMatches.Clear();
    alistHotelIDsFullMatches.Clear();
    alistHotelNamesCityMatches.Clear();
    alistHotelNamesFullMatches.Clear();
    alistSavedQueries.Clear();
    */
    //Reset the FetchXML variable
    strAirportFetchXml = "";
    #endregion
  
    //Get the GUID of the RFP the page was called from
    strRfpGuid = Request["Id"];
    //20e2f37f-48e2-dd11-a573-0003ffc35ce2
    //strRfpGuid = "20e2f37f-48e2-dd11-a573-0003ffc35ce2";
    try
    {
      //Get the CRM varaibles from the web.config file
      strUniqueName = WebConfigurationManager.AppSettings["UniqueName"].ToString();
      strOrgName = WebConfigurationManager.AppSettings["OrgName"].ToString();
      strServerName = WebConfigurationManager.AppSettings["ServerName"].ToString();
  
      #region webservices
      //Initialize CRM web services============
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      token.AuthenticationType = 0;
      //token.OrganizationName = "AccommodationsPlusInternationa";
      token.OrganizationName = strOrgName;
      //token.CallerId = new Guid("33A3DB94-2D5C-DE11-8FE7-0003FFFEF7A2");
  
      CrmService service = new CrmService();
      //service.Url = "http://moss:5555/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=accommodationsplusinternationa";
      service.Url = "http://" + strServerName + "/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=" + strUniqueName;
      service.CrmAuthenticationTokenValue = token;
      //service.Credentials = System.Net.CredentialCache.DefaultCredentials;
      service.Credentials = new NetworkCredential("Administrator", "pass@word1", "Contoso");
      //End Initialize CRM web services========
      #endregion
  
      #region getcities
      /*
      //Get Cities and IDs
      QueryExpression queryPrincipal = new QueryExpression();
      queryPrincipal.EntityName = EntityName.new_city.ToString();
      ColumnSet cols = new ColumnSet();
      cols.Attributes = new string[] { "new_name", "new_cityid" };
      queryPrincipal.ColumnSet = cols;
      //queryPrincipal.ColumnSet = new AllColumns();
  
      BusinessEntityCollection myCities = service.RetrieveMultiple(queryPrincipal);
      foreach (BusinessEntity myCity in myCities.BusinessEntities)
      {
        new_city C = (new_city)myCity;
        alistAllCities.Add(C.new_name);
        alistAllCitiesIds.Add(C.new_cityid.Value.ToString());
      }
      */
      //Use SQL
      string mySelectQuery = "SELECT new_name, new_cityid FROM dbo.new_cityextensionbase";
      SqlConnection myConnection = new SqlConnection(strConStr);
      SqlCommand myCommand = new SqlCommand(mySelectQuery, myConnection);
      SqlDataReader myReader;
      try
      {
        myConnection.Open();
        myReader = myCommand.ExecuteReader();
        // Always call Read before accessing data.
        while (myReader.Read())
        {
          //alistCurrencies.Add(myReader.GetGuid(0).ToString());
          alistAllCities.Add(myReader.GetString(0));
          alistAllCitiesIds.Add(myReader.GetGuid(1).ToString());
        }
        // always call Close when done reading.
        myReader.Close();
        //close command
        myCommand = null;
        // Close the connection when done with it.
        myConnection.Close();
      }
      catch (SqlException ssqlEx)
      {
        //Console.WriteLine("***************SQL SERVER ERROR******************\nUnable to connect to SQL Server " + ssqlEx.ToString());
        //sw.WriteLine("***************SQL SERVER ERROR******************\nUnable to connect to SQL Server " + ssqlEx.ToString());
        //If error connecting to SQL server, set NoSql flag to true.
        //bNoSQL = true;
      }
      #endregion
  
      //Retrieve the RFP that called the custom search page
      rfpGuid = new Guid(strRfpGuid);
        
      //ColumnSet rfpCols = new ColumnSet();
      //rfpCols.Attributes = new string[] { "new_rfpprogramid", "new_bidcode", "new_rfpclosedate", "new_daysremaining", "new_airportid", "new_airport", "new_airlinecode", "new_longlist" };
      //theRfp = (new_rfpprogram)service.Retrieve(EntityName.new_rfpprogram.ToString(), rfpGuid, rfpCols);
  
      //If the search has never been run before....
      //if (theRFP.new_searchrun == null || theRFP.new_searchrun.Value == false)
      //{
        strRfpName = theRfp.new_bidcode;
  
        strAirportSavedQuery = "";
        //*******NEED validation code to be sure these fields have data in them*****
        //Retrieve the saved query values
        //airportid is a CRM LookUp for the Airport
        //Read the lookup field, but the lookup only has the 
        //airport code id, not the whole query name
        if (theRfp.new_airportid != null && theRfp.new_airportid.Value != null)
          strAirportSavedQuery = theRfp.new_airportid.Value.ToString();
        else
          txtDebug.Text += "***ERROR*** - No saved Query in RFP program record";
  
        //=========================================
        //Get the airport 3 letter code
        if (strAirportSavedQuery != "")
        {
          strAirportNameQuery = "Select new_airportcode from New_AirportDestinationExtensionBase where new_airportdestinationid='" + strAirportSavedQuery + "';"; ;
          strAirportCode = "";
          using (SqlConnection connection = new SqlConnection(strConStr))
          {
            SqlCommand command = new SqlCommand(strAirportNameQuery, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            if (reader != null)
            {
              // Call Read before accessing data.     
              while (reader.Read())
              {
                strAirportCode = reader[0].ToString();
              }
              // Call Close when done reading.
              reader.Close();
            }
          }
          //==========================================
  
          #region getfetchxml
          //Initialize the variable for the search query
          //Instead of getting the spefic query by name, which we do not have, we 
          //only have the airport code, get all saved queries
          //Saved queries are in the form: "3 Letter Code - City Name"
          string strSavedQueries = "Select name, fetchxml from dbo.UserQueryBase";
          //Use a SQL query to retrieve the FetchXMl for the saved queries
          //*** Need a catch here to catch if no queries are found
          using (SqlConnection connection = new SqlConnection(strConStr))
          {
            SqlCommand command = new SqlCommand(strSavedQueries, connection);
            connection.Open();
            SqlDataReader reader = command.ExecuteReader();
            // Call Read before accessing data.
            while (reader.Read())
            {
              string sTemp = reader[0].ToString();
              //Instead of an exact match, use IndexOf to find the saved query name
              //that has the 3 digit airport code in it
              if (sTemp.IndexOf(strAirportCode) != -1)
                strAirportFetchXml = reader[1].ToString();
              //else if (sTemp == strRfpSavedQuery)
              //  strRfpFetchXml = reader[1].ToString();
            }
            // Call Close when done reading.
            reader.Close();
          }
          #endregion
  
          //string fetch1 = service.Fetch(strAirportFetchXml);
          //txtDebug.Text += fetch1;
  
          #region parseXML
          //At this point the strAirportFetchXML variable should have the saved query XML string
          //The next code will parse the XML and create arraylists of the City names and IDs
          //For an example of the FetchXML data see the end of this file.
          if (strAirportFetchXml != "")
          {
            //Parse the XML for the City, State, Country Query=============================================
            char[] delimiterChars = { '<' };
            string[] words = strAirportFetchXml.Split(delimiterChars);
            foreach (string s in words)
            {
              if (s.IndexOf("new_city") != -1)
              {
                int iFirstQuote = s.IndexOf("\"");
                int iNextQuote = s.IndexOf("\"", iFirstQuote + 1);
                int iFirstBrace = s.IndexOf("{");
                int iNextBrace = s.IndexOf("}", iFirstBrace);
                //txtDebug.Text += s.Substring(iFirstQuote + 1, iNextQuote - (iFirstQuote + 1)) + "  ID: " + s.Substring(iFirstBrace + 1, iNextBrace - (iFirstBrace + 1)); 
  
                //Add the City name and City ID to the arrays
                //ex of stroed data: Jamaica (NY)
                string sCityTemp = s.Substring(iFirstQuote + 1, iNextQuote - (iFirstQuote + 1));
                sCityTemp = sCityTemp.Replace("(", "(");
                sCityTemp = sCityTemp.Replace(")", ")");
  
                alistCities.Add(sCityTemp);
                alistCityMatchIds.Add(s.Substring(iFirstBrace + 1, iNextBrace - (iFirstBrace + 1)));
              }
              if (s.IndexOf("new_hotcountry") != -1 && s.IndexOf("value") != -1)
              {
                bCountry = true;
                int iValueStart = s.IndexOf("value") + 7;
                int iValueEnd = s.IndexOf("\"", iValueStart + 1);
                strCountry = s.Substring(iValueStart, iValueEnd - iValueStart);
              }
              if (s.IndexOf("new_hotstate") != -1 && s.IndexOf("value") != -1)
              {
                bCountry = true;
                int iValueStart = s.IndexOf("value") + 7;
                int iValueEnd = s.IndexOf("\"", iValueStart + 1);
                strState = s.Substring(iValueStart, iValueEnd - iValueStart);
              }
            }
          }
          else
          {
            //sw1.WriteLine("***ERROR*** - FetchXML Parse Error");
            txtDebug.Text += "***ERROR*** - FetchXML Parse Error";
          }
          //End Parse XML code=========================================================================
          #endregion
  
          #region buildsqlquery
          //Loop through the array of City IDs and build the SQL query to retrieve the hotels
          //that match City, State, Country
          //strCityQuery = "";
          if (alistCityMatchIds.Count > 0)  // If city names exist in the array list
          {
            for (int i = 0; i < alistCityMatchIds.Count; i++)
            {
              if (i < alistCityMatchIds.Count - 1)
                strCityQuery += alistCityMatchIds[i].ToString() + "' OR New_HotelExtensionBase.new_nearmajorcityid='";
              else
              {
                //If it is the last city in the list, close off the first part of
                //the query
                strCityQuery += alistCityMatchIds[i].ToString() + "'))";
                //If there is a value for both State and Country
                //Add to the query
                if (strState != "" && strCountry != "")
                  strCityQuery += " AND (New_HotelExtensionBase.new_hotstate='" + strState + "') AND (New_HotelExtensionBase.new_hotcountry='" + strCountry + "');";
                else if (strState != "" && strCountry == "") //State, no country
                  strCityQuery += " AND (New_HotelExtensionBase.new_hotstate='" + strState + "');";
                else if (strState == "" && strCountry != "")  //Country, no state
                  strCityQuery += " AND (New_HotelExtensionBase.new_hotcountry='" + strCountry + "');";
              }
            }
          }
          else
          {
            //sw1.WriteLine("***ERROR*** - No Cities Found...");
            txtDebug.Text += "***ERROR*** - No Cities Found...";
          }
          //txtDebug.Text += strCityQuery;
          #endregion
  
          #region retrievenonfilteredresults
          //This code retrieves the Hotels that match City, State, Country. 
          //Hotel names are loaded into the lstCityMatches list box
          //Hotel names are also loaded in the Array list: alistHotelNamesCityMatches
          //Hotel IDs are loaded into teh array list: alistHotelIdsCityMatches
          int iCityMatchCount = 0;
          //if (strCityQuery != "Select new_hotname, New_HotelBase.new_hotelid from New_HotelBase INNER JOIN New_HotelExtensionBase ON New_HotelBase.New_HotelId = New_HotelExtensionBase.New_HotelId where ((New_HotelExtensionBase.new_nearmajorcityid = '")      
          if (strCityQuery != "SELECT new_hotname, new_hotstreet1, new_nearmajorcityid, new_numofrooms, new_markettier, new_airportcode, new_airportdistance, new_localtel, new_email2, new_hotelid FROM New_HotelExtensionBase where ((New_HotelExtensionBase.new_nearmajorcityid = '")
          {
            //txtDebug.Text += strCityQuery;
            try
            {
              //Retrieve the Hotel IDs that match the Query
              using (SqlConnection connection = new SqlConnection(strConStr))
              {
                SqlCommand command = new SqlCommand(strCityQuery, connection);
                connection.Open();
                SqlDataReader reader = command.ExecuteReader();
                //// Call Read before accessing data.
                bool found = false;
                int iMatches = 0;
                //dynamicCheckboxes = new CheckBox[1000];
  
  
                while (reader.Read() && !found)
                {
                  string strHotelName = (!reader.IsDBNull(reader.GetOrdinal("new_hotname")))
                                         ? (string)reader.GetValue(reader.GetOrdinal("new_hotname"))
                                         : string.Empty;
  
                  string strHotelStreet = (!reader.IsDBNull(reader.GetOrdinal("new_hotstreet1")))
                                         ? (string)reader.GetValue(reader.GetOrdinal("new_hotstreet1"))
                                         : string.Empty;
  
                  string strHotelCity = "";
                  Guid guidHotelCityGuid = (!reader.IsDBNull(reader.GetOrdinal("new_nearmajorcityid")))
                                            ? (Guid)reader.GetValue(reader.GetOrdinal("new_nearmajorcityid"))
                                            : Guid.Empty;
                  string strHotelCityGuid = guidHotelCityGuid.ToString();
                  for (int i = 0; i < alistAllCitiesIds.Count; i++)
                  {
                    if (strHotelCityGuid == alistAllCitiesIds[i].ToString())
                    {
                      strHotelCity = alistAllCities[i].ToString();
                      i = alistAllCitiesIds.Count + 5;
                    }
                  }
  
                  int iNumRooms = 0;
                  if (!reader.IsDBNull(3))
                    iNumRooms = reader.GetInt32(3);
                  //string strNumRooms = iNumRooms.ToString();
  
                  int iMT = 6;
                  if (!reader.IsDBNull(4))
                    iMT = reader.GetInt32(4);
                  //int iMT             = (!reader.IsDBNull(reader.GetOrdinal("new_markettier")))
                  //                       ? (int)reader.GetValue(reader.GetOrdinal("new_markettier"))
                  //                       : int.Parse("");
                  //int iMT = Int32.Parse(strMarketTier);
                  string strMarketTier = strMarketTiers[iMT - 1];
  
  
                  //command.CommandText = "SELECT new_hotname, new_hotstreet1, new_nearmajorcityid, 
                  //                              new_numofrooms, new_markettier, new_airportcode, 
                  //                              new_airportdistance, new_localtel, new_hotemail, new_hotelid
  
                  strAirportCode = "";
                  string strAirportCodeId = "";
                  if (!reader.IsDBNull(5))
                    strAirportCode = reader.GetString(5);
                  for (int i = 0; i < alistAirportCodesIds.Count; i++)
                  {
                    if (strAirportCodeId == alistAirportCodesIds[i].ToString())
                    {
                      strAirportCode = alistAirportCodesIds[i].ToString();
                      i = alistAirportCodesIds.Count + 5;
                    }
                  }
  
                  string strAirportDist = "";
                  if (!reader.IsDBNull(6))
                    strAirportDist = reader.GetString(6);
  
                  string strLocalTel = (!reader.IsDBNull(reader.GetOrdinal("new_localtel")))
                                        ? (string)reader.GetValue(reader.GetOrdinal("new_localtel"))
                                        : string.Empty;
  
                  //Change to DOS email
                  string strEmail = (!reader.IsDBNull(reader.GetOrdinal("new_email2")))
                                     ? (string)reader.GetValue(reader.GetOrdinal("new_email2"))
                                     : string.Empty;
  
                  //nonFilteredResults.Add(new Hotel(strHotelName, strHotelStreet, strHotelCity, strLocalTel, strEmail, strNumRooms, strMarketTier, strAirportCode, strAirportDist));
                  //nonFilteredResults.Add(new objHotel(strHotelName, strHotelStreet, strHotelCity, strLocalTel, strEmail, iNumRooms, strMarketTier, strAirportCode, strAirportDist));
                  nonFilteredResults.Add(new objHotel(strHotelName, strHotelStreet, strHotelCity, strEmail, iNumRooms, strMarketTier, strAirportCode, strAirportDist));
  
                  //Add to ArrayLists
                  //alistHotelNamesCityMatches.Add(strHotelName);              
                  //alistHotelIdsCityMatches.Add(reader["new_hotelid"].ToString());
  
                  alistHNCMs.Add(strHotelName);
                  alistHICMs.Add(reader["new_hotelid"].ToString());
                }
                // Call Close when done reading.
                reader.Close();
              }
            }
            catch (SqlException sqlEx)
            {
              txtDebug.Text += sqlEx.ToString();
            }
            catch (Exception ex)
            {
              txtDebug.Text += "General exception: " + ex.ToString();
            }
          }
          else
          {
            txtDebug.Text += "***ERROR*** - No City, State Country Query...";
          }
          #endregion
  
          #region debugtestcode
          /*
        if (theRfp.new_hoteltypeallsuite != null && theRfp.new_hoteltypeallsuite.Value == true)
          txtDebug.Text += "All Suite Checked\n";
        if (theRfp.new_hoteltypebb != null && theRfp.new_hoteltypebb.Value == true)
          txtDebug.Text += "BB Checked\n";
        if (theRfp.new_hoteltypecabin != null && theRfp.new_hoteltypecabin.Value == true)
          txtDebug.Text += "Cabin Checked\n";
        if (theRfp.new_hoteltypecondominium != null && theRfp.new_hoteltypecondominium.Value == true)
          txtDebug.Text += "Condo Checked\n";
        if (theRfp.new_numofrooms != null && theRfp.new_numofrooms.Value != null)
          txtDebug.Text += "Num rooms entered\n" + theRfp.new_numofrooms.Value.ToString();
        if (theRfp.new_hoteltypeconferencecenter != null && theRfp.new_hoteltypeconferencecenter.Value == true)
          txtDebug.Text += "Conference Checked\n";
        if (theRfp.new_hoteltypeextstay != null && theRfp.new_hoteltypeextstay.Value == true)
          txtDebug.Text += "Ext stay Checked\n";
        if (theRfp.new_hoteltypehotel != null && theRfp.new_hoteltypehotel.Value == true)
          txtDebug.Text += "Hotel Checked\n";
        if (theRfp.new_doeshotelhaveashuttle != null && theRfp.new_doeshotelhaveashuttle.Value == 1)
          txtDebug.Text += "Shuttle = yes\n";
        if (theRfp.new_restaurant != null && theRfp.new_restaurant.Value == true)
          txtDebug.Text += "Restaurant entered\n";
        if (theRfp.new_hoteltypeinn != null && theRfp.new_hoteltypeinn.Value == true)
          txtDebug.Text += "Inn Checked\n";
        if (theRfp.new_hoteltypemotel != null && theRfp.new_hoteltypemotel.Value == true)
          txtDebug.Text += "Motel Checked\n";
        if (theRfp.new_hoteltyperesort != null && theRfp.new_hoteltyperesort.Value == true)
          txtDebug.Text += "Resort Checked\n";
        if (theRfp.new_markettier != null && theRfp.new_markettier.Value > 0)
          txtDebug.Text += "Market tier entered\n";
        if (theRfp.new_airportdistance != null)
          txtDebug.Text += "Distance entered\n";
         * */
          #endregion
  
          //for (int i = 0; i < alistHotelIdsCityMatches.Count; i++)
          //{
          //  txtDebug.Text += alistHotelIdsCityMatches[i].ToString() + "\n";
          //}
          //txtDebug.Text += "Count: " + alistHotelIdsCityMatches.Count.ToString() + "\n";
  
          //GetFilteredHotels(ref FilteredResults, ref nonFilteredResults, ref alistHotelIdsCityMatches);
  
        }
        else
          txtDebug.Text += "***ERROR*** - No saved Query in RFP program record";
      //}
      //else //Retrieve long list hotels
      //{
        //QueryByAttribute query = new QueryByAttribute();
        //query.ColumnSet = new AllColumns();
        //query.EntityName = EntityName.new_longlist.ToString();
        //query.Attributes = new string[] { "new_rfpprogramid" };
        //query.Values = new string[] { theRFP.new_rfpprogramid.Value.ToString() };
        //BusinessEntityCollection retrieved = service.RetrieveMultiple(query);
        //for (int i = 0; i < retrieved.BusinessEntities.Length; i++)
        //{
        //  new_longlist nLL = (new_longlist)retrieved.BusinessEntities[i];
        //  Guid guiHotel = new Guid(nLL.new_hotelid.Value.ToString());
        //  new_hotel tH = (new_hotel)service.Retrieve(EntityName.new_hotel.ToString(), guidHotel, new AllColumns());
  
        //  nonFilteredResults.Add(new Hotel(tH.new_hotname, tH.new_hotcitystrHotelStreet, strHotelCity, strLocalTel, strEmail, strNumRooms, strMarketTier, strAirportCode, strAirportDist));
  
        //  alistHNCMs.Add(nLL.new_name);
        //  alistHICMs.Add(nLL.new_hotelid.Value.ToString());
        //}
      //}
    }
    catch (System.Web.Services.Protocols.SoapException soapEx)
    {
      txtDebug.Text += "SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString();
    }
    catch (Exception ex)
    {
      txtDebug.Text += "General exception: " + ex.StackTrace.ToString() + "\n" + ex.ToString();
    }
  
    //alistHNCMs.Add(strHotelName);              
    //alistHICMs.Add(reader["new_hotelid"].ToString());
  
    //txtDebug.Text += "HNCMs length: " + alistHNCMs.Count.ToString() + "\n";
    //txtDebug.Text += "HICMs length: " + alistHICMs.Count.ToString() + "\n";
    return nonFilteredResults;
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected void grdNonFilteredHotels_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
  {
    grdNonFilteredHotels.DataSource = NonFilteredHotels;
  }
  
    
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected void grdFilteredHotels_NeedDataSource(object source, GridNeedDataSourceEventArgs e)
  {
    grdFilteredHotels.DataSource = FilteredHotels;
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected void grdNonFilteredHotels_RowDrop(object sender, GridDragDropEventArgs e)
  {
    if (string.IsNullOrEmpty(e.HtmlElement))
    {
      if (e.DraggedItems[0].OwnerGridID == grdNonFilteredHotels.ClientID)
      {
        // items are drag from pending to shipped grid 
        if ((e.DestDataItem == null && FilteredHotels.Count == 0) ||
             e.DestDataItem != null && e.DestDataItem.OwnerGridID == grdFilteredHotels.ClientID)
        {
          IList<objHotel> filteredHotels = FilteredHotels;
          IList<objHotel> nonFilteredHotels = NonFilteredHotels;
          int destinationIndex = -1;
          if (e.DestDataItem != null)
          {
            objHotel order = GetHotel(filteredHotels, e.DestDataItem.GetDataKeyValue("Hotel").ToString());
            destinationIndex = (order != null) ? filteredHotels.IndexOf(order) : -1;
          }
          foreach (GridDataItem draggedItem in e.DraggedItems)
          {
            objHotel tmpOrder = GetHotel(nonFilteredHotels, draggedItem.GetDataKeyValue("Hotel").ToString());
            if (tmpOrder != null)
            {
              if (destinationIndex > -1)
              {
                filteredHotels.Insert(destinationIndex, tmpOrder);
              }
              else
              {
                filteredHotels.Add(tmpOrder);
              }
              nonFilteredHotels.Remove(tmpOrder);
            }
          }
          FilteredHotels = filteredHotels;
          NonFilteredHotels = nonFilteredHotels;
          grdNonFilteredHotels.Rebind();
          grdFilteredHotels.Rebind();
        }
      }
    }
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  private static objHotel GetHotel(IEnumerable<objHotel> ordersToSearchIn, string hotelName)
  {
    foreach (objHotel order in ordersToSearchIn)
    {
      if (order.Hotel == hotelName)
      {
        return order;
      }
    }
    return null;
  }
  
  /// <summary>====================================================================================
  /// 
  /// </summary>===================================================================================
  protected void grdFilteredHotels_RowDrop(object sender, GridDragDropEventArgs e)
  {
    if (string.IsNullOrEmpty(e.HtmlElement))
    {
      if (e.DraggedItems[0].OwnerGridID == grdFilteredHotels.ClientID)
      {
        if ((e.DestDataItem == null && FilteredHotels.Count == 0) ||
             e.DestDataItem != null && e.DestDataItem.OwnerGridID == grdNonFilteredHotels.ClientID)
        {
          IList<objHotel> filteredHotels = FilteredHotels;
          IList<objHotel> nonFilteredHotels = NonFilteredHotels;
          int destinationIndex = -1;
          if (e.DestDataItem != null)
          {
            objHotel order = GetHotel(nonFilteredHotels, e.DestDataItem.GetDataKeyValue("Hotel").ToString());
            destinationIndex = (order != null) ? nonFilteredHotels.IndexOf(order) : -1;
          }
  
          foreach (GridDataItem draggedItem in e.DraggedItems)
          {
            objHotel tmpOrder = GetHotel(filteredHotels, draggedItem.GetDataKeyValue("Hotel").ToString());
            if (tmpOrder != null)
            {
              if (destinationIndex > -1)
              {
                nonFilteredHotels.Insert(destinationIndex, tmpOrder);
              }
              else
              {
                nonFilteredHotels.Add(tmpOrder);
              }
              filteredHotels.Remove(tmpOrder);
            }
          }
          FilteredHotels = filteredHotels;
          NonFilteredHotels = nonFilteredHotels;
          grdNonFilteredHotels.Rebind();
          grdFilteredHotels.Rebind();
        }
      }
    }
  }
  
  #region Nested type: Order
  
    protected class Order
    {
        private string _companyName;
        private string _customerId;
        private int _orderId;
        private string _date;
  
        public Order(int orderId, string customerId, string companyName, string requiredDate)
        {
            _orderId = orderId;
            _customerId = customerId;
            _companyName = companyName;
            _date = requiredDate;
        }
  
        public int OrderID
        {
            get { return _orderId; }
        }
  
        public string CustomerID
        {
            get { return _customerId; }
        }
  
        public string Company
        {
            get { return _companyName; }
        }
  
        public string Date
        {
            get { return _date; }
        }
    }
  
    #endregion
  
  #region Nested type: Hotel
  protected class objHotel
  {
    private string _hotelName;
    private string _hotelStreet;
    private string _hotelCity;
    //private string _hotelTel;
    private string _hotelEmail;
    //private string _hotelRooms;
    private int _hotelRooms;
    private string _hotelRating;
    private string _hotelCode;
    private string _hotelDist1;
  
//    public Hotel(string hotelName, string hotelStreet, string hotelCity, string hotelTel, string hotelEmail, string hotelRooms, string hotelRating, string hotelCode, string hotelDist1 )
//    public objHotel(string hotelName, string hotelStreet, string hotelCity, string hotelTel, string hotelEmail, int hotelRooms, string hotelRating, string hotelCode, string hotelDist1 )
    public objHotel(string hotelName, string hotelStreet, string hotelCity, string hotelEmail, int hotelRooms, string hotelRating, string hotelCode, string hotelDist1 )
    {
      _hotelName = hotelName;
      _hotelStreet = hotelStreet;
      _hotelCity = hotelCity;
      //_hotelTel = hotelTel;
      _hotelEmail = hotelEmail;
      _hotelRooms = hotelRooms;
      _hotelRating = hotelRating;
      _hotelCode = hotelCode;
      _hotelDist1 = hotelDist1;
    }
  
    //public string HotelName
    //{
    //  get { return _hotelName; }
    //}
  
    public string Hotel
    {
      get { return _hotelName; }
    }
  
    public string Street
    {
      get { return _hotelStreet; }
    }
  
    public string City
    {
      get { return _hotelCity; }
    }
  
    //public string Tel
    //{
    //  get { return _hotelTel; }
    //}
  
    public string DOS_Email
    {
      get { return _hotelEmail; }
    }
  
    public int Rooms
    {
      get { return _hotelRooms; }
    }
  
    public string Star_Rating
    {
      get { return _hotelRating; }
    }
  
    public string Arpt_Code
    {
      get { return _hotelCode; }
    }
  
    public string Arpt_Dist
    {
      get { return _hotelDist1; }
    }
  
    //public string HotelStreet
    //{
    //  get { return _hotelStreet; }
    //}
  
  
    //public string HotelCity
    //{
    //  get { return _hotelCity; }
    //}
  
    //public string HotelTel
    //{
    //  get { return _hotelTel; }
    //}
  
    //public string HotelEmail
    //{
    //  get { return _hotelEmail; }
    //}
  
    ////public string HotelRooms
    ////{
    ////  get { return _hotelRooms; }
    ////}
  
    //public int HotelRooms
    //{
    //  get { return _hotelRooms; }
    //}
  
    //public string HotelRating
    //{
    //  get { return _hotelRating; }
    //}
  
    //public string HotelCode
    //{
    //  get { return _hotelCode; }
    //}
  
    //public string HotelDist1
    //{
    //  get { return _hotelDist1; }
    //}
  }
  #endregion
  
  
  //===============================================================================================
  //===============================================================================================
  public void sendRFPs(ArrayList RFPHOTELS, ArrayList RFPHOTELNAMES, ArrayList HOTELNAMESCITYMATCHES)
  {
    //for (int i = 0; i < FilteredHotels.Count; i++)
    //{
    //  txtDebug.Text += "Hotel: " + i.ToString() + " " + FilteredHotels[i].Hotel + " " + FilteredHotels[i]."\n";
    //}
    //txtDebug.Text += "FilteredHotels count: " + FilteredHotels.Count.ToString() + "\n";
    //txtDebug.Text += "RFPHOTELS count: " + RFPHOTELS.Count.ToString() + "\n";
    //txtDebug.Text += "RFPHOTELNAMES count: " + RFPHOTELNAMES.Count.ToString() + "\n";
    //txtDebug.Text += "HOTELNAMESCITYMATCHES count: " + HOTELNAMESCITYMATCHES.Count.ToString() + "\n";
  
    string strDosEmail = "";
    string strGmEmail = "";
    string strMainEmail = "";
  
    //sw1 = File.AppendText("C://ApiLogs//API_AF_SendEmails_Log.txt");
    try
    {
      #region webservice
      strUniqueName = WebConfigurationManager.AppSettings["UniqueName"].ToString();
      strOrgName = WebConfigurationManager.AppSettings["OrgName"].ToString();
      strServerName = WebConfigurationManager.AppSettings["ServerName"].ToString();
  
      //Initialize CRM web services============
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      token.AuthenticationType = 0;
      //token.OrganizationName = "AccommodationsPlusInternationa";
      token.OrganizationName = strOrgName;
      //token.CallerId = new Guid("33A3DB94-2D5C-DE11-8FE7-0003FFFEF7A2");
  
      CrmService service = new CrmService();
      //service.Url = "http://moss:5555/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=accommodationsplusinternationa";
      service.Url = "http://" + strServerName + "/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=" + strUniqueName;
      service.CrmAuthenticationTokenValue = token;
      //service.Credentials = System.Net.CredentialCache.DefaultCredentials;
      service.Credentials = new NetworkCredential("Administrator", "pass@word1", "Contoso");
      //End Initialize CRM web services========
      #endregion
  
      //retrieve the RFP and the System User
      ColumnSet rfpCols = new ColumnSet();
      rfpCols.Attributes = new string[] { "new_emailtext", "ownerid" };
      new_rfpprogram tR = (new_rfpprogram)service.Retrieve(EntityName.new_rfpprogram.ToString(), new Guid(lblRfpGuid.Text), rfpCols);
      systemuser sU = (systemuser)service.Retrieve(EntityName.systemuser.ToString(), tR.ownerid.Value, new AllColumns());
  
      //For each hotel in the Filtered Hotels grid
      for (int i = 0; i < FilteredHotels.Count; i++)
      //for (int i = 0; i < grdFilteredHotels.Items.Count; i++)
      {
        //txtDebug.Text += i.ToString() + ": " + grdFilteredHotels.Items[i].Cells[3].Text + "\n";
        //txtDebug.Text += i.ToString() + " " + grdFilteredHotels.Items[i].Cells[2].Text + "\n";
        // Create the query object.
        QueryByAttribute query = new QueryByAttribute();
        //query.ColumnSet = new AllColumns();
        //new_hotel nH = new new_hotel();
          
        ColumnSet hotelCols = new ColumnSet();
        hotelCols.Attributes = new string[] {"new_hotname", "new_hotstreet1", "new_nearmajorcityid", "new_localtel", 
                                             "new_email2", "new_numofrooms", "new_markettier", "new_airportcode", "new_airportdistance",
                                             "new_email","new_email2","new_web_username","new_web_password", "new_hotelid"};
  
          
        query.ColumnSet = hotelCols;
        query.EntityName = EntityName.new_hotel.ToString();
        query.Attributes = new string[] { "new_hotname" };
        //query.Values = new string[] { grdFilteredHotels.Items[i].Cells[2].Text };
        query.Values = new string[] { FilteredHotels[i].Hotel.Trim() };       
        // Execute the retrieval.
        BusinessEntityCollection retrieved = service.RetrieveMultiple(query);
  
        new_hotel theHotel = (new_hotel)retrieved.BusinessEntities[0];
  
        //set the Long List entity status code to P (2)
        for (int ii = 0; ii< alistLongList.Count; ii++)
        {
          new_longlist nLL = (new_longlist)alistLongList[ii];
          if (nLL.new_hotelid.Value == theHotel.new_hotelid.Value)
          {
            nLL.new_rfpstatus = new Picklist();
            nLL.new_rfpstatus.Value = 2;
            service.Update(nLL); 
          }
        }
        //txtDebug.Text += i.ToString() + ": " + grdFilteredHotels.Items[i].Cells[2].Text + " ID: " + theHotel.new_hotelid.Value.ToString() + "\n";
  
        //Create a new rfpSent object
        new_rfpsent rfpSent = new new_rfpsent();
          
        //Set the owner to the same owner as the Rfp
        rfpSent.ownerid = new Owner();
        rfpSent.ownerid.type = EntityName.systemuser.ToString();
        rfpSent.ownerid.Value = tR.ownerid.Value;
  
        //RfpPrgram IDs
        rfpSent.new_rfpregardingid = new Lookup();
        rfpSent.new_rfpregardingid.type = EntityName.new_hotel.ToString();
        rfpSent.new_rfpregardingid.Value = new Guid(theHotel.new_hotelid.Value.ToString());
  
        //rfpSent.new_name = item.Text.ToString();
        rfpSent.new_name = grdFilteredHotels.Items[i].Cells[2].Text;
  
        rfpSent.new_rfpsentid2 = new Lookup();
        rfpSent.new_rfpsentid2.type = EntityName.new_rfpprogram.ToString();
        rfpSent.new_rfpsentid2.Value = new Guid(lblRfpGuid.Text);
        //rfpSent.new_rfpsentid2.Value = new Guid(strRfpGuid);
  
        //Set bid code
        rfpSent.new_bidcode = lblBidCode.Text;
        ////Date
        rfpSent.new_datesent = new CrmDateTime();
        rfpSent.new_datesent.Value = DateTime.Now.ToShortDateString();
  
        //Set the Bid Status to Pending
        rfpSent.new_rfpstatus = new Picklist();
        rfpSent.new_rfpstatus.Value = 1;
  
        //Airport Name (text, not GUID)
        rfpSent.new_airportcode = lblAirlineCode.Text;
  
        // contactGuid is the GUID of the record being retrieved.
        //Guid hotelGuid = new Guid(strHotelGuid);
  
        // Retrieve the contact.
        // The EntityName indicates the EntityType of the object being retrieved.
        //new_hotel theHotel = (new_hotel)service.Retrieve(EntityName.new_hotel.ToString(), hotelGuid, new AllColumns());
  
        //Email to Director of Sales
        strEmail = "";
        if (theHotel.new_email2 != null)
        {
          strEmail = theHotel.new_email2;
          //txtDebug.Text += "strEmail: " + strEmail + "\n";
        }
        string strHotelName = theHotel.new_hotname;
        strHotelName = strHotelName.Replace(" ", "*");
        string strUrl = "http://crm:99/api/ApiPortal.aspx?RfpGuid=" + lblRfpGuid.Text + "&HotelGuid=" + theHotel.new_hotelid.Value.ToString() + "&HotelName=" + strHotelName + "&RfpName=" + lblBidCode.Text;
        rfpSent.new_rfpurl = strUrl;
  
        //string strUrl = "http://192.168.1.50:99/api/ApiPortal.aspx?RfpGuid=" + lblRfpGuid.Text + "&HotelGuid=" + theHotel.new_hotelid.Value.ToString() + "&HotelName=" + strHotelName + "&RfpName=" + lblBidCode.Text;
        if (strEmail != "")
        {
          //WhoAmIRequest userRequest = new WhoAmIRequest();
          //WhoAmIResponse user = (WhoAmIResponse)service.Execute(userRequest);
          //txtDebug.Text +=  "WhoAmIUser: " + user.UserId.ToString() + "\n";        
          //WhoAmIUser: 33a3db94-2d5c-de11-8fe7-0003fffef7a2
  
  
          //retrieve the RFP and the System User
          //ColumnSet rfpCols = new ColumnSet();
          //rfpCols.Attributes = new string[] { "new_emailtext", "ownerid" };
          //new_rfpprogram tR = (new_rfpprogram)service.Retrieve(EntityName.new_rfpprogram.ToString(), new Guid(lblRfpGuid.Text), rfpCols);
          //systemuser sU = (systemuser)service.Retrieve(EntityName.systemuser.ToString(), tR.ownerid.Value, new AllColumns());
  
          string strBody = tR.new_emailtext;
          strBody = strBody.Replace("http://www.api.com/", strUrl);
  
          //MailMessage message = new MailMessage("administrator@litwareinc.com", strEmail, "New RFP", strBody);
          //message.BodyEncoding = System.Text.Encoding.
  
          System.Web.Mail.MailMessage message = new System.Web.Mail.MailMessage();
          //System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
          if ( sU.internalemailaddress != null)
            message.From = sU.internalemailaddress.ToString();
          else
            message.From = "administrator@contoso.com";
            
          txtDebug.Text += "Email: " + message.From.ToString() + "\n";
          message.To = strEmail;
          //message.To.Add(new MailAddress(strEmail));
          message.Subject = "New RFP Request from API";
          message.Body = strBody;
          message.BodyFormat = MailFormat.Html;
          SmtpMail.SmtpServer = "crm-srv-01";
          //System.Net.Mail.SmtpClient smtp = new System.Net.Mail.SmtpClient();
          try
          {
            SmtpMail.Send(message);
            rfpSent.new_dosemailsent = "Sent to address: " + strEmail;
          }
          catch (Exception smEx)
          {
            rfpSent.new_mailresult = "Mail send failed with message: " + smEx.ToString();
          }
        }
        else
        {
          rfpSent.new_mailresult = "Mail send failed, no Director of Sales email for this hotel";
        }
        Label1.Text = "Emails sent!";
        cmdSendRFPs.Enabled = false;
        rfpSent.new_dosemailsent = strEmail;
  
        //Create the RFP Sent Record
        service.Create(rfpSent);
  
        if (theHotel.new_web_username == null || theHotel.new_web_password == null ||
            theHotel.new_web_username == "" || theHotel.new_web_password == "")
        {
          //txtDebug.Text += "\nNo username or password...creating\n";
          string strUsername = theHotel.new_hotname.Replace(" ", "");
          theHotel.new_web_username = strUsername;
  
          string strPassword = strUsername.Substring(0, 4);
          for (int zzz = 0; zzz < 4; zzz++)
            strPassword += RandomClass.Next(0, 10);
  
          theHotel.new_web_password = strPassword;
          service.Update(theHotel);
        }
      }
    }
    catch (System.Web.Services.Protocols.SoapException soapEx)
    {
      txtDebug.Text += "SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString();
    }
    catch (Exception ex)
    {
      txtDebug.Text += "Exception: " + ex.ToString();
    }
    finally
    {
      this.Form.Dispose();
      HttpContext.Current.Session.Abandon();
      ClientScript.RegisterStartupScript(GetType(), "close", "window.close();", true);
    }
  }
  
  //===============================================================================================
  //===============================================================================================
  //alistRfpHotels.Add(alistHotelIdsCityMatches[i].ToString());
  //alistRfpHotelNames.Add(theHotel.HotelName);
  protected void cmdSendRFPs_Click(object sender, ImageClickEventArgs e)
  {
    sendRFPs(alistRfpHotels, alistRfpHotelNames, alistHotelNamesCityMatches);
    //sw1.Close();
  }
  
}
  
  
  
/*
  //===============================================================================================
  //===============================================================================================
  protected void getCitiesAndAirportCodes()
  {
    try
    {
      strUniqueName = WebConfigurationManager.AppSettings["UniqueName"].ToString();
      strOrgName = WebConfigurationManager.AppSettings["OrgName"].ToString();
      strServerName = WebConfigurationManager.AppSettings["ServerName"].ToString();
  
      //Initialize CRM web services============
      CrmAuthenticationToken token = new CrmAuthenticationToken();
      token.AuthenticationType = 0;
      token.OrganizationName = "AccommodationsPlusInternationa";
  
      CrmService service = new CrmService();
      service.Url = "http://" + strServerName + "/mscrmservices/2007/crmservice.asmx?WSDL&uniquename=" + strUniqueName;
      service.CrmAuthenticationTokenValue = token;
      service.Credentials = System.Net.CredentialCache.DefaultCredentials;
      //End Initialize CRM web services========
  
      //Get Cities and IDs
      QueryExpression queryPrincipal = new QueryExpression();
      queryPrincipal.EntityName = EntityName.new_city.ToString();
      queryPrincipal.ColumnSet = new AllColumns();
  
  
      BusinessEntityCollection myCities = service.RetrieveMultiple(queryPrincipal);
      foreach (BusinessEntity myCity in myCities.BusinessEntities)
      {
        new_city C = (new_city)myCity;
        alistAllCities.Add(C.new_name);
        alistAllCitiesIds.Add(C.new_cityid.Value.ToString());
      }
  
      //Get Airport Codes and IDs
      queryPrincipal = new QueryExpression();
      queryPrincipal.EntityName = EntityName.new_airportdestination.ToString();
      queryPrincipal.ColumnSet = new AllColumns();
      BusinessEntityCollection myAirCodes = service.RetrieveMultiple(queryPrincipal);
      foreach (BusinessEntity myAirCode in myAirCodes.BusinessEntities)
      {
        new_airportdestination AD = (new_airportdestination)myAirCode;
        alistAirportCodes.Add(AD.new_airportcode);
        alistAllCitiesIds.Add(AD.new_airportdestinationid.Value.ToString());
      }
    }
    catch (System.Web.Services.Protocols.SoapException soapEx)
    {
      //txtDebug.Text += "SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString();
      //sw1.WriteLine( "SOAP exception: " + soapEx.Detail.InnerText + "  " + soapEx.ToString() );
    }
    catch (Exception ex)
    {
      //txtDebug.Text += "Exception: " + ex.ToString();
      //sw1.WriteLine("Exception: " + ex.ToString() );
    }
  }
*/

HI:

I ahve attached the files here, just rename "afgrids.png" to "afgrids.aspx" and rename afgrids.aspx.png" to "afgrids.aspx.cs". Please note that the methods that build the data tables use Queries that are built at run-time by user-selections, and retrieve the data from Dynamcis CRM so they are a bit long...

John.
0
Tsvetoslav
Telerik team
answered on 13 Aug 2010, 07:23 AM
Hi John,

The only place that should be reworked is the SortCommand where you need to cancel the event and call the grids' Rebind() (not DataBind() ) method. Other than that I could not spot any reason for the described issue although I suspect that it is due to a broken html which leads to the grid's scripts not being loaded correctly. Please, open up a formal support ticket, prepare a small test project where the problem can be observed (you should pass to the grid some dummy data instead of the one returned by the queries to the Dynamics CRM) and send it to us. We shall debug it and help you trace down the cause for the described behavior. Thanks in advance.

Regards,
Tsvetoslav
the Telerik team
Do you want to have your say when we set our development plans? Do you want to know when a feature you care about is added or when a bug fixed? Explore the Telerik Public Issue Tracking system and vote to affect the priority of the items
Tags
Grid
Asked by
John
Top achievements
Rank 1
Answers by
Tsvetoslav
Telerik team
John
Top achievements
Rank 1
Share this question
or