Service account throwing SQLiteException on NServiceBus startup - sqlite

I'm getting the following exception when I try to start nservicebus.host.exe with service account credentials:
Database was not configured through Database method.
System.Data.SQLite.SQLiteException: Unable to open the database file
at System.Data.SQLite.SQLite3.Open(String strFilename, SQLiteOpenFlagsEnum flags, Int32 maxPoolSize, Boolean usePool)
at System.Data.SQLite.SQLiteConnection.Open()
at NHibernate.Connection.DriverConnectionProvider.GetConnection() in :line 0
at NHibernate.Tool.hbm2ddl.SuppliedConnectionProviderConnectionHelper.Prepare() in :line 0
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.GetReservedWords(Dialect dialect, IConnectionHelper connectionHelper) in :line 0
at NHibernate.Tool.hbm2ddl.SchemaMetadataUpdater.Update(ISessionFactory sessionFactory) in :line 0
at NHibernate.Impl.SessionFactoryImpl..ctor(Configuration cfg, IMapping mapping, Settings settings, EventListeners listeners) in :line 0
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() in D:\dev\fluent-nhibernate\src\FluentNHibernate\Cfg\FluentConfiguration.cs:line 93
--- End of inner exception stack trace ---
at FluentNHibernate.Cfg.FluentConfiguration.BuildSessionFactory() in D:\dev\fluent-nhibernate\src\FluentNHibernate\Cfg\FluentConfiguration.cs:line 100
at NServiceBus.SagaPersisters.NHibernate.Config.Internal.SessionFactoryBuilder.Build(IDictionary^2 nhibernateProperties, Boolean updateSchema) in c:\Dev\DotNet\NServiceBus\src\impl\SagaPersisters\NHibernateSagaPersister\NServiceBus.SagaPersisters.NHibernate.Config\Internal\SessionFactoryBuilder.cs:line 48
--- End of inner exception stack trace ---
at NServiceBus.SagaPersisters.NHibernate.Config.Internal.SessionFactoryBuilder.Build(IDictionary^2 nhibernateProperties, Boolean updateSchema) in c:\Dev\DotNet\NServiceBus\src\impl\SagaPersisters\NHibernateSagaPersister\NServiceBus.SagaPersisters.NHibernate.Config\Internal\SessionFactoryBuilder.cs:line 55
at NServiceBus.ConfigureNHibernateSagaPersister.NHibernateSagaPersister(Configure config, IDictionary^2 nhibernateProperties, Boolean autoUpdateSchema) in c:\Dev\DotNet\NServiceBus\src\impl\SagaPersisters\NHibernateSagaPersister\NServiceBus.SagaPersisters.NHibernate.Config\ConfigureNHibernateSagaPersister.cs:line 80
at Ibfx.BackOffice.Services.NewAccounts.NewAccountsEndpoint.Init() in C:\Dev\TFS\Omega\Src\Svcs\NewAccounts\Src\Service\NewAccountsEndpoint.cs:line 67
at NServiceBus.Host.Internal.GenericHost.Start() in c:\Dev\DotNet\NServiceBus\src\host\NServiceBus.Host\Internal\GenericHost.cs:line 56
Everything works fine if I run the host using my own account, but if I run the host as a service with domain credentials or use those same credentials with the RunAs command I get the above exception. What are the permissions I need to configure so the service will work?
Here's my config:
var configure = NServiceBus.Configure.With()
.Log4Net<Log4NetLoggerAdapter>(a => { })
.UnityBuilder(container)
.XmlSerializer()
.RijndaelEncryptionService()
.MsmqTransport()
.IsTransactional(false)
.PurgeOnStartup(false)
.MsmqSubscriptionStorage();
configure.Configurer.ConfigureComponent<MsmqSubscriptionStorage>(
ComponentCallModelEnum.None).ConfigureProperty(p => p.DontUseExternalTransaction
, true
);
IBus bus = configure.UnicastBus()
.ImpersonateSender(true)
.LoadMessageHandlers()
.Sagas()
.NHibernateSagaPersister()
.CreateBus()
.Start();
And I have a NServiceBus.Host.exe.config file with the following:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup useLegacyV2RuntimeActivationPolicy="true">
<supportedRuntime version="v4.0"/>
</startup>
</configuration>

What happens when you temporarily give EVERYONE and ANONYMOUS LOGON Full Control over the directory specified? If that solves the exception, it's definitely a security issue. Are you using |DataDirectory| in your connection string? Are you sure the process is actually looking at the directory that you think it's looking at?
Following that, I would try using the SQLite in memory connection string settings to see if it's able to at least create a database and use it:
":memory:;Version=3;New=True;Pooling=True;Max Pool Size=1;"
The above string uses in-memory SQLite but keeps a single connection open so that the tables and data continue to exist until the process exits.
Another strategy that I would use is to change the saga persister to another SQL flavor, such as MS SQL to see if that solves it.

Related

NLog throws 'Target cannot be found' for any custom target running on Azure Web App

I've created two NLog custom targets on .NET Standard 2.0, and imported them into an existing ASP.NET 4.7.2 website.
nlog.config looks like this:
<?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"
internalLogLevel="Info"
internalLogFile="${basedir}/internal-nlog.txt"
throwExceptions="true"
throwConfigExceptions="true">
<extensions>
<add assembly="MyAssembly"/>
</extensions>
<targets async="false">
<target name="logconsole" xsi:type="Console" />
<target xsi:type="AzureTableTarget"
name="azureTable"
// some configs
/>
<target xsi:type="PostmarkLogTarget"
name="postmark"
// some configs
/>
</targets>
<rules>
<logger name="*" minlevel="Warn" writeTo="postmark" />
<logger name="*" minlevel="Info" writeTo="azureTable" />
<logger name="*" minlevel="Debug" writeTo="logconsole" />
</rules>
</nlog>
When the app starts locally, everything works fine. When it starts on the Azure App Service, I get this in the nlog internal log (and a big, fat error page):
2019-06-21 15:08:53.5719 Info Message Template Auto Format enabled
2019-06-21 15:08:53.6015 Info Loading assembly: MyAssembly
2019-06-21 15:08:53.6926 Info Adding target ConsoleTarget(Name=logconsole)
2019-06-21 15:08:53.7595 Error Parsing configuration from D:\home\site\wwwroot\NLog.config failed. Exception: NLog.NLogConfigurationException: Exception when parsing D:\home\site\wwwroot\NLog.config. ---> System.ArgumentException: Target cannot be found: 'AzureTableTarget'
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Config.LoggingConfigurationParser.ParseTargetsElement(ILoggingConfigurationElement targetsElement)
at NLog.Config.LoggingConfigurationParser.ParseNLogSection(ILoggingConfigurationElement configSection)
at NLog.Config.XmlLoggingConfiguration.ParseNLogSection(ILoggingConfigurationElement configSection)
at NLog.Config.LoggingConfigurationParser.LoadConfig(ILoggingConfigurationElement nlogConfig, String basePath)
at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(ILoggingConfigurationElement nlogElement, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
--- End of inner exception stack trace ---
2019-06-21 15:08:53.8489 Error Failed loading from config file location: D:\home\site\wwwroot\NLog.config Exception: NLog.NLogConfigurationException: Exception when parsing D:\home\site\wwwroot\NLog.config. ---> System.ArgumentException: Target cannot be found: 'AzureTableTarget'
at NLog.Config.Factory`2.CreateInstance(String itemName)
at NLog.Config.LoggingConfigurationParser.ParseTargetsElement(ILoggingConfigurationElement targetsElement)
at NLog.Config.LoggingConfigurationParser.ParseNLogSection(ILoggingConfigurationElement configSection)
at NLog.Config.XmlLoggingConfiguration.ParseNLogSection(ILoggingConfigurationElement configSection)
at NLog.Config.LoggingConfigurationParser.LoadConfig(ILoggingConfigurationElement nlogConfig, String basePath)
at NLog.Config.XmlLoggingConfiguration.ParseNLogElement(ILoggingConfigurationElement nlogElement, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.ParseTopLevel(NLogXmlElement content, String filePath, Boolean autoReloadDefault)
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
--- End of inner exception stack trace ---
at NLog.Config.XmlLoggingConfiguration.Initialize(XmlReader reader, String fileName, Boolean ignoreErrors)
at NLog.Config.XmlLoggingConfiguration..ctor(XmlReader reader, String fileName, Boolean ignoreErrors, LogFactory logFactory)
at NLog.Config.LoggingConfigurationFileLoader.LoadXmlLoggingConfiguration(XmlReader xmlReader, String configFile, LogFactory logFactory)
at NLog.Config.LoggingConfigurationFileLoader.LoadXmlLoggingConfigurationFile(LogFactory logFactory, String configFile)
at NLog.Config.LoggingConfigurationFileLoader.TryLoadLoggingConfiguration(LogFactory logFactory, String configFile, LoggingConfiguration& config)
2019-06-21 15:08:54.1153 Info Configuring from an XML element in D:\home\site\wwwroot\NLog.config...
2019-06-21 15:08:54.1457 Info Message Template Auto Format enabled
2019-06-21 15:08:54.1457 Info Loading assembly: MyAssembly
2019-06-21 15:08:54.1457 Info Adding target ConsoleTarget(Name=logconsole)
2019-06-21 15:08:54.3332 Info Adding target AzureTableTarget(Name=azureTable)
2019-06-21 15:08:54.3525 Info Adding target PostmarkLogTarget(Name=postmark)
2019-06-21 15:08:54.4120 Info Found 38 configuration items
2019-06-21 15:08:54.4738 Info Configuration initialized.
The second load comes about because I have code in global.asax.cs to register and configure the targets specifically. This code fires immediately after setting up AutoFac, and before anything tries to log to anywhere.
Running locally, the code proceeds through these steps in order, even in Release mode. It looks like it tries to log a message before configuration has completed when running on Azure.
Even if that were the case, both custom targets have default public constructors, so NLog should be able to instantiate them automagically. (Which is why I reload configs after setting up the targets.)
Two questions:
What is different about the Azure App Service that causes (or allows) NLog to jump the gun like that?
Short of removing nlog.config and setting up logging in code, how can I prevent this behavior from happening?
Target cannot be found: 'AzureTableTarget'
This mean that the target class 'AzureTableTarget' cannot be found in one of the assemblies and thus an instance cannot be create.
You need to tell NLog in which assembly the AzureTableTarget type could be found.
Something like this:
<extensions>
<add assembly="AssemblyNameWhereAzureTableTargetIsDefined"/>
</extensions>
What is different about the Azure App Service that causes (or allows) NLog to jump the gun like that?
Are the same assemblies available? So is the assembly with the AzureTableTarget published?
Short of removing nlog.config and setting up logging in code
For this case it doesn't matter if NLog is configured from file or from code.
how can I prevent this behavior from happening?
Always add all external NLog extensions to <extensions>
Last but not least, throwExceptions="true" isn't recommend for production! (If your logging breaks, do you really like that your application breaks?)
Found it. Wow.
I had this code hanging out in a .cs file:
public static readonly Logger Logger = LogManager.GetCurrentClassLogger();
On the App Service deployment, the static constructor of the class containing that line ran before App_Start had finished. On my local box, it didn't.
So I changed it to this:
public static Logger Logger => _logger ?? (_logger = LogManager.GetCurrentClassLogger());
private static Logger _logger;
...and everything works now. The Logger is only created when used, not just because ASP.NET wanted to instantiate static classes ahead of time.

ASP.NET Web API cause exceptions while running on raspberry pi 2 (ARM)

I have coded a Web API in Ubuntu using .NET Core recently and I need to use database to store the application data so that I decided to use EF Core. I ran this project on Ubuntu machine and everything worked appropriately.
I've also tried to run it on my raspberry pi 2 but I wasn't lucky enough to make it work properly. I did the instruction on this website and got this output as soon as I tried to access the api/dooz on Firefox while accessing my RP through Remmina Remote Desktop.
If the problem is with the database, how can I include the .db file to the iDooz_1/bin/Release/netcoreapp2.1/linux-arm/publish folder to make it work?
How can I solve it?
c343#RP:~/publish_idooz1$ ./iDooz_1
Hosting environment: Production
Content root path: /home/c343/publish_idooz1
Now listening on: http://localhost:5000
Application started. Press Ctrl+C to shut down.
warn: Microsoft.AspNetCore.HttpsPolicy.HttpsRedirectionMiddleware[3]
Failed to determine the https port for redirect.
fail: Microsoft.AspNetCore.Server.Kestrel[13]
Connection id "0HLFUSJJ3S54N", Request id "0HLFUSJJ3S54N:00000001": An unhandled exception was thrown by the application.
Microsoft.Data.Sqlite.SqliteException (0x80004005): SQLite Error 1: 'no such table: Players'.
at Microsoft.Data.Sqlite.SqliteException.ThrowExceptionForRC(Int32 rc, sqlite3 db)
at Microsoft.Data.Sqlite.SqliteCommand.PrepareAndEnumerateStatements(Stopwatch timer)+MoveNext()
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteReader(CommandBehavior behavior)
at Microsoft.Data.Sqlite.SqliteCommand.ExecuteDbDataReader(CommandBehavior behavior)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.Execute(IRelationalConnection connection, DbCommandMethod executeMethod, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Storage.Internal.RelationalCommand.ExecuteReader(IRelationalConnection connection, IReadOnlyDictionary`2 parameterValues)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.BufferlessMoveNext(DbContext _, Boolean buffer)
at Microsoft.EntityFrameworkCore.Storage.Internal.NoopExecutionStrategy.Execute[TState,TResult](TState state, Func`3 operation, Func`3 verifySucceeded)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryingEnumerable`1.Enumerator.MoveNext()
at Microsoft.EntityFrameworkCore.Query.QueryMethodProvider.GetResult[TResult](IEnumerable`1 valueBuffers, Boolean throwOnNullResult)
at lambda_method(Closure )
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ResultEnumerable`1.GetEnumerator()
at Microsoft.EntityFrameworkCore.Query.Internal.LinqOperatorProvider.ExceptionInterceptor`1.EnumeratorExceptionInterceptor.MoveNext()
at System.Linq.Enumerable.TryGetFirst[TSource](IEnumerable`1 source, Boolean& found)
at System.Linq.Enumerable.First[TSource](IEnumerable`1 source)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.<>c__DisplayClass15_1`1.<CompileQueryCore>b__0(QueryContext qc)
at Microsoft.EntityFrameworkCore.Query.Internal.QueryCompiler.Execute[TResult](Expression query)
at Microsoft.EntityFrameworkCore.Query.Internal.EntityQueryProvider.Execute[TResult](Expression expression)
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at iDooz.Controllers.DoozController..ctor() in /home/c343/Documents/iDooz_1/Controllers/DoozController.cs:line 24
at lambda_method(Closure , IServiceProvider , Object[] )
at Microsoft.AspNetCore.Mvc.Controllers.ControllerActivatorProvider.<>c__DisplayClass4_0.<CreateActivator>b__0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Controllers.ControllerFactoryProvider.<>c__DisplayClass5_0.<CreateControllerFactory>g__CreateController|0(ControllerContext controllerContext)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ControllerActionInvoker.InvokeInnerFilterAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeNextResourceFilter()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Rethrow(ResourceExecutedContext context)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.Next(State& next, Scope& scope, Object& state, Boolean& isCompleted)
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeFilterPipelineAsync()
at Microsoft.AspNetCore.Mvc.Internal.ResourceInvoker.InvokeAsync()
at Microsoft.AspNetCore.Builder.RouterMiddleware.Invoke(HttpContext httpContext)
at Microsoft.AspNetCore.Server.Kestrel.Core.Internal.Http.HttpProtocol.ProcessRequests[TContext](IHttpApplication`1 application)
^CApplication is shutting down...
However, api/values, the default API in the webapi application worked properly and I got the correct output as in I got earlier on Ubuntu.
NOTE: First, this project is generally made to build a Tic Toc Toe and to learn about REstful APIs using ASP.NET Core Web API. So, I made a database using Entity Framework called Dooz.db and that is in the main directory of the project. Second, I'm doing dotnet publish -c Release -r linux-arm because the .NET Core SDK is not available for ARM-Processors.
Third, this is the part of the code in which the terminal had output an error
at System.Linq.Queryable.Count[TSource](IQueryable`1 source)
at iDooz.Controllers.DoozController..ctor() in /home/c343/Documents/iDooz_1/Controllers/DoozController.cs:line 24
Here is the code:
public class DoozController : ControllerBase
{
public DoozController()
{
if(db.Players.Count() == 0)
{
db.Players.Add(new Player { PlayerID = 1, Username = "Alex123", Password = "1234", ProfilePic = "ProfilePics/Alex123.jpg" });
db.Players.Add(new Player { PlayerID = 2, Username = "Ashkan_007", Password = "12345", ProfilePic = "ProfilePics/Ashkan_007.jpg" });
.
.
.
db.SaveChanges();
}
}
.
.
.
You need to copy the database file into publish folder.

How can I connect oracle coherence remote cluster using java

There is a coherence cluster (with a cache by name mycache) that is runnig on ip address xxx.xxx.xxx.xxx (not localhost). I am trying to connect it and read from cache using java.
This is my Reader class:
import com.tangosol.net.CacheFactory;
import com.tangosol.net.NamedCache;
public class Reader {
public static void main(String[] args) {
NamedCache cache = CacheFactory.getCache("mycache");
System.out.println("Value in cache is: " + cache.get("key1"));
}
}
I am using Intellij IDEA, in vm option for reader I added this line:
-Dtangosol.coherence.cacheconfig=mycache.xml
and this is mycache.xml file:
<?xml version='1.0'?>
<coherence xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.oracle.com/coherence/coherence-operational-config"
xsi:schemaLocation="http://xmlns.oracle.com/coherence/coherence-operational-config
coherence-operational-config.xsd"
xml-override="{tangosol.coherence.override /tangosol-coherence-override-{mode}.xml}">
<cluster-config>
<member-identity>
<cluster-name>RemoteCluster</cluster-name>
</member-identity>
<unicast-listener>
<well-known-addresses>
<socket-address id="1">
<address>192.168.104.160</address>
<port>8088</port>
</socket-address>
</well-known-addresses>
</unicast-listener>
</cluster-config>
</coherence>
when I run reader.main() I get this exception:
Problem : An ElementProcessor could not be located for the element [coherence]
Advice : The specified element is unknown to the NamespaceHandler implementation. Perhaps the xml element is foreign to the Xml Namespace?
at com.tangosol.util.Base.ensureRuntimeException(Base.java:286)
at com.tangosol.net.ScopedCacheFactoryBuilder.instantiateFactory(ScopedCacheFactoryBuilder.java:433)
at com.tangosol.net.ScopedCacheFactoryBuilder.buildFactory(ScopedCacheFactoryBuilder.java:385)
at com.tangosol.net.ScopedCacheFactoryBuilder.getFactory(ScopedCacheFactoryBuilder.java:267)
at com.tangosol.net.ScopedCacheFactoryBuilder.getConfigurableCacheFactory(ScopedCacheFactoryBuilder.java:119)
at com.tangosol.net.CacheFactory.getConfigurableCacheFactory(CacheFactory.java:127)
at com.tangosol.net.CacheFactory.getCache(CacheFactory.java:205)
at com.tangosol.net.CacheFactory.getCache(CacheFactory.java:182)
at Reader.main(Reader.java:11)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:134)
Caused by: com.tangosol.config.ConfigurationException: Configuration Exception
-----------------------
Problem : An ElementProcessor could not be located for the element [coherence]
Advice : The specified element is unknown to the NamespaceHandler implementation. Perhaps the xml element is foreign to the Xml Namespace?
it looks like the problem in the mycache.xml. Those elements used when you want to set up cluster member, while you want to connect a client.
Assuming that "mycache" schema exists on remote cluster try to change the mycache.xml with following:
<?xml version="1.0"?>
<!DOCTYPE cache-config SYSTEM "cache-config.dtd">
<cache-config xmlns="http://schemas.tangosol.com/cache">
<caching-scheme-mapping>
<cache-mapping>
<cache-name>mycache</cache-name>
<scheme-name>extend-dist</scheme-name>
</cache-mapping>
</caching-scheme-mapping>
<caching-schemes>
<remote-cache-scheme>
<scheme-name>extend-dist</scheme-name>
<service-name>ExtendTcpCacheService</service-name>
<initiator-config>
<tcp-initiator>
<remote-addresses>
<socket-address>
<address>192.168.104.160</address>
<port>8088</port>
</socket-address>
</remote-addresses>
</tcp-initiator>
<outgoing-message-handler>
<request-timeout>20s</request-timeout>
</outgoing-message-handler>
</initiator-config>
</remote-cache-scheme>
</caching-schemes>
</cache-config>
Note: if remote cluster uses POF serialization for mycache you'll have to add POF mapping and configuration -Dtangosol.pof.enabled=true
Your xml file is an operational config rather than cache config. To use this configuration, run your programm with:
-Dtangosol.coherence.override=mycache.xml
instead of:
-Dtangosol.coherence.cacheconfig=mycache.xml
BTW you should rename mycache.xml to e.g. operational-config.xml in order to not confuse it with cache configuration.

Hosting my MVC 5 entity framework code first project ! MULTIPLE ERRORS

I'm trying to host my ASP.NET MVC 5 Entity Framework code first project (the project is running perfectly fine on my machine with local db connection strings) on go daddy. I've been getting a few errors and I was able to correct them up until now.
Now I'm getting this error:
CREATE DATABASE permission denied in database 'master'.
Description: An unhandled exception occurred during the execution of the current web request. Please review the stack trace for more information about the error and where it originated in the code.
Exception Details: System.Data.SqlClient.SqlException: CREATE DATABASE permission denied in database 'master'.
I've removed the trust level option in my web.config file because it was creating problems with CAS trust level in the asp.net net parameters of godaddy. My CAS trust level in go daddy is set to full.
My connection strings:
<add name="DefaultConnection"
connectionString="Data Source=ipadress;AttachDbFilename=|DataDirectory|\aspnet-aspProjetFinal-20141211061340.mdf;Initial Catalog=aspnet-aspProjetFinal-20141211061340;Integrated Security=false;User Id=myuser; Password=mypassword;"
providerName="System.Data.SqlClient" />
<add name="monModel"
connectionString="data source=ipadress;initial catalog=GestionClientsContext;Trusted_Connection=True;Integrated Security=false;MultipleActiveResultSets=True;App=EntityFramework;User Id=myuser; Password=mypassword;"
providerName="System.Data.SqlClient" />
I've tried a few things, for example, this:
http://forums.asp.net/t/1742970.aspx?CREATE+DATABASE+permission+denied+in+database+master+
But I'm not sure if I need to delete some lines after adding said line at the top of the code.
My global.asax.cs file:
public class MvcApplication : System.Web.HttpApplication
{
protected void Application_Start()
{
Database.SetInitializer<GestionClientsContext>(null);
Database.SetInitializer(new InitialisationGestionClients());
GestionClientsContext testing = new GestionClientsContext();
testing.Database.Initialize(true);
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
//throw new Exception(ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString);
}
I clearly need some guidance, I've already spent a lot of hours just trying to get it online ! Let me know what you think ! Thanks !
What you asked for Dan:
public class InitialisationGestionClients : System.Data.Entity.CreateDatabaseIfNotExists<GestionClientsContext>
{
protected override void Seed(GestionClientsContext context)
{
base.Seed(context);
var lesClients = new List<Clients>
{
new Clients{nom="Finch", prenom="Paul",dateInscription=DateTime.Parse("2014-01-10"),adresse="911 De la Commune", email="test#hotmail.com", solde=0,commentaires="Juste un test"}
};
lesClients.ForEach(s => context.Clients.Add(s));
context.SaveChanges();
var lesFacures = new List<Factures>
{
new Factures{motif="Programmes janvier 2014", montant=25,dateFacturation=DateTime.Parse("2014-01-10"),statusPaid=false, ClientsId=1}
};
lesFacures.ForEach(s => context.Factures.Add(s));
context.SaveChanges();
var lesPaiements = new List<Paiements>
{
new Paiements{montant=25,datePaiements=DateTime.Parse("2014-02-10"), ClientsId=1}
};
lesPaiements.ForEach(s => context.Paiements.Add(s));
context.SaveChanges();
}
}
UPDATE: I've gotten the site to "run" if I can use this word. I can now access the application online BUT as soon as I try to login or create a new user, using the MVC login feature, I get the following error:
CREATE DATABASE permission denied in database 'master'.
I already got that error before when the application was trying to load but I didn't get it since I change the trust level to FULL. I'm not sure I'm following this one ! I'm just trying to login why is he trying to create anything at all !

Access denied error using asymmetric binding in web host server - .NET

I'm getting an Access denied error when I attempt to make a web service request. The web service requires an asymmetric security binding. The call is made via a webpage that references a .NET dll that references the web service. All of this works fine on our server but we loaded it up at a web hosting company we got hit with this error.
My theory is that whatever the GetKeyPairHelper method does it requires the ability to write a file to do it while we don't have access to the location it tries to write to. The support people at this company ran a trace for us and these were the last two lines:
06:03.1 w3wp.exe 5860 CreateFile C:\ProgramData NAME COLLISION >Desired Access: Read Data/List Directory, Synchronize, Disposition: Create, Options: >Directory, Synchronous IO Non-Alert, Open Reparse Point, Attributes: N, ShareMode: Read, >Write, AllocationSize: 0
06:03.1 w3wp.exe 5860 CreateFile C:\ProgramData ACCESS DENIED >Desired Access: Read Attributes, Disposition: Open, Options: Open Reparse Point, >Attributes: n/a, ShareMode: Read, Write, Delete, AllocationSize: n/a
Looks like something trying to write to C:\ProgramData but what? And why? And how do I get around it? I'm hoping there is some way to configure this so it doesn't have to write a file. Perhaps this job can be performed in memory or directed to an area we have access to.
Stacktrace:
Error: Access is denied. : Server stack trace:
at System.Security.Cryptography.Utils.CreateProvHandle(CspParameters parameters, Boolean randomKeyContainer)
at System.Security.Cryptography.Utils.GetKeyPairHelper(CspAlgorithmType keyType, CspParameters parameters, Boolean randomKeyContainer, Int32 dwKeySize, SafeProvHandle& safeProvHandle, SafeKeyHandle& safeKeyHandle)
at System.Security.Cryptography.RSACryptoServiceProvider.GetKeyPair()
at System.Security.Cryptography.RSACryptoServiceProvider..ctor(Int32 dwKeySize, CspParameters parameters, Boolean useDefaultKeySize)
at System.Security.Cryptography.X509Certificates.X509Certificate2.get_PrivateKey()
at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.get_PrivateKey()
at System.IdentityModel.Tokens.X509AsymmetricSecurityKey.GetSignatureFormatter(String algorithm)
at System.IdentityModel.SignedXml.ComputeSignature(SecurityKey signingKey)
at System.ServiceModel.Security.WSSecurityOneDotZeroSendSecurityHeader.CompletePrimarySignatureCore(SendSecurityHeaderElement[] signatureConfirmations, SecurityToken[] signedEndorsingTokens, SecurityToken[] signedTokens, SendSecurityHeaderElement[] basicTokens)
at System.ServiceModel.Security.SendSecurityHeader.CompleteSignature() at System.ServiceModel.Security.SendSecurityHeader.CompleteSecurityApplication()
at System.ServiceModel.Security.SecurityAppliedMessage.OnWriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.WriteMessage(XmlDictionaryWriter writer)
at System.ServiceModel.Channels.Message.WriteMessage(XmlWriter writer)
at CustomMessageEncoder.CustomTextMessageEncoder.WriteMessage(Message message, Int32 maxMessageSize, BufferManager bufferManager, Int32 messageOffset)
in C:\xxxxx\CustomEncoders\CustomTextMessageEncoder.cs:line 86
Code:
public override ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset)
{
MemoryStream stream = new MemoryStream();
XmlWriter writer = XmlWriter.Create(stream, this.writerSettings);
message.WriteMessage(writer); //'line 86' in stacktrace.
writer.Close();
byte[] messageBytes = stream.GetBuffer();
int messageLength = (int)stream.Position;
stream.Close();
int totalLength = messageLength + messageOffset;
byte[] totalBytes = bufferManager.TakeBuffer(totalLength);
Array.Copy(messageBytes, 0, totalBytes, messageOffset, messageLength);
//maybe parse message around here...
ArraySegment<byte> byteArray = new ArraySegment<byte>(totalBytes, messageOffset, messageLength);
return byteArray;
}
What happened here is that the hosting company was hosting our site on a shared server and so rightfully denied access to the C:\ProgramData folder which, further down the directory contains C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys which is the folder you need access to in order to use certificates based security. Their solution for us was to allow access to this folder for our app pool only. Works like a charm.

Resources