private bool ShouldPerspectiveKpiBeHighlighted(PerspectiveKpi pkpi, Microsoft.AnalysisServices.Design.Scripts mdxScript)
 {
     return(ShouldPerspectiveKpiColumnBeHighlighted(pkpi, mdxScript, pkpi.Kpi.Value) ||
            ShouldPerspectiveKpiColumnBeHighlighted(pkpi, mdxScript, pkpi.Kpi.Goal) ||
            ShouldPerspectiveKpiColumnBeHighlighted(pkpi, mdxScript, pkpi.Kpi.Status) ||
            ShouldPerspectiveKpiColumnBeHighlighted(pkpi, mdxScript, pkpi.Kpi.Trend));
 }
        //return true if the kpi column is a reference to a measure, and if that measure isn't in the perspective or is hidden
        private bool ShouldPerspectiveKpiColumnBeHighlighted(PerspectiveKpi pkpi, Microsoft.AnalysisServices.Design.Scripts mdxScript, string column)
        {
            if (string.IsNullOrEmpty(column))
            {
                return(false);
            }
            foreach (MeasureGroup mg in pkpi.ParentCube.MeasureGroups)
            {
                foreach (Measure m in mg.Measures)
                {
                    if (string.Compare("[Measures].[" + m.Name + "]", column, true) == 0)
                    {
                        if (pkpi.Parent.MeasureGroups.Contains(mg.ID) && pkpi.Parent.MeasureGroups[mg.ID].Measures.Contains(m.ID))
                        {
                            return(false);
                        }
                        else
                        {
                            return(true);
                        }
                    }
                }
            }

            //foreach (object calcMember in mdxScript.CalculatedMembers)
            //{
            //    Microsoft.AnalysisServices.Design.Script calc = calcMember as Microsoft.AnalysisServices.Design.Script;
            //    if (calc != null && calc.CalculationProperty != null && string.Compare(calc.CalculationProperty.CalculationReference, column, true) == 0)
            //    {
            //        if (CalcIsHidden(calc)) return false;
            //        if (pkpi.Parent.Calculations.Contains(column))
            //            return false;
            //        else //found the calc, it's visible, but it isn't in the perspective
            //            return true;
            //    }
            //}
            return(false);
        }
        public override void OnWindowActivated(Window GotFocus, Window LostFocus)
        {
            try
            {
                if (GotFocus == null) return;
                IDesignerHost designer = GotFocus.Object as IDesignerHost;
                if (designer == null) return;
                ProjectItem pi = GotFocus.ProjectItem;
                if ((pi==null) || (!(pi.Object is Cube))) return;
                EditorWindow win = (EditorWindow)designer.GetService(typeof(Microsoft.DataWarehouse.ComponentModel.IComponentNavigator));
                VsStyleToolBar toolbar = (VsStyleToolBar)win.SelectedView.GetType().InvokeMember("ToolBar", getflags, null, win.SelectedView, null);
                Cube cube = (Cube)pi.Object;


                IntPtr ptr = win.Handle;
                string sHandle = ptr.ToInt64().ToString();

                if (!windowHandlesFixedForPerspectives.ContainsKey(sHandle))
                {
                    windowHandlesFixedForPerspectives.Add(sHandle,win);
                    win.ActiveViewChanged += new EventHandler(win_ActiveViewChanged);
                }

                //if (win.SelectedView.Caption == "Perspectives")
                if (win.SelectedView.MenuItemCommandID.ID == (int) BIDSViewMenuItemCommandID.Perspectives)
                {
                    Microsoft.AnalysisServices.Design.Scripts mdxScriptCache = new Microsoft.AnalysisServices.Design.Scripts(cube);

                    Control perspectiveBuilder = (Control)win.SelectedView.GetType().InvokeMember("ViewControl", getflags, null, win.SelectedView, null); //Microsoft.AnalysisServices.Design.PerspectivesBuilder
                    Control grid = perspectiveBuilder.Controls[0]; //Microsoft.SqlServer.Management.UI.Grid.DlgGridControl

                    if (!windowHandlesFixedForGridEvents.ContainsKey(sHandle))
                    {
                        grid.MouseClick += new MouseEventHandler(grid_MouseClick);
                        grid.KeyPress += new KeyPressEventHandler(grid_KeyPress);
#if DENALI || SQL2014
                        _IsMetroOrGreater = VisualStudioHelpers.IsMetroOrGreater(win);
                        HookCellPaintEvent(grid, true);
#endif
                        windowHandlesFixedForGridEvents.Add(sHandle,win);
                    }
                    
                    System.Reflection.BindingFlags getpropertyflags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;

                    object dlgStorage = null;
#if KATMAI || DENALI || SQL2014
                    dlgStorage = grid.GetType().BaseType.BaseType.InvokeMember("DlgStorage", getpropertyflags, null, grid, null);
#else
                    dlgStorage = grid.GetType().BaseType.InvokeMember("DlgStorage", getpropertyflags, null, grid, null); //Microsoft.SqlServer.Management.UI.Grid.IDlgStorage
#endif

                    object storage = dlgStorage.GetType().InvokeMember("Storage", getpropertyflags, null, dlgStorage, null); //Microsoft.SqlServer.Management.UI.Grid.MemDataStorage

                    System.Reflection.BindingFlags getfieldflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                    ArrayList rows = (ArrayList)storage.GetType().BaseType.InvokeMember("m_arrRows", getfieldflags, null, storage, new object[] { });
                    //ArrayList columns = (ArrayList)storage.GetType().BaseType.InvokeMember("m_arrColumns", getfieldflags, null, storage, new object[] { });
                    object[] perspectivesColumns = (object[])rows[0];

                    ArrayList allGridCubeObjects = (ArrayList)perspectiveBuilder.GetType().InvokeMember("allGridCubeObjects", getfieldflags, null, perspectiveBuilder, null);

                    for (int i = 3; i < rows.Count; i++)
                    {
                        object[] columns = (object[])rows[i];
                        object cell = columns[2]; //Microsoft.SqlServer.Management.UI.Grid.GridCell
                        string rowObjectType = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                        if (rowObjectType == "MeasureGroup")
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            MeasureGroup mg = cube.MeasureGroups.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.MeasureGroups.Contains(mg.ID))
                                {
                                    PerspectiveMeasureGroup pmg = perspective.MeasureGroups[mg.ID];
                                    foreach (Measure m in mg.Measures)
                                    {
                                        if (m.Visible && !pmg.Measures.Contains(m.ID))
                                        {
                                            bHighlight = true;
                                            break;
                                        }
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType == "CubeDimension")
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            CubeDimension cd = cube.Dimensions.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.Dimensions.Contains(cd.ID))
                                {
                                    PerspectiveDimension pcd = perspective.Dimensions[cd.ID];
                                    foreach (CubeHierarchy h in cd.Hierarchies)
                                    {
                                        if (h.Visible && h.Enabled && !pcd.Hierarchies.Contains(h.HierarchyID))
                                        {
                                            bHighlight = true;
                                            break;
                                        }
                                    }
                                    if (!bHighlight)
                                    {
                                        foreach (CubeAttribute a in cd.Attributes)
                                        {
                                            if (a.AttributeHierarchyVisible && a.AttributeHierarchyEnabled && a.Attribute.AttributeHierarchyVisible && a.Attribute.AttributeHierarchyEnabled && !pcd.Attributes.Contains(a.AttributeID))
                                            {
                                                bHighlight = true;
                                                break;
                                            }
                                        }
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType == "Kpi")
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            rowObjectName = rowObjectName.Trim();
                            Kpi kpi = cube.Kpis.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.Kpis.Contains(kpi.ID))
                                {
                                    PerspectiveKpi pkpi = perspective.Kpis[kpi.ID];
                                    bHighlight = ShouldPerspectiveKpiBeHighlighted(pkpi, mdxScriptCache);
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType.EndsWith("Action"))
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            rowObjectName = rowObjectName.Trim();
                            Microsoft.AnalysisServices.Action action = cube.Actions.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.Actions.Contains(action.ID))
                                {
                                    bHighlight = true;
                                    if (action.TargetType == ActionTargetType.DimensionMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            if (string.Compare(action.Target, "[" + dim.CubeDimension.Name + "]", true) == 0)
                                            {
                                                bHighlight = false;
                                                break;
                                            }
                                        }
                                    }
                                    else if (action.TargetType == ActionTargetType.AttributeMembers || action.TargetType == ActionTargetType.HierarchyMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            foreach (PerspectiveAttribute attr in dim.Attributes)
                                            {
                                                if (string.Compare(action.Target, "[" + attr.Parent.CubeDimension.Name + "].[" + attr.Attribute.Name + "]", true) == 0)
                                                {
                                                    bHighlight = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    else if (action.TargetType == ActionTargetType.Level || action.TargetType == ActionTargetType.LevelMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            foreach (PerspectiveHierarchy hier in dim.Hierarchies)
                                            {
                                                foreach (Level level in hier.Hierarchy.Levels)
                                                {
                                                    if (string.Compare(action.Target, "[" + hier.Parent.CubeDimension.Name + "].[" + hier.Hierarchy.Name + "].[" + level.Name + "]", true) == 0)
                                                    {
                                                        bHighlight = false;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else if (action.TargetType == ActionTargetType.HierarchyMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            foreach (PerspectiveHierarchy hier in dim.Hierarchies)
                                            {
                                                if (string.Compare(action.Target, "[" + hier.Parent.CubeDimension.Name + "].[" + hier.Hierarchy.Name + "]", true) == 0)
                                                {
                                                    bHighlight = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        bHighlight = false;
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType == "CalculatedMember")
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            rowObjectName = rowObjectName.Trim();

                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];

                                Microsoft.AnalysisServices.Design.Script calc = (Microsoft.AnalysisServices.Design.Script)allGridCubeObjects[i].GetType().InvokeMember("Object", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetField, null, allGridCubeObjects[i], null);
                                if (CalcIsHidden(calc)) continue;
                                                                
                                bool bHighlight = false;
                                if (calc != null && calc.CalculationProperty != null && perspective.Calculations.Contains(calc.CalculationProperty.CalculationReference) && !CalcIsHidden(calc))
                                {
                                    if (!string.IsNullOrEmpty(calc.CalculationProperty.AssociatedMeasureGroupID))
                                    {
                                        if (!perspective.MeasureGroups.Contains(calc.CalculationProperty.AssociatedMeasureGroupID))
                                            bHighlight = true;
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                    }
                    grid.Refresh();
                }
            }
            catch { }
        }
        void OpenCalcPropertiesDialog()
        {
            Form form1 = null; //should be a CalcPropertiesEditorForm which is private
            Cube cube = (Cube)this.ApplicationObject.ActiveWindow.ProjectItem.Object;
            System.IServiceProvider provider = (System.IServiceProvider)this.ApplicationObject.ActiveWindow.ProjectItem.ContainingProject;
            using (WaitCursor cursor1 = new WaitCursor())
            {
                IUserPromptService oService = (IUserPromptService)provider.GetService(typeof(IUserPromptService));

                foreach (Type t in System.Reflection.Assembly.GetAssembly(typeof(Microsoft.AnalysisServices.Design.Scripts)).GetTypes())
                {
                    if (t.FullName == "Microsoft.AnalysisServices.Design.Calculations.CalcPropertiesEditorForm")
                    {
                        form1 = (Form)t.GetConstructor(new Type[] { typeof(IUserPromptService) }).Invoke(new object[] { oService });
                        break;
                    }
                }
                if (form1 == null) throw new Exception("Couldn't create instance of CalcPropertiesEditorForm");

                object script1 = null; //should be a Microsoft.AnalysisServices.MdxCodeDom.MdxCodeScript object
                try
                {
                    //validate the script because deploying an invalid script makes cube unusable
                    Microsoft.AnalysisServices.Design.Scripts scripts = new Microsoft.AnalysisServices.Design.Scripts(cube);
                    System.Reflection.BindingFlags getflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                    script1 = scripts.GetType().InvokeMember("mdxCodeScript", getflags, null, scripts, null);
                }
                catch (Microsoft.AnalysisServices.Design.ScriptParsingFailed ex)
                {
                    string throwaway = ex.Message; //prevents a warning during compile
                    MessageBox.Show("MDX Script in " + cube.Name + " is not valid.", "Problem Deploying MDX Script");
                    return;
                }

                if (cube.MdxScripts.Count == 0)
                {
                    MessageBox.Show("There is no MDX script defined in this cube yet.");
                    return;
                }

                System.Reflection.BindingFlags getmethodflags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                form1.GetType().InvokeMember("Initialize", getmethodflags, null, form1, new object[] { cube.MdxScripts[0], script1, cube, null });

                //now make custom changes to the form
                Button okButton = (Button)form1.Controls.Find("okButton", true)[0];
                Panel panel = (Panel)form1.Controls.Find("gridPanel", true)[0];

                Button descButton = new Button();
                descButton.Text = "Edit Description";
                descButton.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;
                descButton.Left = panel.Left;
                descButton.Top = okButton.Top;
                descButton.Width += 40;
                descButton.Click += new EventHandler(descButton_Click);
                form1.Controls.Add(descButton);
            }

            if (Microsoft.DataWarehouse.DataWarehouseUtilities.ShowDialog(form1,provider) == DialogResult.OK)
            {
                using (WaitCursor cursor2 = new WaitCursor())
                {
                    System.Reflection.BindingFlags getflags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                    CalculationPropertyCollection collection1 = (CalculationPropertyCollection)form1.GetType().InvokeMember("GetResultProperties", getflags, null, form1, new object[] { });

                    DesignerTransaction transaction1 = null;
                    try
                    {
                        IDesignerHost host1 = (IDesignerHost)ApplicationObject.ActiveWindow.Object;
                        transaction1 = host1.CreateTransaction("BidsHelperCalcPropertiesUndoBatchDesc");
                        IComponentChangeService service1 = (IComponentChangeService)ApplicationObject.ActiveWindow.Object;
                        service1.OnComponentChanging(cube.MdxScripts[0].CalculationProperties, null);
                        cube.MdxScripts[0].CalculationProperties.Clear();
                        for (int num1 = collection1.Count - 1; num1 >= 0; num1--)
                        {
                            CalculationProperty property1 = collection1[num1];
                            collection1.RemoveAt(num1);
                            cube.MdxScripts[0].CalculationProperties.Insert(0, property1);
                        }
                        service1.OnComponentChanged(cube.MdxScripts[0].CalculationProperties, null, null, null);
                    }
                    catch (CheckoutException exception1)
                    {
                        if (transaction1 != null)
                            transaction1.Cancel();
                        if (exception1 != CheckoutException.Canceled)
                        {
                            throw exception1;
                        }
                    }
                    finally
                    {
                        if (transaction1 != null)
                            transaction1.Commit();
                    }
                }
            }
        }
        public override void OnWindowActivated(Window GotFocus, Window LostFocus)
        {
            try
            {
                package.Log.Debug("TriStatPerspectives OnWindowActivated fired");
                if (GotFocus == null)
                {
                    return;
                }
                IDesignerHost designer = GotFocus.Object as IDesignerHost;
                if (designer == null)
                {
                    return;
                }
                ProjectItem pi = GotFocus.ProjectItem;
                if ((pi == null) || (!(pi.Object is Cube)))
                {
                    return;
                }
                EditorWindow   win     = (EditorWindow)designer.GetService(typeof(Microsoft.DataWarehouse.ComponentModel.IComponentNavigator));
                VsStyleToolBar toolbar = (VsStyleToolBar)win.SelectedView.GetType().InvokeMember("ToolBar", getflags, null, win.SelectedView, null);
                Cube           cube    = (Cube)pi.Object;


                IntPtr ptr     = win.Handle;
                string sHandle = ptr.ToInt64().ToString();

                if (!windowHandlesFixedForPerspectives.ContainsKey(sHandle))
                {
                    windowHandlesFixedForPerspectives.Add(sHandle, win);
                    win.ActiveViewChanged += new EventHandler(win_ActiveViewChanged);
                }

                //if (win.SelectedView.Caption == "Perspectives")
                if (win.SelectedView.MenuItemCommandID.ID == (int)BIDSViewMenuItemCommandID.Perspectives)
                {
                    Microsoft.AnalysisServices.Design.Scripts mdxScriptCache = new Microsoft.AnalysisServices.Design.Scripts(cube);

                    Control perspectiveBuilder = (Control)win.SelectedView.GetType().InvokeMember("ViewControl", getflags, null, win.SelectedView, null); //Microsoft.AnalysisServices.Design.PerspectivesBuilder
                    Control grid = perspectiveBuilder.Controls[0];                                                                                        //Microsoft.SqlServer.Management.UI.Grid.DlgGridControl

                    if (!windowHandlesFixedForGridEvents.ContainsKey(sHandle))
                    {
                        grid.MouseClick += new MouseEventHandler(grid_MouseClick);
                        grid.KeyPress   += new KeyPressEventHandler(grid_KeyPress);
#if !(YUKON || KATMAI)
                        _IsMetroOrGreater = VisualStudioHelpers.IsMetroOrGreater(win);
                        HookCellPaintEvent(grid, true);
#endif
                        windowHandlesFixedForGridEvents.Add(sHandle, win);
                    }

                    System.Reflection.BindingFlags getpropertyflags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.GetProperty | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;

                    object dlgStorage = null;
#if !(YUKON)
                    dlgStorage = grid.GetType().BaseType.BaseType.InvokeMember("DlgStorage", getpropertyflags, null, grid, null);
#else
                    dlgStorage = grid.GetType().BaseType.InvokeMember("DlgStorage", getpropertyflags, null, grid, null); //Microsoft.SqlServer.Management.UI.Grid.IDlgStorage
#endif

                    object storage = dlgStorage.GetType().InvokeMember("Storage", getpropertyflags, null, dlgStorage, null); //Microsoft.SqlServer.Management.UI.Grid.MemDataStorage

                    System.Reflection.BindingFlags getfieldflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                    ArrayList rows = (ArrayList)storage.GetType().BaseType.InvokeMember("m_arrRows", getfieldflags, null, storage, new object[] { });
                    //ArrayList columns = (ArrayList)storage.GetType().BaseType.InvokeMember("m_arrColumns", getfieldflags, null, storage, new object[] { });
                    object[] perspectivesColumns = (object[])rows[0];

                    ArrayList allGridCubeObjects = (ArrayList)perspectiveBuilder.GetType().InvokeMember("allGridCubeObjects", getfieldflags, null, perspectiveBuilder, null);

                    for (int i = 3; i < rows.Count; i++)
                    {
                        object[] columns       = (object[])rows[i];
                        object   cell          = columns[2]; //Microsoft.SqlServer.Management.UI.Grid.GridCell
                        string   rowObjectType = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                        if (rowObjectType == "MeasureGroup")
                        {
                            cell = columns[1];
                            string       rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            MeasureGroup mg            = cube.MeasureGroups.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string      perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective     = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.MeasureGroups.Contains(mg.ID))
                                {
                                    PerspectiveMeasureGroup pmg = perspective.MeasureGroups[mg.ID];
                                    foreach (Measure m in mg.Measures)
                                    {
                                        if (m.Visible && !pmg.Measures.Contains(m.ID))
                                        {
                                            bHighlight = true;
                                            break;
                                        }
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType == "CubeDimension")
                        {
                            cell = columns[1];
                            string        rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            CubeDimension cd            = cube.Dimensions.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string      perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective     = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.Dimensions.Contains(cd.ID))
                                {
                                    PerspectiveDimension pcd = perspective.Dimensions[cd.ID];
                                    foreach (CubeHierarchy h in cd.Hierarchies)
                                    {
                                        if (h.Visible && h.Enabled && !pcd.Hierarchies.Contains(h.HierarchyID))
                                        {
                                            bHighlight = true;
                                            break;
                                        }
                                    }
                                    if (!bHighlight)
                                    {
                                        foreach (CubeAttribute a in cd.Attributes)
                                        {
                                            if (a.AttributeHierarchyVisible && a.AttributeHierarchyEnabled && a.Attribute.AttributeHierarchyVisible && a.Attribute.AttributeHierarchyEnabled && !pcd.Attributes.Contains(a.AttributeID))
                                            {
                                                bHighlight = true;
                                                break;
                                            }
                                        }
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType == "Kpi")
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            rowObjectName = rowObjectName.Trim();
                            Kpi kpi = cube.Kpis.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string      perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective     = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.Kpis.Contains(kpi.ID))
                                {
                                    PerspectiveKpi pkpi = perspective.Kpis[kpi.ID];
                                    bHighlight = ShouldPerspectiveKpiBeHighlighted(pkpi, mdxScriptCache);
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType.EndsWith("Action"))
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            rowObjectName = rowObjectName.Trim();
                            Microsoft.AnalysisServices.Action action = cube.Actions.GetByName(rowObjectName);
                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string      perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective     = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];
                                bool bHighlight = false;
                                if (perspective.Actions.Contains(action.ID))
                                {
                                    bHighlight = true;
                                    if (action.TargetType == ActionTargetType.DimensionMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            if (string.Compare(action.Target, "[" + dim.CubeDimension.Name + "]", true) == 0)
                                            {
                                                bHighlight = false;
                                                break;
                                            }
                                        }
                                    }
                                    else if (action.TargetType == ActionTargetType.AttributeMembers || action.TargetType == ActionTargetType.HierarchyMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            foreach (PerspectiveAttribute attr in dim.Attributes)
                                            {
                                                if (string.Compare(action.Target, "[" + attr.Parent.CubeDimension.Name + "].[" + attr.Attribute.Name + "]", true) == 0)
                                                {
                                                    bHighlight = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    else if (action.TargetType == ActionTargetType.Level || action.TargetType == ActionTargetType.LevelMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            foreach (PerspectiveHierarchy hier in dim.Hierarchies)
                                            {
                                                foreach (Level level in hier.Hierarchy.Levels)
                                                {
                                                    if (string.Compare(action.Target, "[" + hier.Parent.CubeDimension.Name + "].[" + hier.Hierarchy.Name + "].[" + level.Name + "]", true) == 0)
                                                    {
                                                        bHighlight = false;
                                                        break;
                                                    }
                                                }
                                            }
                                        }
                                    }
                                    else if (action.TargetType == ActionTargetType.HierarchyMembers)
                                    {
                                        foreach (PerspectiveDimension dim in perspective.Dimensions)
                                        {
                                            foreach (PerspectiveHierarchy hier in dim.Hierarchies)
                                            {
                                                if (string.Compare(action.Target, "[" + hier.Parent.CubeDimension.Name + "].[" + hier.Hierarchy.Name + "]", true) == 0)
                                                {
                                                    bHighlight = false;
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    else
                                    {
                                        bHighlight = false;
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                        else if (rowObjectType == "CalculatedMember")
                        {
                            cell = columns[1];
                            string rowObjectName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                            rowObjectName = rowObjectName.Trim();

                            for (int j = 3; j < columns.Length; j += 2)
                            {
                                cell = perspectivesColumns[j + 1];
                                string      perspectiveName = (string)cell.GetType().InvokeMember("CellData", getpropertyflags, null, cell, null);
                                Perspective perspective     = cube.Perspectives.GetByName(perspectiveName);
                                cell = columns[j];

                                Microsoft.AnalysisServices.Design.Script calc = (Microsoft.AnalysisServices.Design.Script)allGridCubeObjects[i].GetType().InvokeMember("Object", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.GetField, null, allGridCubeObjects[i], null);
                                if (CalcIsHidden(calc))
                                {
                                    continue;
                                }

                                bool bHighlight = false;
                                if (calc != null && calc.CalculationProperty != null && perspective.Calculations.Contains(calc.CalculationProperty.CalculationReference) && !CalcIsHidden(calc))
                                {
                                    if (!string.IsNullOrEmpty(calc.CalculationProperty.AssociatedMeasureGroupID))
                                    {
                                        if (!perspective.MeasureGroups.Contains(calc.CalculationProperty.AssociatedMeasureGroupID))
                                        {
                                            bHighlight = true;
                                        }
                                    }
                                }

                                HighlightCell(bHighlight, columns, cell, j);
                            }
                        }
                    }
                    grid.Refresh();
                }
            }
            catch { }
        }
        public static void DeployScript(ProjectItem projItem, DTE2 ApplicationObject)
        {
            Microsoft.AnalysisServices.Cube oCube = (Microsoft.AnalysisServices.Cube)projItem.Object;
            try
            {
                //validate the script because deploying an invalid script makes cube unusable
                Microsoft.AnalysisServices.Design.Scripts script = new Microsoft.AnalysisServices.Design.Scripts(oCube);

            }
            catch (Microsoft.AnalysisServices.Design.ScriptParsingFailed ex)
            {
                string throwaway = ex.Message;
                MessageBox.Show("MDX Script in " + oCube.Name + " is not valid.", "Problem Deploying MDX Script");
                return;
            }

            if (oCube.MdxScripts.Count == 0)
            {
                MessageBox.Show("There is no MDX script defined in this cube yet.");
                return;
            }

            try
            {
                ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 1, 5);

                // Check if the file is read-only (and probably checked in to a source control system)
                // before attempting to save. (issue: 10327 )
                FileAttributes fa = System.IO.File.GetAttributes(projItem.get_FileNames(1));
                if ((fa & FileAttributes.ReadOnly) != FileAttributes.ReadOnly )
                {
                    //TODO - can I check and maybe prompt before saving?
                    //Save the cube
                    projItem.Save("");
                }

                ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 2, 5);

                // extract deployment information
                DeploymentSettings deploySet = new DeploymentSettings(projItem);

                // use xlst to create xmla alter command
                XslCompiledTransform xslt = new XslCompiledTransform();
                XmlReader xsltRdr;
                XmlReader xrdr;

                // read xslt from embedded resource
                xsltRdr = XmlReader.Create(new StringReader(BIDSHelper.Resources.Common.DeployMdxScript));
                using ((xsltRdr))
                {
                    // read content from .cube file
                    xrdr = XmlReader.Create(projItem.get_FileNames(1));
                    using (xrdr)
                    {

                        ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 3, 5);
                        // Connect to Analysis Services
                        Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
                        svr.Connect(deploySet.TargetServer);
                        ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 4, 5);
                        // execute the xmla
                        try
                        {
                            Microsoft.AnalysisServices.Scripter scr = new Microsoft.AnalysisServices.Scripter();

                            // Build up the Alter MdxScript command using XSLT against the .cube file
                            XslCompiledTransform xslta = new XslCompiledTransform();
                            StringBuilder sb = new StringBuilder();
                            XmlWriterSettings xws = new XmlWriterSettings();
                            xws.OmitXmlDeclaration = true;
                            xws.ConformanceLevel = ConformanceLevel.Fragment;
                            XmlWriter xwrtr = XmlWriter.Create(sb, xws);

                            xslta.Load(xsltRdr);
                            XsltArgumentList xslarg = new XsltArgumentList();

                            Database targetDB = svr.Databases.FindByName(deploySet.TargetDatabase);
                            if (targetDB == null)
                            {
                                throw new System.Exception(string.Format("A database called {0} could not be found on the {1} server", deploySet.TargetDatabase, deploySet.TargetServer));
                            }
                            string targetDatabaseID = targetDB.ID;
                            xslarg.AddParam("TargetDatabase", "", targetDatabaseID);
                            xslta.Transform(xrdr, xslarg, xwrtr);

                            // Extract the current script from the server and keep a temporary backup copy of it
                            StringBuilder sbBackup = new StringBuilder();
                            XmlWriterSettings xwSet = new XmlWriterSettings();
                            xwSet.ConformanceLevel = ConformanceLevel.Fragment;
                            xwSet.OmitXmlDeclaration = true;
                            xwSet.Indent = true;
                            XmlWriter xwScript = XmlWriter.Create(sbBackup,xwSet);

                            Cube oServerCube = targetDB.Cubes.Find(oCube.ID);
                            if (oServerCube == null)
                            {
                                throw new System.Exception(string.Format("The {0} cube is not yet deployed to the {1} server.", oCube.Name, deploySet.TargetServer));
                            }
                            else if (oServerCube.State == AnalysisState.Unprocessed)
                            {
                                throw new System.Exception(string.Format("The {0} cube is not processed the {1} server.", oCube.Name, deploySet.TargetServer));
                            }
                            if (oServerCube.MdxScripts.Count == 0)
                            {
                                scr.ScriptAlter(new Microsoft.AnalysisServices.MajorObject[] { oServerCube }, xwScript, true);
                            }
                            else
                            {
                                MdxScript mdxScr = oServerCube.MdxScripts[0];
                                scr.ScriptAlter(new Microsoft.AnalysisServices.MajorObject[] { mdxScr }, xwScript, true);
                            }
                            xwScript.Close();

                            // update the MDX Script
                            XmlaResultCollection xmlaRC = svr.Execute(sb.ToString());
                            if (xmlaRC.Count == 1 && xmlaRC[0].Messages.Count == 0)
                            {
                                // all OK - 1 result - no messages
                            }
                            else
                            {
                                    StringBuilder sbErr = new StringBuilder();
                                for (int iRC = 0; iRC < xmlaRC.Count;iRC ++)
                                {
                                    for (int iMsg = 0; iMsg < xmlaRC[iRC].Messages.Count; iMsg++)
                                    {
                                        sbErr.AppendLine(xmlaRC[iRC].Messages[iMsg].Description);
                                    }
                                }
                                MessageBox.Show(sbErr.ToString(),"BIDSHelper - Deploy MDX Script" );
                            }

                            // Test the MDX Script
                            AdomdConnection cn = new AdomdConnection("Data Source=" + deploySet.TargetServer + ";Initial Catalog=" + deploySet.TargetDatabase);
                            cn.Open();
                            AdomdCommand cmd = cn.CreateCommand();
                            string qry = "SELECT {} ON 0 FROM [" + oCube.Name +"];";
                            cmd.CommandText = qry;
                            try
                            {
                                // test that we can query the cube without errors
                                cmd.Execute();

                                // Building the project means that the .asdatabase file gets re-built so that
                                // we do not break the Deployment Wizard.
                                // --
                                // This line is included in this try block so that it is only executed if we can
                                // successfully query the cube without errors.
                                projItem.DTE.Solution.SolutionBuild.BuildProject(projItem.DTE.Solution.SolutionBuild.ActiveConfiguration.Name, projItem.ContainingProject.UniqueName, false);

                            }
                            catch (System.Exception ex)
                            {
                                // undo the deployment if we caught an exception during the deployment
                                svr.Execute(sbBackup.ToString());
                                MessageBox.Show(ex.Message);
                            }
                        }
                        catch (System.Exception ex)
                        {
                            if (MessageBox.Show("The following error occured while trying to deploy the MDX Script\r\n"
                                                + ex.Message
                                                + "\r\n\r\nDo you want to see a stack trace?"
                                            ,"BIDSHelper - Deploy MDX Script"
                                            , MessageBoxButtons.YesNo
                                            , MessageBoxIcon.Error
                                            , MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                            {
                                MessageBox.Show(ex.StackTrace);
                            }
                        }
                        finally
                        {
                            ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 5, 5);
                            // report any results back (status bar?)
                            svr.Disconnect();
                        }
                    }
                }
            }
            finally
            {
                ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(false, "Deploying MdxScript", 5, 5);
            }
        }
Example #7
0
        void OpenCalcPropertiesDialog()
        {
            Form form1 = null; //should be a CalcPropertiesEditorForm which is private
            Cube cube  = (Cube)this.ApplicationObject.ActiveWindow.ProjectItem.Object;

            System.IServiceProvider provider = (System.IServiceProvider) this.ApplicationObject.ActiveWindow.ProjectItem.ContainingProject;
            using (WaitCursor cursor1 = new WaitCursor())
            {
                IUserPromptService oService = (IUserPromptService)provider.GetService(typeof(IUserPromptService));

                foreach (Type t in System.Reflection.Assembly.GetAssembly(typeof(Microsoft.AnalysisServices.Design.Scripts)).GetTypes())
                {
                    if (t.FullName == "Microsoft.AnalysisServices.Design.Calculations.CalcPropertiesEditorForm")
                    {
                        form1 = (Form)t.GetConstructor(new Type[] { typeof(IUserPromptService) }).Invoke(new object[] { oService });
                        break;
                    }
                }
                if (form1 == null)
                {
                    throw new Exception("Couldn't create instance of CalcPropertiesEditorForm");
                }

                object script1 = null; //should be a Microsoft.AnalysisServices.MdxCodeDom.MdxCodeScript object
                try
                {
                    //validate the script because deploying an invalid script makes cube unusable
                    Microsoft.AnalysisServices.Design.Scripts scripts  = new Microsoft.AnalysisServices.Design.Scripts(cube);
                    System.Reflection.BindingFlags            getflags = System.Reflection.BindingFlags.NonPublic | System.Reflection.BindingFlags.GetField | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                    script1 = scripts.GetType().InvokeMember("mdxCodeScript", getflags, null, scripts, null);
                }
                catch (Microsoft.AnalysisServices.Design.ScriptParsingFailed ex)
                {
                    string throwaway = ex.Message; //prevents a warning during compile
                    MessageBox.Show("MDX Script in " + cube.Name + " is not valid.", "Problem Deploying MDX Script");
                    return;
                }

                if (cube.MdxScripts.Count == 0)
                {
                    MessageBox.Show("There is no MDX script defined in this cube yet.");
                    return;
                }

                System.Reflection.BindingFlags getmethodflags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                form1.GetType().InvokeMember("Initialize", getmethodflags, null, form1, new object[] { cube.MdxScripts[0], script1, cube, null });

                //now make custom changes to the form
                Button okButton = (Button)form1.Controls.Find("okButton", true)[0];
                Panel  panel    = (Panel)form1.Controls.Find("gridPanel", true)[0];

                Button descButton = new Button();
                descButton.Text   = "Edit Description";
                descButton.Anchor = AnchorStyles.Left | AnchorStyles.Bottom;
                descButton.Left   = panel.Left;
                descButton.Top    = okButton.Top;
                descButton.Width += 40;
                descButton.Click += new EventHandler(descButton_Click);
                form1.Controls.Add(descButton);
            }

            if (Microsoft.DataWarehouse.DataWarehouseUtilities.ShowDialog(form1, provider) == DialogResult.OK)
            {
                using (WaitCursor cursor2 = new WaitCursor())
                {
                    System.Reflection.BindingFlags getflags    = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.InvokeMethod | System.Reflection.BindingFlags.DeclaredOnly | System.Reflection.BindingFlags.Instance;
                    CalculationPropertyCollection  collection1 = (CalculationPropertyCollection)form1.GetType().InvokeMember("GetResultProperties", getflags, null, form1, new object[] { });

                    DesignerTransaction transaction1 = null;
                    try
                    {
                        IDesignerHost host1 = (IDesignerHost)ApplicationObject.ActiveWindow.Object;
                        transaction1 = host1.CreateTransaction("BidsHelperCalcPropertiesUndoBatchDesc");
                        IComponentChangeService service1 = (IComponentChangeService)ApplicationObject.ActiveWindow.Object;
                        service1.OnComponentChanging(cube.MdxScripts[0].CalculationProperties, null);
                        cube.MdxScripts[0].CalculationProperties.Clear();
                        for (int num1 = collection1.Count - 1; num1 >= 0; num1--)
                        {
                            CalculationProperty property1 = collection1[num1];
                            collection1.RemoveAt(num1);
                            cube.MdxScripts[0].CalculationProperties.Insert(0, property1);
                        }
                        service1.OnComponentChanged(cube.MdxScripts[0].CalculationProperties, null, null, null);
                    }
                    catch (CheckoutException exception1)
                    {
                        if (transaction1 != null)
                        {
                            transaction1.Cancel();
                        }
                        if (exception1 != CheckoutException.Canceled)
                        {
                            throw exception1;
                        }
                    }
                    finally
                    {
                        if (transaction1 != null)
                        {
                            transaction1.Commit();
                        }
                    }
                }
            }
        }
        public static void DeployScript(ProjectItem projItem, DTE2 ApplicationObject)
        {
            Microsoft.AnalysisServices.Cube oCube = (Microsoft.AnalysisServices.Cube)projItem.Object;
            try
            {
                //validate the script because deploying an invalid script makes cube unusable
                Microsoft.AnalysisServices.Design.Scripts script = new Microsoft.AnalysisServices.Design.Scripts(oCube);
            }
            catch (Microsoft.AnalysisServices.Design.ScriptParsingFailed ex)
            {
                string throwaway = ex.Message;
                MessageBox.Show("MDX Script in " + oCube.Name + " is not valid.", "Problem Deploying MDX Script");
                return;
            }

            if (oCube.MdxScripts.Count == 0)
            {
                MessageBox.Show("There is no MDX script defined in this cube yet.");
                return;
            }

            try
            {
                ApplicationObject.StatusBar.Animate(true, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 1, 5);


                // Check if the file is read-only (and probably checked in to a source control system)
                // before attempting to save. (issue: 10327 )
                FileAttributes fa = System.IO.File.GetAttributes(projItem.get_FileNames(1));
                if ((fa & FileAttributes.ReadOnly) != FileAttributes.ReadOnly)
                {
                    //TODO - can I check and maybe prompt before saving?
                    //Save the cube
                    projItem.Save("");
                }

                ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 2, 5);

                // extract deployment information
                DeploymentSettings deploySet = new DeploymentSettings(projItem);

                // use xlst to create xmla alter command
                XslCompiledTransform xslt = new XslCompiledTransform();
                XmlReader            xsltRdr;
                XmlReader            xrdr;

                // read xslt from embedded resource
                xsltRdr = XmlReader.Create(new StringReader(BIDSHelper.Resources.Common.DeployMdxScript));
                using ((xsltRdr))
                {
                    // read content from .cube file
                    xrdr = XmlReader.Create(projItem.get_FileNames(1));
                    using (xrdr)
                    {
                        ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 3, 5);
                        // Connect to Analysis Services
                        Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
                        svr.Connect(deploySet.TargetServer);
                        ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 4, 5);
                        // execute the xmla
                        try
                        {
                            Microsoft.AnalysisServices.Scripter scr = new Microsoft.AnalysisServices.Scripter();

                            // Build up the Alter MdxScript command using XSLT against the .cube file
                            XslCompiledTransform xslta = new XslCompiledTransform();
                            StringBuilder        sb    = new StringBuilder();
                            XmlWriterSettings    xws   = new XmlWriterSettings();
                            xws.OmitXmlDeclaration = true;
                            xws.ConformanceLevel   = ConformanceLevel.Fragment;
                            XmlWriter xwrtr = XmlWriter.Create(sb, xws);

                            xslta.Load(xsltRdr);
                            XsltArgumentList xslarg = new XsltArgumentList();

                            Database targetDB = svr.Databases.FindByName(deploySet.TargetDatabase);
                            if (targetDB == null)
                            {
                                throw new System.Exception(string.Format("A database called {0} could not be found on the {1} server", deploySet.TargetDatabase, deploySet.TargetServer));
                            }
                            string targetDatabaseID = targetDB.ID;
                            xslarg.AddParam("TargetDatabase", "", targetDatabaseID);
                            xslta.Transform(xrdr, xslarg, xwrtr);

                            // Extract the current script from the server and keep a temporary backup copy of it
                            StringBuilder     sbBackup = new StringBuilder();
                            XmlWriterSettings xwSet    = new XmlWriterSettings();
                            xwSet.ConformanceLevel   = ConformanceLevel.Fragment;
                            xwSet.OmitXmlDeclaration = true;
                            xwSet.Indent             = true;
                            XmlWriter xwScript = XmlWriter.Create(sbBackup, xwSet);

                            Cube oServerCube = targetDB.Cubes.Find(oCube.ID);
                            if (oServerCube == null)
                            {
                                throw new System.Exception(string.Format("The {0} cube is not yet deployed to the {1} server.", oCube.Name, deploySet.TargetServer));
                            }
                            else if (oServerCube.State == AnalysisState.Unprocessed)
                            {
                                throw new System.Exception(string.Format("The {0} cube is not processed the {1} server.", oCube.Name, deploySet.TargetServer));
                            }
                            if (oServerCube.MdxScripts.Count == 0)
                            {
                                scr.ScriptAlter(new Microsoft.AnalysisServices.MajorObject[] { oServerCube }, xwScript, true);
                            }
                            else
                            {
                                MdxScript mdxScr = oServerCube.MdxScripts[0];
                                scr.ScriptAlter(new Microsoft.AnalysisServices.MajorObject[] { mdxScr }, xwScript, true);
                            }
                            xwScript.Close();

                            // update the MDX Script
                            XmlaResultCollection xmlaRC = svr.Execute(sb.ToString());
                            if (xmlaRC.Count == 1 && xmlaRC[0].Messages.Count == 0)
                            {
                                // all OK - 1 result - no messages
                            }
                            else
                            {
                                StringBuilder sbErr = new StringBuilder();
                                for (int iRC = 0; iRC < xmlaRC.Count; iRC++)
                                {
                                    for (int iMsg = 0; iMsg < xmlaRC[iRC].Messages.Count; iMsg++)
                                    {
                                        sbErr.AppendLine(xmlaRC[iRC].Messages[iMsg].Description);
                                    }
                                }
                                MessageBox.Show(sbErr.ToString(), "BIDSHelper - Deploy MDX Script");
                            }


                            // Test the MDX Script
                            AdomdConnection cn = new AdomdConnection("Data Source=" + deploySet.TargetServer + ";Initial Catalog=" + deploySet.TargetDatabase);
                            cn.Open();
                            AdomdCommand cmd = cn.CreateCommand();
                            string       qry = "SELECT {} ON 0 FROM [" + oCube.Name + "];";
                            cmd.CommandText = qry;
                            try
                            {
                                // test that we can query the cube without errors
                                cmd.Execute();

                                // Building the project means that the .asdatabase file gets re-built so that
                                // we do not break the Deployment Wizard.
                                // --
                                // This line is included in this try block so that it is only executed if we can
                                // successfully query the cube without errors.
                                projItem.DTE.Solution.SolutionBuild.BuildProject(projItem.DTE.Solution.SolutionBuild.ActiveConfiguration.Name, projItem.ContainingProject.UniqueName, false);
                            }
                            catch (System.Exception ex)
                            {
                                // undo the deployment if we caught an exception during the deployment
                                svr.Execute(sbBackup.ToString());
                                MessageBox.Show(ex.Message);
                            }
                            finally
                            {
                                cmd.Dispose();
                                cn.Close();
                                cn.Dispose();
                            }
                        }
                        catch (System.Exception ex)
                        {
                            if (MessageBox.Show("The following error occured while trying to deploy the MDX Script\r\n"
                                                + ex.Message
                                                + "\r\n\r\nDo you want to see a stack trace?"
                                                , "BIDSHelper - Deploy MDX Script"
                                                , MessageBoxButtons.YesNo
                                                , MessageBoxIcon.Error
                                                , MessageBoxDefaultButton.Button2) == DialogResult.Yes)
                            {
                                MessageBox.Show(ex.StackTrace);
                            }
                        }
                        finally
                        {
                            ApplicationObject.StatusBar.Progress(true, "Deploying MdxScript", 5, 5);
                            // report any results back (status bar?)
                            svr.Disconnect();
                            svr.Dispose();
                        }
                    }
                }
            }
            finally
            {
                ApplicationObject.StatusBar.Animate(false, vsStatusAnimation.vsStatusAnimationDeploy);
                ApplicationObject.StatusBar.Progress(false, "Deploying MdxScript", 5, 5);
            }
        }