<commit_before>﻿using System;
using System.Configuration;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;
using Microsoft.Rest;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Security.Claims;
using pbipaembed.Models;

namespace pbipaembed.Controllers
{
    public class ISVCannedController : Controller
    {
        private static readonly string AuthorityUrl = ConfigurationManager.AppSettings["authorityUrl"];
        public static readonly string ResourceUrl = ConfigurationManager.AppSettings["resourceUrl"];
        private static readonly string ClientId = ConfigurationManager.AppSettings["clientId"];
        private static readonly string ApiUrl = ConfigurationManager.AppSettings["apiUrl"];
        private static readonly string GroupId = ConfigurationManager.AppSettings["groupId"];
        private static readonly string EmbedUrlBase = ConfigurationManager.AppSettings["embedUrlBase"];
        private static readonly AuthenticationContext authenticationContext = new AuthenticationContext(AuthorityUrl);

        private string accessToken;

        public ActionResult Index()
        {
            return View();
        }

        private async Task<IPowerBIClient> CreatePowerBIClientForISV()
        {
            var credential = new UserPasswordCredential(MvcApplication.pbiUserName, MvcApplication.pbiPassword);
            var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);
            var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
            var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials);

            return client;
        }
                
        [Authorize]
        public async Task<ActionResult> ListReports()
        {
            var viewModel = new ReportsViewModel();
            using (var client = await CreatePowerBIClientForISV())
            {
                var reports = await client.Reports.GetReportsInGroupAsync(GroupId);
                viewModel.Reports = reports.Value.ToList();
            }

            return View(viewModel);
        }

        [Authorize]
        public async Task<ActionResult> EmbedReport()
        {
            string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            string reportId = Request.Form["SelectedReport"].ToString();
            using (var client = await CreatePowerBIClientForISV())
            {
                var report = client.Reports.GetReportInGroup(GroupId, reportId);
                GenerateTokenRequest generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true); //no role specified means you can access everything!
                // Generate Embed Token.
                if (!tenantID.StartsWith("1"))  // the owner tenant of this app starts with 1, which can access everything
                {
                    switch (report.Name.ToLower())
                    {
                        case "adventureworks":
                            // for non Analysis Service, map user to Username()
                            var salesUser = new EffectiveIdentity(
                                username: "adventure-works\\pamela0",
                                roles: new List<string> { "Sales" },
                                datasets: new List<string> { report.DatasetId });
                            generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List<EffectiveIdentity> { salesUser });
                            break;
                        case "testaasrls":
                            // for Analysis Service, map user to CustomData()
                            var embedUser = new EffectiveIdentity(
                                username: MvcApplication.pbiUserName,
                                customData: "embed",
                                roles: new List<string> { "Sales Embedded" },
                                datasets: new List<string> { report.DatasetId });
                            generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List<EffectiveIdentity> { embedUser });
                            break;
                    }
                }
                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, reportId, generateTokenRequestParameters);
                // Refresh the dataset
                // await client.Datasets.RefreshDatasetInGroupAsync(GroupId, report.DatasetId);

                // Generate Embed Configuration.
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse,
                    EmbedUrl = report.EmbedUrl,
                    Id = reportId,
                    Name = report.Name<commit_msg>bi-directional filtering with AAS, must reference security table, not recommend.<commit_after>﻿using System;
using System.Configuration;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.PowerBI.Api.V2;
using Microsoft.PowerBI.Api.V2.Models;
using Microsoft.Rest;
using System.Threading.Tasks;
using System.Collections.Generic;
using System.Linq;
using System.Web.Mvc;
using System.Security.Claims;
using pbipaembed.Models;

namespace pbipaembed.Controllers
{
    public class ISVCannedController : Controller
    {
        private static readonly string AuthorityUrl = ConfigurationManager.AppSettings["authorityUrl"];
        public static readonly string ResourceUrl = ConfigurationManager.AppSettings["resourceUrl"];
        private static readonly string ClientId = ConfigurationManager.AppSettings["clientId"];
        private static readonly string ApiUrl = ConfigurationManager.AppSettings["apiUrl"];
        private static readonly string GroupId = ConfigurationManager.AppSettings["groupId"];
        private static readonly string EmbedUrlBase = ConfigurationManager.AppSettings["embedUrlBase"];
        private static readonly AuthenticationContext authenticationContext = new AuthenticationContext(AuthorityUrl);

        private string accessToken;

        public ActionResult Index()
        {
            return View();
        }

        private async Task<IPowerBIClient> CreatePowerBIClientForISV()
        {
            var credential = new UserPasswordCredential(MvcApplication.pbiUserName, MvcApplication.pbiPassword);
            var authenticationResult = await authenticationContext.AcquireTokenAsync(ResourceUrl, ClientId, credential);
            var tokenCredentials = new TokenCredentials(authenticationResult.AccessToken, "Bearer");
            var client = new PowerBIClient(new Uri(ApiUrl), tokenCredentials);

            return client;
        }
                
        [Authorize]
        public async Task<ActionResult> ListReports()
        {
            var viewModel = new ReportsViewModel();
            using (var client = await CreatePowerBIClientForISV())
            {
                var reports = await client.Reports.GetReportsInGroupAsync(GroupId);
                viewModel.Reports = reports.Value.ToList();
            }

            return View(viewModel);
        }

        [Authorize]
        public async Task<ActionResult> EmbedReport()
        {
            string tenantID = ClaimsPrincipal.Current.FindFirst("http://schemas.microsoft.com/identity/claims/tenantid").Value;

            string reportId = Request.Form["SelectedReport"].ToString();
            using (var client = await CreatePowerBIClientForISV())
            {
                var report = client.Reports.GetReportInGroup(GroupId, reportId);
                GenerateTokenRequest generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true); //no role specified means you can access everything!
                // Generate Embed Token.
                if (!tenantID.StartsWith("1"))  // the owner tenant of this app starts with 1, which can access everything
                {
                    switch (report.Name.ToLower())
                    {
                        case "adventureworks":
                            // for non Analysis Service, map user to Username()
                            var salesUser = new EffectiveIdentity(
                                username: "adventure-works\\pamela0",
                                roles: new List<string> { "Sales" },
                                datasets: new List<string> { report.DatasetId });
                            generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List<EffectiveIdentity> { salesUser });
                            break;
                        case "testaasrls":
                            // for Analysis Service, map user to CustomData()
                            var embedUser = new EffectiveIdentity(
                                username: MvcApplication.pbiUserName,
                                customData: "embed",
                                roles: new List<string> { "Sales Embedded" },
                                datasets: new List<string> { report.DatasetId });
                            generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List<EffectiveIdentity> { embedUser });
                            break;
                    }
                }
                else
                {
                    switch (report.Name.ToLower())
                    {
                        case "testaasrls":
                            // for Analysis Service, map user to CustomData()
                            var embedUser = new EffectiveIdentity(
                                username: MvcApplication.pbiUserName,
                                customData: "<EMAIL>",
                                roles: new List<string> { "Sales BiDi" },
                                datasets: new List<string> { report.DatasetId });
                            generateTokenRequestParameters = new GenerateTokenRequest(
                            accessLevel: "edit", allowSaveAs: true,
                            identities: new List<EffectiveIdentity> { embedUser });
                            break;
                    }
                }
                var tokenResponse = await client.Reports.GenerateTokenInGroupAsync(GroupId, reportId, generateTokenRequestParameters);
                // Refresh the dataset
                // await client.Datasets.RefreshDatasetInGroupAsync(GroupId, report.DatasetId);

                // Generate Embed Configuration.
                var embedConfig = new EmbedConfig()
                {
                    EmbedToken = tokenResponse,
                    EmbedUrl = report.EmbedUrl,
                    Id = reportId,
                    Name = report.Name
{'fraction_non_alphanumeric': 0.07276707530647986, 'fraction_numerical': 0.0008756567425569177, 'mean_word_length': 1.7547033285094067, 'pattern_counts': {'":': 5, '<': 25, '<?xml version=': 0, '>': 25, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 5, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '3830826', 'n_tokens_mistral': 2532, 'n_tokens_neox': 2476, 'n_words': 625}