getting error + ServerDatabaseFactory.Create("dbserver") 'ServerDatabaseFactory.Create("dbserver")' threw an exception of type 'Microsoft.Practices.ServiceLocation.ActivationException' Microsoft.Practices.EnterpriseLibrary.Data.Database

Dec 22, 2011 at 11:18 AM

Hi

 

I recently migrated application from v1.0 to v5.0 . When am running am getting "

The type Database cannot be constructed. You must configure the container to supply this value."

So I do tracing and while at quickwatch window  found below error at this line 

ServerDatabaseFactory.Create("dbserver")

 Error at quickwatch:

+  ServerDatabaseFactory.Create("dbserver") 'ServerDatabaseFactory.Create("dbserver")' threw an exception of type 'Microsoft.Practices.ServiceLocation.ActivationException' Microsoft.Practices.EnterpriseLibrary.Data.Database {Microsoft.Practices.ServiceLocation.ActivationException}

Please find the code and web.config files given below:

code:

 
protected DatabaseProviderFactory ServerDatabaseFactory;
            protected string DatabaseServer;
            protected int userSecurityId;
            protected WindowsIdentity usingIdentity;


            // Deprecated in favor of security
            //         protected DASDalDatabase(string serverConfigSection) : this( serverConfigSection, WindowsIdentity.GetCurrent() )
            //         {
            //         }            

this is used to call the appsettings path
            protected DASDalDatabase(string serverConfigSection, System.Security.Principal.WindowsIdentity windowsIdentity)
            {
                try
                {
                    string pagDBConfigFile;
                    #region Unused-Commented code
                    // v-pchett : Added code to impersonate the actual user to retreive the login id

                    //if (windowsIdentity == null)
                    //{
                    //    WindowsPrincipal wp = (WindowsPrincipal)Thread.CurrentPrincipal;
                    //    WindowsIdentity wi = (WindowsIdentity)wp.Identity;
                    //    WindowsImpersonationContext wc = wi.Impersonate();

                    //    // Get the current logged on user User
                    //    this.usingIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();

                    //    // Undo the impersonation							
                    //    wc.Undo();
                    //}
                    //else
                    //{
                    //    usingIdentity = windowsIdentity;

                    //}
                    #endregion


                    // We need to locate this file. These pag config files don't seem to be quite compatible with
                    // V2 of the framework. Shortest path was to use a third file rather than figure out what was 
                    // wrong and port the PAG configuration application blocks. This will find the file (as long as it's
                    // called pag.config. "pag" is located in app.cofig.

                    bool found = false;
                    //					string[] keys = System.Configuration.ConfigurationSettings.AppSettings.AllKeys;
                    string[] keys = System.Configuration.ConfigurationManager.AppSettings.AllKeys;
                    foreach (string s in keys)
                    {
                        if (s == "pathPag")
                        {
                            found = true;
                            break;
                        }
                    }

                    if (found)
                    {
                        //	pagDBConfigFile = System.Configuration.ConfigurationSettings.AppSettings["pathPag"];
                        pagDBConfigFile = System.Configuration.ConfigurationManager.AppSettings["pathPag"];
                    }
                    else
                    {
                        if (System.Web.HttpContext.Current != null)
                        {
                            pagDBConfigFile = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
                        }
                        else
                        {
                            // assume its as winform
                            pagDBConfigFile = Path.GetDirectoryName(this.GetType().Module.FullyQualifiedName);
                        }
                    }

                    if (pagDBConfigFile.ToCharArray()[pagDBConfigFile.Length - 1] != '\\') pagDBConfigFile += "\\";

                    //pagDBConfigFile += System.Configuration.ConfigurationSettings.AppSettings["pag"];
                    pagDBConfigFile += System.Configuration.ConfigurationManager.AppSettings["pag"];
                   
                    string mapconfigfile = @pagDBConfigFile;
                    // This database factory helps us create a connection to a database that doesn't happen to be the default
                    // database. This plus the string (next line) locate it and build the connection string.
                    //kiran-19/12/2011
                    //  ServerDatabaseFactory = new PAG.Data.DatabaseProviderFactory(new ConfigurationContext(pagDBConfigFile));

                   // ServerDatabaseFactory = new PAG.Data.DatabaseProviderFactory(new FileConfigurationSource(mapconfigfile,true));
                    IConfigurationSource config;
                    config = new FileConfigurationSource(mapconfigfile);
                    ServerDatabaseFactory = new PAG.Data.DatabaseProviderFactory(config);
                    // This refers to a string in the pag.config file which identifies a section that describes the server connection.
                    // It is used along with the database factory above to create a correct connection to the server..
                    
                    DatabaseServer = serverConfigSection;
                  
                }
                catch (System.Exception ex)
                {
                    throw (new DASException("System Exception", ex));
                }
            }

Database is initiated in this method, Error is getting at return parameter here.

  public SqlDatabase GetADatabase()
            {
                try
                {
                    //kiran-19/12/2011
                    //return ((PAG.Data.Sql.SqlDatabase)ServerDatabaseFactory.CreateDatabase(DatabaseServer));
                    Database db = ServerDatabaseFactory.CreateDefault();
                    
                     // error is getting here.
                    return (PAG.Data.Sql.SqlDatabase)ServerDatabaseFactory.Create("dbserver");
           
                }
                catch (System.Exception ex)
                {
                    throw (new DASException("System Exception", ex));
                }
            }

Please find the configuration files here:

Pag.config

<configuration>
  <configSections>
    <section name="enterpriselibrary.configurationSettings" type="Microsoft.Practices.EnterpriseLibrary.Configuration.ConfigurationManagerSectionHandler, Microsoft.Practices.EnterpriseLibrary.Configuration" />
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="true" />
  </configSections>
  <enterpriselibrary.configurationSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" defaultSection="" applicationName="Application" xmlns="http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/configuration">

    <configurationSections>
      <configurationSection name="dataConfiguration" encrypt="false">
        <storageProvider xsi:type="XmlFileStorageProviderData" name="XML File Storage Provider" path="E:\BI_FeedStore\Legacy\VSS-EDS\Web Services - DAS\Web Services - Das Version1\UI\DASWEB\dataConfiguration.config">
        <!--<storageProvider xsi:type="XmlFileStorageProviderData" name="XML File Storage Provider" path="E:\BI_FeedStore\Legacy\VSS-EDS\Web Services - DAS\Web Services - Das Version1\UI\DASWEB\web.config">-->
        </storageProvider>
        <dataTransformer xsi:type="XmlSerializerTransformerData" name="Xml Serializer Transformer">
          <includeTypes />
        </dataTransformer>
      </configurationSection>
    </configurationSections>
  </enterpriselibrary.configurationSettings>
</configuration>

 Dataconfiguration.config

<?xml version="1.0" encoding="utf-8"?>
<dataConfiguration defaultDatabase="DASDbConnectionString">
  <xmlSerializerSection type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data">
    <enterpriseLibrary.databaseSettings xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" defaultInstance="DataAccessQuickStart" xmlns="http://www.microsoft.com/practices/enterpriselibrary/08-31-2004/data">
      <databaseTypes>
        <databaseType name="Sql Server" type="Microsoft.Practices.EnterpriseLibrary.Data.Sql.SqlDatabase, Microsoft.Practices.EnterpriseLibrary.Data" />
      </databaseTypes>
      <instances >
        <instance  name="dbserver" type="Sql Server"  connectionString="DASDbConnectionString" />
      </instances>
      <connectionStrings>
        <connectionString name="DASDbConnectionString">
          <parameters>
            <parameter name="database" value="DASDB" isSensitive="false" />
            <parameter name="Integrated Security" value="true" isSensitive="false"/>
            <parameter name="server" value="svkiran" isSensitive="false" />
            <parameter name="providerName" value=" System.Data.SqlClient"/>
            </parameters>
        </connectionString>
       </connectionStrings>
      
    </enterpriseLibrary.databaseSettings>
  </xmlSerializerSection>
</dataConfiguration>

Web.config appsettings

<appSettings>
		<add key="xmlNavFile" value="\Default_Files\Navigation.xml"/>
		<!-- setting it to true will display the yellow error page in case of error. false - displays error page with custom message-->
		<add key="DisplayExceptionToUser" value="false"/>
		<!--<add key="pag" value="pag.config"/>-->
    <add key="pag" value="pag.config"/>
		<add key="pathPag" value="E:\BI_FeedStore\Legacy\VSS-EDS\Web Services - DAS\Web Services - Das Version1\UI\DASWEB"/>
		<!-- 1 for true and 0 for false-->
		<add key="DebugMode" value="0"/>
		<add key="XslPath" value="E:\BI_FeedStore\Legacy\VSS-EDS\Web Services - DAS\Web Services - Das Version1\UI\XSLT\"/>
		<add key="TimerLoopDurationInMinutes" value="720"/>
		<add key="LogLevel" value="trace"/>
		<add key="PersistenceConnStr" value="Data Source=DEVEDS/Distribution;Initial Catalog=SqlPersistenceService;Integrated Security=True"/>
		<add key="EmailFrom" value="ebisops"/>
		<add key="MSAppsResetAnswersList" value="6,7,8,9,10,11,46"/>
		<add key="DomainList" value="AFRICA,CORP,EUROPE,FAREAST,MIDDLEEAST,MSNBCI,NORTHAMERICA,NTDEV,PARTNERS,PARTTEST,REDMOND,SEGROUP,SOUTHAMERICA,SOUTHPACIFIC,SYS-NTGROUP,WINCHILD,WINGROUP,XRED"/>
	</appSettings>


 So can you please provide me the solution how to resolve this errors.

 

Thanks and Regards

Kiran

 

 

Dec 22, 2011 at 2:59 PM

Thanks for the details.

As I mentioned in the previous thread, You are still using the version 1.1 configuration.

Enterprise Library configuration had a major change between version 1 and version 2 so you will need to migrate the configuration.  I would recommend reading the Enterprise Library 5.0 Developers Guide especially chapter 2 on Data Access and Appendix D on configuration.

Since you are already explicitly reading in configuration I would recommend loading the dataConfiguration.config directly:

            string mapConfigFile = "dataConfiguration.config";
            IConfigurationSource config;
            config = new FileConfigurationSource(mapConfigFile);
            var ServerDatabaseFactory = new PAG.Data.DatabaseProviderFactory(config);

            var db = ServerDatabaseFactory.CreateDefault();

The dataConfiguration.config file would look something like this:

<configuration>
  <configSections>
    <section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
  </configSections>
  <dataConfiguration defaultDatabase="dbserver" />
  <connectionStrings>
    <add name="dbserver" connectionString="data source=svkiran;Integrated Security=True;Database=DASDB;"
      providerName="System.Data.SqlClient" />
  </connectionStrings>
</configuration>

 If you want to hook into app.config or web.config then you could add FileConfigurationSource there:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <configSections>
        <section name="enterpriseLibrary.ConfigurationSource" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ConfigurationSourceSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true" />
    </configSections>
    <enterpriseLibrary.ConfigurationSource selectedSource="File-based Configuration Source"
        parentSource="File-based Configuration Source">
        <sources>
            <add name="File-based Configuration Source" type="Microsoft.Practices.EnterpriseLibrary.Common.Configuration.FileConfigurationSource, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
                filePath="C:\configdir\dataConfiguration.config" />
        </sources>
        <redirectSections>
            <add sourceName="File-based Configuration Source" name="dataConfiguration" />
        </redirectSections>
    </enterpriseLibrary.ConfigurationSource>
</configuration>

If you did that then the confiuration would be automatically loaded and you could retrieve the database with one line:

            var db = EnterpriseLibraryContainer.Current.GetInstance<Database>();

--
Randy Levy
Enterprise Library support engineer
entlib.support@live.com