The first to open Excel catalyst 47th wave -Excel of interconnection with PowerBIDeskTop

When abroad in the pursuit of open source software, and generated a lot of high-quality open source code on GitHub and other platforms, but in the country but in the harvest of white blowing an IQ of tax paid upsurge of knowledge, really sad.
But to share the spirit of the Internet, so bring more people to share the benefit.
In PowerBI field, there has been very good DAXStudio and Tabular Editor and other open source tools, far-reaching. Whereby, Excel catalyst also decided to the core, but also PowerBI population eager to functional point of open source.
I hope to benefit from the group, not to be considered as it has, and continues to be a continuation of the use of information asymmetry harvest IQ taxes, and it is best to press the open source principle, the signature on the code source when quoting.

Cipian corresponding functions implemented by: Wave 3 - (connection PowerbiDesktop Excel pivot table data model) and PowerbiDesktop interconnection https://www.jianshu.com/p/e05460ad407d

How to identify the service instance SSAS currently open PowerBIDeskTop the computer turned on?

Because time is running PowerBIDeskTop, it is to open an instance of SSAS, and turn on the Sqlserver similar, but limited access to the machine function, specific form can be viewed on the Task Manager to have msmdsrv.exe process.

Open the file after Pbix process msmdsrv.exe

When you open multiple pbix file, there will be more msmdsrv.exe process, the core connection PowerBIDeskTop Excel, it has become recognized as the port number msmdsrv.exe open.

And even when recognized port number, if there are multiple msmdsrv.exe run at the same time, you also need the port number different msmdsrv.exe opened by correspondence back to the original PowerBIDeskTop open Pbix file.

Associated with the file name only in, when the user views, in order to distinguish the specific port to which the corresponding connecting msmdsrv.exe model belongs, ultimately through connection port number required to achieve the corresponding file pbix connected to the data corresponding to the desired model in the past.

Specific code

Excel catalyst technical difficulties to achieve the above, using the open DAXStudio code snippet.

The old rule, first create an entity class, used to store some of the key information.

    class PbidFileInfo
    {
        public string FileName { get; set; }
        public int Port { get; set; }
        public string DbName { get; set; }

        public string ModelName { get; set; }

    }

Information on PowerBIDeskTop opened by the SSAS instance port number and the corresponding pbix file name, etc. available through the following code, return List list.


public static List<Entity.PbidFileInfo> GetPbidPortTittleMappings()
        {
            List<Entity.PbidFileInfo> pbidPortTittleMappings = new List<Entity.PbidFileInfo>();
            ManagementClass mgmtClass = new ManagementClass("Win32_Process");
            foreach (ManagementObject process in mgmtClass.GetInstances())
            {
                string processName = process["Name"].ToString().ToLower();
                if (processName == "msmdsrv.exe")
                {

                    // get the process pid
                    System.UInt32 pid = (System.UInt32)process["ProcessId"];
                    var parentPid = int.Parse(process["ParentProcessId"].ToString());
                    var parentTitle = "";
                    if (parentPid > 0)
                    {
                        var parentProcess = Process.GetProcessById(parentPid);
                        //if (parentProcess.ProcessName == "devenv") _icon = EmbeddedSSASIcon.Devenv;
                        parentTitle = parentProcess.MainWindowTitle;
                        if (parentTitle.Length == 0)
                        {
                            // for minimized windows we need to use some Win32 api calls to get the title
                            parentTitle = GetWindowTitle(parentPid);
                        }
                    }
                    // Get the command line - can be null if we don't have permissions
                    // but should have permission for PowerBI msmdsrv as it will have been
                    // launched by the current user.
                    string cmdLine = null;
                    if (process["CommandLine"] != null)
                    {
                        cmdLine = process["CommandLine"].ToString();
                        try
                        {
                            var rex = new System.Text.RegularExpressions.Regex("-s\\s\"(?<path>.*)\"");
                            var m = rex.Matches(cmdLine);
                            if (m.Count == 0) continue;
                            string msmdsrvPath = m[0].Groups["path"].Captures[0].Value;
                            var portFile = string.Format("{0}\\msmdsrv.port.txt", msmdsrvPath);
                            if (System.IO.File.Exists(portFile))
                            {
                                string sPort = System.IO.File.ReadAllText(portFile, Encoding.Unicode);
                                string cnnString = cnnString = $"localhost:{sPort}";
                                using (AMO.Server server = new AMO.Server())
                                {
                                    server.Connect(cnnString);
                                    string dbName = server.Databases[0].Name;
                                    string modelName = server.Databases[0].Model.Name;

                                    pbidPortTittleMappings.Add(new Entity.PbidFileInfo()
                                    {
                                        FileName = parentTitle.Replace(" - Power BI Desktop", ""),
                                        Port = int.Parse(sPort),
                                        DbName = dbName,
                                        ModelName = modelName
                                    });
                                }
                            }
                        }
                        catch (Exception)
                        {
                        }
                    }
                }
            }
            return pbidPortTittleMappings;
        }


        //#region PInvoke calls to get the window title of a minimize window
        delegate bool EnumThreadDelegate(IntPtr hWnd, IntPtr lParam);

        [DllImport("user32.dll")]
        static extern bool IsWindowVisible(IntPtr hWnd);


        [DllImport("user32.dll")]
        static extern bool EnumThreadWindows(int dwThreadId, EnumThreadDelegate lpfn,
            IntPtr lParam);

        private static IEnumerable<IntPtr> EnumerateProcessWindowHandles(int processId)
        {
            var handles = new List<IntPtr>();

            foreach (ProcessThread thread in Process.GetProcessById(processId).Threads)
                EnumThreadWindows(thread.Id,
                    (hWnd, lParam) => { handles.Add(hWnd); return true; }, IntPtr.Zero);

            return handles;
        }

        private const uint WM_GETTEXT = 0x000D;

        [DllImport("user32.dll", CharSet = CharSet.Auto)]
        static extern IntPtr SendMessage(IntPtr hWnd, uint Msg, int wParam,
            StringBuilder lParam);

        private static string GetWindowTitle(int procId)
        {
            foreach (var handle in EnumerateProcessWindowHandles(procId))
            {
                StringBuilder message = new StringBuilder(1000);
                if (IsWindowVisible(handle))
                {
                    SendMessage(handle, WM_GETTEXT, message.Capacity, message);
                    if (message.Length > 0) return message.ToString();
                }

            }
            return "";
        }

Code above idea is: under the use ManagementClass Win32_Process, to obtain the corresponding msmdsrv.exe pid.

Some systems through the API function, to obtain the corresponding title.

Reuse characteristic of CommandLine, take the path to the corresponding mating msmdsrv.exe regular path splicing process and obtain the final msmdsrv.port.txt file full path. The path of the machine as the author is
C: \ Users \ Administrator \ Microsoft \ Power BI Desktop Store App \ AnalysisServicesWorkspaces \ AnalysisServicesWorkspace115089896 \ Data \ msmdsrv.port.txt

C:\Users\Administrator\Microsoft\Power BI Desktop Store App\AnalysisServicesWorkspaces\AnalysisServicesWorkspace1855860078\Data\msmdsrv.port.txt

Reuse port number information is stored in this file property, ultimately msmdsrv.exe different port numbers corresponding to get hands.

Reuse AMO object model, also read this database name and port number under Model name to.

After the final to get together all the information, you can go back to the Excel client to initiate access connection.
And at the user level, use the form readability visualize key information for users to choose a different model.

Display critical information for users to choose on the Excel client

        private void formPbidNewConnect_Load(object sender, EventArgs e)
        {
            this.dataGridView1.SelectionMode = DataGridViewSelectionMode.FullRowSelect;
            List<Entity.PbidFileInfo> pbidPortTittleMappings = PbidConnection.GetPbidPortTittleMappings();
            foreach (var item in pbidPortTittleMappings)
            {
                this.dataGridView1.Rows.Add(new object[] { item.Port, item.FileName,item.DbName,item.ModelName });
            }
            this.dataGridView1.Rows[0].Selected = true;
        }

In the PivotTable level, simply construct a Oledb connection with the provider MSOLAP can.
Specific code as follows:

        private void btnEnter_Click(object sender, EventArgs e)
        {
            DataGridViewRow row = this.dataGridView1.SelectedRows[0];
            Entity.PbidFileInfo pbidFileInfo = Common.GetPbidFileInfo(row);
            Excel.WorkbookConnection wkbcnn;
            if (Common.ExcelApp.ActiveWorkbook.Connections.Cast<Excel.WorkbookConnection>().Any(s=>s.Name==pbidFileInfo.FileName))
            {
                Common.ExcelApp.ActiveWorkbook.Connections[pbidFileInfo.FileName].Delete();
            }
            string wkbCnnString = $"OLEDB;Provider=MSOLAP;Integrated Security=SSPI;Persist Security Info=True;Data Source=localhost:{pbidFileInfo.Port};Initial Catalog={pbidFileInfo.DbName};";
            Common.ExcelApp.ActiveWorkbook.Connections.Add(pbidFileInfo.FileName, "pbidConnection", wkbCnnString, pbidFileInfo.ModelName, 1);
            Excel.Worksheet wht = Common.ExcelApp.Worksheets.Add();
            wkbcnn = Common.ExcelApp.ActiveWorkbook.Connections[pbidFileInfo.FileName];
            Excel.PivotCache pvtCache = Common.ExcelApp.ActiveWorkbook.PivotCaches().Create(Excel.XlPivotTableSourceType.xlExternal, wkbcnn);
            pvtCache.CreatePivotTable(wht.Range["A1"]);
            this.Close();
        }

Epilogue

Nothing can not be shared, in order to healthy and prosperous communities, Excel catalyst to the essence of the most commercially valuable code contributions to the community, but also to the voice of the Chinese community to be more loud, out of international influence.

Technical exchange QQ group

QQ group name: Excel catalyst open discussion groups, QQ group number: 788 145 319
Excel catalyst dimensional code open source discussion groups

About Excel catalyst

Excel catalyst name, first a public micro-channel number, then shun its name, officially launched the Excel plug-in, plug-continuous updates, the update cycle depends on my time may be able to fight for one week on a line function modules. Excel catalyst plug-permanent commitment to individual users free of charge!

Excel catalyst plugin uses the latest deployment of technology, once installed, all future updates automatically update is complete, no need to repeat concerns updates, manually download the installation package to reinstall, you can always keep the latest version with a single installation!

The catalyst Excel plug-in download link: https://pan.baidu.com/s/1Iz2_NZJ8v7C9eqhNjdnP3Q

Contact the author

No public

取名催化剂,因Excel本身的强大,并非所有人能够立马享受到,大部分人还是在被Excel软件所虐的阶段,就是头脑里很清晰想达到的效果,而且高手们也已经实现出来,就是自己怎么弄都弄不出来,或者更糟的是还不知道Excel能够做什么而停留在不断地重复、机械、手工地在做着数据,耗费着无数的青春年华岁月。所以催生了是否可以作为一种媒介,让广大的Excel用户们可以瞬间点燃Excel的爆点,无需苦苦地挣扎地没日没夜的技巧学习、高级复杂函数的烧脑,最终走向了从入门到放弃的道路。

最后Excel功能强大,其实还需树立一个观点,不是所有事情都要交给Excel去完成,也不是所有事情Excel都是十分胜任的,外面的世界仍然是一个广阔的世界,Excel只是其中一枚耀眼的明星,还有其他更多同样精彩强大的技术、工具等。*Excel催化剂也将借力这些其他技术,让Excel能够发挥更强大的爆发!

关于Excel催化剂作者

姓名:李伟坚,从事数据分析工作多年(BI方向),一名同样在路上的学习者。
服务过行业:零售特别是鞋服类的零售行业,电商(淘宝、天猫、京东、唯品会)

技术路线从一名普通用户,通过Excel软件的学习,从此走向数据世界,非科班IT专业人士。
历经重重难关,终于在数据的道路上达到技术平原期,学习众多的知识不再太吃力,同时也形成了自己的一套数据解决方案(数据采集、数据加工清洗、数据多维建模、数据报表展示等)。

擅长技术领域:Excel等Office家族软件、VBA&VSTO的二次开发、Sqlserver数据库技术、Sqlserver的商业智能BI技术、Powerbi技术、云服务器布署技术等等。

2018 began his career made a major adjustment, from the original full-time job, turned freelance, no fixed income, temporarily on the road ahead is not clear, bitter return to full-time job, for Excel catalyst operations and development must be greatly affected (within the time could not maintain full-time job can not just put the results in a work published in time, the time outside of work is very limited, because he has thirty years of age, family responsibility).

And the majority of advocates with expectations: Excel catalyst has been able to run down, I have the benefit of the group were able to support ( multi-message encouragement, friend circle under forwarded the recommendation under small a reward and the most focused and where the company can and recommended recommended peers, so I can maximize the value of technology in your company to achieve a win-win (you can imagine how the data is preliminary consultant or small projects to develop forms of cooperation).

Guess you like

Origin www.cnblogs.com/ExcelCuiHuaJi/p/11225095.html