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.
Related
I have a solution (S) in Visual Studio containing 3 projects, I'll call them CL, WPF, and CFG;
S.CL is a project for a console application.
S.WPF is a project for a WPF application.
S.CFG is a project that contains the config file.
I have created a settings file with user scope and public visibility. Both of these projects use the same settings.
S.CL only needs to read these settings.
S.WPF is a form to edit these settings, so it requires read and write. It contains a save button connected to an event handler.
S.CFG app.config:
<?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="S.CFG.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<S.CFG.Properties.Settings>
<setting name="ExampleSetting" serializeAs="String">
<value>ExampleValue</value>
</setting>
</S.CFG.Properties.Settings>
</userSettings>
</configuration>
S.CL Execute.cs:
namespace S.CL
{
public class Execute
{
public static void Main(String[] args)
{
Console.WriteLine(S.CFG.Properties.Settings.Default.ExampleSetting);
}
}
}
S.WPF MainWindow.xaml.cs:
namespace S.WPF
{
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
S.CFG.Properties.Settings.Default.ExampleSetting = "New value";
Console.WriteLine(S.CFG.Properties.Settings.Default.ExampleSetting);
}
}
}
So, steps to reproduce:
Run S.CL out> ExampleValue
Run S.WPF out> New value
Run S.CL out> ExampleValue
On the last run of S.CL, the output should have been "New value".
I can confirm that S.WPF also gets the newest value every time it runs. In my full application, the form displays the newest value in a text box before hitting save.
So far I've managed to find out the S.WPF creates a folder with this new app.config in the user's AppData folder. S.CL uses it's built in copy of the default config, whereas S.WPF uses it's built in copy of the default config until it writes, where it then creates a local copy that only that executable accesses.
I just want to be able to persist these settings between these 2 executables. I have thought about other ways of doing this, another would be to keep an XML file of settings in the root directory of both executables and just parse this file but I would rather using Visual Studio's app.config/Settings.Settings functionality to do this (if possible).
Thanks in advance!
instead of adding the app.config files to each project, you could have one app.config file in your solution and link this one file to both of the projects, as described here: Share code with Add as Link.
Edit:
If you want to be able to load an external app.config, you can check follow the instructions of this post,
I would like to access the values in the ConfigurationManager.AppSettings object from a MEF plugin which has its own app.config file.
However, the keys from the app.config file are not present in AppSettings after the plugin is loaded.
The keys from the application loading the plugin are still present.
I noticed that using a Settings.settings file allows this behaviour, via the app.config file, so the file must be being loaded somehow.
My plugin looks like:
[Export(IPlugin)]
public class Plugin
{
public Plugin()
{
// reads successfully from app.config via Settings object
var value1 = Settings.Default["Key1"];
// returns null from app.config via ConfigurationManager
var value1 = ConfigurationManager.AppSettings["Key2"]
}
}
The app.config looks like this:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="..." >
<section name="Plugin.Settings" type="..." />
</sectionGroup>
</configSections>
<appSettings>
<add key="Key2" value="Fails" />
</appSettings>
<applicationSettings>
<Plugin.Settings>
<setting name="Key1" serializeAs="String">
<value>Works</value>
</setting>
</Plugin.Settings>
</applicationSettings>
</configuration>
I can manually load the app.config file with:
var config = ConfigurationManager.OpenExeConfiguration("Plugin.dll");
var value = AppSettings.Settings["Key2"].Value
but this seems more like a workaround than a solution.
Is there a way to access a MEF plugin's <appSettings> directly, from inside the plugin?
If not, what is recommended?
By default the ConfigurationManager loads the .config for the entry assembly, i.e. the assembly that started the currently executing process.
The correct way to do this would be something like this:
[Export(IPlugin)]
public class Plugin
{
public Plugin()
{
var config = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
var value = config.AppSettings.Settings["Key2"].Value;
}
}
This would make the plugin automatically open the .config for the DLL it was compiled in, and fetch values from there.
I'd recommend you to use a dependency injection tool like Unity, in order to provide to your plug-ins the configuration they required. By proceeding in this way, your plug-ins will no longer need to reference System.Configuration.dll.
When are settings from app.config actually read by application?
Suppose I have a windows service and some app settings for it. In code I have a method where some setting is used. Method is being called in every iteration, not just once during all the time. If I change the setting value through the configuration file should I restart the service for it to be "refreshed" inside or will it be accepted the next time without any interaction from my side?
You need to call ConfigurationManager.RefreshSection method to get the latest values read directly from disk. Here's a simple way to test and provide answer to your question:
static void Main(string[] args)
{
while (true)
{
// There is no need to restart you application to get latest values.
// Calling this method forces the reading of the setting directly from the config.
ConfigurationManager.RefreshSection("appSettings");
Console.WriteLine(ConfigurationManager.AppSettings["myKey"]);
// Or if you're using the Settings class.
Properties.Settings.Default.Reload();
Console.WriteLine(Properties.Settings.Default.MyTestSetting);
// Sleep to have time to change the setting and verify.
Thread.Sleep(10000);
}
}
My app.config containing:
<?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="ConsoleApplication2.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="myKey" value="Original Value"/>
</appSettings>
<userSettings>
<ConsoleApplication2.Properties.Settings>
<setting name="MyTestSetting" serializeAs="String">
<value>Original Value</value>
</setting>
</ConsoleApplication2.Properties.Settings>
</userSettings>
</configuration>
After you start the application, open the app.config within the build folder, and change the value of the appSetting "myKey". You'll see the new value printed out to the console.
To answer the question, yes they are cached on the first time they are each read I think, and to force the read straight from the disk, you need to refresh the section.
Either when you load it up via the configuration manager (ConfigurationManager.GetSection("x/y");) or when you try to access the properties.
There is a slight grey area here because when you get the configuration out via the config manager:
var config = (MyConfigSection)ConfigurationManager.GetSection("MyConfigSection");
You get a configuration object back if you have provided the configuration section type in the configurationSections element at the top of the config file. If you do not actually provide the actual config you will still get an object back.
However if you have a required field that is not set it will not throw an exception till you call the property. I have worked this out whilst trying to unit test my custom configuration sections.
I've tried updating my application's .config file during installer (via a .NET Installer Class Action). But, I can't seem to get ConfigurationManager to list any properties or be able to set anything.
I learned of this approach from several stackoverflow posts that pointed me to this guide: http://raquila.com/software/configure-app-config-application-settings-during-msi-install/
I've investigated the differences between my project and his and noticed that my configuration files are formatted differently. I believe this has to do with the fact that i'm using "Settings" files.
Config files formatted in the guide look like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="Param1" value="" />
<add key="Param2" value="" />
<add key="Param3" value="" />
</appSettings>
</configuration>
Where mine looks like:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<sectionGroup name="userSettings" type="System.Configuration.UserSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyAppName.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
<section name="MyAppName.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" allowExeDefinition="MachineToLocalUser" requirePermission="false" />
</sectionGroup>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" >
<section name="MyAppName.Settings1" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<userSettings>
<MyAppName.Properties.Settings>
<setting name="TESTSETTING" serializeAs="String">
<value>asdfasdfasdf</value>
</setting>
</MyAppName.Properties.Settings>
<MyAppName.Settings1>
<setting name="VerboseErrorMode" serializeAs="String">
<value>False</value>
</setting>
<applicationSettings>
<MyAppName.Settings1>
<setting name="RunOnStartup" serializeAs="String">
<value>True</value>
</setting>
</MyAppName.Settings1>
</applicationSettings>
</configuration>
To shed some light on what was going on... I tried printing out the list of settings like so:
Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
// Try getting the Settings1 Section
AppSettingsSection appSettings = (AppSettingsSection)config.GetSection("Settings1"); // Also tried myNamespace.Settings1
if (appSettings != null)
{
valList = "Settings1: ";
foreach (string key in appSettings.Settings.AllKeys)
{
string value = appSettings.Settings[key].Value;
valList += ("Key: '" + key + "' = '" + value + "'\n");
}
}
else
{
valList = "appSettings was null";
}
MessageBox.Show(valList);
MessageBox.Show(valList);
I have tried several permutations of this... and in all cases output is "appSettings was null".
I also tried initializing the configuration manager in several different ways...
Configuration config = ConfigurationManager.OpenExeConfiguration(exePath);
MessageBox.Show("Section Count: " + config.Sections.Count);
MessageBox.Show("Has File: " + config.HasFile);
MessageBox.Show("Namespace Declared: " + config.NamespaceDeclared);
config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
MessageBox.Show("Section Count: " + config.Sections.Count);
MessageBox.Show("Has File: " + config.HasFile);
MessageBox.Show("Namespace Declared: " + config.NamespaceDeclared);
For each of them the section count returned was 20. (I have no idea where the 20 comes from... I would have expected it to be 3).
HasFile was true for the first case and false for the second.
Namespace Declared was false in both cases.
Thanks!
EDIT (6-18-09): Still looking into this question. Anyone else have any ideas? Thanks.
Search Keywords: "Object Reference Not Set to not set to an instance" <-- this occurs when trying to write to a property.
I came across the same problem, after deep investigation, I found out the easiest way to update any part of config files (e.g. app.config), that's by using XPath.
We have an application which connects to web service, during the installation, the user enters the URL of the web service and this should be saved in the following app.config file:
<?xml version="1.0"?>
<configuration>
<configSections>
<sectionGroup name="applicationSettings" type="System.Configuration.ApplicationSettingsGroup, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089">
<section name="ApplicationServer.Properties.Settings" type="System.Configuration.ClientSettingsSection, System, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</sectionGroup>
</configSections>
<applicationSettings>
<ApplicationServer.Properties.Settings>
<setting name="ApplicationServer_ApplicationServerUrl" serializeAs="String">
<value>whatever comes from setup should go here</value>
</setting>
</ApplicationServer.Properties.Settings>
</applicationSettings>
</configuration>
Here is the code to do this in the installer class:
public override void Install(System.Collections.IDictionary stateSaver)
{
base.Install(stateSaver);
string targetDirectory = Context.Parameters["targetdir"];
string param1 = Context.Parameters["param1"];
string path = System.IO.Path.Combine(targetDirectory, "app.config");
System.Xml.XmlDocument xDoc = new System.Xml.XmlDocument();
xDoc.Load(path);
System.Xml.XmlNode node = xDoc.SelectSingleNode("/configuration/applicationSettings/Intellisense.ApplicationServer.Properties.Settings/setting[#name='ApplicationServer_ApplicationServerUrl']/value");
node.InnerText = (param1.EndsWith("/") ? param1 : param1 + "/");
xDoc.Save(path); // saves the web.config file
}
Basically, since the config file is a XML based document, I am using XPath expression to locate specific node and change its value.
One thing to try is moving it from install to Commit to ensure that the file has been written first before trying to access it. Alternatively you could use the custom action to write your own file and just alter your config file to point at the alternative xml file.
I worked on a Sharepoint product install where I dug into all of this and I will admit it is very tedious to get working correctly. I was creating config and batch files on the fly based on install parameters.
You can access these settings using the System.Configuration namespace but, its not as simple as I would like and in retrospect using System.Xml.Linq is far simpler. Anyway, here is how I got it to work.
The important concept is, the applicationSettings section is not AppSettings, its a seperate section supported by the ClientSettingsSection type.
//Open the application level config file
ExeConfigurationFileMap exeMap = new ExeConfigurationFileMap();
exeMap.ExeConfigFilename = String.Format("{0}.config",
Context.Parameters["assemblypath"]);
Configuration config = ConfigurationManager.OpenMappedExeConfiguration(exeMap,
ConfigurationUserLevel.None);
//Get the settings section
ClientSettingsSection settingsSection =
config.GetSectionGroup("applicationSettings").Sections
.OfType<ClientSettingsSection>().Single();
//Update "TheSetting"
//I couldn't get the changes to persist unless
//I removed then readded the element.
SettingElement oldElement = settingsSection.Get("TheSetting");
settingsSection.Settings.Remove(oldElement);
SettingElement newElement = new SettingElement("TheSetting",
SettingSerializeAs.String);
newElement.Value = new SettingValueElement();
newElement.Value.ValueXml = oldElement.Value.ValueXml.CloneNode(true);
newElement.Value.ValueXml.InnerText = "Some New Value";
settingsSection.Add(newElement);
//Save the changes
config.Save(ConfigurationSaveMode.Full);
So, as you can see, simple. :-S
Instead of accessing your settings configuration via ConfigurationManager, you should be able to access it via Settings.Default. Settings are more of a Visual Studio feature than a .NET feature...a convenience that makes it easy to visually design your applications configuration rather than manually writing it in appSettings or creating custom configuration sections. However, the configuration schema that is rendered when you use Settings is non-standard, and can be difficult to access manually.
Visual Studio should have generated a Settings class for you when you built your application, and you should be able to access that class via Properties.Settings.Default. It should have a property for each setting, in your case, the following:
Properties.Settings.Default.TESTSETTING
Properties.Settings.Default.VerboseErrorMode
Properties.Settings.Default.RunOnStartup
You should be able to both read and write these settings. A critical thing to note...anything flagged as a "user" setting will not be written back to the {yourapplication}.exe.config file...it will be written to a User.config file in the users isolated profile storage area. This is under C:\Documents and Settings{username} on XP, and C:\Users{username} on Vista, in the AppData folder. Depending on the OS and users profile, the subfolder under the AppData may change, but its completely unique and keyed to a particular version of the application. Installation of a newer version will result in a completely new set of configuration settings stored under the same keyed folder, but a different version subfolder.
I hope this helps. :)
This is what you need: http://social.msdn.microsoft.com/Forums/en-US/csharpgeneral/thread/f89a00eb-9400-48ce-af20-cef78002c14e
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.