Unable to Insert \ Update using EF6 - c#

I am creating an ASP.Net MVC application and I have created a new console application just so that I can pass it a few parameters and use the DataContext in the MVC application so that I dont have to continually repeat myself.
This is the code that I am using
using mySite.WebSite.DataModel;
namespace mySite.AvailabilityManager
{
class Program
{
public static List<DateTime>Availability = new List<DateTime>();
static void Main(string[] args)
{
var startingDt = Convert.ToDateTime("04-09-2015 08:00:00");
var endingDt = Convert.ToDateTime("04-09-2015 17:00:00");
CreateAvailabilty(startingDt, endingDt);
AddAvailabilityToDatabase();
}
public static void CreateAvailabilty(DateTime startingDt, DateTime endingDt)
{
var hoursDiff = endingDt.Subtract(startingDt);
for (int i = 0; i < hoursDiff.Hours; i++)
{
Availability.Add(startingDt);
startingDt = startingDt.AddHours(1);
}
}
public static void AddAvailabilityToDatabase()
{
using (var db = new FitnessForAllContext())
{
foreach (var availableDate in Availability.Select(date => new AvailableDate {DateAvailable = date}))
{
db.AvailableDates.Add(availableDate);
db.SaveChanges();
}
}
}
}
When I get to db.AvailableDates.Add(..) I get this error
No connection string named 'MyDBContext' could be found in the application config file.
I was under the impression that because I am using the reference from my MVC application and the connection string is in the ASP.Net MVC config file that I would not have to repeat the connection string in my app.config file for the console application.
So, to summaries,
I have the MVC Project refernece in my console application
This fails because of the lack of a connection string at db.AvailableDates.Add(availableDate);
The mySite.Website assembly is being pulled through into my bin debug folder
If you could offer some insight as to what I need to do without having to continually repeat myself by adding the connection string everywhere I intend on using this, unless I REALLY have to repeat myself

Standard, the connection string needs to be in de config file of the startup project. In this case of the console application. The config of the referenced project is ignored.

You can have a constant or an embedded resource or anything IN your EntityFramework project that contains connection string. But I think, it's not a good practice, every executing project should have it's own configuration.

Related

AppDomain.CurrentDomain.BaseDirectory does not return same folder for UnitTesting project [duplicate]

I have a web project like:
namespace Web
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
lbResult.Text = PathTest.GetBasePath();
}
}
}
The method PathTest.GetBasePath() is defined in another Project like:
namespace TestProject
{
public class PathTest
{
public static string GetBasePath()
{
return AppDomain.CurrentDomain.BaseDirectory;
}
}
}
Why it's display ...\Web\ while the TestProject assembly is compiled into bin folder(in other words it should display ...\Web\bin in my thought).
Now I got a troublesome if I modified method into:
namespace TestProject
{
public class FileReader
{
private const string m_filePath = #"\File.config";
public static string Read()
{
FileStream fs = null;
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + m_filePath,FileMode.Open, FileAccess.Read);
StreamReader reader = new StreamReader(fs);
return reader.ReadToEnd();
}
}
}
The File.config is created in TestProject. Now AppDomain.CurrentDomain.BaseDirectory + m_filePath will returen ..\Web\File.config (actually the file was be copied into ..\Web\bin\File.config), an exception will be thrown.
You could say that I should modified m_filePath to #"\bin\File.config". However If I use this method in a Console app in your suggest, AppDomain.CurrentDomain.BaseDirectory + m_filePath will return ..\Console\bin\Debug\bin\File.config (actually the file was copyed into .\Console\bin\Debug\File.config), an exception will be thrown due to surplus bin.
In other words, in web app, AppDomain.CurrentDomain.BaseDirectory is a different path where file be copyed into (lack of /bin), but in console app it's the same one path.
Any one can help me?
Per MSDN, an App Domain "Represents an application domain, which is an isolated environment where applications execute." When you think about an ASP.Net application the root where the app resides is not the bin folder. It is totally possible, and in some cases reasonable, to have no files in your bin folder, and possibly no bin folder at all. Since AppDomain.CurrentDomain refers to the same object regardless of whether you call the code from code behind or from a dll in the bin folder you will end up with the root path to the web site.
When I've written code designed to run under both asp.net and windows apps usually I create a property that looks something like this:
public static string GetBasePath()
{
if(System.Web.HttpContext.Current == null) return AppDomain.CurrentDomain.BaseDirectory;
else return Path.Combine(AppDomain.CurrentDomain.BaseDirectory,"bin");
}
Another (untested) option would be to use:
public static string GetBasePath()
{
return System.Reflection.Assembly.GetExecutingAssembly().Location;
}
In case you want a solution that works for WinForms and Web Apps:
public string ApplicationPath
{
get
{
if (String.IsNullOrEmpty(AppDomain.CurrentDomain.RelativeSearchPath))
{
//exe folder for WinForms, Consoles, Windows Services
return AppDomain.CurrentDomain.BaseDirectory;
}
else
{
//bin folder for Web Apps
return AppDomain.CurrentDomain.RelativeSearchPath;
}
}
}
The above code snippet is for binaries locations.
The AppDomain.CurrentDomain.BaseDirectory is still a valid path for Web Apps, it's just the root folder where the web.config and Global.asax are, and is same as Server.MapPath(#"~\");
If you use AppDomain.CurrentDomain.SetupInformation.PrivateBinPath instead of BaseDirectory, then you should get the correct path.
When ASP.net builds your site it outputs build assemblies in its special place for them. So getting path in that way is strange.
For asp.net hosted applications you can use:
string path = HttpContext.Current.Server.MapPath("~/App_Data/somedata.xml");

Data Source in connection string - Setup project

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.

Deployable database Test Methods

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
}
}

Why can't I read a db4o file created by a Java app in a C# app?

I have a db4o database that was generate by a Java app and I'm trying to read it using a C# app.
However, when running the following line of code:
IObjectContainer db = Db4oEmbedded.OpenFile(#"..\..\..\Databases\people.db4o");
I get the following error:
Unable to cast object of type
'Db4objects.Db4o.Reflect.Generic.GenericObject' to type
'Db4objects.Db4o.Ext.Db4oDatabase'.
Any ideas? I know there are person objects that contain personId fields (along with others) in the DB. I'm using db4o version 8. I'm not sure what version was used to generate the database.
The entire program is:
using System;
using System.Collections.Generic;
using System.Linq;
using Db4objects.Db4o;
using Db4objects.Db4o.Config;
using MyCompany.Domain;
namespace MyCompany.Anonymizer
{
internal class Program
{
// Private methods.
private static IEmbeddedConfiguration ConfigureAlias()
{
IEmbeddedConfiguration configuration = Db4oEmbedded.NewConfiguration();
configuration.Common.AddAlias(new TypeAlias("com.theircompany.Person", "MyCompany.Domain.Person, MyCompany.Domain"));
configuration.Common.Add(new JavaSupport());
return configuration;
}
private static void Main(string[] args)
{
IObjectContainer db = Db4oEmbedded.OpenFile(#"..\..\..\Databases\people.db4o");
try
{
IList<Person> result = db.Query<Person>();
for (int i = 0; i < result.Count; i++)
{
Person person = result[i];
Console.WriteLine(string.Format("Person ID: {0}", person.personId));
}
}
finally
{
db.Close();
}
}
}
}
The most common scenario in which this exception is thrown is when db4o fails to resolve the type of a stored object.
In your case, db4o is failing to read one of its internal objects which makes me believe you have not passed the configuration to the OpenFile() method (surely, the code you have posted is not calling ConfigureAlias() method);
Keep in mind that as of version 8.0 no further improvement will be done regarding cross platform support (you can read more details here).

C#/.NET Server Path to default/index page

In my attempt to further future-proof a project I am trying to find the best way to retrieve the full path and filename of the index/default page in a web directory using C# and without knowing the web server's list of filename possibilities.
'Server.MapPath("/test/")' gives me 'C:\www\test\'
...so does: 'Server.MapPath(Page.ResolveUrl("/test/"))'
...but I need 'C:\www\test\index.html'.
Does anyone know of an existing method of retrieving the filename that the webserver will serve up when someone browses to that directory - be it default.aspx, or index.html, or whatever?
Thanks for any help,
fodder
ASP.NET has no knowledge of this. You would need to query IIS for the default document list.
The reason for this is that IIS will look in your web folder for the first matching file in the IIS default document list then hand off to the matching ISAPI extension for that file type (by extension) in the script mappings.
To obtain the default document list you can do the following (using the Default Website as an example where the IIS Number = 1):
using System;
using System.DirectoryServices;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
using (DirectoryEntry w3svc =
new DirectoryEntry("IIS://Localhost/W3SVC/1/root"))
{
string[] defaultDocs =
w3svc.Properties["DefaultDoc"].Value.ToString().Split(',');
}
}
}
}
It would then be a case of iterating the defaultDocs array to see which file exists in the folder, the first match is the default document. For example:
// Call me using: string doc = GetDefaultDocument("/");
public string GetDefaultDocument(string serverPath)
{
using (DirectoryEntry w3svc =
new DirectoryEntry("IIS://Localhost/W3SVC/1/root"))
{
string[] defaultDocs =
w3svc.Properties["DefaultDoc"].Value.ToString().Split(',');
string path = Server.MapPath(serverPath);
foreach (string docName in defaultDocs)
{
if(File.Exists(Path.Combine(path, docName)))
{
Console.WriteLine("Default Doc is: " + docName);
return docName;
}
}
// No matching default document found
return null;
}
}
Sadly this won't work if you're in a partial trust ASP.NET environment (for example shared hosting).

Categories

Resources