The unit test adapter failed to connect to the data source - c#

I'm having an issue with my Datasource for my unit test. I'm wanting to keep the records in XML. As far as I can tell this is supported but I keep getting this error "The unit test adapter failed to connect to the data source...".
I have set up my app.config as follows:
<configuration>
<configSections>
<section name="microsoft.visualstudio.testtools" type="Microsoft.VisualStudio.TestTools.UnitTesting.TestConfigurationSection, Microsoft.VisualStudio.QualityTools.UnitTestFramework, Version=10.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a"/>
</configSections>
<connectionStrings>
<add name="PersonTestData" connectionString="Dsn=XML Files;dbq=PersonTestData.xml;defaultdir=.\; driverid=790;maxbuffersize=2048;pagetimeout=5" providerName="System.Data.Odbc" />
</connectionStrings>
<microsoft.visualstudio.testtools>
<dataSources>
<add name="PersonTestData" connectionString="PersonTestData" dataTableName="PersonData" dataAccessMethod="Sequential"/>
</dataSources>
</microsoft.visualstudio.testtools>
</configuration>
The Code that I'm using is this:
[TestMethod()]
[DeploymentItem("PersonTestData.xml")]
[DataSource("PersonTestData")]
public void CompareToTest()
{
Person Test = (Person)TestContext.DataRow["Person"];
Int32 result = Main.CompareTo(Test);
Assert.IsNotNull(result);
}
And Finally the XML file It's self:
<?xml version="1.0" encoding="utf-8" ?>
<PersonData xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xsd="http://www.w3.org/2001/XMLSchema">
<Person>
<LastName>Jones</LastName>
<FirstName>Bill</FirstName>
<Age>24</Age>
</Person>
<Person>
<LastName>West</LastName>
<FirstName>John</FirstName>
<Age>24</Age>
</Person>
<Person>
<LastName>Jones</LastName>
<FirstName>Bill</FirstName>
<Age>24</Age>
</Person>
</PersonData>
Not sure where I'm going wrong at this point.

I think you don't need an ODBC connection string to read the xml file. Simply use the DataSource attribute as below. Also "PersonTestData.xml" properties. CopyToOutputDirectory set to "CopyAlways".
[TestClass]
public class UnitTest1
{
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
[TestMethod]
[DeploymentItem("PersonTestData.xml")]
[DataSource("Microsoft.VisualStudio.TestTools.DataSource.XML",
"|DataDirectory|\\PersonTestData.xml",
"Person",
DataAccessMethod.Sequential)]
public void CompareToTest()
{
var row = TestContext.DataRow;
var firstName = row["FirstName"].ToString();
var lastName = row["LastName"].ToString();
//Asserts...
}
}

Related

Changing a path for logger using Form application and implementing it to Service with C#

I am working on a File Watcher service which has a form application in it too (2 different projects in same solution). So I am getting a path for where to save the log with Forms application. Then I put that in my app.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="location" value="C:\Users\user\Documents" />
<add key="logLocation" value="C:\Users\user\Documents" /> <!-- this is where it changes save it-->
</appSettings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.7.2" />
</startup>
</configuration>
And I have a Variables class where I define my variable.
using System.Configuration;
namespace FileWatchingService
{
public static class Variables
{
public static string FilePath { get; set; } = ConfigurationManager.AppSettings.Get("location");
public static string LogPath { get; set; } = ConfigurationManager.AppSettings.Get("logLocation");
}
}
Then I am trying put my LogPath in here:
using System;
using System.IO;
namespace FileWatchingService
{
public static class Logger
{
public static void Log(string message)
{
try
{
string _message = String.Format("{0} {1}", message, Environment.NewLine);
//File.AppendAllText(AppDomain.CurrentDomain.BaseDirectory + "logFile.log", _message);
File.AppendAllText(Variables.LogPath + "logFile.log", _message);
}
catch (Exception ex)
{
//Implement logging on next version
}
}
}
}
Problem is that my way does not work. What can I do to change my log files path?
Looking solely at the code, it seems you're missing a \ at the end of the LogPath value.
You could also do File.AppendAllText(Variables.LogPath + "\logFile.log", _message); or just define the LogPath itself, such as:
<appSettings>
<add key="location" value="C:\Users\user\Documents" />
<add key="logLocation" value="C:\Users\user\Documents\log.txt" /> <!-- the file itself -->
</appSettings>
Nevertheless, I would advise to just use a library for logging, instead of developing your own. Go with NLog or Serilog

Configuring instances in Unity Container configured in App.Config at runtime

I have a speciifc configuration problem.
<configuration>
<configSections>
<section name="custom" type="ConfigurationSample.CustomConfigurationSection, ConfigurationSample"/>
<section name="unity" type="Microsoft.Practices.Unity.Configuration.UnityConfigurationSection, Microsoft.Practices.Unity.Configuration"/>
</configSections>
<custom>
<customConfigurations>
<configuration id="CAT1">
<name>Tom</name>
<address type="rent">
<area>Misissipi</area>
</address>
<conifugration/>
<configuration id="Mouse1">
<name>Jerry</name>
<address type="own">
<area>Seatle</area>
</address>
<conifugration/>
<customConfigurations>
</custom>
<unity xmlns="http://schemas.microsoft.com/practices/2010/unity">
<alias alias="IAnimal" type="MyApp.IAnimal, MyApp" />
<alias alias="CAT" type="MyApp.CAT, MyApp" />
<alias alias="Mouse" type="MyApp.Mouse, MyApp" />
<container>
<!-- should register CAT instance with name CAT1 at runtime and mapto IAnimal !-->
<!-- should register Mouse with name Mouse1 at runtime and mapto IAnimal !-->
</container>
</unity>
</configuration>
This is my app.config. All I am looking for runtime registering instances in unity container while reading the custom config section since CAT class CAT configuration in its constructor.
My classes:
public interface IAnimal
{
public string Name {get;set}
pubic bool IsLiving();
}
public class Mouse
{
MouseConfig config;
public Mouse(IAnimalConfig config)
{
this.config=config;
}
public string Name {get;set}
pubic bool IsLiving(){
//do something with config
}
}
public class Cat
{
CATConfig config;
public CAT(IAnimalConfig config)
{
this.config=config;
}
public string Name {get;set}
pubic bool IsLiving(){
//do something with config
}
}
I hope you understand where i am leading to. I need to provide config objects as parameter to the derived classes. So based on my customconfig i want to register instances in unity container. So i can work with those instances in my application. since i already know their types and name of those instances i can resolve from container.
Please let me know if i have to add anything more. Thanks

An unhandled exception of type 'System.IO.FileNotFoundException' - Dll & remoting

I'm trying to make a game of Nim where the logic takes place on a server and a client presents the game to get better at .NET Remoting.
I have a dll I built from this class library:
namespace Nim_Common
{
public interface computerCommon
{
int[] startGame(int columnNumber);
int[] computeTurn(int[] penStatus);
bool checkWin();
}
}
That dll I add as a reference to my client project and my server project, and add the dll to the bin/Debug directory in each project.
This is the relevant part of my client code:
using Nim_Common;
namespace Nim
{
public partial class Form1 : Form
{
private computerCommon computerServerHandler;
...
public Form1()
{
InitializeComponent();
computerToolStripMenuItem.Select();
newColumnNumber = -1;
RemotingConfiguration.Configure("client.exe.config");
computerServerHandler = (computerCommon)Activator.GetObject(typeof(computerCommon), "http://localhost:1234/_Server_");
StartGame(this, null);
}
private void StartGame(object sender, EventArgs e)
{
int max = 0;
if(columns != null)
for (int i = 0; i < columns.Length; i++) Controls.Remove(columns[i]);
int[] temp = computerServerHandler.startGame(newColumnNumber);
columns = new Column[temp.Length];
...
}
And in the server part:
using Nim_Common;
namespace Nim_Server
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
RemotingConfiguration.Configure("server.exe.config");
}
}
class ServerPart : MarshalByRefObject, computerCommon
{
...
public ServerPart()
{
...
}
public int[] startGame(int columnNumber)
{
...
}
public int[] computeTurn(int[] penStatus)
{
...
}
public bool checkWin()
{
...
}
}
}
server.exe.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.runtime.remoting>
<application>
<channels>
<channel ref="http server" port="1234" />
</channels>
<service>
<wellknown mode ="SingleCall" type="Nim_Server.ServerPart, Nim_Server" objectUri="_Server_" />
</service>
</application>
</system.runtime.remoting>
</configuration>
client.exe.config:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<system.runtime.remoting>
<application>
<channels>
<channel ref="http client" />
</channels>
<client>
<wellknown type="Nim_Common.computerCommon, Nim_Common" url="http://localhost:1234" />
</client>
</application>
</system.runtime.remoting>
</configuration>
My firewall is off if that matters.
Everything is fine in compile time, the server runs fine. When the client reaches this line, it throws the exception:
int[] temp = computerServerHandler.startGame(newColumnNumber);
The exception is something like:
An unhandled exception of type 'System.IO.FileNotFoundException' occurred in mscorlib.dll
Additional information: Could not load file or one of its dependencies, the system could not find "Nim_Common". // This is shown in my native language so I'm improvising a bit with the translation.
What is going on and how do I fix this?
Thanks.
I was receiving this error from one of my own compiled dlls. It turns out I had filled in the AssemblyCultureAttribute in my AssemblyInfo.cs file. The project built without issue but would not load in any referenced projects when used.
According to msdn :
Putting this attribute on an assembly and using something other than the empty string ("") for the culture name will make this assembly look like a satellite assembly, rather than a main assembly that contains executable code. Labeling a traditional code library with this attribute will break it, because no other code will be able to find the library's entry points at runtime.

unable to add data to SQL database using entity framework in windows service

I wrote a windows service for a project in which I needed to store some data in a database. I created the table with the required columns and created an entity model from the database. Context and mapping are done automatically by VS 2012. In order to test if the data is being saved, I hard coded some values and ran the service but the data doesn't get saved in the database.
Here is a sample service I wrote to test this out:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Diagnostics;
using System.Linq;
using System.ServiceProcess;
using System.Text;
using System.Threading.Tasks;
namespace serviceWithDatabase
{
public partial class testService : ServiceBase
{
Database1Entities db = new Database1Entities();
public testService()
{
InitializeComponent();
test();
}
protected override void OnStart(string[] args)
{
}
public void test()
{
Table t = new Table();
t.ticker = "goog";
t.Day1 = 1234;
t.Day2 = 4567;
t.Day3 = 7890.56;
db.Tables.Add(t);
db.SaveChanges();
}
protected override void OnStop()
{
}
}
}
model for the table:
namespace serviceWithDatabase
{
using System;
using System.Collections.Generic;
public partial class Table
{
public int Id { get; set; }
public string ticker { get; set; }
public Nullable<double> Day1 { get; set; }
public Nullable<double> Day2 { get; set; }
public Nullable<double> Day3 { get; set; }
}
}
App.config code:
<?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=5.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="Database1Entities" connectionString="metadata=res://*/Model1.csdl|res://*/Model1.ssdl|res://*/Model1.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\Database1.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
<parameters>
<parameter value="v11.0" />
</parameters>
</defaultConnectionFactory>
</entityFramework>
</configuration>
I can manually go into the database via VS 2012 and add data but it won't save data via the windows service. Anyone have any suggestions ?
the database was stored within the project and VS was updating the wrong database. When you place the database outside of the project folder (e.g. on your desktop) it works perfectly fine. This issue cost me a weekend lol. Hope it helps others :)
Try deleting the App.config and passing in your connection string directly some other way.
The App.config seemed to prevent compilation for me.

How do I resolve NHibernate.MappingException

I have a database, hbm mapping file and the App.config located in a class library. Now from a test project I reference that library and attempt to call a HibernateHelper class I create, at runtime the following error is thrown :
NHibernate.MappingException : Could not compile the mapping document: HibernateExample.Mappings.Products.hbm.xml
Please keep in mind that this is a class library that is being reference from a Test project.
If I change it output type to console application, it runs fine. But when I change it back to class library and reference it from my Test Project it throws the above mention error.
I tried adding config.Configure() but that throws a NhibernateDuplicateMapping exception.
FIXED:
Fixed the duplication mapping issue by removing from appconfig. and fixed the problem mapping entity by placing a hibernate.cfg.xml file in my Test project as well.
public sealed class NHibernateHelper
{
private static ISessionFactory _sessionFactory;
const string Connectionstring = "servicestring";
public static void OpenSession()
{
var config = new Configuration();
config.Configure();
config.AddAssembly(Assembly.GetCallingAssembly());
_sessionFactory = config.BuildSessionFactory();
}
public static ISession GetCurrentSession()
{
ISession session = null;
if (_sessionFactory == null)
OpenSession();
if (_sessionFactory != null)
{
session = _sessionFactory.OpenSession();
}
return session;
}
public static void CloseSessionFactory()
{
if (_sessionFactory != null)
{
_sessionFactory.Close();
}
}
// var dsn = ConfigurationManager.ConnectionStrings[Connectionstring].ConnectionString;
//config.SessionFactory().Integrate.Using<MsSqlCeDialect>().Connected.ByAppConfing(dsn);
// System.Diagnostics.Debug.WriteLine("My connection string: "+dsn);
//Get NHibernate configuration
//_sessionFactory = config.BuildSessionFactory();
//config.AddAssembly("HibernateExample");
}
Any ideas?
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="hibernate-configuration" type="NHibernate.Cfg.ConfigurationSectionHandler, NHibernate" />
</configSections>
<hibernate-configuration xmlns="urn:nhibernate-configuration-2.2" >
<session-factory>
<property name="connection.driver_class"> NHibernate.Driver.SqlServerCeDriver</property>
<property name="dialect">NHibernate.Dialect.MsSqlCeDialect</property>
<property name="connection.connection_string">Data Source=FirstSample.sdf;</property>
<property name="show_sql">true</property>
<mapping assembly="HibernateExample"/>
</session-factory>
</hibernate-configuration>
<connectionStrings>
<add name="testconnectionstring"
connectionString="Data Source=|DataDirectory|\FirstSample.sdf;Integrated Security=True"
providerName="Microsoft.SqlServerCe.Client.3.5" />
</connectionStrings>
<runtime>
<assemblyBinding xmlns="urnchemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="System.Data.SqlServerCe" publicKeyToken="89845DCD8080CC91" culture="neutral"/>
<bindingRedirect oldVersion="0.0.0.0-9.0.242.0" newVersion="3.5.0.0"/>
</dependentAssembly>
</assemblyBinding>
</runtime>
</configuration>
<?xml version="1.0" encoding="utf-8" ?>
<hibernate-mapping xmlns="urn:nhibernate-mapping-2.2" assembly="HibernateExample" namespace="HibernateExample.Domain" >
<class name="Product" table="Products">
<id name="Id" type="integer">
<generator class="identity"/>
</id>
<property name="Name" type="string"/>
<property name="Category" type="string"/>
<property name="Discontinued" />
</class>
</hibernate-mapping>
Exception Thrown:
Test 'NunitTest.TestClass.canquerydb' failed: NHibernate.MappingException : Could not compile the mapping document: HibernateExample.Mappings.Products.hbm.xml
----> System.InvalidOperationException : Could not find the dialect in the configuration
at NHibernate.Cfg.Configuration.LogAndThrow(Exception exception)
at NHibernate.Cfg.Configuration.AddDeserializedMapping(HbmMapping mappingDocument, String documentFileName)
at NHibernate.Cfg.Configuration.ProcessMappingsQueue()
at NHibernate.Cfg.Configuration.AddInputStream(Stream xmlInputStream, String name)
at NHibernate.Cfg.Configuration.AddResource(String path, Assembly assembly)
at NHibernate.Cfg.Configuration.AddAssembly(Assembly assembly)
at NHibernate.Cfg.Configuration.AddAssembly(String assemblyName)
NHibernateTest\NHibernateHelper.cs(21,0): at HibernateExample.NHibernateTest.NHibernateHelper.openSession()
NHibernateTest\NHibernateHelper.cs(28,0): at HibernateExample.NHibernateTest.NHibernateHelper.GetCurrentSession()
TestClass.cs(21,0): at NunitTest.TestClass.canquerydb()
--InvalidOperationException
at NHibernate.Dialect.Dialect.GetDialect(IDictionary`2 props)
at NHibernate.Cfg.Configuration.AddDeserializedMapping(HbmMapping mappingDocument, String documentFileName)
From the error, it appears that you are not configuring the Dialect before adding the mapping. This is required.
Here's a simple piece of basic configuration code:
var configuration = new Configuration();
configuration.SessionFactory().Integrate.Using<MsSql2012Dialect>()
.Connected.ByAppConfing("connName");//sic
//now you can add the mappings

Categories