My program used to start even though Mysql is offline, it will open but give an indicator that the program is not connected to the database, which is what i want. I want it to start even if the database is offline and just give an indicator that its not connected
I set a connection indicator like this:
public void connStatus()
{
MySqlConnection myConn = new MySqlConnection("SERVER = localhost; user id = root; password =; database = mpdb");
try
{
myConn.Open();
dbconsign.Visible = true;
dbnotconsign.Visible = false;
}
catch (Exception ex)
{
MetroMessageBox.Show(this, ex.Message , "NOTIFICATION", MessageBoxButtons.OK, MessageBoxIcon.Hand);
dbconsign.Visible = false;
dbnotconsign.Visible = true;
}
finally
{
if (myConn.State == ConnectionState.Open)
{
myConn.Close();
}
}
}
(I know that my code above is not the best one for checking server connections, but i just needed something to indicate if the database is online or offline, im new to programming and im not very good at it yet.)
now, after I added some dll's and went on with my little program, the program will only start if Mysql is Online. It won't start at all and will give messages like this:
Could not find schema information for the element 'setting'.
Could not find schema information for the element 'value'.
so i figured out something is wrong at the App.Config,
and the problem is I only have little knowledge on XML and i don't understand whats going on with the one on my project.
Can someone please tell me why is this happening? and how do i fix it?
Any suggestions and corrections are highly appreciated.
this is the App.config of my project:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="cpsfmV2._0.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<userSettings>
<cpsfmV2._0.Properties.Settings>
<setting name="CurrentDate" serializeAs="String">
<value />
</setting>
</cpsfmV2._0.Properties.Settings>
</userSettings>
<system.data>
<DbProviderFactories>
<remove invariant="MySql.Data.MySqlClient" />
<add name="MySQL Data Provider" invariant="MySql.Data.MySqlClient" description=".Net Framework Data Provider for MySQL" type="MySql.Data.MySqlClient.MySqlClientFactory, MySql.Data, Version=6.9.12.0, Culture=neutral, PublicKeyToken=c5687fc88969c44d" />
</DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="MySql.Data" publicKeyToken="c5687fc88969c44d" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-6.9.12.0" newVersion="6.9.12.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I am so happy i learned something new today,i just learned about proper debugging today thanks to google and stackoverflow.
I tried to google stuff related to NullReference Exception i found a very helpful guide from this post, not exactly the answer but the guy on the post explained it in easily understandable terms for newbies like me.
What is a NullReferenceException, and how do I fix it?
though the error says:
'System.NullReferenceException' occurred in MetroFramework.dll Additional information: Object reference not set to an instance of an object.
which got me confused as a beginner, i read on the post linked above that you need to check for the InnerException,
which i did and led me to my other mistake which says
System.TypeInitializationException
and it turns out its all because of a variable i declared from another class.
someone whos a newbie like me might get the same problem so i'll share the posts that helped me.
how to solve System.TypeInitializationException was unhandled exception in vb.net?
Field xxx is never assigned to, and will always have its default value null
and the final solution to my problem was i turned this:
private AuditTrail audittrail = new AuditTrail();
private void loginbtn_Click(object sender, EventArgs e)
{
//some code here
audittrail.RecordLogin();
}
into this:
private AuditTrail audittrail;
private void loginbtn_Click(object sender, EventArgs e)
{
audittrail = new AuditTrail();
//some code here
audittrail.RecordLogin();
}
and now its working :) Thanks to the helpful posts above.
Related
I am trying to pass the full connection string to DbContext constructor as an argument and I get this error:
Unable to complete operation. The supplied SqlConnection does not specify an initial catalog or AttachDBFileName.
And this is what I have tried:
public DatabaseContext() :base(#"Data Source=|DataDirectory|ComponentDatabase.sqlite") {}
Problem can't be about anything else but connection string because I was able to connect my database using connection string from App.config like this:
App.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<entityFramework>
<providers>
<provider invariantName="System.Data.SQLite" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="System.Data.SQLite.EF6" type="System.Data.SQLite.EF6.SQLiteProviderServices, System.Data.SQLite.EF6" />
</providers>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="mssqllocaldb" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
<connectionStrings>
<!-- use AppDomain.SetData to set the DataDirectory -->
<add name="MapDbConnectionStr" connectionString="Data Source=|DataDirectory|ComponentDatabase.sqlite" providerName="System.Data.SQLite" />
</connectionStrings>
<system.data>
<DbProviderFactories>
<remove invariant="System.Data.SQLite.EF6" />
<add name="SQLite Data Provider (Entity Framework 6)" invariant="System.Data.SQLite.EF6" description=".NET Framework Data Provider for SQLite (Entity Framework 6)" type="System.Data.SQLite.EF6.SQLiteProviderFactory, System.Data.SQLite.EF6" />
<remove invariant="System.Data.SQLite" /><add name="SQLite Data Provider" invariant="System.Data.SQLite" description=".NET Framework Data Provider for SQLite" type="System.Data.SQLite.SQLiteFactory, System.Data.SQLite" /></DbProviderFactories>
</system.data>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Data.SQLite" publicKeyToken="db937bc2d44ff139" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.105.2" newVersion="1.0.105.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Data.SQLite.EF6" publicKeyToken="db937bc2d44ff139" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.0.105.2" newVersion="1.0.105.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
DbContext
public DatabaseContext() :base("MapDbConnectionStr") {}
P.S. I know that App.config has a lot of unnecessary lines, yes.
As far as I am aware there isn't a Connection factory for the type of database you are trying to connect to.
You could write your own connection factory:
public class MySqlLiteConnectionFactory : IDbConnectionFactory
{
public DbConnection CreateConnection(string connectionString)
{
return new SQLiteConnection(connectionString);
}
}
now go and find the entry for defaulConnectionfactory in app.config and replace the line which specifies the type. At the moment thats going to read something like this:
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
change it to something like this:
<defaultConnectionFactory type="MyNamespace.MySQLiteConnectionFactory, MyAssemblyHere" />
You should now be able to correctly use the Context ctor (string connectionString).
There is another was of doing this without relying on appsettings EF 6 and onwards supports code-based configuration.
So you can do something with configurations that looks a bit like this:
DbConfiguration.Loaded += (_, a) =>
{
a.ReplaceService<DbProviderServices>((s, k) => new MyProviderServices(s));
a.ReplaceService<IDbConnectionFactory>((s, k) => new MyConnectionFactory(s));
};
Full details of this are documented here at microsoft:
Using the name from config file works because it can determine the provider type based on accompanying config provided. When using the connection string directly in the constructor it cannot determine that the connection string is for SQLite and assumes MSSQL so it is trying to use a SqlConnection. Hence the error message you encountered.
Take Note:
The connection to the database (including the name of the database)
can be specified in several ways. If the parameterless DbContext
constructor is called from a derived context, then the name of the
derived context is used to find a connection string in the app.config
or web.config file. If no connection string is found, then the name is
passed to the DefaultConnectionFactory registered on the Database
class. The connection factory then uses the context name as the
database name in a default connection string. (This default connection
string points to .\SQLEXPRESS on the local machine unless a different
DefaultConnectionFactory is registered.) Instead of using the derived
context name, the connection/database name can also be specified
explicitly by passing the name to one of the DbContext constructors
that takes a string. The name can also be passed in the form
"name=myname", in which case the name must be found in the config file
or an exception will be thrown. Note that the connection found in the
app.config or web.config file can be a normal database connection
string (not a special Entity Framework connection string) in which
case the DbContext will use Code First. However, if the connection
found in the config file is a special Entity Framework connection
string, then the DbContext will use Database/Model First and the model
specified in the connection string will be used. An existing or
explicitly created DbConnection can also be used instead of the
database/connection name.
Taken from the class remarks for DbContext
The last quoted sentence stands out...
An existing or explicitly created DbConnection can also be used
instead of the database/connection name.
You could consider using SQLiteConnection
public class DatabaseContext : DbContext {
public DatabaseContext()
:base(new SQLiteConnection(#"Data Source=|DataDirectory|ComponentDatabase.sqlite"), true) {
//...
}
//...
}
As i understood correctly it could be helpful, please use builder with db context options. I use SqlServer, hovewer there should be not a lot of changes.
var builder = new DbContextOptionsBuilder<MapDbContext>();
builder.UseSqlServer(ConfigurationManager.ConnectionStrings["MapDbConnectionStr"].ConnectionString), opt => opt.EnableRetryOnFailure());
var mycontext = new MapDbContext(builder.Options);
public MapDbContext(DbContextOptions<MapDbContext> options)
: base(options)
{ }
Hope it helps, Good luck.
I am new to Postgresql. I am tring to use Postgresql with entity framework6, using npgsql.
I already have a database. I am using "Code First form database" option.
The problem is that the first time a query is executed, it takes me lots of time to execute it. I think that is when the connection is opened for the first time.
I created this simple example with the problem (TestJSONB is DbContext):
class Program
{
static void Main(string[] args)
{
TestQuery();
TestQuery();
}
private static void TestQuery()
{
using (DALJSONB.TestJSONB dataModel = new DALJSONB.TestJSONB())
{
var query1 =
dataModel.Database.SqlQuery<int>(
#"
SELECT 1;
");
query1.ToList();
var query2 =
dataModel.Database.SqlQuery<int>(
#"
SELECT 1;
");
query2.ToList();
}
}
}
The first execution times of TestQuery() are something like:
query1.ToList() - 2348ms
query2.ToList() - 2ms
The second execution times of TestQuery() are something like:
query1.ToList() - 19ms
query2.ToList() - 2ms
My app.config is:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
</startup>
<connectionStrings>
<add name="TestJSONB" connectionString="Host=x.x.x.x;Username=x;Password=x;Persist Security Info=True;Database=TestJSONB" providerName="Npgsql" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
<provider invariantName="Npgsql" type="Npgsql.NpgsqlServices, EntityFramework6.Npgsql" />
</providers>
</entityFramework>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Npgsql" publicKeyToken="5d8b90d52f46fda7" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.2.1.0" newVersion="3.2.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
Is it possible to decrease this time?
Thanks in advance.
This very likely has nothing to do with PostgreSQL or Npgsql, but rather with Entitt Framework itself starting up, building your model etc. try to connect to your database without EF (I.e. just creating an NpgsqlConnection and opening it) and you should see it runs pretty quickly.
It's common for EF applications to send sa sort of dummy warm-up query before actually servicing user calls, precisely to avoid this significant first-time delay.
I have created a web form that is a registration form using Identity. The form calls code behind that looks like this:
protected void CreateUser_Click(object sender, EventArgs e)
{
var userStore = new UserStore<IdentityUser>();
var manager = new UserManager<IdentityUser>(userStore);
var user = new IdentityUser() { UserName = UserName.Text };
IdentityResult result = manager.Create(user, Password.Text);
if (result.Succeeded)
{
StatusMessage.Text = string.Format("User {0} was created successfully!", user.UserName);
}
else
{
StatusMessage.Text = result.Errors.FirstOrDefault();
}
}
And my web config file is this:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section
name="entityFramework"
type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089"
requirePermission="false" />
</configSections>
<system.web>
<authentication mode="Forms" />
<roleManager enabled="true" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
I also have MS SQL Express installed on my machine. When i use the form the app creates a database in SQLExpress called DefaultConnection.
My question is how does entity/identity/.net know about my database at all, since I don't have the connection string written anywhere explicitly?
If this is somehow a feature of 'convention over configuration' then how can I explicitly direct entity to a different database?
Edit:
I have tried adding
<add name="MyConnection"
connectionString="[the connection string];TrustServerCertificate=False"
providerName="System.Data.SqlClient" />`
to the connection strings and updated my create user code:
...
var connString = ConfigurationManager.ConnectionStrings["MyConnection"].ConnectionString;
var context = new System.Data.Entity.DbContext(connString);
var userStore = new UserStore<IdentityUser>(context);
var manager = new UserManager<IdentityUser>(userStore);
...
but this threw a InvalidOperationException with the following message:
Additional information: The entity type IdentityUser is not part of the model for the current context.
Last Edit:
Found out how to avoid the exception, changed this:
var context = new System.Data.Entity.DbContext(connString);
into this:
var context = new Microsoft.AspNet.Identity.EntityFramework.IdentityDbContext(connString);
By convention a local database will be created on your local SQL Server instance.
See: Code First to a New Database - MSDN
By convention DbContext has created a database for you.
If a local SQL Express instance is available (installed by default with Visual Studio 2010) then Code First has created the database on that instance
If SQL Express isn’t available then Code First will try and use LocalDb (installed by default with Visual Studio 2012)
The database is named after the fully qualified name of the derived context
You can over come it by specifying an explicit connection string in web.config like:
<configuration>
<connectionStrings>
<add name="MyDBContext"
connectionString="Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName"
providerName="System.Data.SqlClient" />
</connectionStrings>
</configuration>
Here remember to change the name to the class that is extending DbContext in your code.
So for example if you are extending DbContext as:
public class MyDBContext : DbContext
then use MyDBContext as key for connection string in the configuration.
or off course you can pass the connection string in the constructor:
namespace MyCodeFirstProject
{
public class MyDBContext: DbContext
{
public MyDBContext() :
base("Data Source=SQLServerAddress;Integrated Security=SSPI;Initial Catalog=yourdbName") {}
}
}
I using c#. At this time I using Windows 7.My question is ; When I running my code,
that's gives me errors etc 193:0xc1 error , Services started but after stopped , 1053 services errors.
Here is my code.
public RupdaterService()
{
InitializeComponent();
this.timer1.Elapsed += new System.Timers.ElapsedEventHandler(this.timer1_Elapsed);
}
protected override void OnStart (string[] args)
{
timer1.Enabled=true;
this.DBEntry("Service Started");
}
protected override void OnStop()
{
this.timer1.Enabled = false;
this.DBEntry("Service Stopped");
}
private void timer1_Elapsed(object sender,System.Timers.ElapsedEventArgs e)
{
this.DBEntry("Service Running");
}
Here is my App.Config.
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c5***9" >
<section name="HedefliRUpdater.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5***9" requirePermission="false" />
</sectionGroup>
</configSections>
<system.serviceModel>
</system.serviceModel>
<applicationSettings>
<HedefliRUpdater.Properties.Settings>
<setting name="HedefliRUpdater_srvHedefli_wsrvHermesHedefliMesaj"
serializeAs="String">
<value>http://***.com/hedefli/srvHedefli.asmx</value>
</setting>
</HedefliRUpdater.Properties.Settings>
</applicationSettings>
Thanks in advance,
Some things to check. These happened to me, off the top of my head:
Is there anything in the Event Logs? They can sometimes give you a clue.
Is the Event Log full? If Windows can't write to it, it won't start the service. Try clearing the Application event log and see if it starts.
Are there any syntax errors in the .config file? We once had a problem with an .msi installer that put an <endpoint> tag after the end of </configuration>
It looks like you're writing to a database. Does the user that the service runs under have access to that database?
Try putting Debugger.Break() at the beginning of your OnStart() to prompt Windows to connect an instance of Visual Studio when it starts up. At the very least, it'll tell you if the fault is happening before it gets to your OnStart, or after.
Do you have more than one <endpoint> specified in the app.config/web.config file that matches the same contract? Try removing the superfluous endpoint
I don't know what your problem is, but this question Easier way to debug a Windows service provides excellent tips to allow you to debug the startup of your service.
I had a similar issue and found the following link to be useful:
http://support.microsoft.com/default.aspx?scid=kb;en-us;Q325680
In my case the exe was in C:\Documents ans Settings.... and there was a file named C:\Documents. Deleting this file helped, but I am still looking for a way to solve this programatically.
Bashing our heads against the wall here
We are an ISV and have hundreds of companies using our software with no problems. The software is Winforms/C# on .NET 2.0.
One of our clients has installed our software and it crashes on startup on all of their machines, apart from on one guy's laptop where it works fine.
On calling OdbcConnection.Open(), we get the following exception:
The type initializer for 'System.Transactions.Diagnostics.DiagnosticTrace' threw an exception.
at System.Transactions.Diagnostics.DiagnosticTrace.get_Verbose()
at System.Transactions.Transaction.get_Current()
at System.Data.Common.ADP.IsSysTxEqualSysEsTransaction()
at System.Data.Common.ADP.NeedManualEnlistment()
at System.Data.Odbc.OdbcConnection.Open()
at OurCompany.OurForm.connectionTestWorker_DoWork(Object sender)
This has an InnerException:
Configuration system failed to initialize
at System.Configuration.ClientConfigurationSystem.EnsureInit(String configKey)
at System.Configuration.ClientConfigurationSystem.PrepareClientConfigSystem(String sectionName)
at System.Configuration.ClientConfigurationSystem.System.Configuration.Internal.IInternalConfigSystem.GetSection(String sectionName)
at System.Configuration.ConfigurationManager.GetSection(String sectionName)
at System.Configuration.PrivilegedConfigurationManager.GetSection(String sectionName)
at System.Diagnostics.DiagnosticsConfiguration.GetConfigSection()
Google just says "app.config is syntactically incorrect, rebuild it" yet the same app.config works fine on hundreds of other machines.
Here's app.config, as requested:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="OurApp.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<system.diagnostics>
</system.diagnostics>
<applicationSettings>
<OurApp.Properties.Settings>
<setting name="OurApp_WebServices_OurServiceName" serializeAs="String">
<value>http://ourdomain.com/OurService.asmx</value>
</setting>
</OurApp.Properties.Settings>
</applicationSettings>
<appSettings>
<add key="WorkflowEngine" value="old" />
<add key="ProductID" value="3" />
<add key="EnableMigrationWizard" value="false" />
<add key="UseAlternativeFtpPort" value="true" />
<add key="FeedbackWhileConnecting" value="true" />
</appSettings>
</configuration>
A repair of the .NET Framework hasn't fixed this. I'm at a total loss. Any ideas?
Check machine.config and user.config. Along with app.config, those are the 3 that make up the config sections.
Reflector shows EnsureInit has 2 exception paths:
catch (Exception exception) {
this._initError = new ConfigurationErrorsException(SR.GetString("Config_client_config_init_error"), exception);
throw this._initError;
} catch {
this._initError = new ConfigurationErrorsException(SR.GetString("Config_client_config_init_error"));
throw this._initError;
}
Since the 2nd would only handle a non-CLS exception, I'd guess that you're hitting the first one. If that's the case, you probably need to recursively go through InnerException to get the full details.
Just for anyone's future reference, I had this problem with a local app that I was developing on my desktop and found that the problem was simply that I had the case wrong in . Once that was fixed it worked like a charm again.
Solved this by overwriting machine.config with a known working copy from another machine at the same SP/patch level.
I had this exact same error occur when trying to open an OLE DB connection with ASP/VB.NET 3.5 SP1. If I add my URL to the list of trusted sites in IE, then the error goes away and the connection opens successfully. I don't know if this will fix things in other browsers.