cancel
Showing results for 
Search instead for 
Did you mean: 
Reply
priyankbhat
Level: Powered On

Custom method/function for avoiding repeated code in powerapp

Hi,

 

I have created small app based on sharepoint data.

 

App pull data from sharepoint and displayes summary using graphs and few labels. There are few actions on app screen like week filter and there is additional filter by some roles using drop downs. App also refreshes data using timer control every 5 min if app is kept running.

 

Code pulls data from 2-3 sharepoint views and manipulate data based on filters before it is displayed or everytime something changes in drop down screen values are refreshed.

 

Same code is used for Onvisible of screen, onselect in refresh icon, ontimerend in timer control and onchange in 2 drop downs.

 

Now there is duplication of codes. If i change anything i have to manually replicate code on all 5 locations on screen. Please suggest is there anyway i can simplify by writing 1 custom functions on powerapps which can be called on all 5 location. This can help me reduce errors and consistancy in reporting on screen.

 

Thanks and waiting for your reply.

 

Priyank

1 ACCEPTED SOLUTION

Accepted Solutions
Mike8
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

Hello @BrianR,

Yes, you are right. It should have been easier to achieve something like this.

After some testing I also confirm that:

 

"True that if you have just a bit of code behind a button, in many cases it may "act" like it is sequential.  Though if you think about it, when you do:

 

Select(A);

Select(B)

 

All you are doing is telling it to press A, and then to press B - nothing about waiting for A to complete before pressing B - they are independent (if you had disable on press set, then conceivably I guess PowerApps could have been written to wait until A was no longer disabled (and thus done) before selecting B."  


But maybe there is a solution. I don't know if you can use it but take a look at this..

 

Select(A);Select(B) doesn't work because the two selects are independent.
You can try Select(A);Select(A) though. This way, ButtonA is pressed the first time and it's not pressed for the second time before the code runs. So, this is an example that works.


Button1.OnSelect = 
UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,ClearCollect(Collection1,RetrieveObjectData.Run("Root"));UpdateContext({vScriptToRun:2}),
2,ClearCollect(Collection2,Collection1);UpdateContext({vScriptToRun:3}),
3,ClearCollect(Collection3,Collection2))

RetrieveObjectData is a flow that takes some time to run.
By changing the variable vScriptToRun the next select function will run different script each time.
In your case it would be..

Button1.OnSelect = UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,Script1 for Reading the first two CDS entities can be done in parallel;UpdateContext({vScriptToRun:2}),
2,Script2 for Reading the next CDS entity can only be done after the first two are complete;UpdateContext({vScriptToRun:3}),
3,Script3 for Reading the objects from Salesforce can only be done once the other step is done)

Yeah, not very nice way to do what you need but it may help.

View solution in original post

11 REPLIES 11
Mike8
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

Hello,

This might help..
https://docs.microsoft.com/en-us/powerapps/maker/canvas-apps/functions/function-select

You can have the code that you repeat multiple times in the same screen, on the OnSelect property of a button, and reference the button using the Select() function

BrianR
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

I use the button method and it works fairly well, though as mentioned you can't "call" (Select()) a button from another screen.

 

However, one thing I have tried (which works fairly well) is to use Navigate() to quickly hop to the screen with the button that has the buttons with the code I want on it, and then quickly navigate back by calling Back().  I pass parameters in the Navigate() to tell the other screen which "buttons" to press, and what to do.

 

While this seems a bit convoluted (and I agree that it is and only use this sparingly), it can be necessary in my app as I read in a lot of data from multiple sources that needs to be displayed and at times updated.  No way could I, or would I, duplicate that code everywhere it is needed.

 

This does result in a slight "flicker" of the screens (as it changes to one and back to the other), but I've lessened that by using the screen to show what is being done with some animation.  

 

Note that the issue with the button approach is that when you call a button from one code block using Select(button), that will IMMEDIATELY return so if you code that calls it relies upon the code you called to be complete - it won't be (in most cases).  ie: they are executed in parallel.  

 

No easy way around this and there aren't (to my knowledge) any functions in PowerApps to allow you to synchronize between two sections of code.  

 

You can simulate something like a semaphore (or more appropriately a "spinlock") by using a global variable and a timer.  I won't go into the details here, as it would take a while to explain.  

 

I did this initially and it worked well (though took me quite a while to work out all of the details).  However, in the end, I managed to structure my code in such a way that the synchronization wasn't needed (ie: ensured there were no dependencies on stuff the called button did the "caller" required at that point - though you cannot always do this).  

 

If only we had macros within PowerApps, that would alleviate the need for all of this mess (though honestly still some need to do synchronization for other purposes as well).

Mike8
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

Hello BrianR,

If you need to run the expression from a different screen, as you said you need to work with the global variable and the timer.
If you haven't done it yet, you can also have variables in the expression that you set to the desired value before you run the expression and they are used like parameters. You can have the functionality but it could have been easier.
I think this is the issue. Smiley Happy

Edit: I have just tested on what you said here
"Note that the issue with the button approach is that when you call a button from one code block using Select(button), that will IMMEDIATELY return so if you code that calls it relies upon the code you called to be complete - it won't be (in most cases).  ie: they are executed in parallel."
and I now understand your problem. Yes. I was expecting to run the expression differently.
I tried
Button1.OnSelect = Collect(A,{text:"A"})
Button2.OnSelect = Select(Button1);Select(Button1);Collect(A,{text:"B"})
I pressed Button2 and instead of A,A,B the table is B,A,A.
Strange.

Edit 2:
When I tried it like this, by pressing Button3
Button1.OnSelect = Collect(A,{text:"A"})
Button2.OnSelect = Collect(A,{text:"B"})
Button3.OnSelect = Select(Button1);Select(Button2);Select(Button1);Select(Button2);Select(Button1);Select(Button2)
it worked as expected.
You may need to have only the Select() functions on the pressed button. No extra expressions. 
Seems like when there are extra expressions, the code runs like using the Concurrent() function. And when not, it run as you expect.
I did a quick test. I don't know how reliable it is. You can try it though.


Community Support Team
Community Support Team

Re: Custom method/function for avoiding repeated code in powerapp

Hi @priyankbhat,

 

Could you please share a bit more about your scenario?

Do you want to use 1 custom function in all 5 locations on your screen instead of the repeated code? 

Further, could you please show more details about the repeated code within your app?

 

If the repeated code that you mentioned is used to retrieve the data from your SP list data source and manipulate data based on filters, you could consider take a try to create a collection (Using ClearCollect function) to store the filter data/results, then if you want to reference the filtered data/results in other location, you could reference the collection directly.

 

In addition, I also agree with @Mike8's thought almost. If you have same action formula within the OnSelect property of other controls, you could consider take a try to use the Select function to achieve your needs. But please make sure all controls (which has same action formula, e.g. ) are within same container.

 

Best regards,

Kris

Community Support Team _ Kris Dai
If this post helps, then please consider Accept it as the solution to help the other members find it more quickly.
BrianR
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

@Mike8,

 

The reason for the timer is that I need one of the "functions" (aka buttons) to wait on another to complete.  I do indicate completion by a global variable that one sets and the other checks, but there is no way to have the other one wait on that variable to be set that I'm aware of other than using a timer (set the timer that autoresets to timeout say after 250ms and then call itself.  if the flag is not set, then don't do anything within the button, if it is, then stop the timer and continue the code that was dependent on the first to be complete).

 

True that if you have just a bit of code behind a button, in many cases it may "act" like it is sequential.  Though if you think about it, when you do:

 

Select(A);

Select(B)

 

All you are doing is telling it to press A, and then to press B - nothing about waiting for A to complete before pressing B - they are independent (if you had disable on press set, then conceivably I guess PowerApps could have been written to wait until A was no longer disabled (and thus done) before selecting B.  

 

But if you have something short that executes quickly, then I imagine in many cases the action behind A might be done before the action behind B.  But probably also not guanteed unless PowerApps is specifically looking for this and then serializing things.

 

I do know though that when you have a lot of code in the OnSelect for a button, that you cannot guarantee that the action for Select(A) is done before the action behind Select(B) (yes you can ensure that A is pressed/selected before B, but not that one will complete before the other).  :-)  

 

 

In my case, the code behind each button takes a while to execute (2-3 seconds usually) as it is loading multiple data sources and doing some filters (3 CDS entities, 5 Salesforce objects).  So in this case I've seen this happen all over the board regarding what gets done first (and no consistent pattern, which makes sense).  

 

The only way I know that easily works for this is to have the first call Navigate() back to the same screen, passing that screen data telling it to start the 2nd.  :-)  (which is an "easy" workaround but causes even more flicker on the screen so the timer approach is perhaps slightly better (though it technically is "slower" within the resolution of your timer).  

 

Honestly, while it was nice to see the Concurrent() function and it does make some things easier - technically it wasn't needed as with Select() you could do the same thing.  What we need is something that allows for sequetial execution - either macros or true functions (either) or a synchronization object that I can wait on.  :-)

 

But your point about "You can have the functionality but it could have been easier" is indeed the issue - not just with this - but with most everything in PowerApps.  ie: I want to have the user upload an image of any resolution with the Add Picture control (works), display it in an Image control (works) and then upload it to CDS.  

 

Hmm, well, yes I can upload it as an entity image, but that is limited to 144x144 ( and it crops the image so if it was rectangular, its a mess).  To upload in full detail - well you have to use a Flow, Azure function, etc.  Why?  

 

Things like these where basic functionality (like macros, or a wait function, ability to upload files to Sharepoint, open Excels from Sharepoint, upload images in full resolution, etc) that one would expect to be in PowerApps but isnt - really moves this out of being a tool for non developers to one giving a developer headaches.  :-(

 

 

Highlighted
BrianR
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

Hi Kris,

 

So basically all I really want to do in this case is reuse code in multiple sections of my app.  There are MANY scenarios for this - from just basic logic that might implement an equivalent filter within galleries on the same or different screen, to perhaps a debug macro that will log to a collection ie: DebugMessage( "Operation successful", Success) which would do a Collect( ) to set various parameters (think of an event log), etc.  

 

Without the ability to do a macro, I'm duplicating that code in MANY places.  In the event log example I have to duplicate lines such as:

 

 

If(gDbgEnabled, Collect( cAppLog, { Scrn:LogName, Obj: "Test", 
             Msg: "Test message", Time: Now(), LogLvl: LogLvl.Info } ) );

 

in my code to do this - this basically will only update the collection (maintain the log) if my gDbgEnabled variable is true, but it also formats the message and adds other parameters.  Which other than it being a lot to type and paste, also is MUCH harder to maintain (what if I wanted to change something about the format of how this was put into the log (collection)?  I'd have to change it EVERYWHERE it was used.

 

With a macro, I could instead define a macro in such a way that I could call it instead like:

 

Debug( "Test", "Test message", LogLvl.Info )

and have it be replaced by the code above (I'm thinking "C" type macros here for reference).  With the ability to define a function within PowerApps - even better.  Each of which is FAR more maintainable, and for that matter easier to understand, and leads to LESS potential for errors.  And having the ability for the macros to be called between screens makes that even better.

 

 

But in the case that I was using Select(), its more pronounced.  I am loading from 8 data sources - 3 from CDS and 5 from Salesforce into separate collections (the CDS ones I'm reading multiple records, the Salesforce onces, only a single record per object).

 

Two of the CDS entities have no direct dependence on the other being loaded, but the third has LookUps() to the first two so I need to make sure that they are loaded first (I'm doing a LookUp() to the Collection they were loaded into, not back to the data source).  

 

The Salesforce objects I then read in are mostly independent of each other.

 

So basically I need to ensure that the following is sequentially done:

 

  • Reading the first two CDS entities can be done in parallel
  • Reading the next CDS entity can only be done after the first two are complete
  • Reading the objects from Salesforce can only be done once the other step is done

 

 

Note that these aren't simple ClearCollect()s to load the data, but each item loaded has multiple filters on it, in some cases is calling AddColumns(), and other data transformations as it brings it into the respective collections.  Also multiple conditions on what load in based on various criteria.  

 

The reason I don't just put all of this in a big code block and forget about it is that I give the user the option to Refresh and reload the CDS entities at any time and do not wish to duplicate this code and maintain it separately.   Ditto with the items from Salesforce.  

 

The CDS entities SHOULD in most cases not HAVE to be reloaded as they seldom change (mostly static data), though the collections loaded from Salesforce can't all be loaded at once (there are over 200,000 records and I only need 1) and throughout the application, the user might choose another.  

 

But in both cases, the user needs the ability to refresh the info at will and independently of each other.

 

Not sure how else to do this.  Since there is no direct way to share code or do macros, the Select() "hack" (potentially having to Navigate() between screens) is the "best" approach I know of being available (similar to how a boat makes the "best" airplane out of a list of boat, anchor, and bag of cement.  :-))  

 

Having either Macro or true Function capability - or a "WaitFor" function would resolve either (Macro/Function is the right approach here though, but "WaitFor" has other uses).

 

Lack of Macro support or function) is my #1 issue with PowerApps.  And while calling out to MS Flow, Azure, or third party web service is possible to do some of this - it is both something that SHOULD be unnecessary - but also won't work in all cases well.  And of course - taking Flow as an example - having to use a separate tool using a different language to do basically functionality that should be provided just complicates what is supposed to be (PowerApps) an easy "no code" (or low code) environment to build applications into something involving more skills and components than necessary.

 

Mike8
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

Hello @BrianR,

Yes, you are right. It should have been easier to achieve something like this.

After some testing I also confirm that:

 

"True that if you have just a bit of code behind a button, in many cases it may "act" like it is sequential.  Though if you think about it, when you do:

 

Select(A);

Select(B)

 

All you are doing is telling it to press A, and then to press B - nothing about waiting for A to complete before pressing B - they are independent (if you had disable on press set, then conceivably I guess PowerApps could have been written to wait until A was no longer disabled (and thus done) before selecting B."  


But maybe there is a solution. I don't know if you can use it but take a look at this..

 

Select(A);Select(B) doesn't work because the two selects are independent.
You can try Select(A);Select(A) though. This way, ButtonA is pressed the first time and it's not pressed for the second time before the code runs. So, this is an example that works.


Button1.OnSelect = 
UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,ClearCollect(Collection1,RetrieveObjectData.Run("Root"));UpdateContext({vScriptToRun:2}),
2,ClearCollect(Collection2,Collection1);UpdateContext({vScriptToRun:3}),
3,ClearCollect(Collection3,Collection2))

RetrieveObjectData is a flow that takes some time to run.
By changing the variable vScriptToRun the next select function will run different script each time.
In your case it would be..

Button1.OnSelect = UpdateContext({vScriptToRun:1});Select(Button2);Select(Button2);Select(Button2)
Button2.OnSelect = 
Switch(vScriptToRun,
1,Script1 for Reading the first two CDS entities can be done in parallel;UpdateContext({vScriptToRun:2}),
2,Script2 for Reading the next CDS entity can only be done after the first two are complete;UpdateContext({vScriptToRun:3}),
3,Script3 for Reading the objects from Salesforce can only be done once the other step is done)

Yeah, not very nice way to do what you need but it may help.

View solution in original post

BrianR
Level 10

Re: Custom method/function for avoiding repeated code in powerapp

@Mike8 - That's actually a great idea to use the two back to back Selects of the same button.  I'll try that!  Hadn't thought of this, but it makes sense.  Definitely a kludge, but one that looks to be very workable.   I'll try this when I have time.

 

I've already used the parameters to the screen in the way you mentioned, and it works well other than having to change the user's view (for however long the actions take).  But not too bad.  

 

Thanks,
Brian

JoeriW
Level: Powered On

Re: Custom method/function for avoiding repeated code in powerapp

Selects only add the action to the queue. So if you queue it right, it will follow that sequence. But other user actions might still come in between. Let's just put the Function definition as soon as possible into the tool.

Helpful resources

Announcements
firstImage

Microsoft Business Applications Virtual Launch Event

Join us for an in-depth look at the new innovations across Dynamics 365 and the Microsoft Power Platform.

firstImage

Watch Sessions On Demand!

Continue your learning in our online communities.

Power Platform 2019 release wave 2 plan

Power Platform 2019 release wave 2 plan

Features releasing from October 2019 through March 2020

FirstImage

Power Platform World Tour

Coming to a city near you

thirdimage

PowerApps Community User Group Member Badge

Fill out a quick form to claim your user group badge now!

FourthImage

Join PowerApps User Group!!

Connect, share, and learn with your peers year-round

Top Kudoed Authors
Users Online
Currently online: 322 members 3,772 guests
Please welcome our newest community members: