When using Scaffold-DbContext for UWP I get 'Unable to load DLL 'sqlite3'' - sqlite

I am trying to scaffolf an Entityframeworkcore DbContext for a UWP app from a Sqlite databse. I do:
Scaffold-DbContext "data source=C:\SqliteDbFiles\Sqlite.db" Microsoft.EntityFrameworkCore.Sqlite
No matter what I try though I keep getting this error:
System.DllNotFoundException: Unable to load DLL 'sqlite3': This operation is only valid in the context of an app container. (Exception from HRESULT: 0x8007109A)
at Microsoft.Data.Sqlite.Interop.NativeMethods.Sqlite3_sqlite3.sqlite3_open_v2(IntPtr filename, Sqlite3Handle& ppDb, Int32 flags, IntPtr vfs)
at Microsoft.Data.Sqlite.Interop.NativeMethods.Sqlite3_sqlite3.open_v2(IntPtr filename, Sqlite3Handle& ppDb, Int32 flags, IntPtr vfs)
at Microsoft.Data.Sqlite.Interop.NativeMethods.sqlite3_open_v2(String filename, Sqlite3Handle& ppDb, Int32 flags, String vfs)
at Microsoft.Data.Sqlite.SqliteConnection.Open()
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqliteDatabaseModelFactory.Create(String connectionString, TableSelectionSet tableSelectionSet)
at Microsoft.EntityFrameworkCore.Scaffolding.RelationalScaffoldingModelFactory.Create(String connectionString, TableSelectionSet tableSelectionSet)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.SqliteScaffoldingModelFactory.Create(String connectionString, TableSelectionSet tableSelectionSet)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineeringGenerator.GetMetadataModel(ReverseEngineeringConfiguration configuration)
at Microsoft.EntityFrameworkCore.Scaffolding.Internal.ReverseEngineeringGenerator.GenerateAsync(ReverseEngineeringConfiguration configuration, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Design.DatabaseOperations.ReverseEngineerAsync(String provider, String connectionString, String outputDir, String dbContextClassName, IEnumerable`1 schemas, IEnumerable`1 tables, Boolean useDataAnnotations, Boolean overwriteFiles, CancellationToken cancellationToken)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.<ReverseEngineerImpl>d__21.MoveNext()
at System.Linq.Buffer`1..ctor(IEnumerable`1 source)
at System.Linq.Enumerable.ToArray[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.<>c__DisplayClass4_0`1.<Execute>b__0()
at Microsoft.EntityFrameworkCore.Design.OperationExecutor.OperationBase.Execute(Action action)
Unable to load DLL 'sqlite3': This operation is only valid in the context of an app container. (Exception from HRESULT: 0x8007109A)
Any help would be greatly appreciated

The version of sqlite3.dll used at runtime on UWP won't work at design-time. You can manually download one of the Precompiled Binaries for Windows and copy it to the output directory (e.g. bin\x86\Debug) before running the command.
A simpler solution might be to scaffold the DbContext in a non-UWP project and just copy the classes into the UWP project after they're generated.

Related

XMLSerializer throws Access Denied exception when code runs on web server but not locally

When I run the following line of code locally it runs succesfully. When I upload the code to the Arvixe web server I get the exception. I can read and write the temp folder as found by Path.GetTempPath()
I understand that XMLSerializer needs a temp path to create .DLLs. Does ASP.NET use a different temp path that it does not have permissions? I have compiled as Generate Serialization Assemblies Auto, Off and On to no avail. It must be a server setting as it runs on another Arvixe server but I dont know what to ask the server admins to do.
'This is the code line that causes the exception:
Sub Test
Dim formatter = New XmlSerializer(GetType(TestSMTPClass))
End Sub`
'This is a simple class we are trying to serialize
Public Class TestSMTPClass
Property ServerIP As String
Property Port As String
End Class
Throws this exception
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
ex.ToString
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Runtime.InteropServices.Marshal.ThrowExceptionForHRInternal(Int32 errorCode, IntPtr errorInfo)
at Microsoft.Win32.Fusion.ReadCache(ArrayList alAssems, String name, UInt32 nFlag)
at System.Reflection.RuntimeAssembly.EnumerateCache(AssemblyName partialName)
at System.Reflection.RuntimeAssembly.LoadWithPartialNameInternal(AssemblyName an, Evidence securityEvidence, StackCrawlMark& stackMark)
at System.Reflection.Assembly.LoadWithPartialName(String partialName, Evidence securityEvidence)
at System.Xml.Serialization.TempAssembly.LoadGeneratedAssembly(Type type, String defaultNamespace, XmlSerializerImplementation& contract)
at System.Xml.Serialization.XmlSerializer..ctor(Type type, String defaultNamespace)
at OCC_Competition.TestSMTP.btnTestCode_Click(Object sender, EventArgs e)

Swagger open and giving a error in .NET 6 MacOS Visual Studio 2022 preview 1

[41m[30mfail[39m[22m[49m: Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware[1]
An unhandled exception has occurred while executing the request.
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions.DefaultTagsSelector(ApiDescription apiDescription)
System.TypeLoadException: Could not load type 'Microsoft.AspNetCore.Http.Metadata.ITagsMetadata' from assembly 'Microsoft.AspNetCore.Http.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions.DefaultSortKeySelector(ApiDescription apiDescription)
at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
at System.Linq.EnumerableSorter`1.ComputeMap(TElement[] elements, Int32 count)
at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
at System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
at System.Linq.GroupedEnumerable`2.GetEnumerator()
at System.Linq.OrderedEnumerable`1.GetEnumerator()+MoveNext()
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware: Error: An unhandled exception has occurred while executing the request.
System.TypeLoadException: Could not load type 'Microsoft.AspNetCore.Http.Metadata.ITagsMetadata' from assembly 'Microsoft.AspNetCore.Http.Abstractions, Version=6.0.0.0, Culture=neutral, PublicKeyToken=adb9793829ddae60'.
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions.DefaultTagsSelector(ApiDescription apiDescription)
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGeneratorOptions.DefaultSortKeySelector(ApiDescription apiDescription)
at System.Linq.EnumerableSorter`2.ComputeKeys(TElement[] elements, Int32 count)
at System.Linq.EnumerableSorter`1.ComputeMap(TElement[] elements, Int32 count)
at System.Linq.EnumerableSorter`1.Sort(TElement[] elements, Int32 count)
at System.Linq.OrderedEnumerable`1.GetEnumerator()+MoveNext()
at System.Linq.Lookup`2.Create(IEnumerable`1 source, Func`2 keySelector, IEqualityComparer`1 comparer)
at System.Linq.GroupedEnumerable`2.GetEnumerator()
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GeneratePaths(IEnumerable`1 apiDescriptions, SchemaRepository schemaRepository)
at Swashbuckle.AspNetCore.SwaggerGen.SwaggerGenerator.GetSwagger(String documentName, String host, String basePath)
at Swashbuckle.AspNetCore.Swagger.SwaggerMiddleware.Invoke(HttpContext httpContext, ISwaggerProvider swaggerProvider)
at Microsoft.AspNetCore.Diagnostics.DeveloperExceptionPageMiddleware.Invoke(HttpContext context)
Use Visual Studio preview 3 and the exact 6.0.100 .net version (working for M1 chip as well)

SQL Server CE Entity Framework code-first, the specified connection does not specify Initial Catalog or AttachDbFileName

I have a desktop application that works with SQL Server CE and EF using a code-first approach, I have large volume of users working with this.
The connection string that I am passing to DbContext class constructor,
#"Data Source=" + Path.Combine("Path to local app data", "Databasename.sdf") + ";Password=mypassword"
But on one of the Windows 7 SP1 (32 bit) machines, I am getting following error:
System.InvalidOperationException: Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.
at System.Data.Entity.SqlServer.SqlProviderServices.GetOrGenerateDatabaseNameAndGetFileNames(SqlConnection sqlConnection, String& databaseName, String& dataFileName, String& logFileName)
at System.Data.Entity.SqlServer.SqlProviderServices.DbCreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection) at System.Data.Entity.Core.Common.DbProviderServices.CreateDatabase(DbConnection connection, Nullable1 commandTimeout, StoreItemCollection storeItemCollection)
at System.Data.Entity.Core.Objects.ObjectContext.CreateDatabase()
at System.Data.Entity.Migrations.Utilities.DatabaseCreator.Create(DbConnection connection)
at System.Data.Entity.Migrations.DbMigrator.EnsureDatabaseExists(Action mustSucceedToKeepDatabase)
at System.Data.Entity.Migrations.DbMigrator.Update(String targetMigration)
at System.Data.Entity.MigrateDatabaseToLatestVersion2.InitializeDatabase(TContext context) at System.Data.Entity.Internal.InternalContext.<>c__DisplayClassf1.b__e()
at System.Data.Entity.Internal.InternalContext.PerformInitializationAction(Action action)
at System.Data.Entity.Internal.InternalContext.PerformDatabaseInitialization()
at System.Data.Entity.Internal.LazyInternalContext.b__4(InternalContext c)
at System.Data.Entity.Internal.RetryAction1.PerformAction(TInput input) at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabaseAction(Action1 action)
at System.Data.Entity.Internal.LazyInternalContext.InitializeDatabase()
at System.Data.Entity.Internal.InternalContext.GetEntitySetAndBaseTypeForType(Type entityType)
at System.Data.Entity.Internal.Linq.InternalSet1.Initialize() at System.Data.Entity.Internal.Linq.InternalSet1.get_InternalContext()
at System.Data.Entity.Infrastructure.DbQuery1.System.Linq.IQueryable.get_Provider() at System.Linq.Queryable.Any[TSource](IQueryable1 source)
at GCMApiSDK.DataService.d__12.MoveNext()
--- End of stack trace from previous location where exception was thrown ---
at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task)
at System.Runtime.CompilerServices.TaskAwaiter.ValidateEnd(Task task)
at GCMApiSDK.AuthenticationDialog.<LoginButton_Click_1>d__11.MoveNext()
I am unable to figure out what is going wrong with that particular machine, because the same thing works for other Windows 7 users.
Plus I also tried re-installing SQL Server CE Runtime 3.5 SP2, but no luck.
To add more info, the database is successfully created in the specified location, but I'm unable to do other operations.

The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047) - Visual Studio 2017

I have ordinary ASP.NET project with .NET Framework 4.5.2, It work great as Web Site Projects (WSP), but I try to change this project to Web Application Projects (WAP). I don't change anything in body of project code, I only add designer with definition of control and add default namespace needed to WSP project. But aspnet_compiler crashed with message below (this is a part of MSBuild process):
C:\WINDOWS\Microsoft.NET\Framework\v4.0.30319\aspnet_compiler.exe -v /
-p E:\Projects\Arenda_5\MyArenda\ArendaNew\obj\Debug\AspnetCompileMerge\Source
-d E:\Projects\Arenda_5\MyArenda\ArendaNew\obj\Debug\AspnetCompileMerge\TempBuildDir
-errorstack
Microsoft (R) ASP.NET Compilation Tool version 4.8.3752.0 Utility to
precompile an ASP.NET application Copyright (C) Microsoft Corporation.
All rights reserved. (0): warning : The following assembly has
dependencies on a version of the .NET Framework that is higher than
the target and might not load correctly during runtime causing a
failure: ArendaNew, Version=1.0.0.0, Culture=neutral,
PublicKeyToken=null. The dependencies are: Microsoft.VisualBasic,
Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a.
You should either ensure that the dependent assembly is correct for
the target framework, or ensure that the target framework you are
addressing is that of the dependent assembly.
E:\Projects\Arenda_5\MyArenda\ArendaNew\obj\Debug\AspnetCompileMerge\Source\global.asax(41):
warning BC42025: Access of shared member, constant member, enum member
or nested type through an instance; qualifying expression will not be
evaluated
....
E:\Projects\Arenda_5\MyArenda\ArendaNew\obj\Debug\AspnetCompileMerge\Source\My_Saved.ashx(43):
warning BC42025: Access of shared member, constant member, enum member
or nested type through an instance; qualifying expression will not be
evaluated.
error ASPPARSE: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
error ASPPARSE: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
error ASPPARSE: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
error ASPPARSE: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
error ASPPARSE: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
error ASPPARSE: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047)
[FileLoadException]: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047) at
System.Reflection.AssemblyName.nInit(RuntimeAssembly& assembly,
Boolean forIntrospection, Boolean raiseResolveEvent) at
System.Reflection.AssemblyName..ctor(String assemblyName) at
System.Web.Configuration.CompilationSection.LoadAssembly(String
assemblyName, Boolean throwOnFail) at
System.Web.UI.TemplateParser.LoadAssembly(String assemblyName, Boolean
throwOnFail) at
System.Web.UI.TemplateParser.AddAssemblyDependency(String
assemblyName, Boolean addDependentAssemblies) at
System.Web.UI.MainTagNameToTypeMapper.ProcessTagNamespaceRegistrationCore(TagNamespaceRegisterEntry
nsRegisterEntry) at
System.Web.UI.MainTagNameToTypeMapper.ProcessTagNamespaceRegistration(ArrayList
nsRegisterEntries)
[HttpParseException]: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047) at
System.Web.UI.MainTagNameToTypeMapper.ProcessTagNamespaceRegistration(ArrayList
nsRegisterEntries) at
System.Web.UI.MainTagNameToTypeMapper.ProcessTagNamespaceRegistration(TagNamespaceRegisterEntry
nsRegisterEntry) at
System.Web.UI.BaseTemplateParser.ProcessDirective(String
directiveName, IDictionary directive) at
System.Web.UI.TemplateControlParser.ProcessDirective(String
directiveName, IDictionary directive) at
System.Web.UI.PageParser.ProcessDirective(String directiveName,
IDictionary directive) at
System.Web.UI.TemplateParser.ParseStringInternal(String text, Encoding
fileEncoding)
[HttpParseException]: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047) at
System.Web.UI.TemplateParser.ParseString(String text, VirtualPath
virtualPath, Encoding fileEncoding) at
System.Web.UI.TemplateParser.ParseReader(StreamReader reader,
VirtualPath virtualPath) at
System.Web.UI.TemplateParser.ParseFile(String physicalPath,
VirtualPath virtualPath) at
System.Web.UI.TemplateParser.ParseInternal() at
System.Web.UI.TemplateParser.Parse() at
System.Web.Compilation.BaseTemplateBuildProvider.get_CodeCompilerType()
at
System.Web.Compilation.BuildProvider.GetCompilerTypeFromBuildProvider(BuildProvider
buildProvider) at
System.Web.Compilation.WebDirectoryBatchCompiler.CompileNonDependentBuildProviders(ICollection
buildProviders)
[HttpParseException]: The given assembly name or codebase was invalid.
(Exception from HRESULT: 0x80131047) at
System.Web.Compilation.WebDirectoryBatchCompiler.Process() at
System.Web.Compilation.BuildManager.BatchCompileWebDirectoryInternal(VirtualDirectory
vdir, Boolean ignoreErrors) at
System.Web.Compilation.BuildManager.BatchCompileWebDirectory(VirtualDirectory
vdir, VirtualPath virtualDir, Boolean ignoreErrors) at
System.Web.Compilation.BuildManager.PrecompileWebDirectoriesRecursive(VirtualDirectory
vdir, Boolean topLevel) at
System.Web.Compilation.BuildManager.PrecompileAppInternal(VirtualPath
startingVirtualDir, IEnumerable1 excludedVirtualPaths) at
System.Web.Compilation.BuildManager.PrecompileApp(VirtualPath
startingVirtualDir, IEnumerable1 excludedVirtualPaths) at
System.Web.Compilation.BuildManager.PrecompileApp(ClientBuildManagerCallback
callback, IEnumerable1 excludedVirtualPaths) at
System.Web.Compilation.BuildManagerHost.PrecompileApp(ClientBuildManagerCallback
callback, List1 excludedVirtualPaths) at
System.Web.Compilation.BuildManagerHost.PrecompileApp(ClientBuildManagerCallback
callback, List`1 excludedVirtualPaths) at
System.Web.Compilation.ClientBuildManager.PrecompileApplication(ClientBuildManagerCallback
callback, Boolean forceCleanBuild) at
System.Web.Compilation.ClientBuildManager.PrecompileApplication(ClientBuildManagerCallback
callback) at System.Web.Compilation.Precompiler.Main(String[] args)

Security Exception When i am trying to run working asp code on one system from another system

I have one asp code which is working perfectly on one system. I am using Microsoft web matrix to run it. But when I am trying to run it in another system, I am getting some errors:
Server Error in '/' Application.
Security Exception
Description: The application attempted to perform an operation not
allowed by the security policy. To grant this application the
required permission please contact your system administrator or change
the application's trust level in the configuration file.
Exception Details: System.Security.SecurityException: The source was
not found, but some or all event logs could not be searched.
Inaccessible logs: Security.
Source Error:
Line 136: catch (Exception ex1)
Line 137: {
Line 138: EventLog.WriteEntry("GLOBAL_ASAX.Session_Start", ex1.Message + ": " + ex1.StackTrace, EventLogEntryType.Error);
Line 139: }
Line 140: }
Source File: c:\Users\sysadmin\Documents\NET2_VXLICENSING_Web\Global.asax Line: 138
Stack Trace:
[SecurityException: The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security.]
System.Diagnostics.EventLog.FindSourceRegistration(String source, String machineName, Boolean readOnly) +665
System.Diagnostics.EventLog.SourceExists(String source, String machineName) +104
System.Diagnostics.EventLog.VerifyAndCreateSource(String sourceName, String currentMachineName) +75
System.Diagnostics.EventLog.WriteEntry(String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData) +205
System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type, Int32 eventID, Int16 category, Byte[] rawData) +87
System.Diagnostics.EventLog.WriteEntry(String source, String message, EventLogEntryType type) +14
ASP.global_asax.Session_Start(Object sender, EventArgs e) in c:\Users\sysadmin\Documents\NET2_VXLICENSING_Web\Global.asax:138
System.Web.SessionState.SessionStateModule.RaiseOnStart(EventArgs e) +8879616
System.Web.SessionState.SessionStateModule.CompleteAcquireState() +237
System.Web.SessionState.SessionStateModule.BeginAcquireState(Object source, EventArgs e, AsyncCallback cb, Object extraData) +504
System.Web.AsyncEventExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute() +66
System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously) +155
Version Information: Microsoft .NET Framework Version:2.0.50727.5485; ASP.NET Version:2.0.50727.5491
I searched a lot on the internet about it but nothing is working. I also updated registry keys.

Resources