The full Code can be found here: http://home.htw-berlin.de/~s0531210/eb/DataBaseTest.zip
It is a simple Project with testing Entity Framework.
I have a DLL that allows access to a SQL Server Compact database. This access happens by Enttiy Framework 5.0.
A second project is a console application that accesses this DLL. When calling a class from the DLL to store sample data into the database, the exception is "Error underlying provider Open."
This exception occurs when calling: db.SaveChanges ();
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace DatabaseLibrary
{
public class SLD
{
public SLD()
{
}
public void enterData()
{
using (var db = new SLDDatabaseModelEntitiesContext())
{
for (int i = 0; i < 10; i++)
{
SLDEntity entrysfoo = new SLDEntity();
entrysfoo.Flip = i;
entrysfoo.Slidename = "bla" + i;
db.SLDEntity.Add(entrysfoo);
}
db.SaveChanges(); //DAtanbank speichern
}
}
public SLDEntity getFromDataBase(string wsiname)
{
using (var db = new SLDDatabaseModelEntitiesContext())
{
foreach (var item in db.SLDEntity)
{
if (item.Slidename.Equals(wsiname))
{
return item;
}
}
}
return new SLDEntity();
}
}
}
i hope you guys can help me. I have no clue where the problem is. I searched the internet and i found something about persmission iusses, but the connectionstring is reqiredpermissin=false.
thanks the tip with the connection string worked. The Database was not there where the App.config file from the consoleapp pointed at. but I do not understand why the connection string in the dll, which one also has a App.config File is ignored. If I want, that the connection string is available only in the DLL, Do I have to set the connection string in the DLL manually via a command?
Related
I am trying to access the macros inside of an Access database (accdb).
I tried using:
using Microsoft.Office.Interop.Access.Dao;
...
DBEngine dbe = new DBEngine();
Database ac = dbe.OpenDatabase(fileName);
I found a container["Scripts"] that had a document["Macro1"] which is my target. I am struggling to access the contents of the document. I also question if the Microsoft.Office.Interop.Access.Dao is the best reference for what I am trying to achieve.
What is the best way to view the content of the macros and modules?
You can skip the DAO part, it's not needed in this case. Macros are project specific, so in order to get them all, you would need to loop through your projects. In my example, i just have one project.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.Office.Interop.Access;
namespace Sandbox48
{
public class Program
{
public static void Main(string[] args)
{
Microsoft.Office.Interop.Access.Application oAccess = null;
string savePath = #"C:\macros\";
oAccess = new Microsoft.Office.Interop.Access.Application();
// Open a database in exclusive mode:
oAccess.OpenCurrentDatabase(
#"", //filepath
true //Exclusive
);
var allMacros = oAccess.CurrentProject.AllMacros;
foreach(var macro in allMacros)
{
var fullMacro = (AccessObject)macro;
Console.WriteLine(fullMacro.Name);
oAccess.SaveAsText(AcObjectType.acMacro, fullMacro.FullName, $"{savePath}{ fullMacro.Name}.txt");
}
Console.Read();
}
}
}
I have been using edge.js to call a C# function from within my Node.js app, however when I go to execute the C# code I get for example:
Metadata file 'System.Collections.Generic.dll' could not be found
Metadata file 'System.Text.dll' could not be found
...
My code is this below, basically wanting to run a SSIS package using a stored procedure which I am calling from C#. Basically all my referenced dll's can't be found? Where should I put the dlls for edge to find them?
var executeSQL = edge.func(function() {
/*
#r "System.Data.dll"
#r "System.Collections.Generic.dll"
#r "System.Linq.dll"
#r "System.Text.dll"
using System.Linq;
using System.Text;
using System.Data;
using System.Collections.Generic;
using System.Threading.Tasks;
public class StartUp
{
public async Task<object> Invoke(object input)
{
string result = string.Empty;
string packagePath = #"\SSISDB\test\package.dtsx";
string spName = "storedProcName";
using (var conn = new System.Data.SqlClient.SqlConnection("connectionString"))
using (var command = new System.Data.SqlClient.SqlCommand(spName, conn)
{
CommandType = System.Data.CommandType.StoredProcedure
})
{
conn.Open();
command.Parameters.AddWithValue("#PackagePath", packagePath);
command.ExecuteNonQuery();
Console.WriteLine("Finished");
};
return null;
}
}
*/
});
I know I can do this without C# and just use a module within node like mssql to execute the stored procedure but this was just an example test to get used to using edge.js
The comment from stuartd was correct in the sense to put the dlls under the same directory as the script (which I had tried) but I was still having the same issue. I solved my problem by having my C# code as a separate file and then referenced that file as below as part of the executeSSIS function. payload is just the object that gets passed from my node.js script to my C# script. Doing it this way solved my issue.
var payload = {
filePath: 'C:/temp/xlsx/' + req.file.filename,
path: req.packageName,
server: req.server
};
var executeSSIS = edge.func({
source: __dirname + '/cs/Program.cs',
references: [
__dirname + '/cs/System.Data.dll'
]
});
executeSSIS(payload);
I am trying to insert a new property into the msi file. I am able to update the msi database file using the following code.Is there a way to add new values into a table. I am not able to find any.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using WindowsInstaller;
namespace msiExample
{
[System.Runtime.InteropServices.ComImport(), System.Runtime.InteropServices.Guid("000C1090-0000-0000-C000-000000000046")]
class Installer { }
class msiMain
{
static void Main(string[] args)
{
WindowsInstaller.Installer ins = (WindowsInstaller.Installer)new Installer();
string strFileMsi = #"C:\APP.msi";
System.Console.WriteLine("STARTING SECOND QUERY");
Database db2 = ins.OpenDatabase(strFileMsi, WindowsInstaller.MsiOpenDatabaseMode.msiOpenDatabaseModeDirect);
View vw2 = db2.OpenView(#"Select * FROM Property where Value='Unknown'");
vw2.Execute(null);
Record rcrd2 = vw2.Fetch();
while (rcrd2 != null)
{
System.Console.WriteLine(rcrd2.get_StringData(1));
rcrd2.set_StringData(1,"No data");
vw2.Modify(WindowsInstaller.MsiViewModify.msiViewModifyUpdate, rcrd2);
rcrd2 = vw2.Fetch();
}
db2.Commit();
vw2.Close();
System.Console.WriteLine("completed");
}
}
}
Windows Installer XML (WiX) Deployment Tools Foundation (DTF) libraries help a lot here. The easiest way I know to do it is:
using Microsoft.Deployment.WindowsInstaller.Linq;
using (QDatabase database = new QDatabase(#"C:\data\test.msi", DatabaseOpenMode.Direct))
{
var record = database.Properties.NewRecord();
record.Property = "MyProperty";
record.Value = "MyValue";
record.Insert();
}
If you still want to think SQL then:
using Microsoft.Deployment.WindowsInstaller;
using (Database database = new Database(#"C:\data\test.msi", DatabaseOpenMode.Direct))
{
database.Execute("INSERT INTO `Property` (`Property`, `Value`) VALUES('MyProperty', 'MyValue')");
}
the DTF answer from Christopher Painter is better but with the com objet, based on your code :
WindowsInstaller.View vw2 = db2.OpenView("INSERT INTO Property (Property, Value) VALUES ('property_name', 'property_value')");
vw2.Execute(null);
db2.Commit();
vw2.Closed();
Use ` for name of tables and columns
Use ' for strings values
I have two projects in my solution. The first is an MVC project called EXSIS and the second is a C# Windows Forms Application called Backend. EXSIS contains the database file exsisDB.mdf and was built using the database first method. Now what I want to be able to do is access EXSIS's DbContext (called exsisDBEntities) within Backend in order to add records to my database at a particular time every day. I have added EXSIS as a reference to Backend.
Here is the code for Form1 in Backend:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Data.Entity;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EXSIS.Models;
namespace Backend
{
public partial class Form1 : Form
{
exsisDBEntities db = new exsisDBEntities();
public Form1()
{
InitializeComponent();
}
private void Form1_Load_1(object sender, EventArgs e)
{
System.Threading.TimerCallback callback = new System.Threading.TimerCallback(ProcessTimerEvent);
var dt = new DateTime(DateTime.Now.Year, DateTime.Now.Month, DateTime.Now.Day, 1, 0, 0);
if (DateTime.Now < dt)
{
var timer = new System.Threading.Timer(callback, null, dt - DateTime.Now, TimeSpan.FromHours(24));
}
}
private void ProcessTimerEvent(object obj)
{
LastOrder();
}
private void LastOrder()
{
List<Customer> customers = new List<Customer>();
customers = db.Customers.ToList();
foreach (Customer customer in db.Customers)
{
DateTime LastOrderDate = Convert.ToDateTime(customer.Transactions.Last().Date);
TimeSpan TimeSinceLastOrder = DateTime.Now - LastOrderDate;
if (TimeSinceLastOrder.TotalDays > 30)
{
Notification n = new Notification();
n.NotificationID = db.Notifications.Last().NotificationID + 1;
n.DateGenerated = DateTime.Now;
n.NotificationType = "Last Order";
n.CustID = customer.CustID;
NotificationLink nl = new NotificationLink();
nl.NotificationLinkID = db.NotificationLinks.Last().NotificationLinkID + 1;
nl.NotificationID = n.NotificationID;
nl.RepID = customer.RepID;
db.Notifications.Add(n);
db.NotificationLinks.Add(nl);
}
}
db.SaveChanges();
}
}
}
When I ran this I originally got an error saying:
No connection string named 'exsisDBEntities' could be found in the application config file.
So I went to the web.config file in EXSIS and copied the following connection string across to the app.config file in Backend:
<connectionStrings>
<add name="exsisDBEntities" connectionString="metadata=res://*/Models.EXSISModel.csdl|res://*/Models.EXSISModel.ssdl|res://*/Models.EXSISModel.msl;provider=System.Data.SqlClient;provider connection string="data source=(LocalDB)\v11.0;attachdbfilename=|DataDirectory|\exsisDB.mdf;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" providerName="System.Data.EntityClient" />
</connectionStrings>
But that just gave me a new error. When the following line in the the LastOrder() method runs:
customers = db.Customers.ToList();
I get the error message:
An unhandled exception of type 'System.Data.Entity.Core.EntityException' occurred in EntityFramework.SqlServer.dll
Additional information: The underlying provider failed on Open.
Any help with how to resolve this error would be greatly appreciated.
You're missing the *.edmx file from the other project. The metadata=res://... connection string is a reference to the edmx file and the database. Both are required in a database-first generate context.
However, as #TroyCarlson noted, you're better off moving all this off into a class library that both projects can reference.
I have same problem , but I can't solve it yet but "using" might be useful:
using(exsisDBEntities db = new exsisDBEntities())
{
//your code
}
As a database developer with a very small amount of programming experience, I'm currently attempting to develop a C# .NET console application to import XML files into a SQL Server database. Once the import is done, I need to create a 'Response' file to be passed back to another application.
In doing my own research, I've come across the SQLBULKLOAD class. In fact, I've found some example code online that shows (at least partially) exactly what I'm trying to do:
using System;
using System.IO;
using System.Collections;
using SQLXMLBULKLOADLib;
using System.Data.OleDb;
using System.Diagnostics;
namespace SQLXmlExample
{
class Program
{
[STAThread]
static void Main(string[] args)
{
string schema = "C:\\ImportSample\\MappingFile.xml";
string datafile = "C:\\ImportSample\\DataFile.xml";
string connectionString = #"provider=SQLOLEDB;data source=localhost;database=SqlXmlDemo;Integrated Security=SSPI;";
for (int i = 0; i < args.Length; i++)
{
switch (args[i].ToLower())
{
case "-schema":
schema = args[i + 1];
break;
case "-datafile":
datafile = args[i + 1];
break;
}
}
if (schema == string.Empty || datafile == string.Empty)
{
Console.WriteLine("Missing Schema or Data File. Format: SqlXmlExample -datafile [filename] -schema [filename]");
return;
}
Load(datafile, schema, connectionString);
}
static public void Load(string XMLFilename, string XMLMappingFilename, string ConnectionString)
{
SQLXMLBULKLOADLib.SQLXMLBulkLoad loader = new SQLXMLBULKLOADLib.SQLXMLBulkLoad();
loader.CheckConstraints = true;
loader.XMLFragment = true;
loader.SchemaGen = true;
loader.SGDropTables = false;
loader.Transaction = false;
loader.ConnectionString = ConnectionString;
loader.Execute("C:\\ImportSample\\MappingFile.xml", "C:\\ImportSample\\DataFile.xml");
}
}
}
With the code above, I'm able to import an .XML file into a SQL Server instance. However, my problem is generating the 'Response' .XML file to provide information about the bulk loading operation (i.e. how many records were inserted, if the insert was successful).
As it stands now, I'm thinking that I may be using the wrong class for what I'm trying to accomplish. Am I using the correct class, or should I be using a different one?
If possible, could anyone point me in the direction of some more material to assist me? Any help would be greatly appreciated.
How about using the ErrorLogFile?
This is where the bulk loader stores all its errors and messages, simply try one out, make it fail, see what the format is and then you can then load, parse and generate xml?