Modify contents of static files - asp.net

how can I modify the response before it is sent to the client when I use Microsoft.Owin.StaticFiles?
FileServerOptions options = new FileServerOptions();
options.FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(Path.Combine(Environment.CurrentDirectory, "Content/"));
options.DefaultFilesOptions.DefaultFileNames = new string[] { "index.htm", "index.html" };
options.StaticFileOptions.OnPrepareResponse = (r) =>
{
r.OwinContext.Response.WriteAsync("test");
};
options.EnableDefaultFiles = true;
app.UseFileServer(options);
"test" is never written into the response. I tried to use another middleware which waits until the StaticFiles Middleware is executed:
app.Use((ctx, next) =>
{
return next().ContinueWith(task =>
{
return ctx.Response.WriteAsync("Hello World!");
});
});
FileServerOptions options = new FileServerOptions();
options.FileSystem = new Microsoft.Owin.FileSystems.PhysicalFileSystem(Path.Combine(Environment.CurrentDirectory, "Content/"));
options.DefaultFilesOptions.DefaultFileNames = new string[] { "index.htm", "index.html" };
options.EnableDefaultFiles = true;
app.UseFileServer(options);
But this didn't work. How can I modify the response?

On prepare response is not meant to modify the content of a static file.
You are only allowed to add the header.
I needed to pass some variable that change to a static web page and I got around it by using
On prepare response and passed the variables as cookies for the page.
This works nicely for a few variables but if you want to change a page significantly you are better of using mvc components.
appBuilder.UseStaticFiles(new StaticFileOptions()
{
RequestPath = new PathString(baseUrl),
FileSystem = new PhysicalFileSystem(staticFilesLocation),
ContentTypeProvider = new JsonContentTypeProvider(),
OnPrepareResponse = r => r.OwinContext.Response.Cookies.Append("baseUrl",_webhostUrl)
});

Related

How do I create a CSharpCompilation using Roslyn in Blazor WebAssembly?

I am trying to write a Blazor WebAssembly (WASM) app that accepts some code (from some text input field) and compiles the code using Roslyn.
I'm using Roslyn's CSharpCompilation class to create the compilation. Its Create method takes four parameters, one of which is a list of MetadataReferences (aka assembly references). In other (non-blazor) type applications, like a C# console app, you could get these MetadataReferences based on Asssembly Location, like this:
var locatedAssemblies = AppDomain.CurrentDomain.GetAssemblies().Where(a => !string.IsNullOrEmpty(a.Location)).ToArray();
foreach (var assembly in locatedAssemblies)
{
MetadataReference reference = MetadataReference.CreateFromFile(assembly.Location);
}
This unfortunately no longer works in Blazor WASM, because the Locations of the assemblies are empty.
I had tried getting assemblies in different ways, like AppDomain.CurrentDomain.GetAssemblies() and Assembly.GetEntryAssembly().GetReferencedAssemblies(), but all had empty Locations. I also tried calling Assembly.Load(), but to no avail.
Does anyone know how to get MetadataReferences in Blazor WASM, or how I would otherwise create a compilation in Blazor WASM?
(I'm also aware of MetadataReference.CreateFromStream() that I'll probably need to use, but it still requires the assembly location).
Thanks in advance.
I also wanted to compile C# inside a Blazor WASM app and found your question without an answer. After some digging I was able to create a working demo (repo link below.) Basically get the bytes for each assembly with HttpClient and use MetadataReference.CreateFromImage(bytes).
Full basic example repo I created: https://github.com/LostBeard/BlazorWASMScriptLoader
ScriptLoaderService.cs source:
using Microsoft.AspNetCore.Components;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.Emit;
using Microsoft.CodeAnalysis.Text;
using System.Collections.Immutable;
using System.Reflection;
namespace BlazorWASMScriptLoader
{
// requires "Microsoft.CodeAnalysis.CSharp"
// can be added via nuget
public class ScriptLoaderService
{
HttpClient _httpClient = new HttpClient();
public ScriptLoaderService(NavigationManager navigationManager)
{
_httpClient.BaseAddress = new Uri(navigationManager.BaseUri);
}
async Task<MetadataReference?> GetAssemblyMetadataReference(Assembly assembly)
{
MetadataReference? ret = null;
var assmeblyName = assembly.GetName().Name;
var assemblyUrl = $"./_framework/{assmeblyName}.dll";
try
{
var tmp = await _httpClient.GetAsync(assemblyUrl);
if (tmp.IsSuccessStatusCode)
{
var bytes = await tmp.Content.ReadAsByteArrayAsync();
ret = MetadataReference.CreateFromImage(bytes);
}
}
catch { }
return ret;
}
public async Task<Assembly?> CompileToDLLAssembly(string sourceCode, string assemblyName = "")
{
if (string.IsNullOrEmpty(assemblyName)) assemblyName = Path.GetRandomFileName();
var codeString = SourceText.From(sourceCode);
var options = CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp11);
var parsedSyntaxTree = SyntaxFactory.ParseSyntaxTree(codeString, options);
var appAssemblies = Assembly.GetEntryAssembly()?.GetReferencedAssemblies().Select(o => Assembly.Load(o)).ToList();
appAssemblies.Add(typeof(object).Assembly);
var references = new List<MetadataReference>();
foreach (var assembly in appAssemblies)
{
var metadataReference = await GetAssemblyMetadataReference(assembly);
if (metadataReference == null)
{
// assembly may be located elsewhere ... handle if needed
continue;
}
var metadataReferene = metadataReference;
references.Add(metadataReferene);
}
CSharpCompilation compilation = CSharpCompilation.Create(
assemblyName,
syntaxTrees: new[] { parsedSyntaxTree },
references: references,
options: new CSharpCompilationOptions(
OutputKind.DynamicallyLinkedLibrary,
concurrentBuild: false,
optimizationLevel: OptimizationLevel.Debug
)
);
using (var ms = new MemoryStream())
{
EmitResult result = compilation.Emit(ms);
if (!result.Success)
{
IEnumerable<Diagnostic> failures = result.Diagnostics.Where(diagnostic =>
diagnostic.IsWarningAsError ||
diagnostic.Severity == DiagnosticSeverity.Error);
foreach (Diagnostic diagnostic in failures)
{
Console.Error.WriteLine("{0}: {1}", diagnostic.Id, diagnostic.GetMessage());
}
return null;
}
else
{
ms.Seek(0, SeekOrigin.Begin);
var assembly = Assembly.Load(ms.ToArray());
return assembly;
}
}
}
}
}

Download multiple files (50mb) blazor server-side

i can't really find a way to download a 100mb zip file from the server to the client and also show the progress while downloading. So how will this look for a normal api controller i can add to my server-side project? if lets say i have 3 files i want to download at 50mb each.
i have tried using JSInterop like this, but this is not showing the progress of the file download, and how will i do if i want to download 3 seperate files at the same time?
try
{
//converting file into bytes array
var dataBytes = System.IO.File.ReadAllBytes(file);
await JSRuntime.InvokeVoidAsync(
"downloadFromByteArray",
new
{
ByteArray = dataBytes,
FileName = "download.zip",
ContentType = "application/force-download"
});
}
catch (Exception)
{
//throw;
}
JS:
function downloadFromByteArray(options: {
byteArray: string,
fileName: string,
contentType: string
}): void {
// Convert base64 string to numbers array.
const numArray = atob(options.byteArray).split('').map(c => c.charCodeAt(0));
// Convert numbers array to Uint8Array object.
const uint8Array = new Uint8Array(numArray);
// Wrap it by Blob object.
const blob = new Blob([uint8Array], { type: options.contentType });
// Create "object URL" that is linked to the Blob object.
const url = URL.createObjectURL(blob);
// Invoke download helper function that implemented in
// the earlier section of this article.
downloadFromUrl({ url: url, fileName: options.fileName });
// At last, release unused resources.
URL.revokeObjectURL(url);
}
UPDATE:
if im using this code, it will show me the progress of the file. But how can i trigger it from my code? This way does not do it. But typing the url does.
await Http.GetAsync($"Download/Model/{JobId}");
Controller
[HttpGet("download/model/{JobId}")]
public IActionResult DownloadFile([FromRoute] string JobId)
{
if (JobId == null)
{
return BadRequest();
}
var FolderPath = $"xxxx";
var FileName = $"Model_{JobId}.zip";
var filePath = Path.Combine(environment.WebRootPath, FolderPath, FileName);
byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
return File(fileBytes, "application/force-download", FileName);
}
UPDATE 2!
i have got it download with progress and click with using JSInterop.
public async void DownloadFiles()
{
//download all selectedFiles
foreach (var file in selectedFiles)
{
//download these files
await JSRuntime.InvokeAsync<object>("open", $"Download/Model/{JobId}/{file.Name}", "_blank");
}
}
Now the only problem left is.. it only downloads the first file out of 3.

Response on created context keeps giving me NullStream

I'm trying to write a middleware for batch requests i .net core 2.0.
So far the I have splitted the request, pipe each request on to the controllers.
The controllers return value, but for some reason the response on the created context that I parse to the controllers keeps giving me a NullStream in the body, so I think that there is something that I miss in my setup.
The code looks like this:
var json = await streamHelper.StreamToJson(context.Request.Body);
var requests = JsonConvert.DeserializeObject<IEnumerable<RequestModel>>(json);
var responseBody = new List<ResponseModel>();
foreach (var request in requests)
{
var newRequest = new HttpRequestFeature
{
Body = request.Body != null ? new MemoryStream(Encoding.ASCII.GetBytes(request.Body)) : null,
Headers = context.Request.Headers,
Method = request.Method,
Path = request.RelativeUrl,
PathBase = string.Empty,
Protocol = context.Request.Protocol,
Scheme = context.Request.Scheme,
QueryString = context.Request.QueryString.Value
};
var newRespone = new HttpResponseFeature();
var requestLifetimeFeature = new HttpRequestLifetimeFeature();
var features = CreateDefaultFeatures(context.Features);
features.Set<IHttpRequestFeature>(newRequest);
features.Set<IHttpResponseFeature>(newRespone);
features.Set<IHttpRequestLifetimeFeature>(requestLifetimeFeature);
var innerContext = _factory.Create(features);
await _next(innerContext);
var responseJson = await streamHelper.StreamToJson(innerContext.Response.Body);
I'm not sure what it is I'm missing in the setup, since innerContext.Response.Body isn't set.
One of the endpoints that I use for testing and that gets hit looks like this
[Route("api/[controller]")]
public class ValuesController : Controller
{
// GET api/values
[HttpGet]
public IEnumerable<string> Get()
{
return new string[] { "value1", "value2" };
}
}
I found the error, or two errors for it to work.
First I had to change my newResponse to
var newRespone = new HttpResponseFeature{ Body = new MemoryStream() };
Since HttpResponseFeature sets Body to Stream.Null in the constructor.
When that was done, then Body kept giving an empty string when trying to read it. That was fixed by setting the Position to Zero like
innerContext.Response.Body.Position = 0;

Result of the "R Script" without ColumnNames

I'm going crazy!
I'm using Azure Machine Learning and R Script. I deploy it as Web Service. I use sample code based on HttpClient.
using (var client = new HttpClient())
{
var scoreRequest = new
{
Inputs = new Dictionary<string, StringTable>() {
{
"input1",
new StringTable()
{
ColumnNames = new string[] {
"experts_estimates",
"experts_share_of_unique_information",
"avg_correlation",
"point_a",
"point_b",
"is_export_mode"
},
Values = new string[,] {
{
expertsEstimatesStr,
expertsShareOfUniqueInformationStr,
avgCorrelationStr,
pointAStr,
pointBStr,
isExportModeStr
},
}
}
},
},
GlobalParameters = new Dictionary<string, string>()
{
}
};
client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
client.BaseAddress = new Uri(apiUrl);
// WARNING: The 'await' statement below can result in a deadlock
// if you are calling this code from the UI thread of an ASP.Net application.
// One way to address this would be to call ConfigureAwait(false)
// so that the execution does not attempt to resume on the original context.
// For instance, replace code such as:
// result = await DoSomeTask()
// with the following:
// result = await DoSomeTask().ConfigureAwait(false)
HttpResponseMessage response = await client.PostAsJsonAsync("", scoreRequest);
if (response.IsSuccessStatusCode)
{
string result = await response.Content.ReadAsStringAsync();
return result;
}
else
{
// Print the headers - they include the requert ID and the timestamp,
// which are useful for debugging the failure
var headers = response.Headers.ToString();
string responseContent = await response.Content.ReadAsStringAsync();
throw new Exception(responseContent, new Exception(headers));
}
}
and when I run code from Visual Studio I get:
but when I run code from Azure App Service I get:
Any ideas?
One solution is adding "edit metadata" module inside the model and rename the output columns. It'll be easy than using the code to name the columns.

Post data with free-jqgrid, what are the code in client and Web API side?

I am using ASP.NET MVC 6 Web API. In the View I use free-jqgrid.
Let's borrow Oleg's free jqgrid data to demonstrate my purpose. We already have the table shown.
Next I am going to add new Vendor. Please notify that there is primary key id(identity column) in the database. We don't want it displaying in the screen.
In VendorRespository.cs, I add the new Vendor as
public void AddVendor(Vendor item)
{
using (VendorDataContext dataContext = new VendorDataContext())
{
dataContext.Database.Connection.ConnectionString = DBUtility.GetSharedConnectionString(
"http://centralized.admin.test.com");
var newVendor = dataContext.Vendors.Create();
newVendor.Company = item.Company;
newVendor.ContactName = item.ContactName;
newVendor.ContactPhone = item.ContactName;
newVendor.UserName = item.UserName;
newVendor.UserKey = item.UserKey;
newVendor.Active = item.Active;
newVendor.FacilityId =item.FacilityId;
newVendor.ClientID = item.ClientID;
dataContext.SaveChanges();
}
}
My questions:
Not sure the script like?
<script>
API_URL = "/VendorManagement/";
function updateDialog(action) {
return {
url: API_URL
, closeAfterAdd: true
, closeAfterEdit: true
, afterShowForm: function (formId) { }
, modal: true
, onclickSubmit: function (params) {
var list = $("#jqgrid");
var selectedRow = list.getGridParam("selrow");
rowData = list.getRowData(selectedRow);
params.url += rowData.Id;
params.mtype = action;
}
, width: "300"
};
}
jQuery("#jqgrid").jqGrid('navGrid',
{ add: true, edit: true, del: true },
updateDialog('PUT'),
updateDialog('POST'),
updateDialog('DELETE')
);
In the controller, not sure what is the code?
// POST
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("DefaultApi", new { id = item.Id });
response.Headers.Location = new Uri(uri);
return response;
}
My code has many compiling errors such as
'HttpRequest' does not contain a definition for 'CreateResponse' and the best extension method overload 'HttpRequestMessageExtensions.CreateResponse(HttpRequestMessage, HttpStatusCode, Vendor)' requires a receiver of type 'HttpRequestMessage'
Please help me to get rid of the error and inappropriate code.
EDIT:
I borrowed the code snippet from here.
I need add the code such as
[Microsoft.AspNet.Mvc.HttpGet]
public dynamic GetVendorById(int pkey)
{
return null;
}
And
// POST
[System.Web.Http.HttpPost]
public HttpResponseMessage PostVendor(Vendor item)
{
_vendorRespository.AddVendor(item);
var response = Request.CreateResponse<Vendor>(HttpStatusCode.Created, item);
string uri = Url.Link("/VendorManagement/GetVendorById", new { id = item.pkey });
response.Headers.Location = new Uri(uri);
return response;
}

Resources