I am using the Spring Frame Work .net to integrate the c# Application as follows.
Setting The Development Environment
1.1 Installing the NuGet Extension
Please follow the
NuGetInstall link to install the nuget extension for visual studio 2010.
1.2 Downloading the Pr-Requisiste Software Using Nuget Package Manager Console.
After Installing Nuget application, Create the HelloWorld console application in visual studio as follows.
1.2.1 File --> Project --> ConsoleApplication --> Enter application name is HelloWorld.
1.2.2
Open the Nuget Package Manager Console using Menu Tools --> Library
Package Manager --> Package Manager Console and It will open the
following screen.
1.2.3 Download the Spring Core Application using NuGet Package Manager Console.
Install-Package Spring.Core -Version 1.3.2
After Running the above command, the
Spring.Core dependencies are downloaded and as shown in the screen shot.
1.2.4 Download the Common.Logging.Log4Net using NuGet Package Manager Console.
Install-Package Common.Logging.Log4Net -Version 1.2.0
After Running the above command, the
Common.Logging.Log4Net dependencies are downloaded and as shown in the screen shot.
After
running above commands, all dependencies are added to your HelloWorld
Solution Folder --> Reference folder and it is shown below.
And also dll's are copied to your project solution folder --> Packages. The hierarchy as shown below.
Develop the Hello World Application
Create the Hello Package Folder
Create the
Hello Folder in the HelloWorld Solution Explore.
Create the Hello World Class
Create the following Class in the Hello Folder
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace HelloWorld.Hello
{
public class HelloWorld
{
public string GetMessage()
{
return "My First Spring Hello World Application";
}
}
}
Create the App.conf File
Right Click HelloWorld Solution Folder
--> Add --> New Item > Choose Application Configuration File
--> Click Add button and it will create the App.conf file.
Add the following Content to the App.conf file.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="common">
<section name="logging" type="Common.Logging.ConfigurationSectionHandler, Common.Logging" />
</sectionGroup>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.ContextHandler, Spring.Core"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
<section name="log4net" type="log4net.Config.Log4NetConfigurationSectionHandler,log4net" />
</configSections>
<common>
<logging>
<factoryAdapter type="Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net">
<!-- choices are INLINE, FILE, FILE-WATCH, EXTERNAL-->
<!-- otherwise BasicConfigurer.Configure is used -->
<!-- log4net configuration file is specified with key configFile-->
<arg key="configType" value="INLINE" />
</factoryAdapter>
</logging>
</common>
<spring>
<context>
<!-- using embedded assembly configuration file
<resource uri="assembly://Spring.IocQuickStart.MovieFinder/Spring.IocQuickStart.MovieFinder/AppContext.xml"/>
-->
<!-- using section in App.config -->
<resource uri="config://spring/objects"/>
</context>
<objects xmlns="http://www.springframework.net" >
<description>An example that demonstrates simple IoC features.</description>
<object id="hello"
type="HelloWorld.Hello.HelloWorld, HelloWorld">
</object>
</objects>
</spring>
<log4net>
<appender name="ConsoleAppender" type="log4net.Appender.ConsoleAppender">
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%-5level - %message%newline" />
</layout>
</appender>
<!-- Set default logging level to DEBUG -->
<root>
<level value="DEBUG" />
<appender-ref ref="ConsoleAppender" />
</root>
<!-- Set logging for MovieFinder to DEBUG -->
<logger name="hello">
<level value="DEBUG" />
</logger>
<!-- Set logging for Spring to INFO.
Logger names in Spring correspond to the namespace -->
<logger name="Spring">
<level value="INFO" />
</logger>
</log4net>
</configuration>
Registering the Bean
I have highlighted the bold and italic font to register the Spring Bean in the App.Conf file As follows.
<object id="hello"
type="HelloWorld.Hello.HelloWorld, HelloWorld">
</object>
Id : Unique Id for your bean.
type: Hello World Class Name, and Assembly Name.
In our example Class Name is HelloWorld.Hello.HelloWorld and Assmbly Name is HelloWorld.
Running the Application
Getting the Spring Context
IApplicationContext context= ContextRegistry.GetContext();
Getting the registered bean
HelloWorld Hello = (HelloWorld)context.GetObject("hello");
Invoke the Hello WolrdBean GetMessage Method
Console.WriteLine (hello.GetMessage());
HelloWorld Client Class
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spring.Context;
using Spring.Context.Support;
using HelloWorld.Hello;
namespace HelloWorld
{
public class Program
{
static void Main(string[] args)
{
IApplicationContext context = null;
try
{
Console.WriteLine("Initializing the Context");
context = ContextRegistry.GetContext();
Console.WriteLine("Initializing the Context Successfully");
Console.WriteLine("Getting the HelloWorld Handle");
HelloWorld.Hello.HelloWorld hello = (HelloWorld.Hello.HelloWorld)context.GetObject("hello");
Console.WriteLine("Data Out put from spring method {0}", hello.GetMessage());
}
catch (Exception e)
{
Console.WriteLine(e);
}
finally
{
if (context != null)
{
context.Dispose();
}
}
}
}
}
Copy Dependencies DLL and XML Files to bin/debug folder
Visual
studio 2010 shouldn't copy internal dependencies to bin/debug folder.
Please go to the HelloWorld/Packages directory and copy the following
dependency files to bin/debug folder.
copy Common.Logging.Log4Net.1.2.0\lib\2.0\Common.Logging.Log4Net.dll ..\HelloWorld\bin\Debug
copy log4net.1.2.10\lib\2.0\log4net* ..\HelloWorld\bin\Debug
Execute Application
Go
to the HelloWorld Project Directory --> bin --> Debug Directory
and run the HelloWorld.exe and it will display the following output
Initializing the Context
INFO - ApplicationContext Refresh: Completed
Initializing the Context Successfully
Getting the HelloWorld Handle
Data Out put from spring method My First Spring Hello World Application
Common Errors:
Error 1:
Common.Logging.ConfigurationException: Could not configure Common.Logging from configuration section 'common/logg
C:\Users\nagore\Documents\Visual Studio 2010\Projects\HelloWorld\HelloWorld\bin\Debug>HelloWorld.exe
Initializing the Context
System.TypeInitializationException: The type initializer for 'Spring.Context.Support.ContextRegistry' threw an exception
. ---> Common.Logging.ConfigurationException: Could not configure Common.Logging from configuration section 'common/logg
ing'. ---> System.Configuration.ConfigurationErrorsException: An error occurred creating the configuration section handl
er for common/logging: Unable to create type 'Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, Common.Logging.Log4Net
' (C:\Users\nagore\Documents\Visual Studio 2010\Projects\HelloWorld\HelloWorld\bin\Debug\HelloWorld.exe.Config line 16)
---> Common.Logging.ConfigurationException: Unable to create type 'Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter, C
ommon.Logging.Log4Net' ---> System.IO.FileNotFoundException: Could not load file or assembly 'Common.Logging.Log4Net' or
one of its dependencies. The system cannot find the file specified.
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOn
ly, StackCrawlMarkHandle stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName, ObjectHandleOnStack type)
at System.RuntimeTypeHandle.GetTypeByName(String name, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOn
ly, StackCrawlMark& stackMark, IntPtr pPrivHostBinder, Boolean loadTypeFromPartialName)
at System.RuntimeType.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase, Boolean reflectionOnly, Stac
kCrawlMark& stackMark)
at System.Type.GetType(String typeName, Boolean throwOnError, Boolean ignoreCase)
at Common.Logging.ConfigurationSectionHandler.ReadConfiguration(XmlNode section)
--- End of inner exception stack trace ---
at Common.Logging.ConfigurationSectionHandler.ReadConfiguration(XmlNode section)
at Common.Logging.ConfigurationSectionHandler.Create(Object parent, Object configContext, XmlNode section)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionImpl(RuntimeConfiguration
Record configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader read
er)
at System.Configuration.RuntimeConfigurationRecord.RuntimeConfigurationFactory.CreateSectionWithRestrictedPermissions
(RuntimeConfigurationRecord configRecord, FactoryRecord factoryRecord, SectionRecord sectionRecord, Object parentConfig,
ConfigXmlReader reader)
at System.Configuration.RuntimeConfigurationRecord.CreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord,
SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader)
at System.Configuration.BaseConfigurationRecord.CallCreateSection(Boolean inputIsTrusted, FactoryRecord factoryRecord
, SectionRecord sectionRecord, Object parentConfig, ConfigXmlReader reader, String filename, Int32 line)
--- End of inner exception stack trace ---
at System.Configuration.BaseConfigurationRecord.EvaluateOne(String[] keys, SectionInput input, Boolean isTrusted, Fac
toryRecord factoryRecord, SectionRecord sectionRecord, Object parentResult)
at System.Configuration.BaseConfigurationRecord.Evaluate(FactoryRecord factoryRecord, SectionRecord sectionRecord, Ob
ject parentResult, Boolean getLkg, Boolean getRuntimeObject, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPe
rmission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPe
rmission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSectionRecursive(String configKey, Boolean getLkg, Boolean checkPe
rmission, Boolean getRuntimeObject, Boolean requestIsHere, Object& result, Object& resultRuntimeObject)
at System.Configuration.BaseConfigurationRecord.GetSection(String configKey)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(Stri
ng sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at Common.Logging.ConfigurationReader.GetSection(String sectionName)
at Common.Logging.LogManager.BuildLoggerFactoryAdapter()
--- End of inner exception stack trace ---
at Common.Logging.LogManager.BuildLoggerFactoryAdapter()
at Common.Logging.LogManager.get_Adapter()
at Common.Logging.LogManager.GetLogger(Type type)
at Spring.Context.Support.ContextRegistry..cctor() in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Context\Support
\ContextRegistry.cs:line 60
--- End of inner exception stack trace ---
at Spring.Context.Support.ContextRegistry.GetContext()
at HelloWorld.Program.Main(String[] args) in c:\users\nagore\documents\visual studio 2010\Projects\HelloWorld\HelloWo
rld\Program.cs:line 19
Solution:
The
Common.Logging.Log4Net.dll missing in the debug folder. Please copy the
Common.Logging.Log4Net.dll folder from the
HelloWorld/Packages/Common.Logging.Log4Net.1.2.0/lib to
HelloWorld/HelloWorld/bin/Debug.
Error2
Common.Logging.ConfigurationException: Unable to create instance of type Common.Logging.Log4Net.Log4NetLoggerFact
Initializing the Context
System.TypeInitializationException: The type initializer for 'Spring.Context.Support.ContextRegistry' threw an exception
. ---> Common.Logging.ConfigurationException: Unable to create instance of type Common.Logging.Log4Net.Log4NetLoggerFact
oryAdapter. Possible explanation is lack of zero arg and single arg NameValueCollection constructors ---> System.Reflect
ion.TargetInvocationException: Exception has been thrown by the target of an invocation. ---> System.IO.FileNotFoundExce
ption: Could not load file or assembly 'log4net, Version=1.2.10.0, Culture=neutral, PublicKeyToken=1b44e1d426115821' or
one of its dependencies. The system cannot find the file specified.
at Common.Logging.Log4Net.Log4NetLoggerFactoryAdapter..ctor(NameValueCollection properties)
--- End of inner exception stack trace ---
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor)
at System.Reflection.RuntimeConstructorInfo.Invoke(BindingFlags invokeAttr, Binder binder, Object[] parameters, Cultu
reInfo culture)
at System.RuntimeType.CreateInstanceImpl(BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo culture,
Object[] activationAttributes, StackCrawlMark& stackMark)
at System.Activator.CreateInstance(Type type, BindingFlags bindingAttr, Binder binder, Object[] args, CultureInfo cul
ture, Object[] activationAttributes)
at System.Activator.CreateInstance(Type type, Object[] args)
at Common.Logging.LogManager.BuildLoggerFactoryAdapter()
--- End of inner exception stack trace ---
at Common.Logging.LogManager.BuildLoggerFactoryAdapter()
at Common.Logging.LogManager.get_Adapter()
at Common.Logging.LogManager.GetLogger(Type type)
at Spring.Context.Support.ContextRegistry..cctor() in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Context\Support
\ContextRegistry.cs:line 60
--- End of inner exception stack trace ---
at Spring.Context.Support.ContextRegistry.GetContext()
at HelloWorld.Program.Main(String[] args) in c:\users\nagore\documents\visual studio 2010\Projects\HelloWorld\HelloWo
rld\Program.cs:line 19
Solution:
The
Log4Net.dll and Log4Net.xml files are missing in the
HelloWorld/bin/Debug Folder. Copy from
theHelloWorld\packages\log4net.1.2.10\lib\2.0 to
HelloWorld/HelloWorld/bin/debug
References:
Spring Example Reference.
Spring FrameWork Sample Application
Micro Soft Reference Dependencies dll's
Missing Dependencies DLL