Nancyfx localization - nancy

I'm testing localization in Nancy and able to get it to work using EMBEDDED resource files but the issue is I don't want embedded resource files because I want them to be allowed to be edited via the GUI or using the file (if I go the DB route or setting the resource file as "content").
According to the doucmentation you should be able to override it to support using a database but I'm unable to get this to work (https://github.com/NancyFx/Nancy/wiki/Localization):
public class ResourceManager : ResourceBasedTextResource
{
public ResourceManager(IResourceAssemblyProvider resourceAssemblyProvider) : base(resourceAssemblyProvider)
{
}
public new string this[string key, NancyContext context]
{
get
{
return "HELO!";
}
}
}
This was just me messing around but I was hoping in the Razor view when I did #Text.Localization. it should return "HELO!" for everything... however it is not working

There really isn't a question in your post so I'm going to have to guess a bit and assume that you're not getting any exception but rather you're not seeing the "HELO!" in your view
Simply implementing a new ResourceBasedTextResource class is not enough. This is a core component and as such you are going to explicitly have to tell Nancy to use it. You do this by overriding the InternalConfiguration property of your Bootstrapper and tell Nancy to use your implementation instead
You can see it in the DemoBootstrapper of the demo that is linked from that wiki page https://github.com/NancyFx/Nancy/blob/8970ac9d6c7cf46e6060f0b83117c19fa18085c2/src/Nancy.Demo.Razor.Localization/DemoBootstrapper.cs#L11
Also, if you are not going to use resource files, then you should look into inheriting from ITextResource interface instead. It's a simple interface so it should be straight forward.
HTH

Related

Registering Startup Class In Nancy Using AutoFac Bootstrapper

I've been reading through a lot of the Jabbr code to learn Nancy and trying to implement many of the same patterns in my own application. One of the things I can't seem to get working is the concept of an on application start class. The Jabbr code base has an App_Start folder with a Startup.cs file (here) in it with the following implementation.
public partial class Startup
{
public void Configuration(IAppBuilder app)
{
...
SetupNancy(kernel, app);
...
}
}
private static void SetupNancy(IKernel kernel, IAppBuilder app)
{
var bootstrapper = new JabbRNinjectNancyBootstrapper(kernel);
app.UseNancy(bootstrapper);
}
When I tried to do something similar to that in my project the Startup.cs file was just ignored. I searched the Jabbr code base to see if it was used anywhere but I wasn't able to find anything and the only differences I could see is Jabbr uses Ninject while I wanted to use AutoFac
Is there a way to register a startup class in nancy?
Take a look at my project over on GitHub, you'll be interested in the Spike branch and may have to unload the ChainLink.Web project to run I can't remember.
I had some trouble finding a way to configure the ILifetimeScope even after reading the accepted answer here by TheCodeJunkie. Here's how you do the actual configuration:
In the bootstrapper class derived from the AutofacNancyBootstrapper, to actually configure the request container, you update the ILifetimeScope's component registry.
protected override void ConfigureRequestContainer(
ILifetimeScope container, NancyContext context)
{
var builder = new ContainerBuilder();
builder.RegisterType<MyDependency>();
builder.Update(container.ComponentRegistry);
}
The application container can be updated similarly in the ConfigureApplicationContainer override.
You should install the Nancy.Bootstrappers.Autofac nuget, inherit from the AutofacNancyBootstrapper type and override the appropriate method (depending on your lifetime scope requirements: application or request). For more info check the readme file https://github.com/nancyfx/nancy.bootstrappers.autofac
HTH
After following the advice from TheCodeJunkie you can use the Update method on the ILifetimeScope container parameter which gives you a ContainerBuilder through an Action:
protected override void ConfigureRequestContainer(ILifetimeScope container, NancyContext context)
{
container.Update(builder =>
{
builder.RegisterType<MyType>();
});
}

MEF and loading EntityTypeConfiguration in runtime

You cannot vote on your own post
0
Hi.
I am developing this (http://arg-co.com/SabteNam%20-%20Copy.zip) windows application, and for my DAL I use Entity Framework. But every single extension has its own EntityTypeConfiguration, so I decided to use [Import] and [Export] to add them in OnModelCreating method of my DbContext.The problem here is that, in 'SabteNamDbContext' class which is located on 'SabteNamDataAccess' library, the '_Configs' is not initialized so I cant iterate it and add its items to 'modelBuilder.Configurations'.
In the source code of 'SampleConfiguration' class, I commented out '[Export(typeof(IDbConfiguration))]' but even Uncommenting this part of code, do not cause application to work properly.
Intresting point is that, if I use the following code in 'Main' windows form, the '_Configs' would be initialized :
[ImportMany(typeof(IDbConfiguration))]
public IEnumerable<EntityTypeConfiguration<object>> _Configs { get; set; }
How can this be fixed ?
While I realize this is probably no longer of use to you, we use a variation on this model from OdeToCode, which I advise you read.
In our case, we have created an interface for our extensions in general, not just for the entity configuration like Scott did, which allows us not only to load the configurations, but also factory and test data per extension, add new permission types to the core application, etc.
Our OnModelCreating looks something like this:
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
// load core object mappings
modelBuilder.Configurations.Add(new UserConfiguration());
modelBuilder.Configurations.Add(new PermissionConfiguration());
// get plugin assemblies
var catalog = new DirectoryCatalog("bin");
var container = new CompositionContainer(catalog);
container.ComposeParts();
var plugins = container.GetExportedValues<IPlugin>();
// load plugin object mappings
foreach (IPlugin plugin in plugins)
{
plugin.RegisterDomainEntities(modelBuilder.Configurations);
}
base.OnModelCreating(modelBuilder);
}

UriFormatException : Invalid URI: Invalid port specified

The assembly qualified string used as a parameter below for a Uri works in XAML, but gives me the error shown when used in code.
I tried every kind of UriKind with the same result. How can I fix this?
[Test]
public void LargeImageSource_IsKnown()
{
var uri = new Uri(
"pack://application:,,,/" +
"MyAssembly.Core.Presentation.Wpf;component/" +
"Images/Delete.png", UriKind.RelativeOrAbsolute);
Assert.That(
_pickerActivityCollectionVm.DeleteActivityCommand.LargeImageSource,
Is.EqualTo(uri));
}
System.UriFormatException : Invalid URI: Invalid port specified.
at System.Uri.CreateThis(String uri, Boolean dontEscape, UriKind uriKind)
at System.Uri..ctor(String uriString, UriKind uriKind)
UPDATE
Based on Thomas' superb answer and my own comments about readability, I wound up using the following in my BaseTestFixture class. Hope this helps someone else.
protected virtual void OnFixtureSetUp() {
// logging, other one time setup stuff...
const string scheme = "pack";
if (!UriParser.IsKnownScheme(scheme)) {
Assert.That(PackUriHelper.UriSchemePack, Is.EqualTo(scheme));
}
}
That's because you're executing this code while the pack:// scheme is not yet registered. This scheme is registered when you create the Application object. You can add this code in the setup of your test fixture:
[SetUp]
public void Setup()
{
if (!UriParser.IsKnownScheme("pack"))
new System.Windows.Application();
}
EDIT: actually it seems the pack:// scheme is registered in the type initializer of the PackUriHelper class (which happens to be used by the Application class). So actually you don't need to create an instance of Application, you only need to access a static member of PackUriHelper to ensure the type initializer has run:
[SetUp]
public void Setup()
{
string s = System.IO.Packaging.PackUriHelper.UriSchemePack;
}
It appears that accessing PackUriHelper.UriSchemePack only registers the pack scheme, not the application scheme, which I needed to use the pack://application:,,,/ syntax in my unit tests. I therefore had to use the new Application() approach, which worked fine for registering both schemes.
If you're seeing this error in a Windows Store / WinRT project:
I wasn't able to use the "pack://" syntax at all when trying to load a resource in my C# app. What worked was ms-appx:// syntax of this kind:
ms-appx://[project folder]/[resource path]
For example, I wanted to load a resource dictionary named "styles.xaml" from a folder "core". This URI ended up working for me:
dictionary.Source = new System.Uri("ms-appx:///core/styles.xaml");
Even though the question specified WPF, the problem seemed extremely similar but ended up having a completely different solution, which took a while to find, and existing answers didn't help at all.
Again, this solution does not apply to WPF

WPF unit test DirectoryNotFoundException

I am having trouble instantiating a view model wich loads an image from Resources.
The line that fails in the assembly I'm testing is:
get { return new ImageSourceConverter().ConvertFromString("pack://application:,,,/Resources/Icons/Commands/DisabledNewSessionIcon.png") as ImageSource; }
the exception is:
Unable to create instance of class
GPAnalysisSuite.Tests.View_Models.Session_Controller.SessionControllerViewModel_NonDefaultConstructorTester.
Error:
System.IO.DirectoryNotFoundException:
Could not find a part of the path
'C:\TGP\GP Analysis
Suite\Application\Tests\TestResults\Paul_PAUL-GP
2011-03-17
11_27_28\Out\Resources\Icons\Commands\DisabledNewSessionIcon.png'..
I have already found a solution to a simular problem and included the following to the TestClass:
[AssemblyInitialize]
public static void InitialisePackageUriHelper(TestContext context)
{
PackUriHelper.Create(new Uri("reliable://0"));
new FrameworkElement();
System.Windows.Application.ResourceAssembly = typeof(App).Assembly;
}
I can see that I need to preserve the Uri of the assembly I'm testing but have no idea how to do it, can anyone help?
I appear to have solved the problem by changing the resource build action from Content to Resource.
Although I have to rebuild the solution everytime I want to run the unit tests this is now workable at least.

Silverlight 4 and COM Interop

I've created a ComVisible-class:
[Guid("73a3f91f-baa9-46ab-94b8-e526c22054a4"), ComVisible(true)]
public interface ITest
{
void Foo();
}
[Guid("99f72d92-b302-4fde-89bb-2dac899f5a48"), ComVisible(true)]
public class Class1 : ITest
{
public void Foo() { }
}
and registered it via
regasm ComClassTest.dll /tlb:ComClassTest.tlb
into the registry.
When I try to call it in my Silverlight 4 out-of-browser, elevated trust application like this:
var foo = AutomationFactory.CreateObject("ComClassTest.Class1");
I get an exception "{System.Exception: Failed to create an object instance for the specified ProgID."
However, I am able to call AutomationFactory.CreateObject("Word.Application") without an Exception and to call Activator.CreateInstance(Type.GetTypeFromProgID("ComClassTest.Class1")) in a normal C#-console application if I copy the ComClassTest.dll into the bin-directory.
What have I forgotton?
First thing to do is test that you can create the object from somewhere else such as VBScript. Create a .vbs file with the content:-
o = CreateObject("ComClassTest.Class1")
If that doesn't generate an error then there is something specifically that SL OOB is upset with otherwise your problem isn't really related to Silverlight at all.
Consider making the following changes to your COM code.
Its often easier to specify ComVisible(true) at the assembly level. You can do that from the application tab of the project properties on the Assembly Information dialog. You can also get Visual Studio to register the assembly with COM and build time using the option found on the build tab of the project properties.
Its a good idea to be specific about the ComInterfaceType you want to expose.
Things get really messy if you expose the class interface directly generally you only want the interface you have defined to be used and that this be the default interface for the class. In addition it probably better to stick to COM naming conventions for the default interface of a class.
Finally (and possibly crucially in your case) its a good idea to be explicit about the ProgId to use for the class.
Applying the above and we get:-
[InterfaceType(ComInterfaceType.InterfaceIsDual)]
[Guid("73a3f91f-baa9-46ab-94b8-e526c22054a4")]
public interface _Class1
{
void Foo();
}
[ClassInterface(ClassInterfaceType.None)]
[Guid("99f72d92-b302-4fde-89bb-2dac899f5a48")]
[ProgId("ComClassTest.Class1")]
public class Class1 : _Class1
{
public void Foo() { }
}

Resources