Application Cache Error event: Failed to parse manifest in C# MVC - asp.net-mvc

I have build App in C# MVC and I'm using HTML5 Application cache manifest for run application even if internet unavailable. my code is as below.
Controller (Home):
public ActionResult Manifest()
{
Response.ContentType = "text/cache-manifest";
return View();
}
View (Manifest.cshtml)
CACHE MANIFEST
NETWORK:
*
CACHE:
~/Scripts/stylesheets/bootstrap.min.css
FALLBACK:
#{
Layout = null;
}
Layout.cshtml
<html manifest="/Home/Manifest">
But i am getting Error : Application Cache Error event: Failed to parse manifest
does i need to include view.cshtml files path in Cache in Manifest file?
I have tried some solution posted earlier in stackoverflow but not found any solution.

I have resolved this issue in visual studio for MVC application. follow below steps:
I have created .appcache file in notepad and copy manifest file content into it. (you don't need to create .Manifest file OR Manifest.cshtml view. just create .appcache file in notepad.)
give reference as <html manifest="~/example.appcache"> in view and issue will be resolved

Related

Web optimizer .net core

Upgrading .net 4.8 mvc app to .net 6. I am keeping the static content in the same folders as in the previous web app project and using the web optimizer to minify and bundle.
I am seeing lot of console errors and the UI is not loading for the app
Layout cshtml
Script and Content folder
It may help if you could show how you configured in program.cs
I tried as the document :
In program.cs:
builder.Services.AddWebOptimizer(x =>x.AddJavaScriptBundle("/js/bundle.js", "js/chat/*.js"));
call
app.UseWebOptimizer();
before:
app.UseStaticFiles();
in chat.js:
console.log("chat");
in hellow.js:
console.log("hellow");
And my project:
in my View,I called:
<script src="/js/bundle.js"></script>
The result:
other document may help:
Update:
I tried to add two floders under the directory of the project as your comment and tried as below to fix the 404 error:
var provider1 = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Script1"));
var provider2 = new Microsoft.Extensions.FileProviders.PhysicalFileProvider(Path.Combine(builder.Environment.ContentRootPath, "Script2"));
builder.Services.AddWebOptimizer
(x =>
{    
x.AddJavaScriptBundle("/bundle1.js","/chat/*.js").UseFileProvider(provider1);
   x.AddJavaScriptBundle("/bundle2.js","/comment/*.js").UseFileProvider(provider2);
});
My project:

ActionFilterAttribute for Twilio RequestValidation example not working - why?

First, I'm newish to MVC so bear with me. I'm following the Twilio example located here to validate that status callbacks from Twilio are authentic: https://www.twilio.com/docs/usage/tutorials/how-to-secure-your-csharp-aspnet-app-by-validating-incoming-twilio-requests#create-a-custom-filter-attribute
The code provided as-is should be reviewed by Twilio as the constructor name has a typo in it as they have "RequestAttribute" in it twice.
My issue is that I cannot for the life of me get the Attribute to resolve when I place it on my controller. I noticed the example Action Filter has a namespace ending ".Filters" and I noticed that my MVC application does not have a "Filters" directory. Some googling indicated that may be a difference between MVC4 and 5 - from what I can tell I'm using MVC5 as that's the listed version number on the System.Web.Mvc reference (version 5.2.2.0 specifically if that matters).
Anyway, Twilio linked to Microsoft documentation on creating the Custom Action Filter here: https://learn.microsoft.com/en-us/previous-versions/aspnet/dd410056(v=vs.98)?redirectedfrom=MSDN
Microsoft suggests creating the Action Filter class directly in the "Controllers" directory - so that's where I placed mine. Here is how that class reads currently:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Twilio.Security;
using System.Net;
using System.Web.Mvc;
using System.Web.Mvc.Filters;
namespace SMSStatusWS.Controllers
{
public class ValidateTwilioRequestAttribute : System.Web.Mvc.ActionFilterAttribute
{
private readonly RequestValidator _requestValidator;
public ValidateTwilioRequestAttribute()
{
var authToken = "<--------REMOVED------->";
_requestValidator = new Twilio.Security.RequestValidator(authToken);
}
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
var context = actionContext.HttpContext;
if (!IsValidRequest(context.Request))
{
actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
base.OnActionExecuting(actionContext);
}
private bool IsValidRequest(HttpRequestBase request)
{
var signature = request.Headers["X-Twilio-Signature"];
var requestUrl = request.Url.AbsoluteUri;
return _requestValidator.Validate(requestUrl, request.Form, signature);
}
}
}
Then my attempt to use it...
[HttpPost]
[ValidateTwilioRequest ]
public ActionResult UpdateSmsStatus(string dbContext, string smsQueueId)
{
// Controller code here...
}
The attribute [ValidateTwilioRequest ] is highlighted in red in Visual Studio... meaning it can't resolve it (I guess) but I'm not sure why as the namespace is the same in both my controller class and the action filter class...
namespace SMSStatusWS.Controllers
So at this point, I'm not sure what's wrong here. As far as I can tell, the custom action filter was created correctly, and I'm using it as Twilio shows, but yet it doesn't work. Even though the filter does not seem to resolve, the project builds and runs... but of course it never hits the code in the action filter.
Is there some other way I need to reference this Action Filter that the docs are not telling me? Thoughts on what to try or look for that I may be overlooking?
UPDATE 10/13/21:
I have made some progress... turns out the attribute not resolving was related to Visual Studio. Not able to figure out why it wasn't resolving, I closed the solution and restarted Visual Studio and when I reopened it, it started resolving the attribute immediately. However, I'm not positive it's working as I can't hit a breakpoint in the OnActionExecuting override and Visual Studio says no symbols have loaded.
So new question now, how do you debug custom Action Filters? Shouldn't I be able to step into the code with the debugger?
You could you try using System.Diagnostics.Debug.WriteLine in the OnActionExecuting function and using that rather than the break point. That should write out to the output window and let you know if that code is running. After adding that code your OnActionExecuting function would look like this.
public override void OnActionExecuting(ActionExecutingContext actionContext)
{
string controller = actionContext.ActionDescriptor.ControllerDescriptor.ControllerName;
string action = actionContext.ActionDescriptor.ActionName;
System.Diagnostics.Debug.WriteLine("Controller-" + controller + ", Action-" + action);
var context = actionContext.HttpContext;
if (!IsValidRequest(context.Request))
{
actionContext.Result = new HttpStatusCodeResult(HttpStatusCode.Forbidden);
}
base.OnActionExecuting(actionContext);
}
Wow... learned a bit about Visual Studio and debugging today.The MVC project I have created for all of this had the project output set to a bin directory 2 levels up from my project. I'll call this the "global bin" - we use our global bin as a place for a lot of other projects to write their output to and that one location is referenced in our nightly build.
What I noticed is that my local project bin directory had an old DLL and PDB file in it, presumably from a build prior to changing the output directory to our global bin (global bin has the current dll and pdb). When debugging, I would notice that the debugger would load the dll and pdb from the "Temporary Asp.Net files" path (you can find this info in the "Module" window while debugging in Visual Studio) - this temp directory had those same old versions of the pdb in it and that is ultimately why I was unable to debug my Action Filter Attribute - it had an outdated pdb that did not have symbols for my latest code changes in it.
My band-aid for now is to set the output directory of my Project back to it's own local bin directory, and in web.config, disable shadowCopyBinAssemblies - which prevents the debugger from using the outdated pdb in the Temporary Asp.Net files directory and instead uses the pdb in the local bin.
That looks like this in web.config...
<system.web>
<hostingEnvironment shadowCopyBinAssemblies="false"/>
<system.web
I'm confused as to why Visual Studio doesn't shadowCopy the dll and pdb from our defined global bin (when it's defined as the project's output directory) to the Temporary Asp.Net files directory. That would solve all of this but I don't know if that can be configured anywhere.
As soon as I changed this to output to the project's bin directory and disabled the shadowCopy in web.config, the debugger loaded symbols from the correct dll and pdb and my breakpoints hit immediately.
I guess I'll add a post-build event or something to copy the dll & pdb files to our global bin so this doesn't break our nightly build, but this feels like a hack. If the default shadowCopy settings for the Temporary Asp.Net Files directory can't be changed I don't know what else to do about it. Is this a Visual Studio bug perhaps... shadowCopying from the project bin always, even if the output is configured to be written elsewhere?

Kentico 12 PageBuilder missing reference

In the _Layout.cshtml page, I receive this exception (IFeatureSet' does not contain a definition for 'PageBuilder' and no accessible extension method 'PageBuilder' accepting a first argument of type 'IFeatureSet' could be found).
Here is my code.
#{
var editMode = string.Empty;
if (HttpContext.Current.Kentico().PageBuilder().EditMode)
{
editMode = "kentico-page-builder";
}
}
The project won't build because of it. The project has been upgraded to Kentico 12.0.30 even though the dll version says 12.0.0 (See attached image)
I have restarted Visual Studio, my computer, cleared temp files, cleared cache. Nothing fixes it. Anyone have any ideas why?
The PageBuilder() extension method is located in the Kentico.PageBuilder.Web.Mvc namespace, so you need to add this to your view:
#using Kentico.PageBuilder.Web.Mvc
Or, you can follow the guidance in #3 in the Registering the page builder section on https://docs.kentico.com/k12/developing-websites/page-builder-development and register the namespace in the web.config of the /Views folder:
<add namespace="Kentico.PageBuilder.Web.Mvc"/>

CKEditor image dialog is failed

I worked with CKEditor on my .Net Mvc4 project. On localhost all works well, but after publishing project to server is not initialising:
"Uncaught TypeError: Cannot set property 'dir' of undefined"
I fixed this by adding code line before editor initialization:
CKEDITOR.basePath = '//some url/ckeditor/'
After that, the ckeditor is working but refusing to open image upload dialog:
error in ckeditor plugins image.js
Uncaught Error: [CKEDITOR.dialog.openDialog] Dialog "image" failed when loading definition.
There is no any changes in my ckeditor folder. The version is: 4.4.5
Any solutions please?
Check the "Network" tab in your browser for HTTP 404 errors. It looks like the file that contains Image Dialog definition is not available. Either it is not present (e.g. has been accidentally removed) or you have some weird url rewrite issues.
Check in your CKEDITOR.basePath plugins folder image plugin is in there, if not then add it and wala working like a charm ! hope it helps !
Issue
You are getting the error from only including the ckeditor.js (or ckeditor4.js since 4.13) file on server, with this error becoming raised when CKE attempts to load other features such as plugins and languages but cannot find these files in the basepath folder. You can confirm this from the network tab in browser devtools, as CKE attempts to load features, then cannot find them.
Option 1: Link to a CDN Bundle
CKE offers 3 primary bundles (basic, standard, full) which offer a choice between features and page load. More info here.
Option 2: Include Necessary Files
Make the extra files available on your server.
Here's a gulp task which bundles everything from the ckeditor node module folder (excluding the sample).
gulp.task("copy-ckeditor", function () {
// Check and copy languages in config.ckEditorLanguages
var isIncluded = function(path) {
var found = false,
lang = path.split('lang')[1];
if (lang) {
for (var i in config.ckEditorLanguages) {
if (lang.indexOf(config.ckEditorLanguages[i]) != -1) {
found = true;
}
}
}
return found;
},
copyFile = function(stream) {
stream.pipe(gulp.dest(config.buildPath.js + "lib/ckeditor"));
};
return gulp.src([
"node_modules/ckeditor/**/*.*",
"!node_modules/ckeditor/samples",
"!node_modules/ckeditor/samples/**/*"
])
.pipe(foreach(function(stream, file){
if (file.path.indexOf("lang") != -1) {
if (isIncluded(file.path)) {
copyFile(stream);
}
} else {
copyFile(stream);
}
return stream;
}));
});
Option 3: Build and Host Your Own Custom Bundle
If you want to use a single file load, you can use the CKE4 Builder allowing you to customise built-in plugins.

Excel doesn't want to open XLSX files downloaded through ASP output

I use ASP MVC3 framework, created an Excel file and outputted it using FileResult action with content type "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet".
When attempting to open it Excel just says "file is corrupt and cannot be opened."
When I open the source generated Excel file that was used to send the output it works without any problems. I also run file comparison on the bytes for both copies and the files are identical. I tried to email the corrupt file to myself and the attachment opens fine.
This leads me to believe it's a problem with headers or some sort of Excel/Windows security config.
If it is the latter, then I need a solution that won't make clients change their security settings.
EDIT - Found the setting:
I've found what setting causes this - "Enable protected view from files originated from the internet" in Excel's Trust Center / Protected View settings.
So I guess the question is - Is there a way for the file to appear trusted?
Here are the response headers:
Cache-Control:private
Content-Disposition:attachment;
filename="Report - Monday, March 19, 2012.xlsx" Content-Length:20569
Content-Type:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
The action method that makes the output:
[HttpPost]
public virtual FileResult Export()
{
try
{
...
string newFilePath = createNewFile(...);
string downloadedFileName = "Report - " + DateTime.Now.ToString("D") + ".xlsx";
return File(newFilePath, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", downloadedFileName);
}
catch (Exception ex)
{
...
}
}
How I create the Excel file:
I have a template XLSX file witch column names and some pivot charts in other sheets. From C# I create a copy of this template and then call SQL Server which outputs data into 1st sheet using OLEDB connector:
set #SQL='insert into OPENROWSET(''Microsoft.ACE.OLEDB.12.0'', ''Excel 12.0;Database=' + #PreparedXLSXFilePath + ';'', ''SELECT * FROM [Data$]'') ...
Thanks in advance for any help.
You would need a digital signature in your Excel file. How to do this from code is another question.
More info here:
http://www.delphifaq.com/faq/windows_user/f2751.shtml

Resources