I have created a class library and added a EF Model but as soon as I declare a variable my project just skip the rest of my code without any error. I do not understand what is causing this to happen.
Library Code
public class Phisc
{
//Global DB Entity variable
live_restoreEntities db = new live_restoreEntities();
//Write data to file
public void PhiscFile(int value)
{
string strFileName, strFilePath;
StreamWriter stm;
//Create a file name that will be created
strFileName = DateTime.Now.ToString("yyyyMMddHHmmss") + "_PHISC";
//The path that were the file will be saved
strFilePath = "c:\\" + strFileName + ".txt";
//Validate if file exists
if (!System.IO.File.Exists(strFilePath))
System.IO.File.Create(strFilePath).Dispose();
stm = new StreamWriter(strFilePath, false);
stm.Write("This is a test message from C#");
stm.Close();
}
}
WinForm Code
private void Form1_Load(object sender, EventArgs e)
{
Phisc.Phisc pFile = new Phisc.Phisc();
pFile.PhiscFile(14);
}
When I create a instance of the library it does not hit my PhiscFile Method.
I have added a breakpoint to it and it stops at this constructor
public live_restoreEntities() : base("name=live_restoreEntities", "live_restoreEntities")
{
this.ContextOptions.LazyLoadingEnabled = true;
OnContextCreated();
}
I am using a windows application to test my library
The parameterless constructor goes out and look for the conenctionstring in the App.config file. It look next to the .exe file.
I'm guessing that you need to include your App.config (from your entity library) to your WinForms library.
In the App.config, it should look like this:
<configuration>
<connectionStrings>
<add name="live_restoreEntities"
connectionString="<your connection string here>"
providerName="System.Data.EntityClient" />
</connectionStrings>
</configuration>
Related
I know similar question was asked before more than once. I read some of the answers yet didn't find a clear one for my issue. To the point, I two applications say A & B. App A has a configuration file as follows:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key = "Key0" value = "4567" />
<add key = "Key1" value = "1" />
<add key = "Key2" value = "2" />
</appSettings>
</configuration>
App B tries to modify "Key0" of App A configuration file:
namespace ModifyOtherConfig
{
public partial class Form1 : Form
{
string otherConfigFilePath;
public Form1()
{
InitializeComponent();
}
private void exitToolStripMenuItem_Click(object sender, EventArgs e)
{
Application.Exit();
}
private void button1_Click(object sender, EventArgs e)
{
ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
fileMap.ExeConfigFilename = #"c:\users\om606\documents\visual studio 2015\projects\csharptesting\csharptesting\bin\debug\csharptesting.exe";
Configuration otherConfig = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
string otherSetting = otherConfig.AppSettings.Settings["Key0"].Value;
MessageBox.Show(otherSetting);
otherSetting = "098";
MessageBox.Show(otherSetting);
otherConfig.SaveAs(fileMap.ExeConfigFilename, ConfigurationSaveMode.Full);
}
}
}
When I try to run this code I get the following error:
An unhandled exception of type 'System.Configuration.ConfigurationErrorsException' occurred in System.Configuration.dll
Additional information: Data at the root level is invalid. Line 1, position 1.
What do I do wrong? Do I miss something very obvious? I'd appreciate if someone could point me in the right direction.
Oh, you're pointing your fileMap.ExeConfigFilename to the .exe, change it to point to the .config file instead. That's why you are seeing the xml error.
fileMap.ExeConfigFilename = #"c:\users\om606\documents\visual studio 2015\projects\csharptesting\csharptesting\bin\debug\csharptesting.exe.config";
for your other issue, do:
otherConfig.AppSettings.Settings.Remove("Key0");
otherConfig.AppSettings.Settings.Add("Key0", "098");
then save it.
I know, that the following code looks naive, but it should only bring to mind, what I want to achieve.
My web.config file:
<connectionStrings>
<add name="ADConnectionString" connectionString="AppData.GetConnectionString()" />
</connectionStrings>
I want to get the string from C#:
public class AppData
{
public static string GetConnectionString()
{
return "LDAP://expample.domain.com:389/DC=example,DC=domain,DC=com";
}
}
I know it is possible to get data from the web.config in the C# code (The AppSettings for example). But is the opposite also possible?
I dont think it is possible as it is just an XML file. All you can do in XML file is add comment,create nodes,add attributes or add nested elements etc etc but you cant add any code to it.
However I think there are certain languages that allow you to do so
https://stackoverflow.com/questions/24486772/write-php-code-inside-xml-file
I DO NOT recommend use it. But you actually can do something like this:
using System.Web.Configuration;
using System.Configuration;
var config = WebConfigurationManager.OpenWebConfiguration(null);
var connectionStringsSection = (ConnectionStringsSection)config.GetSection("connectionStrings");
connectionStringsSection.ConnectionStrings["ADConnectionString"].ConnectionString = AppData.GetConnectionString();
config.Save();
Use Reflection
Here's an example:
private string test = WebConfigurationManager.ConnectionStrings["Test"].ConnectionString; //returns "ExecuteTest" -- note! no parenthesis!
protected void Page_Load(object sender, EventArgs e)
{
MethodInfo m = this.GetType().GetMethod(test); //expects static method
if (m != null)
{
object result = m.Invoke(this, new object[] { });
}
}
private static void ExecuteTest()
{
//do stuff
}
But no, you can't edit/pull data into the web.config on the fly. Changing the web.config will cause the application to restart killing all sessions. It's possible to build the web.config prior to starting but once it's up and running it's essentially locked down.
I have developed a Windows application with the backend of SQL Server to insert employee names. I am going to insert the employee details on three databases one by one. So, I like to get connecting values from text file. Whenever I want to change the connection, I just want to enter the login details in the text file.
How can I get a connection string from a text file?
Use an app.config (MSDN) file.
Allows you to configure multiple named connection strings which you can access via the System.Configuration.ConfigurationManager class' ConnectionStrings property
Plaese try like this
using System;
using System.IO;
class Test
{
public static void Main()
{
string txtpath = #"c:\textfile.txt";
try
{
if (File.Exists(txtpath))
{
using (StreamReader sr = new StreamReader(txtpath))
{
while (sr.Peek() >= 0)
{
string ss = sr.ReadLine();
string [] txtsplit = ss.Split(';');
//now loop through array
string server=txtsplit[0].Tostring();
string userid= split[1].Tostring(); // user id
string password= split[2].Tostring(); // password
}
}
}
}
catch (Exception e)
{
Console.WriteLine("Error: {0}", e.ToString());
}
}
}
You don’t need to use plain text file to do this. There is a special configuration file you can use and a set of classes to make your life easier.
Add configuration file to you project
Go to Add new item in the solution and select Application Configuration File
Add connection strings to the configuration file
Just copy / paste this and modify connection string and connection string name as needed
<configuration>
<connectionStrings>
<add name="Conn1" connectionString="Data Source=SERVER_NAME;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=12345678" providerName="System.Data.SqlClient"/>
<add name="Conn2" connectionString="Data Source=SERVER_NAME;Initial Catalog=DATABASE;Persist Security Info=True;User ID=USER;Password=12345678" providerName="System.Data.SqlClient"/>
</connectionStrings>
</configuration>
Add System.Configuration reference to your project
Right click references, go to add new and select System.Configuration from .NET tab
Add wrapper class
This is not needed but it will make your life easier. Create a class like this so you don’t have to call configuration manager every time you need to connect to database
using System;
using System.Configuration;
using System.Text;
namespace WindowsFormsApplication4
{
class Config
{
public static string CONNECTION_STRING_1
{
get
{
return ConfigurationManager.ConnectionStrings["Conn1"].ConnectionString;
}
}
public static string CONNECTION_STRING_2
{
get
{
return ConfigurationManager.ConnectionStrings["Conn2"].ConnectionString;
}
}
}
}
Use connection strings in other methods like this
SqlConnection conn = new SqlConnection(Config.CONNECTION_STRING_1);
class Sql
{
public static string ReadCS()
{
using (var streamReader = File.OpenText("SqlSettings.txt"))//Enter FileName
{
var lines = streamReader.ReadToEnd();
return lines;
}
}
public SqlConnection con = new SqlConnection(Sql.ReadCS());
}
I'm creating a setup project for my C# desktop application.
What the data source should be written in the connection string for the access database ?and where I should put my database file in the solution project ?
Assuming you're using the VS setup project, you need to add the access database file as content and place it in the application directory, for example. To specify the location in the configuration file, you need to write a custom action that modifies the connection string accordingly.
The following example is an installer class that sets the connection string after install phase (not tested):
[RunInstaller(true)]
public partial class Installer1 : System.Configuration.Install.Installer
{
public Installer1()
{
InitializeComponent();
this.AfterInstall += new InstallEventHandler(Installer1_AfterInstall);
}
void Installer1_AfterInstall(object sender, InstallEventArgs e)
{
string sTargetDir = Context.Parameters["TargetDir"];
string sAppConfig = Path.Combine(sTargetDir, "<your app>.exe.config");
string sDBPath = Path.Combine(sTargetDir, "<your db>.mdb");
XDocument doc = XDocument.Load(sAppConfig);
var elem = doc.Root.Element("/configuration/connectionStrings/add[#name='<your connection name>']");
string connectionString = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0};", sDBPath);
elem.SetAttributeValue("connectionString", connectionString);
doc.Save(sAppConfig);
}
}
Alternatively, you can use Wix which has the XmlFile utility in the util extension which does it for you without you writing a custom action.
I am currently in the middle of creating an app that uses a sql CE database, I have made this database deploy-able with the application, however the problem I'm having at the moment is I need to run TestMethods but this is erroring out when it doesn't find the database as its looking in the "testingProject" folder under debug or release as that is it's Data Directory
using (SqlCeConnection sqlCon = new SqlCeConnection(#"Data Source=|DataDirectory|\database.sdf;Persist Security Info=False;"))
The code above is my connection string, so I'm guessing that means that the test is running and searching for a database in its own data directory
Any help on what I could do without changing the database connection string, database location and still leaving my application deployable? or am I asking something impossible?
EDIT
[TestMethod]
public void TestForReadingFromDB()
{
List<string> list = class.readDB();
Assert.IsNotNull(list);
Assert.AreNotEqual(0, list.Count);
}
just added in the test method that's currently failing
In the test project you can override the DataDirectory location using
AppDomain.CurrentDomain.SetData("DataDirectory", <PATH_TO_DATA_DIRECTORY>);
For instance in my app.config file the testing projects I have
<appSettings>
<add key="DataDirectory" value="..\..\Database"/>
</appSettings>
In my test fixture base I have:
var dataDirectory = ConfigurationManager.AppSettings["DataDirectory"];
var absoluteDataDirectory = Path.GetFullPath(dataDirectory);
AppDomain.CurrentDomain.SetData("DataDirectory", absoluteDataDirectory);
This sets the DataDirectory to the folder /Database under the test project folder structure.
Once I drop or create a copy of the database in there I can easily run Integration Tests.
this is how I specify the data directory path for testing in my initialize data class
public class TestClasse
{
public TestClass()
{
GetAppDataDirectoryForTesting();
}
private static string GetAppDataDirectoryForTesting()
{ //NOTE: must be using visual studio test tools for this to work
string path = AppDomain.CurrentDomain.BaseDirectory;
var dirs = path.Split(Path.DirectorySeparatorChar);
var appDataPath = "";
for (int i = 0; i < dirs.Length - 3; i++)
{
appDataPath += dirs[i] + Path.DirectorySeparatorChar.ToString();
}
appDataPath = appDataPath + "[foldername(i.e. in my case project name)]" + Path.DirectorySeparatorChar.ToString() + "App_Data";
return appDataPath;
}
[TestMethod]
public void SomeTestMethod()
{
....test code
}
}