I'm building a MVC 4 application with Spring support.
My Web.config looks like following
<configSections>
<sectionGroup name="spring">
<section name="context" type="Spring.Context.Support.WebContextHandler, Spring.Web"/>
<section name="objects" type="Spring.Context.Support.DefaultSectionHandler, Spring.Core" />
</sectionGroup>
</configSections>
...
<spring>
<context type="Spring.Context.Support.MvcApplicationContext, Spring.Web.Mvc3, Version=1.3.2.40943, Culture=neutral, PublicKeyToken=65e474d141e25e07">
<!--<resource uri="config://spring/objects"/>-->
</context>
<objects xmlns="http://www.springframework.net" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.net http://www.springframework.net/xsd/spring-objects.xsd">
<object type="Org.Zighinetto.MyNS.RepositoryHelper" singleton="true" id="Org.Zighinetto.RepositoryHelper">
<property name="SessionFactory" ref="Org.Zighinetto.SessionFactory"/>
</object>
<object id="Org.Zighinetto.Ecommerce.NHibernateHelper" type="MvcTest.Utils.NHibernateHelper" singleton="true"/>
<object id="Org.Zighinetto.Ecommerce.SessionFactory" type="NHibernate.ISessionFactory" factory-object="Org.Zighinetto.Ecommerce.NHibernateHelper" factory-method="CreateSessionFactory" />
</objects>
</spring>
In my Controller I want to get a reference to that object that basically wraps all FNH DAOs (I called them Repositories...)
public CustomerController()
{
IApplicationContext ctx = new MvcApplicationContext();
RepositoryHelper repoHelper = (RepositoryHelper)ctx.GetObject("Org.Zighinetto.RepositoryHelper");
_customerRepository = repoHelper.CustomerRepository;
}
GetObject call crashes with following exception
No object named 'Org.Zighinetto.RepositoryHelper' is defined : Cannot find definition for object [Org.Zighinetto.RepositoryHelper]
[NoSuchObjectDefinitionException: No object named 'Org.Zighinetto.RepositoryHelper' is defined : Cannot find definition for object [Org.Zighinetto.RepositoryHelper]]
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObjectInternal(String name, Type requiredType, Object[] arguments, Boolean suppressConfigure) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractObjectFactory.cs:2065
Spring.Objects.Factory.Support.AbstractObjectFactory.GetObject(String name) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Objects\Factory\Support\AbstractObjectFactory.cs:1826
Spring.Context.Support.AbstractApplicationContext.GetObject(String name) in c:\_prj\spring-net\trunk\src\Spring\Spring.Core\Context\Support\AbstractApplicationContext.cs:1538
Am I initializing Spring.net context bad? What can I do to obtain that object reference?
[Add]
ctx.GetObjectDefinitionNames() returns empty string. So no object has been defined
Initializing AppContext with new MvcApplicationContext("~/Web.Config") doesn't change
I fixed using IApplicationContext ctx = WebApplicationContext.GetRootContext()
Related
So, I have a ListView that is x:Bind to a list and a DataTemplate.
The DataTemplate has an Elipse filled with an ImageBrush.
Everything works as it should but:
If an item in the list has a Null value for its string URL image property, the app crashes.
I have tried setting a TargetNullValue but my problem is that the X:DataType of the template is a class from an API, so I cant control it. I want to have an image as a default value in case the item has an image value of null.
In other words, if the item's image URL property is Null, I want XAML to load a predefined image from my Assets folder.
The problem is that because I have set my DataType as the class, anything I x:Bind to has to be within that class.
<Ellipse Width="40" Height="40">
<Ellipse.Fill>
<ImageBrush ImageSource="{x:Bind IconUrl, Mode=OneWay,TargetNullValue=/Assets/NoAvatarIcon.png}"/>
</Ellipse.Fill>
</Ellipse>
The above for example doesn't work for a Null string in ImageSource as the Path is set to the Class.
Right? Any workarounds?
The FallbackValue in Binding and x:Bind is different.
In Binding, FallbackValue is the value to use when the binding is unable to return a value.
A binding uses FallbackValue for cases where the Path doesn't evaluate on the data source at all, or if attempting to set it on the source with a two-way binding throws an exception that's caught by the data binding engine. FallbackValue is also used if the source value is the dependency property sentinel value DependencyProperty.UnsetValue.
But in x:Bind, FallbackValue specifies a value to display when the source or path cannot be resolved. It can't work with DependencyProperty.UnsetValue.
For your scenario, you can use Converter to operate DependencyProperty.UnsetValue just like following code.
public class ImageConverter : IValueConverter
{
public object Convert(object value, Type targetType, object parameter, string language)
{
object res;
res = (value == null ? false : true) ? string.IsNullOrEmpty(value.ToString()) ? null : new BitmapImage(new Uri(value.ToString())) : null;
return res;
}
public object ConvertBack(object value, Type targetType, object parameter, string language)
{
throw new NotImplementedException();
}
}
Usage in Xaml File
<Page.Resources>
<local:ImageConverter x:Key="cm" />
</Page.Resources>
<StackPanel Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
<ListView x:Name="MyListView" ItemsSource="{x:Bind Items}">
<ListView.ItemTemplate>
<DataTemplate x:DataType="local:HeadPhoto">
<Ellipse Width="40" Height="40">
<Ellipse.Fill>
<ImageBrush ImageSource="{x:Bind PicUri,TargetNullValue=/Assets/pic.png,Converter={StaticResource cm }}" />
</Ellipse.Fill>
</Ellipse>
</DataTemplate>
</ListView.ItemTemplate>
</ListView>
</StackPanel>
</Page>
Placeholder image effect.
I am consuming WCF Data Service as Following:
DataMan.ContextWrapper context = new DataMan.ContextWrapper(new Uri("http://localhost:2060/PCM/DataMan.svc/rest/"));
DataMan.Report newReport = DataMan.Report.CreateReport("123123123123", DateTime.Now, "999.199905171156550187000.25");
newReport.Title = "tt";
newReport.StudyAcDate = Convert.ToDateTime("2016-05-04 12:09:00");
newReport.Body = "asdasd";
newReport.Auther = "ali.h";
newReport.ApproverComment = "cm";
newReport.Approver = "admin";
context.AddToReports(newReport);
DataServiceResponse response = context.SaveChanges();
but after calling SaveChange() I have got the following error:
The server encountered an error processing the request. The exception message is 'Incoming message for operation 'ProcessRequestForMessage' (contract 'IRequestHandler' with namespace 'http://tempuri.org/') contains an unrecognized http body format value 'Xml'. The expected body format value is 'Raw'. This can be because a WebContentTypeMapper has not been configured on the binding. See the documentation of WebContentTypeMapper for more details.'. See server logs for more details.
and my WCF Data Service is as following:
public class ContextWrapper : DataAccessDbContext
{
public ContextWrapper() : base("connection string")
{
}
}
[JSONPSupportBehavior]
public class DataMan : EntityFrameworkDataService<ContextWrapper>
{
public static void InitializeService(DataServiceConfiguration config)
{
config.SetEntitySetAccessRule("*", EntitySetRights.All);
config.SetEntitySetAccessRule("Studies", EntitySetRights.None);
config.SetServiceOperationAccessRule("*", ServiceOperationRights.All);
config.UseVerboseErrors = true; // TODO - Remove for production?
config.DataServiceBehavior.MaxProtocolVersion = DataServiceProtocolVersion.V3;
}
protected override void HandleException(HandleExceptionArgs args)
{
base.HandleException(args);
}
}
I also implemented and configured WebContentTypeMapper to bypass mentioned Error as following:
public class ContentTypeMapper : WebContentTypeMapper
{
public override WebContentFormat GetMessageFormatForContentType(string contentType)
{
return WebContentFormat.Raw;
}
}
Custom binding:
<binding name="XmlMapper">
<webMessageEncoding webContentTypeMapperType="MARCO.SOA.PCMServiceLib.ContentTypeMapper,MARCO.SOA.PCMServiceLib.Core"/>
<httpTransport manualAddressing="true"/>
</binding>
</customBinding>
Service endpoint:
<service behaviorConfiguration="Commom2.Behavior" name="MARCO.SOA.PCMServiceLib.DataMan">
<endpoint address="rest" behaviorConfiguration="Rest.Behavior" binding="webHttpBinding"
bindingConfiguration="XmlMapper" contract="System.Data.Services.IRequestHandler">
<identity>
<dns value="localhost" />
</identity>
</endpoint>
<host>
<baseAddresses>
<add baseAddress="http://localhost:2060/PCM/DataMan.svc"/>
</baseAddresses>
</host>
</service>
but it still get exception, I think something went wrong with my configuration.
Any help would be truly appreciated.
Thanks in advance.
okay, after much trouble I finally solved the problem,
so we need to initiate factory property for serviceActivation
So my relative address was:
<serviceHostingEnvironment>
<serviceActivations>
.
.
.
<add relativeAddress="DataMan.svc" service="MARCO.SOA.PCMServiceLib.DataMan"/>
.
.
.
</serviceActivations>
</serviceHostingEnvironment>
and I have changed it to
<serviceHostingEnvironment>
<serviceActivations>
.
.
.
<add relativeAddress="DataMan.svc" service="MARCO.SOA.PCMServiceLib.DataMan" factory="System.Data.Services.DataServiceHostFactory, Microsoft.Data.Services, Version=5.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
.
.
.
</serviceActivations>
</serviceHostingEnvironment>
now everything is now working nice.
more info about DataServiceHostFactory
Note:
By this we don't need to override GetMessageFormatForContentType of WebContentTypeMapper and force it to return WebContentFormat.Raw or another content format and don't need any customBinding in config file.
Thanks to all.
I've tried a 1000 different options an permutations.
Why can't compile my Cat mapping?
Exception thrown: 'NHibernate.MappingException' in NHibernate.dll
Additional information: Could not compile the mapping document: (string)
Configuration cfg = new Configuration();
cfg.Configure();
cfg.AddXmlString(
#"<?xml version=""1.0"" encoding=""utf - 8"" ?>"
+ #"<hibernate-mapping xmlns=""urn:nhibernate-mapping-2.2"" assembly=""QuickStart"" namespace=""QuickStart.Cat"">"
+ #"<class name=""Cat"" table=""Cat"">"
+ #" <id name=""Id"" ><column name=""CatId"" /><generator class=""uuid.hex"" /></id>"
//+ #" <id name=""Id"" ><column name=""CatId"" sql-type=""char(32)"" not-null=""true"" /><generator class=""uuid.hex"" /></id>"
//+ #" <property name=""Name"" ><column name=""Name"" length=""16"" not-null=""true"" /></property>"
//+ #" <property name=""Sex"" />"
//+ #" <property name=""Weight"" />"
+ #"</class>"
+ #"</hibernate-mapping>"
);
--- from Web.Config
NHibernate.Connection.DriverConnectionProvider
NHibernate.Driver.SqlClientDriver
NHibernate.Dialect.MsSql2012Dialect
Server=localhost;initial catalog=PlaygroundDB;Integrated Security=True
encoding=""utf - 8"" ?> should be encoding=""utf-8""?>
But I never add xml mapping programmaticaly one by one. And even less as raw string (which is quite prone to errors). Instead, I add ClassName.hbm.xml files in project, setting their Build action property to Embedded resource, and I call .AddAssembly(MyProjectAssembly) before building the configuration.
If your mappings are embedded in the same assembly defining your session factory, the code is as simple as:
public static class NHibernateSessionFactory
{
private static readonly ISessionFactory _sessionFactory;
static NHibernateSessionFactory()
{
var configuration = new Configuration();
configuration.Configure();
configuration.AddAssembly(typeof(NHibernateSessionFactory).Assembly);
_sessionFactory = configuration.BuildSessionFactory();
}
public static ISessionFactory Instance { get { return _sessionFactory; } }
}
Minimal configuration file (hibernate.cfg.xml) I am using:
<?xml version="1.0" encoding="utf-8"?>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2">
<session-factory name="ProjectName">
<property name="connection.driver_class">NHibernate.Driver.SqlClientDriver</property>
<property name="connection.connection_string_name">ProjectConnectionStringName</property>
<property name="dialect">NHibernate.Dialect.MsSql2012Dialect</property>
<property name="adonet.batch_size">100</property>
<property name="prepare_sql">true</property>
</session-factory>
</hibernate-configuration>
ProjectConnectionStringName refers to a connection string defined in .Net standard configuration connectionStrings node.
I need to configure a Quartz.NET instance using Spring.NET. I haven't been able to find an example of how to do this, other than very simple cases. I don't need any of the job/trigger config since those are done via the API for us. What I need is a means to configure these settings.
quartz.scheduler.instanceName = ServerScheduler
quartz.threadPool.type = Quartz.Simpl.SimpleThreadPool, Quartz
quartz.threadPool.threadCount = 10
quartz.threadPool.threadPriority = Normal
quartz.plugin.xml.type = Quartz.Plugin.Xml.JobInitializationPlugin, Quartz
quartz.plugin.xml.fileNames = C:/Tools/Forge/DataImport/Config/quartz_jobs.xml
quartz.jobStore.type = Quartz.Impl.AdoJobStore.JobStoreTX, Quartz
quartz.jobStore.driverDelegateType = Quartz.Impl.AdoJobStore.StdAdoDelegate, Quartz
quartz.jobStore.dataSource = ForgePlatformDatasource
quartz.dataSource.ForgePlatformDatasource.connectionString = Server=172.20.0.113 Database=ForgeQuartz;Uid=sa;Pwd=654321
quartz.dataSource.ForgePlatformDatasource.provider = SqlServer-40
quartz.jobStore.useProperties = true
quartz.scheduler.exporter.type = Quartz.Simpl.RemotingSchedulerExporter, Quartz
quartz.scheduler.exporter.port = 555
quartz.scheduler.exporter.bindName = QuartzScheduler
quartz.scheduler.exporter.channelType = tcp
According to what I remember you can set all your config details on the SchedulerFactoryObject -> QuartzProperties property.
<object name="SomeName" type="Spring.Scheduling.Quartz.SchedulerFactoryObject, Spring.Scheduling.Quartz">
<property name="QuartzProperties">
<dictionary>
<entry key="quartz.scheduler.instanceName" value="ServerScheduler"/>
<entry key="quartz.threadPool.type" value="Quartz.Simpl.SimpleThreadPool, Quartz"/>
<entry key="quartz.threadPool.threadCount" value="10"/>
... and many more ...
</dictionary>
</property>
</object>
The API-Documentation:
/// <summary>
/// Set Quartz properties, like "quartz.threadPool.type".
/// </summary>
/// <remarks>
/// Can be used to override values in a Quartz properties config file,
/// or to specify all necessary properties locally.
/// </remarks>
/// <seealso cref="ConfigLocation" />
public virtual IDictionary QuartzProperties
{
set { quartzProperties = value; }
}
I'm creating an ASP.NET MVC application using F# on IIS 7.
When I attempt to run it from the browser, I'm met with a YSOD containing the following:
[ArgumentNullException: Value cannot
be null. Parameter name: dictionary]
System.Collections.Generic.Dictionary2..ctor(IDictionary2
dictionary, IEqualityComparer`1
comparer) +12700827
System.Web.Compilation.CompilationUtil.CreateCodeDomProviderWithPropertyOptions(Type
codeDomProviderType) +84
System.Web.Compilation.CompilationUtil.CreateCodeDomProviderNonPublic(Type
codeDomProviderType) +16
System.Web.Compilation.AssemblyBuilder..ctor(CompilationSection
compConfig, ICollection
referencedAssemblies, CompilerType
compilerType, String
outputAssemblyName) +469
System.Web.Compilation.CompilerType.CreateAssemblyBuilder(CompilationSection
compConfig, ICollection
referencedAssemblies, String
generatedFilesDir, String
outputAssemblyName) +127
System.Web.Compilation.BuildProvidersCompiler.ProcessBuildProviders()
+675 System.Web.Compilation.BuildProvidersCompiler.PerformBuild()
+46 System.Web.Compilation.ApplicationBuildProvider.GetGlobalAsaxBuildResult(Boolean
isPrecompiledApp) +11321455
System.Web.Compilation.BuildManager.CompileGlobalAsax()
+50 System.Web.Compilation.BuildManager.EnsureTopLevelFilesCompiled()
+872
I looked up the method using Reflector to see if it could give me any more context and found that it was failing on the first line
private static CodeDomProvider CreateCodeDomProviderWithPropertyOptions(Type codeDomProviderType)
{
IDictionary<string, string> providerOptions = new Dictionary<string, string>(GetProviderOptions(codeDomProviderType));
//Snip
}
It leads me to believe that the propertyOptions I've specified in my Web.config for the F# CodeDom are incorrect. However, if I remove them I receive the same error.
<system.codedom>
<compilers>
<compiler language="F#;f#;fs;fsharp" extension=".fs" warningLevel="4"
type="Microsoft.FSharp.Compiler.CodeDom.FSharpAspNetCodeProvider,
FSharp.Compiler.CodeDom">
<providerOption name="CompilerVersion" value="v4.0"/>
<providerOption name="WarnAsError" value="false"/>
</compiler>
</compilers>
</system.codedom>
Any ideas on correcting this error?
It’s a bug in ASP.NET in VS2010 Beta2 (it has since been fixed, so will work in next release). It affects any 3rd party CodeDOM provider, and I don’t believe there is any workaround.
I found the cause to the problem.
The Microsoft.FSharp.Compiler.CodeDom.FSharpAspNetCodeProvider.FileExtension is hardcoded to "fs".
Inside of System.CodeDom.Compiler.CodeDomCompilationConfiguration..ctor() CompilerInfos are created for each of the allowed languages. A CompilerInfo for FSharp is not found within the creation of this.
internal CodeDomCompilationConfiguration()
{
this._compilerLanguages = new Hashtable(StringComparer.OrdinalIgnoreCase);
this._compilerExtensions = new Hashtable(StringComparer.OrdinalIgnoreCase);
this._allCompilerInfo = new ArrayList();
CompilerParameters compilerParams = new CompilerParameters();
compilerParams.WarningLevel = 4;
string codeDomProviderTypeName = "Microsoft.CSharp.CSharpCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
CompilerInfo compilerInfo = new CompilerInfo(compilerParams, codeDomProviderTypeName);
compilerInfo._compilerLanguages = new string[] { "c#", "cs", "csharp" };
compilerInfo._compilerExtensions = new string[] { ".cs", "cs" };
compilerInfo._providerOptions = new Dictionary<string, string>();
compilerInfo._providerOptions["CompilerVersion"] = "v4.0";
this.AddCompilerInfo(compilerInfo);
compilerParams = new CompilerParameters();
compilerParams.WarningLevel = 4;
codeDomProviderTypeName = "Microsoft.VisualBasic.VBCodeProvider, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089";
compilerInfo = new CompilerInfo(compilerParams, codeDomProviderTypeName);
compilerInfo._compilerLanguages = new string[] { "vb", "vbs", "visualbasic", "vbscript" };
compilerInfo._compilerExtensions = new string[] { ".vb", "vb" };
compilerInfo._providerOptions = new Dictionary<string, string>();
compilerInfo._providerOptions["CompilerVersion"] = "v4.0";
this.AddCompilerInfo(compilerInfo);
//Snip
}
The FileExtension is compared against _compilerExtensions in System.CodeDom.Compiler.CodeDomProvider.GetCompilerInfoForExtensionNoThrow which (in the case of "fs") returns null to System.CodeDom.Compiler.CodeDomProvider.IsDefinedExtension which will then return false to System.Web.Compilation.CompilationUtil.GetProviderOptions that returns the null that was causing the ArgumentNullException.
Thanks for pointing me in the right direction, #Brian
Perhaps the bug Brian noted can be worked around by specifying some more info in web.config:
type="Microsoft.FSharp.Compiler.CodeDom.FSharpAspNetCodeProvider,
FSharp.Compiler.CodeDom,
Version=1.9.7.8,
Culture=neutral,
PublicKeyToken=a19089b1c74d0809"