NLog config file to get configuration setting values from a web.config - web-config

Is there a method to get a value from the <ApplicationSettings> section of a web.config within NLog layout variables?
I already store SMTP details within my web.config and don't want to duplicate the settings just to use within my NLog.config.
Ideally I'd like to do something like: ${aspnet-config:SmtpHostServer}
which then fetches the value from the web.config

I couldn't see any obvious way to do this other than creating my own LayoutRenderer (see below). If you're putting into your own assembly don't forget to add the following into your NLog.Config:
<extensions>
<add assembly="YOURASSEMBLYNAMEHERE" />
</extensions>
Hope this helps someone else:
[LayoutRenderer("aspnet-config")]
public class AspNetConfigValueLayoutRenderer : LayoutRenderer
{
[DefaultParameter]
public string Variable
{
get;
set;
}
protected override void Append(StringBuilder builder, LogEventInfo logEvent)
{
if (this.Variable == null)
{
return;
}
HttpContext context = HttpContext.Current;
if (context == null)
{
return;
}
builder.Append(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings[this.Variable], CultureInfo.InvariantCulture));
}
}

Updated Answer
NLog ver. 4.6 includes ${appsetting:SmtpHostServer} in the core NLog-nuget-package. No longer requires NLog.Extended. See also https://github.com/nlog/NLog/wiki/AppSetting-Layout-Renderer
NLog.Extensions.Logging ver. 1.4 includes ${configsetting} that allows one to read settings from appsettings.json. See also https://github.com/NLog/NLog/wiki/ConfigSetting-Layout-Renderer
Original Answer
Nowadays this is possible without custom code:
Use NLog.Extended and use
${appsetting:SmtpHostServer}.
See docs for ${appsetting}
Please note: this isn't supported in .NET Core / .NET standard yet.

Related

Show warning when EL not found

I'm creating a JSF Applikation and i would like to get some kind of warning (preferably i the console) if i make typos in my EL-Expression.
Example:
On my page i wanted to show some Text that is localized. The locale-config in faces-config.xml is properly set up and works with the var 'msgs'.
I used this code on my page:
<h:outputText value="#{msg.title_edit_customer}"/>
When i checked my Page in the browser, nothing got showed.
I took me a while to realize that i made a typo - with #{msgs.... it worked as expected.
Can i activate some kind of Debug-Output, so i can see directly that there is an invalid EL somewhere?
My Setup: Eclipse 4.4.2, Tomcat 8, MyFaces 2.2.8
Thanks to #SJuan76 i could figure it out:
Create your own javax.el.ELResolver, all the Methods can return null/false.
Open the Source of the Class org.apache.myfaces.el.unified.resolver.ScopedAttributeResolver and copy the methods facesContext(ELContext) and findScopedMap(FacesContext, Object) (since ScopedAttributeResolver is final, we can't extend it).
Edit the getValue-Method:
#Override
public Object getValue(ELContext context, Object base, Object property) {
if(!context.isPropertyResolved()){
//Douple Check false-positives
boolean foundInScope = false;
final Map<String, Object> scopedMap = findScopedMap(
facesContext(context), property);
if (scopedMap != null) {
Object object = scopedMap.get(property);
if (object != null) {
foundInScope = true;
}
}
if (!foundInScope) {
log.warn(String.format("EL-Property %s couldn't be resolved",
property));
}
}
return null;
}
Edit faces-config.xml to register your resolver:
<application>
<el-resolver>com.myPackage.DebugELResolver</el-resolver>
</application>
Since there are many Resolvers and each one does a little bit of the Resolving, our new Resolver should come last. Add following to web.xml:
<context-param>
<param-name>org.apache.myfaces.EL_RESOLVER_COMPARATOR</param-name>
<param-value>org.apache.myfaces.el.unified.CustomLastELResolverComparator</param-value>
</context-param>
Now you'll get some log-Output, every time an expression couldn't be resolved:
03.07.2015 07:34:21 com.myPackage.DebugELResolver [http-nio-8080-exec-2] WARN EL-Property msgx couldn't be resolved
I couldn't figure out how to get the actual EL-Expression (e.g. #{msgx.title_edit_customer}.

How do I get to use Model1.foo instead of Model1.edmx, and invoke IModelConversionExtension callbacks

I have a VSIX and a associated MEF DLL using IModelConversionExtension Class as per the documentation, and a pkgdef file setting up .foo as an extension to invoke the EF Designer.
[PartCreationPolicy(CreationPolicy.Shared)]
[Export(typeof(IModelConversionExtension))]
[ModelFileExtension(".foo")]
public class MyConversionCallback : IModelConversionExtension
{
public void OnAfterFileLoaded(ModelConversionExtensionContext context)
{
//How does this get called?
return;
}
public void OnBeforeFileSaved(ModelConversionExtensionContext context)
{
//How does this get called?
return;
}
}
[$RootKey$\Editors\{c99aea30-8e36-4515-b76f-496f5a48a6aa}\Extensions]
"foo"=dword:00000032
[$RootKey$\Projects]
[$RootKey$\Projects\{F184B08F-C81C-45F6-A57F-5ABD9991F28F}]
[$RootKey$\Projects\{F184B08F-C81C-45F6-A57F-5ABD9991F28F}\RelatedFiles]
[$RootKey$\Projects\{F184B08F-C81C-45F6-A57F-5ABD9991F28F}\RelatedFiles\.foo]
".diagram"=dword:00000002
[$RootKey$\Projects]
[$RootKey$\Projects\{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}]
[$RootKey$\Projects\{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\RelatedFiles]
[$RootKey$\Projects\{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}\RelatedFiles\.foo]
".diagram"=dword:00000002
I can get both the similar Transform and Generation MEF Classes to work fine.
And my Model1.foo does invoke the EF Designer, but
1. OnAfterFileLoaded and OnBeforeFileSaved never fire, and
2. I get an error message when I try to save Model1.foo, which says to see errors in the Error List but there are none.
What am not doing to get this to work.
Thanks
OnAfterFileLoaded is supposed to be invoked if you load a file whose extension is different than edmx and the IEntityDesignerConversionData.FileExtension returns a value that matches your extension. OnBeforeFileSaved works the opposite way - on save. However - I looked at code in this area today and concluded that it actually cannot work. I filed a work item for this: https://entityframework.codeplex.com/workitem/1371

Asp.Net Web API Error: The 'ObjectContent`1' type failed to serialize the response body for content type 'application/xml; charset=utf-8'

Simplest example of this, I get a collection and try to output it via Web API:
// GET api/items
public IEnumerable<Item> Get()
{
return MyContext.Items.ToList();
}
And I get the error:
Object of type
'System.Data.Objects.ObjectQuery`1[Dcip.Ams.BO.EquipmentWarranty]'
cannot be converted to type
'System.Data.Entity.DbSet`1[Dcip.Ams.BO.EquipmentWarranty]'
This is a pretty common error to do with the new proxies, and I know that I can fix it by setting:
MyContext.Configuration.ProxyCreationEnabled = false;
But that defeats the purpose of a lot of what I am trying to do. Is there a better way?
I would suggest Disable Proxy Creation only in the place where you don't need or is causing you trouble. You don't have to disable it globally you can just disable the current DB context via code...
[HttpGet]
[WithDbContextApi]
public HttpResponseMessage Get(int take = 10, int skip = 0)
{
CurrentDbContext.Configuration.ProxyCreationEnabled = false;
var lista = CurrentDbContext.PaymentTypes
.OrderByDescending(x => x.Id)
.Skip(skip)
.Take(take)
.ToList();
var count = CurrentDbContext.PaymentTypes.Count();
return Request.CreateResponse(HttpStatusCode.OK, new { PaymentTypes = lista, TotalCount = count });
}
Here I only disabled the ProxyCreation in this method, because for every request there is a new DBContext created and therefore I only disabled the ProxyCreation for this case .
Hope it helps
if you have navigation properties and you do not want make them non virtual, you should using JSON.NET and change configuration in App_Start to using JSON not XML!
after install JSON.NET From NuGet, insert this code in WebApiConfig.cs in Register method
var json = config.Formatters.JsonFormatter;
json.SerializerSettings.PreserveReferencesHandling = Newtonsoft.Json.PreserveReferencesHandling.Objects;
config.Formatters.Remove(config.Formatters.XmlFormatter);
If you have navigation properties make them non virtual. Mapping will still work but it prevents the creation of Dynamic Proxy entities which cannot be serialized.]
Not having lazy loading is fine in a WebApi as you don't have a persistent connection and you ran a .ToList() anyway.
I just disabled proxy classes on a per needed basis:
// GET: ALL Employee
public IEnumerable<DimEmployee> Get()
{
using (AdventureWorks_MBDEV_DW2008Entities entities = new AdventureWorks_MBDEV_DW2008Entities())
{
entities.Configuration.ProxyCreationEnabled = false;
return entities.DimEmployees.ToList();
}
}
Add the following code in Application_Start function of Global.asax.cs:
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings
.ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;
GlobalConfiguration.Configuration.Formatters
.Remove(GlobalConfiguration.Configuration.Formatters.XmlFormatter);
This instruct the API to serialize every response into JSON and remove XML responses.
In my case the object being returned had a property within it with a type that did not have an argumentless/default constructor. By adding a zero-argument constructor to that type the object could be serialized successfully.
I had the same problem and my DTO was missing an parameter less constructor.
public UserVM() { }
public UserVM(User U)
{
LoginId = U.LoginId;
GroupName = U.GroupName;
}
First constructor was missing.
I got this error message and it turns out the problem was that I had accidentally set my class to use the same serialized property name for two properties:
public class ResultDto
{
//...
[JsonProperty(PropertyName="DataCheckedBy")]
public string ActualAssociations { get; set; }
[JsonProperty(PropertyName="DataCheckedBy")]
public string ExpectedAssociations { get; set; }
//...
}
If you're getting this error and you aren't sending entities directly through your API, copy the class that's failing to serialize to LINQPad and just call JsonConvert.SerializeObject() on it and it should give you a better error message than this crap. As soon as I tried this it gave me the following error message: A member with the name 'DataCheckedBy' already exists on 'UserQuery+ResultDto'. Use the JsonPropertyAttribute to specify another name.
After disable Proxy Creation, use eager loading (Include()) to load the proxy object.
In my Project EntityCollection returned from the WebApi action method.
Configuration.ProxyCreationEnabled = false not applicable. I have tried the below approach it is working fine for me.
Control Panel.
2.Turn on Windows Features on or off
Choose Internet Information Service
Check all the World Wide Web Components it would be better to check all the components in IIS.
Install the components.
Go to (IIS) type inetmgr in command prompt.
select the published code in the Virtual directory.
Convert into application
Browse it the application.
The answer by #Mahdi perfectly fixes the issue for me, however what I noticed is that if my Newtonsoft.JSON is 11.0 version then it doesn't fix the issue, but the moment I update Newtonsoft.JSON to latest 13.0 it starts working.

how to change the themes in asp.net mvc 2

I would like to have an option wherein a user can choose his theme for the site from the dropdown list and the theme applies to that page [atleast].
I want this to be done in ASP.NET MVC 2 without using jquery like frameworks.
How can this be accomplished.
I am using the default webforms viewengine and donot want to go for a custom viewengine for this purpose.
It seems this is not supported out of the box, but here's what I did to implement theming:
First, I Added the App_Themes folder to my project, and set up a couple of themes
I then decided to try and mimic the Web-forms profile provider as close as possible, and added a profile-property to web.config:
<profile>
<properties>
<add name="ThemePreference" type="string" defaultValue="Blue" />
</properties>
</profile>
So, basically what I wanted to do was to be able to load the different css's from the appropriate theme-folder when the theme changed. I did this by implementing a helper method attached to the UrlHelper class so that I could write:
<link href="#Url.Theme("~/Content/Site.css")" rel="stylesheet" type="text/css" />
This should then load the appropriate themed Site.css, and fall back to ~/Content/Site.css if no file was found.
The helper is pretty simple:
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
SettingsProperty settingsProperty = ProfileBase.Properties["ThemePreference"];
return url.Content("~/App_Themes/"+settingsProperty.DefaultValue + u);
}
}
Now, in this version of the code it simply gets the default-value, so you'll need to tweak the code slightly. But as you can see, this is not limited to css-files, but works with everything from .master files to images.
Update - Using Session instead of profile
public static class UrlHelpers
{
public static string Theme(this UrlHelper url, string u)
{
if (u.StartsWith("~")) u = u.TrimStart('~');
object currentThemeName = null;
if (url.RequestContext.HttpContext.Session != null)
{
currentThemeName = url.RequestContext.HttpContext.Session["ThemePreference"];
}
return currentThemeName != null ? url.Content(String.Format("~/App_Themes/{0}{1}", currentThemeName, u)) : url.Content("~"+u);
}
}
The return-line in this method checks if it found a ThemePreference session-value, and then returnes the appropriate URL for the content requested, otherwise it simply returns the content as it was requested with no App_Theme prefix.
In your controlleraction for the DropDown postmethod, you'd simply do:
Session.Add("ThemePreference", whateverValueYouGotFromDropdown);
Update ends
With some tweaking and fixing, this should do the trick.
Hope it helps some, even though it's not a complete walkthrough :)

MEF Contrib Provider Model Not Importing Parts

I have been trying to use the configurable provider model for handling my MEF imports and exports from MEF Contrib (link). I've read the Codeplex documentation and Code Junkie's blog post (link); however, I can't seem to get the container to create the parts. Where am I going wrong?
Program.cs
namespace MEFTest
{
class Program
{
static void Main(string[] args)
{
Program p = new Program();
p.Run();
}
// [ImportMany("command", typeof(IHelp))]
public IEnumerable<IHelp> Commands { get; set; }
void Run()
{
Compose();
foreach(IHelp cmd in Commands)
{
Console.WriteLine(cmd.HelpText);
}
Console.ReadKey();
}
void Compose()
{
var provider = new ConfigurableDefinitionProvider("mef.configuration");
var catalog = new DefinitionProviderPartCatalog<ConfigurableDefinitionProvider>(provider);
var container = new CompositionContainer(catalog);
container.ComposeParts(this);
}
}
}
TestCommand.cs
namespace MEFTest
{
//[Export("command", typeof(IHelp))]
public class TestCommand : IHelp
{
private string _helpText = "This is a test.";
public string CommandName
{
get { return "Test"; }
}
public string HelpText
{
get { return _helpText; }
}
}
}
App.Config section:
<mef.configuration>
<parts>
<part type="MEFTest.TestCommand, MEFTest">
<exports>
<export contract="IHelp" />
</exports>
</part>
<part type="MEFTest.Program, MEFTest">
<imports>
<import member="Commands" contract="IHelp" />
</imports>
</part>
</parts>
</mef.configuration>
I don't get any build errors and it runs fine if I switch to the typical attribute-based system that is part of the MEF core (with the appropriate catalog too). Program.Commands is always NULL in the above example. I tried to just use a singular property instead of a collection and get the same results.
When I debug I can get the provider.Parts collection so I know it's accessing the configuration information correctly; however, I get an InvalidOperationException whenever I debug and try to drill into catalog.Parts.
Anyone have any experience as to where I'm going wrong here?
As documented here, you also need this in your config file:
<configSections>
<section
name="mef.configuration"
type="MefContrib.Models.Provider.Definitions.Configurable.PartCatalogConfigurationSection, MefContrib.Models.Provider" />
</configSections>
If you already have that, then it might be interesting to show us the stack trace of the InvalidOperationException that you get when accessing provider.Parts.
I had the same problems and could not get it to work, but here are some details:
It seems that ComposeParts() does not work as expected (at least in the version I used) because it uses static methods, based on Reflection to find all required Imports (so it seems that this part cannot be changed from outside of MEF). Unfortunately we want to use xml configuration and not the MEF attributes.
It works if you add [Import] attributes to the members of the class you you use with ComposeParts(). In your case this would be "Programm". In this case all exports defined in the configuration file will be found.
I could not find any documentation or examples on the MEF Contrib page relating to that problem. Also there is no unittest in the MEF contrib projekt that uses ComposeParts().
A workaround would be to use container.GetExportedValues() to retrieve the values, but in this case you have to set the classes members manually.
Hope that helps.