none
Getting default behavior using queries with AutoExecute = false

    Question

  • There have been several posts about this the last one was here.

    I have after some late night studying have come up with a work around.  I consider it to be a bit out of the MVVM pattern but it gets the job done.  This all revolves around a bug which I think will be fixed soon as it doesn't seem that hard. 

    Here we go:)

    The following code snippet is all of the required code per form to be able to do this.  You will need to add a reference to System.Windows.Controls.Data to your client project. 

    The code snippet is set up for a search form based on the AdventureWorks LT R2 database but you could easily adapt this to your form.

    I have totally commented the code and you should be able to follow this. 

    By the way if this is too much trouble I have created a couple of controls which I have put in my Commands extension suite for sale here so that it is just drag and drop onto a screen and you are good to go. The only code you have to write is the call to load the query in a method created by the control.

     

        public partial class SearchCustomers
        {
            TextBox lastNameTextBox;
            DataGrid customersDataGrid;
            DispatcherTimer timer = new DispatcherTimer() { Interval = new TimeSpan(0, 0, 0, 0, 500) };
    
            partial void SearchCustomers_Created()
            {
                //get the controls you want to work with.
                this.FindControl("LastNameParameter").ControlAvailable += new EventHandler<ControlAvailableEventArgs>(SearchCustomers_ControlAvailable);
                this.FindControl("CustomerGrid").ControlAvailable +=new EventHandler<ControlAvailableEventArgs>(SearchCustomers_ControlAvailable);
            }
    
            void timer_Tick(object sender, EventArgs e)
            {
                Customers.Load();
                timer.Stop();
            }
    
            void SearchCustomers_ControlAvailable(object sender, ControlAvailableEventArgs e)
            {
                if (e.Control is TextBox)
                {//Get the text box control and get a key up so that you can run the query on enter of a text box.
                    lastNameTextBox = e.Control as TextBox;
                    lastNameTextBox.KeyUp += new System.Windows.Input.KeyEventHandler(lastNameTextBox_KeyUp);
                }
                else if (e.Control is DataGrid)
                {//Get the datagrid you want to sort and page
                    customersDataGrid = e.Control as DataGrid;
                    //get the mouse down button to execute the query after the click of a header.
                    //the reason this works is that the datagrid still sets the sort order of a column but the query is not rerun so we will do it.
                    customersDataGrid.MouseLeftButtonDown += new System.Windows.Input.MouseButtonEventHandler(customersDataGrid_MouseLeftButtonDown);
                    //get the items source as an IPagedCollectionView so that you can execute the query after the page changed.
                    //the reason this works is that the datagrid still sets the current page but the query is not rerun so we will do it.
                    (customersDataGrid.ItemsSource as IPagedCollectionView).PageChanged += new EventHandler<EventArgs>(SearchCustomers_PageChanged);
                }
            }
    
            void SearchCustomers_PageChanged(object sender, EventArgs e)
            {
                //this may be overkill but I remove an event for this dispatcher then create a new one then start the timer.
                //it seems to work better if we wait a bit to run the query in order to let the datagrid finish setting what ever it needs to then execute the query
                Dispatchers.Main.Invoke(() => { timer.Tick -= timer_Tick; timer.Tick += new EventHandler(timer_Tick); timer.Start(); });
            }
    
            void customersDataGrid_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e)
            {
                //get the current ui element receiving the click
                UIElement oUIElement = sender as UIElement;
    
                //get a point relative the the RootVisual.
                Point pt = e.GetPosition(null);
    
                //Get a list of UIElements which are contained in the host ui element.
                var oUIClickedElementList = VisualTreeHelper.FindElementsInHostCoordinates(pt, oUIElement);
    
                //*****Get the colHeaderPresenter *******  if you ever need to get the datagrid column itself you can get that by getting the DataGridColumnHeadersPresenter then get the index of the columnHeader from the
                //DataGridColumnHeadersPresenter's children.  The index will give you the column index you can use the DataGrid.Columns[columnIndex] to get the actual DataGridColumn
                //This is not necessary here I just thought I would pass it along.
                DataGridColumnHeadersPresenter colHeaderPresenter = oUIClickedElementList.Where(element => element.GetType().Equals(typeof(DataGridColumnHeadersPresenter))).FirstOrDefault() as DataGridColumnHeadersPresenter;
    
                //Get the column header clicked with a lambada expression of all of the contained elements where the type is DataGridColumnHeader.
                DataGridColumnHeader colHeader = oUIClickedElementList.Where(element => element.GetType().Equals(typeof(DataGridColumnHeader))).FirstOrDefault() as DataGridColumnHeader;
    
                if (colHeader != null)
                {
                    //handle the event
                    e.Handled = true;
    
                    //this may be overkill but I remove an event for this dispatcher then create a new one then start the timer.
                    //it seems to work better if we wait a bit to run the query in order to let the datagrid finish setting what ever it needs to then execute the query
                    Dispatchers.Main.Invoke(() => { timer.Tick -= timer_Tick; timer.Tick += new EventHandler(timer_Tick); timer.Start(); });
                }
            }
    
            void lastNameTextBox_KeyUp(object sender, System.Windows.Input.KeyEventArgs e)
            {
                if (e.Key == System.Windows.Input.Key.Enter)
                {
                    //this may be overkill but I remove an event for this dispatcher then create a new one then start the timer.
                    //it seems to work better if we wait a bit to run the query in order to let the datagrid finish setting what ever it needs to then execute the query
                    Dispatchers.Main.Invoke(() => { timer.Tick -= timer_Tick; timer.Tick += new EventHandler(timer_Tick); timer.Start(); });
                }
            }
        }
    
    

    Here is a screen shot of the designer.

     

    If you find this helpful let me know.

     


    Derek
    Friday, January 13, 2012 9:29 PM

Answers

  • I know that most people would consider the behavior a bug, but if you think about what turning off automatic execution means, it quite literally does what it means. No matter what you change about the inputs to the query that backs the visual collection, it will not automatically execute. If you disable automatic execution, you are responsible for forcing a reload of the collection.

    That being said, there's a much simpler solution to re-enable paging and sorting for collections that are not automatically executed: subscribe a property changed event handler to the collection property and reload the collection when the PageNumber (for paging) and SortDescriptors (for sorting) properties change. Here's an example using a collection property called Customers:

    // The <ScreenName>_Created method
    partial void EditableCustomersGrid_Created()
    {
        INotifyPropertyChanged customersProperty = this.Details.Properties.Customers;
        Dispatchers.Main.Invoke(() =>
        {
            customersProperty.PropertyChanged += this.CustomersProperty_PropertyChanged;
        });
    }
    
    private void CustomersProperty_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "PageNumber": // Changed when current page is changed
            case "SortDescriptors": // Changed when sorting is changed
                this.Details.Dispatcher.BeginInvoke(() => this.ReloadCustomers());
                break;
        }
    }
    
    private void ReloadCustomers()
    {
        this.Customers.Load();
    }


    Justin Anderson, LightSwitch Development Team

    Thursday, September 06, 2012 7:45 AM
    Moderator

All replies

  • Many thanks, Derek!

    Is there a group of example apps that use the AdventureWorks LT R2 database? 

     

     


    Garth Henderson - Vanguard Business Technology
    Friday, January 13, 2012 11:23 PM
  • Can anyone confirm if the problem exists if you just use a WCF RIA service?

    I know that with a WCF RIA Service you have to put in this code:

            // Override the Count method in order for paging to work correctly
            protected override int Count<T>(IQueryable<T> query)
            {
                return query.Count();
            }
    

     


    Make Them Ask: That's a LightSwitch App?

    http://LightSwitchHelpWebsite.com

    Friday, January 13, 2012 11:26 PM
  • Yes Michael, this problem does exist when just using RIA services.

    Regards


    Xander
    Saturday, January 14, 2012 6:38 AM
  • Is it possible to set AutoExecute in code? That way you could set it to false in the designer, and then reset it to true as soon as you have called Run() so that from then on, paging and sorting can work.
    There is always a way. You just have to find it.
    Monday, January 16, 2012 7:58 AM
  • @Garth--No I just created a demo app using AD LT R2 db.

    @TakalaneSesame -- The Auto Execute property is read only.


    Derek
    Monday, January 16, 2012 8:04 PM
  • Thanks Derek. It seems to work.

    This is not to criticize your solution but I experimented and unfortunately the timer is necessary which, of course, is horribly kludgy. The required delay probably depends on the speed of the client computer.

    I'm new LightSwitch but I wonder if there is another event that we should catch after the PageChanged to know when it's safe to load the data again.

    TakalaneSesame, that sounds like an interesting idea but I can't find where to set Auto Execute in code.

    Monday, January 16, 2012 8:18 PM
  • This works for me regardless if what the timer delay is set to, including zero but it doesn't work at all if I do the load in PageChanged without the timer.

    I don't really understand it and I guess it doesn't really matter but this makes me wonder if it's just the fact that the load is on another event is what makes it work, not the time delay.

    Anyway... this seems to be a workable solution for now.

    Thanks


    • Edited by icosa Tuesday, January 17, 2012 3:23 PM
    Tuesday, January 17, 2012 3:19 PM
  • Derek, I've found this to be not quite the complete solution.  I don't have exactly your code but probably the same problem.

    I have a search button instead of detecting the enter key.

    Do the search, move to page 2 and then change the last name text box. It automatically does another query because changing the parameter resets to page 1 therefore firing the PageChanged event.

    I solved this with a  bool _pagingEnabled flag which is, normally false, set true by my search button but set false on the TextChanged event of the textbox and Click event of a checkbox that I have for criteria. The pageChanged event is ignored if this is false.

    With this logic, if you change the filter parameters after you've done the query then paging will no longer work. I guess that's okay because you're probably about to do another query.

    I haven't looked closer to see if there is a better way. It would be nice if we could disconnect the automatic binding between the controls and parameters after we've done the query and then connect them (or copy values in code) when we want to query again.

    I guess it's easy for me to criticize but I can't help wondering how on earth this bug was missed. Microsoft decided that auto exec = false was useful to avoid unnecessary queries but it seems that nobody tried it with more than one page of data.
    • Edited by icosa Thursday, January 26, 2012 11:07 PM
    Thursday, January 26, 2012 11:04 PM
  • I will look into this, thanks for the input.
    Derek
    Friday, January 27, 2012 12:20 AM
  • I have implemented this for grids, but I have 2 questions:

    1. How can one do this for a ModalWindowPicker?

    2. Has anyone tested if this has been fixed in Visual Studio 2012?


    There is always a way. You just have to find it.

    Saturday, April 14, 2012 6:24 PM
  • 2. Has anyone tested if this has been fixed in Visual Studio 2012?

    From a quick test I did with one of my grids that has AutoExec = false, it appears the paging problem still exists in the V2 beta.  When I clicked to go to Page 2, nothing visually changed in the grid.

    Ed Taylor

    Sunday, April 15, 2012 4:34 AM
  • 2. Has anyone tested if this has been fixed in Visual Studio 2012?

    From a quick test I did with one of my grids that has AutoExec = false, it appears the paging problem still exists in the V2 beta.  When I clicked to go to Page 2, nothing visually changed in the grid.

    Ed Taylor

     Hi, just to emphasize to Microsoft the importance of solving this issue, by next beta or final version of LS v2. At least for me, resolving this issue would make my life easier. 

    Thanks ... 


    Thursday, May 03, 2012 5:38 PM
  • I have also that kind of problem - we have a lot of parameters (textboxes and Combos) and a search button - the search

    should only takes place if the search button will be pressed...

    now if a disable "Auto Execute Query" the paging does'nt work and disable paging  is not an option because of the count of rows (performance)

    i cannot understand why this bug is present also in V2 Beta???

    robert

    Wednesday, May 23, 2012 11:49 AM
  • Quite agree.

    Microsoft. Have you fixed this bug yet?

    I really don't want to have to go through what these people have gone through to make this work.

    Can you comment?

    Gus

    Tuesday, August 14, 2012 2:38 PM
  • I know that most people would consider the behavior a bug, but if you think about what turning off automatic execution means, it quite literally does what it means. No matter what you change about the inputs to the query that backs the visual collection, it will not automatically execute. If you disable automatic execution, you are responsible for forcing a reload of the collection.

    That being said, there's a much simpler solution to re-enable paging and sorting for collections that are not automatically executed: subscribe a property changed event handler to the collection property and reload the collection when the PageNumber (for paging) and SortDescriptors (for sorting) properties change. Here's an example using a collection property called Customers:

    // The <ScreenName>_Created method
    partial void EditableCustomersGrid_Created()
    {
        INotifyPropertyChanged customersProperty = this.Details.Properties.Customers;
        Dispatchers.Main.Invoke(() =>
        {
            customersProperty.PropertyChanged += this.CustomersProperty_PropertyChanged;
        });
    }
    
    private void CustomersProperty_PropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        switch (e.PropertyName)
        {
            case "PageNumber": // Changed when current page is changed
            case "SortDescriptors": // Changed when sorting is changed
                this.Details.Dispatcher.BeginInvoke(() => this.ReloadCustomers());
                break;
        }
    }
    
    private void ReloadCustomers()
    {
        this.Customers.Load();
    }


    Justin Anderson, LightSwitch Development Team

    Thursday, September 06, 2012 7:45 AM
    Moderator
  • Justin,

    This is simply, this is brilliant and simply brilliant !

    Thanks for sharing.

    paul.


    paul van bladel

    Thursday, September 06, 2012 2:01 PM
  • Paul, when I read Justin answer to this post I felt exactly the same as you ... totally agree, simply brilliant ... 


    • Edited by smr.software Thursday, September 06, 2012 2:08 PM
    Thursday, September 06, 2012 2:06 PM
  • @Justin - I don't consider this as a bug at all, if you turn auto-execue off, you turn it off, simple.

    Great code again, as usual!

    Thanks.


    Yann - LightSwitch Central - Click here for FREE Themes, Controls, Types and Commands
     
    If you find a reply helpful, please click "Vote as Helpful", if a reply answers your question, please click "Mark as Answer"
     
    By doing this you'll help people find answers faster.

    Friday, September 07, 2012 5:09 AM
    Moderator
  • I was under the impression that LS was aimed at developers of all skills levels. Justin was the only person able to solve this problem. This is something that any developer in my organisation will run into. Data apps are useless without good filtering. Good filering requries custom search.

    Maybe its technically not a bug. However, if you are able to disable functionality with a mouse click then I don't think its unreasonable to assume that either a) you should be warned of the potential implications or b) its shouldn't break the buit in functionality. After all, how is any developer to know that turning off 'auto exec query' will leave paging in a broken state?  I found out the hard way. I didn't notice until I had to demo the app to the client.

    The auto exec feature leads one into the following scenario. When enabled the query is only fired when the control loses focus. So imagine you have a series of search boxes. When you get to the last one you have to click outside of it to fire the search. But when using the standard search the query is fired as you type.  Turning off autoexec was something I did after following Beth's video. Even Beth appeared to be unaware that once her data grew to occupy more than a single page the paging would not work.

    Bug or no bug my enthusiasm for LS is hanging by a thread.

    Gus

    PS: Still nothing from MS Connect about this. Without Justin's answer I'd have already decided to ditch LS development and cut my losses. I really think MS can do a lot better with the resources it has at its disposal.

    Monday, September 10, 2012 6:41 AM
  • Hi Gus,

    What I do in the scenario of a custom search screen (with autoexec = true) with multiple search boxes, is to put a "search button" on the screen, which is doing a refresh. From a user perspective, it's consistent behavior.

     


    paul van bladel

    Monday, September 10, 2012 7:29 AM
  • Hi Paul, yes I am using a button to fire the search, precisely because:

    1> using autoexec means you either have to click outside the last box to fire the search

    2> it doesn't seem that clever to fire a complicated search every time something changes in the filter

    But, I have run into another problem. At first I thought Justin's workaround did the job. However, I just noticed that it doesn't after all. Unless I am doing something wrong.

    see this screencast:

    http://screencast.com/t/JKYgLEcJ

    More alarming is that when I turned on Autoexec query and commented out Justin's code I got the same issue. When a filter is applied to the query the page size is ignored. Paging works but page size changes to some random value.

    So, it doesn't matter whether or not you use the built in method, or use some clever workaround, paging is screwed.  I don't care what anyone says, this looks like a bug to me.

    Can any of you guys replicate this issue?

    Gus

    Tuesday, September 11, 2012 6:57 AM
  • When a filter is applied to the query the page size is ignored. Paging works but page size changes to some random value.

    Gus, sorry I do not have time to look at your query or video, but I believe the behavior you describe is symptomatic of a problem in your query and has nothing to do with Lightswitch. I vaguely remember a similar situation that we encountered long ago and that was outside of LS. I would suggest going down to the basic query and adding one simple filter at a time until you can spot what the issue is. Maybe even use SQL tracing.

    Regards


    Xander

    Tuesday, September 11, 2012 7:05 AM
  • thanks Xander

    any chance you could explain why a query built inside LS would cause a grid paging problem?

    The query works perfectly. The data is correct. Why would that change the page size property?

    Besides isn't the Entity Model used here? In which case there isn't any SQL or does the model ultimately create SQL from LS code?  Either way I don't care I just want it to work out of the box.

    Anyone got any other suggestions?

    Gus

    Tuesday, September 11, 2012 8:50 AM
  • Well, I tried stripping out some of my custom query code such as:

     // filter on role level
                if (RoleLevel != null)
                {
                    query = from co_AxaptaFeed in query
                            from Roles in co_AxaptaFeed.co_Consultants_Roles
                            where Roles.RoleLevel == RoleLevel
                            select co_AxaptaFeed;
                }

    And paging works when there is no custom code and the only filters are text boxes where LS does the querying. So, the question is. Is there something wrong with my query code or is there a bug in paging?

    Gus

    Tuesday, September 11, 2012 9:18 AM
  • Can anyone help on this?

    I am really stuck and need to solve this as soon as possible?  I can't work out how to make the above query simpler or do it in another way. And I don't see the point in trying to analyse it with SQL profiler.

    I'd like to know why this query breaks paging and what I can do to fix it?

    Justin?

    Tuesday, September 25, 2012 2:39 PM
  • Using the above guidance, I 'fixed' the 'bug' using an extension, and then only having to add one line of code per query:

    //overload method
            public static void ISFixPagingProblem(this IScreenObject screenObject, string controlName, Action CallbackMethod)
            {
                new FixMicrosoftPagingProblem(screenObject, controlName, CallbackMethod);
            }
    
    public class FixMicrosoftPagingProblem
        {
            private Action _CallbackMethod;
            private String _collectionName;
            private IScreenObject _screenObject;
            public FixMicrosoftPagingProblem(IScreenObject screenObject, string collectionName,Action CallbackMethod)
            {
                _screenObject = screenObject;
                _collectionName = collectionName;
                INotifyPropertyChanged collection = (INotifyPropertyChanged)screenObject.Details.Properties[_collectionName];
                _CallbackMethod = CallbackMethod;
                Microsoft.LightSwitch.Threading.Dispatchers.Main.Invoke(() =>
                {
                    collection.PropertyChanged += collection_PropertyChanged;
                });
            }
            
    
            void collection_PropertyChanged(object sender, PropertyChangedEventArgs e)
            {
                switch (e.PropertyName)
                {
                    case "PageNumber": // Changed when current page is changed
                    case "SortDescriptors": // Changed when sorting is changed
                        _screenObject.Details.Dispatcher.BeginInvoke(() => { _CallbackMethod(); });
                        break;
                }
            }
        }
    
    ///Then, in the _InitializeDataWorkspace method of the screen:
    
    this.ISFixPagingProblem("MyVisualCollection", MyVisualCollection.Load);

    Friday, March 22, 2013 7:29 PM
  • Justin,

    The bug is not about forcing the user to execute the query when autoexec is set to false; i'd have thought that was obvious! No, as you and the team know very well, the bug is actually the fact that when this is the case, sorting and paging no longer works 'out of the box' Your solution for that is simple and elegant for sure; but this does NOT later the fact that this IS a bug and what's more, the team has been made aware of it ( many times) since Beta 1.

    I would not be posting this (since you HAVE provided such a solution ) were it not for the fact that so many other niggles, particularly re datgriids etc, have NOT been fixed in subsequent releases. However full of welcome new (HTML client ) goodies they are, the fact is that by the Team's own admission, HTML client is NOT for LOB desktop ( at least not yet ), thus as a developer one has to wonder why these bugs have been ignored time after time, For proof, check out another post of mine here and its subsequent responses.

    I will be posting more detail and effectively making a plea that the Silverlight client ( yes, the LOB tool ) gets the attention it deserves in terms of fixing things that are 'LOB crucial' and still broken after at least 3 major releases, despite the fact that said bugs have been logged for years.

    Ian MacPherson


    Ian Mac

    Saturday, March 23, 2013 2:30 PM
  • Hi Ian,

    Although I do understand where you're coming from (& why it's so frustrating when bugs don't get addressed), I'm sorry, but in this particular case I have to agree with Justin that this issue is not a bug, it's just an unexpected consequence of turning AutoExecute off.

    If auto execution of the query is turned off, then why is it not logical (gee, I sound like Spock) that anything that depends on execution of the query (such as paging & sorting) is also turned off, & now needs to be triggered manually?

    If paging & sorting (which needs to execute the query with new parameter values to do what they do) just went ahead & executed the query anyway, then it would be a violation of the intent of turning AutoExecute off, wouldn't it? (For me the answer is "yes")

    Justin's code isn't a work-around for a bug, it's just a clever example of how to manually execute the query when required, when AutoExecute is turned off.

    You don't have to agree with me, just because I have a different point of view. I just wanted to express my thoughts on the issue for consideration by anyone who currently feels that the issue is a bug.


    Yann - LightSwitch Central - Click here for FREE Themes, Controls, Types and Commands
     
    Please click "Mark as Answer" if a reply answers your question. Please click "Vote as Helpful" , if you find a reply helpful.
     
    By doing this you'll help others to find answers faster.

    Saturday, March 23, 2013 3:53 PM
    Moderator
  • Hi Yann,

    This is an interesting debate. OK I will give you a scenario explaining reasons why I want to use this and why iit should 'just work' Needless to say I disagree with your assertion ( in an extremely respectful and friendly manner i should add ); whether a true bug, or an unexpected consequence of turning autoexec OFF, it still doesn't work 'out of the box as it should.

    Lets say I have a datagrid screen ( and by the way I almost NEVER use the built in search on grids, I create a panel above the grid that allows me to select various parameters. This might be because there are things I want to filter on that I can only pick out on the server side i.e. related stuff, or simply because I want a combination of values).

    Now with autoexec ON, each time I select ONE of those parameters, off the query 'execs', irrespective of whether I've finished selecting parameters or not. So I want to defer execution until I am ready, then sure enough I will do something on my screen that reloads the collection with all my selected parameters. Voila! One database hit, which is as it should be.

    Now to refer to your point about paging and sorting in paragraphs 2 and 3 of your post, bearing in mind that I now have a set of data in my grid. Also bear in mind that although autoexec is OFF, the required 'support paging' and 'page size' flags have been set on the visual collection at design time. Given this, why should I not now expect that A) my initial reload respects those settings and brings in at most 'page size' records and B) subsequent page calls do the same thing ?

    And yes, I like Justin's solution. It's elegant. But what does it do? Oh yes, it monitors a physical change of the paging and/or sort properties! In other words, it fixes what is missing intrinsically. In my book, that's a bug which has NOT been fixed in the framework itself. This may be pedantic, but my main point is that Justin's answer (whilst extremely welcome) came in September 2012. This issue was logged on connect at V1 beta, along with MANY others. They are not being fixed intrinsically. You and I can probably agree on that!

    All the best

    Ian Mac


    Ian Mac

    Saturday, March 23, 2013 7:49 PM
  • . . .  and by the way I almost NEVER use the built in search on grids, I create a panel above the grid that allows me to select various parameters. This might be because there are things I want to filter on that I can only pick out on the server side i.e. related stuff, or simply because I want a combination of values.

    Now with autoexec ON, each time I select ONE of those parameters, off the query 'execs', irrespective of whether I've finished selecting parameters or not. So I want to defer execution until I am ready, then sure enough I will do something on my screen that reloads the collection with all my selected parameters. Voila! One database hit, which is as it should be.


    Ian Mac

    Hiya Ian, 

    We also never depend on the grid search and use a top criteria selection.   We also never use the Screen Filters because of the 2083 char limit on the passed values.   We always build Table Code Queries.   I have some Criteria screens with over 60 values.

    To get around the auto-exec bugs (its a bug because it doesn't function the way that it needs to), I use the following work around.

    Just set a query to look for a null PK value - which will never happen.

    partial void PMRentalContractsSearch_PreprocessQuery(string FilterTerm, bool? CanRunQueryYorN, int? pPropId, bool? pIsContractCurrentYorN, string pAddress1, etc.          {
                if (CanRunQueryYorN == false )
                {
                    query = query.Where(p => p.RentalContractGuid == null);
                }
                else 
                {
                    query = query.OrderBy(p => p.PMUnit.PBUCode);
    
                    if ( pPropId != null)
                        query = query.Where(p => p.PMProperty.PropId == pPropId);
                    
                    if (FilterTerm != null)
                        query = FilterControl.FilterExtensions.Filter(query, FilterTerm, this.Application);
    

    Buttons are set for the user to turn on or off the auto-search function.    

    It has been working great.


    Garth Henderson - Vanguard Business Technology

    Sunday, March 24, 2013 4:26 AM
  • "its a bug because it doesn't function the way that it needs to"

    Sorry, but something not working the way you "need" it to does not make it a bug. At best, it's a feature request, because you want the behaviour to be different than it's been designed to be.

    If I turn my house's electricity supply off at the main switch, can I reasonably expect my bedroom light to still work, just because I need it to? Of course not. And neither should one expect paging & sorting, which rely on the query being executed automatically, to still automatically execute the query, as they do when AutoExecute is turned on, when AutoExecute is turned off.

    If you turn it off, you take responsibility for manually executing the query. So why do people think that it's not reasonable to expect to have to take responsibility for manually implementing paging & sorting.

    You all know that I will fight hard when there's a bug that's not being addressed. But this is not a bug. It will not get "fixed".

    If you want the behaviour changed, submit a suggestion. Then maybe it'll be considered. But continue to insist that it's a bug, & the team is going to say "this is not a bug, therefore it doesn't need to be "fixed".


    Yann - LightSwitch Central - Click here for FREE Themes, Controls, Types and Commands
     
    Please click "Mark as Answer" if a reply answers your question. Please click "Vote as Helpful" , if you find a reply helpful.
     
    By doing this you'll help others to find answers faster.

    Sunday, March 24, 2013 6:47 AM
    Moderator
  • Hi Yann,

    If I switch my electricity back on, MANUALLY, then yes I expect my bedroom light to work. If you read my post in thorough detail, you will discover that there is nothing illogical in what i say, given that I have set the perfectly legal ( or at least, allowable ) combination of 'autoexec' 'OFF', 'Support paging' ON and 'Page size' to whatever.

    Like I said, that is an ALLOWABLE combination, so when I manually reload, I want those settings obeyed! Since they are not, it IS a bug!


    Ian Mac

    Sunday, March 24, 2013 4:45 PM
  • Yann,

    As an addendum, I've noticed in some previous posts that you personally saw no need to ever have autoexec set to OFF' Given the scenario I outlined in an earlier post regarding multiple database hits when autoecec is ON and multiple parameters are available for selection, I find it hard to believe you would advocate that position!


    Ian Mac

    Sunday, March 24, 2013 4:52 PM
  • Actually I can see an objection to my reaction to your electricity analogy in the situation where my bedroom light swtich is in the OFF position when I turn my supply OFF ( using the Light Switch no less! ).

    So just to clarify, if in fact I have left my bedroom switch in the 'ON' position when I turn OFF my supply ( think 'support paging' ON ), then I think I can reasonably expect by bedroom light to work when I switch the supply back on. Don't you think ? :-)) 


    Ian Mac

    Sunday, March 24, 2013 5:19 PM
  • So just to clarify, if in fact I have left my bedroom switch in the 'ON' position when I turn OFF my supply ( think 'support paging' ON ), then I think I can reasonably expect by bedroom light to work when I switch the supply back on. Don't you think ? :-))

    So let's run with this statement for a little bit. In the analogy, what does switching the power supply on or off represent? It's the setting of the Auto Execute Query property. Which is mutually exclusive to whether your support sorting or specify a new set of sort descriptors.

    All Auto Execute Query means is that, when set to true, if a property is changed that would affect the result of a query, then execute the query again (automatically) or your behalf. When set to false, if a property is changed that would affect the result of query, the query is not executed until explicitly told to execute, hence, not automatically executing (essentially the name of the property).

    This is the behavior of the property regardless of what your scenario is, what controls are used, what you are trying to accomplish, etc. I really don't understand why you are trying to read more into what it does since it doesn't imply anything beyond the straight-forward name of the property.

    So if you want to turn of automatic execution of the query, a choice that you consciously made, then you need to re-enable automatic execution behaviors (e.g. changing sort descriptions) manually. The Auto Execute Query property isn't going to determine a subset of properties to listen to; it's all or nothing. That is the design of the property.

    Just because a feature does not do as much as you want does not mean there is a bug. What you are asking for is an improvement to an existing feature. You are asking for a way to have more fine-grained control of what causes automatic execution and what doesn't. This is a feature request or a suggestion, not a bug. Bugs are "this feature does not do what it describes". This case, where setting Auto Execute Query to false causes the query to not be automatically executed, is not a bug.


    Justin Anderson, LightSwitch Development Team

    Sunday, March 24, 2013 11:17 PM
    Moderator
  • Justin, Yann,

    Hands up, mea culpa!

    I think this whole thing stemmed from the fact that in (at least ) Beta 1, the first manual reload did not obey the page size setting. Rather shortsightedly i hadn't checked that that particular issue had been resolved in future releases. Now I see that it has. With autoexec off, you would indeed expect that at least to happen correctly on the first call, as indeed it now does.

    It's sobering to think that one can become so focused on an issue that you can't see the blindingly obvious i.e. that a subsequent page change call has NO WAY of intrinsically performing its duty with autoecec off unless you are monitoring page/sort change properties on the collection! ( hence, as I've said before, Justin's simple and elegant method of doing just that ).

    Lesson learned. Pull back, approach with new eyes, see and understand that this indeed is NOT a bug!!!


    Ian Mac

    Monday, March 25, 2013 11:32 AM
  • hmmm . . . . is it possible (meaning that it has to work 100% - no gotchas) to turn AutoExec on and off at runtime?

    Our users like to have the software:

    1)  not run the Preprocess query after each parm change - this is generally when they have to change several parms at one time.

    as well as

    2) kick off a Preprocess query after each parm change - this is to further "tune" or use existing parms with slight changes.

    They also want to be able to save their criteria - as well as to pass the results "around" to other screens and reports.

    I've seen PreprocessQuery being called multiple times.   I'd sure like to know exactly what kicks off a PreprocessQuery call.   (I think) I've noticed that several parm values can be set within a method but the PreprocessQuery isn't called until the method ends.

    We need more documentation on LS.

    Considering that this is Derek's post, I'd sure like to hear about more stories of how others are using LS Search capabilities so that we can build a consensus of what works best.


    Garth Henderson - Vanguard Business Technology

    Monday, March 25, 2013 6:15 PM
  • If it helps anyone, I had to add the namespaces:

    System.ComponentModel

    Microsoft.LightSwitch.Threading

    to my screen code to make Justin's code work.

    As far as the bug vs feature issue, I think the term we use is less relevant than whether the functionality makes any sense from a user's perspective. When a user wants to make multiple, optional parameter selections to filter records, having the screen refresh each time a single parameter is selected is a little clunky. Worse is the fact that the screen offers the user page controls to look through the results but the page controls don't function. This is a lot like the way the Excel export option only exports the first page of results. Who would think that is logical from a user's point of view? The same can be said of the built-in LS grid search box. The user sees columns with data and they want to search the results to find just the records with that value. For some reason the search returns no results. Why, because the search box is not searching the values of related tables. All of these "features" cause problems for a user who is making perfectly reasonable assumptions about what should happen. Bug, feature request, whatever. That said, I know LS is "young" and it is a great tool for a wide range of users.


    4tuneate

    Tuesday, April 09, 2013 11:52 PM
  • What we can learn from this is that this is a massive time waster for everyone.

    I got stuck on this before I came across Justin's solution and I wasted hours and hours and hours on it. I was tearing my hair out and tried everything I could. I even tried replacing the standard grid with third party ones but nothing fixed it.

    As far as I am concerned it's about time the LS Team sat down and discussed this problem and came up with a more intuitive solution for developers.

    For me, Lightswitch is on the back burner. Having spent 6 months learning and building apps with it I am very careful about what I use it for. There's a lot I like about it. But I also put a lot of effort into it and I'm not sure the productivity gains it offers outweigh the constant struggles I had trying to deliver some very minor requirements. If I had put 6 months into .net MVC4 would I be better off?  I am starting to believe that yes I would.

    My designer has given up trying to build shells for it because he uses a Mac and prefers HTML/CSS and can't get to grips with VS development and my company requires desktop web applications and isn't that keen on any more Silverlight development.

    So for me, Lightswitch has fallen short. And this issue and many other similar issues are why.

    But I will be keeping an eye on it and hoping future versions include desktop web and improvements to issues such as these.

    Gus

    Wednesday, April 10, 2013 10:57 AM
  • I agree 100% with Gus - spend also a lot of time to get around some limitations and a lot of bugs and speed problems (sluggish)...

    now we have a 2-Tier SL app out and it works but really sluggish and that is why we not develop more with lightswitch.

    As there is the HTML Client out I hope that the LS Team will inform us about what's coming next especially with Silverlight?

    robert

    Wednesday, April 10, 2013 11:36 AM
  • Gus, I think LightSwitch has a very good sweet spot between ease of use and power.  There is nothing you can’t do in ASP.NET MVC but how easy it is become the question.  I’m using LightSwitch to ease into ASP.NET MVC, since ASP.NET MVC requires you to become proficient at HTML, CSS, Javascript, jQuery, ASP.NET, Linq, and SQL Server all at once.  LightSwitich does the heavy lifting for you in all these areas and provides hooks for you to write code with these technologies, thus being a good way to learn them.
     
    I also take my hat off to the LightSwitch team for developing the Browse/Details screen navigation using tabs in the HTML Client.  I’m quite sure I would not have designed a native ASP.NET MVC app that way.
     
    I’m sure there will be a day when I become proficient enough with ASP.NET MVC that I will use it as my dominant tool, until then LightSwitch is a stepping stone and even a permanent tool in my toolbox for simple forms over data apps.
     
    -- David

    Efficiently read and post to forums with newsreaders: http://communitybridge.codeplex.com
    Wednesday, April 10, 2013 7:30 PM
  •  
    I’m sure there will be a day when I become proficient enough with ASP.NET MVC that I will use it as my dominant tool, until then LightSwitch is a stepping stone and even a permanent tool in my toolbox for simple forms over data apps.
     
    -- David

    Does anyone think that the MVC4 Framework will ever become a RAD ERP environment?

    What is the difference between a web service generated with VMC4 and the web service generated with VS 2012 Upd 2?

    From my perspective I see both LS and MVC technologies evolving into a more unified VS technology so we have the best of both.  Time will tell.

    My work around with the PreprocessQuery and AutoExec has been in place with production apps since Beta 2.  This issue isn't even in my top 25 "wish list" items for the VS team to work toward.

    I'm very grateful for what the LS team continues to do to work toward a RAD ERP environment.  It is a journey.  I'm looking forward to using RAD HTML5 client development.

    Thoughts?


    Garth Henderson - Vanguard Business Technology

    Thursday, April 11, 2013 1:18 AM
  • This has gone way off-topic, but... I wrestle with these questions on a daily (and nightly!) basis. One of my largest applications has a legacy Windows Forms client talking WCF to the back-end. This Windows Forms client has evolved through the years, has been worked on by a number of developers and has become difficult to maintain. Plus, my customers are requesting a web app!

    The app in question is a bit like a call center app where you have an inbox of incoming communication and tasks and you need to pick up typically multiple calls and tasks (in separate windows where each window then becomes a separate unit of work) and do work on all of those simultaneously by keeping an eye on the status and incoming updates of each and updating from your perspective as well. In addition you might be completing "dynamic pre-configured forms" for each of those. So there is a lot going on at any one time. You also have all the typical admin functionality and reports, etc.

    So how do I turn this into a web app?

    Note that I already have most of the above functionality exposed as a RIA domain service in my initial anticipation of using LS. 

    Options as I see them:

    1. Use LS Silverlight (original plan, have made some progress with this already, but the death of Silverlight has all but killed this option for me)

    2. Use LS HTML client - not possible with current HTML client due to limitation of only being able to have one unit of work at a time (i.e. SDI vs MDI). This is the biggest let-down of the HTML client for me. 3rd parties will extend the UI capabilities tremendously (e.g. C1 with Wijmo), but SDI will not work for me or for ERP type systems I believe. The problem I am talking about is quite well explained here: Breeze Multiple Managers

    3. Use one of the many up and coming Javascript SPA frameworks (AngularJS, EmberJS, Durandal) together with a good Javascript data-access freamework like BreezeJS. However, this is a LOT of work and the learning curve is very steep.

    4. Use ASP.NET MVC4. I have done some projects in this before and it is not too difficult to master. If one links this with the likes of the Kendo UI Wrappers where you can use the wrappers a lot to write Javascript on your behalf. This is definitely easier than option 3 (based on my own current skills).

    5. Redevelop the entire app on top of Dynamics CRM. Dynamics CRM is a very powerful development framework offering a lot more than just CRM. I've not discounted this option altogether but there is a lot more to the application than just the client part mentioned above so this is a fairly radical option with lots to consider.

    6. Go on holiday, forget about the above and hope the problem goes away by the time you return (i.e. MS releases the the LS HTML client V2 that has all the capabilities of the Silverlight client).

    Garth, there is a lot of commonality between your requirements and mine and I don't think there is an easy solution right now. I'm spending a bit of time every day on 1, 3 and 4 above, switching backwards and forwards....

    Those are some of my current thoughts...

    Regards


    Xander

    • Edited by novascape Thursday, April 11, 2013 2:35 AM inserted CRM option
    Thursday, April 11, 2013 2:26 AM
  • Hey Xander,

    So . . . if #2 was solved you'd be happy moving forward with LS?

    What you are talking about as a Unit of Work is the LS Workspace, yes?

    AFAIK, the server side will still support unlimited Workspaces with the HTML5 Client, yes?


    Garth Henderson - Vanguard Business Technology

    Thursday, April 11, 2013 4:41 PM
  • Hey Garth,

    The server side is fine, it can support any number of concurrent data work spaces so we are safe there from an investment point of view.

    The "limitation" is with the current client side framework utilized in the HTML client. Most reasonably sized LOB applications need to support multiple simultaneous data work spaces (or units of work). The LS Silverlight client excelled in this area with its simple, yet powerful, multiple tabs approach where each tab has its own data work space.

    I have noticed however, that in the final release of the current HTML client that the API method myApp.dataWorkspace was renamed to myApp.activeDataWorkspace and I wonder what the significance of that might be? Could it be that they are aiming to support multiple data work spaces in the next version, with one being the active one at any point? If that is the case then there is hope.

    Would I move forward with LS if #2 was solved? Hard to say at this point as it depends on the rate of innovation coming from MS. My personal view is that what we have with the Silverlight client today is what will remain and they are not going to put any more work into it. So it remains to be seen how quickly the HTML client will evolve, how much 3rd parties will jump in and provide extensions or custom controls and how much progress I make in other areas.

    Regards


    Xander

    Friday, April 12, 2013 2:49 AM
  • Everyone,

    I know we've drifted off slightly into 'general suitability' territory, but that's a good thing and I'll tell you why. The original topic was raised as part of discussing general usability issues in the SIlverlight client, specifically around the datagrid control, its lack of intelligent column alignment, auto-column sizing etc along with inconsistent other control alignment settings, query performance et al.

    The topic discussed the fact that many of these issues had been pointed out on connect since V1 beta and that not one of them have been addressed. These issues and others, though seemingly of small effect in isolation, cumulatively give the impression that the Silverlight client has largely been neglected of late.  I could point to various posts where promises were made but nothing to date has materialised, presumably because the team were focused on delivering the HTML Client, a product which displays great promise.

    And here's the rub. In response to many excited posts at the time of the first release of HTML client, it was affirmed that this was targeted at the mobile spaceonly and was not, at least in the current form, targeted at desktop-sized LOB application development. I don't think many of us would argue that indeed HTML5 is not the way things are going ( re LightSwitch or anything else ), but LightSwitch was originally developed for that very scenario.

    So the question is, given we won't be able to develop fully functional LOB applications using purely the HTML client for some while to come, what is the roadmap for the Silverlight client ( particularly the fixing of said niggling issues ) and indeed what is MS's intention re where the HTML Client will ultimately sit in the LOB space?

    I think as evangelists and developers using this product we are entitle to a fair answer on this issue, so that we are all clear.

    Team?


    Ian Mac

    Friday, April 12, 2013 8:30 AM
  • Hello Ian,

    I agree with you and I have asked this question a lot of times in the last months here in this forum but no response from MS and I cannot understand why?

    Why isn't it possible to give us a roadmap what's coming next with the SL client or tell us that it is dead!

    robert

    Friday, April 12, 2013 8:43 AM
  • It's because the death of Silverlight is painful. It's like our granny just died.

    They are trying to protect us from the pain by not telling us until we're older.

    They do have a heart you know.

    :)

    • Proposed as answer by Grampa Parent Monday, May 27, 2013 8:34 PM
    • Unproposed as answer by Grampa Parent Monday, May 27, 2013 8:34 PM
    Friday, April 12, 2013 8:47 AM
  • I am running into this same issue right now using LS for VS 2013. In my situation, I have a datagrid that is driven by some paramaterized form fields. It is also the first screen of my app, so when my app loads and AutoExecute = TRUE, I end up retrieving all records in the database. The work flow is that the screen should open with no rows retrieved. The user enters their selection criteria via the form fields, usually selecting themselves from a dropdown and then clicking Search and they then get their own records.

    I assumed the AutoExecute property meant "initially on page load", not all the time. Maybe the property could be renamed or there could be a second property that means "just on initial page load". Basically, what you have done, except built in. It seems logical that there are many, many situations. especially search screens like mine, where you want to not load records when the page loads AND you still want to implement paging and sorting.

    Friday, August 29, 2014 4:41 PM
  • Hi Justin,

    Thanks for this simple code to fix the paging and sorting functions. How can I get the built-in Search in the DataGrid to work?

    Best regards,

    CT

    Thursday, September 18, 2014 1:05 AM
  • The built in search I would have imagined would work as that is a call to reload the data anyway.

    Derek

    Thursday, September 18, 2014 4:12 PM
  • Hey everybody.  Interesting thread, to say the least.  I apologize for resurrecting such an old thread, but the discussion here made me realize something that I just had to comment on.

    What I realized - if I'm interpreting Justin and Yann's comments correctly - is that changing the sort order through column clicking actually re-executes the query.  I'll assume that means re-execution on the server side.

    If that's true, then I'm sorry, but that is just utterly appalling.  Anyone who's done any native Silverlight or WPF development knows how easy it is to do client-side sorting with a CollectionView.  So Lightswitch, which uses Silverlight under the covers (for desktop), doesn't do that?  That's completely ridiculous.

    So in that context, can you understand why I (and probably others) would think it's a bug that turning off Auto Execute breaks sorting?  If not, I'll tell you.  Because you shouldn't need to re-query the database to sort a visual collection.

    So anyway, that's all I wanted to vent about.  At least we have Justin's solution. Thank you for that, Justin.

    Tuesday, May 26, 2015 8:54 PM
  • What I realized - if I'm interpreting Justin and Yann's comments correctly - is that changing the sort order through column clicking actually re-executes the query.  I'll assume that means re-execution on the server side.

    If that's true, then I'm sorry, but that is just utterly appalling.  Anyone who's done any native Silverlight or WPF development knows how easy it is to do client-side sorting with a CollectionView.  So Lightswitch, which uses Silverlight under the covers (for desktop), doesn't do that?  That's completely ridiculous.

    So in that context, can you understand why I (and probably others) would think it's a bug that turning off Auto Execute breaks sorting?  If not, I'll tell you.  Because you shouldn't need to re-query the database to sort a visual collection.

    Server side sorting is absolutely the correct behavior and cannot be any other way. Client side sorting can only work if you have *all* the records downloaded to the client side, which is not a typical scenario at all.

    You might have thousands of records in the database and only show one page of say 45 records in the grid. The only way to efficiently sort this is to go back to the server, resort there and get the updated page of records.

    Auto Execute of queries is a different matter altogether.


    Regards, Xander. My Blog

    Tuesday, May 26, 2015 9:01 PM
  • I agree with you in the case of paged results.

    But I disagree with the assertion that paging is the typical scenario.  Most of my users are used to seeing hundreds (sometimes thousands) of records at a time in a desktop application, so I almost always provide the full result set.  With good, responsive live scrolling, and the ability to quickly change the sort order, working with a grid of a few hundred items (or more) is very efficient for the user.

    So if you have all of the records on the client, then client-side sorting (and filtering too, by the way) gets you the best responsiveness.  I mean, why not?  What you see on the screen is just a collection.  You should be able to slice, dice, sort, and filter it a hundred different ways without calling back to the server.

    By the way, I figured out how to do client-side filtering in my HTML client, and it rocks.  Maybe I'll share it someday. :)

    Tuesday, May 26, 2015 9:23 PM
  • Perhaps the best solution is to allow client side sorting and filtering when paging is disabled.

    You should share your HTML client side filtering as we need every bit of information on the HTML client to be shared with the community given the lack of communication from MS :)

    ps. there seems to be a bit of a bug with sorting on the Table control in the HTML client if you have any invisible columns where sorting just does not work as expected on a column next to an invisible column. The simple fix for this seems to be to never have any invisible columns.


    Regards, Xander. My Blog

    Tuesday, May 26, 2015 10:02 PM
  • Thanks, Xander.  I'll try to do that soon, probably in it's own thread so searches will find it more easily.  I'll link to it here.
    Wednesday, May 27, 2015 12:50 PM