/// <summary>
    /// this code is used with LinqServerModeDataSource_Selecting so we can run in server mode
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinqServerModePodTop_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e)
    {
        try
        {
            Int32 _companyid = -1; //after testing default to empty string 
            Int32 _userid = -1;

            //company id: always add as a search param as user must be logged in
            //if (Page.Session["user"] != null)
            if (Page.Session["user"] != null)
            {
                _companyid = (Int32)((UserClass)Page.Session["user"]).CompanyId;
                _userid = (Int32)((UserClass)Page.Session["user"]).UserId;
            }

            //020513 search over last 12 months
            int _months = 12;
            DateTime _minDate = DateTime.Now.AddMonths(0 - _months);

            //dynamic queries using system.Linq.dynamic + Dynamic.cs library
            //20/10/2010 we have build a unique index (OrderIx) from OrderId, TitleId, ContainerSubId as usual primary keys are not going to 
            //be unique in the view. aspxgrid only works properly when it has a unique key 
            e.KeyExpression = "OrderIx"; //"OrderID"; //a key expression is required 
            if (_companyid > 0 && _userid > 0)
            {
                //020513 get from date range startdate + N months
                //var _nquery = new linq_classesDataContext().view_orders.Where(c => c.CompanyID == _companyid && c.ContactID == _userid).OrderByDescending(c => c.OrderID).Take(10); //c => c.CompanyID == 7
                var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).Where(c => c.CompanyID == _companyid && c.ContactID == _userid).OrderByDescending(c => c.OrderID).Take(10);

                e.QueryableSource = _nquery;
                //Int32 _count = _nquery.Count();

            }
            else if (_companyid == -1 && _userid > 0)  //internal user 
            {
                //var _nquery = new linq_classesDataContext().view_orders.OrderByDescending(c => c.OrderID).Take(10); //c => c.CompanyID == 7
                var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).OrderByDescending(c => c.OrderID).Take(10);
                //_count = _nquery.Count();

                e.QueryableSource = _nquery;
            }
            else //they should never reach this as must be logged in to get dashboard but just a precaution
            {
                //var _nquery = new linq_classesDataContext().view_orders.OrderBy("OrderID").OrderByDescending(c => c.OrderID).Take(10);
                var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).OrderBy("OrderID").OrderByDescending(c => c.OrderID).Take(10);
                //_count = _nquery.Count();

                e.QueryableSource = _nquery;
            }
        }
        catch (Exception ex)
        {
            this.dxlblerr4.Text = ex.Message.ToString();
            this.dxlblerr4.Visible = true;
        }

    }
    /// <summary>
    /// this code is used with LinqServerModeDataSource_Selecting so we can run in server mode
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinqServerModeOrders_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e)
    {

        ParameterCollection _params = new ParameterCollection();
        SessionParameterPasser _sessionWrapper = new SessionParameterPasser();
        Int32 _companyid = -1; //after testing default to empty string 
        string _countries = "";
        //check if session created from advanced search, in which case we can use the parameters passed back
        string _query = "";
        string _name = "";
        string _mode = "";

        if (_sessionWrapper["mode"] != null) //this is only usually set when we pass it back from history search or logout
        {
            _mode = (string)_sessionWrapper["mode"];
            _sessionWrapper["mode"] = null;
        }
        else
        {
            _mode = this.dxhfMethod.Contains("mode") ? this.dxhfMethod["mode"].ToString() : "0"; //this.dxhfQuery["method"].ToString();
        }

        //mode 0=history, 1=basic search so rebuild filter, 2=advanced search, 3=user status report
        if (_mode == "0")
        {
            if (_sessionWrapper["query"] != null && _sessionWrapper["name"] != null)
            {
                _query = _sessionWrapper["query"].ToString();
                _name = _sessionWrapper["name"].ToString();
            }
        }
        else if (_mode == "1")
        {
            _query = get_filter();
            _name = get_name();
        }
        else if (_mode == "2")
        {
            if (_sessionWrapper["query"] != null && _sessionWrapper["name"] != null)
            {
                _query = _sessionWrapper["query"].ToString();
                _name = _sessionWrapper["name"].ToString();
            }
        }
        else if (_mode == "3")
        {
            //ASPxComboBox _cbo = (ASPxComboBox)this.FindControl("dxcboclosedyn");
            //if (_cbo!= null) {
            //    _cbo.SelectedItem = _cbo.Items.FindByValue(false); 
            //}

            _params.Add("JobClosed", wwi_func.vbool("0").ToString());
            _name += " job status equals Active jobs";  
        }

        //company id: always add as a search param if user is logged in
        //if (Page.Session["user"] != null)
        //company id: always add as a search param if user is logged in UNLESS _mode = -1 which we can use to bypass params
        if (Page.Session["user"] != null)
        {
            bool _usedefaultid = false;

            if (_mode != "-1" && _mode != "0")
            {
                _companyid = (Int32)((UserClass)Page.Session["user"]).CompanyId;

                //***************
                //added for MacMillan filtering
                string _contactid = ((UserClass)Page.Session["user"]).UserId.ToString();
                //09.04.2015 Paul Edwards check which clients are are visible for this company
                IList<string> _clientids = null;
                _clientids = wwi_func.array_from_xml("xml\\contact_iso.xml", "contactlist/contact[id='" + _contactid + "']/clientids/clientid/value");
                if (_clientids.Count > 0)
                {
                    //don't use sql IN(n) as linq won't parse the statement
                    string _clients = "(CompanyID ==" + string.Join(" OR CompanyID ==", _clientids.Select(i => i.ToString()).ToArray()) + ")";
                    _params.Add("NULL", _clients);

                }
                //21.10.2014 Paul Edwards for delivery tracking check which DeliveryID's are visible for this company
                //check individual contact ID iso 
                IList<string> _deliveryids = null;
                _deliveryids = wwi_func.array_from_xml("xml\\contact_iso.xml", "contactlist/contact[id='" + _contactid + "']/deliveryids/deliveryid/value");
                if (_deliveryids.Count > 0)
                {
                    //don't use sql IN(n) as linq won't parse the statement
                    string _deliveries = "(DeliveryAddress==" + string.Join(" OR DeliveryAddress==", _deliveryids.Select(i => i.ToString()).ToArray()) + ")";
                    _params.Add("NULL", _deliveries); //select for this company off list

                }
                else
                {
                    if (_companyid == -1)
                    {
                        //***************
                        //if internal user check for a selected company
                        //if external user but they have access to company drop down check for selected company and if restricted to particular countries for selected companyID
                        //else return default
                        if (!string.IsNullOrEmpty((string)this.dxcbocompany.Value))
                        {
                            _params.Add("CompanyID", this.dxcbocompany.Value.ToString());
                            _name += this.dxcbocompany.Text.ToString() != "" ? ", company name equals " + this.dxcbocompany.Text.ToString() : "";
                        }
                    }
                    else if (_companyid > 0 && this.dxcbocompany.Enabled)
                    {
                        if (!string.IsNullOrEmpty((string)this.dxcbocompany.Value))
                        {
                            IList<string> _args = null;

                            //check for additional country restrictions e.g. EDC can see usborne shipments but ONLY to the US
                            _args = wwi_func.array_from_xml("xml\\company_iso.xml", "companylist/company[id='" + _companyid + "']/visibleitems/item[itemid='" + this.dxcbocompany.Value.ToString() + "']/destinationid");
                            if (_args.Count > 0)
                            {
                                //don't use sql IN(n) as linq won't parse the statement
                                _countries = "(CountryID==" + string.Join(" OR CountryID==", _args.Select(i => i.ToString()).ToArray()) + ")";
                                _params.Add("CompanyID", this.dxcbocompany.Value.ToString() + " AND " + _countries); //select for this company off list
                            }
                            else
                            {
                                _params.Add("CompanyID", this.dxcbocompany.Value.ToString());
                            }

                            //050613 only check as consignee if xml item does not contain 'companyonly' = -1 tag
                            _args = wwi_func.array_from_xml("xml\\company_iso.xml", "companylist/company[id='" + _companyid + "']/visibleitems/item[itemid='" + this.dxcbocompany.Value.ToString() + "']/companyonly");
                            if (_args.Count == 0)
                            {
                                //if company id and selected company are the same do an OR operand e.g. companyid =1 OR consignee = 1
                                //otherwise use AND e.g. consignee = 1 AND companyid = 234 
                                if (_companyid.ToString() == (string)this.dxcbocompany.Value)
                                {
                                    _params.Add("ConsigneeID_OR", _companyid.ToString()); //select for this user's company
                                }
                                else
                                {
                                    _params.Add("ConsigneeID_AND", _companyid.ToString()); //select for this user's company
                                }
                            }
                        }
                        else
                        {
                            _usedefaultid = true;

                        }
                    }
                    else
                    {
                        _usedefaultid = true;
                    }
                }
            }
            else
            {
                _usedefaultid = true;
            }
            
            //default company filter 
            if (_usedefaultid)
            {
                Parameter _p = return_default_view(-1);
                if (_p != null) { _params.Add(_p); }
            }
        }
        //check for additional parameters if query is not from history (mode=0)
        //but you can only apply these filters when a) user is logged in or b) a query parameter has been entered
        //otherwise you could create a default query of e.g. (Jobclosed==false) which would return ALL closed jobs in database
        //if ((_mode != "0") && (_query !="" | _companyid !=-1))
        //
        if ((_mode != "0" & _mode != "1") && (_query != "" || _params.Count > 0))
        {
            //28/08/2010 users can filter by individual contacts within the company
            //if its an employee we need to check
            //((OrderControllerID=={cboname.Value}) or (OperationsControllerID=={cboname.Value})) or
            //(OriginPortControllerID=={cboname.Value}) or (DestinationPortControllerID=={cboname.Value})) !!!
            //19/10/2010 only use contact id is user is not doing their own status report
            //if (_mode != "3" && this.cboName.Value != null)
            if (this.cboName.Value != null)
            {
                //11/03/2011 (All users) option added value = -1 use companyid to pull out all records for company instead of individual user
                //so we don't need to do anyhing as companyid has been parametised above
                if (!String.IsNullOrEmpty(this.cboName.Value.ToString()) && this.cboName.Value.ToString() != "-1")
                {
                    _params.Add("ContactID", this.cboName.Value.ToString());
                    _name += ", user name equals " + this.cboName.Text.ToString(); 
                }

            }

            //15/09/2010 include closed jobs y/n when combo = Active jobs (jobclosed = 1) or combo = closed jobs (jobclosed = 0)
            //when combo = All jobs we can ignore this filter
            if (this.dxcboclosedyn.Value != null)
            {
                _params.Add("JobClosed", Convert.ToBoolean(this.dxcboclosedyn.Value).ToString());
                _name += ", job status equals " + this.dxcboclosedyn.Text.ToString().Replace("Search", "");  
                
            }

        }


        //now rebuild query with additional parameters
        string _f = "";
        if (_params.Count > 0)
        {
            foreach (Parameter p in _params)
            {
                string _pname = p.Name.ToString();
                string _op = "AND";
                string[] _check = _pname.Split("_".ToCharArray());
                _pname = _check[0].ToString();
                _op = _check.Length > 1 ? _check[1].ToString() : _op;

                string _a = _f != "" ? " " + _op + " " : "";
                //_f += _a + "(" + _pname + "==" + p.DefaultValue.ToString() + ")";
                _f += _pname != "NULL" ? _a + "(" + _pname + "==" + p.DefaultValue.ToString() + ")" : _a + "(" + p.DefaultValue.ToString() + ")";


            }

            if (_query != "") { _query = _f + " AND " + _query; } else { _query = _f; }
        }


        //deprecated 100113 added during company check
        //add country restrictions
        //if (_countries != "") { _query += " AND (" + _countries + ")"; }
        //finally if there's no query string check filter expression and force search, otherwise the default search is to display no records. this is only a problem for publiship 
        //users as everyone else will at least have the company filter
        if (_query == "")
        {
            if (this.gridOrder.FilterExpression.ToString() != "")
            {
                _query = "OrderNumber > -1";
            }
        } 
        //19/04/2013 re-designed query means we can use subdeliveryid as key NO IT DOESN'T back to OrderIx
        //dynamic queries using system.Linq.dynamic + Dynamic.cs library
        //20/10/2010 we have build a unqiue index (OrderIx) from OrderId, TitleId, ContainerSubId as usual primary keys are not going to 
        //be unique in the view. aspxgrid only works properly when it has a unique key 

        //important! need a key id or error=key expression is undefined
        e.KeyExpression = "OrderIx";//"SubDeliveryID"; //"OrderIx"; //"OrderID"; //a key expression is required 

        if (!string.IsNullOrEmpty(_query))
        {
            //get start date from dll value
            //e.g if search is for last 12 months dllvalue 1 start date = current date - (1 * 12) months
            //if search is for 2-3 years dllvalue 3 start date = current date - (3 * 12) months
            int _dllvalue = this.dxcboMonths.Value != null ? wwi_func.vint(this.dxcboMonths.Value.ToString()) : 1;
            //number of months to include after start date
            int _months = 12;
            //multiply base * 12 to get start date
            int _lowest = 0 - (_dllvalue * 12);
            DateTime _minDate = DateTime.Now.AddMonths(_lowest);
            //var _query = new linq_classesDataContext().view_orders.Where(_filter);
            //290413 using new userdefined inline table function so we can parametise with month range from current date
            //var _nquery = new linq_view_orders_udfDataContext().view_orders_by_age(1, 12).Where(_query); //c => c.CompanyID == 7
            //get from date range startdate + N months
            var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).Where(_query); //c => c.CompanyID == 7
            e.QueryableSource = _nquery;
                        
            //Int32 _count = _nquery.Count();

            if (!String.IsNullOrEmpty(_name)) { append_to_query_log(_query, _name);
            this.gridOrder.SettingsText.Title = "Search results: " + _name;
            }
        }
        else //default to display nothing in grid 
        {
            //var _nquery = new linq_classesDataContext().view_order_2s.Where(c => c.OrderNumber == -1);
            var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(DateTime.Now, 0).Where(c => c.OrderNumber == -1) ; //c => c.CompanyID == 7
            //_count = _nquery.Count();

            e.QueryableSource = _nquery;
        }
    }
    /// <summary>
    /// DEPRECATED databinding using LINQ but this does not run in server mode!
    /// </summary>
    protected void bind_linq_datasource_non_server_mode()
    {
        string _filter = "OrderNumber = -1";
        string _companyid = "";
        
        //_companyid = "-1";
        //if (Page.Session["user"] != null)
        //{
        //    _companyid = ((UserClass)Page.Session["user"]).CompanyId.ToString();
        // 
        //}
        //_filter = " CompanyID = " + _companyid;

        if (Session["filter"] != null)
        {
            string _f = (string)Session["filter"];
            if (_companyid != string.Empty) { _filter += " AND " + _f; } else { _filter = _f; }
        }
               
        
        //dynamic queries using system.Linq.dynamic + Dynamic.cs library
        if (_filter != "")
        {
            int _dllvalue = this.dxcboMonths.Value != null ? wwi_func.vint(this.dxcboMonths.Value.ToString()) : 1;
            //number of months to include after start date
            int _months = 12;
            //multiply base * 12 to get start date
            int _lowest = 0 - (_dllvalue * 12);
            DateTime _minDate = DateTime.Now.AddMonths(_lowest);
            //get from date range startdate + N months
            //var _query = new linq_classesDataContext().view_orders.Where(_filter, System.StringComparison.InvariantCultureIgnoreCase);
            var _query = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).Where(_filter); 
            
            this.gridOrder.DataSource = _query;
        }
        else
        {
            //var _query = new linq_classesDataContext().view_orders;
            var _query = new linq.linq_view_orders_udfDataContext().view_orders_by_age(DateTime.Now, 0); 
            this.gridOrder.DataSource = _query;
        }

        this.gridOrder.DataBind();
    }
    //end load

    #region grid databinding
    /// <summary>
    /// this code is used with LinqServerModeDataSource_Selecting so we can run in server mode
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinqServerModePod_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e)
    {

        Int32 _companyid = -1; //after testing default to empty string 
        SessionParameterPasser _sessionWrapper = new SessionParameterPasser();
        ParameterCollection _params = new ParameterCollection();
        //check if session created from advanced search, in which case we can use the parameters passed back
        string _query = "";
        int _mode = this.dxhfsource.Contains("mode") ? wwi_func.vint(this.dxhfsource["mode"].ToString()) : 1; //default mode to quick search

        //a simplified version of the methods used in order tracking - no history but advanced search is available
        if (_sessionWrapper["query"] != null && _mode == 2)
        {
            _query = _sessionWrapper["query"].ToString();
        }
        else
        {
            _query = get_filter();
        }
        //company id: always add as a search param if user is logged in
        //if (Page.Session["user"] != null)
        //company id: always add as a search param if user is logged in UNLESS _mode = -1 which we can use to bypass params
        if (Page.Session["user"] != null)
        {
            _companyid = (Int32)((UserClass)Page.Session["user"]).CompanyId;

            if (_companyid != -1) //-1 is a WWI company
            {
                Parameter _p = return_default_view(-1);
                if (_p != null) { _params.Add(_p); }
            }

        }

        //now rebuild query with additional parameters
        string _f = "";
        if (_params.Count > 0)
        {
            foreach (Parameter p in _params)
            {
                string _a = _f != "" ? " AND " : "";
                _f += _a + "(" + p.Name.ToString() + "==" + p.DefaultValue.ToString() + ")";
            }

            if (_query != "") { _query = _f + " AND " + _query; } else { _query = _f; }
        }

        //get start date from dll value
        //e.g if search is for last 12 months dllvalue 1 start date = current date - (1 * 12) months
        //if search is for 2-3 years dllvalue 3 start date = current date - (3 * 12) months
        int _dllvalue = this.dxcboRange.Value != null ? wwi_func.vint(this.dxcboRange.Value.ToString()) : 1;
        //number of months to include after start date
        int _months = 12;
        //multiply base * 12 to get start date
        int _lowest = 0 - (_dllvalue * 12);
        DateTime _minDate = DateTime.Now.AddMonths(_lowest);

        //dynamic queries using system.Linq.dynamic + Dynamic.cs library
        //20/10/2010 we have build a unqiue index (OrderIx) from OrderId, TitleId, ContainerSubId as usual primary keys are not going to 
        //be unique in the view. aspxgrid only works properly when it has a unique key 
        e.KeyExpression = "OrderIx"; //"OrderID"; //a key expression is required 

        if (!string.IsNullOrEmpty(_query))
        {
            //var _nquery = new linq_classesDataContext().view_orders.Where(_query); //c => c.CompanyID == 7
            var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).Where(_query); //c => c.CompanyID == 7
            e.QueryableSource = _nquery;
            //Int32 _count = _nquery.Count();

        }
        else //default to display nothing in grid 
        {
            //var _nquery = new linq_classesDataContext().view_orders.Where(c => c.OrderNumber == -1);
            var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).Where(c => c.OrderNumber == -1);
            //_count = _nquery.Count();

            e.QueryableSource = _nquery;
        }
    }
    /// <summary>
    /// this code is used with LinqServerModeDataSource_Selecting so we can run in server mode
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    protected void LinqServerModeOrders_Selecting(object sender, DevExpress.Data.Linq.LinqServerModeDataSourceSelectEventArgs e)
    {

        ParameterCollection _params = new ParameterCollection();
        SessionParameterPasser _sessionWrapper = new SessionParameterPasser();
        Int32 _companyid = -1; //after testing default to empty string 

        //check if session created from advanced search, in which case we can use the parameters passed back
        string _query = "";
        string _name = "";
        string _mode = "";

        if (_sessionWrapper["mode"] != null) //this is only usually set when we pass it back from history search or logout
        {
            _mode = (string)_sessionWrapper["mode"];
            _sessionWrapper["mode"] = null;
        }
        else
        {
            _mode = this.dxhfMethod.Contains("mode") ? this.dxhfMethod["mode"].ToString() : "0"; //this.dxhfQuery["method"].ToString();
        }

        //mode 0=history, 1=basic search so rebuild filter, 2=advanced search, 3=user status report
        if (_mode == "0")
        {
            if (_sessionWrapper["query"] != null && _sessionWrapper["name"] != null)
            {
                _query = _sessionWrapper["query"].ToString();
                _name = _sessionWrapper["name"].ToString();
            }
        }
        else if (_mode == "1")
        {
            _query = get_filter();
            _name = get_name();
        }
        else if (_mode == "2")
        {
            if (_sessionWrapper["query"] != null && _sessionWrapper["name"] != null)
            {
                _query = _sessionWrapper["query"].ToString();
                _name = _sessionWrapper["name"].ToString();
            }
        }

        //company id: always add as a search param if user is logged in
        //if (Page.Session["user"] != null)
        //company id: always add as a search param if user is logged in UNLESS _mode = -1 which we can use to bypass params
        if (Page.Session["user"] != null && _mode != "-1" && _mode != "0")
        {
            _companyid = (Int32)((UserClass)Page.Session["user"]).CompanyId;

            if (_companyid != -1) //-1 is a WWI company
            {
                Parameter _p = return_default_view(-1);
                if (_p != null) { _params.Add(_p); }
            }

            //11/03/2011 this is done below!
            //19/10/2010 if mode=3 add contact id/employee as param
            //if (_mode == "3")
            //{
            //    if (_companyid != -1) //-1 = ~WWI employee so need to use employee id
            //    {
            //        Parameter _p = return_default_view(1);
            //        if (_p != null) { _params.Add(_p); }
            //    }
            //    else
            //    {
            //        Parameter _p = return_default_view(3);
            //        if (_p != null) { _params.Add(_p); }
            //    }
            //    //for status report just show active jobs? or use combo below
            //    //_params.Add("JobClosed", Convert.ToBoolean("false").ToString());
            //} 
        }

        //check for additional parameters if query is not from history (mode=0)
        //but you can only apply these filters when a) user is logged in or b) a query parameter has been entered
        //otherwise you could create a default query of e.g. (Jobclosed==false) which would return ALL closed jobs in database
        //if ((_mode != "0") && (_query !="" | _companyid !=-1))
        //
        if ((_mode != "0" && _mode != "1") && (_query != "" || _params.Count > 0))
        {
            //28/08/2010 users can filter by individual contacts within the company
            //if its an employee we need to check
            //((OrderControllerID=={cboname.Value}) or (OperationsControllerID=={cboname.Value})) or
            //(OriginPortControllerID=={cboname.Value}) or (DestinationPortControllerID=={cboname.Value})) !!!
            //19/10/2010 only use contact id is user is not doing their own status report
            //if (_mode != "3" && this.cboName.Value != null)
            if (this.cboName.Value != null)
            {
                //11/03/2011 (All users) option added value = -1 use companyid to pull out all records for company instead of individual user
                //so we don't need to do anyhing as companyid has been parametised above
                if (!String.IsNullOrEmpty(this.cboName.Value.ToString()) && this.cboName.Value.ToString() != "-1")
                {
                    _params.Add("ContactID", this.cboName.Value.ToString());
                }

            }

            //15/09/2010 include closed jobs y/n when combo = Active jobs (jobclosed = 1) or combo = closed jobs (jobclosed = 0)
            //when combo = All jobs we can ignore this filter
            if (this.dxcboclosedyn.Value != null)
            {
                _params.Add("JobClosed", Convert.ToBoolean(this.dxcboclosedyn.Value).ToString());

            }
        }

        //additional filtering options e.g. today's updates
        if(this.dxhfMethod.Contains("hfparam"))
        {
            string _hfparam = this.dxhfMethod.Get("hfparam").ToString();

            switch (_hfparam)
            {
                case "today": {
                    _params.Add("dtupdated.Value.Date", "DateTime.Parse(\"" + DateTime.Today.ToShortDateString() + "\")");  
                    break;
                }
                default: {
                    break;
                }
            }

            this.dxhfMethod.Remove("hfparam"); 
        }

        //now build query with additional parameters
        string _f = "";
        if (_params.Count > 0)
        {
            foreach (Parameter p in _params)
            {
                string _a = _f != "" ? " AND " : "";
                _f += _a + "(" + p.Name.ToString() + "==" + p.DefaultValue.ToString() + ")";
            }

            if (_query != "") { _query = _f + " AND " + _query; } else { _query = _f; }
        }

        //get start date from dll value
        //e.g if search is for last 12 months dllvalue 1 start date = current date - (1 * 12) months
        //if search is for 2-3 years dllvalue 3 start date = current date - (3 * 12) months
        int _dllvalue = this.dxcboRange.Value != null ? wwi_func.vint(this.dxcboRange.Value.ToString()) : 1;
        //number of months to include after start date
        int _months = 12;
        //multiply base * 12 to get start date
        int _lowest = 0 - (_dllvalue * 12);
        DateTime _minDate = DateTime.Now.AddMonths(_lowest);

        //dynamic queries using system.Linq.dynamic + Dynamic.cs library
        //20/10/2010 we have build a unqiue index (OrderIx) from OrderId, TitleId, ContainerSubId as usual primary keys are not going to 
        //be unique in the view. aspxgrid only works properly when it has a unique key 
        e.KeyExpression = "OrderIx"; //"OrderID"; //a key expression is required 

        if (!string.IsNullOrEmpty(_query))
        {
            //var _nquery = new linq_classesDataContext().view_orders.Where(_query); //c => c.CompanyID == 7
            var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(_minDate, _months).Where(_query); //c => c.CompanyID == 7
            e.QueryableSource = _nquery;
            //Int32 _count = _nquery.Count();

            if (!String.IsNullOrEmpty(_name)) { append_to_query_log(_query, _name); }
        }
        else //default to display nothing in grid 
        {
            //var _nquery = new linq_classesDataContext().view_orders.Where(c => c.OrderNumber == -1);
            var _nquery = new linq.linq_view_orders_udfDataContext().view_orders_by_age(DateTime.Now, 0).Where(c => c.OrderNumber == -1) ;
            //_count = _nquery.Count();
            e.QueryableSource = _nquery;
        }
    }
    /// <summary>
    /// DEPRECATED databinding using LINQ but this does not run in server mode!
    /// </summary>
    protected void bind_linq_datasource_non_server_mode()
    {
        string _filter = "OrderNumber = -1";
        string _companyid = "";
        
        //_companyid = "-1";
        //if (Page.Session["user"] != null)
        //{
        //    _companyid = ((UserClass)Page.Session["user"]).CompanyId.ToString();
        // 
        //}
        //_filter = " CompanyID = " + _companyid;

        if (Session["filter"] != null)
        {
            string _f = (string)Session["filter"];
            if (_companyid != string.Empty) { _filter += " AND " + _f; } else { _filter = _f; }
        }
               
        
        //dynamic queries using system.Linq.dynamic + Dynamic.cs library
        if (_filter != "")
        {
            //var _query = new linq_classesDataContext().view_orders.Where(_filter, System.StringComparison.InvariantCultureIgnoreCase);
            var _query = new linq.linq_view_orders_udfDataContext().view_orders_by_age(DateTime.Now, 0).Where(_filter); 
            this.gridOrder.DataSource = _query;
        }
        else
        {
            //var _query = new linq_classesDataContext().view_orders;
            var _query = new linq.linq_view_orders_udfDataContext().view_orders_by_age(DateTime.Now, 0);
            this.gridOrder.DataSource = _query;
        }

        this.gridOrder.DataBind();
    }
    /// <summary>
    /// DEPRECATED databinding using LINQ but this does not run in server mode!
    /// </summary>
    protected void bind_linq_datasource_non_server_mode()
    {
        string _filter = "OrderNumber = -1";
        string _companyid = "";
        
        //_companyid = "-1";
        //if (Page.Session["user"] != null)
        //{
        //    _companyid = ((UserClass)Page.Session["user"]).CompanyId.ToString();
        // 
        //}
        //_filter = " CompanyID = " + _companyid;

        if (Session["filter"] != null)
        {
            string _f = (string)Session["filter"];
            if (_companyid != string.Empty) { _filter += " AND " + _f; } else { _filter = _f; }
        }
             
        
        //dynamic queries using system.Linq.dynamic + Dynamic.cs library
        if (_filter != "")
        {
            //290413 using new usedefined inline table function so we can parametise with month range
            //for anon view default to last 12 months only
            //var _query = new linq_classesDataContext().view_order_2s.Where(_filter, System.StringComparison.InvariantCultureIgnoreCase);
            var _query = new linq.linq_view_orders_udfDataContext().view_orders_by_age(DateTime.Now, 0).Where(_filter, System.StringComparison.InvariantCultureIgnoreCase); //c => c.CompanyID == 7
            this.gridOrder.DataSource = _query;
        }
        else
        {
            // var _query = new linq_classesDataContext().view_order_2s;
            var _query = new linq.linq_view_orders_udfDataContext().view_orders_by_age(DateTime.Now, 0).Where(c => c.OrderNumber == -1); //c => c.CompanyID == 7
            this.gridOrder.DataSource = _query;
        }

        this.gridOrder.DataBind();
    }