References to Separate Projects When Configuring Unity? - dependency-injection

I read a really cool blog about using Autofac to completely decouple an application. But try as I might (and being horribly new to all this), I just couldn't get Autofac to gel.
I turned to Unity from the MS Patterns & Practices Enterprise Library and that went a whole lot better. To make things unnecessarily hard for myself, I separated out all my stuff into projects as:
UnityDi (Console app)
UnityDi.Contracts (Interfaces)
UntiyDi.Domain (Classes)
UnityDi.Repositories (Data Access)
UnityDi.Services (Access to repository through a service layer)
I used XML configuration to pony up Unity:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration" />
</configSections>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<assembly name="UnityDi.Contracts" />
<assembly name="UnityDi.Domain" />
<assembly name="UnityDi.Services" />
<assembly name="UnityDi.Repositories" />
<namespace name="UnityDi.Contracts" />
<namespace name="UnityDi.Domain" />
<namespace name="UnityDi.Services" />
<namespace name="UnityDi.Repositories" />
<container>
<register type="IUser" mapTo="User"></register>
<register type="IUserService" mapTo="UserService"></register>
<register type="IUserRepository" mapTo="UserRepository"></register>
</container>
</unity>
</configuration>
And got that into a running app, no worries:
private static readonly IUnityContainer Container = new UnityContainer();
...
Container.LoadConfiguration();
BUT in order to do so, I need a reference to all the above projects from my console app.
Is there a way to make the app only ever have a reference to UnityDi.Contracts (the interfaces)? Then the app is well and truly decoupled (admittedly with a sledgehammer).
I hope that is enough of an explanation, I'm totally new to this and I'm being extreme like this to facilitate better learning.

I suspect the reason it looks like you need project references is that without them, VS won't copy the assemblies into your apps bin folder when you hit F5. How would it, it has no way of knowing you need them!
The project references are the quickest solution to the problem. The other thing you could do is add a post-build step to copy the appropriate DLLs to end up in the right directory so you can run the app.

Related

Shipping logs to Logz.io with NLog fails

I'm just trying to ship some error logs from my ASP.NET MVC 5 app to Logz.io
I'm using NLog to ship my logs.
I've installed NLog and NLog.Web packages
I have the following nlog.config file :
<?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"
autoReload="true"
throwExceptions="true"
internalLogLevel="ERROR"
internalLogFile="C:\Temp\nlog-internal.log">
<extensions>
<add assembly="Logzio.DotNet.NLog"/>
</extensions>
<targets async="true">
<target name="file" type="File"
fileName="<pathToFileName>"
archiveFileName="<pathToArchiveFileName>"
keepFileOpen="false"
layout="<long layout patten>"/>
<target name="logzio"
type="Logzio"
token="LRK......"
logzioType="nlog"
listenerUrl="https://listener.logz.io:8071"
bufferSize="1"
bufferTimeout="00:00:05"
retriesMaxAttempts="3"
retriesInterval="00:00:02"
debug="false" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logzio" />
</rules>
</nlog>
Then, each of my C# controller have this line :
private static Logger logger = LogManager.GetCurrentClassLogger();
and then I try to ship my logs using something like :
logger.Fatal("Something bad happens");
However, when I writeTo="file" in the nlog.config file, I can find a log file on my local disk with "Something bad happens", so everything is fine.
However, nothing appear on my LogzIo web interface when I writeTo="logzio", no logs are shipped there.
What did I miss ?
Answering my own question after I found how to solve this.
Actually, my whole project use HTTPS.
In internal Nlog logs, I had this error
Error : System.Net.WebException : The request was aborted: Could not create SSL/TLS secure channel
I've just added this line of code at the very beginning of ApplicationStart in Global.asax.cs
ServicePointManager.SecurityProtocol |= SecurityProtocolType.Tls12;
After testing the whole project during some days, it seems it doesn't affect the other parts of the project.
However, just be careful as it is a global setting
I had the same issue, and it turned out that in my published app the logzio dlls were missing. I added them and it resolved the issue.
Check if you're missing these files in your bin folder:
Logzio.DotNet.NLog.dll
Logzio.DotNet.Core.dll

Publish an MVC application with a web.config for each production environment

I have an MVC application with a Dev, Staging, and Production environment. Dev and Staging are essentially the same thing (same VM, IIS, DB etc.); however, Production is hosted on 4 VMs behind a load balancer. Each VM has it's own DB. For example, the instance deployed to VM1 communicates with the PROD1 DB, VM2->PROD2, etc.
For deployment to Dev and Staging, I do a simple File System deployment from VS2013 to the VM using Debug/Release web.config transforms. For Production deployments, a SysAdmin will copy the bits deployed and tested in Staging to each Production VM. This is to ensure that what was tested and verified by QA in Staging is what we promote to Production -- I don't want to do another build between Staging and Production. Because of this, our SysAdmin is responsible for (with DevOps guidance) editing each web.config between Staging and Production. This basically consists of changing connectionString values from "Data Source=STAGINGDB" to "Data Source=PROD1" (and PROD2, PROD3, PROD4).
What I ultimately want is when I publish to Staging, I want to deploy my web.config using standard Release web.config transform; however, alongside this file I want to also create and drop 4 additional files (web.config.PROD1, .PROD2, etc.). This will allow us to create scripts which ignore the existing web.config (with Staging settings) and copy/rename the appropriate .PROD config.
I am able to (sort of) achieve this with MSBuild:
<Project ToolsVersion="12.0" DefaultTargets="Build">
...
<Target Name="Build">
<TransformXml Source="Web.config" Transform="Web.PROD1.config" Destination="Web.config.PROD1" />
<TransformXml Source="Web.config" Transform="Web.PROD2.config" Destination="Web.config.PROD2" />
...
</Target>
</Project>
My main issue with this approach is that I have to create 4 essentially redundant solution configurations to wire up to the Transform. Every setting is the same except the DB connectionString. Seems like there should be a more efficient way.
Can I execute individual transforms without solution configurations by simply calling the appropriate transform via MSBuild, like:
<add name="connectionString" connectionString="PROD1" xdt:Transform="SetAttributes" xdt:Locator="Match(name)" />
Should I be using another process altogether? I'd rather not use a 3rd party nuget solution if I can stay way from it. Should I be using a .wpp.targets file? XmlPoke?
My desired workflow
Right-click my MVC app and choose "Publish" (File System)
Let the Release transforms do their thing and generate the web.config. I have basic configurations. Debug = Dev, Release = Staging.
Add a custom step that generates 4 additional web.config files
Package everything up, and publish to the Staging server, so I see this on the VM:
Everything I've read leads me to believe that I should be writing custom MSBuild steps, but I don't know what I should be doing (or how). Here's some pseudo-code:
<Project ToolsVersion="12.0" DefaultTargets="Build">
...
<Target Name="Build">
<TransformXml Source="Web.config" Transform="[Do-Basic-Transform-On-Conection-String]" Destination="Web.config.PROD1" />
<TransformXml Source="Web.config" Transform="[Do-Basic-Transform-On-Conection-String]" Destination="Web.config.PROD2" />
<IncludeFilesInPublish>
<FileToInclude>Web.config.PROD1</FileToInclude>
<FileToInclude>Web.config.PROD2</FileToInclude>
</IncludeFilesInPublish>
</Target>
</Project>
Can I [Do-Basic-Transform-On-Connection-String] inline here without a solution configuration? I'll only be changing 2 connectionString values. If I need to create a solution config, that's fine... I just don't think it's totally necessary especially if I can do it inline. Maybe I'm wrong?
How do I accomplish the <IncludeFilesInPublish> bit so that whatever I do get's packaged up during the Publish, so my Staging deployment has my release candidate code and web.configs ready for promotions.
I think your question is twofold: 1) how do I pass environment variables or parameters (i.e. PROD1) into my xdt transformation file so I only have to use one transformation file? and 2) how do I get MSBuild to iterate over a set of known named items to produce outputs distinguished by each item in this set?
For the first part, the only reason why I assert you might be asking this is because you said "I have to create 4 essentially redundant solution configurations to wire up to the Transform", so if your transform took "PROD1" as a parameter you could ideally just use one transform. But I'm not sure that you can do this without creating your own XmlTransform task. The xdt transformation tooling is really limited. But the nice thing about MSBuild is that it's flexible enough that you could theoretically come up with your own transformation task that extends/subclasses or behaves like the one out of the box.
using System;
using Microsoft.Build.Framework;
using Microsoft.Build.Utilities;
using Microsoft.Web.Publishing.Tasks;
namespace Thanks.IllWriteMyOwnTasks
{
public class MyCustomTransformXml : TransformXml // no idea if you can do this
{
public override bool Execute()
{
// do stuff here,
// maybe declare parameters that you can pass down to base.Execute()
return true;
}
}
}
..
<!--<UsingTask TaskName="TransformXml" AssemblyFile="$(MSBuildExtensionsPath)\Microsoft\VisualStudio\v11.0\Web\Microsoft.Web.Publishing.Tasks.dll" />-->
<UsingTask TaskName="MyCustomTransformXml" AssemblyFile="Thanks.IllWriteMyOwnTasks.dll" />
For the second part, I think you can use ItemGroup.
<ItemGroup>
<MyEnvironments Include="PROD1" />
<MyEnvironments Include="PROD2" />
<MyEnvironments Include="PROD3" />
<MyEnvironments Include="PROD4" />
</ItemGroup>
<Target Name="BeforeBuild">
<TransformXml Source="Web.config"
Transform="Web.%(MyEnvironments.Identity).config"
Destination="Web.config.%(MyEnvironments.Identity)" />
</Target>
I haven't tested this, but I think based on what I see over here it will automatically repeat the same task as it iterates over MyEnvironments in this example.
You can add the extra transform files to your solution without adding a new solution configuration, and run the transform as in your own example (except for the target. 'Build' didn't work for me):
<Project ToolsVersion="12.0" DefaultTargets="Build">
...
<Target Name="BeforeBuild">
<TransformXml Source="Web.config" Transform="Web.PROD1.config" Destination="Web.config.PROD1" />
<TransformXml Source="Web.config" Transform="Web.PROD2.config" Destination="Web.config.PROD2" />
...
</Target>
</Project>
If you are only changing a connectionstring, your transform file will be pretty minimal:
<?xml version="1.0" encoding="utf-8"?>
<configuration xmlns:xdt="http://schemas.microsoft.com/XML-Document-Transform">
<connectionStrings>
<add name="MyDB"
connectionString="Data Source=PROD1SQLServer;Initial Catalog=MyReleaseDB;Integrated Security=True"
xdt:Transform="SetAttributes" xdt:Locator="Match(name)"/>
</connectionStrings>
</configuration>
After adding the above, and compiling, you will need to add the newly generated Web.config.PRODX files to your solution. After adding them, you simply open properties for each file and ensure that their compile action is set to 'Content'. This will mean that they are included in your deployments.
As the web.PRODX.config transform files are not part of a solution configuration, you could stick them in a folder to reduce clutter.

Ant tasks don't run IN IzPack installer

.
Hello, everyone
I'm studying IzPack as a tool to be used in a future project and I'm really enjoying it. It's as flexible as I need and makes the process much more easy. I have even submmited a silly pull request at github with a modification I needed to my purposes. Who knows?
Although I don't find it particularly complicated, I've been stuck trying to use a resource for some days. I need that certain Ant Tasks to be executed in certain points of the installation process (right before everything is unpacked is the really one that matters) and that is not working, besides all the efford. :(
My current state, that seems right looking at examples, is the following:
[ My current use of this is based on an example I found here (the docs don't clear too much when It cames to these kind of Actions.]
In my definitions xml file, I included some things:
First, the AntActionsSpect.xml and the .jars, followed by the listeners:
<resources>
...
<res id="AntActionsSpec.xml" src="specs/AntActionsSpec.xml" />
...
</resources>
<jar src="libs/ant/ant.jar" stage="both" />
<jar src="libs/ant/ant-launcher.jar" stage="both" />
<listeners>
<listener classname="AntActionInstallerListener" stage="install" />
<listener classname="AntActionUninstallerListener" stage="uninstall" />
</listeners>
<pack name="test_app" required="yes" installGroups="Application Core">
...
In the specs/AntActionsSpec.xml file, I have the following:
<pack name="test_app">
<antcall order="beforepacks" quiet="no" verbose="yes" buildfile="$INSTALL_PATH/ant-tasks.xml">
<property name="INSTALL_PATH" value="$INSTALL_PATH" />
<target name="touch_beforepacks" />
</antcall>
</pack>
And the ant-tasks.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<project>
<target name="touch_beforepacks">
<touch file="$INSTALL_PATH/beforepacks.txt"/>
</target>
</project>
Nothing special here, just creating a dumb file.
The ant-tasks.xml is unpacked right before anyone else. Everything builds with no error, even if I create one "mistake" at AntActionsSpec or ant-tasks.xml, what suggests me that they aren't even been loaded, though if I mess with the path where the definitions file has them, the build will fail.
I would like some help addressing that. I'm probably making some stupid little error and just can't see it by myself. If any of you could provide an example of a running build, that would be sweet.
If I can give any more information, please, let me known so I can update the question.
Thank you very much.
Just found it using a forum on a Google Groups discussion: [izpack-user] Quick question on variable substitution.
Unfortunattly the I will conclude that the docs are misleading. The docs in
"AntActionInstallerListener and AntActionUninstallerListener" until this date are stating that I should use this listener configuration:
<listeners>
<listener classname="AntActionInstallerListener" stage="install" />
<listener classname="AntActionUninstallerListener" stage="uninstall" />
</listeners>
That is what is up there, in the question. Comparing my XML code with the one in the Google Groups discussion, I found a different use of it:
<listeners>
<listener installer="AntActionInstallerListener"
uninstaller="AntActionUninstallerListener" />
</listeners>
In fact, that is the instruction given in the other wiki: Ant Actions (InstallerListener and UninstallerListener), what points out that I something can be wrong under the hood, but that is a story to another episode.
That just works. The Ant tasks are executed properly. :)
I just could not find where freaking Codehaus will allow me to grab a login and edit the docs wiki. >:( . If someone could endorse-me with some testing and then adjust the wiki for future happiness or just give a link to this tired programmer, I'd be happy.

NLog internal log not working with ASP.Net MVC

I have a problem with NLog for logging its internal logs with this configuration
<?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"
throwExceptions="true"
internalLogFile="${basedir}/App_Data/NLog.log"
internalLogLevel="Trace">
<targets>
<target name="debug"
xsi:type="File"
fileName="${basedir}/App_Data/Site.log" />
</targets>
<rules>
<logger name="*"
writeTo="debug" />
</rules>
</nlog>
The target "debug" is working well, but the internalLogFile is only working if I set it for exemple to "D:/NLog.log".
Any idea why this happening?
You can't use layout renderers ${...} in the internalLogFile property. They are for a target's layout only:
<target layout="${...}" />
Try to use relative path like "..\App_Data\NLog.log"
Update NLog 4.6 enables some simple layouts.
The internalLogFile attribute needs to be set to an absolute path and the executing assembly needs to have permission to write to that absolute path.
The following worked for me.
Create a folder somewhere - e.g. the route of your c: drive, e.g. c:\logs
Edit the permissions of this folder and give full control to everyone
Set your nlog config: internalLogFile="C:\logs\nlog.txt"
Remember to clean up after yourself and not leave a directory with those sorts of permissions on
NLog ver. 4.6 add support for environment-variables like %appdata% or %HOME%, and using these basic layouts in internalLogFile=:
${currentdir}
${basedir}
${tempdir}
NLog ver. 4.7 also adds this:
${processdir}
See also: https://github.com/NLog/NLog/wiki/Internal-Logging
from this link I think the path is absolute

NLog throws configuration exception on all aspnet layout renderers

I have been working to set up NLog v2 on my ASP.NET MVC 3 application and it has worked very well so far. (I'm using the package from the offical nuGet repository) However, when I try to change the log layout to include any of the aspnet-* layout renderers, I get a configuration error. I've reduced the problem to the following minimum use case:
In the configSections block:
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
The Nlog block:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true">
<variable name="logDirectory" value="C:\Logs" />
<targets>
<target name="logFile" xsi:type="File" fileName="${logDirectory}\app.log"
layout="${aspnet-user-identity}" />
</targets>
<rules>
<logger name="*" minlevel="Info" writeTo="logfile" />
</rules>
If I change layout use any combination of renderers that are not part of the aspnet* family, this works well (I haven't tested every one, but I've looked at quite a few). The error I get is here:
Configuration Error
Description: An error occurred during the processing of a configuration file required to service this request. Please review the specific error details below and modify your configuration file appropriately.
Parser Error Message: An error occurred creating the configuration section handler for nlog: Exception occurred when loading configuration from C:\..[snip]..\web.config
Source Error:
Line 16: </configSections>
Line 17:
Line 18: <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
Line 19: xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" throwExceptions="true">
Line 20:
I have really no idea what's going on. I'm not sure what about that renderer causes the configuration to become invalid. I've been banging around at it most of the day and have gotten nowhere, so I'm hoping someone here can help.
Thank you!
Make sure you have referenced the NLog.Extended assembly which is where those layouts are defined and which must have been added by the NuGet package as well to the references:
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
throwExceptions="true">
<extensions>
<add assembly="NLog.Extended" />
</extensions>
<variable name="logDirectory" value="C:\Logs" />
<targets>
<target name="logFile"
xsi:type="File"
fileName="${logDirectory}\app.log"
layout="${aspnet-user-identity} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Debug" writeTo="logfile" />
</rules>
</nlog>
As of NLog 4.0 the ASP.NET renderes are now in Nlog.Web
http://nlog-project.org/2015/06/13/NLog-Extended_NLog-Web_and_NLog-Windows-Forms.html
Alternative solution if Darin's doesn't work
You must have NLog.Extended referenced as Darin mentions
http://nuget.org/packages/NLog.Extended
As of NLog 2.0 you do not need to add reference in the configuration XML.
My problem was that I had no hard references to NLog.Extended in my web layer (where my web.config is) so the compiler wasn't copying the file where it needed to be.
This can be easily fixed by adding a hard reference to NLog.Extended that is a no-op wherever you are configuring your logging:
//forces the compiler to include NLog.Extensions in all downstream output directories
private static AspNetApplicationValueLayoutRenderer blank = new AspNetApplicationValueLayoutRenderer();
In my case I was using extension of le_nlog and for a reason, it was not installed in the app !
so I installed *le_nlog* by doing so :
PM> Install-Package le_nlog

Resources