开发者

Changing connection data in PowerPivot file

So I've run into an interesting problem. I need to specify a custom WHERE clause in a PowerPivot query. I must change it based on external conditions. I would like to edit the file and save a copy. Any idea how to do this? I op开发者_如何学编程ened the PowerPivot file from binary, but it appears encrypted...


You can go to existing connections, and then make an update there. If you open the same data source (SQL, SSRS, or anything else) again instead of changing parameters on the existing connection, it will slow your perf as PowerPivot will treat those as separate connections.


Solution was to open the Excel workbook up as a Zip (using the Package class).

If you are looking to modify the queries, you can. The file at /xl/customData/item1.data is a backup file that represents the PowerPivot database (which is just an Analysis Services database running in Vertipaq mode) used to process queries. You need to restore the file to a SSAS instance running in Vertipaq mode. Once that's done, script the queries as an ALTER script. Modify the scripts (in this case, replacing @projectId with my actual projectID), then run them against the database. Once all this is done, back the database up and put back into the Excel workbook. That modifies the queries.

The connection data is stored in the /xl/connections.xml file. Open that up, modify, and replace. Repack it all up again, and now you have a workbook again.

Here's the code I made. You will have to call the methods as you need. Basic idea is there, though...

    const string DBName = "Testing";
    const string OriginalBackupPath = @"\\MyLocation\BKUP.abf";
    const string ModifiedBackupPath = @"\\MyLocation\BKUPAfter.abf";
    const string ServerPath = @"machineName\powerpivot";

    private static readonly Server srv = new Server();
    private static readonly Scripter scripter = new Scripter();
    private static Database db;

    private static byte[] GetPackagePartContents(string packagePath, string partPath)
    {
        var pack = Package.Open(packagePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        var part = pack.GetPart(new Uri(partPath, UriKind.Relative));
        var stream = part.GetStream();
        var b = new byte[stream.Length];
        stream.Read(b, 0, b.Length);
        stream.Flush();
        stream.Close();
        pack.Flush();
        pack.Close();
        return b;
    }

    private static void WritePackagePartContents(string packagePath, string partPath, byte[] contents)
    {
        var uri = new Uri(partPath, UriKind.Relative);
        var pack = Package.Open(packagePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
        var part = pack.GetPart(uri);
        var type = part.ContentType;
        pack.DeletePart(uri);
        pack.CreatePart(uri, type);
        part = pack.GetPart(uri);
        var stream = part.GetStream();
        stream.Write(contents, 0, contents.Length);
        stream.Flush();
        stream.Close();
        pack.Flush();
        pack.Close();
    }

    private static void RestoreBackup(string server, string dbName, string backupPath)
    {
        srv.Connect(server);
        if (srv.Databases.FindByName(dbName) != null) { srv.Databases.FindByName(dbName).Drop(); srv.Update(); }
        srv.Restore(backupPath, dbName, true);
        srv.Update();
        srv.Refresh();
    }

    private static void WriteContentsToFile(byte[] contents, string filePath)
    {
        var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        fileStream.Write(contents, 0, contents.Length);
        fileStream.Flush();
        fileStream.Close();
    }

    private static byte[] ReadContentsFromFile(string filePath)
    {
        var fileStream = File.Open(filePath, FileMode.OpenOrCreate, FileAccess.Write);
        var b = new byte[fileStream.Length];
        fileStream.Read(b, 0, b.Length);
        fileStream.Flush();
        fileStream.Close();
        return b;
    }

    private static XDocument GetAlterScript(MajorObject obj)
    {
        var stream = new MemoryStream();
        var streamWriter = XmlWriter.Create(stream);
        scripter.ScriptAlter(new[] { obj }, streamWriter, false);
        streamWriter.Flush();
        streamWriter.Close();
        stream.Flush();
        stream.Position = 0;
        var b = new byte[stream.Length];
        stream.Read(b, 0, b.Length);
        var alterString = new string(Encoding.UTF8.GetString(b).ToCharArray().Where(w => w != 65279).ToArray());
        var alter = XDocument.Parse(alterString);
        stream.Close();
        return alter;
    }

    private static void ExecuteScript(string script)
    {
        srv.Execute(script);
        srv.Update();
        db.Process();
        db.Refresh();
    }



    private static void ProcessPowerpointQueries(string bookUrl, string projectId)
    {
        byte[] b = GetPackagePartContents(bookUrl, "/xl/customData/item1.data");
        WriteContentsToFile(b, OriginalBackupPath);
        RestoreBackup(ServerPath, DBName, OriginalBackupPath);
        var db = srv.Databases.GetByName(DBName);
        var databaseView = db.DataSourceViews.FindByName("Sandbox");
        var databaseViewAlter = GetAlterScript(databaseView);
        var cube = db.Cubes.FindByName("Sandbox");
        var measureGroup = cube.MeasureGroups.FindByName("Query");
        var partition = measureGroup.Partitions.FindByName("Query");
        var partitionAlter = GetAlterScript(partition);
        var regex = new Regex(@"\s@projectid=\w*[ ,]");
        var newDatabaseViewAlter = databaseViewAlter.ToString().Replace(regex.Match(databaseViewAlter.ToString()).Value.Trim(',',' '), @"@projectid=" + projectId);
        ExecuteScript(newDatabaseViewAlter);
        var newPartitionAlter = partitionAlter.ToString().Replace(regex.Match(partitionAlter.ToString()).Value.Trim(',', ' '), @"@projectid=" + projectId);
        ExecuteScript(newPartitionAlter);
        db.Backup(ModifiedBackupPath, true);
        WritePackagePartContents(bookUrl, @"/xl/customData/item1.data", ReadContentsFromFile(ModifiedBackupPath));
        db.Drop();
        srv.Disconnect();
    }

    private static void ProcessWorkbookLinks(string bookUrl, string newCoreUrl)
    {
        var connectionsFile = GetPackagePartContents(bookUrl, @"/xl/connections.xml");
        var connectionsXml = Encoding.UTF8.GetString(connectionsFile);
        connectionsXml = connectionsXml.Replace(
            new Regex(@"Data Source=\S*;").Match(connectionsXml).Value.Trim(';'), @"Data Source=" + newCoreUrl);
        WritePackagePartContents(bookUrl, @"/xl/connections.xml", connectionsXml.Replace(@"https://server/site/", newCoreUrl).ToCharArray().Select(Convert.ToByte).ToArray());
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜