Override UrlResolver - asp.net-mvc

I've been working through the Angular 2 tutorial (in TypeScript) when I got stuck on this part. They now want to separate templates into separate files. That's fine and dandy, but I've got a quirky setup: I'm serving up the files with ASP.NET MVC, and it's refusing to serve up the file from the Views folder. Fair enough: I anticipate needing to serve up Razor (.cshtml) files, so I'm happy to try and hack this out instead of just whitelisting .html.
I've worked with Angular 1 before, and in this situation I used a decorator to modify the $templateRequest service to modify the template URLs into something MVC will accept, and then I set up MVC to serve up the corresponding files. Quite clever work if I do say so myself. So I just need to replicate this in Angular 2, right? That should be easy.
Wrong. So wrong. After some guesswork Googling I found UrlResolver which, after some client-side debugging I confirmed, is the class I want to extend. The documentation even says:
This class can be overridden by the application developer to create custom behavior.
Yes! This is exactly what I want to do. Unfortunately no examples of how to override it have been supplied. I've found this DemoUrlResolver and this MyUrlResolver, but I can't figure out how or if either of them works. I've tried the multiple approaches to supplying my custom provider (see this answer) including the bootstrap and providers (on the module and the app component) approaches all to no avail.
How do I override UrlResolver?
I assume it doesn't matter, but at the moment my extension does nothing but defer to the base class:
class MvcUrlResolver extends UrlResolver {
resolve(baseUrl: string, url: string): string {
return super.resolve(baseUrl, url);
}
}

Interesting question. Since it is part of compiler it makes sense that it would not be instantiated along with other application components, and after some research and analyzing angular's code I found the solution. You need to provide it directly in the call to platformBrowserDynamic(). In this case it will be merged into default compiler options and will be used by injector that instantiates compiler.
import { COMPILER_OPTIONS } from '#angular/core';
class MvcUrlResolver extends UrlResolver {
resolve(baseUrl: string, url: string): string {
let result = super.resolve(baseUrl, url);
console.log('resolving urls: baseUrl = ' + baseUrl + '; url = ' + url + '; result = ' + result);
return result;
}
}
platformBrowserDynamic([{
provide: COMPILER_OPTIONS,
useValue: {providers: [{provide: UrlResolver, useClass: MvcUrlResolver}]},
multi: true
}]).bootstrapModule(AppModule);

Related

Xamarin Forms - iOS not processing correctly

I am using the CrossDownManager plugin for Xamarin Forms
Here
When I run the method on Android it processes as expected. On iOS Debug.Writeline("Success!") isn't being hit like it was on Android.
Here is the code:
void ViewImage(string imageLink)
{
var downloadManager = CrossDownloadManager.Current;
downloadManager.PathNameForDownloadedFile = new System.Func<IDownloadFile, string>(file =>
{
string path = DependencyService.Get<IImageSaver>().Save("YHTS" + DateTime.Today.Ticks.ToString() + ".jpg");
Debug.WriteLine("Success!");
return path;
});
try
{
var file = downloadManager.CreateDownloadFile(imageLink);
Debug.WriteLine("file created");
downloadManager.Start(file);
Debug.WriteLine("downloadstarted");
}
catch (Exception e)
{
Debug.WriteLine(e.ToString());
}
}
For the life of me I can't figure out why the that code block isn't processed. Any ideas?
This is an interesting issue as technically your code should work as expected. I've done a little digging and found a reply to a similar question here.
your options are many... including:
DEBUG preprocessor as you show in your question.
Use System.Diagnostic.Debug.WriteLine: Any calls to Debug.* will be
removed by the compiler due to the [Conditional("DEBUG")] attribute
being applied.
Create your own "Logger" class as a wrapper to the stdout writers and
[Conditional("DEBUG")] it
Use Fody and re-weave the assemblies to remove/NOP/redirect the
WriteLine I do this to redirect the calls to in internal log and upon
crash or user stat requests, forward this log to our crash reporting
servers. etc, .....
So there are a few alternatives to consider, one of the common suggestions I've seen is to use the fully qualified reference for WriteLine(); as such:
System.Console.WriteLine("woop woop");
I would suggest giving the above a try first.

SilverStripe 3.1 routing and Link function

I'm updating a SilverStripe website from 2.4 to 3.1.
I have many Links functions used in controllers and views.
The problem is that when I set routes.yml like this
Director:
rules:
'gottesdienste//$Action/$ID/$OtherID' : LiturgiesPage_Controller
'veranstaltungen//$Action/$ID/$OtherID' : ArrangementsPage_Controller
Links in my site change from
gottesdienste/archive/2012
to
LiturgiesPage_Controller/archive/2012
How do I fix this?
You need to implement a custom Link() method that uses the base string you want.
public function Link($action = null) {
return self::join_links('gottesdienste', $action);
}

Conditional imports / code for Dart packages

Is there any way to conditionally import libraries / code based on environment flags or target platforms in Dart? I'm trying to switch out between dart:io's ZLibDecoder / ZLibEncoder classes and zlib.js based on the target platform.
There is an article that describes how to create a unified interface, but I'm unable to visualize that technique not creating duplicate code and redundant tests to test that duplicate code. game_loop employs this technique, but uses separate classes (GameLoopHtml and GameLoopIsolate) that don't seem to share anything.
My code looks a bit like this:
class Parser {
Layer parse(String data) {
List<int> rawBytes = /* ... */;
/* stuff you don't care about */
return new Layer(_inflateBytes(rawBytes));
}
String _inflateBytes(List<int> bytes) {
// Uses ZLibEncoder on dartvm, zlib.js in browser
}
}
I'd like to avoid duplicating code by having two separate classes -- ParserHtml and ParserServer -- that implement everything identically except for _inflateBytes.
EDIT: concrete example here: https://github.com/radicaled/citadel/blob/master/lib/tilemap/parser.dart. It's a TMX (Tile Map XML) parser.
You could use mirrors (reflection) to solve this problem. The pub package path is using reflection to access dart:io on the standalone VM or dart:html in the browser.
The source is located here. The good thing is, that they use #MirrorsUsed, so only the required classes are included for the mirrors api. In my opinion the code is documented very good, it should be easy to adopt the solution for your code.
Start at the getters _io and _html (stating at line 72), they show that you can load a library without that they are available on your type of the VM. Loading just returns false if the library it isn't available.
/// If we're running in the server-side Dart VM, this will return a
/// [LibraryMirror] that gives access to the `dart:io` library.
///
/// If `dart:io` is not available, this returns null.
LibraryMirror get _io => currentMirrorSystem().libraries[Uri.parse('dart:io')];
// TODO(nweiz): when issue 6490 or 6943 are fixed, make this work under dart2js.
/// If we're running in Dartium, this will return a [LibraryMirror] that gives
/// access to the `dart:html` library.
///
/// If `dart:html` is not available, this returns null.
LibraryMirror get _html =>
currentMirrorSystem().libraries[Uri.parse('dart:html')];
Later you can use mirrors to invoke methods or getters. See the getter current (starting at line 86) for an example implementation.
/// Gets the path to the current working directory.
///
/// In the browser, this means the current URL. When using dart2js, this
/// currently returns `.` due to technical constraints. In the future, it will
/// return the current URL.
String get current {
if (_io != null) {
return _io.classes[#Directory].getField(#current).reflectee.path;
} else if (_html != null) {
return _html.getField(#window).reflectee.location.href;
} else {
return '.';
}
}
As you see in the comments, this only works in the Dart VM at the moment. After issue 6490 is solved, it should work in Dart2Js, too. This may means that this solution isn't applicable for you at the moment, but would be a solution later.
The issue 6943 could also be helpful, but describes another solution that is not implemented yet.
Conditional imports are possible based on the presence of dart:html or dart:io, see for example the import statements of resource_loader.dart in package:resource.
I'm not yet sure how to do an import conditional on being on the Flutter platform.

Zend Framework 2, Module.php and getting value of param

In Module.php I have a some code (simplified version):
namespace Application;
use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;
class Module{
public $somevariable = 'test';
public function onBootstrap( MvcEvent $e ) {
$this->somevariable = 'test2';
}
public function getValue(){
return $this->somevariable;
}
}
Next, I want to get value from variable "somevariable" in template layout.phtml. I do this as follows:
echo Application\Module::getValue();
but this doesn't work. What is wrong with that?
P.S. I never programmed much in PHP, so maybe I missed something :-(
you can use
$e->getViewModel()->setVariable('somevariable', 'somethingvalue');
and in the view :
echo $this->layout()->somevariable;
for detail, see this article : http://samsonasik.wordpress.com/2012/07/27/zend-framework-2-mvcevent-layout-view-get-namespace/
If a variable is just a string it doesn't make much sense to go with that approach. And please don't take this offensively, but if you don't have much experience in PHP (you tried to call a static function that is not static), then i wonder why you would start learning PHP with such a high class framework.
And if still you insist on doing that, please follow the official Documentation and read yourself through the whole QuickStart again and again. Check out some of the Modules out there and see how they do stuff.
Try to do the easy stuff first until you hit those points where you really need such functionality.

Why getting a 202 in two equal setup structuremap code paths

In the C# language, using StructureMap 2.5.4, targeting .NET Framework 3.5 libraries.
I've taken the step to support multiple Profiles in a structure map DI setup, using ServiceLocator model with Bootstrapper activation. First setup was loading default registry, using the scanner.
Now I like to determine runtime what Registry configuration I like to use. Scanning and loading multiple assemblies with registries.
Seems it's not working for the actual implementation (Getting the 202, default instance not found), but a stripped test version does work. The following setup.
Two assemblies containing Registries and implementations
Scanning them in running AppDomain, providing the shared Interface, and requesting Creation Of Instance, using the interfaces in constructor (which get dealt with thanx to the profile on Invokation)
Working code sample below (same structure for other setup, but with more complex stuff, that get's a 202):
What type of couses are possible for a 202, specifically naming the System.Uri type, not being handles by a default type?? (uri makes no sense)
// let structure map create instance of class tester, that provides the registered
// interfaces in the registries to the constructor of tester.
public class Tester<TPOCO>
{
private ITestMe<TPOCO> _tester;
public Tester(ITestMe<TPOCO> some)
{
_tester = some;
}
public string Exec()
{
return _tester.Execute();
}
}
public static class Main {
public void ExecuteDIFunction() {
ObjectFactory.GetInstance<Tester<string>>().Exec();
}
}
public class ImplementedTestMe<TSome> : ITestMe<TSome>
{
public string Execute()
{
return "Special Execution";
}
}
public class RegistryForSpecial : Registry
{
public RegistryForSpecial()
{
CreateProfile("Special",
gc =>
{
gc.For(typeof(ITestMe<>)).UseConcreteType(typeof(ImplementedTestMe<>));
});
}
}
Background articles on Profiles I used.
How to setup named instances using StructureMap profiles?
http://devlicio.us/blogs/derik_whittaker/archive/2009/01/07/setting-up-profiles-in-structuremap-2-5.aspx
http://structuremap.sourceforge.net/RegistryDSL.htm
EDIT:
It seemed the missing interface was actually the one being determined runtime. So here is the next challange (and solved):
I provided a default object whenever StructureMap needs to create the object. Like:
x.ForRequestedType<IConnectionContext>()
.TheDefault.Is.Object(new WebServiceConnection());
This way I got rid of the 202 error, because now a real instance could be used whever structure map needed the type.
Next was the override on runtime. That did not work out at first using the ObjectFactory.Configure method. Instead I used the ObjectFactory.Inject method to overide the default instance. Works like a charm.
ObjectFactory.Inject(typeof(IConnectionContext), context);
Loving the community effort.
Error code 202 means a default instance could not be built for the requested type. Your test code is apparently not equal to your real code that fails. If you are getting an error about Uri, you likely have a dependency that requires a Uri in its constructor. It may not be the class you are asking for - it may be one of that classes dependendencies - or one of the dependencies dependencies... somewhere down the line someone is asking StructureMap to resolve a Uri, which it cannot do, without some help from you.

Resources