I built an assembly containing one js file.
I marked the file as Embedded Resource and added it into AssemblyInfo file.
I can't refernce the Assembly from a web site. It is in the bin folder but I don't see the reference to it.
It seems like not having at least a class inside the assembly I can't reference it.
I would include the js file into my pages from the assembly.
How should I do this?
Thanks
I do exactly the same thing in one of my projects. I have a central ScriptManager class that actually caches the scripts as it pulls them, but the core of extracting the script file from the embedded resource looks like this:
internal static class ScriptManager
{
private static Dictionary<string, string> m_scriptCache =
new Dictionary<string, string>();
public static string GetScript(string scriptName)
{
return GetScript(scriptName, true);
}
public static string GetScript(string scriptName, bool encloseInCdata)
{
StringBuilder script = new StringBuilder("\r\n");
if (encloseInCdata)
{
script.Append("//<![CDATA[\r\n");
}
if (!m_scriptCache.ContainsKey(scriptName))
{
var asm = Assembly.GetExecutingAssembly();
var stream = asm.GetManifestResourceStream(scriptName);
if (stream == null)
{
var names = asm.GetManifestResourceNames();
// NOTE: you passed in an invalid name.
// Use the above line to determine what tyhe name should be
// most common is not setting the script file to be an embedded resource
if (Debugger.IsAttached) Debugger.Break();
return string.Empty;
}
using (var reader = new StreamReader(stream))
{
var text = reader.ReadToEnd();
m_scriptCache.Add(scriptName, text);
}
}
script.Append(m_scriptCache[scriptName]);
if (encloseInCdata)
{
script.Append("//]]>\r\n");
}
return script.ToString();
}
}
EDIT
To provide more clarity, I've posted my ScriptManager class. To extract a script file, I simply call it like this:
var script = ScriptManager.GetScript("Fully.Qualified.Script.js");
The name you pass in it the full, case-sensitive resource name (the exception handler gets a list of them by calling GetManifestResourceNames()).
This gives you the script as a string - you can then put it out into a file, inject it into the page (which is what I'm doing) or whatever you like.
Assembly myAssembly = // Get your assembly somehow (see below)...
IList<string> resourceNames = myAssembly.GetManifestResourceNames();
This will return a list of all resource names that have been set as 'Embedded Resource'. The name is usually the fully qualified namespace of wherever you put that JS file. So if your project is called My.Project and you store your MyScript.js file inside a folder in your project called Resources, the full name would be My.Project.Resources.MyScript.js
If you then want to use that JS file:
Stream stream = myAssembly.GetManifestResourceStream(myResourceName);
Where myResourceName argument might be "My.Project.Resources.MyScript.js". To get that JS file in that Stream object, you'll need to write it as a file to the hard drive, and serve it from your website as a static file, something like this:
Stream stream = executingAssembly.GetManifestResourceStream(imageResourcePath);
if (stream != null)
{
string directory = Path.GetDirectoryName("C:/WebApps/MyApp/Scripts/");
using (Stream file = File.OpenWrite(directory + "MyScript.js"))
{
CopyStream(stream, file);
}
stream.Dispose();
}
And the code for CopyStream method:
private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
You might want to stick all this code in an Application_Start event in your Global.asax. You don't want it to run for each request
Now getting a reference to your Assembly is a different matter, there are many ways. One way is to include all the above code in your Assembly in question, then make sure you reference that Assembly from your main WebApp project in Visual Studio, then get a reference to the currently executing Assembly like so.
namespace My.Project
{
public class ResourceLoader
{
public static void LoadResources()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
// rest of code from above (snip)
}
}
}
Then call ResourceLoader.LoadResources() from your Application_Start event in your Global.asax.
Hope this helps
Fully working example (I hope):
namespace TestResources.Assembly
{
public class ResourceLoader
{
public static void LoadResources()
{
Assembly myAssembly = Assembly.GetExecutingAssembly();
Stream stream = myAssembly
.GetManifestResourceStream("TestResources.Assembly.CheckAnswer.js");
if (stream != null)
{
string directory = Path.GetDirectoryName("C:/WebApps/MyApp/Scripts/");
using (Stream file = File.OpenWrite(directory + "MyScript.js"))
{
CopyStream(stream, file);
}
stream.Dispose();
}
}
private static void CopyStream(Stream input, Stream output)
{
byte[] buffer = new byte[8 * 1024];
int len;
while ((len = input.Read(buffer, 0, buffer.Length)) > 0)
{
output.Write(buffer, 0, len);
}
}
}
}
Some caveats:
Change "C:/WebApps/MyApp/" to wherever your web app is located, maybe write some code to work this out dynamically
Make sure the /Scripts folder exists in your webapp root
I think it will overwrite the 'MyScript.js' file if it already exists, but just in case you might want to add some code to check for that file and delete it
Then stick a call to this code in your Global.asax file:
protected void Application_Start()
{
ResourceLoader.LoadResources();
}
Then the path for your web site will be /Scripts/MyScript.js eg:
<head>
<!-- Rest of head (snip) -->
<script type="text/javascript" src="/Scripts/MyScript.js"></script>
</head>
Related
In .Net MAUI Blazor I can use an img tag to display an image from wwwroot folder. But how to display an image from the device's internal storage? And how to display images from application resources?
From Internal storage
We can read it into bytes and convert it to base64 string , then show on img tag .
Giving that we've put an image called dog.png in FileSystem.CacheDirectory folder.
Sample code
#if (imageSource is not null)
{
<div>
<img src="#imageSource" width="200" height="200" />
</div>
}
#code {
private string? imageSource;
protected override void OnInitialized()
{
var newFile = Path.Combine(FileSystem.CacheDirectory, "dog.png");
var imageBytes = File.ReadAllBytes(newFile);
imageSource = Convert.ToBase64String(imageBytes);
imageSource = string.Format("data:image/png;base64,{0}", imageSource);
}
}
To display from resource, see … Blazor Hybrid static Files / .Net Maui:
Add file to project, in a folder named Resources/Raw.
Make sure file / Properties / Build Action = MauiAsset.
Create a razor component that:
Calls Microsoft.Maui.Storage.FileSystem.OpenAppPackageFileAsync to obtain a Stream for the resource.
Reads the Stream with a StreamReader.
Calls StreamReader.ReadToEndAsync to read the file.
Example razor code (from that link):
#page "/static-asset-example"
#using System.IO
#using Microsoft.Extensions.Logging
#using Microsoft.Maui.Storage
#inject ILogger<StaticAssetExample> Logger
<h1>Static Asset Example</h1>
<p>#dataResourceText</p>
#code {
public string dataResourceText = "Loading resource ...";
protected override async Task OnInitializedAsync()
{
try
{
using var stream =
await FileSystem.OpenAppPackageFileAsync("Data.txt");
using var reader = new StreamReader(stream);
dataResourceText = await reader.ReadToEndAsync();
}
catch (FileNotFoundException ex)
{
dataResourceText = "Data file not found.";
Logger.LogError(ex, "'Resource/Raw/Data.txt' not found.");
}
}
}
To access local file (not an asset in resources) from razor code, you’ll need a service that given the file name (or relative path), returns the file contents as a stream.
I’m not finding a doc saying how to do that for Maui, then inject that into razor code.
Such a service would use .Net File System Helpers to access the file. This would be similar to the MauiAsset example above, but using one of the path helpers, NOT calling OpenAppPackageFileAsync.
TBD - someone give reference link or example?
From my research :
You can actually get the path of the wwwroot folder in the razor application with : AppDomain.CurrentDomain.BaseDirectory.
In windows you can add files in this folder that will be accessible from the Blazor HTML. However, in Android the wwwroot folder is embeded in the app and will not be accessible (AppDomain.CurrentDomain.BaseDirectory return a empty folder).
After looking on the .NET MAUI github repo in the BlazorWebView class I found :
public virtual IFileProvider CreateFileProvider(string contentRootDir)
{
// Call into the platform-specific code to get that platform's asset file provider
return ((BlazorWebViewHandler)(Handler!)).CreateFileProvider(contentRootDir);
}
Which can be used to pass files to Blazor. For exemple if you want to make accessible all the files from the AppDataDirectory :
public class CustomFilesBlazorWebView : BlazorWebView
{
public override IFileProvider CreateFileProvider(string contentRootDir)
{
var lPhysicalFiles = new PhysicalFileProvider(FileSystem.Current.AppDataDirectory);
return new CompositeFileProvider(lPhysicalFiles, base.CreateFileProvider(contentRootDir));
}
}
Then in MainPage.xaml :
<local:CustomFilesBlazorWebView HostPage="wwwroot/index.html" x:Name="WebView">
<BlazorWebView.RootComponents>
<RootComponent Selector="#app" ComponentType="{x:Type local:Main}" />
</BlazorWebView.RootComponents>
</local:CustomFilesBlazorWebView>
For exemple if in AppDataDirectory you have a file images/user.png in any Blazor component you can use :
<img src="images/user.png" />
I solved in this way.
Add the png image to Resources\Raw and set to MauiAsset compilation type
Check the project file to avoid that the image is excluded via ItemGroup-> None Remove. In this case delete the ItemGroup related to the image.
After this:
In my razor component HTML
<img src="#imageSource">
In the code part:
private string? imageSource;
protected override async Task OnInitializedAsync()
{
try
{
using var stream =
await FileSystem.OpenAppPackageFileAsync("testimage.png");
using var reader = new StreamReader(stream);
byte[] result;
using (var streamReader = new MemoryStream())
{
stream.CopyTo(streamReader);
result = streamReader.ToArray();
}
imageSource = Convert.ToBase64String(result);
imageSource = string.Format("data:image/png;base64,{0}", imageSource);
}
catch (Exception ex)
{
//log error
}
}
strong text [Plugin error at Note entity][1]
[1]: http://i.stack.imgur.com/hRIi9.png
Hi,Anyone resolved my issue i got a Plug-in error which i worked at Update of "Note" entity.Basically i want a Plugin which converted pre-exiting Note attachment XML file into new .MMP extension file with the same name.
I have done following procedure firstly i created a "Converter_Code.cs" dll which contains Convert() method that converted XML file to .MMP file here is the constructor of the class.
public Converter(string xml, string defaultMapFileName, bool isForWeb)
{
Xml = xml;
DefaultMapFileName = defaultMapFileName;
Result = Environment.NewLine;
IsForWeb = isForWeb;
IsMapConverted = false;
ResultFolder = CreateResultFolder(MmcGlobal.ResultFolder);
}
In ConvertPlugin.cs Plug-in class firstly i retrieved Note entity attachment XML file in a string using following method in
IPluginExecutionContext context =(IPluginExecutionContext)serviceProvider.
GetService (typeof(IPluginExecutionContext));
IOrganizationServiceFactory serviceFactory= (IOrganizationServiceFactory)serviceProvider.GetService(typeof(IOrganizationServiceFactory));
IOrganizationService service = serviceFactory.CreateOrganizationService
(context.UserId);
if (context.InputParameters.Contains("Target")
&& context.InputParameters["Target"] is Entity)
{
// Obtain the target entity from the input parameters.
Entity entity = (Entity)context.InputParameters["Target"];
var annotationid = entity.GetAttributeValue<Guid>("annotationid");
if (entity.LogicalName != "annotation")
{
return;
}
else
{
try
{
//retrieve annotation file
QueryExpression Notes = new QueryExpression { EntityName ="annotation"
,ColumnSet = new ColumnSet("filename", "subject", "annotationid",
"documentbody") };
Notes.Criteria.AddCondition("annotationid", ConditionOperator.Equal,
annotationid);
EntityCollection NotesRetrieve = service.RetrieveMultiple(Notes);
if (NotesRetrieve != null && NotesRetrieve.Entities.Count > 0)
{
{
//converting document body content to bytes
byte[] fill = Convert.FromBase64String(NotesRetrieve.Entities[0]
.Attributes["documentbody"].ToString());
//Converting to String
string content = System.Text.Encoding.UTF8.GetString(fill);
Converter objConverter = new Converter(content, "TestMap", true);
objConverter.Convert();
}
}
}
catch (FaultException<OrganizationServiceFault> ex)
{
throw new InvalidPluginExecutionException("something is going wrong");
}
}
}
}
and than A string is passed to "Converter" constructor as a parameter.
finally i merged all dll using ILMerge following method:
ilmerge /out:NewConvertPlugin.dll ConvertPlugin.dll Converter_Code.dll
and NewConvertPlugin is registered successfully but while its working its generate following error:
Unexpected exception from plug-in (Execute): ConverterPlugin.Class1: System.Security.SecurityException: That assembly does not allow partially trusted callers.
i also debug the plugin using Error-log but its not worked so i could not get a reason whats going wrong.
The error is caused by the library you merged inside your plugin.
First of all you are using CRM Online (from your screenshot) and with CRM Online you can use only register plugins inside sandbox.
Sandbox means that your plugins are limited and they run in a partial-trust environment.
You merged an external library that requires full-trust permissions, so your plugin can't work and this is the reason of your error.
Because you are in CRM Online, or you find another library (the Converter) that requires only partial-trust, hoping that the merge process will work, or you include (if you have it) the source code of the converter library directly inside your plugin.
Given an application.wadl file, how do I generate Client app (Spring or any) and domain objects from a wadl file?
I tried :
wadl2java https://genologics.com/files/permanent/API/2.5/application.wadl
WADLToJava Error: java.lang.IllegalStateException: Single WADL resources element is expected
This is my findings by reviewing the source-code:
As SourceGenerator.java, wadltojava is trying to get the "resources" element from the "application" element and expects it to be one only.
private void generateResourceClasses(Application app, GrammarInfo gInfo,
Set<String> typeClassNames, File src) {
Element appElement = app.getAppElement();
List<Element> resourcesEls = getWadlElements(appElement, "resources");
if (resourcesEls.size() != 1) {
throw new IllegalStateException("Single WADL resources element is expected");
}
List<Element> resourceEls = getWadlElements(resourcesEls.get(0), "resource");
if (resourceEls.size() == 0) {
throw new IllegalStateException("WADL has no resource elements");
}
........
}
I checked the WADL you provided and seems like there is only one "resources" element.
On checking further in getWadlElements() method is using getWadlNamespace():
private List<Element> getWadlElements(Element parent, String name) {
List<Element> elements = parent != null
? DOMUtils.getChildrenWithName(parent, getWadlNamespace(), name)
: CastUtils.cast(Collections.emptyList(), Element.class);
if (!"resource".equals(name)) {
for (int i = 0; i < elements.size(); i++) {
Element el = elements.get(i);
Element realEl = getWadlElement(el);
if (el != realEl) {
elements.set(i, realEl);
}
}
}
return elements;
}
The namespace used here in WadlGenerator.java is
public static final String WADL_NS = "http://wadl.dev.java.net/2009/02";
But in your WADL the namespace seems to be different as below, and may be causing issue.
<wadl:application xmlns:wadl="http://research.sun.com/wadl/2006/10" xmlns:xs="http://www.w3.org/2001/XMLSchema">
It seems that you are using CXF so as per my understanding, I would suggest you to use the same framework which is used to generate the WADL.
Update:
Or, have the WADL and XSD's on your local and modify the namespace manually in WADL to the latest one and try again.
I have Download and Main cs files. The first one contains method LoadAsset
public IEnumerator LoadAsset(string link, string loadObject)
{
WWW download;
string ErrorMsg=" ";
download = new WWW(link);
yield return download;
if (download.error != null)
{
ErrorMsg=download.error;
}
else
{
ErrorMsg="Downloading ....";
AssetBundle asset = download.assetBundle;
GameObject loadedObject;
loadedObject = Instantiate(asset.Load(loadObject,typeof(GameObject))) as GameObject;
asset.Unload(false);
ErrorMsg="Done";
}
Debug.Log(ErrorMsg);
}
I want to call this method from Main.cs file and return loadedObject in it. Tried to use StartCoroutine
Download download;
download=new Download();
StartCoroutine("download.LoadAsset()");
but without success. Can anybody help me?
Try without the quotes
StartCoroutine( download.LoadAsset() )
You add the quotes when you want to cancel it, but it won't work on a method outside your class.
It would be event better to add a method to your Main.cs that starts the coroutine for you, something like this
public void StartLoadAssetCo()
{
StartCoroutine(LoadAsset());
}
and then just call StartLoadAssetCo from outside the class
download.StartLoadAssetCo();
I have successfully created a GMF editor which draws models based on my EMF model.What i wanted to do is to iterate through my model's EClasses .Can this be achieved at runtime through my plugin code without having to read the xml file that the gmf editor creates ?Is there such an API from EMF?
When you generate test code from the genmodel file then inside the XYZ.test plugin there is such type of code that i was searching.It traverses through the xmi file of your model
// Create a resource set to hold the resources.
//
ResourceSet resourceSet = new ResourceSetImpl();
// Register the appropriate resource factory to handle all file extensions.
//
resourceSet.getResourceFactoryRegistry().getExtensionToFactoryMap().put
(Resource.Factory.Registry.DEFAULT_EXTENSION,
new XMIResourceFactoryImpl());
// Register the package to ensure it is available during loading.
//
resourceSet.getPackageRegistry().put
(XYZmetamodelPackage.eNS_URI,
XYZmetamodelPackage.eINSTANCE);
// If there are no arguments, emit an appropriate usage message.
//
if (args.length == 0) {
System.out.println("Enter a list of file paths or URIs that have content like this:");
try {
Resource resource = resourceSet.createResource(URI.createURI("http:///My.metamodel"));
ModelObject root = atagmetamodelFactory.eINSTANCE.createModelObject();
resource.getContents().add(root);
resource.save(System.out, null);
}
catch (IOException exception) {
exception.printStackTrace();
}
}
else {
// Iterate over all the arguments.
//
for (int i = 0; i < args.length; ++i) {
// Construct the URI for the instance file.
// The argument is treated as a file path only if it denotes an existing file.
// Otherwise, it's directly treated as a URL.
//
File file = new File(args[i]);
URI uri = file.isFile() ? URI.createFileURI(file.getAbsolutePath()): URI.createURI(args[i]);
try {
// Demand load resource for this file.
//
Resource resource = resourceSet.getResource(uri, true);
System.out.println("Loaded " + uri);
// Validate the contents of the loaded resource.
//
for (EObject eObject : resource.getContents()) {
Diagnostic diagnostic = Diagnostician.INSTANCE.validate(eObject);
if (diagnostic.getSeverity() != Diagnostic.OK) {
printDiagnostic(diagnostic, "");
}
}
}
catch (RuntimeException exception) {
System.out.println("Problem loading " + uri);
exception.printStackTrace();
}
}
}
}