Convert.FromBase64String not working after v14 Upgrade - dotnetnuke

We just upgraded our 2sxc custom API to v14, and now we're having an issue in an API controller that's used for uploading files with converting from Base64 to a byte array. Here's the code:
public class IntegrationApiController : Custom.Hybrid.Api14
{
[HttpPost]
public string UploadPdf([FromBody] dynamic bodyJson)
{
var entity = new Dictionary<string, object>();
var guid = Guid.NewGuid();
entity.Add("EntityGuid", guid);
App.Data.Create("PDFForm", entity);
var data = Convert.FromBase64String(bodyJson.file.ToString());
var returnThing = SaveInAdam(stream: new MemoryStream(data), fileName: bodyJson.fileName.ToString(), contentType: "PDFForm", guid: guid, field: "File");
return returnThing.Url;
}
}
We're getting the following error now:
{
"Message": "2sxc Api Controller Finder Error: Error selecting / compiling an API controller. Check event-log, code and inner exception. ",
"ExceptionMessage": "c:\\Websites\\Mainstar\\Portals\\0\\2sxc\\DocusignForms\\api\\IntegrationApiController.cs(26): error CS1061: 'ToSic.Sxc.Services.IConvertService' does not contain a definition for 'FromBase64String' and no extension method 'FromBase64String' accepting a first argument of type 'ToSic.Sxc.Services.IConvertService' could be found (are you missing a using directive or an assembly reference?)",
"ExceptionType": "System.Web.HttpCompileException",
"StackTrace": " at System.Web.Compilation.AssemblyBuilder.Compile()\r\n at System.Web.Compilation.BuildProvidersCompiler.PerformBuild()\r\n at System.Web.Compilation.BuildManager.CompileWebFile(VirtualPath virtualPath)\r\n at System.Web.Compilation.BuildManager.GetVPathBuildResultInternal(VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)\r\n at System.Web.Compilation.BuildManager.GetVPathBuildResultWithNoAssert(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean throwIfNotFound, Boolean ensureIsUpToDate)\r\n at System.Web.Compilation.BuildManager.GetVPathBuildResult(HttpContext context, VirtualPath virtualPath, Boolean noBuild, Boolean allowCrossApp, Boolean allowBuildInPrecompile, Boolean ensureIsUpToDate)\r\n at System.Web.Compilation.BuildManager.GetCompiledAssembly(String virtualPath)\r\n at ToSic.Sxc.Dnn.WebApiRouting.AppApiControllerSelector.HttpControllerDescriptor(HttpRequestMessage request, String controllerFolder, String controllerPath, String controllerTypeName, LogCall`1 wrapLog) in C:\\Projects\\2sxc\\2sxc\\Src\\Dnn\\ToSic.Sxc.Dnn.WebApi\\Dnn\\WebApiRouting\\AppApiControllerSelector.cs:line 168\r\n at ToSic.Sxc.Dnn.WebApiRouting.AppApiControllerSelector.SelectController(HttpRequestMessage request) in C:\\Projects\\2sxc\\2sxc\\Src\\Dnn\\ToSic.Sxc.Dnn.WebApi\\Dnn\\WebApiRouting\\AppApiControllerSelector.cs:line 83"
}
Any ideas how to fix this? I did try changing "Convert.FromBase64String" to "System.Convert.FromBase64String" and that didn't solve the issue - I got a "Cannot perform runtime binding on a null reference" error instead.
Any help would be greatly appreciated!

System.Convert... sounds right. And IMHO should work.
My guess is that your bodyJson or bodyJson.file is null.

Related

Invalid column name when using EF Core filtered includes

I came across this error when modifying a DB first project (using fluent migrator) and scaffolding the EF context to generate models. I have reproduced it by making a code-first simplification. This means that I can't accept answers that suggest modifying the annotations or fluent configuration, because this will be deleted and recreated on the next migration and scaffold.
The simplified idea is that a device has:
many attributes
many histories representing changes to the device over time
each history entry has an optional location
IOW you can move a device around to locations (or no location) and keep track of that over time.
The code-first model I came up with to simulate this is as follows:
public class ApiContext : DbContext
{
public ApiContext(DbContextOptions<ApiContext> options) : base(options) { }
public DbSet<Device> Devices { get; set; }
public DbSet<History> Histories { get; set; }
public DbSet<Location> Locations { get; set; }
}
public class Device
{
public int DeviceId { get; set; }
public string DeviceName { get; set; }
public List<History> Histories { get; } = new List<History>();
public List<Attribute> Attributes { get; } = new List<Attribute>();
}
public class History
{
public int HistoryId { get; set; }
public DateTime DateFrom { get; set; }
public string State { get; set; }
public int DeviceId { get; set; }
public Device Device { get; set; }
public int? LocationId { get; set; }
public Location Location { get; set; }
}
public class Attribute
{
public int AttributeId { get; set; }
public string Name { get; set; }
public int DeviceId { get; set; }
public Device Device { get; set; }
}
public class Location
{
public int LocationId { get; set; }
public string LocationName { get; set; }
public List<History> Histories { get; } = new List<History>();
}
Running the following query to select all devices works fine. I'm using a filtered include to only select the most recent history for this "view":
var devices = _apiContext.Devices.AsNoTracking()
.Include(d => d.Histories.OrderByDescending(h => h.DateFrom).Take(1))
.ThenInclude(h => h.Location)
.Include(d => d.Attributes)
.Select(d => d.ToModel()).ToList();
that works fine, however when I try and select only one device by ID using the same includes:
var device = _apiContext.Devices.AsNoTracking()
.Include(d => d.Histories.OrderByDescending(h => h.DateFrom).Take(1))
.ThenInclude(h => h.Location)
.Include(d => d.Attributes)
.First(d => d.DeviceId == deviceId)
.ToModel();
I get the following error:
Unhandled exception. Microsoft.Data.SqlClient.SqlException (0x80131904): Invalid column name 'LocationId'.
Invalid column name 'HistoryId'.
Invalid column name 'DateFrom'.
Invalid column name 'LocationId'.
Invalid column name 'State'.
at Microsoft.Data.SqlClient.SqlConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection, Action`1 wrapCloseInAction)
at Microsoft.Data.SqlClient.TdsParser.ThrowExceptionAndWarning(TdsParserStateObject stateObj, Boolean callerHasConnectionLock, Boolean asyncClose)
at Microsoft.Data.SqlClient.TdsParser.TryRun(RunBehavior runBehavior, SqlCommand cmdHandler, SqlDataReader dataStream, BulkCopySimpleResultSet bulkCopyHandler, TdsParserStateObject stateObj, Boolean& dataReady)
at Microsoft.Data.SqlClient.SqlDataReader.TryConsumeMetaData()
at Microsoft.Data.SqlClient.SqlDataReader.get_MetaData()
at Microsoft.Data.SqlClient.SqlCommand.FinishExecuteReader(SqlDataReader ds, RunBehavior runBehavior, String resetOptionsString, Boolean isInternal, Boolean forDescribeParameterEncryption, Boolean shouldCacheForAlwaysEncrypted)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReaderTds(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, Boolean isAsync, Int32 timeout, Task& task, Boolean asyncWrite, Boolean inRetry, SqlDataReader ds, Boolean describeParameterEncryptionRequest)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, TaskCompletionSource`1 completion, Int32 timeout, Task& task, Boolean& usedCache, Boolean asyncWrite, Boolean inRetry, String method)
at Microsoft.Data.SqlClient.SqlCommand.RunExecuteReader(CommandBehavior cmdBehavior, RunBehavior runBehavior, Boolean returnStream, String method)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.SqlClient.SqlCommand.ExecuteDbDataReader(CommandBehavior behavior)
at System.Data.Common.DbCommand.ExecuteReader()
at Microsoft.EntityFrameworkCore.Storage.RelationalCommand.ExecuteReader(RelationalCommandParameterObject parameterObject)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.InitializeReader(DbContext _, Boolean result)
at Microsoft.EntityFrameworkCore.SqlServer.Storage.Internal.SqlServerExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.SingleQueryingEnumerable`1.Enumerator.MoveNext()
at System.Linq.Enumerable.Single[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.First[TSource](IQueryable`1 source, Expression`1 predicate)
at efcore_test.App.PrintSingleDevice(Int32 deviceId) in C:\Users\Iain\projects\efcore-5-bug\efcore-test\App.cs:line 44
at efcore_test.Program.<>c__DisplayClass1_0.<Main>b__4(App app) in C:\Users\Iain\projects\efcore-5-bug\efcore-test\Program.cs:line 28
at efcore_test.Program.RunInScope(IServiceProvider serviceProvider, Action`1 method) in C:\Users\Iain\projects\efcore-5-bug\efcore-test\Program.cs:line 35
at efcore_test.Program.Main(String[] args) in C:\Users\Iain\projects\efcore-5-bug\efcore-test\Program.cs:line 28
ClientConnectionId:1418edb2-0889-4f4d-9554-85344c9a35a9
Error Number:207,State:1,Class:16
I can't figure out why this is working for a number of rows but not working for a single row.
For completeness, ToModel() is just an extension method to return a POCO.
I'm not even sure where to start looking, ideas welcome!
Edit
bug report: https://github.com/dotnet/efcore/issues/26585
repro: https://github.com/thinkOfaNumber/efcore-5-test
Update: The bug is fixed in EF Core 6.0, so the next applies to EF Core 5.0 only.
Looks like you have hit EF Core 5.0 query translation bug, so I would suggest to seek/report it to EF Core GitHub issue tracker.
From what I can tell, it's caused by "pushing down" the root query as subquery because of the Take operator (which is basically what First method is using in the second case). This somehow messes up the generated subquery aliases and leads to invalid SQL.
It can be seen by comparing the generated SQL for the first query
SELECT [d].[DeviceId], [d].[DeviceName], [t0].[HistoryId], [t0].[DateFrom], [t0].[DeviceId], [t0].[LocationId], [t0].[State], [t0].[LocationId0], [t0].[LocationName], [a].[AttributeId], [a].[DeviceId], [a].[Name]
FROM [Devices] AS [d]
OUTER APPLY (
SELECT [t].[HistoryId], [t].[DateFrom], [t].[DeviceId], [t].[LocationId], [t].[State], [l].[LocationId] AS [LocationId0], [l].[LocationName]
FROM (
SELECT TOP(1) [h].[HistoryId], [h].[DateFrom], [h].[DeviceId], [h].[LocationId], [h].[State]
FROM [Histories] AS [h]
WHERE [d].[DeviceId] = [h].[DeviceId]
ORDER BY [h].[DateFrom] DESC
) AS [t]
LEFT JOIN [Locations] AS [l] ON [t].[LocationId] = [l].[LocationId]
) AS [t0]
LEFT JOIN [Attribute] AS [a] ON [d].[DeviceId] = [a].[DeviceId]
ORDER BY [d].[DeviceId], [t0].[DateFrom] DESC, [t0].[HistoryId], [t0].[LocationId0], [a].[AttributeId]
and for the second (or just inserting .Where(d => d.DeviceId == deviceId).Take(1) before Select in the first):
SELECT [t].[DeviceId], [t].[DeviceName], [t1].[HistoryId], [t1].[DateFrom], [t1].[DeviceId], [t1].[LocationId], [t1].[State], [t1].[LocationId0], [t1].[LocationName], [a].[AttributeId], [a].[DeviceId], [a].[Name]
FROM (
SELECT TOP(1) [d].[DeviceId], [d].[DeviceName]
FROM [Devices] AS [d]
WHERE [d].[DeviceId] = #__deviceId_0
) AS [t]
OUTER APPLY (
SELECT [t].[HistoryId], [t].[DateFrom], [t].[DeviceId], [t].[LocationId], [t].[State], [l].[LocationId] AS [LocationId0], [l].[LocationName]
FROM (
SELECT TOP(1) [h].[HistoryId], [h].[DateFrom], [h].[DeviceId], [h].[LocationId], [h].[State]
FROM [Histories] AS [h]
WHERE [t].[DeviceId] = [h].[DeviceId]
ORDER BY [h].[DateFrom] DESC
) AS [t0]
LEFT JOIN [Locations] AS [l] ON [t].[LocationId] = [l].[LocationId]
) AS [t1]
LEFT JOIN [Attribute] AS [a] ON [t].[DeviceId] = [a].[DeviceId]
ORDER BY [t].[DeviceId], [t1].[DateFrom] DESC, [t1].[HistoryId], [t1].[LocationId0], [a].[AttributeId]
Note the usage of [t] in the first SELECT [t].[HistoryId]... inside the OUTER APPLY, which in the fist query is alias to the inner Histories subquery in FROM clause, while in second it is alias to the outer Devices subquery, which of couse have no columns mentioned in the error message. Apparently in the second case [t0] should have been used.
Since it is a bug, you have to wait it to be fixed. Until then, the workaround I could suggest is to explicitly execute row limiting operator (First) outside of the EF Core query context, e.g.
var device = _apiContext.Devices.AsNoTracking()
.Include(d => d.Histories.OrderByDescending(h => h.DateFrom).Take(1))
.ThenInclude(h => h.Location)
.Include(d => d.Attributes)
.Where(d => d.DeviceId == deviceId) // instead of .First(d => d.DeviceId == deviceId)
.AsEnumerable() // switch to client evaluation (LINQ to Objects context)
.First() // and execute `First` here
.ToModel();

Retrieving XML from database with Dapper

I am using Dapper to query a table that includes an XML field:
CREATE TABLE Workflow
(
Guid uniqueidentifier not null,
State xml not null
)
which is then mapped to a property of type XDocument:
public class Workflow
{
public Guid InstanceId { get;set; }
public XDocument State { get;set; }
}
but when I try to query the table, I get the following error:
Error parsing column 1 (State= - String)
at Dapper.SqlMapper.ThrowDataException(Exception ex, Int32 index, IDataReader reader, Object value) in d:\\Dev\\dapper-dot-net\\Dapper NET40\\SqlMapper.cs:line 4045
at Deserialize038b29f4-d97d-4b62-b45b-786bd7d50e7a(IDataReader )
at Dapper.SqlMapper.<QueryImpl>d__11`1.MoveNext() in d:\\Dev\\dapper-dot-net\\Dapper NET40\\SqlMapper.cs:line 1572
at System.Collections.Generic.List`1..ctor(IEnumerable`1 collection)
at System.Linq.Enumerable.ToList[TSource](IEnumerable`1 source)
at Dapper.SqlMapper.Query[T](IDbConnection cnn, String sql, Object param, IDbTransaction transaction, Boolean buffered, Nullable`1 commandTimeout, Nullable`1 commandType) in d:\\Dev\\dapper-dot-net\\Dapper NET40\\SqlMapper.cs:line 1443
at MyProject.DapperBase.Query[TResult](String command, DynamicParameters parameters, IDbTransaction transaction, Boolean buffered, Int32 commandTimeout) in d:\\MyProject\\DapperBase.cs:line 122
at MyProject.WorkflowData.Get(Guid identifier) in d:\\MyProject\\WorkflowData.cs:line 41
at MyProject.WorkflowLogic.Save(Workflow workflow) in d:\\MyProject\\WorkflowLogic.cs:line 34
at MyProject.WorkflowsController.Save(Guid id, WorkflowRequest request) in d:\\MyProject\\WorkflowsController.cs:line 97
InnerException: Invalid cast from 'System.String' to 'System.Xml.Linq.XDocument'.
at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider)at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
at System.Convert.ChangeType(Object value, Type conversionType)
at Deserialize038b29f4-d97d-4b62-b45b-786bd7d50e7a(IDataReader )
Other than modifying my POCO to use a string datatype and then convert the string into an XDocument elsewhere, is there a way of getting Dapper to correctly deserialise the XML from the database?
In the end, I just brute-forced it:
public class Workflow
{
public Guid InstanceId { get;set; }
public XDocument StateIn { set { State = value.ToString(); } }
public string State { get;set; }
public XDocument StateOut { get { return XDocument.Parse(State); } }
}
Dapper plays with the State value, and I just set the value on StateIn and read it off StateOut. I feel a little bit dirty coming up with a solution like this, but hey, it works.
Perhaps creating a custom type handler can help? Something like:
public class XDocumentTypeHandler : SqlMapper.TypeHandler<XDocument>
{
public override void SetValue(IDbDataParameter parameter, XDocument value)
{
// set value in db parameter.
}
public XDocument Parse(object value)
{
// parse value from db to an XDocument.
}
}
You have to add the type handler with SqlMapper.AddTypeHandler().
See a sample implementation.

NHibernate 2nd level cache with Prevalence

I'm writing a Windows Forms application which needs to store some NHibernate's entities data in a persistent 2nd layer cache. As far as I know, the only 2nd level cache provider which satisfies my app's requirements is Prevalence, but I'm getting an awkward exception when I configure it:
System.ArgumentNullException was unhandled
Message=Value cannot be null.
Parameter name: key
Source=mscorlib
ParamName=key
StackTrace:
at System.Collections.Generic.Dictionary`2.FindEntry(TKey key)
at System.Collections.Generic.Dictionary`2.TryGetValue(TKey key, TValue& value)
at NHibernate.Impl.SessionFactoryObjectFactory.GetNamedInstance(String name)
at NHibernate.Impl.SessionFactoryImpl.GetRealObject(StreamingContext context)
at System.Runtime.Serialization.ObjectManager.ResolveObjectReference(ObjectHolder holder)
at System.Runtime.Serialization.ObjectManager.DoFixups()
at System.Runtime.Serialization.Formatters.Binary.ObjectReader.Deserialize(HeaderHandler handler, __BinaryParser serParser, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream, HeaderHandler handler, Boolean fCheck, Boolean isCrossAppDomain, IMethodCallMessage methodCallMessage)
at System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize(Stream serializationStream)
at Bamboo.Prevalence.Implementation.PendingCommandsEnumerator.NextCommand()
at Bamboo.Prevalence.Implementation.PendingCommandsEnumerator.MoveNext()
at Bamboo.Prevalence.PrevalenceEngine.RecoverCommands(CommandLogReader reader, ExceptionDuringRecoveryHandler handler)
at Bamboo.Prevalence.PrevalenceEngine.RecoverSystem(Type systemType, CommandLogReader reader, ExceptionDuringRecoveryHandler handler)
at Bamboo.Prevalence.PrevalenceEngine..ctor(Type systemType, String prevalenceBase, BinaryFormatter formatter, ExceptionDuringRecoveryHandler handler)
at Bamboo.Prevalence.TransparentPrevalenceEngine..ctor(Type systemType, String prevalenceBase, BinaryFormatter formatter, ExceptionDuringRecoveryHandler handler)
at Bamboo.Prevalence.TransparentPrevalenceEngine..ctor(Type systemType, String prevalenceBase, BinaryFormatter formatter)
at Bamboo.Prevalence.PrevalenceActivator.CreateTransparentEngine(Type systemType, String prevalenceBase, BinaryFormatter formatter)
at Bamboo.Prevalence.PrevalenceActivator.CreateTransparentEngine(Type systemType, String prevalenceBase)
at NHibernate.Caches.Prevalence.PrevalenceCacheProvider.SetupEngine()
at NHibernate.Caches.Prevalence.PrevalenceCacheProvider.Start(IDictionary`2 properties)
at NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners)
at NHibernate.Cfg.Configuration.BuildSessionFactory()
at AcessoDados.DB.Configure() in C:\Users\Herberth\MyProject\DataAccess\DB.cs:line 78
This is only extra code I'm using:
configuration.SessionFactory().Caching.Through<NHibernate.Caches.Prevalence.PrevalenceCacheProvider>().PrefixingRegionsWith("MyRegion").WithDefaultExpiration(60);
It works fine when I comment out this line (without the cache, of course);
Here's the complete code I'm using:
configuration = new Configuration();
var mapper = new ModelMapper();
mapper.AddMappings(Assembly.GetExecutingAssembly().GetExportedTypes());
HbmMapping domainMapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
configuration.DataBaseIntegration(c =>
{
c.Dialect<MySQLDialect>();
c.ConnectionString = #"Server=localhost;Database=mydb;Uid=root;Pwd=mypwd";
c.ConnectionString = DBConnectionStrings.Principal;
c.LogFormattedSql = true;
c.LogSqlInConsole = true;
c.IsolationLevel = System.Data.IsolationLevel.ReadCommitted;
});
configuration.AddMapping(domainMapping);
configuration.Cache(c => { c.UseQueryCache = true; });
configuration.SessionFactory().Caching.Through<NHibernate.Caches.Prevalence.PrevalenceCacheProvider>().PrefixingRegionsWith("MyRegion").WithDefaultExpiration(60);
SessionFactory = configuration.BuildSessionFactory();
All dependencies are in their latest version.
Thanks in advance!
I had this issue because the directories NHibernate.Cache.StandardQueryCache and UpdateTimestampsCache in the executable directory got out of date.
However, that lead to the next issue -- I couldn't install under Program Files because NHibernate attempted to create these directories on first run.

Import values from CSV into SQL Server

I'm in need of importing CSV data from a client computer to a SQL Server which exists elsewhere on the network. I want to do this with PowerShell as I'm trying to become more fluent in using it.
However, when I use an example I've found on the internet I've run into an issue which I don't understand.
For reference I'm using the third example from:
http://blogs.technet.com/b/heyscriptingguy/archive/2011/11/28/four-easy-ways-to-import-csv-files-to-sql-server-with-powershell.aspx
I've got the information importing into the datatable, however it appears that once the system tries to insert the data into the database I get the following error which is apparently an issue with how my data is getting into my datatable because the at symbol and bracket seem to be causing the issue.
This is the error:
System.Management.Automation.MethodException: Cannot convert argument "0", with value: "System.Object[]", for "WriteToServer" to
type "System.Data.DataRow[]":
"Cannot convert the "#{[Type]=1; [EID]=803; [FirstName]=Bob; [MiddleInit]=; [LastName]=Miller; [HireDate]=03031903; [Rule]=H;
[Rate]=0100; [Status]=1; [Store]=8; [Dept]=04; [Class]=130;
[Badge]=803;}" value of type
"System.Management.Automation.PSCustomObject" to type "System.Data.DataRow"."
---> System.Management.Automation.PSInvalidCastException: Cannot convert
the "#{[Type]=1; [EID]=803; [FirstName]=Bob; [MiddleInit]=;
[LastName]=Miller; [HireDate]=03031903; [Rule]=H; [Rate]=0100;
[Status]=1; [Store]=8; [Dept]=04; [Class]=130; [Badge]=803;}" value of
type "System.Management.Automation.PSCustomObject" to type
"System.Data.DataRow".
at System.Management.Automation.LanguagePrimitives.ConvertTo(Object
valueToConvert, Type resultType, Boolean recursion, IFormatProvider
formatProvider, TypeTable backupTypeTable)
at System.Management.Automation.LanguagePrimitives.ConvertUnrelatedArrays(Object
valueToConvert, Type resultType, Boolean recursion, PSObject
originalValueToConvert, IFormatProvider formatProvider, TypeTable backupTable)
at System.Management.Automation.LanguagePrimitives.ConvertTo(Object
valueToConvert, Type resultType, Boolean recursion, IFormatProvider
formatProvider, TypeTable backupTypeTable)
at System.Management.Automation.Adapter.PropertySetAndMethodArgumentConvertTo(Object
valueToConvert, Type resultType, IFormatProvider formatProvider)
at System.Management.Automation.Adapter.MethodArgumentConvertTo(Object
valueToConvert, Boolean isParameterByRef, Int32 parameterIndex, Type
resultType, IFormatProvider formatProvider)
at System.Management.Automation.Adapter.SetNewArgument(String methodName, Object[] arguments, Object[] newArguments,
ParameterInformation parameter, Int32 index)
--- End of inner exception stack trace ---
at System.Management.Automation.Adapter.SetNewArgument(String methodName, Object[] arguments, Object[] newArguments,
ParameterInformation parameter, Int32 index)
at System.Management.Automation.Adapter.GetMethodArgumentsBase(String
methodName, ParameterInformation[] parameters, Object[] arguments,
Boolean expandParamsOnBest)
at System.Management.Automation.DotNetAdapter.MethodInvokeDotNet(String
methodName, Object target, MethodInformation[] methodInformation,
Object[] arguments)
at System.Management.Automation.Adapter.BaseMethodInvoke(PSMethod method,
Object[] arguments)
at System.Management.Automation.ParserOps.CallMethod(Token token, Object target, String methodName, Object[] paramArray, Boolean
callStatic, Object valueToSet)
at System.Management.Automation.MethodCallNode.InvokeMethod(Object
target, Object[] arguments, Object value)
at System.Management.Automation.MethodCallNode.Execute(Array input, Pipe outputPipe, ExecutionContext context)
at System.Management.Automation.ParseTreeNode.Execute(Array input, Pipe outputPipe, ArrayList& resultList, ExecutionContext context)
at System.Management.Automation.StatementListNode.ExecuteStatement(ParseTreeNode
statement, Array input, Pipe outputPipe, ArrayList& resultList,
ExecutionContext context)
Message + CategoryInfo : NotSpecified: (:) [Write-Error], WriteErrorException
+ FullyQualifiedErrorId : Microsoft.PowerShell.Commands.WriteErrorException,Write-DataTable.PS1

WPF unity Activation error occured while trying to get instance of type

I am getting the following error when trying to Initialise the Module using Unity and Prism. The DLL is found by
return new DirectoryModuleCatalog() { ModulePath = #".\Modules" };
The dll is found and the Name is Found
#region Constructors
public AdminModule(
IUnityContainer container,
IScreenFactoryRegistry screenFactoryRegistry,
IEventAggregator eventAggregator,
IBusyService busyService
)
: base(container, screenFactoryRegistry)
{
this.EventAggregator = eventAggregator;
this.BusyService = busyService;
}
#endregion
#region Properties
protected IEventAggregator EventAggregator { get; set; }
protected IBusyService BusyService { get; set; }
#endregion
public override void Initialize()
{
base.Initialize();
}
#region Register Screen Factories
protected override void RegisterScreenFactories()
{
this.ScreenFactoryRegistry.Register(ScreenKeyType.ApplicationAdmin, typeof(AdminScreenFactory));
}
#endregion
#region Register Views and Various Services
protected override void RegisterViewsAndServices()
{
//View Models
this.Container.RegisterType<IAdminViewModel, AdminViewModel>();
}
#endregion
the code that produces the error is:
namespace Microsoft.Practices.Composite.Modularity
protected virtual IModule CreateModule(string typeName)
{
Type moduleType = Type.GetType(typeName);
if (moduleType == null)
{
throw new ModuleInitializeException(string.Format(CultureInfo.CurrentCulture, Properties.Resources.FailedToGetType, typeName));
}
return (IModule)this.serviceLocator.GetInstance(moduleType); <-- Error Here
}
Can Anyone Help Me
Error Log Below:
General Information
Additional Info:
ExceptionManager.MachineName: xxxxx
ExceptionManager.TimeStamp: 22/02/2010 10:16:55 AM
ExceptionManager.FullName: Microsoft.ApplicationBlocks.ExceptionManagement, Version=1.0.3591.32238, Culture=neutral, PublicKeyToken=null
ExceptionManager.AppDomainName: Infinity.vshost.exe
ExceptionManager.ThreadIdentity:
ExceptionManager.WindowsIdentity: xxxxx
1) Exception Information
Exception Type: Microsoft.Practices.Composite.Modularity.ModuleInitializeException
ModuleName: AdminModule
Message: An exception occurred while initializing module 'AdminModule'.
- The exception message was: Activation error occured while trying to get instance of type AdminModule, key ""
Check the InnerException property of the exception for more information. If the exception occurred
while creating an object in a DI container, you can exception.GetRootException() to help locate the
root cause of the problem.
Data: System.Collections.ListDictionaryInternal
TargetSite: Void HandleModuleInitializationError(Microsoft.Practices.Composite.Modularity.ModuleInfo, System.String, System.Exception)
HelpLink: NULL
Source: Microsoft.Practices.Composite
StackTrace Information
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.HandleModuleInitializationError(ModuleInfo moduleInfo, String assemblyName, Exception exception)
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
at Microsoft.Practices.Composite.Modularity.ModuleManager.InitializeModule(ModuleInfo moduleInfo)
at Microsoft.Practices.Composite.Modularity.ModuleManager.LoadModulesThatAreReadyForLoad()
at Microsoft.Practices.Composite.Modularity.ModuleManager.OnModuleTypeLoaded(ModuleInfo typeLoadedModuleInfo, Exception error)
at Microsoft.Practices.Composite.Modularity.FileModuleTypeLoader.BeginLoadModuleType(ModuleInfo moduleInfo, ModuleTypeLoadedCallback callback)
at Microsoft.Practices.Composite.Modularity.ModuleManager.BeginRetrievingModule(ModuleInfo moduleInfo)
at Microsoft.Practices.Composite.Modularity.ModuleManager.LoadModuleTypes(IEnumerable`1 moduleInfos)
at Microsoft.Practices.Composite.Modularity.ModuleManager.LoadModulesWhenAvailable()
at Microsoft.Practices.Composite.Modularity.ModuleManager.Run()
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.InitializeModules()
at Infinity.Bootstrapper.InitializeModules() in D:\Projects\dotNet\Infinity\source\Inifinty\Infinity\Application Modules\BootStrapper.cs:line 75
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.Run(Boolean runWithDefaultConfiguration)
at Microsoft.Practices.Composite.UnityExtensions.UnityBootstrapper.Run()
at Infinity.App.Application_Startup(Object sender, StartupEventArgs e) in D:\Projects\dotNet\Infinity\source\Inifinty\Infinity\App.xaml.cs:line 37
at System.Windows.Application.OnStartup(StartupEventArgs e)
at System.Windows.Application.<.ctor>b__0(Object unused)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Boolean isSingleParameter)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Boolean isSingleParameter, Delegate catchHandler)
2) Exception Information
Exception Type: Microsoft.Practices.ServiceLocation.ActivationException
Message: Activation error occured while trying to get instance of type AdminModule, key ""
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object GetInstance(System.Type, System.String)
HelpLink: NULL
Source: Microsoft.Practices.ServiceLocation
StackTrace Information
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType)
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.CreateModule(String typeName)
at Microsoft.Practices.Composite.Modularity.ModuleInitializer.Initialize(ModuleInfo moduleInfo)
3) Exception Information
Exception Type: Microsoft.Practices.Unity.ResolutionFailedException
TypeRequested: AdminModule
NameRequested: NULL
Message: Resolution of the dependency failed, type = "Infinity.Modules.Admin.AdminModule", name = "". Exception message is: The current build operation (build key Build Key[Infinity.Modules.Admin.AdminModule, null]) failed: The parameter screenFactoryRegistry could not be resolved when attempting to call constructor Infinity.Modules.Admin.AdminModule(Microsoft.Practices.Unity.IUnityContainer container, PhoenixIT.IScreenFactoryRegistry screenFactoryRegistry, Microsoft.Practices.Composite.Events.IEventAggregator eventAggregator, PhoenixIT.IBusyService busyService). (Strategy type BuildPlanStrategy, index 3)
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object DoBuildUp(System.Type, System.Object, System.String)
HelpLink: NULL
Source: Microsoft.Practices.Unity
StackTrace Information
*********************************************
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, String name)
at Microsoft.Practices.Unity.UnityContainer.Resolve(Type t, String name)
at Microsoft.Practices.Composite.UnityExtensions.UnityServiceLocatorAdapter.DoGetInstance(Type serviceType, String key)
at Microsoft.Practices.ServiceLocation.ServiceLocatorImplBase.GetInstance(Type serviceType, String key)
4) Exception Information
Exception Type: Microsoft.Practices.ObjectBuilder2.BuildFailedException
ExecutingStrategyTypeName: BuildPlanStrategy
ExecutingStrategyIndex: 3
BuildKey: Build Key[Infinity.Modules.Admin.AdminModule, null]
Message: The current build operation (build key Build Key[Infinity.Modules.Admin.AdminModule, null]) failed: The parameter screenFactoryRegistry could not be resolved when attempting to call constructor Infinity.Modules.Admin.AdminModule(Microsoft.Practices.Unity.IUnityContainer container, PhoenixIT.IScreenFactoryRegistry screenFactoryRegistry, Microsoft.Practices.Composite.Events.IEventAggregator eventAggregator, PhoenixIT.IBusyService busyService). (Strategy type BuildPlanStrategy, index 3)
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object ExecuteBuildUp(Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.Builder.BuildUp(IReadWriteLocator locator, ILifetimeContainer lifetime, IPolicyList policies, IStrategyChain strategies, Object buildKey, Object existing)
at Microsoft.Practices.Unity.UnityContainer.DoBuildUp(Type t, Object existing, String name)
5) Exception Information
Exception Type: System.InvalidOperationException
Message: The parameter screenFactoryRegistry could not be resolved when attempting to call constructor Infinity.Modules.Admin.AdminModule(Microsoft.Practices.Unity.IUnityContainer container, PhoenixIT.IScreenFactoryRegistry screenFactoryRegistry, Microsoft.Practices.Composite.Events.IEventAggregator eventAggregator, PhoenixIT.IBusyService busyService).
Data: System.Collections.ListDictionaryInternal
TargetSite: Void ThrowForResolutionFailed(System.Exception, System.String, System.String, Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForResolutionFailed(Exception inner, String parameterName, String constructorSignature, IBuilderContext context)
at BuildUp_Infinity.Modules.Admin.AdminModule(IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
6) Exception Information
Exception Type: Microsoft.Practices.ObjectBuilder2.BuildFailedException
ExecutingStrategyTypeName: BuildPlanStrategy
ExecutingStrategyIndex: 3
BuildKey: Build Key[PhoenixIT.IScreenFactoryRegistry, null]
Message: The current build operation (build key Build Key[PhoenixIT.IScreenFactoryRegistry, null]) failed: The current type, PhoenixIT.IScreenFactoryRegistry, is an interface and cannot be constructed. Are you missing a type mapping? (Strategy type BuildPlanStrategy, index 3)
Data: System.Collections.ListDictionaryInternal
TargetSite: System.Object ExecuteBuildUp(Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
at Microsoft.Practices.Unity.ObjectBuilder.NamedTypeDependencyResolverPolicy.Resolve(IBuilderContext context)
at BuildUp_Infinity.Modules.Admin.AdminModule(IBuilderContext )
7) Exception Information
Exception Type: System.InvalidOperationException
Message: The current type, PhoenixIT.IScreenFactoryRegistry, is an interface and cannot be constructed. Are you missing a type mapping?
Data: System.Collections.ListDictionaryInternal
TargetSite: Void ThrowForAttemptingToConstructInterface(Microsoft.Practices.ObjectBuilder2.IBuilderContext)
HelpLink: NULL
Source: Microsoft.Practices.ObjectBuilder2
StackTrace Information
at Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.ThrowForAttemptingToConstructInterface(IBuilderContext context)
at BuildUp_PhoenixIT.IScreenFactoryRegistry(IBuilderContext )
at Microsoft.Practices.ObjectBuilder2.DynamicMethodBuildPlan.BuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.BuildPlanStrategy.PreBuildUp(IBuilderContext context)
at Microsoft.Practices.ObjectBuilder2.StrategyChain.ExecuteBuildUp(IBuilderContext context)
For more information, see Help and Support Center at http://go.microsoft.com/fwlink/events.asp.
The innermost exception is the issue.
Your Module type needs a parameter called "screenFactoryRegistry" of type IScreenFactoryRegistry. Since IScreenFactoryRegistry is an interface and you apparently have not done a Register in the container to map that interface to a concrete type, the Unity container throws an exception.
To resolve this, you'd need to map that type in Unity, probably in the ConfigureContainer method of your bootstrapper:
Container.RegisterType<IScreenFactoryRegistry, MyScreenFactoryRegistryImplementation>();

Resources