Null return from C# application settings file - c#

I am attempting to use this code:
String MainDB = ConfigurationManager.AppSettings["MainDB"];
MessageBox.Show(MainDB);
String MailInfo = ConfigurationManager.AppSettings["MailInfo"];
MessageBox.Show(MailInfo);
String HousingIndexLocation = ConfigurationManager.AppSettings["HousingIndex"];
MessageBox.Show(HousingIndexLocation);
to access values generated by this screen:
Everytime the values are returned null.
what am I missing in my implementation of these settings?

Try
String MainDB = Properties.Settings.Default.MainDB;
MessageBox.Show(MainDB);
String MailInfo = Properties.Settings.Default.MailInfo;
MessageBox.Show(MailInfo);
String HousingIndexLocation = Properties.Settings.Default.HousingIndex;
MessageBox.Show(HousingIndexLocation);

You're getting an error because ConfigurationManager is not the proper way to access properties stored in those files. Take a look at:
Using Settings in C#
Long story short, you access the settings in the Settings file using the Properties namespace:
Properties.Settings.Default.MainDB;
// And so on...

Related

How to make a model to carry only a boolean value without database?

I have a settings page and one of them is called "Enable News" And it have to return a boolean value
What i want to do is to carry the value of this field and call it again in another pages like
if (model.Boolean == true)
{
//Code
}
WITHOUT using database because this option is made for only 1 User
The purpose is to save this data in the model without database and be able to edit it later
Storing configurations can be done using XML, JSON and other formats according to the project requirements and what you're comfortable using.
JSON format is fairly simple if you have an object like
class UserSettings {
public bool EnableNews {get; set}
...
}
Then you can simple use Json.NET to store and retrieve an object of this class as follows:
var settings = new UserSettings();
settings.EnableNews = True;
....
string json = JsonConvert.SerializeObject(settings, Formatting.Indented);
//store it to file settings.json for example
//when you want to edit it you can load the file to string
string json_string = File.ReadAllText("file_path");
//then convert json string to model back to edit and read it
UserSettings userSettings = JsonConvert.DeserializeObject<UserSettings>(json_string);
for more details read Newtonsoft Json Package samples

How to read resourcefile from dll c#

I would like to use resourcefiles to get some text.These resourcefiles will be in dll.It's nothing todo with localization just in case you ask.
I want to have the ability to choose which rexfile to use based on a configsettings.
Sample
MyCompany.RexFiles.dll
RexFileA
RexFileB
RexFileC
My question
Given that in a config file I have a settings that decide which rexfile to use eg CurrentRexfile="RexFileB"
How can I default to right rexFile depending on the configSettings.
Any suggestions
You can use the ResourceManager Class to retrieve resources:
System.Reflection.Assembly myAssembly = this.GetType().Assembly;
string rexFile = ConfigurationManager.AppSettings["CuurentRexfile"];
System.Reflection.Assembly otherAssembly = System.Reflection.Assembly.Load(rexFile);
System.Resources.ResourceManager resManager = new System.Resources.ResourceManager("ResourceNamespace.myResources", otherAssembly);
string test = resManager.GetString("resourceString");
more read here

How to Create New User Setting in app.config at Run Time

I have an Editable ComboBox. The user enters text and presses a Save button. Their text is turned into a string.
I need it at Run Time to Create a new User Setting to the app.config with the name of their string. (I think this part works now).
Then another ComboBox's Selected Item is saved to the Setting. (Object reference not set error).
This is to create a custom preset that will save each control state, checkboxes, textboxes, etc. in the program.
// Control State to be Saved to Setting
Object comboBox2Item = ComboBox2.SelectedItem;
// User Custom Text
string customText = ComboBox1.Text;
// Create New User Setting
var propertyCustom = new SettingsProperty(customText);
propertyCustom.Name = customText;
propertyCustom.PropertyType = typeof(string);
Settings.Default.Properties.Add(propertyCustom);
// Add a Control State (string) to the Setting
Settings.Default[customText] = (string)comboBox2Item;
At this part I get an error.
Settings.Default[customText] = (string)comboBox2Item;
Exception:Thrown: "Object reference not set to an instance of an object."
I have tried setting ComboBox1.Text to an Object instead of string, with same error. The text and string is also not null.
Object customText = ComboBox1.Text;
Here's a visual of what I'm trying to do
Original Answer:
I haven't tried adding a new setting to the file but i have had to update it. Here is some code that I use to save and retrieve the saved changes to the file. I know it doesn't directly answer the question but should point you in the right direction as to what classes to look at and use.
I'll try to update to directly answer this question once I get some breathing time.
public static void UpdateConfig(string setting, string value, bool isUserSetting = false)
{
var assemblyPath = AppDomain.CurrentDomain.BaseDirectory;
var assemblyName = "AssemblyName";
//need to modify the configuration file, launch the server with those settings.
var config =
ConfigurationManager.OpenExeConfiguration(string.Format("{0}\\{1}.exe", assemblyPath, "AssemblyName"));
//config.AppSettings.Settings["Setting"].Value = "false";
var getSection = config.GetSection("applicationSettings");
Console.WriteLine(getSection);
var settingsGroup = isUserSetting
? config.SectionGroups["userSettings"]
: config.SectionGroups["applicationSettings"];
var settings =
settingsGroup.Sections[string.Format("{0}.Properties.Settings", assemblyName)] as ClientSettingsSection;
var settingsElement = settings.Settings.Get(setting);
settings.Settings.Remove(settingsElement);
settingsElement.Value.ValueXml.InnerText = value;
settings.Settings.Add(settingsElement);
config.Save(ConfigurationSaveMode.Modified);
ConfigurationManager.RefreshSection("appSettings");
Edited Answer:
I did a quick google search and found an accepted answer on the MSDN forum.MSDN question. You have to call save on the properties class in order for the add to take affect. Think of a database transaction, until you call commit, it doesn't take effect.
So what appears to be missing in your code is: Properties.Settings.Default.Save(); which should be the very next line after your Settings.Default.Properties.Add(propertyCustom);

Dynamically creating connection string EF6.0 causes problems

I have the following code somewhere in the application. the code goes like this:
Hyperion.Data.MCQEntities _model = null;
const string K_MODEL = #"res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;";
public Engine(string cnnstr)
{
//string connection =(new ConnectionStringBuilder(cnnstr)).ToString();
string connectionString = new System.Data.EntityClient.EntityConnectionStringBuilder
{
Metadata = K_MODEL, //"res://*",
Provider = "System.Data.SqlClient",
ProviderConnectionString = cnnstr,
}.ConnectionString;
_model = new Data.MCQEntities(connectionString);
_model.Connection.Open();
}
the problem I do not understand is that when I use Metadata = "res://*" it works but when I use Metadata=K_MODEL it does not work at all. what could be the issue?
res//* tells EF that metadata is embedded in the assembly as a resource. If you skip it EF is looking for file on the disk. The default build action for edmx is to embed artifacts in the assembly so if you have not changed this files are not on disk and EF cannot find them.

What is the EzAPI equivalent for using an OLE DB Source command from variable?

tl;dr
What is the EzAPI code to use an OLE DB Source with data access mode of "SQL command from variable" and assign a variable?
Preamble
Once a month, we need to refresh our public test site with subsets of production data. We have determined that for our needs, an SSIS solution provides the best fit for accomplishing this task.
My goal is to systematically build a large number (100+) of "replication" packages. EzAPI is a friendly wrapper to the SSIS object model and it seems like a great way to save mouse-clicks.
I would like for my packages to look like
Variable - "tableName"; [Schema].[TableName]
Variable - "sourceQuery"; SELECT * FROM [Schema].[TableName]
DataFlow - "Replicate Schema_TableName"
OLE DB Source - "Src Schema_TableName"; Data Access Mode: SQL command from variable; Variable name: User::sourceQuery
OLE DB Destination - "Dest Schema_TableName"; Table or view name variable- fast load; Variable name - User::tableName
Code
This is the code for my table to table replication package.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.SqlServer.SSIS.EzAPI;
using Microsoft.SqlServer.Dts.Runtime;
namespace EzApiDemo
{
public class TableToTable : EzSrcDestPackage<EzOleDbSource, EzSqlOleDbCM, EzOleDbDestination, EzSqlOleDbCM>
{
public TableToTable(Package p) : base(p) { }
public static implicit operator TableToTable(Package p) { return new TableToTable(p); }
public TableToTable(string sourceServer, string database, string table, string destinationServer) : base()
{
string saniName = TableToTable.SanitizeName(table);
string sourceQuery = string.Format("SELECT D.* FROM {0} D", table);
// Define package variables
this.Variables.Add("sourceQuery", false, "User", sourceQuery);
this.Variables.Add("tableName", false, "User", table);
// Configure DataFlow properties
this.DataFlow.Name = "Replicate " + saniName;
this.DataFlow.Description = "Scripted replication";
// Connection manager configuration
this.SrcConn.SetConnectionString(sourceServer, database);
this.SrcConn.Name = "PROD";
this.SrcConn.Description = string.Empty;
this.DestConn.SetConnectionString(destinationServer, database);
this.DestConn.Name = "PREPROD";
this.DestConn.Description = string.Empty;
// Configure Dataflow's Source properties
this.Source.Name = "Src " + saniName;
this.Source.Description = string.Empty;
this.Source.SqlCommand = sourceQuery;
// Configure Dataflow's Destination properties
this.Dest.Name = "Dest " + saniName;
this.Dest.Description = string.Empty;
this.Dest.Table = table;
this.Dest.FastLoadKeepIdentity = true;
this.Dest.FastLoadKeepNulls = true;
this.Dest.DataSourceVariable = this.Variables["tableName"].QualifiedName;
this.Dest.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE;
this.Dest.LinkAllInputsToOutputs();
}
/// <summary>
/// Sanitize a name so that it is valid for SSIS objects.
/// Strips []/\:=
/// Replaces . with _
/// </summary>
/// <param name="name"></param>
/// <returns></returns>
public static string SanitizeName(string name)
{
string saniName = name.Replace("[", String.Empty).Replace("]", string.Empty).Replace(".", "_").Replace("/", string.Empty).Replace("\\", string.Empty).Replace(":", string.Empty);
return saniName;
}
}
}
Invocation looks like TableToTable s2 = new TableToTable(#"localhost\localsqla", "AdventureWorks", "[HumanResources].[Department]", #"localhost\localsqlb"); and that builds a package that does what I want except for using a variable in the source.
Problem
The above code supplies the access mode as SQL Query and the query is embedded in the OLE Source. The desire it to use "SQL Command From Variable" and that variable being #[User::sourceQuery] What I'm stuck on is using a variable in the source.
It should be a simple matter of assigning something like
this.Source.DataSourceVariable = this.Variables["sourceQuery"].QualifiedName;
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND_VARIABLE;
This results in the correct data access mode selected but the variable isn't populated.
You can observe that I perform a similar step in the destination which does accept the variable and works "right."
this.Dest.DataSourceVariable = this.Variables["tableName"].QualifiedName;
this.Dest.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE;
What doesn't work
Listing out the permutations I've attempted
this.Source.AccessMode = AccessMode.AM_OPENROWSET;
Results in Data Access Mode set to Table or View and name of table or the view is blank.
this.Source.AccessMode = AccessMode.AM_OPENROWSET_VARIABLE;
Results in Data Access Mode set to "Table or view name variable" and variable name is sourceQuery. Very close to what I want, except the access mode is not correct. Were this package to run, it'd blow up as the OpenRowSet would expect a straight table name.
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND;
Results in Data Access Mode set to "SQL Command" and the SQL command text is "User::sourceQuery" That's the literal value of the variable name so it's the right thing but since the access mode is wrong, it doesn't work.
this.Source.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD;
this.Source.AccessMode = AccessMode.AM_OPENROWSET_FASTLOAD_VARIABLE;
Niether of these are correct access modes as they are for destinations (I still tried them but they didn't work as expected).
At this point, I thought I'd try to work backwards by creating a package that has the OLE DB source defined as I want it and then inspect the source object's properties.
Application app = new Application();
Package p = app.LoadPackage(#"C:\sandbox\SSISHackAndSlash\SSISHackAndSlash\EzApiPackage.dtsx", null);
TableToTable to = new TableToTable(p);
My code has set both SqlCommand and DataSourceVarible with the variable's qualified name. I've pulled down changeset 65381 and compiled that (after fixing some references to the SQL Server 2012 dlls) in hopes there might have been a fix since the Dec 30 2008 Stable build but to no avail.
Have I found a bug in their code or am I just missing something?
The current, stable build of EzAPI does not support the assignment of a variable as an OleDB Source property. I opened a similar discussion over on CodePlex and ended up learning more about how all of this works.
The root problem is the related property "SqlCommandVariable" should be set when the access mode is set to "SQL Command from Variable." Currently, the code only covers destination variables.
My resolution was to download the source code and modify the setter for the property DataSourceVariable in EzComponents.cs (line 1027 for changeset 65381)
set
{
m_comp.SetComponentProperty("OpenRowsetVariable", value);
if (AccessMode == AccessMode.AM_SQLCOMMAND_VARIABLE)
{
m_comp.SetComponentProperty("SqlCommandVariable", value);
}
ReinitializeMetaData();
}
If you're looking to get this problem resolved properly, you may upvote the Issue
Try swapping around
this.Source.DataSourceVariable = this.Variables["sourceQuery"].QualifiedName;
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND_VARIABLE;
to
this.Source.AccessMode = AccessMode.AM_SQLCOMMAND_VARIABLE;
this.Source.DataSourceVariable = this.Variables["sourceQuery"].QualifiedName;
I've discovered that the order matters more than it does with a typical API.

Categories

Resources