public TabularModelHandler ResetAndConnect() { CreateTestModel(TestFileName); var tm = new TabularModelHandler(TestFileName); TabularDeployer.Deploy(tm, Constants.ServerName, TestDBName, DeploymentOptions.Full); return(new TabularModelHandler(Constants.ServerName, TestDBName)); }
public TabularTree(TabularModelHandler handler) { if (handler == null) { return; } Handler = handler; Handler.Tree = this; }
public void Stop() { if (trace == null || !trace.IsStarted) { return; } trace.Stop(); TabularModelHandler.Log("Analysis Services trace stopped"); }
public static void Cleanup() { lock (tabularEditorSessionTraces) { foreach (var trace in tabularEditorSessionTraces) { CleanupTrace(trace); } tabularEditorSessionTraces.Clear(); TabularModelHandler.Log("Analysis Services trace cleanup completed"); } }
/// <summary> /// Creates a TabularObject representing the provided TOM MetadataObject. /// </summary> /// <param name="metadataObject"></param> protected TabularObject(TOM.MetadataObject metadataObject) { if (metadataObject == null) { throw new ArgumentNullException("metadataObject"); } _metadataObject = metadataObject; Handler = TabularModelHandler.Singleton; Handler.WrapperLookup[metadataObject] = this; // Assign collection based on parent: if (metadataObject.Parent != null) { Collection = (Handler.WrapperLookup[metadataObject.Parent] as TabularObject).GetCollectionForChild(this); } }
public static void Cleanup() { lock (tabularEditorSessionTraces) { try { foreach (var trace in tabularEditorSessionTraces) { CleanupTrace(trace); } tabularEditorSessionTraces.Clear(); TabularModelHandler.Log("Analysis Services trace cleanup completed"); } catch (Exception ex) { TabularModelHandler.Log("Error occurred during trace cleanup: " + ex.Message); } } }
private void Configure() { if (server == null) { return; } if (!server.ConnectionInfo.Server.EqualsI("localhost")) { return; } try { currentTraceName = traceNamePrefix + Guid.NewGuid().ToString("D"); this.trace = server.Traces.Add(currentTraceName); tabularEditorSessionTraces.Add(this.trace); TOM.TraceEvent tEvent; tEvent = this.trace.Events.Add(AS.TraceEventClass.CommandEnd); tEvent.Columns.Add(AS.TraceColumn.EventSubclass); tEvent.Columns.Add(AS.TraceColumn.Success); tEvent.Columns.Add(AS.TraceColumn.TextData); tEvent.Columns.Add(AS.TraceColumn.ApplicationName); tEvent.Columns.Add(AS.TraceColumn.DatabaseName); tEvent = this.trace.Events.Add(AS.TraceEventClass.ProgressReportCurrent); tEvent.Columns.Add(AS.TraceColumn.IntegerData); tEvent.Columns.Add(AS.TraceColumn.CurrentTime); tEvent.Columns.Add(AS.TraceColumn.ObjectName); tEvent.Columns.Add(AS.TraceColumn.ObjectPath); tEvent.Columns.Add(AS.TraceColumn.DatabaseName); this.trace.OnEvent += Trace_OnEvent; this.trace.Update(); TabularModelHandler.Log("Analysis Services trace configured on localhost"); } catch (Exception ex) { this.trace = null; TabularModelHandler.Log("Exception while configuring Analysis Services trace", ex); } }
public static void Cleanup() { lock (tabularEditorSessionTraces) { foreach (var trace in tabularEditorSessionTraces) { if (trace.IsStarted) { trace.Stop(); } if (trace.Parent != null) { trace.Drop(); } trace.Dispose(); } tabularEditorSessionTraces.Clear(); TabularModelHandler.Log("Analysis Services trace cleanup completed"); } }
public void CreateTableTest() { const string tableName = "My Table"; var tm = new TabularModelHandler(); var t = tm.Model.AddTable(tableName); // Check that table was created correctly: Assert.AreEqual(tableName, t.Name); Assert.AreEqual(tm.Model, t.Parent); // New data source should have been created: Assert.AreEqual(1, tm.Model.DataSources.Count); Assert.AreEqual(DataSourceType.Provider, tm.Model.DataSources[0].Type); // Table partition should have been created: Assert.AreEqual(1, t.Partitions.Count); Assert.AreEqual("My Table", t.Partitions[0].Name); Assert.AreEqual(PartitionSourceType.Query, t.Partitions[0].SourceType); Assert.AreEqual(tm.Model.DataSources[0], t.Partitions[0].DataSource); }
public void CreateCalculatedTableTest() { const string tableName = "My CalcTable"; const string expression = "ROW(\"Test\", 1)"; var tm = new TabularModelHandler(); var t = tm.Model.AddCalculatedTable(tableName, expression); // Check that table was created correctly: Assert.AreEqual(tableName, t.Name); Assert.AreEqual(expression, t.Expression); Assert.AreEqual(tm.Model, t.Parent); // New data source should not have been created: Assert.AreEqual(0, tm.Model.DataSources.Count); // Table partition should have been created: Assert.AreEqual(1, t.Partitions.Count); Assert.AreEqual(tableName, t.Partitions[0].Name); Assert.AreEqual(PartitionSourceType.Calculated, t.Partitions[0].SourceType); Assert.AreEqual(expression, t.Partitions[0].Expression); }
public void Start() { try { if (trace == null) { Configure(); } if (trace != null) { if (!trace.IsStarted) { trace.Start(); TabularModelHandler.Log("Analysis Services trace started"); } } } catch (Exception ex) { TabularModelHandler.Log("Exception while starting Analysis Services trace", ex); } }
public NullTree(TabularModelHandler handler) : base(handler) { }
public static bool HasTabularEditorTag(this TabularModelHandler handler) { return(handler.Model.MetadataObject.Annotations.Contains(TabularEditorTag)); }
/// <summary> /// Creates a simple model for unit testing. /// </summary> /// <remarks> /// The model will contain: /// - 1 data source: "Test Datasource" /// - 2 roles: "Test Role 1", "Test Role 2" /// - 2 cultures: "da-DK", "en-US" (all objects translated in these) /// - 2 perspectives: "Test Perspective 1", "Test Perspective 2" /// - 2 tables: "Test Table 1", "Test Table 2" /// - 1 calculated table: "Test CalcTable 1" /// - "Test Table 1" contains: /// - 3 columns, 1 calculated column /// - 1 hierarchy (4 levels - one per column) /// - 2 measures, 1 with kpi /// - "Test Table 2" contains: /// - 3 columns, 1 calculated column /// - 1 hierarchy /// - 1 relationship /// </remarks> /// <param name="fileName">If specified, the model will be saved to this file.</param> /// <param name="compatibilityLevel">Specify the compatibility level of the created model.</param> public static TabularModelHandler CreateTestModel(string fileName = null, int compatibilityLevel = 1200) { var tm = new TabularModelHandler(compatibilityLevel); var ds = tm.Model.AddDataSource("Test Datasource"); ds.ConnectionString = "Provider=MSOLEDBSQL;Data Source=localhost;Initial Catalog=db"; var r1 = tm.Model.AddRole("Test Role 1"); var r2 = tm.Model.AddRole("Test Role 2"); var c1 = tm.Model.AddTranslation("da-DK"); var c2 = tm.Model.AddTranslation("en-US"); var p1 = tm.Model.AddPerspective("Test Perspective 1"); var p2 = tm.Model.AddPerspective("Test Perspective 2"); var t1 = tm.Model.AddTable("Test Table 1"); var t2 = tm.Model.AddTable("Test Table 2"); // Create calculated table based on table 2: var t3 = tm.Model.AddCalculatedTable("Test CalcTable 1", @"DATATABLE ( ""String Column"", STRING, ""Decimal Column"", CURRENCY, ""Int Column"", INTEGER, ""Date Column"", DATETIME, ""Boolean Column"", BOOLEAN, ""Double Column"", DOUBLE, { { ""Category A"", -50.1234, -5, ""2017-01-01"", TRUE, 5.134E17 }, { ""Category B"", 3.1415, 2, ""2017-01-02"", FALSE, 9.761E-12 }, { ""Category C"", 45.9876, 8, ""2017-01-03"", TRUE, 1.654 }, { """", 0, 0, 0, FALSE, 0}, { , , , , , } } )"); var c11 = t1.AddDataColumn("Column 1"); var c12 = t1.AddDataColumn("Column 2"); var c13 = t1.AddDataColumn("Column 3"); var c14 = t1.AddCalculatedColumn("Column 4", "[Column 1]"); var h1 = t1.AddHierarchy("Hierarchy 1", null, c11, c12, c13, c14); h1.Levels[0].Name = "Level 1"; h1.Levels[1].Name = "Level 2"; h1.Levels[2].Name = "Level 3"; h1.Levels[3].Name = "Level 4"; var c21 = t2.AddDataColumn("Column 1"); var c22 = t2.AddDataColumn("Column 2"); var c23 = t2.AddDataColumn("Column 3"); var c24 = t2.AddCalculatedColumn("Column 4", "[Column 1]"); var h2 = t2.AddHierarchy("Hierarchy 1", null, c21, c22, c23, c24); var r = tm.Model.AddRelationship(); r.FromColumn = c11; r.ToColumn = c21; var m1 = t1.AddMeasure("Measure 1", "sum('Test CalcTable 1'[Decimal Column])"); var m2 = t1.AddMeasure("Measure 2", "sum('Test CalcTable 1'[Int Column])"); var k1 = m1.AddKPI(); // Apply translations to all items in table 1: var items = t1.GetChildren().Concat(t1.AllLevels).Concat(Enumerable.Repeat(t1, 1)); foreach (var item in items.OfType <ITranslatableObject>()) { item.TranslatedNames["da-DK"] = item.Name + " DK"; item.TranslatedNames["en-US"] = item.Name + " US"; } // Include all items in table 1 in perspective: foreach (var item in t1.GetChildren().OfType <ITabularPerspectiveObject>()) { item.InPerspective.All(); } if (!string.IsNullOrEmpty(fileName)) { tm.Save(fileName, SaveFormat.ModelSchemaOnly, SerializeOptions.Default); } return(tm); }
internal TabularCommonActions(TabularModelHandler handler) { Handler = handler; }
static bool HandleCommandLine(string[] args) { var upperArgList = args.Select(arg => arg.ToUpper()).ToList(); var argList = args.Select(arg => arg).ToList(); if (upperArgList.Contains("-?") || upperArgList.Contains("/?") || upperArgList.Contains("-H") || upperArgList.Contains("/H") || upperArgList.Contains("HELP")) { OutputUsage(); return(true); } enableVSTS = upperArgList.IndexOf("-VSTS") > -1 || upperArgList.IndexOf("-V") > -1; var warnOnUnprocessed = upperArgList.IndexOf("-WARN") > -1 || upperArgList.IndexOf("-W") > -1; TabularModelHandler h; if (args.Length == 2 || args[2].StartsWith("-")) { // File argument provided (either alone or with switches), i.e.: // TabularEditor.exe myfile.bim // TabularEditor.exe myfile.bim -... if (!File.Exists(args[1]) && !File.Exists(args[1] + "\\database.json")) { Error("File not found: {0}", args[1]); return(true); } else { // If nothing else was specified on the command-line, open the UI: if (args.Length == 2) { return(false); } } try { h = new TOMWrapper.TabularModelHandler(args[1]); } catch (Exception e) { Error("Error loading file: " + e.Message); return(true); } } else if (args.Length == 3 || args[3].StartsWith("-")) { // Server + Database argument provided (either alone or with switches), i.e.: // TabularEditor.exe localhost AdventureWorks // TabularEditor.exe localhost AdventureWorks -... // If nothing else was specified on the command-line, open the UI: if (args.Length == 3) { return(false); } try { h = new TOMWrapper.TabularModelHandler(args[1], args[2]); } catch (Exception e) { Error("Error loading model: " + e.Message); return(true); } } else { // Otherwise, it's nonsensical return(false); } string script = null; string scriptFile = null; var doScript = upperArgList.IndexOf("-SCRIPT"); if (doScript == -1) { doScript = upperArgList.IndexOf("-S"); } if (doScript > -1) { if (upperArgList.Count <= doScript) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } scriptFile = argList[doScript + 1]; if (!File.Exists(scriptFile)) { Error("Specified script file not found.\n"); return(true); } script = File.ReadAllText(scriptFile); } string buildOutputPath = null; var doSave = upperArgList.IndexOf("-BUILD"); if (doSave == -1) { doSave = upperArgList.IndexOf("-B"); } if (doSave > -1) { if (upperArgList.Count <= doSave) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } buildOutputPath = argList[doSave + 1]; var directoryName = new FileInfo(buildOutputPath).Directory.FullName; Directory.CreateDirectory(directoryName); } // Load model: cw.WriteLine("Loading model..."); if (!string.IsNullOrEmpty(script)) { cw.WriteLine("Executing script..."); System.CodeDom.Compiler.CompilerResults result; Scripting.ScriptOutputForm.Reset(false); var dyn = ScriptEngine.CompileScript(script, out result); if (result.Errors.Count > 0) { cw.WriteLine("Script compilation errors:"); foreach (System.CodeDom.Compiler.CompilerError err in result.Errors) { ErrorX(err.ErrorText, scriptFile, err.Line, err.Column, err.ErrorNumber); } return(true); } try { dyn.Invoke(h.Model, null); } catch (Exception ex) { Error("Script execution error: " + ex.Message); return(true); } } if (!string.IsNullOrEmpty(buildOutputPath)) { cw.WriteLine("Building Model.bim file..."); h.Save(buildOutputPath, SaveFormat.ModelSchemaOnly, SerializeOptions.Default); } var replaceMap = new Dictionary <string, string>(); var analyze = upperArgList.IndexOf("-ANALYZE"); if (analyze == -1) { analyze = upperArgList.IndexOf("-A"); } if (analyze > -1) { var rulefile = argList.Skip(analyze + 1).FirstOrDefault(n => !n.StartsWith("-")); var analyzer = new BPA.Analyzer() { Model = h.Model }; BPA.BestPracticeCollection suppliedRules = null; if (!string.IsNullOrEmpty(rulefile)) { if (!File.Exists(rulefile)) { Error("Rulefile not found: {0}", rulefile); return(true); } try { suppliedRules = BPA.BestPracticeCollection.LoadFromJsonFile(rulefile); } catch { Error("Invalid rulefile: {0}", rulefile); return(true); } } cw.WriteLine("Running Best Practice Analyzer..."); cw.WriteLine("================================="); IEnumerable <BPA.AnalyzerResult> bpaResults; if (suppliedRules == null) { bpaResults = analyzer.AnalyzeAll(); } else { bpaResults = analyzer.Analyze(suppliedRules.Concat(analyzer.LocalRules)); } if (!bpaResults.Any()) { cw.WriteLine("No objects in violation of Best Practices."); } foreach (var res in bpaResults) { if (res.RuleHasError) { Warning("Error on rule '{0}': {1}", res.RuleName, res.RuleError); } else { var text = string.Format("{0} {1} violates rule \"{2}\"", res.Object.GetTypeName(), (res.Object as IDaxObject)?.DaxObjectFullName ?? res.ObjectName, res.RuleName ); if (res.Rule.Severity <= 1) { cw.WriteLine(text); } else if (res.Rule.Severity == 2) { Warning(text); } else if (res.Rule.Severity >= 3) { Error(text); } } } cw.WriteLine("================================="); } var deploy = upperArgList.IndexOf("-DEPLOY"); if (deploy == -1) { deploy = upperArgList.IndexOf("-D"); } if (deploy > -1) { var serverName = argList.Skip(deploy + 1).FirstOrDefault(); if (serverName != null && serverName.StartsWith("-")) { serverName = null; } var databaseID = argList.Skip(deploy + 2).FirstOrDefault(); if (databaseID != null && databaseID.StartsWith("-")) { databaseID = null; } var conn = upperArgList.IndexOf("-CONNECTIONS"); if (conn == -1) { conn = upperArgList.IndexOf("-C"); } if (conn > -1) { var replaces = argList.Skip(conn + 1).TakeWhile(s => s[0] != '-').ToList(); if (replaces.Count > 0 && replaces.Count % 2 == 0) { // Placeholder replacing: for (var index = 0; index < replaces.Count; index = index + 2) { replaceMap.Add(replaces[index], replaces[index + 1]); } } } string userName = null; string password = null; var options = DeploymentOptions.StructureOnly; var switches = args.Skip(deploy + 1).Where(arg => arg.StartsWith("-")).Select(arg => arg.ToUpper()).ToList(); if (string.IsNullOrEmpty(serverName) || string.IsNullOrEmpty(databaseID)) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } if (switches.Contains("-L") || switches.Contains("-LOGIN")) { var switchPos = upperArgList.IndexOf("-LOGIN"); if (switchPos == -1) { switchPos = upperArgList.IndexOf("-L"); } userName = argList.Skip(switchPos + 1).FirstOrDefault(); if (userName != null && userName.StartsWith("-")) { userName = null; } password = argList.Skip(switchPos + 2).FirstOrDefault(); if (password != null && password.StartsWith("-")) { password = null; } if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { Error("Missing username or password.\n"); OutputUsage(); return(true); } switches.Remove("-L"); switches.Remove("-LOGIN"); } if (switches.Contains("-O") || switches.Contains("-OVERWRITE")) { options.DeployMode = DeploymentMode.CreateOrAlter; switches.Remove("-O"); switches.Remove("-OVERWRITE"); } else { options.DeployMode = DeploymentMode.CreateDatabase; } if (switches.Contains("-P") || switches.Contains("-PARTITIONS")) { options.DeployPartitions = true; switches.Remove("-P"); switches.Remove("-PARTITIONS"); } if (switches.Contains("-C") || switches.Contains("-CONNECTIONS")) { options.DeployConnections = true; switches.Remove("-C"); switches.Remove("-CONNECTIONS"); } if (switches.Contains("-R") || switches.Contains("-ROLES")) { options.DeployRoles = true; switches.Remove("-R"); switches.Remove("-ROLES"); if (switches.Contains("-M") || switches.Contains("-MEMBERS")) { options.DeployRoleMembers = true; switches.Remove("-M"); switches.Remove("-MEMBERS"); } } /*if(switches.Count > 0) * { * Error("Unknown switch {0}\n", switches[0]); * OutputUsage(); * return true; * }*/ try { if (replaceMap.Count > 0) { cw.WriteLine("Switching connection string placeholders..."); foreach (var map in replaceMap) { h.Model.DataSources.SetPlaceholder(map.Key, map.Value); } } cw.WriteLine("Deploying..."); var cs = string.IsNullOrEmpty(userName) ? TabularConnection.GetConnectionString(serverName) : TabularConnection.GetConnectionString(serverName, userName, password); var deploymentResult = TabularDeployer.Deploy(h, cs, databaseID, options); cw.WriteLine("Deployment succeeded."); foreach (var err in deploymentResult.Issues) { Issue(err); } foreach (var err in deploymentResult.Warnings) { Warning(err); } foreach (var err in deploymentResult.Unprocessed) { if (warnOnUnprocessed) { Warning(err); } else { cw.WriteLine(err); } } } catch (Exception ex) { Error("Deployment failed! " + ex.Message); } return(true); } return(true); }
protected GenericIndexer(TabularObject parent) { ParentObject = parent; Handler = parent.Handler; }
internal bool HandleCommandLine(string[] args) { var upperArgList = args.Select(arg => arg.ToUpper()).ToList(); var argList = args.Select(arg => arg).ToList(); if (upperArgList.Contains("-?") || upperArgList.Contains("/?") || upperArgList.Contains("-H") || upperArgList.Contains("/H") || upperArgList.Contains("HELP")) { OutputUsage(); return(true); } EnableVSTS = upperArgList.IndexOf("-VSTS") > -1 || upperArgList.IndexOf("-V") > -1; var warnOnUnprocessed = upperArgList.IndexOf("-WARN") > -1 || upperArgList.IndexOf("-W") > -1; var errorOnDaxErr = upperArgList.IndexOf("-ERR") > -1 || upperArgList.IndexOf("-E") > -1; TabularModelHandler h; if (args.Length == 2 || args[2].StartsWith("-")) { // File argument provided (either alone or with switches), i.e.: // TabularEditor.exe myfile.bim // TabularEditor.exe myfile.bim -... if (!File.Exists(args[1]) && !File.Exists(args[1] + "\\database.json")) { Error("File not found: {0}", args[1]); return(true); } else { // If nothing else was specified on the command-line, open the UI: if (args.Length == 2) { return(false); } } try { h = new TOMWrapper.TabularModelHandler(args[1]); } catch (Exception e) { Error("Error loading file: " + e.Message); return(true); } } else if (args.Length == 3 || args[3].StartsWith("-")) { // Server + Database argument provided (either alone or with switches), i.e.: // TabularEditor.exe localhost AdventureWorks // TabularEditor.exe localhost AdventureWorks -... // If nothing else was specified on the command-line, open the UI: if (args.Length == 3) { return(false); } try { h = new TOMWrapper.TabularModelHandler(args[1], args[2]); } catch (Exception e) { Error("Error loading model: " + e.Message); return(true); } } else { // Otherwise, it's nonsensical return(false); } string script = null; string scriptFile = null; var doTestRun = upperArgList.IndexOf("-T"); string testRunFile = null; if (doTestRun == -1) { doTestRun = upperArgList.IndexOf("-TRX"); } if (doTestRun > -1) { if (upperArgList.Count <= doTestRun || upperArgList[doTestRun + 1].StartsWith("-")) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } Program.testRun = new TestRun(h.Database?.Name ?? h.Source); testRunFile = argList[doTestRun + 1]; } var doScript = upperArgList.IndexOf("-SCRIPT"); if (doScript == -1) { doScript = upperArgList.IndexOf("-S"); } if (doScript > -1) { if (upperArgList.Count <= doScript) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } scriptFile = argList[doScript + 1]; script = File.Exists(scriptFile) ? File.ReadAllText(scriptFile) : scriptFile; } var doCheckDs = upperArgList.IndexOf("-SCHEMACHECK"); if (doCheckDs == -1) { doCheckDs = upperArgList.IndexOf("-SC"); } string saveToFolderOutputPath = null; string saveToFolderReplaceId = null; var doSaveToFolder = upperArgList.IndexOf("-FOLDER"); if (doSaveToFolder == -1) { doSaveToFolder = upperArgList.IndexOf("-F"); } if (doSaveToFolder > -1) { if (upperArgList.Count <= doSaveToFolder) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } saveToFolderOutputPath = argList[doSaveToFolder + 1]; if (doSaveToFolder + 2 < argList.Count && !argList[doSaveToFolder + 2].StartsWith("-")) { saveToFolderReplaceId = argList[doSaveToFolder + 2]; } var directoryName = new FileInfo(saveToFolderOutputPath).Directory.FullName; Directory.CreateDirectory(saveToFolderOutputPath); } string buildOutputPath = null; string buildReplaceId = null; var doSave = upperArgList.IndexOf("-BUILD"); if (doSave == -1) { doSave = upperArgList.IndexOf("-B"); } if (doSave == -1) { doSave = upperArgList.IndexOf("-BIM"); } if (doSave > -1) { if (upperArgList.Count <= doSave) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } buildOutputPath = argList[doSave + 1]; if (doSave + 2 < argList.Count && !argList[doSave + 2].StartsWith("-")) { buildReplaceId = argList[doSave + 2]; } var directoryName = new FileInfo(buildOutputPath).Directory.FullName; Directory.CreateDirectory(directoryName); } if (doSaveToFolder > -1 && doSave > -1) { Error("-FOLDER and -BUILD arguments are mutually exclusive.\n"); OutputUsage(); return(true); } // Load model: Console.WriteLine("Loading model..."); if (!string.IsNullOrEmpty(script)) { Console.WriteLine("Executing script..."); System.CodeDom.Compiler.CompilerResults result; Scripting.ScriptOutputForm.Reset(false); var dyn = ScriptEngine.CompileScript(script, out result); //nUnit.StartSuite("Script Compilation"); if (result.Errors.Count > 0) { Error("Script compilation errors:"); var errIndex = 0; foreach (System.CodeDom.Compiler.CompilerError err in result.Errors) { errIndex++; ErrorX(err.ErrorText, scriptFile, err.Line, err.Column, err.ErrorNumber); //nUnit.Failure("Script Compilation", $"Compilation Error #{errIndex}", err.ErrorText, $"{scriptFile} line {err.Line}, column {err.Column}"); } return(true); } try { h.BeginUpdate("script"); dyn.Invoke(h.Model, null); h.EndUpdateAll(); } catch (Exception ex) { Error("Script execution error: " + ex.Message); return(true); } finally { h.Model.Database.CloseReader(); } } if (doCheckDs > -1) { Console.WriteLine("Checking source schema..."); ScriptHelper.SchemaCheck(h.Model); } if (!string.IsNullOrEmpty(buildOutputPath)) { Console.WriteLine("Building Model.bim file..."); if (buildReplaceId != null) { h.Database.Name = buildReplaceId; h.Database.ID = buildReplaceId; } h.Save(buildOutputPath, SaveFormat.ModelSchemaOnly, SerializeOptions.Default); } else if (!string.IsNullOrEmpty(saveToFolderOutputPath)) { Console.WriteLine("Saving Model.bim file to Folder Output Path ..."); if (buildReplaceId != null) { h.Database.Name = buildReplaceId; h.Database.ID = buildReplaceId; } //Note the last parameter, we use whatever SerializeOptions are already in the file h.Save(saveToFolderOutputPath, SaveFormat.TabularEditorFolder, null, true); } var replaceMap = new Dictionary <string, string>(); var analyze = upperArgList.IndexOf("-ANALYZE"); if (analyze == -1) { analyze = upperArgList.IndexOf("-A"); } if (analyze > -1) { var rulefile = analyze + 1 < argList.Count ? argList[analyze + 1] : ""; if (rulefile.StartsWith("-") || string.IsNullOrEmpty(rulefile)) { rulefile = null; } Console.WriteLine("Running Best Practice Analyzer..."); Console.WriteLine("================================="); var analyzer = new BPA.Analyzer(); analyzer.SetModel(h.Model, h.SourceType == ModelSourceType.Database ? null : FileSystemHelper.DirectoryFromPath(h.Source)); BPA.BestPracticeCollection suppliedRules = null; if (!string.IsNullOrEmpty(rulefile)) { if (File.Exists(rulefile)) { try { suppliedRules = BPA.BestPracticeCollection.GetCollectionFromFile(Environment.CurrentDirectory, rulefile); } catch { Error("Invalid rulefile: {0}", rulefile); return(true); } } else { suppliedRules = BPA.BestPracticeCollection.GetCollectionFromUrl(rulefile); if (suppliedRules.Count == 0) { Error("No rules defined in specified URL: {0}", rulefile); return(true); } } } IEnumerable <BPA.AnalyzerResult> bpaResults; if (suppliedRules == null) { bpaResults = analyzer.AnalyzeAll(); } else { var effectiveRules = analyzer.GetEffectiveRules(false, false, true, true, suppliedRules); bpaResults = analyzer.Analyze(effectiveRules); } bool none = true; foreach (var res in bpaResults.Where(r => !r.Ignored)) { if (res.InvalidCompatibilityLevel) { Console.WriteLine("Skipping rule '{0}' as it does not apply to Compatibility Level {1}.", res.RuleName, h.CompatibilityLevel); } else if (res.RuleHasError) { none = false; Error("Error on rule '{0}': {1}", res.RuleName, res.RuleError); } else { none = false; if (res.Object != null) { var text = string.Format("{0} {1} violates rule \"{2}\"", res.Object.GetTypeName(), (res.Object as IDaxObject)?.DaxObjectFullName ?? res.ObjectName, res.RuleName ); if (res.Rule.Severity <= 1) { Console.WriteLine(text); } else if (res.Rule.Severity == 2) { Warning(text); } else if (res.Rule.Severity >= 3) { Error(text); } } } } if (none) { Console.WriteLine("No objects in violation of Best Practices."); } Console.WriteLine("================================="); } var deploy = upperArgList.IndexOf("-DEPLOY"); if (deploy == -1) { deploy = upperArgList.IndexOf("-D"); } if (deploy > -1) { var serverName = argList.Skip(deploy + 1).FirstOrDefault(); if (serverName == null || serverName.StartsWith("-")) { serverName = null; } var databaseID = argList.Skip(deploy + 2).FirstOrDefault(); if (databaseID != null && databaseID.StartsWith("-")) { databaseID = null; } // Perform direct save: if (serverName == null) { var nextSwitch = upperArgList.Skip(deploy + 1).FirstOrDefault(); var deploySwitches = new[] { "-L", "-LOGIN", "-O", "-OVERWRITE", "-C", "-CONNECTIONS", "-P", "-PARTITIONS", "-R", "-ROLES", "-M", "-MEMBERS", "-X", "-XMLA" }; if (deploySwitches.Contains(nextSwitch)) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } Console.WriteLine("Saving model metadata back to source..."); if (h.SourceType == ModelSourceType.Database) { try { h.SaveDB(); Console.WriteLine("Model metadata saved."); var deploymentResult = h.GetLastDeploymentResults(); foreach (var err in deploymentResult.Issues) { if (errorOnDaxErr) { Error(err); } else { Warning(err); } } foreach (var err in deploymentResult.Warnings) { Warning(err); } foreach (var err in deploymentResult.Unprocessed) { if (warnOnUnprocessed) { Warning(err); } else { Console.WriteLine(err); } } } catch (Exception ex) { Error("Save failed: " + ex.Message); } } else { try { h.Save(h.Source, h.SourceType == ModelSourceType.Folder ? SaveFormat.TabularEditorFolder : h.SourceType == ModelSourceType.Pbit ? SaveFormat.PowerBiTemplate : SaveFormat.ModelSchemaOnly, h.SerializeOptions, true); Console.WriteLine("Model metadata saved."); } catch (Exception ex) { Error("Save failed: " + ex.Message); } } return(true); } var conn = upperArgList.IndexOf("-CONNECTIONS"); if (conn == -1) { conn = upperArgList.IndexOf("-C"); } if (conn > -1) { var replaces = argList.Skip(conn + 1).TakeWhile(s => s[0] != '-').ToList(); if (replaces.Count > 0 && replaces.Count % 2 == 0) { // Placeholder replacing: for (var index = 0; index < replaces.Count; index = index + 2) { replaceMap.Add(replaces[index], replaces[index + 1]); } } } string userName = null; string password = null; var options = DeploymentOptions.StructureOnly; var switches = args.Skip(deploy + 1).Where(arg => arg.StartsWith("-")).Select(arg => arg.ToUpper()).ToList(); if (string.IsNullOrEmpty(serverName) || string.IsNullOrEmpty(databaseID)) { Error("Invalid argument syntax.\n"); OutputUsage(); return(true); } if (switches.Contains("-L") || switches.Contains("-LOGIN")) { var switchPos = upperArgList.IndexOf("-LOGIN"); if (switchPos == -1) { switchPos = upperArgList.IndexOf("-L"); } userName = argList.Skip(switchPos + 1).FirstOrDefault(); if (userName != null && userName.StartsWith("-")) { userName = null; } password = argList.Skip(switchPos + 2).FirstOrDefault(); if (password != null && password.StartsWith("-")) { password = null; } if (string.IsNullOrEmpty(userName) || string.IsNullOrEmpty(password)) { Error("Missing username or password.\n"); OutputUsage(); return(true); } switches.Remove("-L"); switches.Remove("-LOGIN"); } if (switches.Contains("-O") || switches.Contains("-OVERWRITE")) { options.DeployMode = DeploymentMode.CreateOrAlter; switches.Remove("-O"); switches.Remove("-OVERWRITE"); } else { options.DeployMode = DeploymentMode.CreateDatabase; } if (switches.Contains("-P") || switches.Contains("-PARTITIONS")) { options.DeployPartitions = true; switches.Remove("-P"); switches.Remove("-PARTITIONS"); } if (switches.Contains("-C") || switches.Contains("-CONNECTIONS")) { options.DeployConnections = true; switches.Remove("-C"); switches.Remove("-CONNECTIONS"); } if (switches.Contains("-R") || switches.Contains("-ROLES")) { options.DeployRoles = true; switches.Remove("-R"); switches.Remove("-ROLES"); if (switches.Contains("-M") || switches.Contains("-MEMBERS")) { options.DeployRoleMembers = true; switches.Remove("-M"); switches.Remove("-MEMBERS"); } } var xmla_scripting_only = switches.Contains("-X") || switches.Contains("-XMLA"); string xmla_script_file = null; if (xmla_scripting_only) { var switchPos = upperArgList.IndexOf("-XMLA"); if (switchPos == -1) { switchPos = upperArgList.IndexOf("-X"); } xmla_script_file = argList.Skip(switchPos + 1).FirstOrDefault(); if (String.IsNullOrWhiteSpace(xmla_script_file) || xmla_script_file.StartsWith("-")) { xmla_script_file = null; } if (string.IsNullOrEmpty(xmla_script_file)) { Error("Missing xmla_script_file.\n"); OutputUsage(); return(true); } switches.Remove("-X"); switches.Remove("-XMLA"); } /*if(switches.Count > 0) * { * Error("Unknown switch {0}\n", switches[0]); * OutputUsage(); * return true; * }*/ try { if (replaceMap.Count > 0) { Console.WriteLine("Switching connection string placeholders..."); foreach (var map in replaceMap) { h.Model.DataSources.SetPlaceholder(map.Key, map.Value); } } var cs = string.IsNullOrEmpty(userName) ? TabularConnection.GetConnectionString(serverName) : TabularConnection.GetConnectionString(serverName, userName, password); if (xmla_scripting_only) { Console.WriteLine("Generating XMLA/TMSL script..."); var s = new TOM.Server(); s.Connect(cs); var xmla = TabularDeployer.GetTMSL(h.Database, s, databaseID, options); using (var sw = new StreamWriter(xmla_script_file)) { sw.Write(xmla); } Console.WriteLine("XMLA/TMSL script generated."); } else { Console.WriteLine("Deploying..."); h.Model.UpdateDeploymentMetadata(DeploymentModeMetadata.CLI); var deploymentResult = TabularDeployer.Deploy(h, cs, databaseID, options); Console.WriteLine("Deployment succeeded."); foreach (var err in deploymentResult.Issues) { if (errorOnDaxErr) { Error(err); } else { Warning(err); } } foreach (var err in deploymentResult.Warnings) { Warning(err); } foreach (var err in deploymentResult.Unprocessed) { if (warnOnUnprocessed) { Warning(err); } else { Console.WriteLine(err); } } } } catch (Exception ex) { Error($"{(xmla_scripting_only ? "Script generation" : "Deployment")} failed! {ex.Message}"); } } if (Program.testRun != null) { Program.testRun.SerializeAsVSTest(testRunFile); Console.WriteLine("VSTest XML file saved: " + testRunFile); } return(true); }
public TabularObjectCache(TabularModelHandler handler) { this.handler = handler; }