<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Emre AKA on Medium]]></title>
        <description><![CDATA[Stories by Emre AKA on Medium]]></description>
        <link>https://medium.com/@Cranberryy?source=rss-db4212154f3f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*3DWkCmrbEpCgR2nqa6Q3Tw.jpeg</url>
            <title>Stories by Emre AKA on Medium</title>
            <link>https://medium.com/@Cranberryy?source=rss-db4212154f3f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 04:59:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@Cranberryy/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Introducing Widget Testing in Flutter]]></title>
            <link>https://medium.com/@Cranberryy/widget-testing-with-flutter-c16056534672?source=rss-db4212154f3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/c16056534672</guid>
            <category><![CDATA[flutter]]></category>
            <category><![CDATA[widget-testing]]></category>
            <category><![CDATA[test]]></category>
            <category><![CDATA[unit]]></category>
            <category><![CDATA[component-testing]]></category>
            <dc:creator><![CDATA[Emre AKA]]></dc:creator>
            <pubDate>Tue, 25 Jun 2024 09:00:33 GMT</pubDate>
            <atom:updated>2024-06-25T21:22:42.064Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*QmP6mYFIOqsEe84wEBJxLQ.jpeg" /></figure><p>Hi, developers. I’d like to begin this story with a quote from the book I recommend you: <em>“No software engineers release even the tiniest change without testing, except the very confident and the very sloppy.”</em> — Test Driven Development by Kent Beck</p><p>I’ve prepared an example widget to test. I’ll give you the link of the repository in the end of this story.</p><h4>Let me introduce you the widget we’re going to test</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*H3mh3IvmcLrSL70NQ__yYg.png" /><figcaption>Dog View</figcaption></figure><p>We have a list of dogs that we can:</p><ul><li>Search</li><li>Paginate</li><li>Refresh (Pull to refresh)</li></ul><p>It fetches the paginated dog list when the widget is initialized. It loads more dogs when you scroll down to the end of the list. If you refresh, it resets everything including the search text.</p><p>It searches the dogs in a paginated manner when you type in the search text field. Again, if you scroll down to the end of the list, it brings more search results this time.</p><p>Writing tests first is ideal since they might not get done later, but for educational reasons, we’re starting with the actual code.</p><p><strong>Prerequisites:</strong></p><ul><li>Dart (Beginner)</li><li>Flutter (Beginner)</li></ul><h4>Testing</h4><p><strong>List Dogs (Paginated)</strong></p><ul><li>Should list dogs when the widget is initialized</li><li>Should show error message when service fails</li><li>Should load more dogs when scrolling down</li><li>Should show an error view if a problem occurs while loading more</li></ul><p><strong>Search Dogs (Paginated)</strong></p><ul><li>Should display search results when typed in the search text field</li><li>Should show an error view if a problem occurs during the search</li><li>Should load more search results when scrolling down</li><li>Should show an error view if a problem occurs while loading more search results</li></ul><p><strong>Refresh Dogs List</strong></p><ul><li>Should reset everything, including the search text, when refreshing</li><li>Should display an error view if a problem occurs during the refresh</li></ul><p>These are the ones comes to my mind for now. If there are more cases comes to my mind, we’re also going to take notes of them.</p><h4>Let’s get started!</h4><p>First, create a file named “dogs_view_test.dart” under test folder.</p><pre>void main() {<br>  <br>} </pre><p>We need the widget we’re going to test and its dependencies. Our widget depends on IDogService. Let’s create it first. If dependencies have shared fixture that may affect other tests, mock them. So, we should have a mock implementation of IDogService. I’m going to use a library named <a href="https://pub.dev/packages/mocktail">mocktail</a>.</p><pre>import &#39;package:flutter_example/modules/dog/interfaces/dog_service_interface.dart&#39;;<br>import &#39;package:mocktail/mocktail.dart&#39;;<br><br>class DogServiceMock extends Mock implements IDogService {}<br><br>void main() {<br><br>}</pre><p>Let’s create variables that are going to hold references to the widget and mock service.</p><pre>import &#39;package:flutter/material.dart&#39;;<br>import &#39;package:flutter_example/modules/dog/interfaces/dog_service_interface.dart&#39;;<br>import &#39;package:flutter_example/modules/dog/view/dogs_view.dart&#39;;<br>import &#39;package:flutter_test/flutter_test.dart&#39;;<br>import &#39;package:mocktail/mocktail.dart&#39;;<br><br>class DogServiceMock extends Mock implements IDogService {}<br><br>void main() {<br>  late DogServiceMock dogServiceMock;<br>  late Widget widgetToTest;<br><br>  setUp(() {<br>    dogServiceMock = DogServiceMock();<br>    <br>    widgetToTest = MaterialApp(<br>      home: DogsView(<br>        dogService: dogServiceMock,<br>      ),<br>    );<br>  });<br>}</pre><p>You may not need to wrap your widget with Material App but when you provide localizations, routes via Material App, it becomes necessary to configure a Material App also to make widget work properly.</p><p>We declare them with late keyword because tests should be isolated. We’re going to create a new instance for each test to prevent tests to affect each other.</p><p>You may guess that already, but setUp() function gets called after each test.</p><h4>List Dogs</h4><p><strong>Test case 1</strong>: Should list dogs when the widget is initialized.</p><pre>...<br>void main() {<br>  ...<br>  group(&#39;List Dogs&#39;, () {<br>    final dogList = List.generate(<br>      30,<br>      (index) =&gt; DogModel(<br>        age: 1,<br>        breed: &#39;Poodle $index&#39;,<br>        description: &#39;Max is an intelligent and elegant Poodle.&#39;,<br>        name: &#39;Max&#39;,<br>      ),<br>    );<br><br>    testWidgets(&#39;Should list dogs when widget initialized&#39;, (widgetTester) async {<br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(page: 1, pageSize: 10),<br>      ).thenAnswer((_) async {<br>        return Success(dogList);<br>      });<br><br>      await widgetTester.pumpWidget(widgetToTest);<br><br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(Card), findsExactly(dogList.length));<br>    });<br>  });<br>}</pre><p>We will first set up our mock service to return dogs successfully. Then, we expect to see a number of cards rendered equal to dogs.length, since we used a Card widget to display each Dog model. You can also use find.text() to find the widgets.</p><ul><li>pumpWidget() function takes a widget as an argument and renders it.</li><li>pumpAndSettle() function waits animations and futures to complete.</li><li>find.byType() allows us to find widgets by providing the types. There are a lot more functions that helps a lot.</li></ul><p>Simple, right?</p><p><strong>Test case 2</strong>: Should show error message when service fails.</p><pre>...<br>void main() {<br>  ...<br>  group(&#39;List Dogs&#39;, () {<br>    ...<br>    testWidgets(&#39;Should show error message when service fails&#39;, (widgetTester) async {<br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(page: 1, pageSize: 10),<br>      ).thenAnswer((_) async {<br>        return Failure(Exception(&#39;Error&#39;));<br>      });<br><br>      await widgetTester.pumpWidget(widgetToTest);<br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(FailedInformationWidget), findsOneWidget);<br>    });<br>  });<br>}</pre><p>We will first set up our mock service to return Failure. <em>By the way these Success and Failure types are return types of my methods. Nothing special to testing.</em> Then, we expect to see failed information widget to be displayed.</p><p><strong>Test case 3:</strong> Should load more dogs when scrolling down</p><pre>...<br>void main() {<br>  ...<br>  group(&#39;List Dogs&#39;, () {<br>    ...<br>    testWidgets(&#39;Should load more dogs when scrolling down&#39;, (widgetTester) async {<br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(<br>          page: any(named: &#39;page&#39;),<br>          pageSize: any(named: &#39;pageSize&#39;),<br>        ),<br>      ).thenAnswer((_) async {<br>        return Success(dogList);<br>      });<br><br>      await widgetTester.pumpWidget(widgetToTest);<br>      await widgetTester.pumpAndSettle();<br><br>      final scrollable = find<br>          .descendant(<br>            of: find.byType(ListView),<br>            matching: find.byType(Scrollable),<br>          )<br>          .first;<br><br>      await widgetTester.scrollUntilVisible(<br>        find.byType(Card).last,<br>        500,<br>        scrollable: scrollable,<br>      );<br><br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(Card), findsExactly(dogList.length * 2));<br>    });<br>  });<br>}</pre><p>We simulate scrolling and assert that if there are 2x more cards rendered.</p><p>You can also use widgetTester.drag() function but I think widgetTester.scrolUntilVisible works well with this case.</p><ul><li>find.descendant() function as the name suggest finds the descendant widget of ListView that is matching type Scrollable because we need to find the scrollable widget to scroll.</li><li>widgetTester.scrollUntilVisible() functions scrolls until it finds the widget you are looking for. 500 represents delta.</li></ul><p><strong>Test case 4</strong>: Should show an error view if a problem occurs while loading more</p><pre>...<br>void main() {<br>  ...<br>  group(&#39;List Dogs&#39;, () {<br>    ...<br>    testWidgets(&#39;Should show an error view if a problem occurs while loading more&#39;, (widgetTester) async {<br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(<br>          page: 1,<br>          pageSize: 10,<br>        ),<br>      ).thenAnswer((_) async {<br>        return Success(dogList);<br>      });<br>      <br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(<br>          page: 2,<br>          pageSize: 10,<br>        ),<br>      ).thenAnswer((_) async {<br>        return Failure(Exception(&#39;Error&#39;));<br>      });<br><br>      await widgetTester.pumpWidget(widgetToTest);<br>      await widgetTester.pumpAndSettle();<br><br>      final scrollable = find<br>          .descendant(<br>            of: find.byType(ListView),<br>            matching: find.byType(Scrollable),<br>          )<br>          .first;<br><br>      await widgetTester.scrollUntilVisible(<br>        find.byType(Card).last,<br>        500,<br>        scrollable: scrollable,<br>      );<br><br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(FailedInformationWidget), findsOneWidget);<br>    });<br>  });<br>}</pre><p>We repeat the same process except that this time the request for the next page returns a failure and we expect to see failed information widget to be rendered.</p><p><strong><em>Tip</em></strong><em><br>You can also use setUp() function in groups to prevent code duplication in tests. For now, I’m not going to try to refactor my tests.</em></p><h4>Search Dogs</h4><p>I leave this to you because that’s almost identical to previous test group.</p><h4>Pull to Refresh</h4><p>In this test group, we will employ an additional test utility function called ‘drag’ to initiate a refresh.</p><p><strong>Test case 1:</strong> Should refresh dogs when user pulls to refresh</p><pre>...<br>group(&#39;Pull to Refresh&#39;, () {<br>    setUp(() {<br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(page: 1, pageSize: 10),<br>      ).thenAnswer((_) async {<br>        return Success(dogList);<br>      });<br>    });<br><br>    testWidgets(&#39;Should refresh dogs when user pulls to refresh&#39;,<br>        (widgetTester) async {<br>      await widgetTester.pumpWidget(widgetToTest);<br>      await widgetTester.pumpAndSettle();<br><br>      final refreshIndicator = find.byType(RefreshIndicator);<br><br>      await widgetTester.drag(refreshIndicator, const Offset(0, 300));<br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(Card), findsExactly(dogList.length));<br>    });<br>  });</pre><p>It’s quite straightforward: locate the Refresh Indicator widget, drag it, and initiate a refresh. However, the effectiveness of this test is unclear. It’s uncertain whether a refresh actually occurred. To clarify, one approach is to initially search and list 15 dogs, then perform a refresh to list 30 dogs. If 30 cards are displayed, it indicates a successful refresh. Alternatively, a new method could be implemented to refresh the dogs in the service, and we could simply verify that this refresh method was invoked.</p><p>Actually, another method just occurred to me. Before pumping and settling, you could make our service to return 15 dogs instead of 30 and then verify if there are indeed 15 dogs.</p><p>Let’s try that:</p><pre>testWidgets(&#39;Should refresh dogs when user pulls to refresh&#39;,<br>        (widgetTester) async {<br>      await widgetTester.pumpWidget(widgetToTest);<br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(Card), findsExactly(dogList.length));<br><br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(page: 1, pageSize: 10),<br>      ).thenAnswer((_) async {<br>        return Success(searchedDogList);<br>      });<br><br>      final refreshIndicator = find.byType(RefreshIndicator);<br><br>      await widgetTester.drag(refreshIndicator, const Offset(0, 300));<br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(Card), findsExactly(searchedDogList.length));<br>    });</pre><p>Now, it’s clear to me. What do you think?</p><p><strong>Test case 2:</strong> Should show error message if refresh fails</p><pre>testWidgets(&#39;Should show error message if refresh fails&#39;,<br>        (widgetTester) async {<br>      await widgetTester.pumpWidget(widgetToTest);<br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(Card), findsExactly(dogList.length));<br><br>      when(<br>        () =&gt; dogServiceMock.getDogsPaginated(page: 1, pageSize: 10),<br>      ).thenAnswer((_) async {<br>        return Failure(Exception(&#39;Error&#39;));<br>      });<br><br>      final refreshIndicator = find.byType(RefreshIndicator);<br><br>      await widgetTester.drag(refreshIndicator, const Offset(0, 300));<br>      await widgetTester.pumpAndSettle();<br><br>      expect(find.byType(FailedInformationWidget), findsOneWidget);<br>    });</pre><p>This time, a failure is returned, and a failed information widget is expected to be seen.</p><p>Running flutter test --coverage allows you to execute your tests and review the coverage. <a href="https://marketplace.visualstudio.com/items?itemName=ryanluker.vscode-coverage-gutters">I use this vs code extension to view my coverage</a>, which highly recommend.</p><p><a href="https://github.com/EmreAka/FlutterExample/blob/main/test/dogs_view_test.dart">Here are all tests</a></p><p>All tests have been completed. Naturally, there could be additional test cases, but we won’t spend the entire day writing tests, right? Feel free to practice with any test case that comes to mind :). I appreciate your attention thus far.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c16056534672" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular — How to Get and Set Slicer States from Power BI Report]]></title>
            <link>https://medium.com/@Cranberryy/angular-how-to-get-and-set-slicer-states-from-power-bi-report-ae979cb81632?source=rss-db4212154f3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ae979cb81632</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[power-bi-filter]]></category>
            <category><![CDATA[power-bi-tutorials]]></category>
            <category><![CDATA[power-bi]]></category>
            <category><![CDATA[power-bi-slicer]]></category>
            <dc:creator><![CDATA[Emre AKA]]></dc:creator>
            <pubDate>Fri, 17 Nov 2023 13:08:41 GMT</pubDate>
            <atom:updated>2024-01-24T20:41:39.971Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular — How to Get and Set Slicer States of a Power BI Report</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/96/1*Yp5molacAUoHV7mtZXN-GA.png" /></figure><h3>What Is a Slicer?</h3><blockquote>“Slicers are another way of filtering. They’re displayed on the report page, and narrow the portion of the semantic model that’s shown in the other report visualizations.”</blockquote><p>Slicers are basically filters but they are located on the report page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aSxNCPdzBiDCwoonr9ur2w.jpeg" /><figcaption>Some of the slicers on the report.</figcaption></figure><h3>Setup</h3><p>We are going to work on the demo provided by Microsoft. You should clone the <a href="https://github.com/microsoft/powerbi-client-angular.git">repository</a> if you would like to code along with me.</p><p>After cloning the repository, run the commands below in the project directory:</p><pre>cd angular/powerbi-client-angular &amp;&amp; npm install --legacy-peer-deps &amp;&amp; npm run demo</pre><p>Then, get to the app.component.ts and app.component.html in the demo folder.</p><h3>How To get Slicer States</h3><h4>Get the List of the Slicers</h4><p>We’re going to declare a method:</p><pre>private async getSlicers(): Promise&lt;VisualDescriptor[] | undefined&gt; {<br>  //We&#39;re going to write our code here.<br>}</pre><p>First, we need to get the report object from PowerBI Component:</p><pre>// Get report from the wrapper component<br>const report: Report = this.reportObj.getReport();<br><br>if (!report) {<br>  this.displayMessage = &#39;Report not available.&#39;;<br>  return undefined<br>}</pre><p>As we received our report, we can get the active page that our users are currently viewing:</p><pre>// Get active page of the report<br>const activePage = await report.getActivePage();<br><br>if (!activePage) {<br>  this.displayMessage = &#39;No Active page found&#39;;<br>  return undefined<br>}</pre><p>Then we should get the visuals on the page:</p><pre>// Get visuals of the report<br>const visuals = await activePage.getVisuals()</pre><p>Visuals include everything that you see on the report. We need to only take the slicers. We can achieve that by filtering visuals by type “slicer”:</p><pre>// Filter the slicers out of visauls<br>const slicers = visuals.filter(visual =&gt; visual.type === &quot;slicer&quot;)<br><br>return slicers;</pre><p>Final result of the method:</p><pre>private async getSlicers(): Promise&lt;VisualDescriptor[] | undefined&gt; {<br>    // Get report from the wrapper component<br>    const report: Report = this.reportObj.getReport();<br><br>    if (!report) {<br>      this.displayMessage = &#39;Report not available.&#39;;<br>      return undefined<br>    }<br><br>    // Get active page of the report<br>    const activePage = await report.getActivePage();<br><br>    if (!activePage) {<br>      this.displayMessage = &#39;No Active page found&#39;;<br>      return undefined<br>    }<br><br>    // Get visuals of the report<br>    const visuals = await activePage.getVisuals()<br><br>    // Filter the slicers out of visauls<br>    const slicers = visuals.filter(visual =&gt; visual.type === &quot;slicer&quot;)<br><br>    return slicers;<br>}</pre><p>We successfully received list of slicers. We’re going to use these slicers to get and set their states.</p><h4>Get the List of Slicer States</h4><p>Again, we’re going to declare a method:</p><pre>async getSlicerStates(){<br>  //We&#39;re going to write our code here.<br>}</pre><p>Let’s call the function we’ve just created:</p><pre>// Get slicers of the report<br>const slicers = await this.getSlicers()<br><br>if (!slicers) {<br>  this.displayMessage = &quot;No slicer found&quot;<br>  return<br>}</pre><p>Fine, now we should iterate through the slicers and get their states:</p><pre>const slicerStates: models.ISlicerState[] = []<br><br>for (let slicer of slicers) {<br>  const slicerState = await slicer.getSlicerState()<br>  slicerStates.push(slicerState)<br>}</pre><p>And print the result:</p><pre>console.info(&quot;Slicer States:&quot;)<br>console.info(slicerStates)</pre><p>Our function looks like this:</p><pre>async getSlicerStates() {<br>    // Get slicers of the report<br>    const slicers = await this.getSlicers()<br><br>    if (!slicers) {<br>      this.displayMessage = &quot;No slicer found&quot;<br>      return<br>    }<br><br>    const slicerStates: models.ISlicerState[] = []<br><br>    for (let slicer of slicers) {<br>      const slicerState = await slicer.getSlicerState()<br>      slicerStates.push(slicerState)<br>    }<br><br><br>    this.displayMessage = &quot;Slicers are printed in the console.&quot;<br>    console.info(&quot;Slicer States:&quot;)<br>    console.info(slicerStates)<br>  }</pre><p>Let’s put a button that calls our method on click:</p><pre>//In app.component.html line 12 next to other buttons<br>&lt;button (click)=&quot;getSlicerStates()&quot;&gt;Get slicer states&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/651/1*ZpH_P4h8gE_TxpGKzgHcww.png" /><figcaption>Click the get slicer states button and check out the console.</figcaption></figure><p>Finally, we can try if we can see the result in the console. You must see an array of ISlicerState as follows:</p><pre>[<br>  {<br>    filters: [],<br>    targets: []<br>  },<br>  ...<br>]</pre><p>Filters property holds the array of ISlicerFilter.<br>This is a union type and actually consisting of six different filter types:</p><p>1) IBasicFilter <br>2) IBasicFilterWithKeys <br>3) IAdvancedFilter <br>4) IRelativeDateFilter <br>5) IRelativeTimeFilter <br>6) IHierarchyFilter</p><p>You can determine the type by reading $schema property of them and cast the type.</p><p><strong>Keep in mind: </strong>Filters array will be an empty list if there are no values selected.</p><p>Targets property holds a list of IFilterTarget. And this is also a union type consisting of several types:</p><ol><li>IFilterColumnTarget</li><li>IFilterHierarchyTarget</li><li>IFilterMeasureTarget</li><li>INotSupportedFilterTarget</li><li>IFilterColumnAggrTarget</li><li>IFilterHierarchyAggrTarget</li></ol><p>We’ll come to details of these types later.</p><h3>Set state of a slicer</h3><p>As your guess, we’re declaring another method:</p><pre>async setRegionSlicerState(){<br>  //We&#39;re going to write our code here.<br>}</pre><p>In this example, we’re going to only set the state of single slicer but if you wish, you can go beyond the example and set of all the slicers’ states. Let me know if you have any questions.</p><p>Getting the slicers again.</p><pre>// Get slicers of the report<br>const slicers = await this.getSlicers();<br><br>if (!slicers) {<br>  this.displayMessage = &quot;No slicers found&quot;<br>  return<br>}</pre><p>Let’s explore the code line by line:</p><ol><li>First, we start to iterate through the list of slicers.</li><li>Get the state of the slicer because we need slicer object to set and get the state.</li><li>Check if the “visualName” equals to the name of the visual you’re looking for. You can use our get slicer states method to see the columns of the slicer states. (You can get slicers’ visual names by logging to the console)</li><li>If yes, we have the slicers we need. Assign the slicer to a variable as well as target.</li><li>Since Region slicer’s filter is a basic filter, I’m creating a new Basic Filter but you can definitely create another type of filters. It is totally up to you here. You can get the values somewhere else. In this example, I’ve hard-coded it.</li><li>Finally, we’re setting the state of the slicer with the help of setSlicerState method of slicer object.</li></ol><pre>const slicer = slicers.find((slicer) =&gt; slicer.name === &quot;visual name of the slicer&quot;);<br>const slicerState = await slicer.getSlicerState();<br><br>// New filter to set<br>const basicFilter: models.IBasicFilter = {<br>  $schema: &quot;http://powerbi.com/product/schema#basic&quot;,<br>  target: slicerState.targets,<br>  filterType: 1,<br>  operator: &quot;In&quot;,<br>  values: [<br>    &quot;West&quot;<br>  ],<br>  requireSingleSelection: false<br>}<br><br>// Set region slicer state <br>await regionSlicer.setSlicerState({<br>  filters: [<br>    basicFilter<br>  ]<br>})<br><br>this.displayMessage = &quot;Region slicer&#39;s state set.&quot;</pre><p>Final result of our function looks like this:</p><pre>async setRegionSlicerState() {<br>    // Get slicers of the report<br>    const slicers = await this.getSlicers();<br><br>    if (!slicers) {<br>      this.displayMessage = &quot;No slicers found&quot;<br>      return<br>    }<br><br>    const slicer = slicers.find((slicer) =&gt; slicer.name === &quot;visual name of the slicer&quot;);<br>    const slicerState = await slicer.getSlicerState();<br><br>    // New filter to set<br>    const basicFilter: models.IBasicFilter = {<br>      $schema: &quot;http://powerbi.com/product/schema#basic&quot;,<br>      target: slicerState.targets,<br>      filterType: 1,<br>      operator: &quot;In&quot;,<br>      values: [<br>        &quot;West&quot;<br>      ],<br>      requireSingleSelection: false<br>    }  <br><br>    // Set region slicer state <br>    await slicerState.setSlicerState({<br>      filters: [<br>        basicFilter<br>      ]<br>    })<br><br>    this.displayMessage = &quot;Region slicer&#39;s state set.&quot;<br>}</pre><p>Place another button next to our “Get slicer states” button as follows:</p><pre>//In app.component.html line 13 next to other buttons<br>&lt;button (click)=&quot;setRegionSlicerState()&quot;&gt;Set region slicer state&lt;/button&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/1*F-x4Z7zPFsDNPlcKcGUl6Q.png" /></figure><p>Click the set region slicer state button after report is loaded. You must see thar region filter is changed:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/611/1*vXQ3euJTwsCtlPy8q4rhMQ.png" /></figure><p>That’s it! Thanks for reading. If you have any question, please leave a comment. I’d love to answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ae979cb81632" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Power BI Client Integration (Angular)]]></title>
            <link>https://medium.com/@Cranberryy/power-bi-client-integration-angular-8a7996552bf0?source=rss-db4212154f3f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8a7996552bf0</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[power-bi]]></category>
            <dc:creator><![CDATA[Emre AKA]]></dc:creator>
            <pubDate>Tue, 13 Jun 2023 15:21:24 GMT</pubDate>
            <atom:updated>2023-11-16T20:54:54.623Z</atom:updated>
            <content:encoded><![CDATA[<h3>Angular — Power BI Client Integration</h3><figure><img alt="PowerBI Logo" src="https://cdn-images-1.medium.com/max/96/1*gJOqnqYrWLJPGj9Mf-bYYQ.png" /></figure><h3>What is Power BI?</h3><p>Power BI is a business analytics tool developed by Microsoft. It provides interactive visualizations and business intelligence capabilities with an interface that is user-friendly and accessible to both technical and non-technical users. Power BI allows users to connect to various data sources, transform and model the data, and create interactive reports and dashboards.</p><h3>Power BI Usage Scenarios</h3><p>There are two scenarios: Embed for your customers and Embed for your organization. We’ll be covering Embed for Your Customers scenario.</p><h4>Embed For Your Customers</h4><p>In this scenario, your customer does not need any license of Power BI or data. You or your organization own the license and data.</p><p>The custom application requires an embedding identity that has permission and an appropriate license to access Power BI content.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PQ-uB6JXpWukwHQByuAsOQ.png" /><figcaption><a href="https://learn.microsoft.com/en-us/power-bi/guidance/powerbi-implementation-planning-usage-scenario-embed-for-your-customers#scenario-diagram">https://learn.microsoft.com/en-us/power-bi/guidance/powerbi-implementation-planning-usage-scenario-embed-for-your-customers#scenario-diagram</a></figcaption></figure><p><em>That might look a bit complicated, but I got you.</em></p><p>First, your customers authenticate with the app. They way you authenticate them is not important. It doesn’t have to be Azure AD.</p><p>Second, you need to provide an <strong>Azure AD Access Token </strong>that has permissions/license to Power BI service. An embedding identity can be a <a href="https://learn.microsoft.com/en-us/power-bi/guidance/powerbi-implementation-planning-usage-scenario-embed-for-your-customers#service-principal">service principal or a master user account</a>. We are not going into that because It’s a back-end side of things.</p><p>We’re going to use this token to fetch <strong>Metadata </strong>includes properties required to embed content in the custom application from <strong>Power BI Rest API</strong>.</p><h4>Embed For Your Organization</h4><p>In this scenario, users need the license of Power BI and data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XlpKz_7SIGYxzblFKuySnA.png" /><figcaption><a href="https://learn.microsoft.com/en-us/power-bi/guidance/powerbi-implementation-planning-usage-scenario-embed-for-your-organization#scenario-diagram">https://learn.microsoft.com/en-us/power-bi/guidance/powerbi-implementation-planning-usage-scenario-embed-for-your-organization#scenario-diagram</a></figcaption></figure><p>Only difference here is that app users authenticate with Azure AD.</p><p><em>Enough talk. Let’s get started.</em></p><h3>Implementation</h3><p>We need to install <strong>powerbi-client</strong> and <strong>powerbi-client-angular</strong>:</p><p><em>Don’t forget to import </em><strong><em>PowerBIEmbedModule</em></strong><em> in your module.</em></p><pre>npm i powerbi-client powerbi-client-angular</pre><p>Then, we should get <strong>Azure AD Access Token</strong>. Since we follow <strong>Embed for Your Customers </strong>scenario, we’ll receive our token from our API. If you are following <strong>Embed for Your Organization</strong>, you’ll already had that token.</p><pre>getPowerBiToken(): Observable&lt;IPowerBiTokenResponse&gt; {<br>    return this.http<br>      .get&lt;IPowerBiTokenResponse&gt;(&quot;your endpoint to get the token&quot;)<br>      .pipe(<br>        retry(5),<br>        catchError((err) =&gt; {<br>          console.log(&quot;Error occured while getting power bi token&quot;);<br>          console.log(err);<br>          return throwError(err);<br>        })<br>      );</pre><p>This token should be persisted because we’re going to use this token for Power BI Rest API.</p><p>At that point, we’re going to use <strong>Power BI Rest API</strong> to get <strong>Metadata </strong>includes properties required to embed content.</p><h4>What Are the Required Properties to Embed Content?</h4><pre>{<br>  type: &quot;report&quot;,<br>  id: configDto.id,<br>  embedUrl: configDto.embedUrl,<br>  accessToken: configDto.accessToken,<br>  tokenType: models.TokenType.Embed,<br>}</pre><p>id is the id of the report, <strong>embedUrl </strong>is the <strong>embedUrl </strong>of the report, <strong>accessToken</strong> is embed token (<em>we will get there soon</em>) and lastly, <strong>tokenType </strong>is either <strong>Aad </strong>or <strong>Embed </strong>(if you are following <strong>Embed for Your Organization </strong>you may need to use Aad). There are a lot more properties, but these are the required ones. You can access those properties by importing <strong>IEmbedConfiguration </strong>from<strong> powerbi-client.</strong></p><h4>How To Get Metadata?</h4><p>In order to get the metadata, first, you need to know the id of the report you want to embed.</p><p>You can use this <a href="https://learn.microsoft.com/en-us/rest/api/power-bi/reports/get-reports">endpoint </a>to receive available reports. Don’t forget to include <strong>Azure AD Access Token </strong>in headers as<strong> </strong>Authorization.<br>If you have the report id, then you can use this <a href="https://learn.microsoft.com/en-us/rest/api/power-bi/reports/get-report">endpoint </a>to get its metadata.</p><pre>getReport(reportId: string) {<br>    return this.http.get&lt;IPowerBiReportResponse&gt;(`${environment.powerBIRestAPIUrl}reports/${reportId}`)<br>}</pre><p>I have an interceptor that appends my <strong>Azure AD Access Token </strong>to the headers of the request and also gets a new one if It is expired.</p><pre>@Injectable()<br>export class PowerBiRestAPIInterceptor implements HttpInterceptor {<br><br>  constructor(<br>    private readonly http: HttpClient<br>  ) { }<br><br>  intercept(request: HttpRequest&lt;unknown&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;unknown&gt;&gt; {<br>    if (request.url.indexOf(&quot;api.powerbi.com/v1.0/myorg&quot;) &gt; -1) {<br>      const token = localStorage.getItem(&quot;azure-ad-access-token&quot;)<br>      const newRequest: HttpRequest&lt;any&gt; = request.clone({<br>        headers: request.headers.set(&#39;Authorization&#39;, &#39;Bearer &#39; + token)<br>      })<br>      return next.handle(newRequest).pipe(<br>        catchError((error: HttpErrorResponse) =&gt; {<br>          if (error.status === 403) {<br>            return this.http.get&lt;IPowerBiTokenResponse&gt;(environment.backendAPIUrl + &quot;/api/azure-ad-access-token&quot;)<br>              .pipe(<br>                retry(5),<br>                mergeMap(token =&gt; {<br>                  if (token) {<br>                    localStorage.setItem(&quot;azure-ad-access-token&quot;, token.access_token)<br>                    const newHeaders = request.headers.set(&#39;Authorization&#39;, `Bearer ${token.access_token}`)<br>                    const newRequest = request.clone({ headers: newHeaders })<br>                    return next.handle(newRequest)<br>                  }<br>                }),<br>              )<br>          }<br>        })<br>      );<br>    }<br>    return next.handle(request);<br>  }<br>}</pre><p>You don’t actually need an interceptor, but I preferred that.</p><pre>{<br>  &quot;datasetId&quot;: &quot;cfafbeb1-8037-4d0c-896e-a46fb27ff229&quot;,<br>  &quot;id&quot;: &quot;5b218778-e7a5-4d73-8187-f10824047715&quot;,<br>  &quot;name&quot;: &quot;SalesMarketing&quot;,<br>  &quot;webUrl&quot;: &quot;https://app.powerbi.com//reports/5b218778-e7a5-4d73-8187-f10824047715&quot;,<br>  &quot;embedUrl&quot;: &quot;https://app.powerbi.com/reportEmbed?reportId=5b218778-e7a5-4d73-8187-f10824047715&quot;<br>}</pre><p>That’s the <strong>metadata</strong> we were talking about!<br>Now, we need to get an <strong>embed token</strong> for this report.</p><h4>How To Get Embed Token for Reports</h4><p>We’ll use <a href="https://learn.microsoft.com/en-us/rest/api/power-bi/embed-token/generate-token">generate token endpoint</a> of <strong>Power BI Rest API</strong> to get an <strong>embed token</strong> for a report/ reports.</p><p>There is a limit:</p><ul><li>Maximum 50 datasets.</li><li>Maximum 50 target workspaces.</li><li>Maximum 50 reports.</li></ul><p>Can be used to generate an <strong>embed token</strong> in one request.</p><pre>getEmbedToken(datasetId: string, reportId: string) {<br>    const body = {<br>      datasets: [<br>        {<br>          id: datasetId<br>        }<br>      ],<br>      reports: [<br>        {<br>          id: reportId<br>        }<br>      ]<br>    }<br>    return this.http.post&lt;IPowerBiEmbedTokenResponse&gt;(`${environment.powerBIRestAPIUrl}GenerateToken`, body)<br>}</pre><p>We have all the required values to embed our report.</p><h4>How to Embed the Report?</h4><pre>&lt;powerbi-report <br>    [embedConfig]=&quot;getPowerBIEmbedConfig(configDto)&quot; <br>    [cssClassName]=&quot;reportClass&quot; <br>    [phasedEmbedding]=&quot;false&quot;<br>    [eventHandlers]=&quot;eventHandlersMap&quot; <br>    *ngIf=&quot;configDto$ | async as configDto&quot;&gt;<br>&lt;/powerbi-report&gt;</pre><pre>getPowerBIEmbedConfig(configDto: IPowerBiConfigDto): IEmbedConfiguration {<br>    return {<br>      type: &quot;report&quot;,<br>      id: configDto.id,<br>      embedUrl: configDto.embedUrl,<br>      accessToken: configDto.accessToken,<br>      tokenType: models.TokenType.Embed,<br>      settings: {<br>        background: models.BackgroundType.Transparent,<br>      }<br>    }<br>}</pre><p><strong>getPowerBIEmbedConfig()</strong> maps the result I gathered from the Power BI Rest API into IEmbedConfiguration type.</p><p><a href="https://playgroundbe-bck-1.azurewebsites.net/Reports/SampleReport">Sample report for testing.</a> You can make a HTTP get request to this endpoint and receive an example result in order to use and test for embedding. <br>It returns all required parameters.</p><p>Also, Microsoft has a <a href="https://github.com/microsoft/PowerBI-client-angular#demo">demo </a>application.</p><h4>How to Refresh Embed Token</h4><p>There is a way to <a href="https://learn.microsoft.com/en-us/javascript/api/overview/powerbi/refresh-token#automatically-refresh-token">automatically refresh token</a> if you’re following <strong>Embed for Your Organization</strong> scenario. Both <strong>Azure AD Access Token</strong> and <strong>Embed Token</strong> has an expire time. In order to get a new E<strong>mbed Token</strong>, we need to use <strong>Azure AD Access Token</strong>. If <strong>Azure AD Access Token</strong> is expired, then we can’t refresh our E<strong>mbed Token</strong>. First things first, let’s see how to refresh our <strong>Azure AD Access Token</strong></p><p>I have an interceptor for refreshing my <strong>Azure AD Access Token</strong>. It returns me 403 HTTP Error Code if my token is expired when I make a call to generate a new <strong>Embed Token</strong>. I can catch this error and make a HTTP call to my application’s backend to receive an <strong>Azure AD Access Token</strong>.</p><pre>@Injectable()<br>export class PowerBiRestAPIInterceptor implements HttpInterceptor {<br><br>  constructor(<br>    private readonly http: HttpClient<br>  ) { }<br><br>  intercept(request: HttpRequest&lt;unknown&gt;, next: HttpHandler): Observable&lt;HttpEvent&lt;unknown&gt;&gt; {<br>    if (request.url.indexOf(&quot;api.powerbi.com/v1.0/myorg&quot;) &gt; -1) {<br>      const token = localStorage.getItem(&quot;azure-ad-access-token&quot;)<br>      const newRequest: HttpRequest&lt;any&gt; = request.clone({<br>        headers: request.headers.set(&#39;Authorization&#39;, &#39;Bearer &#39; + token)<br>      })<br>      return next.handle(newRequest).pipe(<br>        catchError((error: HttpErrorResponse) =&gt; {<br>          if (error.status === 403) {<br>            return this.http.get&lt;IPowerBiTokenResponse&gt;(environment.backendAPIUrl + &quot;/api/azure-ad-access-token&quot;)<br>              .pipe(<br>                retry(5),<br>                mergeMap(token =&gt; {<br>                  if (token) {<br>                    localStorage.setItem(&quot;azure-ad-access-token&quot;, token.access_token)<br>                    const newHeaders = request.headers.set(&#39;Authorization&#39;, `Bearer ${token.access_token}`)<br>                    const newRequest = request.clone({ headers: newHeaders })<br>                    return next.handle(newRequest)<br>                  }<br>                }),<br>              )<br>          }<br>        })<br>      );<br>    }<br>    return next.handle(request);<br>  }<br>}</pre><p>For <strong>Embed Token, </strong>unfortunately<strong>, </strong>we cannot use interceptor because Power BI’s iframe uses this token to make HTTP requests. <a href="https://learn.microsoft.com/en-us/javascript/api/overview/powerbi/refresh-token#manual-token-refresh-example">The way Microsoft recommends</a> is that frequently check if the token is expired and if it is, refresh it.</p><pre>source = timer(undefined, 30000);<br><br>private refreshPowerBItokens(reportId: string, datasetId: string) {<br>    const MINUTES_BEFORE_EXPIRATION = 10;<br><br>    const subscription = this.source.subscribe(_ =&gt;<br>      this.checkTokenAndUpdate(MINUTES_BEFORE_EXPIRATION, reportId, datasetId));<br><br>    this.subscriptions.push(subscription);<br>  }<br><br>  private checkTokenAndUpdate(MINUTES_BEFORE_EXPIRATION: number, reportId: string, datasetId: string) {<br>    const tokenExpiration = localStorage.getItem(&quot;embed_token_exp&quot;);<br><br>    const currentTime = Date.now();<br>    const expiration = Date.parse(tokenExpiration);<br><br>    const timeUntilExpiration = expiration - currentTime;<br>    const timeToUpdate = MINUTES_BEFORE_EXPIRATION * 60 * 1000;<br><br>    if (timeUntilExpiration &lt;= timeToUpdate) {<br>      this.updateToken(reportId, datasetId);<br>    }<br>  }<br><br>  private async updateToken(reportId: string, datasetId: string) {<br>    const powerBIToken = await this.powerBIService.getPowerBiToken(reportId, {}).toPromise()<br>    localStorage.setItem(&quot;azure-ad-access-token&quot;, powerBIToken.access_token)<br><br>    const embedToken = await this.powerBIService.getEmbedToken(datasetId, reportId).toPromise()<br>    const date = new Date(embedToken.expiration);<br>    const locale = date.toString()<br>    localStorage.setItem(&quot;embed_token_exp&quot;, locale)<br><br>    await this.reportObj.getReport().setAccessToken(embedToken.token)<br>  }</pre><p>That’s it! Thanks for reading. If you have any question, please leave a comment. I’d love to answer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8a7996552bf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>