The UserId, Password or Account is invalid Teradata .Net Connection - c#

The below code throws an error
The UserId, Password or Account is invalid.
on the code line adapter.Fill(ds);
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Teradata.Client.Provider;
using System.Data;
using System.Diagnostics;
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URL";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("EXEC MACRO", cn);
TdDataReader reader = cmd.ExecuteReader();
TdDataAdapter adapter = new TdDataAdapter(cmd.CommandText, cn.ConnectionString);
DataSet ds = new DataSet();
adapter.Fill(ds);
// myLabel.Text= ds.Tables[0].Rows[0]["event_id"].ToString();
cmd.Dispose();
cn.Close();
}
}
However, the below code works perfectly fine and returns value as expected.
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "URL";
connectionStringBuilder.Database = "DB";
connectionStringBuilder.UserId = "USERNAME";
connectionStringBuilder.Password = "PASSWORD";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
TdConnection cn = new TdConnection();
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
TdCommand cmd = new TdCommand("Show table DB.TABLE1", cn);
String customers = (String)cmd.ExecuteScalar();
MeanTime.Text = customers;
cmd.Dispose();
cn.Close();
The user ID, Password, Datasource etc are all same yet it fails on 1st code but runs properly on 2nd.

When calling procs and macros you can use the TDCommand.ExecuteNonQuery.
UPDATE: Upon further reading here it looks like you can include the CALL when using the Stored Procedure commandtype. The proper Commandtype for a Macro execution is System.Data.CommandType.Text and you probably need the EXEC
For reference, with parameter binding and a procedure, here's a working example below. Some small tweaks would need to be made (as mentioned above) for a macro execution.
//create a new td connection
TdConnection cn = new TdConnection();
//Build the connection string
TdConnectionStringBuilder connectionStringBuilder = new TdConnectionStringBuilder();
connectionStringBuilder.DataSource = "serveraddress";
connectionStringBuilder.Database = "defaultdatabase";
connectionStringBuilder.UserId = "username";
connectionStringBuilder.Password = "password";
connectionStringBuilder.AuthenticationMechanism = "LDAP";
connectionStringBuilder.CommandTimeout = 120;
//Open the connection
cn.ConnectionString = connectionStringBuilder.ConnectionString;
cn.Open();
// Initialize TdCommand from the tdconnection
TdCommand cmd = cn.CreateCommand();
//CommandText is set to Stored Procedure name, in this case,
//.NET Data Provider will generate the CALL statement.
cmd.CommandText = "yourdatabasename.yourprocname";
cmd.CommandType = CommandType.StoredProcedure;
// Create Input Parameter required by this procedure
TdParameter InParm1 = cmd.CreateParameter();
InParm1.Direction = ParameterDirection.Input;
InParm1.DbType = DbType.String;
InParm1.Size = 20;
InParm1.Value = "yourparamvalue";
//and bind it
cmd.Parameters.Add(InParm1);
//------------OPTION 1 CATCHING AN OUTPUT PARAMETER---------------------
//If you are catching an output parameter from a proc then create here:
// Create Output Parameter.
TdParameter OutParm = cmd.CreateParameter();
OutParm.Direction = ParameterDirection.Output;
OutParm.ParameterName = "myOutputParam";
OutParm.DbType = DbType.String;
OutParm.Size = 200;
cmd.Parameters.Add(OutParm);
// Run it up
cmd.ExecuteReader()
//if this is returning a single value you can grab it now:
myOutput = OutParm.Value.ToString();
//------------OPTION 2 CATCHING A RECORDSET-----------------------------
//list based on class set in seperate model
List<myClass> l_myclass = new List<myClass>();
//run it up and catch into a TDDataRead
using (TdDataReader r = cmd.ExecuteReader())
{
if (r.HasRows)
{
//Loop the result set and catch the values in the list
while (r.Read())
{
//"myclass" class defined in a seperate model
//Obviously you could do whatever you want here, but
//creating a list on a class where the column1-column4 is defined makes short work of this.
//Then you can dump the whole l_myclass as json back to the client if you want.
myClass i = new myClass();
i.column1 = (!r.IsDBNull(0)) ? r.GetString(0) : string.Empty;
i.column2 = (!r.IsDBNull(1)) ? r.GetString(1) : string.Empty;
i.column3 = (!r.IsDBNull(2)) ? r.GetString(2) : string.Empty;
i.column4 = (!r.IsDBNull(3)) ? r.GetString(3) : string.Empty;
l_myClass.Add(i);
}
}
}
//Dump the list out as json (for example)
return Json(l_myClass, System.Web.Mvc.JsonRequestBehavior.AllowGet);
I've only, personally, used this on procedures, but the documentation I've read suggests that this is the correct route for macros as well.

Related

Why showing error in Context.Response.Write()

I'm new in ASP.Net development, and facing problem in sending data from webService to webform. I'm using JSON method,but in following line of code I'm having issue. The compiler shows this error message.
"Error 3 Invalid token '(' in class, struct, or interface member
declaration
Can someone tell me what is the problem?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Script.Serialization;
using System.Configuration;
using System.Data.SqlClient;
using System.Data;
using System.Runtime.Remoting.Contexts;
using System.Runtime.Remoting;
/// <summary>
/// Summary description for GetStudent
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
[System.Web.Script.Services.ScriptService]
public class GetStudent : System.Web.Services.WebService {
[WebMethod]
public GetStudent () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
StudentsList.Add(student);
}
JavaScriptSerializer js = new JavaScriptSerializer(StudentsList());
Context.Response.Write(js.Serializ(StudentsList));
}
}
Here is how you need to fix your GetStudent method -
[WebMethod]
public void GetStudent () {
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\\v11.0;AttachDbFilename='C:\\Users\\Abdul Basit Mehmood\\Documents\\Visual Studio 2012\\WebSites\\WebSite1\\App_Data\\Database.mdf';Integrated Security= True");
List<StudentsList> stu = new List<StudentsList>();
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * From Student";
SqlDataReader DR = cmd.ExecuteReader();
while (DR.Read())
{
StudentsList student = new StudentsList();
student.Id = Convert.ToInt32(DR["Id"]);
student.name = DR["name"].ToString();
student.fname = DR["fname"].ToString();
student.email = DR["email"].ToString();
student.contact = DR["contact"].ToString();
student.Pname = DR["Pname"].ToString();
student.Cname = DR["Cname"].ToString();
stu.Add(student); //Changed line: Changed variable name to stu which is the list variable declared earlier.
}
JavaScriptSerializer js = new JavaScriptSerializer(); //changed line : Removed the invalid parameter to the constructor of JavaScriptSerializer class
Context.Response.Write(js.Serializ(stu)); //changed line : Used the correct stu list variable declared at the starting of the method.
}
Note: Please follow extreme caution while naming your class. Your StudentList entity isn't a list but an individual student entity with various properties like Id,name,fname etc. Please consider renaming it to Student.
In order to validate that you aren't getting any invalid characters from your database first try running if below code works fine or not?
class Program
{
static void Main(string[] args)
{
List<StudentsList> stu = new List<StudentsList>();
StudentsList student = new StudentsList();
student.name = "Abdul Basit Mehmood";
student.fname = "Abdul";
stu.Add(student);
JavaScriptSerializer js = new JavaScriptSerializer();
var serializedValue = js.Serialize(stu);
}
}
class StudentsList
{
public string name;
public string fname;
}
serializedValue variable should show you a valid JSON string in quick watch window as shown below:

How can I return a stored procedure's result as XML?

I coded a web service connecting to MS-Sql server and getting the results from a stored procedure. My below code is getting only the first result of procedure, but I need all results in the response xml file. I think that I need to use data adapter, data reader, data fill, etc.. something like this. But I could not succeed. I would appreciate any help:
PS: Info.cs class already created.
[WebMethod]
public Info NumberSearch2(string no)
{
Info ourInfo = new Info();
string cs = ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (SqlConnection Con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = CommandType.StoredProcedure
};
SqlParameter parameter = new SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
}
}
return ourInfo;
}
After #David 's recommendation:
[WebMethod]
//public Info NumberSearch2(string no)
public List<Info> NumberSearch2(string no)
{
Info ourInfo = new Info();
var ourInfos = new List<Info>();
string cs = System.Configuration.ConfigurationManager.ConnectionStrings["DBBaglan"].ConnectionString;
using (System.Data.SqlClient.SqlConnection Con = new System.Data.SqlClient.SqlConnection(cs))
{
System.Data.SqlClient.SqlCommand cmd = new System.Data.SqlClient.SqlCommand(cmdText: "NumberSearch", connection: Con)
{
CommandType = System.Data.CommandType.StoredProcedure
};
System.Data.SqlClient.SqlParameter parameter = new System.Data.SqlClient.SqlParameter
{
ParameterName = "#no",
Value = no
};
cmd.Parameters.Add(parameter);
Con.Open();
System.Data.SqlClient.SqlDataReader dr = cmd.ExecuteReader();
DataSet ds = new DataSet();
while (dr.Read())
{
var ourInfos = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
}
return ourInfos;
}
You're returning a single Info object. If you want a collection of them, return a List<Info> instead. Change the method signature:
public List<Info> NumberSearch2(string no)
Declare the object to return:
var ourInfos = new List<Info>();
Within your loop, add each record to the list:
while (dr.Read())
{
var ourInfo = new Info();
ourInfo.PartNo = dr["PartNo"].ToString();
ourInfo.BrandNo = dr["BrandNo"].ToString();
ourInfo.Manufacturer = dr["Manufacturer"].ToString();
ourInfo.Country = dr["Country"].ToString();
ourInfo.ReferenceNo = dr["ReferenceNo"].ToString();
ourInfos.Add(ourInfo);
}
And return the list:
return ourInfos;

Proper way of closing Oracle table update - C# . NET

I follow below steps to update an oracle table:
First calculate observable collection; property indicating a column. Display this information in a WPF datagrid. I save this information to the Oracle database. This seems to work fine.
While the grid is open, I change the some cell values. I re-saved the modified values to the table. This also works fine.
I try to get updated/modified values to perform some other calculation. I noticed that my program still used the initially saved values; it didnt pick modified values even though database shows correct values. Does is happen because I am not committing / closing the Oracle connection properly?
Here is my code to save the data into Oracle table:
using (OracleConnection thisConnection = new OracleConnection(connectionname))
{
string query = "INSERT INTO TEST(WellBore,PDate, Pressure,Temperature)VALUES(:WellBore,:PDate,:Pressure,:Temperature)";
OracleCommand myAccessCommand = new OracleCommand(query, thisConnection);
var sdate = Datetime.Now.Date.ToShortDateString();
myAccessCommand.Parameters.Add("WellBore", OracleDbType.NVarchar2, 20).Value = “ABC”;
myAccessCommand.Parameters.Add("PDate", DateTime.Parse(sdate));
myAccessCommand.Parameters.Add("Pressure", OracleDbType.Decimal).Value = 1000;
myAccessCommand.Parameters.Add("Temperature ", OracleDbType.Decimal).Value = 50;
thisConnection.Open();
myAccessCommand.ExecuteNonQuery();
thisConnection.Dispose();
}
So I believe my question how do I commit the connection?
Here's an example using an insert statement with a transaction. It also grabs a returned id value, which may not be needed in your case, but anyway:
int event_id = 0;
using (OracleConnection oraConn = new OracleConnection(connStr))
{
string cmdText = #"insert into EVENT
(EVENT_NAME, EVENT_DESC)
values
(:EVENT_NAME, :EVENT_DESC)
RETURNING EVENT_ID INTO :EVENT_ID
";
using (OracleCommand cmd = new OracleCommand(cmdText, oraConn))
{
oraConn.Open();
OracleTransaction trans = oraConn.BeginTransaction();
try
{
OracleParameter prm = new OracleParameter();
cmd.BindByName = true;
prm = new OracleParameter("EVENT_NAME", OracleDbType.Varchar2); prm.Value = "SOME NAME"; cmd.Parameters.Add(prm);
prm = new OracleParameter("EVENT_DESC", OracleDbType.Varchar2); prm.Value = "SOME DESC"; cmd.Parameters.Add(prm);
prm = new OracleParameter("EVENT_ID", OracleDbType.Int32, ParameterDirection.ReturnValue); cmd.Parameters.Add(prm);
cmd.ExecuteNonQuery();
trans.Commit();
// return value
event_id = ConvertFromDB<int>(cmd.Parameters["EVENT_ID"].Value);
}
catch
{
trans.Rollback();
throw;
}
finally
{
trans.Dispose();
}
oraConn.Close();
}
}
Note: The "ConvertFromDB" is just a generic to cast the return value to its .NET equivalent (an int in this case). Again, if you aren't capturing a returned value, you don't need to worry about it.

c# Must declare the scalar variable "#Kundenname"

I am trying to get a little tool to work, for our little company.
This should fill data from a DataGridView into a SQL Server Standard database.
Reading out the SQL table is working fine, but I can't get the tool to write the values.
I get the error mentioned in the title.
Here the code:
var kdNummer = new SqlParameter("Kundennummer", SqlDbType.Int);
var kdName = new SqlParameter("Kundenname", SqlDbType.VarChar);
var kdMail = new SqlParameter("Kundenmail", SqlDbType.VarChar);
var kdTele = new SqlParameter("Telefon", SqlDbType.VarChar);
string kdquery = "INSERT INTO Kunden VALUES (#Kundennummer, #Kundenname, #Kundenmail, #Telefon)";
using (SqlConnection updatedb = new SqlConnection("Data Source=;Initial Catalog=updatedb;User ID=;Password="))
{
updatedb.Open();
for (int i = 0;i<dataGridView1.Rows.Count;i++)
{
using(SqlCommand NrDaten = new SqlCommand(kdquery, updatedb))
{
kdNummer.Value = dataGridView1.Rows[i].Cells["Kundennummer"].Value;
NrDaten.Parameters.Add(kdNummer);
NrDaten.ExecuteNonQuery();
}
using (SqlCommand NameDaten = new SqlCommand(kdquery, updatedb))
{
kdName.Value = dataGridView1.Rows[i].Cells["Kundenname"].Value;
NameDaten.Parameters.Add(kdName);
NameDaten.ExecuteNonQuery();
}
using (SqlCommand MailDaten = new SqlCommand(kdquery, updatedb))
{
kdMail.Value = dataGridView1.Rows[i].Cells["Kundenmail"].Value;
MailDaten.Parameters.Add(kdMail);
MailDaten.ExecuteNonQuery();
}
using (SqlCommand TeleDaten = new SqlCommand(kdquery, updatedb))
{
kdTele.Value = dataGridView1.Rows[i].Cells["Telefon"].Value;
TeleDaten.Parameters.Add(kdTele);
TeleDaten.ExecuteNonQuery();
}
}
updatedb.Close();
}
Your query requires 4 parameters, but you're always only setting one (also please note that in the SqlParameter you need to have the # sign as well). Thus you get an error about missing parameters. Your code should probably look like this:
var kdNummer = new SqlParameter("#Kundennummer", SqlDbType.Int);
var kdName = new SqlParameter("#Kundenname", SqlDbType.VarChar);
var kdMail = new SqlParameter("#Kundenmail", SqlDbType.VarChar);
var kdTele = new SqlParameter("#Telefon", SqlDbType.VarChar);
string kdquery = "INSERT INTO Kunden VALUES (#Kundennummer, #Kundenname, #Kundenmail, #Telefon)";
using (SqlConnection updatedb = new SqlConnection("..."))
{
updatedb.Open();
using (SqlCommand insert = new SqlCommand(kdquery, updatedb))
{
insert.Parameters.Add(kdName);
insert.Parameters.Add(kdNummer);
insert.Parameters.Add(kdMail);
insert.Parameters.Add(kdTele);
for (int i = 0;i<dataGridView1.Rows.Count;i++)
{
kdName.Value = dataGridView1.Rows[i].Cells["Kundenname"].Value;
kdNummer.Value = dataGridView1.Rows[i].Cells["Kundennummer"].Value;
kdMail.Value = dataGridView1.Rows[i].Cells["Kundenmail"].Value;
kdTele.Value = dataGridView1.Rows[i].Cells["Telefon"].Value;
insert.ExecuteNonQuery();
}
}
}
Or even shorter:
string kdquery = "INSERT INTO Kunden VALUES (#Kundennummer, #Kundenname, #Kundenmail, #Telefon)";
using (SqlConnection updatedb = new SqlConnection("..."))
{
updatedb.Open();
for (int i = 0;i<dataGridView1.Rows.Count;i++)
{
using (SqlCommand insert = new SqlCommand(kdquery, updatedb))
{
insert.Parameters.AddWithValue("#Kundenname", dataGridView1.Rows[i].Cells["Kundenname"].Value);
insert.Parameters.AddWithValue("#Kundennummer", dataGridView1.Rows[i].Cells["Kundennummer"].Value);
insert.Parameters.AddWithValue("#Kundenmail", dataGridView1.Rows[i].Cells["Kundenmail"].Value);
insert.Parameters.AddWithValue("#Telefon", dataGridView1.Rows[i].Cells["Telefon"].Value);
insert.ExecuteNonQuery();
}
}
}
EDIT: I modified the long version of the code for maximum re-use of instances. Otherwise you get the errors mentioned in your comment.

Rewriting LINQ to SQL class using DataContext

I have written a function to insert some data into SQL table based on the data received from the client iny my LINQ to SQL class:
//some code
string commString = "INSERT INTO Token (tk_ID, tk_token, tk_date, tk_IP) VALUES (#val1, #val2, #val3, #val4)";
string conString = "placeholder";
token = GenerateToken(clientLoginData);
using (SqlConnection con = new SqlConnection(conString))
{
using (SqlCommand com = new SqlCommand())
{
com.Connection = con;
com.CommandText = commString;
com.Parameters.AddWithValue("#val1", clientLoginData.cl_ID);
com.Parameters.AddWithValue("#val2", token);
com.Parameters.AddWithValue("#val3", clientLoginData.LoginTime);
com.Parameters.AddWithValue("#val4", clientLoginData.cl_IP);
try
{
con.Open();
com.ExecuteNonQuery();
}
catch (SqlException e)
{
}
}
//rest of function
Is this the correct way to do so? I heard you can do it much easier using
SampleDBDataContext dc = new SampleDBDataContext();
and then using this variable dc. I never used it however, is it true? And can someone give me example of inserting one value into the table using this?
your code is a simple c# code to insert value and not Linq2Sql for Linq2Sql you should have
using (YourDbContext dc=new YourDbContext ()){
Token item = new Token();
item.tk_date = clientLoginData.LoginTime;
item.tk_IP = clientLoginData.cl_IP;
item.tk_ID = clientLoginData.cl_ID;
item.tk_token = token;
dc.Tokens.InsertOnSubmit
dc.SubmitChanges();
}
Example 1
Example 2
Do like this:
DataContext dc = new Using(DataContext(Connections.GetDynamicConnectionfromConfig()))
{
Sampleclass obj = new Sampleclass();
//Here assign properties to obj
dc.tableName.InsertOnSubmit(obj);
dc.SubmitChanges();
}
Hope this will help you.
your code should look like this
using (SampleDBDataContext dc = new SampleDBDataContext())
{
Token item = new Token();
item.tk_ID = clientLoginData.cl_ID;
item.tk_token = token;
item.tk_date = clientLoginData.LoginTime;
item.tk_IP = clientLoginData.cl_IP;
dc.Tokens.InsertOnSubmit(item);
dc.SubmitChanges();
}

Categories

Resources