Self Hosted ASP.NET Web API: how to embed images? - asp.net-web-api

I switched my ASP.NET Web API from IIS-hosted to self-hosted. So far I had my images deployed in its own folder (and accessed them with HostingEnvironment.MapPath). Obviously this folder doesn't exist in a self hosted environment. How can I handle images instead?

OK, I figured it out. Here's what I did:
set Build Action of each image as Embedded Resource
replace my MapPath with the following piece of code:
var resourcePath = "My.Namespace." + iconPath; //iconPath = subfolder.subfolder.file.ext
using (Stream imageStream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream(resourcePath))
{
...

Related

Uploading images to Windows Server and making them available publicly

I am trying to upload images in my windows server VM "hosted on-premise" and make these images available publicly like www.example.com/imageFolder/cat.png.
This VM has IIS enabled (I am not sure if IIS is related here) and it is assigned a URL and available publicly.
Aside from any programming languages or frameworks, I just want to know if storing the image in the server and making it available via a link is possible? If so, how can I achieve it?
To clarify further:
I believe what I want is very simple and tedious.
Consider the following workflow:
Run an API that has end points to receive images on the server.
Store the messages in the server.
Return the link that points to the picture.
I want to know the procedure from the windows server side like
Do I need to set certain properties on the folder where I will store the images?
Do I need to add a site to show the images back to the user?
I am a developer and I am new to the Windows Server & IIS so I may not have all the fundamentals.
I made a sample by using ASP.NET MVC5. You can follow this article to upload image in MVC5 application.
Upload Images on Server Folder Using ASP.NET MVC
Then, I do some changes so that it can display the url of images..
[HttpPost]
public ActionResult Upload(HttpPostedFileBase file)
{
Uri requestUri = HttpContext.Request.Url;
string baseUrl = requestUri.Scheme + Uri.SchemeDelimiter + requestUri.Host + (requestUri.IsDefaultPort ? "" : ":" + requestUri.Port);
if (ModelState.IsValid)
{
try
{
if (file != null)
{
string path = Path.Combine(Server.MapPath("~/Images"), Path.GetFileName(file.FileName));
file.SaveAs(path);
}
string link = baseUrl + "/Images/" + file.FileName;
ViewBag.FileStatus = "File uploaded successfully.";
//Return the url of image
ViewBag.FileLink = link;
}
catch (Exception e)
{
ViewBag.FileStatus = "Error while file uploading. Error message is "+e.Message;
}
}
return View("Index");
}
Index.cshtml add this to show url.
<div class="col-md-offset-2 col-md-10 text-success">
#ViewBag.FileLink
</div>
Don't forget to add a folder named Images to store images. After publishing, you also need to add it in published folder, otherwise error message will show that cannot find folder.
It works well.

How do I access BlockBlobClient in Azure Storage JavaScript client library for browsers?

I'm attempting to use BlockBlobClient in a browser page to upload a file using a server-supplied sastoken / URL, similar to this C# code:
var blob = new CloudBlockBlob(new Uri(assetUploadUrl));
blob.UploadFromFile(FilePath, null, new BlobRequestOptions {RetryPolicy = new ExponentialRetry()});
Although the docs suggest BlockBlobClient is available in #azure/storage-blob and should be able to upload browser data from an input[type=file] element using uploadBrowserData, I can find no reference to BlockBlobClient in the browser library source. I looked into modifying the browserify export scripts but I can't find any references in the main package source either. Also the example code suggests that using #azure/storage-blog gives you a BlobServiceClient by default:
const { BlobServiceClient } = require("#azure/storage-blob");
Is BlockBlobClient actually available in the JavaScript client library?
Okay I've figured this out, I need to use the Azure Storage client library for JavaScript, there's even a sample of doing exactly what I need to do. Now I just need to figure out how to bundle npm package files for use in Razor pages.

Calls From External Web Components in PWAs [duplicate]

We are running 2 servers. Server 1 hosts a react application. Server 2 hosts a webcomponent exposed as a single javascript bundle along with some assets such as images. We are dynamically loading the webcomponent Javascript hosted on Server 2 in our react app hosted on Server 1. The fact that it is a webcomponent might or might not affect the issue.
What's happening is that the webcomponent makes uses of assets such as images that are located on Server 2. But when the react app loads the webcomponent, the images are not found as its looking for the images locally on Server 1.
We can fix this in many ways. I am looking for the simplest fix. Since Server 1 app and Server 2 apps are being developed by different teams both should be able to develop in the most natural way possible without making allowances for their app being potentially loaded by other apps.
The fixes that I could think of was:
Making use of absolute URLs to load assets - Need to know the deployed location in advance .
Adding a reverse proxy to Server 1 to redirect to Server 2 whenever a particular path is hit - Need to configure this. The React app could load hundreds of webcomponents, viz we need add a lot of reverse proxies.
Embed all assets into the single javascript on Server 2, like embed svgs into the javascript. - Too limiting. If the SVGs are huge and will make the bundle size bigger.
I was hoping to implement something like -
Since the react app knows where to hit Server 2, can't we write some clever javascript that will make the browser go to Server 2 whenever assets are requested by a Javascript loaded by Server 2.
If you download your Web Component via a classic script (<script> with default type="text/javascript") you can retrieve the URL of the loaded file by using document.currentScript.src.
If you download the file as a module script (<script> with type="module"), you can retrieve the URL by using import.meta.url.
Parse then the property to extract the base path to the Web Component.
Example of Web Component Javascript file:
( function ( path ) {
var base = path.slice( 0, path.lastIndexOf( '/' ) )
customElements.define( 'my-comp', class extends HTMLElement {
constructor() {
super()
this.attachShadow( { mode: 'open' } )
.innerHTML = `<img src="${base}/image.png">`
}
} )
} ) ( document.currentScript ? document.currentScript.src : import.meta.url )
How about uploading all required assets to a 3rd location, or maybe an AWS S3 bucket, Google Drive, Dropbox etc.? That way those assets always have a unique, known URL, and both teams can access them independently. As long as the names remain the same, so will the URLs.

Load Unmanaged dll reference in ASP.NET MVC Core 1.0 (Aka) ASP.net 5 MVC 6

This question relates to an ASP.NET MVC WEP API, and Naudio
what I want
I was working prototype in WPF appliations when I use this code the wav file is converted to mp3
var retMs = new MemoryStream();
using (var ms = new MemoryStream(File.ReadAllBytes("sound.wav")))
using (var rdr = new WaveFileReader(ms))
using (var wtr = new LameMP3FileWriter(retMs, rdr.WaveFormat, 128))
{
rdr.CopyTo(wtr);
}
return retMs.ToArray();
But when using this code in api project I am getting error like this
Unable to load DLL 'libmp3lame.dll': The specified module could not be
found.
I know libmp3lame is unmanged dll, the WPF project I just copy the dll to bin folder and everything works fine, but how can I achieve this in Web API project, I mean asp.net 5 project
Note
the above code is working expected in wpf project
Also now I am only supported in my API is dotnetframwork means windows only
I removed other platform dependencies
Update:
Created Issue in ASP.Net MVC Repo
I'm a little late to the party but I'll share this for posterity. NAudio can convert a WAVE to an MP3 without the unmanaged DLL to avoid this issue all together. The only snag is it has to write out to a file (which can then be read back in). Assuming you have a MemoryStream where you read all the bytes in (like you did):
using (var wfr = new WaveFileReader(ms))
{
MediaFoundationApi.Startup();
MediaFoundationEncoder.EncodeToMp3(wfr, #"C:\Temp\test.mp3", 48000);
MediaFoundationApi.Shutdown();
}
Sounds like an issue with getting the mapping to the module in the bin library path, check out the following as may help -
How to get bin folder in ASP.NET Core 1.0
MVC4 App "Unable to load DLL 'libmp3lame.32.dll'

(UWP) WebClient and downloading data from URL in

How do you download data from an url in UWP? I'm used to using WebClient's DownloadData-method, but it can't be used anymore.
.NET for UWP does not have the WebClient class.
But you have several alternative ways to download the data from URL in UWP.
For example:
var request = WebRequest.CreateHttp("http://www.bing.com");
var donnetClient = new System.Net.Http.HttpClient();
var winrtClient = new Windows.Web.Http.HttpClient();
If you want to download the data at background, you can use the BackgroundDownloader class

Resources