So I have successfully add a data connection to my VS project and now I'm trying to populate the drop down menu that I created with the data from the tables coming from the database; however, when I run the code it says, "Login failed for use 'Username', on this line:
cmd.Connection.Open();
This is my C# code:
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;
using System.Data.SqlClient;
namespace Test1234
{
public partial class Home : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
PopulateDDList1();
//PopulateDDList2();
//PopulateDDList2_1();
}
public void PopulateDDList1()
{
SqlCommand cmd = new SqlCommand("SELECT * FROM [History]", new SqlConnection(ConfigurationManager.AppSettings["Connection"]));
cmd.Connection.Open();
SqlDataReader ddlValues;
ddlValues = cmd.ExecuteReader();
DropDownList1.DataSource = ddlValues;
DropDownList1.DataValueField = "Serial";
DropDownList1.DataTextField = "Serial";
DropDownList1.DataBind();
cmd.Connection.Close();
cmd.Connection.Dispose();
}//end Populate 1
}
}
This is the web.config code:
<?xml version="1.0"?>
<!--
For more information on how to configure your ASP.NET application, please visit
http://go.microsoft.com/fwlink/?LinkId=169433
-->
<configuration>
<connectionStrings>
<add name="ActioNetITInventoryConnectionString" connectionString="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234"
providerName="System.Data.SqlClient" />
</connectionStrings>
<system.web>
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
</system.web>
<appSettings>
<add key="Connection" value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=***********;Integrated Security=True"/>
</appSettings>
</configuration>
<appSettings>
<add key="Connection" value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=***********;Integrated Security=True"/>
</appSettings>
Your connection string contains both a login & password as well as Integrated Security=True
If you are trying to log on with a named login/password, then either set Integrated Security=False or leave it out altogether
I think there error occures due to your connection string. Is there a reason that you don't use the servername but its IP?
By the way: You defined it twice in two different config sections..
If you're using the IP, then you have to add the port:
Data Source=190.190.200.100,1433;Network Library=DBMSSOCN;
Initial Catalog=myDataBase;User ID=myUsername;Password=myPassword;
Alternatively you could use the standard way:
Server=myServerAddress;Database=myDataBase;User Id=myUsername;Password=myPassword;
Or even better if possible: Use trusted connection:
Server=myServerAddress;Database=myDataBase;
Generally have a look here: http://www.connectionstrings.com/sql-server/
You have several potential failure points, for instance:
Calling ExecuteReader but not actually validating data, ie no Null.
Potentially several Columns being returned, when you only need a Key and Value.
Are you sure Serial is valid Column.
Your connection includes integrated security and a login / password. Use one or the other. (Kritner's answer has good information and direction for this).
To make your code a bit more legible and robust, you could do the following:
public IList<TModel> GetModel<T>(string query) where TModel : new()
{
var container = new List<T>();
using(var connection = new SqlConnection(dbConnection))
using(var command = new SqlCommand(query, connection))
{
connection.Open();
using(var reader = command.ExecuteReader())
while(reader.Read())
{
TModel model = new TModel();
var type = model.GetType();
var table = Enumerable.Range(0, reader.FieldCount).Select(reader.GetName).ToArray();
foreach(var property in type.GetProperties())
foreach(var column in table)
if(String.Compare(property.Name, column, true) == 0)
if(!reader.IsDBNull(reader.GetOrdinal(property.Name)))
property.SetValue(model, reader.GetValue(reader.GetOrdinal(property.Name)), null);
container.Add(model);
}
}
}
The following method will build your model, so you would simply do:
drpExample.DataSource = GetModel<Person>("SELECT * FROM [History]");
drpExample.DataBind();
You really shouldn't have a direct query like that, you should really use Parameters but this should get you started. Also you will need the DataKeyValue and DataKeyText which I often apply to the front-end. You would simply set the value to the correlated Property in your model.
As stated in my comment, you can't provide both login credentials and state integrated security=true - it's one or the other.
Integrated Security basically says "use the current domain credentials I'm logged into the system with."
That being said, you probably want it to look like this:
<add key="Connection"
value="Data Source=10.10.101.188;Initial Catalog=ActioNetITInventory;User ID=rails.sa;Password=ActioNet1234;"/>
Although the "Connection" seems redundant as you already have a connection string with the same information. You can use that like this:
SqlCommand cmd = new SqlCommand(
"SELECT * FROM [History]",
new SqlConnection(
ConfigurationManager.ConnectionStrings["ActioNetITInventoryConnectionString"].ConnectionString)
)
);
Related
I am trying to use a button that will add to my two columns in my database. I have placeholder values in there currently but will eventually be using 2 pop ups to read in those values.
My question is: how do I get the connection string? I don't know what to put there or where to get that data.
private void button_AddPartNumber_Click(object sender, EventArgs e)
{
string cmdString = "INSERT INTO Part_Numbers (Part_Number, Barcode_Number) VALUES (#val1, #val2)";
string connectionString = "I DONT KNOW WHAT TO PUT HERE";
using (SqlCommand connection = new SqlCommand(connectionString))
{
using (SqlCommand comm = new SqlCommand())
{
comm.Connection = connectionString;
comm.CommandText = cmdString;
comm.Parameters.AddWithValue("#val1", "L-0G004-0830-xx"); //placeholder value
comm.Parameters.AddWithValue("#val2", "asdf1234"); // placehold value
}
}
} // end button_AddPartNumber_Click()
Well, what database are you using? For example, SQLServer? Oracle? MySQL?
In SQLServer, at least, the connection string is defined in the web.config, or app.config, and has syntax similar to the following:
<appSettings>
<add key="ConnectionStringName" value="AppName"/>
</appSettings>
<connectionStrings>
<add name="AppName" connectionString="Data Source=DataSourceName; Initial Catalog=DataBaseName; user id=UserID; password=Password" providerName="System.Data.SqlClient"/>
</connectionStrings>
Something like that. There's probably something I'm missing, but without testing it out in your code, I'm blanking on what that might be.
This how you extract the connection string from your code if the connection string is properly set in the web.config:
var connectionString = ConfigurationManager.ConnectionStrings["AppName"].ConnectionString;
I have developed a Window Service using SQL Database currently in my DB is full of Record so query execuction taking much time while default command timeout is 30S but I want to increase it to 120S one option is
com.CommandTimeout = 120;
but I have many methods in my Application so I want to set it from APP.config file so it will be applicable for Application level, can anyone please tell me how could I achive this
Thanks
The easiest way to achieve this is to add a new entry in <appSettings> something like this:
<appSettings>
<add key="commandTimeout" value="3000" />
</appSettings>
Afterwards, create a CommandFactory class that will populate the value
class CommandFactory
{
public static int CommandTimeout
{
get
{
int commandTimeout = 0;
var configValue = ConfigurationManager.AppSettings["commandTimeout"];
if(int.TryParse(configValue, out commandTimeout))
return commandTimeout;
return 120;
}
}
public static SqlCommand CreateCommand(SqlConnection connection)
{
var command = new SqlCommand()
{
Connection = connection,
CommandTimeout = CommandTimeout
};
return command;
}
}
Now, in your code, instead of just instantiating a new SqlCommand just call the CommandFactory method:
using(var command = CommandFactory.CreateCommand(yourConnection))
{
//
}
use this in app.config file
<configuration>
<appSettings>
<add key="connectioStringName" value="Data Source=source;Initial Catalog=tableName;User Id=databaseName;Password=password;Connection Timeout=3000"/>
</appSettings>
</configuration>
I'm a 17 year old software engineering student and am having trouble with linking my sql database to my C# Win App. I was able to accomplish this task using a access database but the database needs to be in SQL. Any Help would be greatly appreciated!
The code i have so far is :
Form1.cs
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb; // all Non-SqlServer Databases ie oracle, access, sqlLite
using System.Configuration;
namespace SqlWinApp
{
public partial class Form1 : Form
{
// Declare and init data objects
// Connect to an external data source
//OleDbConnection cnDataCon =
// new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0; Data Source=H:/SEWD/ASP/dataTestJr/App_Data/dbWaxStax.accdb");
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["cnExternalData"].ConnectionString);
// dataset: Container object for data tables
DataSet dsData = new DataSet();
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender, EventArgs e)
{
try
{
cnDataCon.Open();
{
loadDdlTitles();
}
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered on open: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(#"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(#"<script language='javascript'>alert('Application will terminate')</script>");
return;
}
}
private void loadDdlTitles()
{
//Response.Write(#"<script language='javascript'>alert('loadDDlTitles')</script>");
// store sql into a string in order to be utilized at a later time.
string strSqlTitles = "SELECT * FROM tblTitles ORDER BY title";
// data adapters act as data filters
OleDbDataAdapter daTitles = new OleDbDataAdapter();
// command syncs the data source with the filter (data sdapter) and readies it for instantiation
OleDbCommand cmNameTitles = new OleDbCommand(strSqlTitles, cnDataCon);
// select command syncs the filter with the data
daTitles.SelectCommand = cmNameTitles;
try
{
daTitles.Fill(dsData, "tblTitlesInternal"); // blow pt.
}
catch (Exception errDesc)
{
string strMsgError = "Error encountered in data adapter object: " + errDesc.Message.ToString().Replace('\'', ' ');
MessageBox.Show(#"<script language='javascript'>alert('" + strMsgError + "')</script>");
MessageBox.Show(#"<script language='javascript'>alert('Application will terminate')</script>");
}
// Connect control obj to datasource and populate
ddlTitle.DataSource = dsData.Tables["tblTitlesInternal"];
ddlTitle.DisplayMember = "nameTitle";
ddlTitle.ValueMember = "nameTitlesID";
}
}
}
In my App.config i have:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
</configSections>
<connectionStrings>
<add name="cnExternalData" connectionString="Data Source=|DataDirectory|215-6576.All-Purpose Handyman.dbo; Provider=Microsoft.ACE.OLEDB.12.0" />
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Data Source=215-6576;User ID=sa"
providerName="System.Data.SqlClient" />
</connectionStrings>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
</configuration>
Finally, My database is named 215-6576.All-PurposeHandyman.dbo and the table i am using is named tblTitles. Any help again would be greatly appreciated! Thank you!
An invaluable website I've gone to repeatedly is ConnectionStrings.com.
Assuming everything you already have is correct, you just need to modify your SQL connection string in the config file:
<add name="SqlWinApp.Properties.Settings.ConnectionString" connectionString="Server=215-6576;User ID=sa; Database=All-PurposeHandyman; Password=password"
providerName="System.Data.SqlClient" />
If your sa account has a password, you will need to provide that as well via "Password=[Password]" in that same connectionString attribute.
EDIT
In your C# code, you don't need the braces around your call to loadDdlTitles();, you can safely remove those.
EDIT2
Added password attribute into modified connection string to make clear how it should work.
Well, I see 3 problems just off the bat (and there might be more if I looked more closely). The two that are causing you trouble are:
You're still calling your Access connection string
Your SQL connection string is formatted incorrectly.
The third problem isn't major, but it'll be annoying when you go to fix #1: your connection string name is really long.
Modify your sql connection string thusly:
<add name = "SqlConnection" connectionString="[yourConnectionStringHere]" />
Then modify your calling code:
SqlConnection cnDataCon =
new SqlConnection(ConfigurationManager.ConnectionStrings["SqlConnection"].ConnectionString);
For the specific connection string, I recommend heading to http://connectionstrings.com and taking a look. But it will be something like this:
Server=myServerAddress;Database=myDataBase;User Id=myUsername; Password=myPassword;
You need to have the server/machine name in the connection string. This link has some information and examples to use:
http://msdn.microsoft.com/en-us/library/jj653752%28v=vs.110%29.aspx
I am trying bind a DataGrid for WPF to a table in MS SQL Database.
1) First I created a App.config file as followsrrr
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
<connectionStrings/>
2) Secondly, I added a datagrid to my Form with a name grdEventLog
<Grid>
<DataGrid Name="grdEventLog"/>
</Grid>
3) then I added this code to MainWindow.xaml.cs file as follows:
using System.Data;
using System.Data.SqlClient;
using System.Web;
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
FillDataGrid();
}
private void FillDataGrid()
{
string ConString = ConfigurationManager.ConnectionStrings["ConString"].ConnectionString;
string CmdString = string.Empty;
using (SqlConnection con = new SqlConnection(ConString))
{
CmdString = "SELECT Server,Date,Typ,Msg FROM EventLog";
SqlCommand cmd = new SqlCommand(CmdString, con);
SqlDataAdapter sda = new SqlDataAdapter(cmd);
DataTable dt = new DataTable("EventLog");
sda.Fill(dt);
grdEventLog.ItemsSource = dt.DefaultView;
}
}
After typing all these entries, I have the error at ConfigurationManager stating "The name does not exist in the current context"
I am trying to add reference cfgmgr32.dll to overcome this error. But it is not being accepted. Can anyone suggest to over come this error ?!
Alternative suggestion for approaching databinding in WPF is also welcome.
The problem is not in databinding itself. Seems, there is a typo either in config file, or in key used in ConnectionStrings[]. It would be useful if you post entire error with stacktrace here.
P.S. There is a typo in your config file.
It should be not
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
<connectionStrings/>
but
<connectionStrings>
<add name="ConString" connectionString="Data Source=MYDataSB\SQLExpress;
User Id=sa;Password=gm03C3; Initial Catalog=MYDB;">
</connectionStrings>
See the last line.
I have a list of activity code and full name which is placed in web.config file.
But now they are increased to a large number. So I want to remove that from config file and to create a db and access it with help of configuration application block.
Any ideas would be helpful.
You have to add a App.Config file.
Add the connectionstring to the configuration
<configuration>
<connectionStrings>
<add name="connectionstringname"
connectionString="server=localhost;user id=your_bd_userid;Password=your_db_password;database=your_db_name"
providerName="MySql.Data.MySqlClient" />
</connectionStrings>
</configuration>
Your form code goes here
public void LoadActivityData
{
string cnString = ConfigurationManager.ConnectionStrings["connectionstringname"].ConnectionString;
MySqlConnection myConn = new MySqlConnection(cnString);
DataSet dsActivity = new DataSet();
string selectStr = "SELECT * FROM YourActivityTable";
MySqlDataAdapter adapter = new MySqlDataAdapter(selectStr, myConn);
adapter.Fill(dsActivity, "Activities");
grdView1.DataSource = dsActivity;
}
Use System.Configuration namespace to get the configurationmanager class.