├── .vs
├── slnx.sqlite
└── PowerBiVisibility
│ └── v16
│ └── .suo
├── .gitignore
├── README.md
├── PowerBI Dependencies SQL Schema Creation.sql
├── LICENSE
└── PowerBI Visibility.ps1
/.vs/slnx.sqlite:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/granite-cs/PowerBiVisibility/HEAD/.vs/slnx.sqlite
--------------------------------------------------------------------------------
/.gitignore:
--------------------------------------------------------------------------------
1 | ## Ignore files
2 |
3 | *.dll
4 |
5 | # Visual Studio 2015/2017 cache/options directory
6 | .vs/
--------------------------------------------------------------------------------
/.vs/PowerBiVisibility/v16/.suo:
--------------------------------------------------------------------------------
https://raw.githubusercontent.com/granite-cs/PowerBiVisibility/HEAD/.vs/PowerBiVisibility/v16/.suo
--------------------------------------------------------------------------------
/README.md:
--------------------------------------------------------------------------------
1 | # PowerBiVisibility
2 | A script for researching PowerBI pbix files, useful for versioning and tracing DAX dependencies.
3 |
4 | There are 2 code files:
5 | - a Poweshell script which processes a .pbix file
6 | - a SQL script which creates a table and 3 views.
7 |
8 | A Video walkthrough can be seen here:
9 | https://www.youtube.com/watch?v=as_2b_UufxQ
10 |
or
11 | https://www.csgpro.com/blog/2019/12/how-to-reverse-engineer-a-power-bi-pbix-file/
12 |
--------------------------------------------------------------------------------
/PowerBI Dependencies SQL Schema Creation.sql:
--------------------------------------------------------------------------------
1 | /*
2 | (c) 2019 David Berglin
3 | This file is part of the PowerBiVisibility project.
4 | PowerBiVisibility is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
5 | PowerBiVisibility is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
6 | You should have received a copy of the GNU General Public License along with PowerBiVisibility. If not, see https://www.gnu.org/licenses/.
7 | */
8 |
9 | IF OBJECT_ID('[dbo].[Dependencies]', 'U') IS NULL -- U = Table... V = View... P = Stored Procedure
10 | begin
11 | print 'creating table [dbo].[Dependencies]' + ' ...' + convert(varchar, getdate(), 121)
12 |
13 | CREATE TABLE [dbo].[Dependencies](
14 | [DependencyId] [int] IDENTITY(1,1) NOT NULL,
15 | [Source] [varchar](400) NOT NULL, -- Where did this dependency come from (which PowerBI file or SSAS server ?)
16 | [ParentLocation] [varchar](400) NOT NULL, -- What tab(PowerBI) or table(SSAS) holds the dependency?
17 | [ParentName] [varchar](400) NOT NULL, -- What visual(PowerBI) or measure/column(SSAS) holds the dependency?
18 | [ParentAddress] [varchar](400) NOT NULL, -- Standardized 'Location'[Name]
19 | [ParentType] [varchar](40) NOT NULL, -- column/measure/visual
20 | [ChildLocation] [varchar](400) NULL, -- What table(SSAS) is depended upon by the parent?
21 | [ChildName] [varchar](400) NULL, -- What measure/column(SSAS) is depended upon by the parent?
22 | [ChildAddress] [varchar](400) NULL, -- Standardized 'Location'[Name]
23 | [ChildType] [varchar](40) NULL, -- column/measure
24 | [Content] [nvarchar](4000) NULL, -- the plan is to add Measure code into this column
25 | CONSTRAINT [PK_Dependencies] PRIMARY KEY CLUSTERED
26 | (
27 | [DependencyId] ASC
28 | )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
29 | ) ON [PRIMARY]
30 | end
31 | GO
32 |
33 | IF OBJECT_ID('[dbo].[vDependency_Scripts]', 'V') IS NOT NULL -- U = Table... V = View... P = Stored Procedure
34 | begin
35 | print 'deleting view [dbo].[vDependency_Scripts]' + ' ...' + convert(varchar, getdate(), 121)
36 | drop view [dbo].[vDependency_Scripts]
37 | end
38 | GO
39 | print 'creating view [dbo].[vDependency_Scripts]' + ' ...' + convert(varchar, getdate(), 121)
40 | GO
41 | CREATE VIEW [dbo].[vDependency_Scripts] AS
42 | /*
43 | (c) 2019 David Berglin
44 | This file is part of the PowerBiVisibility project.
45 | PowerBiVisibility is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
46 | PowerBiVisibility is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
47 | You should have received a copy of the GNU General Public License along with PowerBiVisibility. If not, see https://www.gnu.org/licenses/.
48 |
49 |
50 | Join to this view and replace values as needed, to generate scripts about dependencies
51 |
52 |
53 | usage example:
54 |
55 | select
56 | *
57 | , Replace(Replace(s.Scripts, '[ReplaceWithName]', DependencyChild), '[ReplaceWithScriptableName]', ScriptableDependencyChild) as [Child Scripts]
58 | , Replace(Replace(s.Scripts, '[ReplaceWithName]', ParentAddress), '[ReplaceWithScriptableName]', ScriptableParent) as [Parent Scripts]
59 | from cte_nested c
60 | join vDependency_Scripts s on 1 = 1
61 |
62 | */
63 | select '
64 | -- [ReplaceWithName] ...scripts below
65 |
66 | -- ALL my Child Dependencies
67 | Select *
68 | from [dbo].[vDependency_Children]
69 | where TopMostParent = ''[ReplaceWithScriptableName]''
70 | order by ChildAddress
71 |
72 | -- All Parents Who Depend on me
73 | Select *
74 | from [dbo].[vDependency_Parents]
75 | where DependencyChild = ''[ReplaceWithScriptableName]''
76 | order by ParentAddress
77 |
78 | -- ALL my DISTINCT Child Dependencies
79 | Select DISTINCT
80 | TopMostParent
81 | ,ChildType
82 | ,ChildAddress
83 | from [dbo].[vDependency_Children]
84 | where TopMostParent = ''[ReplaceWithScriptableName]''
85 | order by ChildAddress
86 |
87 | -- All DISTINCT Parents Who Depend on me
88 | Select DISTINCT
89 | DependencyChild
90 | ,ParentType
91 | ,ParentAddress
92 | from [dbo].[vDependency_Parents]
93 | where DependencyChild = ''[ReplaceWithScriptableName]''
94 | order by ParentAddress
95 |
96 | -- Raw Depencency Data about me
97 | Select *
98 | from [dbo].[Dependencies]
99 | where ChildAddress = ''[ReplaceWithScriptableName]''
100 | or ParentAddress = ''[ReplaceWithScriptableName]''
101 | Order By case when ChildAddress = ''[ReplaceWithScriptableName]'' then 0 else 1 end -- put parents at top, children at bottom
102 | ' as [Scripts]
103 |
104 | GO
105 |
106 | IF OBJECT_ID('[dbo].[vDependency_Parents]', 'V') IS NOT NULL -- U = Table... V = View... P = Stored Procedure
107 | begin
108 | print 'deleting view [dbo].[vDependency_Parents]' + ' ...' + convert(varchar, getdate(), 121)
109 | drop view [dbo].[vDependency_Parents]
110 | end
111 | GO
112 | print 'creating view [dbo].[vDependency_Parents]' + ' ...' + convert(varchar, getdate(), 121)
113 | GO
114 | CREATE VIEW [dbo].[vDependency_Parents] AS
115 | /*
116 | --------------------------------------------------------------
117 | (c) 2019 David Berglin
118 | This file is part of the PowerBiVisibility project.
119 | PowerBiVisibility is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
120 | PowerBiVisibility is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
121 | You should have received a copy of the GNU General Public License along with PowerBiVisibility. If not, see https://www.gnu.org/licenses/.
122 | --------------------------------------------------------------
123 | Purpose is to Find Visuals/Measures (who are Parents) by Dependencies (Children)
124 | This view will show PowerBI Visuals and SSAS Measures which depend on a particular item.
125 |
126 | populate [dbo].[Dependencies] using this Powershell scripts:
127 | PowerBI Visibility.ps1 ... use SQL output option
128 |
129 | research...
130 | select * from [dbo].[Dependencies]
131 | select * from [dbo].[Dependencies] where ChildAddress like '%[[]Total Hours]%' -- [[]text] handles square bracket in "Like" clause
132 |
133 | Sample Script
134 | select distinct *
135 | ,'Select * from [dbo].[vDependency_Children] where TopMostParent = '''+Replace(ParentAddress, '''', '''''')+'''' as [Script To Find Children Dependencies]
136 | ,'Select * from [dbo].[vDependency_Parents] where DependencyChild = '''+Replace(ParentAddress, '''', '''''')+'''' as [Script To Find Parents Who Depend on Me]
137 | from [dbo].[vDependency_Parents]
138 | order by ParentAddress
139 |
140 | Distinct Script
141 | Select distinct
142 | DependencyChild
143 | ,ParentType
144 | ,ParentAddress
145 | from [dbo].[vDependency_Parents]
146 | --------------------------------------------------------------
147 | */
148 |
149 | with cte_nested as ( -- holds nested dependency objects
150 |
151 | -- Select the 'normal' (not recursive, just top level) rows of data
152 | select
153 | 1 as Recursion
154 | ,d.ChildAddress as DependencyChild
155 | ,Replace(d.ParentAddress, '''', '''''') as ScriptableParent -- replace single quotes with two single quotes... for pasting into SQL Select Scripts
156 | ,Replace(d.ChildAddress, '''', '''''') as ScriptableDependencyChild -- replace single quotes with two single quotes... for pasting into SQL Select Scripts
157 | ,d.ChildType
158 | ,d.ChildAddress
159 | ,d.ChildLocation
160 | ,d.ChildName
161 | ,d.ParentType -- parent
162 | ,d.ParentAddress -- parent
163 | ,convert(varchar(5000), d.ParentAddress + isnull('
164 | <= ' + d.ChildAddress,'')) as [Trail]
165 | from [dbo].[Dependencies] d
166 | where d.ChildAddress is not null -- no need to pull in null dependencies
167 | and d.ChildAddress <> ''
168 |
169 | union all
170 |
171 | -- Recursively reach back into this same CTE to find nested data
172 | select
173 | n.Recursion + 1
174 | ,n.DependencyChild
175 | ,Replace(d.ParentAddress, '''', '''''') as ScriptableParent
176 | ,n.ScriptableDependencyChild
177 | ,d.ChildType
178 | ,d.ChildAddress
179 | ,d.ChildLocation
180 | ,d.ChildName
181 | ,d.ParentType -- parent
182 | ,d.ParentAddress -- parent
183 | ,convert(varchar(5000), d.ParentAddress + isnull('
184 | <= ' + n.[Trail], ''))
185 | from [dbo].[Dependencies] d
186 | join cte_nested n
187 | on n.ParentAddress = d.ChildAddress -- pull in the parent
188 | and d.ParentAddress <> ''
189 | and n.Recursion < 20
190 |
191 | )
192 |
193 | ----------------------------------------------------------------
194 | -- Get final results
195 | ----------------------------------------------------------------
196 | select distinct
197 | c.DependencyChild
198 | ,c.ParentType
199 | ,c.ParentAddress
200 | ,c.Recursion
201 | ,c.[Trail] + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) as [Trail]
202 | , Replace(Replace(s.Scripts, '[ReplaceWithName]', DependencyChild), '[ReplaceWithScriptableName]', ScriptableDependencyChild) as [Child Scripts]
203 | , Replace(Replace(s.Scripts, '[ReplaceWithName]', ParentAddress), '[ReplaceWithScriptableName]', ScriptableParent) as [Parent Scripts]
204 | from cte_nested c
205 | join vDependency_Scripts s on 1 = 1 -- no real join needed, this copies the simple text of the script generator, and replaces values to produce scripts you can copy/paste
206 |
207 |
208 | GO
209 | print 'finished view [dbo].[vDependency_Parents]' + ' ...' + convert(varchar, getdate(), 121)
210 |
211 |
212 | GO
213 | IF OBJECT_ID('[dbo].[vDependency_Children]', 'V') IS NOT NULL -- U = Table... V = View... P = Stored Procedure
214 | begin
215 | print 'deleting view [dbo].[vDependency_Children]' + ' ...' + convert(varchar, getdate(), 121)
216 | drop view [dbo].[vDependency_Children]
217 | end
218 | GO
219 | print 'creating view [dbo].[vDependency_Children]' + ' ...' + convert(varchar, getdate(), 121)
220 | GO
221 | CREATE VIEW [dbo].[vDependency_Children] AS
222 | /*
223 | --------------------------------------------------------------
224 | (c) 2019 David Berglin
225 | This file is part of the PowerBiVisibility project.
226 | PowerBiVisibility is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
227 | PowerBiVisibility is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
228 | You should have received a copy of the GNU General Public License along with PowerBiVisibility. If not, see https://www.gnu.org/licenses/.
229 | --------------------------------------------------------------
230 | Purpose is to Find Dependencies (Children) by Visuals/Measures (who are Parents)
231 | This view will show SSAS Measure and Column dependencies
232 |
233 | populate [dbo].[Dependencies] using this Powershell scripts:
234 | PowerBI Visibility.ps1 ... use SQL output option
235 |
236 | research...
237 | select * from [dbo].[Dependencies]
238 | select * from [dbo].[Dependencies] where ChildAddress like '%[[]Total Hours]%' -- [[]text] handles square bracket in "Like" clause
239 |
240 | Sample Script
241 | select distinct *
242 | ,'Select * from [dbo].[vDependency_Children] where TopMostParent = '''+Replace(ParentAddress, '''', '''''')+'''' as [Script To Find Children Dependencies]
243 | ,'Select * from [dbo].[vDependency_Parents] where DependencyChild = '''+Replace(ParentAddress, '''', '''''')+'''' as [Script To Find Parents Who Depend on Me]
244 | from [dbo].[vDependency_Children]
245 | order by ParentAddress
246 |
247 | Distinct Script
248 | select distinct
249 | TopMostParent
250 | ,ChildAddress
251 | from [dbo].[vDependency_Children]
252 |
253 | --------------------------------------------------------------
254 | */
255 |
256 |
257 | with cte_nested as ( -- holds nested dependency objects
258 |
259 | -- Select the 'normal' (not recursive, just top level) rows of data
260 | select
261 | 1 as Recursion
262 | ,d.ParentAddress as TopMostParent
263 | ,Replace(d.ParentAddress, '''', '''''') as ScriptableParent -- replace single quotes with two single quotes... for pasting into SQL Select Scripts
264 | ,Replace(d.ChildAddress, '''', '''''') as ScriptableChild -- replace single quotes with two single quotes... for pasting into SQL Select Scripts
265 | ,d.DependencyId
266 | ,d.ParentType
267 | ,d.ParentLocation
268 | ,d.ParentName
269 | ,d.ParentAddress
270 | ,d.ChildAddress
271 | ,d.ChildType
272 | ,convert(varchar(5000), d.Source
273 | + CHAR(13) + CHAR(10) + ' => ' + d.ParentLocation
274 | + CHAR(13) + CHAR(10) + ' => ' + d.ParentName
275 | + isnull(CHAR(13) + CHAR(10) + ' => ' + d.ChildAddress,'')) as [Trail]
276 | ,d.Content
277 | from [dbo].[Dependencies] d
278 | where d.ChildAddress is not null -- no need to pull in null dependencies
279 | and d.ChildAddress <> ''
280 |
281 | union all
282 |
283 | -- Recursively reach back into this same CTE to find nested data
284 | select
285 | n.Recursion + 1
286 | ,n.TopMostParent
287 | ,Replace(d.ParentAddress, '''', '''''') as ScriptableParent
288 | ,Replace(d.ChildAddress, '''', '''''') as ScriptableChild
289 | ,d.DependencyId
290 | ,d.ParentType
291 | ,d.ParentLocation
292 | ,d.ParentName
293 | ,d.ParentAddress
294 | ,d.ChildAddress
295 | ,d.ChildType
296 | ,convert(varchar(5000), n.[Trail] + isnull(CHAR(13) + CHAR(10) + ' => ' + d.ChildAddress, ''))
297 | ,d.Content
298 | from [dbo].[Dependencies] d
299 | join cte_nested n
300 | on n.ChildAddress = d.ParentAddress -- pull in the child
301 | and d.ParentAddress <> ''
302 | and n.ChildAddress <> ''
303 | and n.Recursion < 20
304 | )
305 |
306 | ----------------------------------------------------------------
307 | -- Get final results
308 | ----------------------------------------------------------------
309 | select distinct
310 | c.TopMostParent
311 | ,c.ParentType
312 | ,c.ParentLocation
313 | ,c.ParentName
314 | ,c.ParentAddress
315 | ,c.ChildType
316 | ,c.ChildAddress
317 | ,c.Recursion
318 | ,c.[Trail] + CHAR(13) + CHAR(10) + isnull(c.Content, '') + CHAR(13) + CHAR(10) + CHAR(13) + CHAR(10) as [Trail]
319 | , CASE WHEN ChildAddress = '' then ''
320 | else Replace(Replace(s.Scripts, '[ReplaceWithName]', ChildAddress), '[ReplaceWithScriptableName]', ScriptableChild) end as [Child Scripts]
321 | , Replace(Replace(s.Scripts, '[ReplaceWithName]', ParentAddress), '[ReplaceWithScriptableName]', ScriptableParent) as [Parent Scripts]
322 | from cte_nested c
323 | join vDependency_Scripts s on 1 = 1 -- no real join needed, this copies the simple text of the script generator, and replaces values to produce scripts you can copy/paste
324 |
325 |
326 | GO
327 | print 'finished view [dbo].[vDependency_Children]' + ' ...' + convert(varchar, getdate(), 121)
328 |
329 |
330 |
331 |
332 | GO
333 | IF Not Exists(
334 | -- Check for non PK Indexes
335 | SELECT *
336 | FROM sys.indexes
337 | WHERE object_id = OBJECT_ID('dbo.Dependencies')
338 | and type_desc <> 'CLUSTERED'
339 | )
340 | begin
341 | print 'creating indexes on Dependency Tables' + ' ...' + convert(varchar, getdate(), 121)
342 |
343 |
344 | CREATE NONCLUSTERED INDEX [idx_Dependency_ParentChildIdPType] ON [dbo].[Dependencies]
345 | (
346 | [ParentAddress] ASC,
347 | [ChildAddress] ASC,
348 | [DependencyId] ASC,
349 | [ParentType] ASC
350 | )
351 | INCLUDE ( [Source],
352 | [ParentLocation],
353 | [ParentName],
354 | [ChildType]) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
355 |
356 |
357 | CREATE NONCLUSTERED INDEX [idx_Dependency_ChildParentIdPType] ON [dbo].[Dependencies]
358 | (
359 | [ChildAddress] ASC,
360 | [ParentAddress] ASC,
361 | [DependencyId] ASC,
362 | [ParentType] ASC
363 | )
364 | INCLUDE ( [Source],
365 | [ParentLocation],
366 | [ParentName],
367 | [ChildType]) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
368 |
369 |
370 | CREATE NONCLUSTERED INDEX [idx_Dependency_ChildParentCType] ON [dbo].[Dependencies]
371 | (
372 | [ChildAddress] ASC,
373 | [ParentAddress] ASC,
374 | [ChildType] ASC
375 | )
376 | INCLUDE ( [ParentType],
377 | [ChildLocation],
378 | [ChildName]) WITH (SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF) ON [PRIMARY]
379 |
380 | print 'finished indexes on Dependency Tables' + ' ...' + convert(varchar, getdate(), 121)
381 | end
382 | else
383 | begin
384 | print 'exists: indexes on Dependency Tables' + ' ...' + convert(varchar, getdate(), 121)
385 | end
386 | GO
387 |
388 |
389 |
--------------------------------------------------------------------------------
/LICENSE:
--------------------------------------------------------------------------------
1 | GNU GENERAL PUBLIC LICENSE
2 | Version 3, 29 June 2007
3 |
4 | Copyright (C) 2007 Free Software Foundation, Inc.
5 | Everyone is permitted to copy and distribute verbatim copies
6 | of this license document, but changing it is not allowed.
7 |
8 | Preamble
9 |
10 | The GNU General Public License is a free, copyleft license for
11 | software and other kinds of works.
12 |
13 | The licenses for most software and other practical works are designed
14 | to take away your freedom to share and change the works. By contrast,
15 | the GNU General Public License is intended to guarantee your freedom to
16 | share and change all versions of a program--to make sure it remains free
17 | software for all its users. We, the Free Software Foundation, use the
18 | GNU General Public License for most of our software; it applies also to
19 | any other work released this way by its authors. You can apply it to
20 | your programs, too.
21 |
22 | When we speak of free software, we are referring to freedom, not
23 | price. Our General Public Licenses are designed to make sure that you
24 | have the freedom to distribute copies of free software (and charge for
25 | them if you wish), that you receive source code or can get it if you
26 | want it, that you can change the software or use pieces of it in new
27 | free programs, and that you know you can do these things.
28 |
29 | To protect your rights, we need to prevent others from denying you
30 | these rights or asking you to surrender the rights. Therefore, you have
31 | certain responsibilities if you distribute copies of the software, or if
32 | you modify it: responsibilities to respect the freedom of others.
33 |
34 | For example, if you distribute copies of such a program, whether
35 | gratis or for a fee, you must pass on to the recipients the same
36 | freedoms that you received. You must make sure that they, too, receive
37 | or can get the source code. And you must show them these terms so they
38 | know their rights.
39 |
40 | Developers that use the GNU GPL protect your rights with two steps:
41 | (1) assert copyright on the software, and (2) offer you this License
42 | giving you legal permission to copy, distribute and/or modify it.
43 |
44 | For the developers' and authors' protection, the GPL clearly explains
45 | that there is no warranty for this free software. For both users' and
46 | authors' sake, the GPL requires that modified versions be marked as
47 | changed, so that their problems will not be attributed erroneously to
48 | authors of previous versions.
49 |
50 | Some devices are designed to deny users access to install or run
51 | modified versions of the software inside them, although the manufacturer
52 | can do so. This is fundamentally incompatible with the aim of
53 | protecting users' freedom to change the software. The systematic
54 | pattern of such abuse occurs in the area of products for individuals to
55 | use, which is precisely where it is most unacceptable. Therefore, we
56 | have designed this version of the GPL to prohibit the practice for those
57 | products. If such problems arise substantially in other domains, we
58 | stand ready to extend this provision to those domains in future versions
59 | of the GPL, as needed to protect the freedom of users.
60 |
61 | Finally, every program is threatened constantly by software patents.
62 | States should not allow patents to restrict development and use of
63 | software on general-purpose computers, but in those that do, we wish to
64 | avoid the special danger that patents applied to a free program could
65 | make it effectively proprietary. To prevent this, the GPL assures that
66 | patents cannot be used to render the program non-free.
67 |
68 | The precise terms and conditions for copying, distribution and
69 | modification follow.
70 |
71 | TERMS AND CONDITIONS
72 |
73 | 0. Definitions.
74 |
75 | "This License" refers to version 3 of the GNU General Public License.
76 |
77 | "Copyright" also means copyright-like laws that apply to other kinds of
78 | works, such as semiconductor masks.
79 |
80 | "The Program" refers to any copyrightable work licensed under this
81 | License. Each licensee is addressed as "you". "Licensees" and
82 | "recipients" may be individuals or organizations.
83 |
84 | To "modify" a work means to copy from or adapt all or part of the work
85 | in a fashion requiring copyright permission, other than the making of an
86 | exact copy. The resulting work is called a "modified version" of the
87 | earlier work or a work "based on" the earlier work.
88 |
89 | A "covered work" means either the unmodified Program or a work based
90 | on the Program.
91 |
92 | To "propagate" a work means to do anything with it that, without
93 | permission, would make you directly or secondarily liable for
94 | infringement under applicable copyright law, except executing it on a
95 | computer or modifying a private copy. Propagation includes copying,
96 | distribution (with or without modification), making available to the
97 | public, and in some countries other activities as well.
98 |
99 | To "convey" a work means any kind of propagation that enables other
100 | parties to make or receive copies. Mere interaction with a user through
101 | a computer network, with no transfer of a copy, is not conveying.
102 |
103 | An interactive user interface displays "Appropriate Legal Notices"
104 | to the extent that it includes a convenient and prominently visible
105 | feature that (1) displays an appropriate copyright notice, and (2)
106 | tells the user that there is no warranty for the work (except to the
107 | extent that warranties are provided), that licensees may convey the
108 | work under this License, and how to view a copy of this License. If
109 | the interface presents a list of user commands or options, such as a
110 | menu, a prominent item in the list meets this criterion.
111 |
112 | 1. Source Code.
113 |
114 | The "source code" for a work means the preferred form of the work
115 | for making modifications to it. "Object code" means any non-source
116 | form of a work.
117 |
118 | A "Standard Interface" means an interface that either is an official
119 | standard defined by a recognized standards body, or, in the case of
120 | interfaces specified for a particular programming language, one that
121 | is widely used among developers working in that language.
122 |
123 | The "System Libraries" of an executable work include anything, other
124 | than the work as a whole, that (a) is included in the normal form of
125 | packaging a Major Component, but which is not part of that Major
126 | Component, and (b) serves only to enable use of the work with that
127 | Major Component, or to implement a Standard Interface for which an
128 | implementation is available to the public in source code form. A
129 | "Major Component", in this context, means a major essential component
130 | (kernel, window system, and so on) of the specific operating system
131 | (if any) on which the executable work runs, or a compiler used to
132 | produce the work, or an object code interpreter used to run it.
133 |
134 | The "Corresponding Source" for a work in object code form means all
135 | the source code needed to generate, install, and (for an executable
136 | work) run the object code and to modify the work, including scripts to
137 | control those activities. However, it does not include the work's
138 | System Libraries, or general-purpose tools or generally available free
139 | programs which are used unmodified in performing those activities but
140 | which are not part of the work. For example, Corresponding Source
141 | includes interface definition files associated with source files for
142 | the work, and the source code for shared libraries and dynamically
143 | linked subprograms that the work is specifically designed to require,
144 | such as by intimate data communication or control flow between those
145 | subprograms and other parts of the work.
146 |
147 | The Corresponding Source need not include anything that users
148 | can regenerate automatically from other parts of the Corresponding
149 | Source.
150 |
151 | The Corresponding Source for a work in source code form is that
152 | same work.
153 |
154 | 2. Basic Permissions.
155 |
156 | All rights granted under this License are granted for the term of
157 | copyright on the Program, and are irrevocable provided the stated
158 | conditions are met. This License explicitly affirms your unlimited
159 | permission to run the unmodified Program. The output from running a
160 | covered work is covered by this License only if the output, given its
161 | content, constitutes a covered work. This License acknowledges your
162 | rights of fair use or other equivalent, as provided by copyright law.
163 |
164 | You may make, run and propagate covered works that you do not
165 | convey, without conditions so long as your license otherwise remains
166 | in force. You may convey covered works to others for the sole purpose
167 | of having them make modifications exclusively for you, or provide you
168 | with facilities for running those works, provided that you comply with
169 | the terms of this License in conveying all material for which you do
170 | not control copyright. Those thus making or running the covered works
171 | for you must do so exclusively on your behalf, under your direction
172 | and control, on terms that prohibit them from making any copies of
173 | your copyrighted material outside their relationship with you.
174 |
175 | Conveying under any other circumstances is permitted solely under
176 | the conditions stated below. Sublicensing is not allowed; section 10
177 | makes it unnecessary.
178 |
179 | 3. Protecting Users' Legal Rights From Anti-Circumvention Law.
180 |
181 | No covered work shall be deemed part of an effective technological
182 | measure under any applicable law fulfilling obligations under article
183 | 11 of the WIPO copyright treaty adopted on 20 December 1996, or
184 | similar laws prohibiting or restricting circumvention of such
185 | measures.
186 |
187 | When you convey a covered work, you waive any legal power to forbid
188 | circumvention of technological measures to the extent such circumvention
189 | is effected by exercising rights under this License with respect to
190 | the covered work, and you disclaim any intention to limit operation or
191 | modification of the work as a means of enforcing, against the work's
192 | users, your or third parties' legal rights to forbid circumvention of
193 | technological measures.
194 |
195 | 4. Conveying Verbatim Copies.
196 |
197 | You may convey verbatim copies of the Program's source code as you
198 | receive it, in any medium, provided that you conspicuously and
199 | appropriately publish on each copy an appropriate copyright notice;
200 | keep intact all notices stating that this License and any
201 | non-permissive terms added in accord with section 7 apply to the code;
202 | keep intact all notices of the absence of any warranty; and give all
203 | recipients a copy of this License along with the Program.
204 |
205 | You may charge any price or no price for each copy that you convey,
206 | and you may offer support or warranty protection for a fee.
207 |
208 | 5. Conveying Modified Source Versions.
209 |
210 | You may convey a work based on the Program, or the modifications to
211 | produce it from the Program, in the form of source code under the
212 | terms of section 4, provided that you also meet all of these conditions:
213 |
214 | a) The work must carry prominent notices stating that you modified
215 | it, and giving a relevant date.
216 |
217 | b) The work must carry prominent notices stating that it is
218 | released under this License and any conditions added under section
219 | 7. This requirement modifies the requirement in section 4 to
220 | "keep intact all notices".
221 |
222 | c) You must license the entire work, as a whole, under this
223 | License to anyone who comes into possession of a copy. This
224 | License will therefore apply, along with any applicable section 7
225 | additional terms, to the whole of the work, and all its parts,
226 | regardless of how they are packaged. This License gives no
227 | permission to license the work in any other way, but it does not
228 | invalidate such permission if you have separately received it.
229 |
230 | d) If the work has interactive user interfaces, each must display
231 | Appropriate Legal Notices; however, if the Program has interactive
232 | interfaces that do not display Appropriate Legal Notices, your
233 | work need not make them do so.
234 |
235 | A compilation of a covered work with other separate and independent
236 | works, which are not by their nature extensions of the covered work,
237 | and which are not combined with it such as to form a larger program,
238 | in or on a volume of a storage or distribution medium, is called an
239 | "aggregate" if the compilation and its resulting copyright are not
240 | used to limit the access or legal rights of the compilation's users
241 | beyond what the individual works permit. Inclusion of a covered work
242 | in an aggregate does not cause this License to apply to the other
243 | parts of the aggregate.
244 |
245 | 6. Conveying Non-Source Forms.
246 |
247 | You may convey a covered work in object code form under the terms
248 | of sections 4 and 5, provided that you also convey the
249 | machine-readable Corresponding Source under the terms of this License,
250 | in one of these ways:
251 |
252 | a) Convey the object code in, or embodied in, a physical product
253 | (including a physical distribution medium), accompanied by the
254 | Corresponding Source fixed on a durable physical medium
255 | customarily used for software interchange.
256 |
257 | b) Convey the object code in, or embodied in, a physical product
258 | (including a physical distribution medium), accompanied by a
259 | written offer, valid for at least three years and valid for as
260 | long as you offer spare parts or customer support for that product
261 | model, to give anyone who possesses the object code either (1) a
262 | copy of the Corresponding Source for all the software in the
263 | product that is covered by this License, on a durable physical
264 | medium customarily used for software interchange, for a price no
265 | more than your reasonable cost of physically performing this
266 | conveying of source, or (2) access to copy the
267 | Corresponding Source from a network server at no charge.
268 |
269 | c) Convey individual copies of the object code with a copy of the
270 | written offer to provide the Corresponding Source. This
271 | alternative is allowed only occasionally and noncommercially, and
272 | only if you received the object code with such an offer, in accord
273 | with subsection 6b.
274 |
275 | d) Convey the object code by offering access from a designated
276 | place (gratis or for a charge), and offer equivalent access to the
277 | Corresponding Source in the same way through the same place at no
278 | further charge. You need not require recipients to copy the
279 | Corresponding Source along with the object code. If the place to
280 | copy the object code is a network server, the Corresponding Source
281 | may be on a different server (operated by you or a third party)
282 | that supports equivalent copying facilities, provided you maintain
283 | clear directions next to the object code saying where to find the
284 | Corresponding Source. Regardless of what server hosts the
285 | Corresponding Source, you remain obligated to ensure that it is
286 | available for as long as needed to satisfy these requirements.
287 |
288 | e) Convey the object code using peer-to-peer transmission, provided
289 | you inform other peers where the object code and Corresponding
290 | Source of the work are being offered to the general public at no
291 | charge under subsection 6d.
292 |
293 | A separable portion of the object code, whose source code is excluded
294 | from the Corresponding Source as a System Library, need not be
295 | included in conveying the object code work.
296 |
297 | A "User Product" is either (1) a "consumer product", which means any
298 | tangible personal property which is normally used for personal, family,
299 | or household purposes, or (2) anything designed or sold for incorporation
300 | into a dwelling. In determining whether a product is a consumer product,
301 | doubtful cases shall be resolved in favor of coverage. For a particular
302 | product received by a particular user, "normally used" refers to a
303 | typical or common use of that class of product, regardless of the status
304 | of the particular user or of the way in which the particular user
305 | actually uses, or expects or is expected to use, the product. A product
306 | is a consumer product regardless of whether the product has substantial
307 | commercial, industrial or non-consumer uses, unless such uses represent
308 | the only significant mode of use of the product.
309 |
310 | "Installation Information" for a User Product means any methods,
311 | procedures, authorization keys, or other information required to install
312 | and execute modified versions of a covered work in that User Product from
313 | a modified version of its Corresponding Source. The information must
314 | suffice to ensure that the continued functioning of the modified object
315 | code is in no case prevented or interfered with solely because
316 | modification has been made.
317 |
318 | If you convey an object code work under this section in, or with, or
319 | specifically for use in, a User Product, and the conveying occurs as
320 | part of a transaction in which the right of possession and use of the
321 | User Product is transferred to the recipient in perpetuity or for a
322 | fixed term (regardless of how the transaction is characterized), the
323 | Corresponding Source conveyed under this section must be accompanied
324 | by the Installation Information. But this requirement does not apply
325 | if neither you nor any third party retains the ability to install
326 | modified object code on the User Product (for example, the work has
327 | been installed in ROM).
328 |
329 | The requirement to provide Installation Information does not include a
330 | requirement to continue to provide support service, warranty, or updates
331 | for a work that has been modified or installed by the recipient, or for
332 | the User Product in which it has been modified or installed. Access to a
333 | network may be denied when the modification itself materially and
334 | adversely affects the operation of the network or violates the rules and
335 | protocols for communication across the network.
336 |
337 | Corresponding Source conveyed, and Installation Information provided,
338 | in accord with this section must be in a format that is publicly
339 | documented (and with an implementation available to the public in
340 | source code form), and must require no special password or key for
341 | unpacking, reading or copying.
342 |
343 | 7. Additional Terms.
344 |
345 | "Additional permissions" are terms that supplement the terms of this
346 | License by making exceptions from one or more of its conditions.
347 | Additional permissions that are applicable to the entire Program shall
348 | be treated as though they were included in this License, to the extent
349 | that they are valid under applicable law. If additional permissions
350 | apply only to part of the Program, that part may be used separately
351 | under those permissions, but the entire Program remains governed by
352 | this License without regard to the additional permissions.
353 |
354 | When you convey a copy of a covered work, you may at your option
355 | remove any additional permissions from that copy, or from any part of
356 | it. (Additional permissions may be written to require their own
357 | removal in certain cases when you modify the work.) You may place
358 | additional permissions on material, added by you to a covered work,
359 | for which you have or can give appropriate copyright permission.
360 |
361 | Notwithstanding any other provision of this License, for material you
362 | add to a covered work, you may (if authorized by the copyright holders of
363 | that material) supplement the terms of this License with terms:
364 |
365 | a) Disclaiming warranty or limiting liability differently from the
366 | terms of sections 15 and 16 of this License; or
367 |
368 | b) Requiring preservation of specified reasonable legal notices or
369 | author attributions in that material or in the Appropriate Legal
370 | Notices displayed by works containing it; or
371 |
372 | c) Prohibiting misrepresentation of the origin of that material, or
373 | requiring that modified versions of such material be marked in
374 | reasonable ways as different from the original version; or
375 |
376 | d) Limiting the use for publicity purposes of names of licensors or
377 | authors of the material; or
378 |
379 | e) Declining to grant rights under trademark law for use of some
380 | trade names, trademarks, or service marks; or
381 |
382 | f) Requiring indemnification of licensors and authors of that
383 | material by anyone who conveys the material (or modified versions of
384 | it) with contractual assumptions of liability to the recipient, for
385 | any liability that these contractual assumptions directly impose on
386 | those licensors and authors.
387 |
388 | All other non-permissive additional terms are considered "further
389 | restrictions" within the meaning of section 10. If the Program as you
390 | received it, or any part of it, contains a notice stating that it is
391 | governed by this License along with a term that is a further
392 | restriction, you may remove that term. If a license document contains
393 | a further restriction but permits relicensing or conveying under this
394 | License, you may add to a covered work material governed by the terms
395 | of that license document, provided that the further restriction does
396 | not survive such relicensing or conveying.
397 |
398 | If you add terms to a covered work in accord with this section, you
399 | must place, in the relevant source files, a statement of the
400 | additional terms that apply to those files, or a notice indicating
401 | where to find the applicable terms.
402 |
403 | Additional terms, permissive or non-permissive, may be stated in the
404 | form of a separately written license, or stated as exceptions;
405 | the above requirements apply either way.
406 |
407 | 8. Termination.
408 |
409 | You may not propagate or modify a covered work except as expressly
410 | provided under this License. Any attempt otherwise to propagate or
411 | modify it is void, and will automatically terminate your rights under
412 | this License (including any patent licenses granted under the third
413 | paragraph of section 11).
414 |
415 | However, if you cease all violation of this License, then your
416 | license from a particular copyright holder is reinstated (a)
417 | provisionally, unless and until the copyright holder explicitly and
418 | finally terminates your license, and (b) permanently, if the copyright
419 | holder fails to notify you of the violation by some reasonable means
420 | prior to 60 days after the cessation.
421 |
422 | Moreover, your license from a particular copyright holder is
423 | reinstated permanently if the copyright holder notifies you of the
424 | violation by some reasonable means, this is the first time you have
425 | received notice of violation of this License (for any work) from that
426 | copyright holder, and you cure the violation prior to 30 days after
427 | your receipt of the notice.
428 |
429 | Termination of your rights under this section does not terminate the
430 | licenses of parties who have received copies or rights from you under
431 | this License. If your rights have been terminated and not permanently
432 | reinstated, you do not qualify to receive new licenses for the same
433 | material under section 10.
434 |
435 | 9. Acceptance Not Required for Having Copies.
436 |
437 | You are not required to accept this License in order to receive or
438 | run a copy of the Program. Ancillary propagation of a covered work
439 | occurring solely as a consequence of using peer-to-peer transmission
440 | to receive a copy likewise does not require acceptance. However,
441 | nothing other than this License grants you permission to propagate or
442 | modify any covered work. These actions infringe copyright if you do
443 | not accept this License. Therefore, by modifying or propagating a
444 | covered work, you indicate your acceptance of this License to do so.
445 |
446 | 10. Automatic Licensing of Downstream Recipients.
447 |
448 | Each time you convey a covered work, the recipient automatically
449 | receives a license from the original licensors, to run, modify and
450 | propagate that work, subject to this License. You are not responsible
451 | for enforcing compliance by third parties with this License.
452 |
453 | An "entity transaction" is a transaction transferring control of an
454 | organization, or substantially all assets of one, or subdividing an
455 | organization, or merging organizations. If propagation of a covered
456 | work results from an entity transaction, each party to that
457 | transaction who receives a copy of the work also receives whatever
458 | licenses to the work the party's predecessor in interest had or could
459 | give under the previous paragraph, plus a right to possession of the
460 | Corresponding Source of the work from the predecessor in interest, if
461 | the predecessor has it or can get it with reasonable efforts.
462 |
463 | You may not impose any further restrictions on the exercise of the
464 | rights granted or affirmed under this License. For example, you may
465 | not impose a license fee, royalty, or other charge for exercise of
466 | rights granted under this License, and you may not initiate litigation
467 | (including a cross-claim or counterclaim in a lawsuit) alleging that
468 | any patent claim is infringed by making, using, selling, offering for
469 | sale, or importing the Program or any portion of it.
470 |
471 | 11. Patents.
472 |
473 | A "contributor" is a copyright holder who authorizes use under this
474 | License of the Program or a work on which the Program is based. The
475 | work thus licensed is called the contributor's "contributor version".
476 |
477 | A contributor's "essential patent claims" are all patent claims
478 | owned or controlled by the contributor, whether already acquired or
479 | hereafter acquired, that would be infringed by some manner, permitted
480 | by this License, of making, using, or selling its contributor version,
481 | but do not include claims that would be infringed only as a
482 | consequence of further modification of the contributor version. For
483 | purposes of this definition, "control" includes the right to grant
484 | patent sublicenses in a manner consistent with the requirements of
485 | this License.
486 |
487 | Each contributor grants you a non-exclusive, worldwide, royalty-free
488 | patent license under the contributor's essential patent claims, to
489 | make, use, sell, offer for sale, import and otherwise run, modify and
490 | propagate the contents of its contributor version.
491 |
492 | In the following three paragraphs, a "patent license" is any express
493 | agreement or commitment, however denominated, not to enforce a patent
494 | (such as an express permission to practice a patent or covenant not to
495 | sue for patent infringement). To "grant" such a patent license to a
496 | party means to make such an agreement or commitment not to enforce a
497 | patent against the party.
498 |
499 | If you convey a covered work, knowingly relying on a patent license,
500 | and the Corresponding Source of the work is not available for anyone
501 | to copy, free of charge and under the terms of this License, through a
502 | publicly available network server or other readily accessible means,
503 | then you must either (1) cause the Corresponding Source to be so
504 | available, or (2) arrange to deprive yourself of the benefit of the
505 | patent license for this particular work, or (3) arrange, in a manner
506 | consistent with the requirements of this License, to extend the patent
507 | license to downstream recipients. "Knowingly relying" means you have
508 | actual knowledge that, but for the patent license, your conveying the
509 | covered work in a country, or your recipient's use of the covered work
510 | in a country, would infringe one or more identifiable patents in that
511 | country that you have reason to believe are valid.
512 |
513 | If, pursuant to or in connection with a single transaction or
514 | arrangement, you convey, or propagate by procuring conveyance of, a
515 | covered work, and grant a patent license to some of the parties
516 | receiving the covered work authorizing them to use, propagate, modify
517 | or convey a specific copy of the covered work, then the patent license
518 | you grant is automatically extended to all recipients of the covered
519 | work and works based on it.
520 |
521 | A patent license is "discriminatory" if it does not include within
522 | the scope of its coverage, prohibits the exercise of, or is
523 | conditioned on the non-exercise of one or more of the rights that are
524 | specifically granted under this License. You may not convey a covered
525 | work if you are a party to an arrangement with a third party that is
526 | in the business of distributing software, under which you make payment
527 | to the third party based on the extent of your activity of conveying
528 | the work, and under which the third party grants, to any of the
529 | parties who would receive the covered work from you, a discriminatory
530 | patent license (a) in connection with copies of the covered work
531 | conveyed by you (or copies made from those copies), or (b) primarily
532 | for and in connection with specific products or compilations that
533 | contain the covered work, unless you entered into that arrangement,
534 | or that patent license was granted, prior to 28 March 2007.
535 |
536 | Nothing in this License shall be construed as excluding or limiting
537 | any implied license or other defenses to infringement that may
538 | otherwise be available to you under applicable patent law.
539 |
540 | 12. No Surrender of Others' Freedom.
541 |
542 | If conditions are imposed on you (whether by court order, agreement or
543 | otherwise) that contradict the conditions of this License, they do not
544 | excuse you from the conditions of this License. If you cannot convey a
545 | covered work so as to satisfy simultaneously your obligations under this
546 | License and any other pertinent obligations, then as a consequence you may
547 | not convey it at all. For example, if you agree to terms that obligate you
548 | to collect a royalty for further conveying from those to whom you convey
549 | the Program, the only way you could satisfy both those terms and this
550 | License would be to refrain entirely from conveying the Program.
551 |
552 | 13. Use with the GNU Affero General Public License.
553 |
554 | Notwithstanding any other provision of this License, you have
555 | permission to link or combine any covered work with a work licensed
556 | under version 3 of the GNU Affero General Public License into a single
557 | combined work, and to convey the resulting work. The terms of this
558 | License will continue to apply to the part which is the covered work,
559 | but the special requirements of the GNU Affero General Public License,
560 | section 13, concerning interaction through a network will apply to the
561 | combination as such.
562 |
563 | 14. Revised Versions of this License.
564 |
565 | The Free Software Foundation may publish revised and/or new versions of
566 | the GNU General Public License from time to time. Such new versions will
567 | be similar in spirit to the present version, but may differ in detail to
568 | address new problems or concerns.
569 |
570 | Each version is given a distinguishing version number. If the
571 | Program specifies that a certain numbered version of the GNU General
572 | Public License "or any later version" applies to it, you have the
573 | option of following the terms and conditions either of that numbered
574 | version or of any later version published by the Free Software
575 | Foundation. If the Program does not specify a version number of the
576 | GNU General Public License, you may choose any version ever published
577 | by the Free Software Foundation.
578 |
579 | If the Program specifies that a proxy can decide which future
580 | versions of the GNU General Public License can be used, that proxy's
581 | public statement of acceptance of a version permanently authorizes you
582 | to choose that version for the Program.
583 |
584 | Later license versions may give you additional or different
585 | permissions. However, no additional obligations are imposed on any
586 | author or copyright holder as a result of your choosing to follow a
587 | later version.
588 |
589 | 15. Disclaimer of Warranty.
590 |
591 | THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY
592 | APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT
593 | HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY
594 | OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO,
595 | THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
596 | PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM
597 | IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF
598 | ALL NECESSARY SERVICING, REPAIR OR CORRECTION.
599 |
600 | 16. Limitation of Liability.
601 |
602 | IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING
603 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS
604 | THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY
605 | GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE
606 | USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF
607 | DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD
608 | PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS),
609 | EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF
610 | SUCH DAMAGES.
611 |
612 | 17. Interpretation of Sections 15 and 16.
613 |
614 | If the disclaimer of warranty and limitation of liability provided
615 | above cannot be given local legal effect according to their terms,
616 | reviewing courts shall apply local law that most closely approximates
617 | an absolute waiver of all civil liability in connection with the
618 | Program, unless a warranty or assumption of liability accompanies a
619 | copy of the Program in return for a fee.
620 |
621 | END OF TERMS AND CONDITIONS
622 |
623 | How to Apply These Terms to Your New Programs
624 |
625 | If you develop a new program, and you want it to be of the greatest
626 | possible use to the public, the best way to achieve this is to make it
627 | free software which everyone can redistribute and change under these terms.
628 |
629 | To do so, attach the following notices to the program. It is safest
630 | to attach them to the start of each source file to most effectively
631 | state the exclusion of warranty; and each file should have at least
632 | the "copyright" line and a pointer to where the full notice is found.
633 |
634 |
635 | Copyright (C)
636 |
637 | This program is free software: you can redistribute it and/or modify
638 | it under the terms of the GNU General Public License as published by
639 | the Free Software Foundation, either version 3 of the License, or
640 | (at your option) any later version.
641 |
642 | This program is distributed in the hope that it will be useful,
643 | but WITHOUT ANY WARRANTY; without even the implied warranty of
644 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
645 | GNU General Public License for more details.
646 |
647 | You should have received a copy of the GNU General Public License
648 | along with this program. If not, see .
649 |
650 | Also add information on how to contact you by electronic and paper mail.
651 |
652 | If the program does terminal interaction, make it output a short
653 | notice like this when it starts in an interactive mode:
654 |
655 | Copyright (C)
656 | This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'.
657 | This is free software, and you are welcome to redistribute it
658 | under certain conditions; type `show c' for details.
659 |
660 | The hypothetical commands `show w' and `show c' should show the appropriate
661 | parts of the General Public License. Of course, your program's commands
662 | might be different; for a GUI interface, you would use an "about box".
663 |
664 | You should also get your employer (if you work as a programmer) or school,
665 | if any, to sign a "copyright disclaimer" for the program, if necessary.
666 | For more information on this, and how to apply and follow the GNU GPL, see
667 | .
668 |
669 | The GNU General Public License does not permit incorporating your program
670 | into proprietary programs. If your program is a subroutine library, you
671 | may consider it more useful to permit linking proprietary applications with
672 | the library. If this is what you want to do, use the GNU Lesser General
673 | Public License instead of this License. But first, please read
674 | .
675 |
--------------------------------------------------------------------------------
/PowerBI Visibility.ps1:
--------------------------------------------------------------------------------
1 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
2 | # (c) 2019 David Berglin
3 | # This file is part of the PowerBiVisibility project.
4 | # PowerBiVisibility is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
5 | # PowerBiVisibility is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.
6 | # You should have received a copy of the GNU General Public License along with PowerBiVisibility. If not, see https://www.gnu.org/licenses/.
7 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
8 | #
9 | # ... if you see this:
10 | # MyFileName.ps1 cannot be loaded because running scripts is disabled on this system. For more information, see about_Execution_Policies at http://go.microsoft.com/fwlink/?LinkID=135170.
11 | #
12 | # ... short answer
13 | # set-executionpolicy -scope CurrentUser -executionPolicy RemoteSigned
14 | #
15 | # ... long answer
16 | # NOTE: In order to run Powershell scripts, you need to enable them... There is a serious security vulnerability if web-based scripts are downloaded and executed
17 | # 1) Find "PowerShell ISE" or else just "PowerShell"
18 | # 2) Run as administrator
19 | # 3) Use a new window, not a saved file.... file based scripts are considered dangerous, so they can't run in some configurations
20 | # 4) optional: use this command to view current setting:
21 | # Get-ExecutionPolicy
22 | # 5) use this command to allow execution permissions:
23 | # set-executionpolicy -scope CurrentUser -executionPolicy RemoteSigned
24 | # 6) execute it (F5 in ISE or Enter in command line mode)
25 | # 7) use this command to return to the most secure configuration:
26 | # set-executionpolicy -scope CurrentUser -executionPolicy Restricted
27 | #
28 | # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
29 |
30 | # see https://docs.microsoft.com/en-us/powershell/power-bi/overview
31 |
32 | cls #clear screen
33 |
34 |
35 | ""
36 | "This script will:"
37 | "...copy a PowerBI Desktop (pbix) file"
38 | "...treat it like a .zip file and unzip it"
39 | "...pull data into memory from the Layout file of the unzipped report folder"
40 | "...delete the copied PowerBI file and the unzipped report folder"
41 | "...convert nested JSON into powershell objects"
42 | "...extract a List of Measures or data columns from the JSON object"
43 | "...read all open PowerBI Desktop (pbix) files, find the selected one"
44 | "...query the SSAS Tabular model server of the open file"
45 | "...extract a List of Measures or data columns from the SSAS server"
46 | "...optionally output dependencies of visuals as SQL scripts"
47 | "...optionally output dependencies of visuals as Tab-Delimited data"
48 | "...optionally save a formatted JSON file of the PBIX content (eg. for source control or comparison)"
49 | ""
50 | "...note: to preserve tabs use Powershell ISE."
51 | "...note: to avoid text wrap: full screen and zoom out."
52 | ""
53 | ""
54 |
55 | $isIse = Test-Path variable:global:psISE # Is the script being run within the "Powershell ISE" app?
56 | if (-not $isISE)
57 | {
58 | ""
59 | "Use 'Powershell ISE' instead of the command line."
60 | "(because the ordinary powershell command line does not preserve tab characters)"
61 | }
62 |
63 |
64 | #----------------------------------------------
65 | # This function is used to optionally output detailed logs to the PowerBI window
66 | #----------------------------------------------
67 | $doShowLogs = $false
68 | Function log($message)
69 | {
70 | if($doShowLogs){
71 | write-host $message
72 | }
73 | }
74 |
75 |
76 |
77 | #----------------------------------------------
78 | # This function is used to present a file picker
79 | #----------------------------------------------
80 | Function Use-FilePicker($initialDirectory) # https://devblogs.microsoft.com/scripting/hey-scripting-guy-can-i-open-a-file-dialog-box-with-windows-powershell/
81 | {
82 | [System.Reflection.Assembly]::LoadWithPartialName(“System.windows.forms”) | Out-Null
83 |
84 | $OpenFileDialog = New-Object System.Windows.Forms.OpenFileDialog
85 | $OpenFileDialog.initialDirectory = $initialDirectory
86 | $OpenFileDialog.filter = “All files (*.*)| *.*”
87 | $OpenFileDialog.ShowDialog() | Out-Null
88 |
89 | #return choice
90 | $OpenFileDialog.filename
91 | }
92 |
93 |
94 |
95 |
96 |
97 | #----------------------------------------------
98 | # Get User Choices
99 | #----------------------------------------------
100 | "Enter 'c' to cancel (for any choice)"
101 | "Enter 'p' for a file picker"
102 |
103 | $sessionFile = $ExecutionContext.SessionState.PSVariable.GetValue("sessionFile") # get last used file name
104 | $initialDirectory = "%userprofile%"
105 | if("$sessionFile" -ne "")
106 | {
107 | $initialDirectory = [System.IO.Path]::GetDirectoryName($sessionFile)
108 | "(blank = `"$sessionFile`""
109 | }
110 |
111 | $choiceOfFile = Read-Host 'Paste the full path to the PowerBI file: C:\folder\example.pbix'
112 |
113 | if($choiceOfFile -eq "p")
114 | {
115 | $choiceOfFile = Use-FilePicker -initialDirectory $initialDirectory # present a file picker
116 | }
117 |
118 |
119 | #----------------------------------------------
120 | # Validate
121 | #----------------------------------------------
122 | if($choiceOfFile -eq "" -and "$sessionFile" -ne ""){ $choiceOfFile = $sessionFile } # no new choice, use previous file
123 | if($choiceOfFile -eq ""){ return } # no choice at all, so quit
124 | if($choiceOfFile -eq "c"){ return } # c = Cancel
125 | if("$PsScriptRoot" -eq ""){
126 | "This powershell script must be saved to -and executed from- a location where temporary files can be stored and manipulated"
127 | "stopping"
128 | ""
129 | return
130 | }
131 | if($choiceOfFile.ToLower().EndsWith(".pbix") -eq $false){
132 | "a .pbix file path was not supplied: $choiceOfFile"
133 | "stopping"
134 | ""
135 | return
136 | }
137 | if((test-path $choiceOfFile) -eq $false){
138 | "a file was not found at this location: $choiceOfFile"
139 | "stopping"
140 | ""
141 | return
142 | }
143 |
144 |
145 |
146 | #----------------------------------------------
147 | # Interpret User Choices
148 | #----------------------------------------------
149 | $fileName = [System.IO.Path]::GetFileName($choiceOfFile)
150 | $fileNameWithoutExtension = [System.IO.Path]::GetFileNameWithoutExtension($choiceOfFile)
151 |
152 | "Do you want: SQL Insert script (s) <-- blank choice uses this"
153 | " Tabbed Delimited Table (t)"
154 | " JSON of PBIX file (j)"
155 | " Measure Expressions (m)"
156 | " Detailed Logs (l)"
157 | " combination (stjml)"
158 | $choiceOfOutput = (Read-Host '.................Enter Your Choice').ToLower()
159 | if($choiceOfOutput -eq "c"){return} #cancel
160 | if($choiceOfOutput -eq ""){$choiceOfOutput = "s"} # apply the default
161 |
162 | $doShowSqlScript = $choiceOfOutput.Contains("s")
163 | $doShowTabbedTable = $choiceOfOutput.Contains("t")
164 | $doGenerateJson = $choiceOfOutput.Contains("j")
165 | $doShowExpression = $choiceOfOutput.Contains("m")
166 | $doShowLogs = $choiceOfOutput.Contains("l")
167 | $doResolveDependencies = ($doShowSqlScript -or $doShowTabbedTable) # Do we need to find measures? Or just generate JSON?
168 |
169 | $ExecutionContext.SessionState.PSVariable.Set("sessionFile", $choiceOfFile ) # now that we know we are doing something, lets remember the file location for next time.
170 |
171 | $doIgnoreVisualQueryJSON = $true
172 | $doIgnoreVisualDataTransformJSON = $true
173 |
174 |
175 | #----------------------------------------------
176 | #"...copy a PowerBI report file"
177 | #----------------------------------------------
178 | "Copying from $choiceOfFile"
179 | $DestinationZipFile = "$PsScriptRoot\Temp_File_Delete_Me.zip"
180 | $DestinationZipFolder = "$PsScriptRoot\Temp_Folder_Delete_Me"
181 | $DestinationJSONFile = "$PsScriptRoot\Temp_Folder_Delete_Me\Report\Layout" # NOTE: No File Extension
182 | "Copying to $DestinationZipFile"
183 |
184 | Copy-Item -Path $choiceOfFile -Destination $DestinationZipFile
185 | "Copied"
186 |
187 |
188 | #----------------------------------------------
189 | #"...treat it like a .zip file and unzip it"
190 | #----------------------------------------------
191 | Add-Type -AssemblyName System.IO.Compression.FileSystem
192 | function Unzip
193 | {
194 | param([string]$zipfile, [string]$outpath)
195 |
196 | [System.IO.Compression.ZipFile]::ExtractToDirectory($zipfile, $outpath)
197 | }
198 | Unzip $DestinationZipFile $DestinationZipFolder
199 | "Unzipped"
200 |
201 |
202 | #----------------------------------------------
203 | #"...pull in data from the Layout file of the unzipped report folder"
204 | #----------------------------------------------
205 | $json = Get-Content -Raw -Path $DestinationJSONFile -Encoding Unicode
206 |
207 | $o = $json | ConvertFrom-Json # $o stands for object... the object represented by the JSON
208 | $wrapper = [PSCustomObject]@{
209 | PowerBI_Visibility_Execution_UtcDate = (Get-Date).ToUniversalTime();
210 | Pbix = $o;
211 | DBs = [System.Collections.ArrayList]@();
212 | }
213 |
214 | "JSON read ...transforming"
215 |
216 |
217 | #----------------------------------------------
218 | #"...delete the copied file and unzipped folder"
219 | #----------------------------------------------
220 | Remove-Item $DestinationZipFolder -recurse
221 | Remove-Item $DestinationZipFile
222 | "Temporary Files Removed"
223 |
224 |
225 |
226 | #----------------------------------------------
227 | # set up variable to hold collections of data that is found
228 | #----------------------------------------------
229 | $script:sql = ""
230 | $script:distinctData = [System.Collections.ArrayList]@() # Holds distinct measure and locations... helps prevent duplicates where table names are missing.
231 | $script:ports = [System.Collections.ArrayList]@()
232 | $script:measureExpressions = [System.Collections.ArrayList]@()
233 |
234 | $visuals = New-Object 'system.collections.generic.dictionary[string,object]'
235 | $measures = New-Object 'system.collections.generic.dictionary[string,object]'
236 | $columns = New-Object 'system.collections.generic.dictionary[string,object]'
237 | $tables = New-Object 'system.collections.generic.dictionary[string,object]'
238 |
239 |
240 |
241 | #----------------------------------------------
242 | # This function creates a "base" object which may be extended for various dependency types (tables/columns/measures/etc)
243 | #----------------------------------------------
244 | function New-Dependency($table, $name, $address, $source)
245 | {
246 | $o = [PSCustomObject]@{
247 | Table = $table;
248 | Name = $name;
249 | Address = $address;
250 | Source = $source;
251 | }
252 | return $o
253 | }
254 |
255 |
256 | $script:mostRecentDB = @{}
257 | $script:mostRecentTable = @{}
258 | #----------------------------------------------
259 | # This function is used to Build a simple object from the complex SSAS Tabular database.
260 | # Assumes that the DB is looping over db >> tables >> columns/measures
261 | # The end-goal of this is to create a JSON string which summarizes the contents of the SSAS db.
262 | #----------------------------------------------
263 | Function log-db-as-JSON($type, $object)
264 | {
265 | if($type -eq "db"){
266 | # DB is handled differently then other kinds of data, since it has a lot of machine-specific settings. So skip the processes below
267 | $script:mostRecentDB = [PSCustomObject]@{
268 | Tables = [System.Collections.ArrayList]@()
269 | Name = $object.Name # this is probably a GUID
270 | Description = $object.Description
271 | LastSchemaUpdate = $object.LastSchemaUpdate
272 | CompatibilityLevel = $object.CompatibilityLevel
273 | }
274 | $rownum = $wrapper.DBs.Add($script:mostRecentDB)
275 | return
276 | }
277 |
278 | $thing = @{} # eg. table or column or measure or some other object:Partitions, Hierarchies, Annotations, ExtendedProperties, etc
279 | # find all properties of this object.
280 | $object | Get-Member | Sort-Object -Property Name | Where-Object {$_.MemberType -ne "Method" } | ForEach-Object {
281 | if($_.Definition.StartsWith("Microsoft.")) { return } # This is a complex object, such as the "Microsoft.AnalysisServices.Tabular.Model" and will not be included in the JSON
282 | $value = $object.($_.Name)
283 | if($value -eq $null) { $value = "(null)"}
284 |
285 | $thing[$_.Name] = $value.ToString()
286 | }
287 |
288 | # Place this in the db object structure
289 | if($type -eq "table"){
290 | $script:mostRecentTable = $thing
291 | $thing.Measures = [System.Collections.ArrayList]@()
292 | $thing.Columns = [System.Collections.ArrayList]@()
293 | $thing.Objects = [System.Collections.ArrayList]@()
294 |
295 | $rownum = $script:mostRecentDB.Tables.Add($script:mostRecentTable)
296 | }
297 | elseif($type -eq "measure") {
298 | $rownum = $script:mostRecentTable.Measures.Add($thing)
299 | }
300 | elseif($type -eq "column") {
301 | $rownum = $script:mostRecentTable.Columns.Add($thing)
302 | }
303 | else { # anything else
304 | $thing."Object-Type" = $type
305 | $rownum = $script:mostRecentTable.Objects.Add($thing)
306 | }
307 | }
308 |
309 |
310 |
311 | #----------------------------------------------
312 | # This function is used to read, format, and store data found within the PowerBI file
313 | # (eg. compile a list of Measure and their locations)
314 | # $typeID tracks where the data was found (useful fpr wjhat type of data it is, and to aid in research of the JSON)
315 | # $sectionDisplayName The Tab name
316 | # $visualLabel The individual Visual on the page (type + ID)
317 | # $queryRef holds the Table & measure/column info. Some table data may be missing.
318 | #----------------------------------------------
319 | function AddVisualDependency($typeID, $sectionDisplayName, $visualLabel, $queryRef){
320 |
321 | $measure = "$queryRef".Trim() # note that table name might be missing
322 | if($measure -eq "") { return } # String.isnullorwhitespace
323 | $table = ""
324 |
325 | # convert "dimDate.Year" tp "dimDate" & "Year"
326 | $periodIndex = $measure.IndexOf(".")
327 | if($periodIndex -gt -1){
328 | $table = $measure.Substring(0,$periodIndex)
329 | $measure = $measure.Substring($periodIndex + 1)
330 | }
331 |
332 | # Extract Table and Measure names from PBIX reference. This happens when the queryRef uses: Sum(tbl.col) so we will extract 'tbl' and 'col'
333 | if($table.IndexOf("(") -gt -1 -and $measure.EndsWith(")"))
334 | {
335 | $original = $table
336 | $table = $table.Substring($table.IndexOf("(") + 1)
337 | log ("in $queryRef ...this script intrepreted the table '$original' as '$table' ")
338 | $original = $measure
339 | $measure = $measure.Substring(0, $measure.Length - 1)
340 | log ("in $queryRef ...this script intrepreted the measure '$original' as '$measure' ")
341 | }
342 |
343 | # resolve names and values
344 | $fullyQualifiedName = "'$table'[$measure]"
345 | $FullName = "$fileName :: $sectionDisplayName :: $visualLabel"
346 | $typeName = 'visual'
347 | if($typeID -eq 4) {
348 | $typeName = 'Drill'
349 | }
350 |
351 |
352 | # track this visual dependency in memory
353 | $distinctText = "$measure ...is.in... $sectionDisplayName ( $visualLabel )"
354 | if($script:distinctData.Contains($distinctText) -eq $false){
355 | $rownum = $script:distinctData.Add($distinctText);
356 |
357 | # build out the dependency object (each kind is a little different)
358 | $visualParent = New-Dependency $sectionDisplayName $visualLabel $FullName $fileName #table/name/address/source
359 | $visualParent | Add-Member -MemberType NoteProperty -Name "UsesMeasure" -Value @() # empty array, this will hold a list of measures that are dependencies of this measure
360 |
361 | $visualChild = New-Dependency $table $measure $fullyQualifiedName $fileName #table/name/address/source
362 | $visualParent.UsesMeasure += $visualChild
363 |
364 | $rownum = $visuals[$FullName] = $visualParent
365 | }
366 | }
367 |
368 |
369 |
370 | #----------------------------------------------
371 | # This function is used to extract the "Title" of visual if there is one.
372 | #----------------------------------------------
373 | function Get-Visual-Friendly-Name ($visual, $defaultIfMissing) {
374 |
375 | #"vcObjects": {
376 | # "title": [
377 | # {
378 | # "properties": {
379 | # "show": {
380 | # "expr": {
381 | # "Literal": {
382 | # "Value": "true" <--true seems to auto generate a Visual Title somehow, based on columns, if there is no explicit Title
383 | # "text": { but this auto generated title is not recognized by this powershell script
384 | # "expr": {
385 | # "Literal": {
386 | # "Value": "'Plan by Business Area'" <--this explicit Title is recognized by this powershell script
387 |
388 |
389 | try {
390 | #Some visual have friendly titles. If it exists, it is preferable as the label
391 | $visualTitle = $visual.vcObjects
392 | if($visualTitle -ne $null) {
393 | $friendlyName = $visualTitle.title[0].properties.text.expr.Literal.Value
394 | if($friendlyName -ne "''")
395 | {
396 | return $friendlyName
397 | }
398 | }
399 | } catch{ } # probably no custom label
400 | if($defaultIfMissing -eq $null) { return "" } # empty default
401 | return $defaultIfMissing
402 | }
403 |
404 |
405 | #----------------------------------------------
406 | # This function is used to collect data about nested objects and properties. Used in the process of researching an object that came from JSON
407 | # The objects within a PowerBI report has changed, and will change, over time.
408 | # This code is used to read sections of the PowerBI report object, and discover what unique Property Names exists
409 | # This is NOT used during normal execution, but is useful while coding this powershell script over time
410 | # STEP: 1-of-2 Collect unique property names within this function
411 | # usage
412 | # $visual.prototypeQuery | Skip-Null | Get-Member | ForEach-Object { AddUniquePropNames $_ }
413 | # |<------------------>| ...Update that section for each object you are researching
414 | #---------------------------------------------
415 | $script:propertyNames = [System.Collections.ArrayList]@()
416 | function AddUniquePropNames($propertyMember){
417 | if($propertyMember.MemberType -eq "Method"){ return } # ignore functions names
418 | $text = $propertyMember.Name
419 | if($script:propertyNames.Contains($text) -eq $false){
420 | $rownum = $script:propertyNames.Add($text);
421 | }
422 | }
423 |
424 | #---------------------------------------------
425 | # this filter will skip null objects in a powershell pipeline, but also will skip the value of $false
426 | # see... https://stackoverflow.com/questions/4356758/how-to-handle-null-in-the-pipeline
427 | #---------------------------------------------
428 | filter Skip-Null
429 | {
430 | if( $_ -ne $null ){ return $_ } else { return $false}
431 | }
432 |
433 |
434 |
435 |
436 |
437 |
438 |
439 |
440 |
441 |
442 |
443 |
444 |
445 |
446 |
447 |
448 |
449 |
450 |
451 |
452 |
453 |
454 | "Evaluating the PBIX file"
455 |
456 | #----------------------------------------------
457 | # Convert Text sections into JSON
458 | # Some properties contain a text string which also includes JSON. This loops over nested properties and converts these to JSON where they are known as objects.
459 | # This next section of code (and loop) traverses the JSON as an object:
460 | # it builds nested objects, standardizes some properties, adds reference points, and ultimiately finds Visual Dependencies
461 | # The result is clean + consistent JSON (for saving as a file). This is also easier to traverse while looking for Measures and Column dependencies
462 | #
463 | # The code pattern below checks if the property is null. If it is not null, it converts the value to an object, assuming it is JSON. If it is null then the text "null" is inserted as its value.
464 | # if($o.config -ne $null) {$o.config = $o.config | ConvertFrom-Json } else { $o | Add-Member -NotePropertyName "config" -NotePropertyValue "null" }
465 | #
466 | #----------------------------------------------
467 | if($o.config -ne $null) {$o.config = $o.config | ConvertFrom-Json } else { $o | Add-Member -NotePropertyName "config" -NotePropertyValue "null" }
468 | if($o.filters -ne $null) {$o.filters = $o.filters | ConvertFrom-Json } else { $o | Add-Member -NotePropertyName "filters" -NotePropertyValue "null" }
469 |
470 | $o.pods | ForEach-Object { #what are pods? I dont know. But The script converts the JSON to an object anyhow
471 | $pod = $_
472 | if($pod.parameters -ne $null) {$pod.parameters = $pod.parameters | ConvertFrom-Json }
473 | }
474 |
475 | if($doIgnoreVisualQueryJSON -or $doIgnoreVisualDataTransformJSON)
476 | {
477 | " (some JSON data is ignored)"
478 | }
479 |
480 | $o.sections | ForEach-Object {
481 | $section = $_ # a Section is a PowerBI TAB
482 |
483 | if($section.config -ne $null) {$section.config = $section.config | ConvertFrom-Json } else { $section | Add-Member -NotePropertyName "config" -NotePropertyValue "null" }
484 | if($section.filters -ne $null) {$section.filters = $section.filters | ConvertFrom-Json } else { $section | Add-Member -NotePropertyName "filters" -NotePropertyValue "null" }
485 |
486 | #----------------------------------------------
487 | #"...convert nested JSON into powershell objects"
488 | # for JSON file output... convert major sections of JSON strings into the underlying objects
489 | #----------------------------------------------
490 | $section.visualContainers | ForEach-Object {
491 | $container = $_
492 |
493 | if($container.config -ne $null) {$container.config = $container.config | ConvertFrom-Json } else { $container | Add-Member -NotePropertyName "config" -NotePropertyValue "null" }
494 | if($container.filters -ne $null) {$container.filters = $container.filters | ConvertFrom-Json } else { $container | Add-Member -NotePropertyName "filters" -NotePropertyValue "null" }
495 | if($container.query -ne $null) {$container.query = $container.query | ConvertFrom-Json } else { $container | Add-Member -NotePropertyName "query" -NotePropertyValue "null" }
496 | if($container.dataTransforms -ne $null) {$container.dataTransforms = $container.dataTransforms | ConvertFrom-Json } else { $container | Add-Member -NotePropertyName "dataTransforms" -NotePropertyValue "null" }
497 |
498 |
499 | if($doIgnoreVisualQueryJSON) { $container.query = "ignored" }
500 | if($doIgnoreVisualDataTransformJSON) { $container.dataTransforms = "ignored" }
501 |
502 | #$container.config | Skip-Null | Get-Member | ForEach-Object { AddUniquePropNames $_ }
503 |
504 | $compareCounter = 10
505 | $container | Add-Member -NotePropertyName "compare_marker$compareCounter" -NotePropertyValue "Compare Markers are added to help file comparison software to align large complex JSON segments."
506 | For ($i=1; $i -le 10; $i++)
507 | {
508 | # for JSON file output... By adding 10 rows of mostly identical data, it will help comparison software to recognize where one object ends, and another starts, since compare software only looks at lines of code.
509 | $compareCounter += 1; $container | Add-Member -NotePropertyName "compare_marker$compareCounter" -NotePropertyValue ($section.name + "-" +$container.config.name)
510 | }
511 | $compareCounter += 1; $container | Add-Member -NotePropertyName "compare_marker$compareCounter" -NotePropertyValue ("tab: " + $section.displayName )
512 |
513 | # Add friendly names of the visual, if it exists
514 | $container.config | ForEach-Object {
515 | $visual = $_.singleVisual
516 | $friendlyName = Get-Visual-Friendly-Name $visual "(No Title)" #custom function to extract "Title" of visual if there is one.
517 | $container.compare_marker20 = $container.compare_marker20 + " - " + $friendlyName # this updates the JSON file output so that the "compare_marker" is a little more user friendly, but this code is only hit when evaluating measures.
518 | }
519 |
520 | # This code places "compare_marker10" at the top of the JSON object by removing and re-adding all other properties.
521 | $namesToSortInMiddle = $container.PSObject.Properties | Where-Object { -not $_.Name.StartsWith("compare_marker") } | select -ExpandProperty Name
522 | $namesToSortAtEnd = "config", "filters", "query", "dataTransforms"
523 |
524 | $container.PSObject.Properties | Sort-Object -Property Name | ForEach-Object {
525 | $name = $_.Name
526 | if(-not $namesToSortInMiddle.Contains($name)) { return } # These go at the top, eg. compare_marker10
527 | if($namesToSortAtEnd.Contains($name)) { return } # These go at the end
528 | $value = $_.Value
529 | $container.PSObject.Properties.Remove($name)
530 | $container | Add-Member $name $value
531 | }
532 | $container.PSObject.Properties | Sort-Object -Property Name | ForEach-Object {
533 | $name = $_.Name
534 | if(-not $namesToSortAtEnd.Contains($name)) { return } # These are already sorted
535 | $value = $_.Value
536 | $container.PSObject.Properties.Remove($name)
537 |
538 | $compareCounter += 1; $container | Add-Member -NotePropertyName "compare_marker$compareCounter" -NotePropertyValue ($section.name + "-" +$container.config.name+ "-" + $name)
539 | $container | Add-Member $name $value
540 | $compareCounter += 1; $container | Add-Member -NotePropertyName "compare_marker$compareCounter" -NotePropertyValue ($section.name + "-" +$container.config.name+ "-" + $name)
541 | }
542 |
543 | }
544 |
545 | #----------------------------------------------
546 | #"...extract a List of Measures or data columns from the JSON object"
547 | #----------------------------------------------
548 | if($doResolveDependencies -eq $true)
549 | {
550 | # $section.filters.value contain the DRILL filters
551 | $section.filters | ForEach-Object {
552 | $drill = $_.expression.Column
553 | if($drill -eq $null) {
554 | $drill = $_.expression.Measure
555 | }
556 | $drillTable = ($drill.Expression.SourceRef.Entity)
557 | $drillMeasure = ($drill.Property)
558 | #write-host "Drill: '$drillTable'[$drillMeasure] to " + $section.displayName
559 |
560 | AddVisualDependency 4 $section.displayName "DrillFilter" "$drillTable.$drillMeasure"
561 | }
562 |
563 | $section.visualContainers | ForEach-Object {
564 | $container = $_
565 | $container.config | ForEach-Object {
566 |
567 | $visual = $_.singleVisual
568 | $visualLabel = $visual.visualType + " " + $visual.name
569 | $friendlyName = Get-Visual-Friendly-Name $visual #custom function to extract "Title" of visual if there is one.
570 | if($friendlyName -ne "") { $visualLabel = $visual.visualType + " " + $friendlyName }
571 |
572 | # This line builds a distinct lists the names of object properties
573 | #$visual.prototypeQuery | Skip-Null | Get-Member | ForEach-Object { AddUniquePropNames $_ }
574 |
575 |
576 | #$visual.prototypeQuery.From
577 | #$visual.prototypeQuery.Select.Column.Expression | ForEach-Object { AddVisualDependency 2 $section.displayName $visualLabel $_ }
578 | #$visual.prototypeQuery.Select.Column.Property | ForEach-Object { AddVisualDependency 2 $section.displayName $visualLabel $_ }
579 | $visual.prototypeQuery.Select.Name | ForEach-Object { AddVisualDependency 2 $section.displayName $visualLabel $_ }
580 | $visual.prototypeQuery.Select.Measure.Property | ForEach-Object { AddVisualDependency 3 $section.displayName $visualLabel $_ }
581 | #$visual.prototypeQuery.Select.Measure.Expression | ForEach-Object { AddVisualDependency 2 $section.displayName $visualLabel $_ }
582 | #$visual.prototypeQuery.Version
583 | #$visual.prototypeQuery.OrderBy
584 |
585 | #"projections" THESE MEASURES ARE APPARENTLY DUPLICATED IN THE prototypeQuery
586 | # $visual.projections.Category.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
587 | # $visual.projections.Series.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
588 | # $visual.projections.Y.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
589 | # $visual.projections.Values.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
590 | # $visual.projections.Y2.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
591 | # $visual.projections.Tooltips.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
592 | # $visual.projections.Rows.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
593 | # $visual.projections.Goal.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
594 | # $visual.projections.Indicator.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
595 | # $visual.projections.TrendLine.queryRef | ForEach-Object { AddVisualDependency 1 $section.displayName $visualLabel $_ }
596 | }
597 | }
598 | }
599 |
600 | $section.visualContainers = $section.visualContainers | Sort-Object -Property compare_marker10 # for JSON file output... Sort so that comparison of this collection is more likely to match
601 | }
602 |
603 | $o.sections = $o.sections | Sort-Object -Property name # for JSON file output... Sort so that comparison of this collection is more likely to match
604 |
605 |
606 |
607 |
608 |
609 |
610 |
611 |
612 |
613 |
614 |
615 |
616 |
617 |
618 |
619 |
620 |
621 |
622 |
623 |
624 |
625 | "Evaluating the Data Sources of open PBIX files"
626 |
627 | $ProcessIdOfSelectedPowerBIFile = 0
628 |
629 | #----------------------------------------------
630 | # Connect to running SSAS Tabular Data Models in open PBIX files
631 | # (The Data Model is encrypted, so it can only be read from a running instance.)
632 | # (The running instance exposes a full SSAS server which can be queried like normal.)
633 | # 1-of-2 FIND THE SERVER CONNECTION Data
634 | #
635 | # steps for connecting powershell to PowerBI Desktop has been adapted from these sources
636 | # https://www.biinsight.com/four-different-ways-to-find-your-power-bi-desktop-local-port-number/
637 | # https://community.powerbi.com/t5/Desktop/Powershell-to-Access-Power-BI-Desktop/td-p/569193
638 | # https://sysnetdevops.com/2017/04/24/exploring-the-powershell-alternative-to-netstat/
639 | # https://audministrator.wordpress.com/2018/11/18/powershell-accessing-power-bi-desktop-data-and-more/
640 | #----------------------------------------------
641 | Get-Process PBIDesktop | foreach-object{
642 | $report = $_
643 | $reportProcessId = $_.Id
644 | $title = $report.mainWindowTitle.ToString().Trim()
645 | if($title -eq "") {
646 | log ("Found empty report: Title: $title ...process:$reportProcessId" )
647 | return # The PowerBI process is running, but a report isn't open... eg. the splash screen
648 | }
649 |
650 |
651 | if(-not $title.Contains($fileNameWithoutExtension)) {
652 | log ("Found open report: Title: $title ...process:$reportProcessId" )
653 | return # The PowerBI report not for the selected file
654 | }
655 |
656 | "Found selected report: $fileNameWithoutExtension ...process ID:$reportProcessId"
657 | $ProcessIdOfSelectedPowerBIFile = $reportProcessId
658 |
659 |
660 | #Find the running Child SSAS tabular model
661 | $Children = Get-WmiObject win32_process | where {$_.ParentProcessId -eq $reportProcessId}
662 |
663 | $Children | ForEach-Object{
664 | log (" child: of " + $_.ParentProcessId + " is " + $_.ProcessId + " for " + $_.ProcessName )
665 |
666 | if($_.ProcessName -eq "msmdsrv.exe"){
667 | # This is the SSSAS tabular model running as a SSAS server in memory, from the selected report file
668 | $ProcessIdOfSelectedTabularModel = $_.ProcessId
669 | "Found selected report: Tabular Model SSAS Server ...process ID: $ProcessIdOfSelectedTabularModel"
670 |
671 |
672 | #Handles NPM(K) PM(K) WS(K) CPU(s) Id SI ProcessName
673 | #------- ------ ----- ----- ------ -- -- -----------
674 | # 1812 52 125412 33740 6.27 6724 0 msmdsrv
675 | # 2137 163 185004 127140 3.34 150420 1 msmdsrv <-- this is a PowerBI .pbix file that is open and running as an SSAS cube (behind the scenes)
676 |
677 | #look for open ports on the SSAS tabular model process, so we can connect directly to the tabular model engine
678 | $found = $false
679 | Get-NetTCPConnection | ? { $_.State -eq "Listen" -and $_.OwningProcess -eq $ProcessIdOfSelectedTabularModel -and $_.LocalAddress -eq "127.0.0.1" } | ForEach-Object {
680 | $tcpConnection = $_
681 | " found port: " + $tcpConnection.LocalPort
682 | $script:ports.Add( $tcpConnection.LocalPort ) | Out-Null
683 | $found = $true
684 | }
685 |
686 | if($found -eq $false) { " no port found" }
687 | }
688 | }
689 | }
690 |
691 |
692 | #----------------------------------------------
693 | # Connect to running SSAS Tabular Data Models in open PBIX files
694 | # (The Data Model is encrypted, so it can only be read from a running instance.)
695 | # (The running instance exposes a full SSAS server which can be queried like normal.)
696 | # 2-of-2 READ THE SERVER DATA
697 | #----------------------------------------------
698 | [System.Reflection.Assembly]::LoadWithPartialName("Microsoft.AnalysisServices.Tabular") | Out-Null;
699 | $script:ports | ForEach-Object {
700 | $port = $_
701 | log (" Checking Port: " + $port)
702 |
703 | $server = "localhost:$port"
704 | $as = New-Object Microsoft.AnalysisServices.Tabular.Server;
705 | $as.Connect($server);
706 | "Connected to $server ...searching..."
707 | $as.Databases | ForEach-Object {
708 | $db = $_
709 |
710 | log-db-as-JSON "db" $db
711 |
712 | #---------------------------------------------------------------------
713 | #-- Read all Table and Measure data into memory
714 | #---------------------------------------------------------------------
715 |
716 | #Since this SSAS tabular model is linked to the open file, by ProcessID, it uses the same dependencySource
717 | $dependencySource = $fileName
718 | # old--> $dependencySource = ("" + $db.Server + " :: " + $db.Id) # eg: localhost:59522 :: ProjDB-02_ALincoln_21a49199-db43-40a3-90ec-87d1614c7b30
719 | log (" ID: " + $db.Id )
720 | log (" Server: " + $db.Server )
721 | log (" Connection: " + $server )
722 | log ("LastSchemaUpdate: " + $db.LastSchemaUpdate )
723 | log ("dependencySource: " + $dependencySource )
724 | log ""
725 | log ""
726 | log ""
727 |
728 |
729 | foreach($table in $db.Model.Tables | Sort-Object -Property Name) {
730 |
731 | $tableInQuotes = "'" + $table.Name + "'" # 'dimDate'
732 | log (" table:" + $tableInQuotes)
733 |
734 | log-db-as-JSON "table" $table
735 |
736 | $tableObject = New-Dependency $table.Name $table.Name $tableInQuotes $dependencySource #table/name/address/source
737 | $tableObject | Add-Member -MemberType NoteProperty -Name "LoweredName" -Value $table.Name.ToLower()
738 | $tableObject | Add-Member -MemberType NoteProperty -Name "LoweredQuotedName" -Value $tableInQuotes.ToLower()
739 | $tables[$table.Name] = $tableObject
740 |
741 |
742 | $table.Partitions | ForEach-Object { log-db-as-JSON "Partition" $_ }
743 | $table.Hierarchies | ForEach-Object { log-db-as-JSON "Hierarchy" $_ }
744 | $table.Annotations | ForEach-Object { log-db-as-JSON "Annotation" $_ }
745 | $table.ExtendedProperties | ForEach-Object { log-db-as-JSON "ExtendedProperty" $_ }
746 |
747 | foreach($sourceColumn in $table.Columns) {
748 | $columnInBrackets = "[" + $sourceColumn.Name + "]" # [Year]
749 | $address = $tableInQuotes + $columnInBrackets # eg. 'dimDate'[Year]
750 | log (" col:" + $columnInBrackets)
751 |
752 | log-db-as-JSON "column" $sourceColumn
753 |
754 | $column = New-Dependency $table.Name $sourceColumn.Name $address $dependencySource #table/name/address/source
755 | $column | Add-Member -MemberType NoteProperty -Name "BracketedName" -Value $columnInBrackets.ToLower()
756 | $column | Add-Member -MemberType NoteProperty -Name "UnBracketedName" -Value ($table.Name + $columnInBrackets).ToLower() # table name has no apostraphe, so: myTable[myColumn] instead of 'myTable'[myColumn]
757 | $column | Add-Member -MemberType NoteProperty -Name "LoweredName" -Value $address.ToLower()
758 | $column | Add-Member -MemberType NoteProperty -Name "Type" -Value $sourceColumn.DataType
759 | $column | Add-Member -MemberType NoteProperty -Name "Length" -Value $sourceColumn.Name.Length
760 |
761 | $columns[$address] = $column
762 | }
763 |
764 | foreach($sourceMeasure in $table.Measures) {
765 |
766 | log-db-as-JSON "measure" $sourceMeasure
767 |
768 | $measureInBrackets = "[" + $sourceMeasure.Name + "]" # [Year AVG]
769 | $address = $tableInQuotes + $measureInBrackets # eg. 'dimDate'[Year AVG]
770 | log (" measure: " + $measureInBrackets )
771 |
772 | if($doShowExpression){
773 | $fullExpression = "`r`n" + $sourceMeasure.Name + ":=`r`n" + $measure.Expression
774 | $script:measureExpressions.Add($fullExpression) | out-null
775 | log (" " + $fullExpression)
776 | }
777 |
778 | $measure = New-Dependency $table.Name $sourceMeasure.Name $address $dependencySource #table/name/address/source
779 | $measure | Add-Member -MemberType NoteProperty -Name "BracketedName" -Value $measureInBrackets.ToLower()
780 | $measure | Add-Member -MemberType NoteProperty -Name "Expression" -Value $sourceMeasure.Expression
781 | $measure | Add-Member -MemberType NoteProperty -Name "UsesMeasure" -Value @() # empty array, this will hold a list of measures that are dependencies of this measure
782 | $measure | Add-Member -MemberType NoteProperty -Name "UsesColumn" -Value @() # empty array, this will hold a list of columns that are dependencies of this measure
783 | $measure | Add-Member -MemberType NoteProperty -Name "UsesTable" -Value @() # empty array, this will hold a list of tables that are dependencies of this measure
784 | $measure | Add-Member -MemberType NoteProperty -Name "Length" -Value $sourceMeasure.Name.Length
785 |
786 | $measures[$address] = $measure
787 | }# end of $table.Measures
788 | }# end of $db.Model.Tables
789 | }# end of db.Databases
790 | $as.Disconnect();
791 | "Disconnected $server"
792 | }# end of $script:ports
793 |
794 |
795 | #----------------------------------------------
796 | # If the user asked to see the Measure Expressions, show them now...
797 | #----------------------------------------------
798 | if($doShowExpression){
799 | ""
800 | "#-----------------------"
801 | "# Measure Expressions "
802 | "#-----------------------"
803 | ""
804 | $script:measureExpressions
805 | ""
806 | ""
807 | }
808 |
809 |
810 |
811 |
812 |
813 | function Remove-Comments($code)
814 | {
815 | # handle both types of comments...
816 | # measure=
817 | # /*
818 | # get rid of this since it might reference a 'table'[column]
819 | # */
820 | # sum(Logic-To-Keep)
821 |
822 | # measure=
823 | # // get rid of this since it might reference a 'table'[column]
824 | # sum(Logic-To-Keep)
825 |
826 | $start = $code.IndexOf("/*") # MULTI-Line
827 | while($start -gt -1)
828 | {
829 |
830 | $end = $code.IndexOf("*/", $start);
831 | if($end -lt 0 -or $end -lt $start) { break } # malformed comment
832 | $textToRemove = $code.Substring($start, ($end - $start + 2)) # include both /* and */ in removal
833 | log "Removing comment: $textToRemove"
834 | $code = $code.Replace($textToRemove, "")
835 |
836 | $start = $code.IndexOf("/*")
837 | }
838 |
839 | $start = $code.IndexOf("//") # SINGLE-Line
840 | while($start -gt -1)
841 | {
842 | $end = $code.IndexOf("`n", $start);
843 | if($end -lt $start) { $end = $code.Length } # go to end of text (eg. you are on the final line of text)
844 | $textToRemove = $code.Substring($start, ($end - $start))
845 | log "Removing comment: $textToRemove"
846 | $code = $code.Replace($textToRemove, "")
847 |
848 | $start = $code.IndexOf("//")
849 | }
850 |
851 | return $code
852 | }
853 |
854 | #---------------------------------------------------------------------
855 | #-- Process each measure. (Discover its dependencies)
856 | # Find columns based on: 'tbl'[col]
857 | # Find columns based on: tbl[col]
858 | # Find measures based on: [meas]
859 | # Find columns based on: [col] ...no table just [col]
860 | # Find table name in quotes: 'dimDate' ...no column
861 | # Find table name (no quotes): dimDate ...no column
862 | #---------------------------------------------------------------------
863 | if($doResolveDependencies)
864 | {
865 | "Finding dependencies"
866 |
867 | ForEach($measure in $measures.Values)
868 | {
869 | if($measure -eq $null) {continue}
870 | if($measure.Expression -eq $null) {continue}
871 |
872 | $foundTextReplacement = "DependencyWasFoundHere"
873 |
874 | $code = $measure.Expression.ToLower()
875 | if($code.StartsWith("`"") -and $code.EndsWith("`"")) { $code = "" } # This measure only returns "text". It does not actually reference columns or other measures
876 |
877 | $code = Remove-Comments $code #If a comment references another measure, it is NOT a dependecy, so remove all comments
878 |
879 | log ""
880 | log ("searching for dependencies in " + $measure.Address)
881 |
882 | #---------------------------------------------------------------------
883 | #-- Find Dependencies based on various textual conventions
884 | #---------------------------------------------------------------------
885 | $foundDependencies = $false
886 |
887 |
888 | # Find columns based on: 'tbl'[col]
889 | Foreach($column in $columns.Values | Where-Object { $code.Contains($_.LoweredName) } | Sort-Object -Property Length -Descending ) # Sort-Object as longest first so that "Total YTD" comes before "Total"
890 | {
891 | $foundDependencies = $true; log ("found dependency: col " + $column.Name)
892 | if($measure.UsesColumn -notcontains $column){ $measure.UsesColumn += $column }
893 | $code = $code.Replace($column.LoweredName, $foundTextReplacement) # removed the text that was found so it isn't found again
894 | }
895 |
896 | # Find columns based on: tbl[col]
897 | Foreach($column in $columns.Values | Where-Object { $code.Contains($_.UnBracketedName) } | Sort-Object -Property Length -Descending )# Sort-Object as longest first so that "Total YTD" comes before "Total"
898 | {
899 | $foundDependencies = $true; log ("found dependency: col " + $column.Name)
900 | if($measure.UsesColumn -notcontains $column){ $measure.UsesColumn += $column }
901 | $code = $code.Replace($column.UnBracketedName, $foundTextReplacement) # removed the text that was found so it isn't found again
902 | }
903 |
904 | # Find measures based on: [meas]
905 | Foreach($dependency in $measures.Values | Where-Object { $code.Contains($_.BracketedName) } | Sort-Object -Property Length -Descending )# Sort-Object as longest first so that "Total YTD" comes before "Total"
906 | {
907 | $foundDependencies = $true; log ("found dependency: measure " + $dependency.Name)
908 | if($measure.UsesMeasure -notcontains $dependency){ $measure.UsesMeasure += $dependency }
909 | $code = $code.Replace($dependency.BracketedName, $foundTextReplacement) # removed the text that was found so it isn't found again
910 | }
911 |
912 | # Find columns based on: [col] ...no table just [col]
913 | Foreach($column in $columns.Values | Where-Object { $code.Contains($_.BracketedName) } | Sort-Object -Property Length -Descending )# Sort-Object as longest first so that "Total YTD" comes before "Total"
914 | {
915 | $foundDependencies = $true; log ("found dependency: col " + $column.Name)
916 | if($measure.UsesColumn -notcontains $column){ $measure.UsesColumn += $column }
917 | $code = $code.Replace($column.BracketedName, $foundTextReplacement) # removed the text that was found so it isn't found again
918 | }
919 |
920 | if(-not $foundDependencies)
921 | {
922 | # The measure formula does not contain a column or another measure.
923 | # Maybe it only returns a number or static text
924 | # But maybe it references a table without referencing a specific column... like: COUNTROWS ( 'tableName' )
925 | # We do not want to search for all table text, since some 'filter' measures would duplicate... filter ( 'tableName', 'tableName'[Column] <> "some value" ), <-- no need to reference 'tableName' twice
926 |
927 | # Find dependencies based on table name in quotes: 'dimDate'
928 | Foreach($table in $tables.Values | Where-Object { $code.Contains($_.LoweredQuotedName) } | Sort-Object -Property Length -Descending )# Sort-Object as longest first so that "Total YTD" comes before "Total"
929 | {
930 | $foundDependencies = $true; log ("found dependency: table " + $table.Name)
931 | if($measure.UsesTable -notcontains $table){ $measure.UsesTable += $table }
932 | $code = $code.Replace($table.LoweredQuotedName, $foundTextReplacement) # removed the text that was found so it isn't found again
933 | }
934 | # Find dependencies based on table name (no quotes): dimDate
935 | Foreach($table in $tables.Values | Where-Object { $code.Contains($_.LoweredName) } | Sort-Object -Property Length -Descending )# Sort-Object as longest first so that "Total YTD" comes before "Total"
936 | {
937 | $foundDependencies = $true; log ("found dependency: table " + $table.Name)
938 | if($measure.UsesTable -notcontains $table){ $measure.UsesTable += $table }
939 | $code = $code.Replace($table.LoweredName, $foundTextReplacement) # removed the text that was found so it isn't found again
940 | }
941 | }
942 |
943 | #---------------------------------------------------------------------
944 | #-- Output what was discovered to the screen
945 | #---------------------------------------------------------------------
946 | #TODO: When coding this Powershell Script, use this to look at progress
947 | # if($foundDependencies)
948 | # {
949 | # #$measure.Expression
950 | # #$measure.UsesColumn | ForEach-Object { write-output ($measure.Address + "`t...uses...`tcolumn`t" + $_.Address ) }
951 | # #$measure.UsesMeasure | ForEach-Object { write-output ($measure.Address + "`t...uses...`tmeasure`t" + $_.Address ) }
952 | # }
953 | # else
954 | # {
955 | # $measure.Address + "`t...references...`tnull`tNo Dependencies?"
956 | # }
957 |
958 | #---------------------------------------------------------------------
959 | #-- Output what has changed to the screen
960 | #---------------------------------------------------------------------
961 | #TODO: When coding this Powershell Script, use this to see how the dependencies have been replaced with "DependencyWasFoundHere" and to see what's left over
962 | # ""
963 | # ""
964 | # "----searching dependencies in measure expression..."
965 | # "----original"
966 | # $measure.Expression
967 | # "----result (with Dependencies removed)"
968 | # $code
969 | # ""
970 |
971 |
972 | if($code.Contains("["))
973 | {
974 | ""
975 | "DEPENDENCY PARSING WAS NOT ABLE TO RESOLVE ALL BRACKETTED TEXT: (eg. a reference to [column] or [measure] was unrecognized)"
976 | "ERROR IN " + $measure.Address
977 | $code
978 | }
979 |
980 | log ($measure.Name + " was parsed into...`r`n" + $code)
981 | }
982 | }
983 |
984 |
985 | "done" # Discovering data is complete. Outputing data comes next
986 |
987 |
988 |
989 |
990 |
991 |
992 |
993 |
994 |
995 |
996 |
997 |
998 |
999 |
1000 |
1001 |
1002 |
1003 |
1004 |
1005 |
1006 |
1007 |
1008 |
1009 |
1010 | #---------------------------------------------
1011 | # The objects within a PowerBI report has changed, and will change, over time.
1012 | # This code is used to read sections of the PowerBI report object, and discover what unique Property Names exists
1013 | # This is NOT used during normal execution, but is useful while coding this powershell script over time
1014 | # STEP: 2-of-2 Show results of previous research
1015 | # usage
1016 | # $visual.prototypeQuery | Skip-Null | Get-Member | ForEach-Object { AddUniquePropNames $_ }
1017 | # |<------------------>| ...Update that section for each object you are researching
1018 | #---------------------------------------------
1019 | if($script:propertyNames.Length -gt 0){
1020 | "------------------------------"
1021 | "These Property Names were discovered in the object, using AddUniquePropNames:"
1022 | ""
1023 | $script:propertyNames
1024 | "------------------------------"
1025 | }
1026 |
1027 |
1028 | #----------------------------------------------
1029 | #"... save a formatted JSON file of the PBIX content"
1030 | #----------------------------------------------
1031 | if($doGenerateJson -eq $true)
1032 | {
1033 | ""
1034 | ""
1035 | "Converting PBIX file to a formatted JSON file"
1036 |
1037 | $uglyJSON = $wrapper | ConvertTo-Json -Depth 100
1038 |
1039 | #attempt to use JSON.net for formatting, if present
1040 | $pathToNewtonsoftJsonNet = $PSScriptRoot + "\Newtonsoft.Json.dll" # $PSScriptRoot is a default variable to the folder containing the Powershell script (assuming it is saved)
1041 | if((test-path -Path $pathToNewtonsoftJsonNet))
1042 | {
1043 | "loading Newtonsoft.Json.dll"
1044 | #load NewtonSoft
1045 | # https://stackoverflow.com/questions/12923074/how-to-load-assemblies-in-powershell/37468429#37468429
1046 | # this locks the dll file... Add-Type -Path $pathToNewtonsoftJsonNet
1047 | $bytes = [System.IO.File]::ReadAllBytes($pathToNewtonsoftJsonNet)
1048 | [System.Reflection.Assembly]::Load($bytes) | Out-Null
1049 |
1050 | # JSON.net has a prettier output than native Powershell JSON which can be unreadable
1051 | $rawJSON = [Newtonsoft.Json.Linq.JToken]::Parse($uglyJSON).ToString()
1052 | }
1053 | else
1054 | {
1055 | "A DLL to NewtonSoft JSON.Net could not be found at $pathToNewtonsoftJsonNet"
1056 | "This DLL produces a JSON format that is easier to read. Without it, the file will save using the Powershell Json format."
1057 | "This DLL can be downloaded from here: https://www.newtonsoft.com/json and copy the .dll from the unzipped bin, eg: \Bin\net45\Newtonsoft.Json.dll"
1058 | $rawJSON = $uglyJSON.Replace(" ", " ").Replace(" ", " ")
1059 | }
1060 | "JSON transformed"
1061 |
1062 |
1063 | $newFileName = [System.IO.Path]::GetFileNameWithoutExtension($choiceOfFile) + ".json"
1064 | $FinalJSONFile = $choiceOfFile.Replace($fileName, $newFileName) # The original path, but new file name
1065 | $rawJSON | Out-File $FinalJSONFile
1066 |
1067 | "JSON File Saved to $FinalJSONFile"
1068 | ""
1069 | }
1070 |
1071 |
1072 |
1073 |
1074 |
1075 |
1076 |
1077 |
1078 |
1079 |
1080 |
1081 |
1082 |
1083 |
1084 | #----------------------------------------------
1085 | # This function is used to build a SQL Insert Script for each measure/column/visual
1086 | #----------------------------------------------
1087 | function AddSQL($parent, $parentType, $child, $childType, $content)
1088 | {
1089 | if($doShowSqlScript -eq $false) {return}
1090 |
1091 | #note the $parent is an object of type: New-Dependency($table, $name, $address, $source)
1092 | #note the $child is an object of type: New-Dependency($table, $name, $address, $source)
1093 |
1094 | $DependencySource = $parent.Source.Replace("'", "''")
1095 | $ParentLocation = $parent.Table.Replace("'", "''")
1096 | $ParentName = $parent.Name.Replace("'", "''")
1097 | $ParentAddress = $parent.Address.Replace("'", "''")
1098 | $ChildLocation = If ($child -ne $null) {$child.Table.Replace("'", "''") } Else { $null }
1099 | $ChildName = If ($child -ne $null) {$child.Name.Replace("'", "''") } Else { $null }
1100 | $ChildAddress = If ($child -ne $null) {$child.Address.Replace("'", "''") } Else { $null }
1101 | $content = If ($content -ne $null) {"'" + $content.Replace("'", "''") + "'" } Else { 'null' }
1102 |
1103 |
1104 | # $script:sql <-- syntax for referencing a variable in the scope of this powershell script is $script:variableName
1105 | $script:sql += "INSERT INTO [dbo].[Dependencies] ([Source]`r`n"
1106 | $script:sql += " ,[ParentLocation],[ParentName],[ParentAddress],[ParentType]`r`n"
1107 | $script:sql += " ,[ChildLocation], [ChildName], [ChildAddress], [ChildType] `r`n"
1108 | $script:sql += " ,[Content])`r`n"
1109 | $script:sql += " VALUES ('$DependencySource'`r`n"
1110 | $script:sql += " ,'$ParentLocation'`r`n"
1111 | $script:sql += " ,'$ParentName'`r`n"
1112 | $script:sql += " ,'$ParentAddress'`r`n"
1113 | $script:sql += " ,'$parentType'`r`n"
1114 | $script:sql += " ,'$ChildLocation'`r`n"
1115 | $script:sql += " ,'$ChildName'`r`n"
1116 | $script:sql += " ,'$ChildAddress'`r`n"
1117 | $script:sql += " ,'$childType'`r`n"
1118 | $script:sql += " ,$content)`r`n"
1119 | }
1120 |
1121 |
1122 | #----------------------------------------------
1123 | # This SQL removes old data from the Dependencies table for the same source (file or SSAS Cube)
1124 | #----------------------------------------------
1125 | function AddSqlPrefix($dependencySource){
1126 | # Assume that the user is replacing all SQL objects for this data source
1127 | $script:sql += "`r`n"
1128 | $script:sql += "--The line below will delete all prior data related to SSAS dependencies `r`n"
1129 | $script:sql += "delete from [dbo].[Dependencies] where [Source] = '$dependencySource'`r`n"
1130 | $script:sql += "select 'rows deleted:' [compare], @@RowCount as [Deleted], '$dependencySource' [Source]`r`n`r`n"
1131 | $script:sql += "`r`n"
1132 | }
1133 |
1134 | #----------------------------------------------
1135 | # This SQL checks how many rows were inserted for the source (file or SSAS Cube)
1136 | #----------------------------------------------
1137 | function AddSqlSuffix($dependencySource, $expectedCount){
1138 | $script:sql += "`r`n"
1139 | $script:sql += "`r`n"
1140 | $script:sql += "`r`n SELECT"
1141 | $script:sql += "`r`n 'rows inserted:' as [compare]"
1142 | $script:sql += "`r`n ,count(*) as [actual]"
1143 | $script:sql += "`r`n ,$expectedCount as [expected]"
1144 | $script:sql += "`r`n ,'$dependencySource' as [source]"
1145 | $script:sql += "`r`n FROM [dbo].[Dependencies] "
1146 | $script:sql += "`r`n WHERE [Source] = '$dependencySource'"
1147 | $script:sql += "`r`n"
1148 | $script:sql += "--WARNING previous Dependencies are DELETED by default.`r`n"
1149 | $script:sql += "--Scroll to the top to edit the `"Delete`" script. `r`n"
1150 | $script:sql += "`r`n"
1151 | }
1152 |
1153 | #----------------------------------------------
1154 | #"...optionally output dependencies of visuals as SQL scripts"
1155 | #----------------------------------------------
1156 | if($doShowSqlScript -eq $true)
1157 | {
1158 |
1159 | $dependencySource = ""
1160 | $expectedCount = 0
1161 |
1162 | ForEach($visual in $visuals.Values)
1163 | {
1164 | # ------------- 1-of-5 ------- Prefix ----------------
1165 | # The SQL scripts have a prefix and suffix to remove prior data for the same dependencySource (file or SSAS Cube)
1166 | $oldSource = $dependencySource
1167 | $dependencySource = $visual.Source
1168 | if($dependencySource -ne $oldSource) {
1169 | if($oldSource -ne ""){
1170 | # Add suffix for previous Source
1171 | AddSqlSuffix $dependencySource $expectedCount
1172 | $expectedCount = 0
1173 | }
1174 | AddSqlPrefix $dependencySource
1175 | }
1176 |
1177 |
1178 | # ------------- 2-of-5 ------- Visuals from PBIX file ----------------
1179 | $visual.UsesMeasure | ForEach-Object {
1180 | AddSQL $visual "visual" $_ "measure" $null
1181 | $expectedCount += 1
1182 | }
1183 | }
1184 |
1185 |
1186 | # ------------- 3-of-5 ------- Measures from SSAS Cube ----------------
1187 | ForEach($measure in $measures.Values)
1188 | {
1189 | # The SQL scripts have a prefix and suffix to remove prior data for the same dependencySource (file or SSAS Cube)
1190 | $oldSource = $dependencySource
1191 | $dependencySource = $measure.Source
1192 | if($dependencySource -ne $oldSource) {
1193 |
1194 | log ("dependency source changed: [$oldSource] -ne [$dependencySource]")
1195 |
1196 | if($oldSource -ne ""){
1197 | # Add suffix for previous Source
1198 | AddSqlSuffix $dependencySource $expectedCount
1199 | $expectedCount = 0
1200 | }
1201 | AddSqlPrefix $dependencySource
1202 | }
1203 |
1204 | $measure.UsesTable | ForEach-Object {
1205 | AddSQL $measure "measure" $_ "table" $null
1206 | $expectedCount += 1
1207 | }
1208 | $measure.UsesColumn | ForEach-Object {
1209 | AddSQL $measure "measure" $_ "column" $null
1210 | $expectedCount += 1
1211 | }
1212 | $measure.UsesMeasure | ForEach-Object {
1213 | AddSQL $measure "measure" $_ "measure" $null
1214 | $expectedCount += 1
1215 | }
1216 |
1217 | # Add DAX expression of measure to SQL data
1218 | $dax = New-Dependency "" "DAX" "" #table/name/address
1219 | $expression = $measure.Name + ":=`r`n" + $measure.Expression
1220 | AddSQL $measure "measure" $dax "DAX" $expression
1221 | $expectedCount += 1
1222 |
1223 | }
1224 |
1225 | # ------------- 4-of-5 ------- Columns from SSAS Cube ----------------
1226 | $columns.Values | ForEach-Object {
1227 | AddSQL $_ "column" $null $null $null # no dependencies of columns... but what if they are calculated???? hmmm.
1228 | $expectedCount += 1
1229 | }
1230 |
1231 | # ------------- 5-of-5 ------- Suffix ----------------
1232 | # The SQL scripts have a prefix and suffix to remove prior data for the same dependencySource (file or SSAS Cube)
1233 | if($dependencySource -ne ""){ AddSqlSuffix $dependencySource $expectedCount }
1234 |
1235 | ""
1236 | "The SQL script will now be copied to your clipboard and also displayed."
1237 | Read-Host "press Enter to continue."
1238 |
1239 | cls
1240 |
1241 | $script:sql | clip # hold in clipboard
1242 | $script:sql # write to screen
1243 |
1244 |
1245 | ""
1246 | "The code above has already been placed on the clipboard. "
1247 | "Copy the above code and review it before executing. "
1248 | "Be aware of line breaks which may alter SQL code when copied from the Powershell window"
1249 | }
1250 |
1251 |
1252 |
1253 |
1254 |
1255 |
1256 |
1257 |
1258 |
1259 |
1260 |
1261 |
1262 |
1263 |
1264 |
1265 |
1266 |
1267 |
1268 |
1269 | #---------------------------------------------------------------------
1270 | #-- Output Table Rows/Columns
1271 | #---------------------------------------------------------------------
1272 | if($doShowTabbedTable) {
1273 |
1274 | ""
1275 | "The tabbed data will now be copied to your clipboard and also displayed."
1276 | Read-Host "press Enter to continue."
1277 |
1278 | cls
1279 | $tabbedData = "`r`n`r`n"
1280 | $tabbedData += "Table`tName`tAddress`tType`t...References...`tTable`tName`tAddress`tType`tSource`r`n"
1281 |
1282 | if($doFilter)
1283 | {
1284 | $columns.Values | Where-Object {$_.LoweredName -like $loweredFilter} | ForEach-Object {
1285 | $tabbedData += "{0}`t{1}`t{2}`t{3}`t>>`t{4}`t{5}`t{6}`t{7}`t{8}`r`n" -f $_.Table, $_.Name, $_.Address, 'column', "Nothing", $null, $null, $null, $dbId
1286 | }
1287 | }
1288 | else # all columns
1289 | {
1290 | $columns.Values | ForEach-Object {
1291 | $tabbedData += "{0}`t{1}`t{2}`t{3}`t>>`t{4}`t{5}`t{6}`t{7}`t{8}`r`n" -f $_.Table, $_.Name, $_.Address, 'column', "Nothing", $null, $null, $null, $dbId
1292 | }
1293 | }
1294 |
1295 |
1296 | ForEach($measure in $measures.Values)
1297 | {
1298 | $measure.UsesTable | ForEach-Object {
1299 | $tabbedData += "{0}`t{1}`t{2}`t{3}`t>>`t{4}`t{5}`t{6}`t{7}`t{8}`r`n" -f $measure.Table, $measure.Name, $measure.Address, 'measure', $_.Table, $_.Name, $_.Address, 'table', $dbId
1300 | }
1301 | $measure.UsesColumn | ForEach-Object {
1302 | $tabbedData += "{0}`t{1}`t{2}`t{3}`t>>`t{4}`t{5}`t{6}`t{7}`t{8}`r`n" -f $measure.Table, $measure.Name, $measure.Address, 'measure', $_.Table, $_.Name, $_.Address, 'column', $dbId
1303 | }
1304 | $measure.UsesMeasure | ForEach-Object {
1305 | $tabbedData += "{0}`t{1}`t{2}`t{3}`t>>`t{4}`t{5}`t{6}`t{7}`t{8}`r`n" -f $measure.Table, $measure.Name, $measure.Address, 'measure', $_.Table, $_.Name, $_.Address, 'measure', $dbId
1306 | }
1307 | }
1308 |
1309 |
1310 | $tabbedData | clip # hold in clipboard
1311 | $tabbedData # write to screen
1312 | ""
1313 | ""
1314 | "The data above has already been placed on the clipboard. "
1315 |
1316 | }
--------------------------------------------------------------------------------