asp.net MVC 5 project using Nlog Methodcall target has no effect - asp.net-mvc

In the ASP.net MVC 5 project, use Nuget to install Nlog, Nlog.config, Nlog.schema Packages.
Target xsi:type="MethodCall" in the NLog.config file
NLog.config
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
autoReload="true"
throwExceptions="false"
internalLogLevel="Off" internalLogFile="c:\temp\nlog-internal.log">
<targets>
<target name="mc" xsi:type="MethodCall" className="NlogMethodCallWebApp.Models.NLogHelper, NlogMethodCallWebApp" methodName="LogMethod">
<parameter layout="${longdate}" />
<parameter layout="${uppercase:${level}}" />
<parameter layout="${message}" />
</target>
</targets>
<rules>
<logger name="*" minlevel="Trace,Debug,Info,Warn,Error,Fatal" writeTo="mc" />
</rules>
</nlog>
Execute Debug HomeController Index Action Method
HomeController.cs
using NLog;
using System.Web.Mvc;
namespace NlogMethodCallWebApp.Controllers
{
public class HomeController : Controller
{
private static Logger logger = NLog.LogManager.GetCurrentClassLogger();
public ActionResult Index()
{
logger.Trace("This is Trace");
logger.Debug("This is Debug");
logger.Info("This is Info");
logger.Warn("This is Warn");
logger.Error("This is Error");
logger.Fatal("This is Fatal");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
return View();
}
}
}
LogMethod set breakpoint in class NLogHelper has no effect
NLogHelper.cs
using System;
using System.Diagnostics;
namespace NlogMethodCallWebApp.Models
{
public class NLogHelper
{
/// <summary>
/// c - NLog
/// </summary>
public static void LogMethod(string longdate, string level, string message)
{
Trace.WriteLine(string.Format("D:{0} L:{1} M:{2}", longdate, level, message));
}
}
}
NLog does not execute LogMethod method. Where is the problem?

You loglevel is wrong.
There a multiple possibilities:
minlevel="Trace,Debug,Info,Warn,Error,Fatal" <-- Yours, that wrong
change to:
levels="Trace,Debug,Info,Warn,Error,Fatal"
or
minlevel="Trace"
or you can also use minlevel and maxlevel
Details:
https://github.com/NLog/NLog/wiki/Configuration-file#log-levels
Also check that the assembly is inside your output directory (your project must reference this assembly)

Related

How create database in public schema?

Sorry and thanks in advance I am newbie in ASP and I don't understand some ideas.
I want that when my app run if not exists my databases it be created.
I am working with postgres 9.2 and Entity Framework 6.1.3 and Npgsql.EntityFramework 2.2.7.
If I remove the line "modelBuilder.HasDefaultSchema("public");" in DBContext Class the schema is created as "dbo" but I want the schema be created in the public schema, and wether I leave "modelBuilder.HasDefaultSchema("public");"
I get this error:
An exception of type 'Npgsql.NpgsqlException' occurred in EntityFramework.dll ..."
Additional Information: ERROR: 42P06:the "public" scheme already exists
what I am doing wrong?
This is my code:
part of web.config for connect to postgres.
<connectionStrings>
<add name="DefaultConnectionString" connectionString="server=localhost;user id=postgres;password=1234;database=Test" providerName="Npgsql" />
<system.data>
<DbProviderFactories>
<remove invariant="Npgsql" />
<add name="Npgsql Data Provider" invariant="Npgsql" description=".Net Data Provider for PostgreSQL" type="Npgsql.NpgsqlFactory, Npgsql, Culture=neutral, PublicKeyToken=5d8b90d52f46fda7" />
</DbProviderFactories>
Then I create a few models and one class that inherits from dbcontext:
public class ContextoAplicacion : DbContext
{
public ContextoAplicacion() :base("name=DefaultConnectionString")
{
}
public DbSet<Afiliado> afiliados { get; set; }
public DbSet<Empresa> empresas { get; set; }
protected override void OnModelCreating(DbModelBuilder modelBuilder)
{
modelBuilder.HasDefaultSchema("public");
}
}
and finally add next code in my HomeController:
ContextoAplicacion _context;
public HomeController()
{
_context = new ContextoAplicacion();
}
public ActionResult Index()
{
var data = _context.afiliados.ToList();
return View();
}
Thanks in advance!!!
Fernando

Custom error page use filter action mvc

My application use MVC4, Entity Framework 6. I want custom Actions return to page error (500, 404, 403) when an error occurs use Filter Action on MVC.
Currently, I'm using Application_Error method in file Global.asax to return page error, but it not working when action call from AJAX.
Ex:
This is page
[ExecuteCustomError]
public ActionResult TestAction()
{
Rerurn View();
}
This is view returned after AJAX call
[ExecuteCustomError]
public ActionResult ReturnView()
{
//If return error code, i have return message error here.
return PartialView();
}
Looks like you haven't provided correct path of your error page.
Like you need to add your error page in shared view folder then you can access this page.
If your page is in the other folder then you have to specify the correct path of your error view page.
Like below :
return PartialView("~/Views/ErrorPartialView.cshtml", myModel);
We have other options to call error page through web. In Config file you can do the below settings :
<configuration>
...
<system.webServer>
...
<httpErrors errorMode="Custom" existingResponse="Replace">
<clear />
<error statusCode="400" responseMode="ExecuteURL" path="/ServerError.aspx"/>
<error statusCode="403" responseMode="ExecuteURL" path="/ServerError.aspx" />
<error statusCode="404" responseMode="ExecuteURL" path="/PageNotFound.aspx" />
<error statusCode="500" responseMode="ExecuteURL" path="/ServerError.aspx" />
</httpErrors>
...
</system.webServer>
...
</configuration>
Here we go for Global Exception Filter :
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCGlobalFilter.Filters
{
public class ExecuteCustomErrorHandler : ActionFilterAttribute, IExceptionFilter
{
public void OnException(ExceptionContext filterContext)
{
Exception e = filterContext.Exception;
filterContext.ExceptionHandled = true;
filterContext.Result = new ViewResult()
{
ViewName = "CommonExceptionPage"
};
}
}
}
Now you have to register your ExecuteCustomErrorHandler class in Global.asax file :
/// <summary>
/// Application start event
/// </summary>
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
log4net.Config.XmlConfigurator.Configure();
// Calling Global action filter
GlobalFilters.Filters.Add(new ExecuteCustomErrorHandler());
}
You need to add CommonExceptionPage view in Shared folder :
CommonExceptionPage.cshtml :
#{
ViewBag.Title = "Execute Custom Error Handler";
}
<hgroup class="title">
<h1 class="error">Error.</h1>
<h2 class="error">An error occurred while processing your request.</h2>
</hgroup>

WebApi 2 routing without MVC route config isn't working

TL;TD I've created a new WebApi2 Application and removed all the default MVC guff so just WebApi guff remains. Why isn't it working.
I've created a Web Api 2 project and don't need any non Web Api functionality so I removed it prior to creating my WebApi route and controller. No matter how I try to access it, I cant hit my new web api controller action. Code snippets below;
Global.asax
public class WebApiApplication : HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.MapHttpAttributeRoutes();
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}"
);
}
}
TestController.cs
public class TestController : ApiController
{
public IEnumerable<TestItem> Get()
{
var updates = new List<TestItem>()
{
new TestItem()
{
Title = "Testing Testing",
Content = "Testing Content",
Date = DateTime.Now
}
};
return updates;
}
}
Project Structure
App_Start
FilterConfig.cs
WebApiConfig.cs
Controllers
TestController.cs
Models
TestItem.cs
Global.asax
I am completely at a loss, I'm sure I've missed something obvious.
Your route is defined as the following:
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "{controller}/{action}/{id}"
);
This is expecting a route which is in 3 segments; i.e. http://localhost/Test/Get/1. However, you don't have any action which matches this. The only action you have matches http://localhost/Test/Get/.
You could correct this by adding defaults: new { id = RouteParameter.Optional } to your Http Route. However, I highly encourage you to consider switching to Attribute based Routing instead. With Attribute routing, you use attributes in your controller to manage your routes, rather than using a magic string routing table. For Example:
[RoutePrefix("Test")]
public class TestController : ApiController {
// http://localhost/Test/Get
[Route("Get")]
public IEnumerable<TestItem> Get() { ...
}
//http://localhost/Test/Get/1
[Route("Get/{id}")
public TestItem Get(int id) { ...
}
}
It's not possible to see what is causing your WebApi to fail from the supplied code, but this will give you a working WebApi with minimal setup.
A side note, FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters) is for MVC filters and not used by WebApi. You should instead use config.Filters.Add(new SomeFilter()) in your WebApiConfig.csfile.
Make a GET request to http://localhost:80/api/test (or whatever port it is running on) and it will return a list of TestItem in either XML or JSON depending on your clients http headers.
Global.asax.cs
public class WebApiApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
GlobalConfiguration.Configure(WebApiConfig.Register);
}
}
WebApiConfig.cs
public static class WebApiConfig
{
public static void Register(HttpConfiguration config)
{
config.Routes.MapHttpRoute(
name: "DefaultApi",
routeTemplate: "api/{controller}/{id}",
defaults: new { id = RouteParameter.Optional }
);
}
}
TestController.cs
public class TestController : ApiController
{
public IEnumerable<TestItem> Get()
{
var updates = new List<TestItem>()
{
new TestItem()
{
Title = "Testing Testing",
Content = "Testing Content",
Date = DateTime.Now
}
};
return updates;
}
}
TestItem.cs
public class TestItem
{
public TestItem()
{
}
public string Content { get; set; }
public DateTime Date { get; set; }
public string Title { get; set; }
}
I have the following nuget packages installed:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Microsoft.AspNet.WebApi" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Client" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.Core" version="5.2.3" targetFramework="net452" />
<package id="Microsoft.AspNet.WebApi.WebHost" version="5.2.3" targetFramework="net452" />
</packages>

Unity - How to enable setter injection in configuration file?

I've created a controller factory and registered my types in code. I can do the following:
public class HomeController : Controller
{
public MasterEntities DbContext { get { return Container.Resolve<MasterEntities>(); }
}
public ActionResult Index()
{
//DbContext can be used here properly...
}
}
However I would like to have the property injected in the setter instead of having to call Container.Resolve<TypeName>() explicitly. Preferrable without using attributes or some configuration in code...
public MasterEntities DbContext { get; set; }
How can this be configured in my .config file? Or does this require the use of attributes or configuration in code?
<register type="HomeController">
<property name="DbContext" />
</register>
should do the trick.

Implementing Profile Provider in ASP.NET MVC

For the life of me, I cannot get the SqlProfileProvider to work in an MVC project that I'm working on.
The first interesting thing that I realized is that Visual Studio does not automatically generate the ProfileCommon proxy class for you. That's not a big deal since it's simpy a matter of extending the ProfileBase class. After creating a ProfileCommon class, I wrote the following Action method for creating the user profile.
[AcceptVerbs("POST")]
public ActionResult CreateProfile(string company, string phone, string fax, string city, string state, string zip)
{
MembershipUser user = Membership.GetUser();
ProfileCommon profile = ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
profile.Company = company;
profile.Phone = phone;
profile.Fax = fax;
profile.City = city;
profile.State = state;
profile.Zip = zip;
profile.Save();
return RedirectToAction("Index", "Account");
}
The problem that I'm having is that the call to ProfileCommon.Create() cannot cast to type ProfileCommon, so I'm not able to get back my profile object, which obviously causes the next line to fail since profile is null.
Following is a snippet of my web.config:
<profile defaultProvider="AspNetSqlProfileProvider" automaticSaveEnabled="false" enabled="true">
<providers>
<clear/>
<add name="AspNetSqlProfileProvider" type="System.Web.Profile.SqlProfileProvider, System.Web, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" connectionStringName="ApplicationServices" applicationName="/" />
</providers>
<properties>
<add name="FirstName" type="string" />
<add name="LastName" type="string" />
<add name="Company" type="string" />
<add name="Phone" type="string" />
<add name="Fax" type="string" />
<add name="City" type="string" />
<add name="State" type="string" />
<add name="Zip" type="string" />
<add name="Email" type="string" >
</properties>
</profile>
The MembershipProvider is working without a hitch, so I know that the connection string is good.
Just in case it's helpful, here is my ProfileCommon class:
public class ProfileCommon : ProfileBase
{
public virtual string Company
{
get
{
return ((string)(this.GetPropertyValue("Company")));
}
set
{
this.SetPropertyValue("Company", value);
}
}
public virtual string Phone
{
get
{
return ((string)(this.GetPropertyValue("Phone")));
}
set
{
this.SetPropertyValue("Phone", value);
}
}
public virtual string Fax
{
get
{
return ((string)(this.GetPropertyValue("Fax")));
}
set
{
this.SetPropertyValue("Fax", value);
}
}
public virtual string City
{
get
{
return ((string)(this.GetPropertyValue("City")));
}
set
{
this.SetPropertyValue("City", value);
}
}
public virtual string State
{
get
{
return ((string)(this.GetPropertyValue("State")));
}
set
{
this.SetPropertyValue("State", value);
}
}
public virtual string Zip
{
get
{
return ((string)(this.GetPropertyValue("Zip")));
}
set
{
this.SetPropertyValue("Zip", value);
}
}
public virtual ProfileCommon GetProfile(string username)
{
return ((ProfileCommon)(ProfileBase.Create(username)));
}
}
Any thoughts on what I might be doing wrong? Have any of the rest of you successfully integrated a ProfileProvider with your ASP.NET MVC projects?
Thank you in advance...
Here's what you need to do:
1) In Web.config's section, add "inherits" attribute in addition to your other attribute settings:
<profile inherits="MySite.Models.ProfileCommon" defaultProvider="....
2) Remove entire <properties> section from Web.config, since you have already defined them in your custom ProfileCommon class and also instructed to inherit from your custom class in previous step
3) Change the code of your ProfileCommon.GetProfile() method to
public virtual ProfileCommon GetProfile(string username)
{
return Create(username) as ProfileCommon;
}
Hope this helps.
Not sure about the whole question, but one thing I noticed in your code:
ProfileCommon profile = (ProfileCommon)ProfileCommon.Create(user.UserName, user.IsApproved) as ProfileCommon;
You do not need both the (ProfileCommon) and the as ProfileCommon. They both do casts, but the () throws and exception while the as returns a null if the cast can't be made.
Try Web Profile Builder. It's a build script that automagically generates a WebProfile class (equivalent to ProfileCommon) from web.config.
The web.config file in the MVC Beta is wrong. The SqlProfileProvider is in System.Web.Profile, not System.Web.Security. Change this, and it should start working for you.

Resources