Call Method in Class from Razor - asp.net-mvc

I've got a method in a class in an App_Code directory in my MVC 4 project. I can call this fine from controllers, but I can't figure out how to call it from an View (.cshtml) file.
namespace LST.App_Code
{
public static class Utilities
{
public static readonly log4net.ILog log = log4net.LogManager.GetLogger("GeneralLog");
From my View, I've tried several things, all along these lines:
#LST.App_Code.Utilities.log.Info("asdf");
When I do that, I receive the following compilation error when trying to load the page:
Description: An error occurred during the compilation of a resource
required to service this request. Please review the following specific
error details and modify your source code appropriately.
Compiler Error Message: CS0433: The type 'LST.App_Code.Utilities'
exists in both
'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET
Files\root\bd7cb704\59585235\assembly\dl3\3b0ad3ff\ec2b5faa_0b13ce01\mvcroot.DLL'
and 'c:\Windows\Microsoft.NET\Framework\v4.0.30319\Temporary ASP.NET
Files\root\bd7cb704\59585235\App_Code.cggwncvj.dll'
Source Error:
Line 7: #using (Html.BeginForm()) Line 8: { Line 9:
#(LST.App_Code.Utilities.log.Info("asdf")) Line 10: Line 11:
#Html.AntiForgeryToken()
I've tried the suggestions about cleaning the project, the asp.net temporary files directory, and setting the batch compilation option. Nothing is working.
I'm not that familiar with the intricacies of the Razor syntax. Can someone please point me in the right direction?

I make it work with no namespace in the .cs file at all.
If you have created the app_code folder, then you can just create class files like this (without namespaces):
using System:
...
public class FooClass{
public string Foo(...)
{
...
}
}
And call it from your view like this:
#{
new FooClass().Foo(...);
}
Worked for me...

Related

Calling Another Project's Controller From A Project In The Same Solution (.NET Core )

There are 2 projects in the same solution. First project is a .NET Core project and it has all the codes(controllers, models etc.) related to packages. I need to get the information (id, name, description) of the packages and display it in the second project(.NET Core Web App with Razor). Is it possible to do it without changing the first project? I only want to show the package list on a single web page.
I tried calling the first project's controller but it didn't work. Maybe I missed a point. Any help is appreciated.
This requirement can be achieved, please see the gif image below.
Tips
If you want to call another project's controller from a project in the same solution, you need to make sure there is in HomeController in both project. I mean the name of any class should be unique in both projects.
Otherwise you will face the same issue like my homepage.
Test Code:
public List<PackageReference> GetPackageList5(string projectname)
{
List<PackageReference> list = new List<PackageReference>();
PackageReference p = null;
XDocument doc = XDocument.Load(_webHostEnvironment.ContentRootPath+ "/"+ projectname + ".csproj");
var packageReferences = doc.XPathSelectElements("//PackageReference")
.Select(pr => new PackageReference
{
Include = pr.Attribute("Include").Value,
Version = pr.Attribute("Version").Value
});
Console.WriteLine($"Project file contains {packageReferences.Count()} package references:");
foreach (var packageReference in packageReferences)
{
p = new PackageReference();
p.Version= packageReference.Version;
p.Include= packageReference.Include;
list.Add(packageReference);
//Console.WriteLine($"{packageReference.Include}, version {packageReference.Version}");
}
return list;
}
My Test Steps:
create two project, Net5MVC,Net6MVC
add project reference.
My .net6 project references a .net5 project. So in my HomeController (.net), I add below:
using Net5MVC.ForCore6;
using Net5MVC.Models;
Suggestion
When we reference the .net5 project in .net6 project, we can build success, but when we deploy it, it always failed. The reason is some file was multiple publish output files with the same relative path.
Found multiple publish output files with the same relative path:
D:\..\Net6\Net6\Net5MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net6MVC\appsettings.Development.json,
D:\..\Net6\Net6\Net5MVC\appsettings.json,
D:\..\Net6\Net6\Net6MVC\appsettings.json.
And usually will add class library to current project, not add a web project.
As we know we can find packages info in .csproj file, so we need copy and paste .csproj file to publish folder.
I still recommend using the GetPackageList5 method above as an interface for your project, using HttpClient for requests.

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"/>

How to remove ErrorViewModel when using dotnet core with MVC

If ErrorViewModel is removed from my project, it won't run, failing at app.UseMvc() with the error:
System.TypeLoadException: 'Could not load type
'DocumentGenerationService.Models.ErrorViewModel' from assembly 'DocumentGenerationService, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null'.'
It is a dotnet core 2.2 application with mvc. I've removed everything that is unnecessary to the application, which includes all the views, as this is a webapi project.
Why can't I remove ErrorViewModel from the project? It's making me sad.
For reference, here's how the startup class looks:
public class Startup
{
...
public void ConfigureServices(IServiceCollection services)
{
services.AddCors();
services.AddSignalR();
services.AddMvc()
.SetCompatibilityVersion(CompatibilityVersion.Version_2_2);
...
}
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
...
app.UseMvc();
}
}
Any ideas how to get rid of the ErrorViewModel class and have the project run? Or an explanation of why it isn't possible?
Thanks StackOverflowers!
I had the same problem and the following solution worked for me:
Remove all the ErrorViewModel related files like Controllers, Views, etc...
Close the Visual Studio if it's open
Go to the source directory and remove obj and bin directories
Open the project with Visual Studio and run it
Now it should work as a normal WebApi project.
First welcome to the Stack Overflow community.
Now after removing the ErrorViewModel from models folder you need to do following things to remove the ErrorViewModel related codes:
Delete the Error method from HomeController
Delete Error.cshtml file from Views/Shared folder
Now check _ViewImports file in the Views folder. If there is any red line starting with #using then please remove this line.
Now build the solution and run again. Hope it will run now gracefully.

Application Cache Error event: Failed to parse manifest in C# 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

Resources