Unity Configuration and Same Assembly - c#

I'm currently getting an error trying to resolve my IDataAccess class.
The value of the property 'type' cannot be parsed. The error is: Could not load file or assembly 'TestProject' or one of its dependencies. The system cannot find the file specified.
(C:\Source\TestIoC\src\TestIoC\TestProject\bin\Debug\TestProject.vshost.exe.config line 14)
This is inside a WPF Application project.
What is the correct syntax to refer to the Assembly you are currently in? is there a way to do this? I know in a larger solution I would be pulling Types from seperate assemblies so this might not be an issue. But what is the right way to do this for a small self-contained test project. Note: I'm only interested in doing the XML config at this time, not the C# (in code) config.
UPDATE: see all comments
My XML config:
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity>
<typeAliases>
<!-- Lifetime manager types -->
<typeAlias alias="singleton" type="Microsoft.Practices.Unity.ContainerControlledLifetimeManager, Microsoft.Practices.Unity" />
<typeAlias alias="external" type="Microsoft.Practices.Unity.ExternallyControlledLifetimeManager, Microsoft.Practices.Unity" />
<typeAlias alias="IDataAccess" type="TestProject.IDataAccess, TestProject" />
<typeAlias alias="DataAccess" type="TestProject.DataAccess, TestProject" />
</typeAliases>
<containers>
<container name="Services">
<types>
<type type="IDataAccess" mapTo="DataAccess" />
</types>
</container>
</containers>
</unity>
</configuration>

In unity 5.7
The section line should be like this
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection,Unity.Configuration" />

This looks fine. Are you sure your assembly name is correct? Check the project preferences to make sure the name of your assembly is correct:
Right click your project and click Properties
Click on the Application tab on the left
Look at the value of the "Assembly Name" field.
Sometimes if you've renamed your project, this field will still be the old value.
It's possible that this is not the issue at all, but it is the simplest thing to check. If you find that this is not the issue, reply to this and I'll post any other ideas I have.
Also, you might consider posting your sample as a .zip file so we can take a look at it.

I just had the same issue. this works for me :
Turn "Copy local" to true in the properties of Microsoft.Practices.Unity.
You should also add a reference to Microsoft.Practices.ObjectBuilder2 (Microsoft.Practices.Unity depends of it)

Related

sonar-dotnet-shared-library does not compile due non-existing dependencies, How to make it work?

I am trying to compile in my machine the sonar-csharp-plugin, but in the pom.xml file there is two dependencies that do not exist in the Maven public repositories:
<dependency>
<groupId>org.sonarsource.dotnet</groupId>
<artifactId>sonar-dotnet-tests-library</artifactId>
<version>1.5.0.393</version>
</dependency>
<dependency>
<groupId>org.sonarsource.dotnet</groupId>
<artifactId>sonar-dotnet-shared-library</artifactId>
<version>1.0.1.138</version>
</dependency>
I download the code of both projects and try to compile them and generate the .jar files for each one.
Trying to compile sonar-dotnet-shared-library-1.0.1.138, I installed the https://www.nuget.org/packages/SonarAnalyzer.CSharp/1.20.0 package and proceed to install it in my maven local repository then when I compile sonar-dotnet-shared-library-1.0.1.138 I get :
[ERROR] Failed to execute goal org.apache.maven.plugins:maven-antrun-plugin:1.7:run (unzip-nuget) on project sonar-dotnet-shared-library: An Ant Build Exception has occured: C:\Temp\sonar-dotnet-shared-library-1.0.1.138\target\analyzer\SonarAnalyzer.Scanner\protobuf does not exist.
[ERROR] around Ant part ...<copy todir="src/main/protobuf">... # 8:35 in C:\Temp\sonar-dotnet-shared-library-1.0.1.138\target\antrun\build-main.xml
I think I am in Maven hell.
What should I do to build the code from the latest release sonar-csharp-plugin??
Edit: when I installed the SonarAnalyzer I used
mvn install:install-file -DgroupId=org.sonarsource.dotnet -DartifactId=SonarAnalyzer.Scanner -Dversion=1.20.0 -Dpackaging=nupkg -Dfile="C:\Temp\SonarAnalyzer.CSharp.1.20.0-RC1.nupkg"
I disable the tasks that generate the error, now the java code start its compilation but I get errors related to
import org.sonarsource.dotnet.protobuf.SonarAnalyzer;
I think that it is a reference to the SonarAnalyzer Dll's, but neither Eclipse nor Maven are able to find it (protobuf is missing)
Edit2:
the POM.XML includes these tasks:
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-antrun-plugin</artifactId>
<executions>
<execution>
<id>unzip-nuget</id>
<phase>validate</phase>
<configuration>
<exportAntProperties>true</exportAntProperties>
<tasks>
<unzip src="${sonarAnalyzer.workDirectory}/SonarAnalyzer.Scanner.nupkg" dest="${sonarAnalyzer.workDirectory}/SonarAnalyzer.Scanner/" />
<delete>
<fileset dir="src/main/protobuf" excludes=".gitignore"></fileset>
</delete>
<copy todir="src/main/protobuf">
<fileset dir="${sonarAnalyzer.workDirectory}/SonarAnalyzer.Scanner/protobuf">
<include name="*.proto"/>
</fileset>
</copy>
</tasks>
</configuration>
<goals>
<goal>run</goal>
</goals>
</execution>
<execution>
<id>compile-protobuf-sources</id>
<phase>generate-sources</phase>
<goals>
<goal>run</goal>
</goals>
<configuration>
<target>
<fileset id="fileset" dir="${project.basedir}/src/main/protobuf">
<include name="*.proto" />
</fileset>
<pathconvert refid="fileset" property="protos" pathsep=" " />
<mkdir dir="${project.build.directory}/generated-sources/protobuf" />
<chmod file="${protobuf.compiler}" perm="u+x" />
<exec failonerror="true" executable="${protobuf.compiler}">
<arg value="proto_path=${project.basedir}/src/main/protobuf" />
<arg value="java_out=${project.build.directory}/generated-sources/protobuf" />
<arg line="${protos}" />
</exec>
</target>
</configuration>
</execution>
</executions>
As I understand, in the SonarAnalyzer.Scanner.nupkg should be a protobuf folder, and the content of that folder is copied to src/main/protobuf.....well the SonarAnalyzer.Scanner.nupkg downloaded from Nuget does not contain that folder....so....
guys from Sonar...... Where do I get that nupkg?
I had the same problem, I've found the solution on this thread from SonarQube's Google group.
You need to fetch the missing artifacts from sonarsource's Artifactory server. As suggested by Duarte Meneses, you can add these lines to [user_home]/.m2/settings.xml :
<profiles>
<profile>
<id>sonarsource-repo</id>
<activation>
<property>
<name>!skip-sonarsource-repo</name>
</property>
</activation>
<repositories>
<repository>
<id>sonarsource</id>
<name>SonarSource Central Repository</name>
<url>https://repox.sonarsource.com/sonarsource</url>
<releases>
<enabled>true</enabled>
<updatePolicy>interval:60</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</repository>
</repositories>
<pluginRepositories>
<pluginRepository>
<id>sonarsource</id>
<name>SonarSource Central Repository</name>
<url>https://repox.sonarsource.com/sonarsource</url>
<releases>
<enabled>true</enabled>
<!-- no need to always check if new versions are available when
executing a maven plugin without specifying the version -->
<updatePolicy>interval:60</updatePolicy>
<checksumPolicy>fail</checksumPolicy>
</releases>
<snapshots>
<enabled>false</enabled>
<updatePolicy>never</updatePolicy>
</snapshots>
</pluginRepository>
</pluginRepositories>
</profile>
</profiles>
I used the above configuration.I also had mirrors declared in my settings.xml, so I had to exclude sonarsource from the mirrored repositories :
<mirrors>
<mirror>
<id>nexus</id>
<mirrorOf>*,!sonarsource</mirrorOf>
<url>http://ci-server/nexus/content/groups/public</url>
</mirror>
</mirrors>
Of course there are other ways to achieve the same result, for example by declaring a proxy repository in your company's Nexus server.
With this configuration, I built SonarQube successfully.

Castle Windsor / ActiveRecord / NHibernate: How to intercept/modify connection string

I have consolidated the connection string information for a number of C# .NET solutions that are in my possession. Previously, each project was storing its connection string in its own format, requiring me to modify several files for each installation of the software.
Only one remaining solution is giving me trouble. This particular solution uses Castle Windsor 2.0, ActiveRecord 2.0 and NHibernate 2.1. The code reads its configuration from an XML file. I wish to remove the connection string from the config file and set it programmatically in the code.
Here is the relevant section of code that initiates Windsor:
windsorContainer = new WindsorContainer(new XmlInterpreter(xmlFileName));
windsorContainer.Resolve<IWindsorConfigurator>().Configure(windsorContainer);
logger = windsorContainer.Resolve<ILogger>();
Here are the contents of the XML file:
<?xml version="1.0"?>
<configuration>
<properties>
<connectionString>Server=*****;Database=*****;User Id=*****;Password=*****</connectionString>
</properties>
<facilities>
<facility id="logging" type="Castle.Facilities.Logging.LoggingFacility, Castle.Facilities.Logging" loggingApi="log4net" configFile="Configs/log4net.config" />
<facility id="atm" type="Castle.Facilities.AutomaticTransactionManagement.TransactionFacility, Castle.Facilities.AutomaticTransactionManagement" />
<facility id="arfacility" type="Castle.Facilities.ActiveRecordIntegration.ActiveRecordFacility, Castle.Facilities.ActiveRecordIntegration" isDebug="false" isWeb="false">
<!-- Configure the namespaces for the models using Active Record Integration -->
<assemblies>
<item>ChronoSteril.Application</item>
</assemblies>
<config>
<add key="connection.driver_class" value="NHibernate.Driver.SqlClientDriver" />
<add key="dialect" value="NHibernate.Dialect.MsSql2005Dialect" />
<add key="connection.provider" value="NHibernate.Connection.DriverConnectionProvider" />
<add key="connection.connection_string" value="#{connectionString}" />
<add key="hibernate.cache.provider_class" value="NHibernate.Caches.SysCache.SysCacheProvider, NHibernate.Caches.SysCache" />
<add key="proxyfactory.factory_class" value="NHibernate.ByteCode.Castle.ProxyFactoryFactory, NHibernate.ByteCode.Castle" />
<add key="hibernate.expiration" value="60" />
</config>
</facility>
</facilities>
<components>
<component id="windsorConfigurator" service="ChronoSteril.Application.IWindsorConfigurator, ChronoSteril.Application" type="ChronoSteril.WinApp.ClarionIntegrationWindsorConfigurator, ChronoSteril.WinApp" />
</components>
I am not familiar with Windsor. During my Google tour, I did see some code that adds facilities programmatically, but those examples were not valid for my version of Windsor (I assume).
Question: Can anyone guide me in removing the connection string information from the XML file and allow me to set it in the code?
Thank you!
I managed to accomplish my intention. It is not ideal, but will work until the code base is rewritten. (I cannot wait to drop the existing code like a bad dream.)
Patrick's comment, under my initial question, let me to refine my search criteria, which yielded the thread located here.
My XML file remains the same, except that I use bogus values for the connection string information. I will never need to modify these, and they do not reveal any valid connection information. This was my intention. I still have not discovered how to successfully remove the ActiveRecord configuration from the XML file and configure using code.
I now call a method that contains the following code:
ISessionFactoryHolder sessionFactoryHolder = ActiveRecordMediator.GetSessionFactoryHolder();
NHibernate.Cfg.Configuration configuration = sessionFactoryHolder.GetConfiguration(typeof(ActiveRecordBase));
connectionString = ReadConnectionString();
configuration.SetProperty("connection.connection_string", connectionString);
This works for me. I hope that it can also help someone else who is in the same position as I was.

Variables in XML configuration

I'm trying to use xml configuration file in my project. Now it looks like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="replication" type="Project.Replication.ReplicationConfigSection, Project.Replication" />
<section name="processing" type="Project.Processing.ProcessingConfigSection, Project.Processing" />
</configSections>
<replication>
<streams>
<stream name="STREAM_DATA_14360" />
</streams>
</replication>
<processing dataStream="STREAM_DATA_14360" />
</configuration>
It works OK, but I'm confused with duplicates in it ("STREAM_DATA_14360").
Can you remind me, how to create variables in XML or something for data reusing to be acceptable in application configuration?
UPDATE:
In real life my configuration has much more sections. There is a value, which apeears in many of this sections: STREAM_DATA_14360. So I want to be able to change this value only in one place of config file, and in other places to use reference to it.
Speed of changing configuration - is the first reason for it.
Size of a file is a second, because values can be huge: STREAM_INFO_FUTURE_SESSION_CONTENTS_12421 (that is third-party names)
You can simply add this value in <appSettings> and access it as you are saying.
You can do this as below:
<appSettings>
<add key="StreamName" value="STREAM_DATA_14360"/>
</appSettings>
In the code, you can access it as below:
string streamName = ConfigurationManager.AppSettings["StreamName"];
Make sure to add reference to System.Configuration assembly before using this.
XML doesn't have any native expansion macros or templating - any scenario would require that you do a preprocess step or have the code that reads the config involved in substituting the value.
If those aren't redacted names though, it seems a simple search/replace would solve the problem without much of a concern on false positives.
You could put something together with T4 templates as a preprocessor, whether that's worth it really depends on how often you expect to modify this file.
It should also be possible to shoehorn the web.config transformation engine into doing the replacements, but you may have to write some hosting code for the XDT engine depending on how your config file is setup.
Apart from using external code that might (or might not) facilitate your life, you can define your own classes that inherit from ConfigurationSection, wherein you define and encapsulate your key/value pairs and use the ConfigurationProperty attribute.
Have look at http://msdn.microsoft.com/en-us/library/2tw134k3.aspx for more info on How to: Create Custom Configuration Sections Using ConfigurationSection.
EDIT: you can make references in xsd (check here)
Thanks for your answers. I agree with Mark, there's no support of variables or references in XML. But, in my case there's much simpler solution. I feel stupid now, but hope that it will help another slowpoke too.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="global" type="Project.GlobalConfigSection, Project" />
<section name="replication" type="Project.Replication.ReplicationConfigSection, Project.Replication" />
<section name="processing" type="Project.Processing.ProcessingConfigSection, Project.Processing" />
</configSections>
<global>
<streamNames>
<streamName name="STREAM_DATA_14360" id="1"/>
</streamNames>
</global>
<replication>
<streams>
<stream nameId="1" />
</streams>
</replication>
<processing dataStreamId="1" />
</configuration>
Consequence: need to edit code to use global section as a source of all long names
Advantage: fast renaming, reusability of values

Prevent namespaces of top Config from getting wiped out when loading and configuring other .config in Unity

This is somewhat specific and difficult situation to explain, so bear with me.
I have created a UnityContainerExtension that is responsible for loading and configuring other .config files.
For example, my App.Config file looks like this:
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration, Version=2.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="SomeAssembly" />
<namespace name="SomeAssembly.SomeNameSpace" />
<container>
<extension type="ConfigSectionExtension" />
<extension type="TestExtension" />
</container>
</unity>
</configuration>
My first extension ConfigSectionExtension runs code (following) that loads in and configures the container with another .config file. ex.
var fileMap = new ExeConfigurationFileMap { ExeConfigFilename = "logging.config"};
Configuration configuration = ConfigurationManager.OpenMappedExeConfiguration( fileMap, ConfigurationUserLevel.None );
((UnityConfigurationSection)configuration.GetSection( "unity" )).Configure( Container );
This code runs fine, however the TestExtension extension in my config cannot be resolved after the Container has been configured with the logging.config file.
The specific response is
"The type name or alias TestExtension could not be resolved."
If I remove the code that loads and configures the logging.config file with the container, then both extensions are found. Is there any way to make this work?
This is essentially my approach to the problem of not being able to link together multiple .config files. If someone knows a better way to link .config files together for Unity, I would of course be open to that solution as well.
OK, I think I have an OK solution. For my extension I can just fully qualify the Type and it will work. ie.
<extension type="MediaInjectorUI.ContainerExtensions.ConfigSectionExtension, MediaInjectorUI" />
<extension type="MediaInjectorUI.ContainerExtensions.TestExtension, MediaInjectorUI" />
Maybe not the prettiest thing in the world, but itdoes the job.

Could not find schema information for the element 'castle'

I'm creating a Custom tag in my web.config. I first wrote the following entry under the configSections section.
<section name="castle"
type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler,
Castle.Windsor" />
But, when I try to create a castle node inside the configuration node as below
<castle>
<components>
</components>
</castle>
I get the following error message:"*Could not find schema information for the element '**castle'*." "***Could not find schema information for the element '**components'***."
Am I missing something? I can't find why. And, if I run the application anyway, I get the following error "Could not find section 'Castle' in the configuration file associated with this domain."
Ps.// The sample comes from "Pro ASP.NET MVC Framework"/Steven Sanderson/APress ISBN-13 (pbk): 978-1-4302-1007-8" on page 99.
Thank you for the help
============================================================
Since I believe to have done exactly what's said in the book and did not succed, I ask the same question in different terms. How do I add a new node using the above information?
=============================================================================
Thank you. I did what you said and do not have the two warnings. However, I've go a big new warning:
"The element 'configuration' in namespace 'MyWindsorSchema' has invalid child element 'configSections' in namespace 'MyWindsorSchema'. List of possible elements expected: 'include, properties, facilities, components' in namespace 'MyWindsorSchema'."
What you get is not an error that will prevent you from running your application. It is just a warning that Visual Studio emits because it does not know the castle node in a config file. You could use a schema to enable intellisense. Download the Castle Windsor Schema file and take a look at the readme.txt inside. It tells you to put windsor.xsd somewhere on your hard drive and then reference it in the config file:
<?xml version="1.0" encoding="utf-8" ?>
<configuration xmlns="MyWindsorSchema"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="MyWindsorSchema file://S:\Common\Windsor\windsor.xsd">
<configSections>
<section name="castle" type="Castle.Windsor.Configuration.AppDomain.CastleSectionHandler, Castle.Windsor" />
</configSections>
<castle>
<components>
</components>
</castle>
</configuration>

Categories