using System;
using System.Collections.Generic;
using System.Text;
using Microsoft.AnalysisServices.AdomdServer;
using Microsoft.AnalysisServices;


namespace ASSprocs
{
    public class DataSourceHelpers
    {

        [SafeToPrepare(true)]
        public void CreateDataSource(string DataSourceName, string ConnectionString,
            string sImpersonationMode, string Account, string Password)
        {
            if (Context.ExecuteForPrepare)
                return;

            // Connect to the calling session
            Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
            svr.Connect("*");

            // Get the current database
            Database db = svr.Databases.GetByName(Context.CurrentDatabaseName);

            // Create a new datasource and set connection string
            DataSource ds = db.DataSources.Add(DataSourceName, DataSourceName);
            ds.ConnectionString = ConnectionString;

            // Set the impersonation info
            bool FoundMode = false;
            foreach (ImpersonationMode mode in Enum.GetValues(typeof(ImpersonationMode)))
            {
                if (mode.ToString() == sImpersonationMode)
                {
                    FoundMode = true;
                    ds.ImpersonationInfo = new ImpersonationInfo(mode, Account, Password);
                    break;
                }
            }
            if (!FoundMode)
                throw (new SystemException("Invalid Impersonation Mode"));

            // Update the server with the new datasource
            ds.Update();    
        }

        [SafeToPrepare(true)]
        public void DropDataSource(string DataSourceName)
        {
            if (Context.ExecuteForPrepare)
                return;

            // Connect to the calling session
            Microsoft.AnalysisServices.Server svr = new Microsoft.AnalysisServices.Server();
            svr.Connect("*");

            // Get the current database
            Database db = svr.Databases.GetByName(Context.CurrentDatabaseName);


            // Find the datasource and remove it
            DataSource ds = db.DataSources.FindByName(DataSourceName);
            if (ds != null)
                ds.Drop();
        }
    }
}
