insert into sql query in wpf - ado.net

Hello everyone i am new in wpf. so i have got problems with it. if you help me, i will be so pleased. thanks everyone in advance.
My problem is, can not insert into name inside database in wpf. how can i fix it? my codes as follows;
private void button1_Click(object sender, RoutedEventArgs e)
{
try
{
string SqlString = "Insert Into UserInformation(name) Values (?)";
using (OleDbConnection conn = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=|DataDirectory|Cell.mdb;Persist Security Info=True"))
{
using (OleDbCommand cmd = new OleDbCommand(SqlString, conn))
{
cmd.CommandType = CommandType.Text;
cmd.Parameters.AddWithValue("name", textBox1.Text);
conn.Open();
cmd.ExecuteNonQuery();
}
}
}
catch (Exception ex)
{ }
}

Try to use cmd.Parameters.AddWithValue("#name", textBox1.Text);

Is it opening the right database file? As people have suggested in the comments, set Visual Studio to break on first-chance exceptions, or remove the exception handling. The database file needs to exist, and you need the appropriate JET drivers.
I've tried your code and it works without any problems here (in a WPF application or otherwise). Using named parameters instead of a question mark was a good suggestion, but it doesn't appear to be the problem. (I have Office 2007 and .NET 3.5 SP1 installed, but I doubt that matters).
Are you using a WPF browser application (cbap)? Because you won't be able to access the local file system (and thus the database) if you are. WPF browser applications run with isolated permissions, much like a Silverlight browser application.

The problem here seams to be the parameter. In the command text you don't specify its name, but when you add it, it has a name. Change command text to :
Insert Into UserInformation(name) Values (#name)
In line:
cmd.Parameters.AddWithValue("name", textBox1.Text);
the parameter name should stay without # .

Related

Managing transactions between EntityFramework and EnterpriseLibrary's DatabaseFactory

I'm working with an existing set of code that manages multiple database updates in a single transaction. Here is a simplified example:
Database db = DatabaseFactory.CreateDatabase();
using (DbConnection dbConnection = db.CreateConnection())
{
dbConnection.Open();
DbTransaction dbTransaction = dbConnection.BeginTransaction();
try
{
//do work
dbTransaction.Commit();
}
catch (Exception ex)
{
dbTransaction.Rollback();
}
}
I am also using EntityFramework in this same project for new development. Below is a simplified example of the usage of my repository class:
List<ThingViewModel> things = new List<ThingViewModel>();
// populate list of things
IObjectRepository thingRepository = new ThingRepository();
thingRepository.AddThings(things);
thingRepository.Save();
I want the work done in 'AddThings' to happen as part of the transaction in the first block of code.
Is there some clean way of blending my repository pattern into this existing code or vice-versa? I'm not at the point yet where it is feasible to rewrite the existing code to be entirely within EntityFramework, so I'm looking for some some interim approach.
I have tried passing the transaction from the older code into the repository, and thus EntityFramework, but that does not seem to work. I have also tried passing the ObjectContext back out to the older code in order to enlist it in the transaction. Neither approach works.
I cannot believe that I am the first person to encounter this hurdle in migrating existing code to EntityFramework... there must be something I am not considering.
I'll list the things that I have tried below:
using (TransactionScope transactionScope = new TransactionScope())
{
Database db = DatabaseFactory.CreateDatabase();
using (DbConnection dbConnection = db.CreateConnection())
{
dbConnection.Open();
DbTransaction dbTransaction = dbConnection.BeginTransaction();
try
{
//do work
dbTransaction.Commit();
}
catch (Exception ex)
{
dbTransaction.Rollback();
}
}
Thing thing = new Thing(){
Prop1 = Val1,
Prop2 = Val2
};
ThingObjectContext context = new ThingObjectContext();
context.Things.AddObject(thing);
context.SaveChanges();
transactionScope.Complete();
}
This last example 'works', it does not function as a transaction. When the EF insert fails, the EL commands are not rolled back by the TransactionScope. If I don't put those explicit calls to .Commit() and .SaveChanges(), nothing happens. I would really like for this to share the same connection if possible. Two other variations of this I am currently playing around with is trying to use the same connection between both EF and EL as well as use EnlistTransaction on one side or the other. Definitely trying to keep this from becoming a MSDTC - don't want the extra overhead associated with that.
Use TransactionScope instead of explicit transaction management. You'll simplify the overall code and everything you do should automatically detect and use the same transaction.
Is there any way you can call Database.GetOpenConnection() instead of CreateConnection() in your EL code, and pass in the things.Connection that you create inside of a TransactionScope block? I haven't tested this, but that is what I would try first.

Run a Stored Procedure via a click of a button in .Net web page

Afternoon All,
I have a stored procedure in an SQL 2005 database named GasNominationsRawData_Insert.
When executed this simply extracts some data from another database and inserts the result into a table. This query works fine.
What i need to do is enable this to be executed on the click on a button on my web page. I have had a good luck around the internet have have managed to create the following code in my .net 2008 web page. But i think im either missing something or i have have completly the wrong code. Im new to programming in .Net but i understand that i need to delclare the stored procedure, create the SQL connection, create the command line, open the conection, execute the query and then close the connection.
I dont need or have any parameters. Essentially this button is just used to push data to a table.
Imports System.Data
Imports System.Data.SqlClient
Partial Class RawData
Inherits System.Web.UI.Page
Protected Sub btnAddRawData_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnAddRawData.Click
'Declare Stored Procedure
Dim GasNominationsRawData_Insert As String = "GasNominationsRawData_Insert"
'Declare SQL Connection (This is the connection string located on the web.config page)
Dim SQLConn As SqlConnection
SQLConn = New SqlConnection("GasNominationsDataConnectionString")
'Declare command
Dim SqlComm As SqlCommand = New SqlCommand("GasNominationsRawData_Insert", SQLConn)
SqlComm.CommandType = CommandType.StoredProcedure
Try
'Open SQL Connection
SQLConn.Open()
'Execute Query
SqlComm.ExecuteNonQuery()
'Close connection
SQLConn.Close()
Catch ex As Exception
Throw (ex)
End Try
End Sub
End Class
Any Help is much appreciated.
Regards Betty
Upps. I overlooked that. You're trying to connect to your database with the connectionstring: "GasNominationsDataConnectionString". That's of course no correct connection string.
Your connection string should look somehow like that:
"Data Source=myServerAddress;Initial Catalog=myDataBase;User Id=myUsername;Password=myPassword;"
So you have to get your connection string first out of your web.config like
Dim GasNominationsDataConnectionString As String = ConfigurationManager.ConnectionStrings("GasNominationsDataConnectionString").ConnectionString
Regards
Anja
Looks fine at a first glance. So what happens on clicking the button? Have you assured that your btnAddRawData_Click is called when the button is clicked?

How to read an .XLSX (Excel 2007) file using ADO.NET? I am finding "Could not find installable ISAM"-error

I need to work in .net 2.0. So I can't use OpenXML.
This is my source code and I have already Installed AccessDatabaseEngine.exe.
But still getting the exception:
"Could not find installable ISAM".
I have also tried "Extended Properties=Excel 8.0" in the connection string.
static void Main(string[] args)
{
DataSet dataSet = new DataSet();
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|Data Directory|\HSC.xlsx;Extended Properties=Excel 12.0;HDR=YES;");
OleDbDataAdapter dataAdapter= new OleDbDataAdapter("select * from [Sheet1$]", connection);
dataAdapter.Fill(dataSet);
}
According to Carl Prothman, that should be
Extended Properties="Excel 12.0 Xml;
-- http://www.connectionstrings.com/excel-2007
In more detail:
OleDbConnection connection = new OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\\Docs\\Book2.xlsx;Extended Properties='Excel 12.0 xml;HDR=YES;'");
Note the single quotes.
I prefer to use the Microsoft OpenXML 2.0 SDK for this kind of functionality. It has a really nice interface, and it does not put a demand on having Office installed on the machine reading the XLSX file which is a good thing.
I'm writing this from my mobile, so hard to provide a link, but a Google search should easily find it for you.
Give it a try. I think you will like it.
EDIT
If you have to use .NET 2.0, you can go for using the JET variant of the OleDb instead.
That means you will do something like this to connect:
OleDbConnection connection = new OleDbConnection("Provider=Microsoft.Jet.OLEDB.4.0;" +
"Data Source='" + filename + "';" +
"Extended Properties=\"Excel 8.0;HDR=No;IMEX=1;\"";);
Then you can query it like in your example above:
OleDbDataAdapter objAdapter = new OleDbDataAdapter("select * from [Sheet1$]", connection);
Try it! Just note that Jet have some strange logic of deciding if a column is numeric or not. See the following SO questions for details: Problem with using OleDbDataAdapter to fetch data from a Excel sheet
You should make sure that the connection string looks like the following ( even if you are accessing microsoft excel version 10 ->
MyConnection = new System.Data.OleDb.OleDbConnection(#"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source='D:\csharp-Excel.xls';Extended Properties='Excel 12.0 Xml;HDR=Yes;'");

Is it possible to retrieve connection string inside DDL generation template in VS2010?

I am playing around with creating a T4 template for the "DDL Generation Template option" (model first) process in Visual Studio 2010 RC. Is it possible to retrieve the connection string that is associated with that process? If I right click on the .edmx file and choose "Generate Database from Model..." I have the option of choosing a data connection. That connection string is saved to the app.config (assuming that the option is checked). So I am wondering if it is possible to retrieve that connection string inside the T4 template. I would like to generate different information from the template based on the connection string.
More generally, is it possible to get any context information in this situation? So far, the only thing I have successfully retrieved is the .NET data provider name.
Note - I have studied the ideas provided by Craig but am only getting the name of the IDE (devenv.exe), which quite possibly means I am just doing something wrong.
In case this helps anyone else, here is a snippet I created to read the Entity Framework connection string from inside T4. You pass it the model name (which is also the name of the connection string). It finds and parses just the connection bit I need. It also throws helpful errors when it does not succeed.
To use:
A. Paste this at the top of your template if you aren't already referencing these assemblies:
<## assembly name="EnvDTE" #>
<## assembly name="System.Configuration" #>
B. Paste this ugly (but compact) code at the end of your template:
<#+
string GetEFConnectionString(string modelName)
{
string file = null, key = "provider connection string=\"";
foreach (EnvDTE.ProjectItem item in ((EnvDTE.Project)((Array)((EnvDTE.DTE)((IServiceProvider)this.Host).GetService(typeof(EnvDTE.DTE))).ActiveSolutionProjects).GetValue(0)).ProjectItems)
if (System.Text.RegularExpressions.Regex.IsMatch(item.Name, "(app|web).config", System.Text.RegularExpressions.RegexOptions.IgnoreCase)) {
file = item.get_FileNames(0); break;
}
if (file == null) throw new Exception("config file could not be found");
var config = System.Configuration.ConfigurationManager.OpenMappedExeConfiguration(new System.Configuration.ExeConfigurationFileMap() { ExeConfigFilename = file }, System.Configuration.ConfigurationUserLevel.None);
var cn = config.ConnectionStrings.ConnectionStrings[modelName];
if (cn == null) throw new Exception(modelName + " connection string could not be found");
string s = cn.ConnectionString;
int pos = s.IndexOf(key,StringComparison.OrdinalIgnoreCase);
if (pos<0) throw new Exception("could not find value '" + key + "' inside connection string");
pos += key.Length;
int pos2=s.IndexOf('"',pos);
if (pos2 < 0) throw new Exception("could not find ending \" in connection string");
return s.Substring(pos,pos2-pos);
}
#>
C. Use it like such:
using(var connection = new SqlConnection(GetEFConnectionString("Database"))) {
..
}
I posted my question on one of the MSDN forums and got a response from Lingzhi Sun who pointed me in the direction of a couple of links at skysanders.net. The second of these links has a very nice example of getting to the app/web.config file and, specifically the part I wanted, the connection strings. It doesn't give any information on the specific connection string for the scenario I described in the original question, but this gets me close enough.
Accessing app.config/web.config from T4 template
Accessing app.config/web.config from T4 template - Take 2
Well, the EF connection string will always have the same name as the model, right? The DB connection string will be embedded in the EF connection string. So I'd say you should be able to get it, at least indirectly, via the EF connection string.
Because you're not running in the assembly, have to specify the config file name.
So it would be something like:
var config = ConfigurationManager.OpenExeConfiguration(name);
var cs = config.ConnectoinStrings[modelName];
Note that name, here, is supposed to be an EXE name. But in the IDE, your config fine is going to be called App.config rather than MyApp.dll.config. So you may have to play around with this to get it to work -- try using "App" as the EXE name!
Worst case is open it as a file and then use the config manager.

cannot open user default database. login failed error

I am getting this "cannot open user default database. login failed" error. What I did was using ORM to create DataContext, in the code first call TableExists function to check if the version_tbl existed, if not, then call scripts to exec sql commands to create version_tbl. Then create a new dataContext, but problem is after the call I am getting this error on dataContext entity. If I remove the TableExists call, then dataContext creation is fine or move the dataContext creation before the TableExists call, but then the problem occurs in the TableExists call when it tries to connect. Seems like I can only connect once. Anyway I can call TableExists then able to create dataContext?
Below is my code sample
static bool TableExists(string tableName)
{
using (SqlConnection connection = new SqlConnection("Data Source=localhost\\SQLEXPRESS;Initial Catalog=planning;Integrated Security=True"))
{
string checkTable =
String.Format(
"IF OBJECT_ID('{0}', 'U') IS NOT NULL SELECT 'true' ELSE SELECT 'false'",
tableName);
SqlCommand command = new SqlCommand(checkTable, connection);
command.CommandType = CommandType.Text;
connection.Open();
bool retVal = Convert.ToBoolean(command.ExecuteScalar());
return retVal;
}
}
myFunc ()
{
if (!TableExists ("version_tbl"))
{
// call scripts to create version_tbl
}
DataContext ctx = new DataContext ();
Before everything else did you check if your domain user has the appropriate DB rgihts?
Try to validate the DB connection first.
You should be able to open two connections to the database at the same time: 1 through ADO.NET and 1 through LinqToSql.
The format of your code as displayed by StackOverflow is difficult to read, but it appears that you are returning from your TableExists method before the using statement is able to close the connection. Does it make any difference if you change that?
Are you getting different errors depending on which order you open the connections or is it always the same error?
Don't stop with the Exception. Go to the database and check the message in the log. The exceptions for LOGIN's are not clear on purpose for security reasons, but the log should have a better explanation of what happened.