Link to home
Start Free TrialLog in
Avatar of homeshopper
homeshopperFlag for United Kingdom of Great Britain and Northern Ireland

asked on

Cannot convert type 'string' to 'Microsoft.AnalysisServices.RelationalDataSource'

Hi, I am getting the following error:
ds = (Microsoft.AnalysisServices.RelationalDataSource)CreateDataSource(db, strDataSourceName, strStringConnection);//Error      1      Cannot convert type 'string' to 'Microsoft.AnalysisServices.RelationalDataSource' Line:255      18
Thanks in advance for any help given.
For clarity I have listed complete below:
protected void btnGo_Click(object sender, EventArgs e)
    {
        try
        {
            errorLabel4.Text = "";
            lblErr.Text = "";
            System.Web.HttpContext.Current.Response.Write("<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>&nbsp;Yes:GO1:<br/>");
            System.Web.HttpContext.Current.Response.Write("");
            strConn = txtConnStr.Text;
            commandText = txtMDX.Text;
            lblTable.Text = "<font color='Silver'>" + "Ln:227T:btn:" + strConn + "#" + "</font>" + "<font color='green'>" + "&nbsp;&nbsp;&nbsp;&nbsp;cmdT:" + "</font>" + "<font color='Silver'>" + commandText + "#" + "</font>";
            //Microsoft.AnalysisServices.AdomdClient.AdomdConnection svr = new Microsoft.AnalysisServices.AdomdClient.AdomdConnection(strConn);
            //svr.Open();
            //Microsoft.AnalysisServices.AdomdClient.AdomdCommand cmd = new Microsoft.AnalysisServices.AdomdClient.AdomdCommand(commandText, svr);
            //<!-- Start Page Content -->            
            System.Web.HttpContext.Current.Response.Write("232:Cube creation process started.<br/>");
            Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
            Microsoft.AnalysisServices.Database db = new Microsoft.AnalysisServices.Database();
            //Microsoft.AnalysisServices.RelationalDataSource ds = new Microsoft.AnalysisServices.RelationalDataSource();
            Microsoft.AnalysisServices.RelationalDataSource ds = new Microsoft.AnalysisServices.RelationalDataSource();
            Microsoft.AnalysisServices.DataSourceView objDataSourceView = new Microsoft.AnalysisServices.DataSourceView();
            DataSet objDataSet = new DataSet();
            Microsoft.AnalysisServices.Dimension[] objDimensions = new Microsoft.AnalysisServices.Dimension[intDimensionTableCount];
            strStringConnection = "Provider=" + strProviderName + ";data source=" + strDBServerName + ";";
            //1) Connect to the Analysis Services :Create a connection of AnalysisServices server.
            //objServer = (Microsoft.AnalysisServices.Server)ConnectAnalysisServices(strDBServerName, strProviderName);
            //static Microsoft.AnalysisServices.Server ServerConnect( String strStringConnection)
            svr = (Microsoft.AnalysisServices.Server)ServerConnect(strStringConnection);
            System.Web.HttpContext.Current.Response.Write("245:ServerConnect(strStringConnection)<br/>");
            //2) Create a Database :Create a database in AnalysisServices server and save it.
            //objDatabase = (Microsoft.AnalysisServices.Database)CreateDatabase(objServer, strCubeDBName);
            //static Microsoft.AnalysisServices.Database CreateDatabase(Microsoft.AnalysisServices.Server svr, String DatabaseName)
            db = (Microsoft.AnalysisServices.Database)CreateDatabase(svr, strCubeDBName);
            System.Web.HttpContext.Current.Response.Write("250:CreateDatabase(svr, strCubeDBName)<br/>");
            //3) Create a DataSource :Add a datasource to the database and set its connection string.
            //objDataSource = (Microsoft.AnalysisServices.RelationalDataSource)CreateDataSource(objServer, objDatabase, strCubeDataSourceName, strDBServerName, strDBName);
            //static string CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
            //static object CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
            ds = (Microsoft.AnalysisServices.RelationalDataSource)CreateDataSource(db, strDataSourceName, strStringConnection);//Error	1	Cannot convert type 'string' to 'Microsoft.AnalysisServices.RelationalDataSource' Line:255	18
            System.Web.HttpContext.Current.Response.Write("256:CreateDataSource(db, strDataSourceName, strStringConnection)<br/>");
			
            //<!-- End Page Content -->
            System.Web.HttpContext.Current.Response.Write("<br/>&nbsp;End");
        }
        catch (System.Exception ex)
        {
            lblErr.Text = "&nbsp;&nbsp;" + ex.Message;
            errorLabel4.Text = "<font color='red'>" + "err:306E:btn:" + "</font>" + ex.ToString();
        }
    }// End btnGo_Click 
		//http://technet.microsoft.com/en-us/library/ms345093.aspx
        //1) Connect to the Analysis Services :Create a connection of AnalysisServices server.
		//Connecting to the Server Object
		static Microsoft.AnalysisServices.Server ServerConnect( String strStringConnection)
        {
            string methodCaption = "ServerConnect method";
            Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
            try
            {
                svr.Connect(strStringConnection);
            }
            #region ErrorHandling
            catch (Microsoft.AnalysisServices.AmoException e)
            {
                MessageBox.Show( "AMO exception " + e.ToString());
                svr = null;
            }
            catch (Exception e)
            {
                MessageBox.Show("General exception " + e.ToString());
                svr = null;
            }
            #endregion          
            return svr;
        }
        //2) Create a Database :Create a database in AnalysisServices server and save it.
		//Creating, Dropping, and Finding a Database
        static Microsoft.AnalysisServices.Database CreateDatabase(Microsoft.AnalysisServices.Server svr, String DatabaseName)
        {
            Microsoft.AnalysisServices.Database db = null;
            if ( (svr != null) && ( svr.Connected))
            {
                // Drop the database if it already exists
                db = svr.Databases.FindByName(DatabaseName);
                if (db != null)
                {
                    db.Drop();
                }
                // Create the database
                db = svr.Databases.Add(DatabaseName);
                db.Update();
            }          
            return db;
        }
		//3) Create a DataSource :Add a datasource to the database and set its connection string.
		//DataSource Objects
        //static object CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
        static string CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
        {
                Microsoft.AnalysisServices.Server svr = db.Parent;
                Microsoft.AnalysisServices.DataSource ds = db.DataSources.FindByName(strDataSourceName);
                if (ds != null)
                    ds.Drop();
                // Create the data source
                ds = db.DataSources.Add(strDataSourceName, strDataSourceName);
                ds.ConnectionString = strConnectionString;
                // Send the data source definition to the server.
                ds.Update();
                return ds.Name;
        }

Open in new window

Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

CreateDataSource function returns string not Microsoft.AnalysisServices.Database,
so u can't case the result of the function to Microsoft.AnalysisServices.Database.
check line 98 for function signature.
Avatar of homeshopper

ASKER

Thank for the help I was able to create DataSource with alterations as follows:
Just now need to work on code to produce DataSouceView.
static object CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
        {
                Microsoft.AnalysisServices.Server svr = db.Parent;
                Microsoft.AnalysisServices.DataSource ds = db.DataSources.FindByName(strDataSourceName);
                if (ds != null)
                    ds.Drop();
                // Create the data source
                ds = db.DataSources.Add(strDataSourceName, strDataSourceName);
                ds.ConnectionString = strConnectionString;
                // Send the data source definition to the server.
                ds.Update();
                //return ds.Name;
                return ds;
        }

Open in new window

Thankyou for the link, I was hoping to use the code as follows:
but it says: The dbo cube either does not exist or has not been processed.
public string strDBServerName = "Localhost";
    public string strProviderName = "msolap";
    public string strFactTableName = "FactResellerSales";
    public string strDBName = "AdventureWorksDW";
    public string strCubeDBName = "OLAPDB";
    public string strDataSourceName = "OLAPDS";
    public string strCubeDataSourceViewName = "OLAPDSView";
    public int intDimensionTableCount = 6;
    public string strStringConnection;

Open in new window

//d) Create a DataSourceView based on the created DataSet.
            //objDataSourceView = (Microsoft.AnalysisServices.DataSourceView)CreateDataSourceView(objDatabase, objDataSource, objDataSet, strCubeDataSourceViewName);
            //static Microsoft.AnalysisServices.DataSourceView CreateDataSourceView(Microsoft.AnalysisServices.Database db, string strDataSourceName)
            objDataSourceView = (Microsoft.AnalysisServices.DataSourceView)CreateDataSourceView(db, strDataSourceName);
            System.Web.HttpContext.Current.Response.Write("262:CreateDataSourceView(db, strDataSourceName)<br/>");

Open in new window

//d) Create a DataSourceView based on the created DataSet.
		//DataSourceView Objects
        static Microsoft.AnalysisServices.DataSourceView CreateDataSourceView(Microsoft.AnalysisServices.Database db, string strDataSourceName)
        {
            // Create the data source view
            Microsoft.AnalysisServices.DataSourceView dsv = db.DataSourceViews.FindByName(strDataSourceName);
            if ( dsv != null)
               dsv.Drop();
            dsv = db.DataSourceViews.Add(strDataSourceName);
            dsv.DataSourceID = strDataSourceName;
            dsv.Schema = new DataSet();
            dsv.Schema.Locale = System.Globalization.CultureInfo.CurrentCulture;
            // Open a connection to the data source
            OleDbConnection connection = new OleDbConnection(dsv.DataSource.ConnectionString);
            connection.Open();
            #region Create tables
            // Add the DimTime table
            AddTable(dsv, connection, "DimTime");
            AddComputedColumn(dsv, connection, "DimTime", "SimpleDate", "DATENAME(mm, FullDateAlternateKey) + ' ' + DATENAME(dd, FullDateAlternateKey) + ',' + ' ' + DATENAME(yy, FullDateAlternateKey)");
            AddComputedColumn(dsv, connection, "DimTime", "CalendarYearDesc", "'CY' + ' ' + CalendarYear");
            AddComputedColumn(dsv, connection, "DimTime", "CalendarSemesterDesc", "CASE WHEN CalendarSemester = 1 THEN 'H1'+' '+ 'CY' +' '+ CONVERT(CHAR (4), CalendarYear) ELSE 'H2'+' '+ 'CY' +' '+ CONVERT(CHAR (4), CalendarYear) END");
            AddComputedColumn(dsv, connection, "DimTime", "CalendarQuarterDesc", "'Q' + CONVERT(CHAR (1), CalendarQuarter) +' '+ 'CY' +' '+ CONVERT(CHAR (4), CalendarYear)");
            AddComputedColumn(dsv, connection, "DimTime", "MonthName", "EnglishMonthName+' '+ CONVERT(CHAR (4), CalendarYear)");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalYearDesc", "'FY' + ' ' + FiscalYear");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalSemesterDesc", "CASE WHEN FiscalSemester = 1 THEN 'H1'+' '+ 'FY' +' '+ CONVERT(CHAR (4), FiscalYear) ELSE 'H2'+' '+ 'FY' +' '+ CONVERT(CHAR (4), FiscalYear) END");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalQuarterDesc", "'Q' + CONVERT(CHAR (1), FiscalQuarter) +' '+ 'FY' +' '+ CONVERT(CHAR (4), FiscalYear)");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalMonthNumberOfYear", "CASE WHEN MonthNumberOfYear = '1'  THEN CONVERT(int,'7') WHEN MonthNumberOfYear = '2'  THEN CONVERT(int,'8') WHEN MonthNumberOfYear = '3'  THEN CONVERT(int,'9') WHEN MonthNumberOfYear = '4'  THEN CONVERT(int,'10') WHEN MonthNumberOfYear = '5'  THEN CONVERT(int,'11') WHEN MonthNumberOfYear = '6'  THEN CONVERT(int,'12') WHEN MonthNumberOfYear = '7'  THEN CONVERT(int,'1') WHEN MonthNumberOfYear = '8'  THEN CONVERT(int,'2') WHEN MonthNumberOfYear = '9'  THEN CONVERT(int,'3') WHEN MonthNumberOfYear = '10' THEN CONVERT(int,'4') WHEN MonthNumberOfYear = '11' THEN CONVERT(int,'5') WHEN MonthNumberOfYear = '12' THEN CONVERT(int,'6') END");
            dsv.Update();
            // Add the DimGeography table
            AddTable(dsv, connection, "DimGeography");
            // Add the DimProductCategory table
            AddTable(dsv, connection, "DimProductCategory");
            // Add the DimProductSubcategory table
            AddTable(dsv, connection, "DimProductSubcategory");
            AddRelation(dsv, "DimProductSubcategory", "ProductCategoryKey", "DimProductCategory", "ProductCategoryKey");
            // Add the DimProduct table
            AddTable(dsv, connection, "DimProduct");
            AddComputedColumn(dsv, connection, "DimProduct", "ProductLineName", "CASE ProductLine WHEN 'M' THEN 'Mountain' WHEN 'R' THEN 'Road' WHEN 'S' THEN 'Accessory' WHEN 'T' THEN 'Touring' ELSE 'Components' END");
            AddRelation(dsv, "DimProduct", "ProductSubcategoryKey", "DimProductSubcategory", "ProductSubcategoryKey");
            dsv.Update();
            // Add the DimCustomer table
            AddTable(dsv, connection, "DimCustomer");
            AddComputedColumn(dsv, connection, "DimCustomer", "FullName", "CASE WHEN MiddleName IS NULL THEN FirstName + ' ' + LastName ELSE FirstName + ' ' + MiddleName + ' ' + LastName END");
            AddComputedColumn(dsv, connection, "DimCustomer", "GenderDesc", "CASE WHEN Gender = 'M' THEN 'Male' ELSE 'Female' END");
            AddComputedColumn(dsv, connection, "DimCustomer", "MaritalStatusDesc", "CASE WHEN MaritalStatus = 'S' THEN 'Single' ELSE 'Married' END");
            AddRelation(dsv, "DimCustomer", "GeographyKey", "DimGeography", "GeographyKey");
            // Add the DimReseller table
            AddTable(dsv, connection, "DimReseller");
            AddComputedColumn(dsv, connection, "DimReseller", "OrderFrequencyDesc", "CASE WHEN OrderFrequency = 'A' THEN 'Annual' WHEN OrderFrequency = 'S' THEN 'Bi-Annual' ELSE 'Quarterly' END");
            AddComputedColumn(dsv, connection, "DimReseller", "OrderMonthDesc", "CASE WHEN OrderMonth = '1' THEN 'January' WHEN OrderMonth = '2' THEN 'February' WHEN OrderMonth = '3' THEN 'March' WHEN OrderMonth = '4' THEN 'April' WHEN OrderMonth = '5' THEN 'May' WHEN OrderMonth = '6' THEN 'June' WHEN OrderMonth = '7' THEN 'July' WHEN OrderMonth = '8' THEN 'August' WHEN OrderMonth = '9' THEN 'September' WHEN OrderMonth = '10' THEN 'October' WHEN OrderMonth = '11' THEN 'November' WHEN OrderMonth = '12' THEN 'December' ELSE 'Never Ordered' END");
            // Add the DimCurrency table
            AddTable(dsv, connection, "DimCurrency");
            dsv.Update();
            // Add the DimSalesReason table
            AddTable(dsv, connection, "DimSalesReason");
            // Add the FactInternetSales table
            AddTable(dsv, connection, "FactInternetSales");
            AddRelation(dsv, "FactInternetSales", "ProductKey", "DimProduct", "ProductKey");
            AddRelation(dsv, "FactInternetSales", "CustomerKey", "DimCustomer", "CustomerKey");
            AddRelation(dsv, "FactInternetSales", "OrderDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactInternetSales", "ShipDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactInternetSales", "DueDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactInternetSales", "CurrencyKey", "DimCurrency", "CurrencyKey");
            dsv.Update();
            // Add the FactResellerSales table
            AddTable(dsv, connection, "FactResellerSales");
            AddRelation(dsv, "FactResellerSales", "ProductKey", "DimProduct", "ProductKey");
            AddRelation(dsv, "FactResellerSales", "ResellerKey", "DimReseller", "ResellerKey");
            AddRelation(dsv, "FactResellerSales", "OrderDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactResellerSales", "ShipDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactResellerSales", "DueDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactResellerSales", "CurrencyKey", "DimCurrency", "CurrencyKey");
            // Add the FactInternetSalesReason table
            AddTable(dsv, connection, "FactInternetSalesReason");
            AddCompositeRelation(dsv, "FactInternetSalesReason", "FactInternetSales", "SalesOrderNumber", "SalesOrderLineNumber");
            dsv.Update();
            // Add the FactCurrencyRate table
            AddTable(dsv, connection, "FactCurrencyRate");
            AddRelation(dsv, "FactCurrencyRate", "CurrencyKey", "DimCurrency", "CurrencyKey");
            AddRelation(dsv, "FactCurrencyRate", "TimeKey", "DimTime", "TimeKey");
            #endregion
            // Send the data source view definition to the server
            dsv.Update();
            return dsv;
        }

Open in new window

Do I need to use the following code first somewhere?
//Processing a Database
        static Microsoft.AnalysisServices.Database ProcessDatabase(Microsoft.AnalysisServices.Database db, Microsoft.AnalysisServices.ProcessType pt)
        {
            db.Process( pt);
            return db;
        }

Open in new window

Just realized I have not created DataSet, so doing so now.
I have added more code, but still get error:The dbo cube either does not exist or has not been processed.
The screen displays the following:
232:Cube creation process started.
245:ServerConnect(strStringConnection)
250:CreateDatabase(svr, strCubeDBName)
256:CreateDataSource(db, strDataSourceName, strStringConnection)
369:Creating a DataSourceView ...
Below, for clarity I have listed all code:
Thanks in advance for any help given.
protected void btnGo_Click(object sender, EventArgs e)
    {
        try
        {
            errorLabel4.Text = "";
            lblErr.Text = "";
            System.Web.HttpContext.Current.Response.Write("<br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/><br/>&nbsp;Yes:GO1:<br/>");
            System.Web.HttpContext.Current.Response.Write("");
            strConn = txtConnStr.Text;
            commandText = txtMDX.Text;
            lblTable.Text = "<font color='Silver'>" + "Ln:227T:btn:" + strConn + "#" + "</font>" + "<font color='green'>" + "&nbsp;&nbsp;&nbsp;&nbsp;cmdT:" + "</font>" + "<font color='Silver'>" + commandText + "#" + "</font>";
            //Microsoft.AnalysisServices.AdomdClient.AdomdConnection svr = new Microsoft.AnalysisServices.AdomdClient.AdomdConnection(strConn);
            //svr.Open();
            //Microsoft.AnalysisServices.AdomdClient.AdomdCommand cmd = new Microsoft.AnalysisServices.AdomdClient.AdomdCommand(commandText, svr);
            //<!-- Start Page Content -->            
            System.Web.HttpContext.Current.Response.Write("232:Cube creation process started.<br/>");
            Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
            Microsoft.AnalysisServices.Database db = new Microsoft.AnalysisServices.Database();
            //Microsoft.AnalysisServices.RelationalDataSource ds = new Microsoft.AnalysisServices.RelationalDataSource();
            Microsoft.AnalysisServices.RelationalDataSource ds = new Microsoft.AnalysisServices.RelationalDataSource();
            Microsoft.AnalysisServices.DataSourceView objDataSourceView = new Microsoft.AnalysisServices.DataSourceView();
            DataSet objDataSet = new DataSet();
            Microsoft.AnalysisServices.Dimension[] objDimensions = new Microsoft.AnalysisServices.Dimension[intDimensionTableCount];
            strStringConnection = "Provider=" + strProviderName + ";data source=" + strDBServerName + ";";
            //1) Connect to the Analysis Services :Create a connection of AnalysisServices server.
            //objServer = (Microsoft.AnalysisServices.Server)ConnectAnalysisServices(strDBServerName, strProviderName);
            //static Microsoft.AnalysisServices.Server ServerConnect( String strStringConnection)
            svr = (Microsoft.AnalysisServices.Server)ServerConnect(strStringConnection);
            System.Web.HttpContext.Current.Response.Write("245:ServerConnect(strStringConnection)<br/>");
            //2) Create a Database :Create a database in AnalysisServices server and save it.
            //objDatabase = (Microsoft.AnalysisServices.Database)CreateDatabase(objServer, strCubeDBName);
            //static Microsoft.AnalysisServices.Database CreateDatabase(Microsoft.AnalysisServices.Server svr, String DatabaseName)
            db = (Microsoft.AnalysisServices.Database)CreateDatabase(svr, strCubeDBName);
            System.Web.HttpContext.Current.Response.Write("250:CreateDatabase(svr, strCubeDBName)<br/>");
            //3) Create a DataSource :Add a datasource to the database and set its connection string.
            //objDataSource = (Microsoft.AnalysisServices.RelationalDataSource)CreateDataSource(objServer, objDatabase, strCubeDataSourceName, strDBServerName, strDBName);
            //static string CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
            //static object CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
            ds = (Microsoft.AnalysisServices.RelationalDataSource)CreateDataSource(db, strDataSourceName, strStringConnection);
            System.Web.HttpContext.Current.Response.Write("256:CreateDataSource(db, strDataSourceName, strStringConnection)<br/>");
            //4) Create a DataSourceView :
            //a) Create a DataSet.
            //b) Add Fact tables in DataSet.
            //c) Add Dimension tables in DataSet and Relation between them.
            //d) Create a DataSourceView based on the created DataSet.
            string[,] strTableNamesAndKeys = { 
                                             { "DimCurrency", "CurrencyKey", "FactResellerSales", "CurrencyKey" },
                                             { "DimEmployee", "EmployeeKey", "FactResellerSales", "EmployeeKey" },
                                             { "DimProduct", "ProductKey", "FactResellerSales", "ProductKey" },
                                             { "DimPromotion", "PromotionKey", "FactResellerSales", "PromotionKey" },
                                             { "DimReseller", "ResellerKey", "FactResellerSales", "ResellerKey" },
                                             { "DimSalesTerritory", "SalesTerritoryKey", "FactResellerSales", "SalesTerritoryKey" },
                                             };
            objDataSet = (DataSet)GenerateDWSchema(strDBServerName, strDBName, strFactTableName, strTableNamesAndKeys, intDimensionTableCount);
            //d) Create a DataSourceView based on the created DataSet.
            //static Microsoft.AnalysisServices.DataSourceView CreateDataSourceView(Microsoft.AnalysisServices.Database db, string strDataSourceName)
            objDataSourceView = (Microsoft.AnalysisServices.DataSourceView)CreateDataSourceView(db, strDataSourceName);
            
            //static Microsoft.AnalysisServices.DataSourceView CreateDataSourceView(Microsoft.AnalysisServices.Database db, string strDataSourceName)
            objDataSourceView = (Microsoft.AnalysisServices.DataSourceView)CreateDataSourceView(db, strDataSourceName);
            System.Web.HttpContext.Current.Response.Write("277:CreateDataSourceView(db, strDataSourceName)<br/>");
            //<!-- End Page Content -->
            System.Web.HttpContext.Current.Response.Write("<br/>&nbsp;End");
        }
        catch (System.Exception ex)
        {
            lblErr.Text = "&nbsp;&nbsp;" + ex.Message;
            errorLabel4.Text = "<font color='red'>" + "err:284E:btn:" + "</font>" + ex.ToString();
        }
    }// End btnGo_Click 
		//http://technet.microsoft.com/en-us/library/ms345093.aspx
        //1) Connect to the Analysis Services :Create a connection of AnalysisServices server.
		//Connecting to the Server Object
		static Microsoft.AnalysisServices.Server ServerConnect( String strStringConnection)
        {
            //string methodCaption = "ServerConnect method";
            Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
            try
            {
                svr.Connect(strStringConnection);
            }
            #region ErrorHandling
            catch (Microsoft.AnalysisServices.AmoException e)
            {
                MessageBox.Show( "AMO exception " + e.ToString());
                svr = null;
            }
            catch (Exception e)
            {
                MessageBox.Show("General exception " + e.ToString());
                svr = null;
            }
            #endregion          
            return svr;
        }
        //2) Create a Database :Create a database in AnalysisServices server and save it.
		//Creating, Dropping, and Finding a Database
        static Microsoft.AnalysisServices.Database CreateDatabase(Microsoft.AnalysisServices.Server svr, String DatabaseName)
        {
            Microsoft.AnalysisServices.Database db = null;
            if ( (svr != null) && ( svr.Connected))
            {
                // Drop the database if it already exists
                db = svr.Databases.FindByName(DatabaseName);
                if (db != null)
                {
                    db.Drop();
                }
                // Create the database
                db = svr.Databases.Add(DatabaseName);
                db.Update();
            }          
            return db;
        }
		//Processing a Database
        static Microsoft.AnalysisServices.Database ProcessDatabase(Microsoft.AnalysisServices.Database db, Microsoft.AnalysisServices.ProcessType pt)
        {
            db.Process( pt);
            return db;
        }
        //3) Create a DataSource :Add a datasource to the database and set its connection string.
		//DataSource Objects
        //static string CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
        static object CreateDataSource(Microsoft.AnalysisServices.Database db, string strDataSourceName, string strConnectionString)
        {
                Microsoft.AnalysisServices.Server svr = db.Parent;
                Microsoft.AnalysisServices.DataSource ds = db.DataSources.FindByName(strDataSourceName);
                if (ds != null)
                    ds.Drop();
                // Create the data source
                ds = db.DataSources.Add(strDataSourceName, strDataSourceName);
                ds.ConnectionString = strConnectionString;
                // Send the data source definition to the server.
                ds.Update();
                //return ds.Name;
                return ds;
        }
        //4) Create a DataSourceView :
        //a) Create a DataSet.
        //b) Add Fact tables in DataSet.
        //c) Add Dimension tables in DataSet and Relation between them.
        //d) Create a DataSourceView based on the created DataSet.
        /// <param name="strDBServerName">DB Server Name.</param>
        /// <param name="strDBName">DB Name.</param>
        /// <param name="strFactTableName">FactTable Name.</param>
        /// <param name="strTableNamesAndKeys">Array of TableNames and Keys.</param>
        /// <param name="intDimensionTableCount">Dimension Table Count.</param>
        /// <returns>DataSet instance.</returns>
        private static object GenerateDWSchema(string strDBServerName, string strDBName, string strFactTableName, string[,] strTableNamesAndKeys, int intDimensionTableCount)
        {
            try
            {
                System.Web.HttpContext.Current.Response.Write("369:Creating a DataSourceView ...");
                System.Web.HttpContext.Current.Response.Write("<br/>");
                //Create the connection string.
                string conxString = "Data Source=" + strDBServerName + "; Initial Catalog=" + strDBName + "; Integrated Security=True;";
                //Create the SqlConnection.
                SqlConnection objConnection = new SqlConnection(conxString);
                DataSet objDataSet = new DataSet();
                //Add FactTable in DataSet.
                objDataSet = (DataSet)FillDataSet(objConnection, objDataSet, strFactTableName);
                //Add table in DataSet and Relation between them.
                for (int i = 0; i < intDimensionTableCount; i++)
                {
                    //Retrieve table's schema and assign the table's schema to the DataSet.
                    //Add primary key to the schema according to the primary key in the tables.
                    objDataSet = (DataSet)FillDataSet(objConnection, objDataSet, strTableNamesAndKeys[i, 0]);
                    objDataSet = (DataSet)AddDataTableRelation(objDataSet, strTableNamesAndKeys[i, 0], strTableNamesAndKeys[i, 1], strTableNamesAndKeys[i, 2], strTableNamesAndKeys[i, 3]);
                }
                return objDataSet;
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("390:Error in Creating a DataSourceView - GenerateDWSchema. Error Message -> " + ex.Message);
                System.Web.HttpContext.Current.Response.Write("<br/>");
                return null;
            }
        }// End GenerateDWSchema(string strDBServerName, string strDBName, string strFactTableName, string[,] strTableNamesAndKeys, int intDimensionTableCount)
        /// <summary>
        /// Fill the DataSet with DataTables.
        /// </summary>
        /// <param name="objConnection">Connection instance.</param>
        /// <param name="objDataSet">DataSet instance.</param>
        /// <param name="strTableName">TableName.</param>
        /// <returns>DataSet instance.</returns>
        private static object FillDataSet(SqlConnection objConnection, DataSet objDataSet, string strTableName)
        {
            try
            {
                string strCommand = "Select * from " + strTableName;
                SqlDataAdapter objEmpData = new SqlDataAdapter(strCommand, objConnection);
                objEmpData.MissingSchemaAction = MissingSchemaAction.AddWithKey;
                objEmpData.FillSchema(objDataSet, SchemaType.Source, strTableName);
                return objDataSet;
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("414:Error in Creating a DataSourceView - FillDataSet. Error Message -> " + ex.Message);
                System.Web.HttpContext.Current.Response.Write("<br/>");
                return null;
            }
        }// End FillDataSet(SqlConnection objConnection, DataSet objDataSet, string strTableName)
        /// <summary>
        /// Add relations between DataTables of DataSet.
        /// </summary>
        /// <param name="objDataSet">DataSet instance.</param>
        /// <param name="strParentTableName">Parent Table Name (Dimension Table).</param>
        /// <param name="strParentTableKey">Parent Table Key.</param>
        /// <param name="strChildTableName">Child Table Name (Fact Table).</param>
        /// <param name="strChildTableKey">Child Table Key.</param>
        /// <returns>DataSet instance.</returns>
        private static object AddDataTableRelation(DataSet objDataSet, string strParentTableName, string strParentTableKey, string strChildTableName, string strChildTableKey)
        {
            try
            {
                objDataSet.Relations.Add(strChildTableName + "_" + strParentTableName + "_FK", objDataSet.Tables[strParentTableName].Columns[strParentTableKey], objDataSet.Tables[strChildTableName].Columns[strChildTableKey]);
                return objDataSet;
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("437:Error in Creating a DataSourceView - AddDataTableRelation. Error Message -> " + ex.Message);
                System.Web.HttpContext.Current.Response.Write("<br/>");
                return null;
            }
        }// End AddDataTableRelation(DataSet objDataSet, string strParentTableName, string strParentTableKey, string strChildTableName, string strChildTableKey)
        /// <summary>
        /// Creating a DataSourceView.
        /// </summary>
        /// <param name="objDatabase">DB instance.</param>
        /// <param name="objDataSource">DataSource instance.</param>
        /// <param name="objDataSet">DataSet instance.</param>
        /// <param name="strCubeDataSourceViewName">Cube DataSourceView Name.</param>
        /// <returns>DataSourceView instance.</returns>
        /// <summary>
        /// Creating the Dimension, Attribute, Hierarchy, and MemberProperty Objects.
        /// </summary>
        /// <param name="objDatabase">DB instance.</param>
        /// <param name="objDataSourceView">DataSource instance.</param>
        /// <param name="strTableNamesAndKeys">Array of Table names and keys.</param>
        /// <param name="intDimensionTableCount">Dimension table count.</param>
        /// <returns>Dimension Array.</returns>
        private static object[] CreateDimension(Microsoft.AnalysisServices.Database objDatabase, Microsoft.AnalysisServices.DataSourceView objDataSourceView, string[,] strTableNamesAndKeys, int intDimensionTableCount)
        {
            try
            {
                System.Web.HttpContext.Current.Response.Write("462:Creating the Dimension, Attribute, Hierarchy, and MemberProperty Objects ...");
                System.Web.HttpContext.Current.Response.Write("<br/>");
                Microsoft.AnalysisServices.Dimension[] objDimensions = new Microsoft.AnalysisServices.Dimension[intDimensionTableCount];
                for (int i = 0; i < intDimensionTableCount; i++)
                {
                    objDimensions[i] = (Microsoft.AnalysisServices.Dimension)GenerateDimension(objDatabase, objDataSourceView, strTableNamesAndKeys[i, 0], strTableNamesAndKeys[i, 1]);
                }
                ////Add Hierarchy and Level
                //Hierarchy objHierarchy = objDimension.Hierarchies.Add("ProductByCategory");
                //objHierarchy.Levels.Add("Category").SourceAttributeID = objCatKeyAttribute.ID;
                //objHierarchy.Levels.Add("Product").SourceAttributeID = objProdKeyAttribute.ID;
                ////Add Member Property
                ////objProdKeyAttribute.AttributeRelationships.Add(objProdDescAttribute.ID);
                //objDimension.Update();
                return objDimensions;
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("480:Error in Creating the Dimension, Attribute, Hierarchy, and MemberProperty Objects. Error Message -> " + ex.Message);
                System.Web.HttpContext.Current.Response.Write("<br/>");
                return null;
            }
        }// End CreateDimension(Microsoft.AnalysisServices.Database objDatabase, Microsoft.AnalysisServices.DataSourceView objDataSourceView, string[,] strTableNamesAndKeys, int intDimensionTableCount)
        /// <summary>
        /// Generate single dimension.
        /// </summary>
        /// <param name="objDatabase">DB instance.</param>
        /// <param name="objDataSourceView">DataSourceView instance.</param>
        /// <param name="strTableName">Table name.</param>
        /// <param name="strTableKeyName">Table key.</param>
        /// <returns>Dimension instance.</returns>
        private static object GenerateDimension(Microsoft.AnalysisServices.Database objDatabase, Microsoft.AnalysisServices.DataSourceView objDataSourceView, string strTableName, string strTableKeyName)
        {
            try
            {
                Microsoft.AnalysisServices.Dimension objDimension = new Microsoft.AnalysisServices.Dimension();
                //Add Dimension to the Database
                objDimension = objDatabase.Dimensions.Add(strTableName);
                objDimension.Source = new Microsoft.AnalysisServices.DataSourceViewBinding(objDataSourceView.ID);
                Microsoft.AnalysisServices.DimensionAttributeCollection objDimensionAttributesColl = objDimension.Attributes;
                //Add Dimension Attributes
                Microsoft.AnalysisServices.DimensionAttribute objAttribute = objDimensionAttributesColl.Add(strTableKeyName);
                //Set Attribute usage and source
                objAttribute.Usage = Microsoft.AnalysisServices.AttributeUsage.Key;
                objAttribute.KeyColumns.Add(strTableName, strTableKeyName, OleDbType.Integer);
                objDimension.Update();
                return objDimension;
            }
            catch (Exception ex)
            {
                System.Web.HttpContext.Current.Response.Write("512:Error in Creating the Dimension, Attribute, Hierarchy, and MemberProperty Objects - GenerateDimension. Error Message -> " + ex.Message);
                System.Web.HttpContext.Current.Response.Write("<br/>");
                return null;
            }
        }// End GenerateDimension(Microsoft.AnalysisServices.Database objDatabase, Microsoft.AnalysisServices.DataSourceView objDataSourceView, string strTableName, string strTableKeyName)
   
        //d) Create a DataSourceView based on the created DataSet.
		//DataSourceView Objects
        static Microsoft.AnalysisServices.DataSourceView CreateDataSourceView(Microsoft.AnalysisServices.Database db, string strDataSourceName)
        {
            // Create the data source view
            Microsoft.AnalysisServices.DataSourceView dsv = db.DataSourceViews.FindByName(strDataSourceName);
            if ( dsv != null)
               dsv.Drop();
            dsv = db.DataSourceViews.Add(strDataSourceName);
            dsv.DataSourceID = strDataSourceName;
            dsv.Schema = new DataSet();
            dsv.Schema.Locale = System.Globalization.CultureInfo.CurrentCulture;
            // Open a connection to the data source
            OleDbConnection connection = new OleDbConnection(dsv.DataSource.ConnectionString);
            connection.Open();
            #region Create tables
            // Add the DimTime table
            AddTable(dsv, connection, "DimTime");
            AddComputedColumn(dsv, connection, "DimTime", "SimpleDate", "DATENAME(mm, FullDateAlternateKey) + ' ' + DATENAME(dd, FullDateAlternateKey) + ',' + ' ' + DATENAME(yy, FullDateAlternateKey)");
            AddComputedColumn(dsv, connection, "DimTime", "CalendarYearDesc", "'CY' + ' ' + CalendarYear");
            AddComputedColumn(dsv, connection, "DimTime", "CalendarSemesterDesc", "CASE WHEN CalendarSemester = 1 THEN 'H1'+' '+ 'CY' +' '+ CONVERT(CHAR (4), CalendarYear) ELSE 'H2'+' '+ 'CY' +' '+ CONVERT(CHAR (4), CalendarYear) END");
            AddComputedColumn(dsv, connection, "DimTime", "CalendarQuarterDesc", "'Q' + CONVERT(CHAR (1), CalendarQuarter) +' '+ 'CY' +' '+ CONVERT(CHAR (4), CalendarYear)");
            AddComputedColumn(dsv, connection, "DimTime", "MonthName", "EnglishMonthName+' '+ CONVERT(CHAR (4), CalendarYear)");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalYearDesc", "'FY' + ' ' + FiscalYear");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalSemesterDesc", "CASE WHEN FiscalSemester = 1 THEN 'H1'+' '+ 'FY' +' '+ CONVERT(CHAR (4), FiscalYear) ELSE 'H2'+' '+ 'FY' +' '+ CONVERT(CHAR (4), FiscalYear) END");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalQuarterDesc", "'Q' + CONVERT(CHAR (1), FiscalQuarter) +' '+ 'FY' +' '+ CONVERT(CHAR (4), FiscalYear)");
            AddComputedColumn(dsv, connection, "DimTime", "FiscalMonthNumberOfYear", "CASE WHEN MonthNumberOfYear = '1'  THEN CONVERT(int,'7') WHEN MonthNumberOfYear = '2'  THEN CONVERT(int,'8') WHEN MonthNumberOfYear = '3'  THEN CONVERT(int,'9') WHEN MonthNumberOfYear = '4'  THEN CONVERT(int,'10') WHEN MonthNumberOfYear = '5'  THEN CONVERT(int,'11') WHEN MonthNumberOfYear = '6'  THEN CONVERT(int,'12') WHEN MonthNumberOfYear = '7'  THEN CONVERT(int,'1') WHEN MonthNumberOfYear = '8'  THEN CONVERT(int,'2') WHEN MonthNumberOfYear = '9'  THEN CONVERT(int,'3') WHEN MonthNumberOfYear = '10' THEN CONVERT(int,'4') WHEN MonthNumberOfYear = '11' THEN CONVERT(int,'5') WHEN MonthNumberOfYear = '12' THEN CONVERT(int,'6') END");
            dsv.Update();
            // Add the DimGeography table
            AddTable(dsv, connection, "DimGeography");
            // Add the DimProductCategory table
            AddTable(dsv, connection, "DimProductCategory");
            // Add the DimProductSubcategory table
            AddTable(dsv, connection, "DimProductSubcategory");
            AddRelation(dsv, "DimProductSubcategory", "ProductCategoryKey", "DimProductCategory", "ProductCategoryKey");
            // Add the DimProduct table
            AddTable(dsv, connection, "DimProduct");
            AddComputedColumn(dsv, connection, "DimProduct", "ProductLineName", "CASE ProductLine WHEN 'M' THEN 'Mountain' WHEN 'R' THEN 'Road' WHEN 'S' THEN 'Accessory' WHEN 'T' THEN 'Touring' ELSE 'Components' END");
            AddRelation(dsv, "DimProduct", "ProductSubcategoryKey", "DimProductSubcategory", "ProductSubcategoryKey");
            dsv.Update();
            // Add the DimCustomer table
            AddTable(dsv, connection, "DimCustomer");
            AddComputedColumn(dsv, connection, "DimCustomer", "FullName", "CASE WHEN MiddleName IS NULL THEN FirstName + ' ' + LastName ELSE FirstName + ' ' + MiddleName + ' ' + LastName END");
            AddComputedColumn(dsv, connection, "DimCustomer", "GenderDesc", "CASE WHEN Gender = 'M' THEN 'Male' ELSE 'Female' END");
            AddComputedColumn(dsv, connection, "DimCustomer", "MaritalStatusDesc", "CASE WHEN MaritalStatus = 'S' THEN 'Single' ELSE 'Married' END");
            AddRelation(dsv, "DimCustomer", "GeographyKey", "DimGeography", "GeographyKey");
            // Add the DimReseller table
            AddTable(dsv, connection, "DimReseller");
            AddComputedColumn(dsv, connection, "DimReseller", "OrderFrequencyDesc", "CASE WHEN OrderFrequency = 'A' THEN 'Annual' WHEN OrderFrequency = 'S' THEN 'Bi-Annual' ELSE 'Quarterly' END");
            AddComputedColumn(dsv, connection, "DimReseller", "OrderMonthDesc", "CASE WHEN OrderMonth = '1' THEN 'January' WHEN OrderMonth = '2' THEN 'February' WHEN OrderMonth = '3' THEN 'March' WHEN OrderMonth = '4' THEN 'April' WHEN OrderMonth = '5' THEN 'May' WHEN OrderMonth = '6' THEN 'June' WHEN OrderMonth = '7' THEN 'July' WHEN OrderMonth = '8' THEN 'August' WHEN OrderMonth = '9' THEN 'September' WHEN OrderMonth = '10' THEN 'October' WHEN OrderMonth = '11' THEN 'November' WHEN OrderMonth = '12' THEN 'December' ELSE 'Never Ordered' END");
            // Add the DimCurrency table
            AddTable(dsv, connection, "DimCurrency");
            dsv.Update();
            // Add the DimSalesReason table
            AddTable(dsv, connection, "DimSalesReason");
            // Add the FactInternetSales table
            AddTable(dsv, connection, "FactInternetSales");
            AddRelation(dsv, "FactInternetSales", "ProductKey", "DimProduct", "ProductKey");
            AddRelation(dsv, "FactInternetSales", "CustomerKey", "DimCustomer", "CustomerKey");
            AddRelation(dsv, "FactInternetSales", "OrderDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactInternetSales", "ShipDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactInternetSales", "DueDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactInternetSales", "CurrencyKey", "DimCurrency", "CurrencyKey");
            dsv.Update();
            // Add the FactResellerSales table
            AddTable(dsv, connection, "FactResellerSales");
            AddRelation(dsv, "FactResellerSales", "ProductKey", "DimProduct", "ProductKey");
            AddRelation(dsv, "FactResellerSales", "ResellerKey", "DimReseller", "ResellerKey");
            AddRelation(dsv, "FactResellerSales", "OrderDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactResellerSales", "ShipDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactResellerSales", "DueDateKey", "DimTime", "TimeKey");
            AddRelation(dsv, "FactResellerSales", "CurrencyKey", "DimCurrency", "CurrencyKey");
            // Add the FactInternetSalesReason table
            AddTable(dsv, connection, "FactInternetSalesReason");
            AddCompositeRelation(dsv, "FactInternetSalesReason", "FactInternetSales", "SalesOrderNumber", "SalesOrderLineNumber");
            dsv.Update();
            // Add the FactCurrencyRate table
            AddTable(dsv, connection, "FactCurrencyRate");
            AddRelation(dsv, "FactCurrencyRate", "CurrencyKey", "DimCurrency", "CurrencyKey");
            AddRelation(dsv, "FactCurrencyRate", "TimeKey", "DimTime", "TimeKey");
            #endregion
            // Send the data source view definition to the server
            dsv.Update();
            return dsv;
        }
        static void AddTable(Microsoft.AnalysisServices.DataSourceView dsv, OleDbConnection connection, String tableName)
        {
            string strSelectText = "SELECT * FROM [dbo].[" + tableName + "] WHERE 1=0";
            OleDbDataAdapter adapter = new OleDbDataAdapter(strSelectText, connection);
            DataTable[] dataTables = adapter.FillSchema(dsv.Schema,SchemaType.Mapped, tableName);
            DataTable dataTable = dataTables[0];
            dataTable.ExtendedProperties.Add("TableType", "Table");
            dataTable.ExtendedProperties.Add("DbSchemaName", "dbo");
            dataTable.ExtendedProperties.Add("DbTableName", tableName);
            dataTable.ExtendedProperties.Add("FriendlyName", tableName);
            dataTable = null;
            dataTables = null;
            adapter = null;
        }
        static void AddComputedColumn(Microsoft.AnalysisServices.DataSourceView dsv, OleDbConnection connection, String tableName, String computedColumnName, String expression)
        {
            DataSet tmpDataSet = new DataSet();
            tmpDataSet.Locale = System.Globalization.CultureInfo.CurrentCulture;
            OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT ("
                + expression + ") AS [" + computedColumnName + "] FROM [dbo].["
                + tableName + "] WHERE 1=0", connection);
            DataTable[] dataTables = adapter.FillSchema(tmpDataSet,SchemaType.Mapped, tableName);
            DataTable dataTable = dataTables[0];
            DataColumn dataColumn = dataTable.Columns[computedColumnName];
            dataTable.Constraints.Clear();
            dataTable.Columns.Remove(dataColumn);
            dataColumn.ExtendedProperties.Add("DbColumnName", computedColumnName);
            dataColumn.ExtendedProperties.Add("ComputedColumnExpression",expression);
            dataColumn.ExtendedProperties.Add("IsLogical", "True");
            dsv.Schema.Tables[tableName].Columns.Add(dataColumn);
            dataColumn = null;
            dataTable = null;
            dataTables = null;
            adapter = null;
            tmpDataSet = null;
        }
        static void AddRelation(Microsoft.AnalysisServices.DataSourceView dsv, String fkTableName, String fkColumnName, String pkTableName, String pkColumnName)
        {
            DataColumn fkColumn = dsv.Schema.Tables[fkTableName].Columns[fkColumnName];
            DataColumn pkColumn = dsv.Schema.Tables[pkTableName].Columns[pkColumnName];
            dsv.Schema.Relations.Add("FK_" + fkTableName + "_"
                + fkColumnName, pkColumn, fkColumn, true);
        }
        static void AddCompositeRelation(Microsoft.AnalysisServices.DataSourceView dsv, String fkTableName, String pkTableName, String columnName1, String columnName2)
        {
            DataColumn[] fkColumns = new DataColumn[2];
            fkColumns[0] = dsv.Schema.Tables[fkTableName].Columns[columnName1];
            fkColumns[1] = dsv.Schema.Tables[fkTableName].Columns[columnName2];
            DataColumn[] pkColumns = new DataColumn[2];
            pkColumns[0] = dsv.Schema.Tables[pkTableName].Columns[columnName1];
            pkColumns[1] = dsv.Schema.Tables[pkTableName].Columns[columnName2];
            dsv.Schema.Relations.Add("FK_" + fkTableName + "_" + columnName1
                + "_" + columnName2, pkColumns, fkColumns, true);
        }	
		//http://technet.microsoft.com/en-us/library/ms345091.aspx
        static void CreateProductDimension(Microsoft.AnalysisServices.Database db, string datasourceName)
        {
            // Create the Product dimension
            Microsoft.AnalysisServices.Dimension dim = db.Dimensions.FindByName("Product");
            if ( dim != null)
               dim.Drop();
            dim = db.Dimensions.Add("Product");
            dim.Type = Microsoft.AnalysisServices.DimensionType.Products;
            dim.UnknownMember = Microsoft.AnalysisServices.UnknownMemberBehavior.Hidden;
            dim.AttributeAllMemberName = "All Products";
            dim.Source = new Microsoft.AnalysisServices.DataSourceViewBinding(datasourceName);
            dim.StorageMode = Microsoft.AnalysisServices.DimensionStorageMode.Molap;
            #region Create attributes
            Microsoft.AnalysisServices.DimensionAttribute attr;
            attr = dim.Attributes.Add("Product Name");
            attr.Usage = Microsoft.AnalysisServices.AttributeUsage.Key;
            attr.Type = Microsoft.AnalysisServices.AttributeType.Product;
            attr.OrderBy = Microsoft.AnalysisServices.OrderBy.Name;
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProduct", "ProductKey"));
            attr.NameColumn = CreateDataItem(db.DataSourceViews[0], "DimProduct", "EnglishProductName");
            attr = dim.Attributes.Add("Product Line");
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProduct", "ProductLine"));
            attr.NameColumn = CreateDataItem(db.DataSourceViews[0], "DimProduct", "ProductLineName");
            attr = dim.Attributes.Add("Model Name");
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProduct", "ModelName"));
            attr.AttributeRelationships.Add(new Microsoft.AnalysisServices.AttributeRelationship("Product Line"));
            attr.AttributeRelationships.Add(new Microsoft.AnalysisServices.AttributeRelationship("Subcategory"));
            attr = dim.Attributes.Add("Subcategory");
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProductSubcategory", "ProductSubcategoryKey"));
            attr.KeyColumns[0].NullProcessing = Microsoft.AnalysisServices.NullProcessing.UnknownMember;
            attr.NameColumn = CreateDataItem(db.DataSourceViews[0], "DimProductSubcategory", "EnglishProductSubcategoryName");
            attr.AttributeRelationships.Add(new Microsoft.AnalysisServices.AttributeRelationship("Category"));
            attr = dim.Attributes.Add("Category");
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProductCategory", "ProductCategoryKey"));
            attr.NameColumn = CreateDataItem(db.DataSourceViews[0], "DimProductCategory", "EnglishProductCategoryName");
            attr = dim.Attributes.Add("List Price");
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProduct", "ListPrice"));
            attr.AttributeHierarchyEnabled = false;
            attr = dim.Attributes.Add("Size");
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProduct", "Size"));
            attr.AttributeHierarchyEnabled = false;
            attr = dim.Attributes.Add("Weight");
            attr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "DimProduct", "Weight"));
            attr.AttributeHierarchyEnabled = false;
            #endregion
            #region Create hierarchies
            Microsoft.AnalysisServices.Hierarchy hier;
            hier = dim.Hierarchies.Add("Product Model Categories");
            hier.AllMemberName = "All Products";
            hier.Levels.Add("Category").SourceAttributeID = "Category";
            hier.Levels.Add("Subcategory").SourceAttributeID = "Subcategory";
            hier.Levels.Add("Model Name").SourceAttributeID = "Model Name";
            hier = dim.Hierarchies.Add("Product Categories");
            hier.AllMemberName = "All Products";
            hier.Levels.Add("Category").SourceAttributeID = "Category";
            hier.Levels.Add("Subcategory").SourceAttributeID = "Subcategory";
            hier.Levels.Add("Model Name").SourceAttributeID = "Product Name";
            hier = dim.Hierarchies.Add("Product Model Lines");
            hier.AllMemberName = "All Products";
            hier.Levels.Add("Subcategory").SourceAttributeID = "Product Line";
            hier.Levels.Add("Model Name").SourceAttributeID = "Model Name";
            #endregion
            dim.Update();
        }
        static Microsoft.AnalysisServices.DataItem CreateDataItem(Microsoft.AnalysisServices.DataSourceView dsv, string tableName, string columnName)
        {
            DataTable dataTable = ((Microsoft.AnalysisServices.DataSourceView)dsv).Schema.Tables[tableName];
            DataColumn dataColumn = dataTable.Columns[columnName];
            return new Microsoft.AnalysisServices.DataItem(tableName, columnName,
                Microsoft.AnalysisServices.OleDbTypeConverter.GetRestrictedOleDbType(dataColumn.DataType));
        }
        static void UpdateAllDimensions(Microsoft.AnalysisServices.Database db)
        {
            foreach (Microsoft.AnalysisServices.Dimension dim in db.Dimensions)
                dim.Process(Microsoft.AnalysisServices.ProcessType.ProcessUpdate);
        }
        public void CreateAdventureWorksCube(Microsoft.AnalysisServices.Database db, string datasourceName)
        {
            // Create the Adventure Works cube
            Microsoft.AnalysisServices.Cube cube = db.Cubes.FindByName("Adventure Works");
            if ( cube != null)
               cube.Drop();
            db.Cubes.Add("Adventure Works");
            cube.DefaultMeasure = "[Reseller Sales Amount]";
            cube.Source = new Microsoft.AnalysisServices.DataSourceViewBinding(datasourceName);
            cube.StorageMode = Microsoft.AnalysisServices.StorageMode.Molap;
            #region Create cube dimensions
            Microsoft.AnalysisServices.Dimension dim;
            dim = db.Dimensions.GetByName("Date");
            cube.Dimensions.Add(dim.ID, "Date", "Order Date Key - Dim Time");
            cube.Dimensions.Add(dim.ID, "Ship Date","Ship Date Key - Dim Time");
            cube.Dimensions.Add(dim.ID, "Delivery Date","Delivery Date Key - Dim Time");
            dim = db.Dimensions.GetByName("Customer");
            cube.Dimensions.Add(dim.ID);
            dim = db.Dimensions.GetByName("Reseller");
            cube.Dimensions.Add(dim.ID);
            #endregion
            #region Create measure groups
            //CreateSalesReasonsMeasureGroup(cube);
            CreateInternetSalesMeasureGroup(cube);
            //CreateResellerSalesMeasureGroup(cube);
            //CreateCustomersMeasureGroup(cube);
            //CreateCurrencyRatesMeasureGroup(cube);
            #endregion
            cube.Update(Microsoft.AnalysisServices.UpdateOptions.ExpandFull);
        }
        //Processing a Cube
		//foreach (Cube cube in db.Cubes)
                //cube.Process(ProcessType.ProcessFull);
        //}
        public void CreateInternetSalesMeasureGroup(Microsoft.AnalysisServices.Cube cube)
        {
        // Create the Internet Sales measure group
            Microsoft.AnalysisServices.Database db = cube.Parent;
            Microsoft.AnalysisServices.MeasureGroup mg = cube.MeasureGroups.FindByName("Internet Sales");
            if ( mg != null)
               mg.Drop();
            mg = cube.MeasureGroups.Add("Internet Sales");
            mg.StorageMode = Microsoft.AnalysisServices.StorageMode.Molap;
            mg.ProcessingMode = Microsoft.AnalysisServices.ProcessingMode.LazyAggregations;
            mg.Type = Microsoft.AnalysisServices.MeasureGroupType.Sales;
            #region Create measures
            Microsoft.AnalysisServices.Measure meas;
            meas = mg.Measures.Add("Internet Sales Amount");
            meas.AggregateFunction = Microsoft.AnalysisServices.AggregationFunction.Sum;
            meas.FormatString = "Currency";
            meas.Source = CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "SalesAmount");
            meas = mg.Measures.Add("Internet Order Quantity");
            meas.AggregateFunction = Microsoft.AnalysisServices.AggregationFunction.Sum;
            meas.FormatString = "#,#";
            meas.Source = CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "OrderQuantity");
            meas = mg.Measures.Add("Internet Unit Price");
            meas.AggregateFunction = Microsoft.AnalysisServices.AggregationFunction.Sum;
            meas.FormatString = "Currency";
            meas.Visible = false;
            meas.Source = CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "UnitPrice");
            meas = mg.Measures.Add("Internet Total Product Cost");
            meas.AggregateFunction = Microsoft.AnalysisServices.AggregationFunction.Sum;
            //meas.MeasureExpression = "[Internet Total Product Cost] * [Average Rate]";
            meas.FormatString = "Currency";
            meas.Source = CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "TotalProductCost");
            meas = mg.Measures.Add("Internet Order Count");
            meas.AggregateFunction = Microsoft.AnalysisServices.AggregationFunction.Count;
            meas.FormatString = "#,#";
            meas.Source = CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "ProductKey");
            #endregion
            #region Create measure group dimensions
            Microsoft.AnalysisServices.CubeDimension cubeDim;
            Microsoft.AnalysisServices.RegularMeasureGroupDimension regMgDim;
            Microsoft.AnalysisServices.ManyToManyMeasureGroupDimension mmMgDim;
            Microsoft.AnalysisServices.MeasureGroupAttribute mgAttr;
            //   Mapping dimension and key column from fact table
            //      > select dimension and add it to the measure group
            cubeDim = cube.Dimensions.GetByName("Date");
            regMgDim = new Microsoft.AnalysisServices.RegularMeasureGroupDimension(cubeDim.ID);
            mg.Dimensions.Add(regMgDim);
            //      > add key column from dimension and map it with 
            //        the surrogate key in the fact table
            mgAttr = regMgDim.Attributes.Add(cubeDim.Dimension.Attributes.GetByName("Date").ID);   // this is dimension key column
            mgAttr.Type = Microsoft.AnalysisServices.MeasureGroupAttributeType.Granularity;
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "OrderDateKey"));   // this surrogate key in fact table
            cubeDim = cube.Dimensions.GetByName("Ship Date");
            regMgDim = new Microsoft.AnalysisServices.RegularMeasureGroupDimension(cubeDim.ID);
            mg.Dimensions.Add(regMgDim);
            mgAttr = regMgDim.Attributes.Add(cubeDim.Dimension.Attributes.GetByName("Date").ID);
            mgAttr.Type = Microsoft.AnalysisServices.MeasureGroupAttributeType.Granularity;
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "ShipDateKey"));
            cubeDim = cube.Dimensions.GetByName("Delivery Date");
            regMgDim = new Microsoft.AnalysisServices.RegularMeasureGroupDimension(cubeDim.ID);
            mg.Dimensions.Add(regMgDim);
            mgAttr = regMgDim.Attributes.Add(cubeDim.Dimension.Attributes.GetByName("Date").ID);
            mgAttr.Type = Microsoft.AnalysisServices.MeasureGroupAttributeType.Granularity;
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "DueDateKey"));
            cubeDim = cube.Dimensions.GetByName("Customer");
            regMgDim = new Microsoft.AnalysisServices.RegularMeasureGroupDimension(cubeDim.ID);
            mg.Dimensions.Add(regMgDim);
            mgAttr = regMgDim.Attributes.Add(cubeDim.Dimension.Attributes.GetByName("Full Name").ID);
            mgAttr.Type = Microsoft.AnalysisServices.MeasureGroupAttributeType.Granularity;
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "CustomerKey"));
            cubeDim = cube.Dimensions.GetByName("Product");
            regMgDim = new Microsoft.AnalysisServices.RegularMeasureGroupDimension(cubeDim.ID);
            mg.Dimensions.Add(regMgDim);
            mgAttr = regMgDim.Attributes.Add(cubeDim.Dimension.Attributes.GetByName("Product Name").ID);
            mgAttr.Type = Microsoft.AnalysisServices.MeasureGroupAttributeType.Granularity;
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "ProductKey"));
            cubeDim = cube.Dimensions.GetByName("Source Currency");
            regMgDim = new Microsoft.AnalysisServices.RegularMeasureGroupDimension(cubeDim.ID);
            mg.Dimensions.Add(regMgDim);
            mgAttr = regMgDim.Attributes.Add(cubeDim.Dimension.Attributes.GetByName("Currency").ID);
            mgAttr.Type = Microsoft.AnalysisServices.MeasureGroupAttributeType.Granularity;
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "CurrencyKey"));
            cubeDim = cube.Dimensions.GetByName("Sales Reason");
            mmMgDim = new Microsoft.AnalysisServices.ManyToManyMeasureGroupDimension();
            mmMgDim.CubeDimensionID = cubeDim.ID;
            mmMgDim.MeasureGroupID = cube.MeasureGroups.GetByName("Sales Reasons").ID;
            mg.Dimensions.Add(mmMgDim);
            cubeDim = cube.Dimensions.GetByName("Internet Sales Order Details");
            regMgDim = new Microsoft.AnalysisServices.RegularMeasureGroupDimension(cubeDim.ID);
            mg.Dimensions.Add(regMgDim);
            mgAttr = regMgDim.Attributes.Add(cubeDim.Dimension.Attributes.GetByName("Sales Order Key").ID);
            mgAttr.Type = Microsoft.AnalysisServices.MeasureGroupAttributeType.Granularity;
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "SalesOrderNumber"));
            mgAttr.KeyColumns.Add(CreateDataItem(db.DataSourceViews[0], "FactInternetSales", "SalesOrderLineNumber"));
            #endregion
            #region Create partitions
            CreateInternetSalesMeasureGroupPartitions(mg);
            #endregion
        }
        static void FullProcessAllMeasureGroups(Microsoft.AnalysisServices.Cube cube)
        {
            foreach (Microsoft.AnalysisServices.MeasureGroup mg in cube.MeasureGroups)
                mg.Process(Microsoft.AnalysisServices.ProcessType.ProcessFull);
        }
        //http://www.mssqltips.com/sqlservertip/2796/create-sql-server-analysis-services-partitions-using-amo/
        public void CreateInternetSalesMeasureGroupPartitions(Microsoft.AnalysisServices.MeasureGroup mg)
        {
         
        }
        static void FullProcessAllPartitions(Microsoft.AnalysisServices.MeasureGroup mg)
        {
            foreach (Microsoft.AnalysisServices.Partition part in mg.Partitions)
                part.Process(Microsoft.AnalysisServices.ProcessType.ProcessFull);
        }
        static void MergeAllPartitions(Microsoft.AnalysisServices.MeasureGroup mg)
        {
            if (mg.Partitions.Count > 1)
            {
                Microsoft.AnalysisServices.Partition[] partArray = new Microsoft.AnalysisServices.Partition[mg.Partitions.Count - 1];
                for (int i = 1; i < mg.Partitions.Count; i++)
                    partArray[i - 1] = mg.Partitions[i];
                mg.Partitions[0].Merge(partArray);
                //To have last changes in the server reflected in AMO
                mg.Refresh();
            }
		}
        static public String DesignAggregationsOnPartitions(Microsoft.AnalysisServices.MeasureGroup mg, double optimizationWanted, double maxStorageBytes)
        {
            double optimization = 0;
            double storage = 0;
            long aggCount = 0;
            bool finished = false;
            Microsoft.AnalysisServices.AggregationDesign ad = null;
            String aggDesignName;
            String AggregationsDesigned = "";
            aggDesignName = mg.AggregationPrefix + "_" + mg.Name;
            ad = mg.AggregationDesigns.Add();
            ad.Name = aggDesignName;
            ad.InitializeDesign();
            while ((!finished) && (optimization < optimizationWanted) && (storage < maxStorageBytes))
            {
                ad.DesignAggregations(out optimization, out storage, out aggCount, out finished);
            }
            ad.FinalizeDesign();
            foreach (Microsoft.AnalysisServices.Partition part in mg.Partitions)
            {
                part.AggregationDesignID = ad.ID;
                AggregationsDesigned += aggDesignName + " = " + aggCount.ToString() + " aggregations designed\r\n\tOptimization: " + optimization.ToString() + "/" + optimizationWanted.ToString() + "\n\r\tStorage: " + storage.ToString() + "/" + maxStorageBytes.ToString() + " ]\n\r";
             }
             return AggregationsDesigned;
		}

Open in new window

I have made one further change:
Not sure what to try next, still get error:
The dbo cube either does not exist or has not been processed.
//d) Create a DataSourceView based on the created DataSet.
            //static Microsoft.AnalysisServices.DataSourceView CreateDataSourceView(Microsoft.AnalysisServices.Database db, string strDataSourceName)
            //private static object CreateDataSourceView(Microsoft.AnalysisServices.Database objDatabase, Microsoft.AnalysisServices.RelationalDataSource objDataSource, DataSet objDataSet, string strCubeDataSourceViewName)
            objDataSourceView = (Microsoft.AnalysisServices.DataSourceView)CreateDataSourceView(db, ds.Name);// This line changed
            
           
            System.Web.HttpContext.Current.Response.Write("277:CreateDataSourceView(db, strDataSourceName)<br/>");

Open in new window

ASKER CERTIFIED SOLUTION
Avatar of Meir Rivkin
Meir Rivkin
Flag of Israel image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial