How do I get the absolute media file path in umbraco using razor? - razor

I've tried the following bit of razor code:
#room.Media("summaryImage","umbracoFile")
but I get something like ~/media/155/lux.jpg, how do I remove the initial ~ to get a server path ie, /media/155/lux.jpg or http://some_url/media/155/lux.jpg?
EDIT:
I've tried
#{
dynamic summaryImagePath = room.Media("summaryImage","umbracoFile");
}
#Page.ResolveUrl(#summaryImagePath)
and
#Page.ResolveUrl(#room.Media("summaryImage","umbracoFile"))
but I keep getting the error:
Error loading Razor Script Cannot perform runtime binding on a null reference
even though #room.Media("summaryImage","umbracoFile") gives ~/media/155/lux.jpg.
Any ideas?

I'm not sure whether there is a solution within Umbraco, I'd just use the .NET framework. With ASP.NET, you can use MapPath to resolve virtual paths to physical file paths:
#HttpContext.Current.Server.MapPath(room.Media("summaryImage","umbracoFile"))
EDIT:
If you are looking for the absolute URL, you may use one of the following variants:
#Page.ResolveUrl(room.Media("summaryImage","umbracoFile"))
or
#VirtualPathUtility.ToAbsolute(room.Media("summaryImage","umbracoFile"))
You may would like to read this article about different approaches for resolving URLs.

Related

Blazor WebAssembly JsonException: A possible object cycle was detected which is not supported

I get this error because I have circular references defined in my object model. My question is, is there any way to resolve this using one of the following two options?
Using Newtonsoft.Json and options.SerializerSettings.ReferenceLoopHandling = ReferenceLoopHandling.Ignore;
Using System.Text.Json and options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
I'm not seeing a way to switch to Newtonsoft.Json in a Blazor WebAssembly application and I tried implementing option 2 in the ConfigureServices function of Startup.cs in my Server project but I still kept getting the error.
I'm just trying to find a solution that doesn't require me redefining my object model. The JsonIgnore attribute does not appear to be an option either because I assume, and it appears, that then any fields I define it on do not exist in the Json on the client which breaks my application.
Update: I found this site which looks to me like discusses exactly what I'm referring to here and how to implement the solution but I have not got it to work yet. If anyone is successfully using Blazor WebAssembly with circular references in your object model please let me know what you're doing.
https://github.com/dotnet/aspnetcore/issues/28286
Thank you for pointing out this error in Blazor. I found the answer in the issue you mentioned (this comment). You need to change json options also on the Client side. This works for me:
On server
services.AddControllersWithViews().AddJsonOptions(options =>
{
options.JsonSerializerOptions.ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve;
options.JsonSerializerOptions.PropertyNamingPolicy = null;
});
On client
var response = await Http.GetFromJsonAsync<T>("{Address}", new JsonSerializerOptions
{
ReferenceHandler = System.Text.Json.Serialization.ReferenceHandler.Preserve,
PropertyNamingPolicy = null
});
To the two options you mentioned there is a third option available if you use .NET 6 or above.
Using System.Text.Json and options.JsonSerializerOptions.ReferenceHandler = ReferenceHandler.IgnoreCycles;
Beware that ignoring cycles have issues on its own (such as data corruption) but if you were depending on it when you were using Newtonsoft.Json then you will be fine as it is basically the same behavior.
If you prefer to go with ReferenceHandler.Preserve, please share more info on what error you are getting and I can try to help you out.
One way to go about this is specify how much depth an object is allowed to have. Please see the documentation here regarding how to do this with System.Text.Json. I think this may help.

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry

Uncaught DOMException: Failed to execute 'define' on 'CustomElementRegistry': this name has already been used with this registry
at http://127.0.0.1:8000/components/#polymer/polymer/lib/elements/dom-module.js:175:16
Tried deleting node-modules and package-lock and reinstalling did not work.
this error is due to a custom element tag-name being registered which is already registered; to fix simply check that an element by this name hasn't already been registered. This example solution checks to see if something is already registered using the existing API and if not, registers the given Class (inheriting from/extending HTMLElement--at some point):
customElements.get('the-element') || customElements.define('the-element', HTMLTheElement);
For more on the API see https://developer.mozilla.org/docs/Web/API/CustomElementRegistry
most/mature libraries address this problem and those that don't, or are mangled by package and build process complexities can have it pop up; in most cases either updating to a current version, migrating to Lit (https://lit.dev) or patching the problem somehow provides a path to a solution; note the simpler solutions are far easier to maintain--as can be seen in the conflation of npm, polymer over the actual error in the original question; the Polymer project became lit-html and LitElement, and recently rebranded as "Lit" (and still includes these lit-things). Professionally I'm migrating away from npm and Nodejs to Deno with the aim of generally resolve the many problems related to npm and tooling insecurity and complexity, however this answer provides a more direct solution (understand the problem and fix directly, or update to the relevant latest solution which includes this somehow).
Well, this worked for me, with no Typescript warnings,
if (!customElements.get('the-element')) { customElements.define('the-element', HTMLTheElement); }
Hope someone will find this useful.
Cheers.
It is unwise to use the answers above. You want it to fail! The reason being is that your NPM should be deduping duplicate packages, so the fact that you see a certain component being defined on the custom elements registry more than once is a crucial error that you need to debug why the same component is registered more than once.
How to debug, in short, go to your browser, inspect element, network tab, refresh, figure out which files are both registering the same element. Then check in the initiator to see which files are loading those files. Then you get a way better idea of why your app is not resolving the same import to a single place (your deduped dependency).
One reason why you might face this problem is due to semver. If you have multiple different major versions of the same dependency, NPM cannot just dedupe all of the installations to your root node_modules. How you solve this is up to you. Some people use npm-aliases for their different majors of a dependency, some people implement a plugin in their build-tool to resolve paths to a single installation, etc.
For people that can't use #jimmonts answer because the issue is in one of their dependencies you can use the following snippet:
This happens for us, because a package we are using defines an element. But this package is used by multiple apps. And these apps, wouldn't you know it, interact. So customElements.define('x-tag', className) gets called multiple times. And the second time it does, it crashes the app.
function safeDecorator(fn) {
// eslint-disable-next-line func-names
return function(...args) {
try {
return fn.apply(this, args);
} catch (error) {
if (
error instanceof DOMException &&
error.message.includes('has already been used with this registry')
) {
return false;
}
throw error;
}
};
}
customElements.define = safeDecorator(customElements.define);
I was getting the same error. You may not have the same issue as me but I thought I would drop my solution here just incase someone runs into the same issue in the future.
I had two modules that both imported the same custom element module, one of the was importing Module.js and the other module.js. Now the browser saw this as two separate files because URLs can be case sensitive, except my server saw this as one file because it is not case sensitive (express.js) or at least it was able to resolve the path to the correct file even with the incorrect case. And so the browser saw two "different" modules both defining the same custom element, but when I searched my source code only one file was defining the custom element.
I had this problem and found out that I was calling on my boundle.js file twice. Since I was using Webpack and HtmlWebpackPlugin, HtmlWebpackPlugin added the reference to my boundled file to my index.html file where I had already referenced it by hand.
I developed a solution, thats overrite the define with a precheck before define. It works fine for me, just ad the 2 lines into your index.js
customElements.defineclone = Object.assign(Object.create(Object.getPrototypeOf(customElements)).define, customElements);
customElements.define = (name, element) => customElements.get(name) || customElements.defineclone(name, element);

How to have class loaded without using "use" but call it as if I used it

I have studied these 2 sources, but none of those works for me.
http://www.yiiframework.com/doc-2.0/guide-concept-autoloading.html
Yii2 - How do I AutoLoad a custom class?
I have created custom helper class which I want to include in every model, controller and view in my application. I am using Yii2 advanced app version 2.0.11, IDE I am using is PHPStorm
QUESTION:
What I want to achieve is to not use use keyword at the beggining of every class but still be able to simply call AppHelper::myMethod() in models, controllers and views.
How is that possible?
Closest I got it working was using this solution https://stackoverflow.com/a/35160997/5395463
All other solutions did not work for me. I am getting errors like:
PHP Fatal Error – yii\base\ErrorException
Class 'frontend\controllers\AppHelper' not found
when I simply dont include use commons\commands\AppHelper;
or when not using namespace as they suggest there with other settings:
Fatal error: Uncaught exception 'yii\base\UnknownClassException'
with message 'Unable to find 'common\commands\AppHelper'
in file: C:\xampp\htdocs\domain.com\web\common/commands/AppHelper.php.
Namespace missing?' in ...
SOLUTION:
Thanks for your responses, I got it working finaly. https://stackoverflow.com/a/42330631/5395463 solution works best for me.
So I removed namespace from that class, but left it in common\commands folder, added require to frontend/web/index.php and backend/web/index.php files (not sure if I should add it to yii file in root too, I didnt, so far it is working good anyways), and changed calls of class from AppHelper::myMethod() to \AppHelper::myMethod() looks like eveything is working now.
In Yii2 You can use an explicit way adding \ to full namespaced name
\frontend\controllers\AppHelper
so you can sue your method
\frontend\controllers\AppHelper::yourMethod();
Solution for not lazy coders:
create component with your class so you can use it like \Yii::$app->my_component
if even this is too much and your IDE is better than Windows Notepad prepare macro that will print this for you
Solution for lazy coders:
Save your class in single PHP file without namespace.
Modify you entry script to include this class - i.e. for Basic Project Template it's /web/index.php; add there
require(__DIR__ . '/path/to/MyClass.php');
For Advanced Project Template modify it properly.
Now you can use your class by calling it like \MyClass (yes, \ is required and yes, your IDE probably will modify it anyway to MyClass with use MyClass; added at the beginning.

Grails package change for domain class caused DuplicateMappingException

While working through a tutorial to start learning Grails, I made a mistake and ran:
grails create-domain-class com.FooBar
instead of:
grails create-domain-class com.acme.FooBar
It was immediately obvious I had made an error so I tried the following:
Searched for a function that reverses the create-domain-class command, it seems there isn't one.
Searched for advice on the web and the consensus is that you can delete a domain class file, any associated views and tests, then to be safe run a text search for your class name in your project directory for any references you may have missed. I have done all this.
Then I ran the correct command to create com.acme.FooBar, which worked.
After this the app fails to run and reports the following error:
org.hibernate.DuplicateMappingException: duplicate import: FooBar refers to both com.acme.FooBar and com.FooBar (try using auto-import="false")
After adding the following code to com.acme.FooBar:
...
static mapping = {
autoImport false
}
...
The app now runs as expected.
However as an experienced Java developer who occasionally does refactor a package I would like to understand how to do that without causing a DuplicateMappingException or resorting to the "autoImport false" solution.
Thanks.
You shouldn't be doing
static mapping = {
autoImport false
}
As, by doing this you said that don't check for domain just by name and look up for package as well. Hence, once you do that you will have to use Fully qualified name of the class in your queries / hqls which may itch sometimes.
You should be removing the Domain completely i.e.
remove the Domain
remove the view folder creating by default with very same name and so do the controller
Now, do grails clean-all(Make it a thumb rule to use grails clean-all first for any issue unexpectedly occuring).
To be more accurate do remove target directory from your project and then do run grails run-app.
I had done very same thing many times and got it resolved by above steps.
Hope it helps.

Is better Razor diagnostics change now included in ServiceStack v3.9.45?

As I'm still getting HttpCompilationException (External Exception) when I work through Mono on Mac with no hint as to what the real error is within Razor. To test it I'm binding to an invalid property name in a model. If I use the correct property name it works.
The project has GitHub issue here: https://github.com/ServiceStack/ServiceStack/pull/561
Is this change now included in v3.9.45? Do I have to do anything extra to enable it? I've got DebugMode on but that just adds stack trace data.
The Razor support was rewritten and my original change to improve the debugging experience wasn't carried forward (originally). It's now been added, see this comment:
https://github.com/ServiceStack/ServiceStack/pull/561#issuecomment-18204358
And this is the pull request that added it.
https://github.com/ServiceStack/ServiceStack/pull/684
It was included as of 3.9.47