Namespace error - c#

I have defined a function in following class like this
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Configuration;
using MFDBAnalyser;
using System.Data;
using System.Data.SqlClient;
using System.Diagnostics;
using System.IO;
namespace MFDBAnalyser
{
public class PrimaryKeyChecker : IMFDBAnalyserPlugin
{
public string RunAnalysis(string ConnectionString)
{
return GetAllPrimaryKeyTables(ConnectionString);
}
/// <summary>
/// This function populates the tables with primary keys in a datagrid dgResultView.
/// </summary>
/// <param name="localServer"></param>
/// <param name="userName"></param>
/// <param name="password"></param>
/// <param name="selectedDatabase"></param>
/// <returns></returns>
public string GetAllPrimaryKeyTables(string ConnectionString)
{
string result = string.Empty;
// Query to select primary key tables.
string selectPrimaryKeyTables = #"SELECT
TABLE_NAME
AS
TABLES
FROM
INFORMATION_SCHEMA.TABLE_CONSTRAINTS
WHERE
CONSTRAINT_TYPE = 'PRIMARY KEY'
AND
TABLE_NAME <> 'dtProperties'
ORDER BY
TABLE_NAME";
// put your SqlConnection and SqlCommand into using blocks!
using(SqlConnection sConnection = new SqlConnection(ConnectionString))
using(SqlCommand sCommand = new SqlCommand(selectPrimaryKeyTables, sConnection))
{
try
{
// Create the dataadapter object
SqlDataAdapter sDataAdapter = new SqlDataAdapter(selectPrimaryKeyTables, sConnection);
DataTable dtListOfPrimaryKeyTables = new DataTable("tableNames");
// Fill the datatable - no need to open the connection, the SqlDataAdapter will do that all by itself
// (and also close it again after it is done)
sDataAdapter.Fill(dtListOfPrimaryKeyTables);
using(StringWriter sw = new StringWriter())
{
dtListOfPrimaryKeyTables.WriteXml(sw);
result = sw.ToString();
}
}
catch(Exception ex)
{
//All the exceptions are handled and written in the EventLog.
EventLog log = new EventLog("Application");
log.Source = "MFDBAnalyser";
log.WriteEntry(ex.Message);
}
}
// return the data table to the caller
return result;
}
}
}
But when I am calling this like this
protected void GetPrimaryKeyTables()
{
DataTable dtPrimaryKeys = new PrimaryKeyChecker().GetAllPrimaryKeyTables(txtHost.Text, txtUsername.Text, txtPassword.Text, Convert.ToString(cmbDatabases.SelectedValue));
dgResultView.DataSource = dtPrimaryKeys;
}
Then it is throwing errors like
Error 1 The type or namespace name
'PrimaryKeyChecker' could not be found
(are you missing a using directive or
an assembly
reference?) D:\Projects\Mindfire\GoalPlan\MFDBAnalyser\MFDBAnalyser\MFDBAnalyser.cs 340 43 MFDBAnalyser

You didn't show what using statements are in effect for GetPrimaryKeyTables() but you can always use the full name:
DataTable dtPrimaryKeys =
new MFDBAnalyser.PrimaryKeyChecker().GetAllPrimaryKeyTables(...));
I suspect you may have misspelled one instance of MFDBAnalyser

If the class that defines GetPrimaryKeyTables() method is not in the MFDBAnalyser namespace, you will need to include using statement at the top of that file, like so...
using MFDBAnalyser;
Alternatively, you could instantiate PrimaryKeyChecker using its full name, like so...
DataTable dtPrimaryKeys = new PrimaryKeyChecker().GetAllPrimaryKeyTables(...);

Related

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll Incorrect syntax near 'b'

i got this error message when i run my code. It said "An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll but was not handled in user code Additional information: Incorrect syntax near 'b'." but i dont know how to solve it. Actually i refer someone code and it just the same as their code but still i got error.
this is my code :
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.Configuration;
using System.Data.SqlClient;
namespace myCookbook
{
public partial class Form1 : Form
{
SqlConnection connection;
string connectionString;
public Form1()
{
InitializeComponent();
connectionString = ConfigurationManager.ConnectionStrings["myCookbook.Properties.Settings.cookBookDatabaseconnectionString"].ConnectionString;
}
private void Form1_Load(object sender, EventArgs e)
{
InsertResipi();
}
private void InsertResipi()
{
using (connection = new SqlConnection(connectionString))
using (SqlDataAdapter myAdapter = new SqlDataAdapter("SELECT * FROM Recipe", connection))
{
DataTable RecipeTable = new DataTable();
myAdapter.Fill(RecipeTable);
listRecipes.DisplayMember = "ResepiName";
listRecipes.ValueMember = "Id";
listRecipes.DataSource = RecipeTable;
}
}
private void InsertIngredient()
{
string myQuery = " SELECT a.IngredientName FROM Ingredient a" +
"INNER JOIN ResipiIngredient b ON a.Id = b.IngredientId" +
"WHERE b.ResipiId = #ResipiId";
using (connection = new SqlConnection(connectionString))
using (SqlCommand myCommand = new SqlCommand(myQuery, connection))
using (SqlDataAdapter adapter = new SqlDataAdapter(myCommand))
{
myCommand.Parameters.AddWithValue("#ResipiId", listRecipes.SelectedValue);
DataTable IngredientTable = new DataTable();
adapter.Fill(IngredientTable); // the error message highlight this line
listIngredient.DisplayMember = "IngredientName";
listIngredient.ValueMember = "Id";
listIngredient.DataSource = IngredientTable;
}
}
private void listRecipes_SelectedIndexChanged(object sender, EventArgs e)
{
// MessageBox.Show(listRecipes.SelectedValue.ToString()); //show id
InsertIngredient();
}
}
}
this is my references
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Configuration;
using System.Data.SqlClient;
namespace databasecookbook
{
public partial class Form1 : Form
{
string connectiondenganawak;
SqlConnection connectionhati;
public Form1()
{
InitializeComponent();
connectiondenganawak = ConfigurationManager.ConnectionStrings
["databasecookbook.Properties.Settings.cookbookConnectionString"].
ConnectionString;
}
private void Form1_Load(object sender, EventArgs e)
{
isirecipe();
}
void isirecipe()
{
using (connectionhati = new SqlConnection(connectiondenganawak))
using (SqlDataAdapter adapterawak = new SqlDataAdapter("SELECT * FROM Recipe", connectionhati))
{
DataTable RecipeTable = new DataTable();
adapterawak.Fill(RecipeTable);
listBoxRecipe.DisplayMember = "Name";
listBoxRecipe.ValueMember = "ID";
listBoxRecipe.DataSource = RecipeTable;
}
}
void isiingredient()
{
string querycinta = " SELECT a.Name FROM Ingredient a" +
"INNER JOIN RecipeIngredient b ON a.Id = b.IngredientID" +
"WHERE b.RecipeID = #RecipeID";
using (connectionhati = new SqlConnection(connectiondenganawak))
using (SqlCommand commandawak =new SqlCommand(querycinta,connectionhati))
using (SqlDataAdapter adapterawak = new SqlDataAdapter(commandawak))
{
commandawak.Parameters.AddWithValue("#RecipeID", listBoxRecipe.SelectedValue);
DataTable IngredientTable = new DataTable();
adapterawak.Fill(IngredientTable);
listBoxIngredients.DisplayMember = "Name";
listBoxIngredients.ValueMember = "ID";
listBoxIngredients.DataSource = IngredientTable;
}
}
private void listBoxRecipe_SelectedIndexChanged(object sender, EventArgs e)
{
isiingredient();
}
}
}
The query string that you get lacks whitespace around line breaks: when you concatenate, say, " SELECT a.Name FROM Ingredient a" + "INNER JOIN RecipeIngredient b ON a.Id = b.IngredientID", there is no space between a and INNER JOIN, so query syntax is incorrect.
C# provides a built-in solution for problem through verbatim string literals, i.e. literals starting in #. These literals can include line breaks:
string myQuery =#"
SELECT a.IngredientName FROM Ingredient a
INNER JOIN ResipiIngredient b ON a.Id = b.IngredientId
WHERE b.ResipiId = #ResipiId
";
This query has valid syntax when you pass it to SQL Server, and it also reads nicely on the screen.

How Do I Use C# Code In HTML To Get ID Out Of A SQL Database?

So I'm trying to create a website with a database and currently just wanting to check the database connnection by printing a number from the database in the HTML code. I'm terrible at scripts so please ignore that.
The C# code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
public class LogFiller
{
public int userID;
string connectionstring = "USER ID=x;" +
"PASSWORD=x;server=x;" +
"Trusted_Connection=yes;" +
"database=x; " +
"connection timeout=30";
public LogFiller()
{
//
// TODO: Add constructor logic here
//
}
public int getUserID
{
get {
using (var connection = new SqlConnection(connectionstring))
{
try
{
connection.Open();
SqlCommand myCommand = new SqlCommand("SELECT ID FROM x WHERE Name = 'x'", connection);
SqlDataAdapter adapter = new SqlDataAdapter(myCommand);
DataTable dt = new DataTable();
adapter.Fill(dt);
return (int)dt.Rows[0][0];
}
catch (Exception e)
{
Console.WriteLine(e.ToString());
}
}
return userID;
}
}
}
The script I thought of (but doesn't work)
#{
LogFiller lf = new LogFiller();
lf.getUserID;
}
For clarification: I want to just write the number that the C# code returns anywhere on my page.
Once you open a C# block with the #{ }, in order to write the value from a variable inside that block you need to escape it with another # like this:
#{
LogFiller lf = new LogFiller();
<p>User ID: #lf.getUserID</p>
}
Also, as someone in a comment stated, you'll likely need to fully qualify your LogFiller type with the namespace. So WhateverYourNamespaceIs.LogFiller

How do I insert SQL server values using C#? I keep getting null

I recently viewed a youtube tutorial on how to use a c#-class to run sql-commands and fetch data. This is the tutorial I have followed: https://www.youtube.com/watch?v=WG3Hwk7Yp48#t=13m42s at 13:42 you can see that he runs his code, inserts name-values into a textbox and is then able to show the new values in the combobox.
However, whenever I run my code I get this error (fullsize image available here):
The table I am trying to collect/insert data from has a 'unr' int which cannot be null, and a name which is a varchar.
This is my SQL-DAL:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using System.Data.SqlClient;
using System.Data.Sql;
namespace WindowsFormsApplication3
{
class DAL
{
private SqlConnection con;
public SqlCommand cmd;
private SqlDataAdapter da;
private DataTable dt;
public DAL()
{
con = new SqlConnection(#"Data Source=VIKTOR-PC;Initial Catalog=HT2015;Integrated Security=True");
con.Open();
}
public void SqlQuery(string queryText)
{
cmd = new SqlCommand(queryText, con);
}
public DataTable QueryEx()
{
da = new SqlDataAdapter(cmd);
dt = new DataTable();
da.Fill(dt);
return dt;
}
public void NoQueryEx()
{
cmd.ExecuteNonQuery();
}
}
and this is my form:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
namespace WindowsFormsApplication3
{
public partial class Form1 : Form
{
private WindowsFormsApplication3.DAL con;
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
con = new DAL();
con.SqlQuery("INSERT INTO dbo.Users(name) VALUES (#NameP)");
con.cmd.Parameters.Add("#NameP", textBox1.Text);
con.NoQueryEx();
con.SqlQuery("SELECT name FROM Users");
comboBox1.Items.Clear();
foreach(DataRow dr in con.QueryEx().Rows)
{
comboBox1.Items.Add(dr[1].ToString());
}
}
}
}
Now it keeps saying that unr is null, and all I want is to add new names to the table. I havent got a clue on how to solve this.
Your table Users has not-nullable column unr.
But this query you're using:
INSERT INTO dbo.Users(name) VALUES (#NameP)
doesn't inserts anything into unr - this is the reason you're getting that exception.
You should either insert something into unr in your query or make it nullable (or having some default value) at table definition.

Trouble in executing the SQL query using c#

using System;
using System.Data.SqlClient;
namespace ConsoleCSharp
{
/// <summary>
/// Summary description for Class1.
/// </summary>
class DataReader_SQL
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main(string[] args)
{
//
// TODO: Add code to start application here
//
try
{
SqlConnection thisConnection = new SqlConnection(#"Network Library=dbmssocn;Data
Source=sourcename,1655;database=Oracle;User id=sysadm;Password=password;");
thisConnection.Open();
SqlCommand thisCommand = thisConnection.CreateCommand();
thisCommand.CommandText = "SELECT * FROM SYSADM.PS_RQ_DEFECT_NOTE where ROW_ADDED_OPRID = 'github'";
SqlDataReader thisReader = thisCommand.ExecuteReader();
while (thisReader.Read())
{
Console.WriteLine(thisCommand.CommandText);
Console.ReadKey();
}
thisReader.Close();
thisConnection.Close();
}
catch (SqlException e)
{
Console.WriteLine(e.Message);
}
}
}
}
Please help me to resolve this issue.Thanks. I want to execute SQL query using c# and get the results on console.I guess there is some problem with my code.Please review and let me know the inputs.
If you want to print the query data, you should run a command like this:
Console.WriteLine(thisReader["ROW_ADDED_OPRID"].ToString());
..inside the while loop.
It appears that you're trying to use the SQL Native Client (normally for use for connecting to Microsoft SQL Server) rather than using an Oracle client. Whilst the System.Data.OracleClient namespace does exist, it is deprecated. Instead, you may want to consider connecting using an OleDbConnection with the appropriate connection string, so something like:
using (OleDbConnection con = new OleDbConnection(#"Network Library=dbmssocn;Data Source=sourcename,1655;database=Oracle;User id=sysadm;Password=password;")
{
con.Open();
using (OleDbCommand cmd = con.CreateCommand() )
{
cmd.CommandText = "SELECT * FROM SYSADM.PS_RQ_DEFECT_NOTE where ROW_ADDED_OPRID = 'github'";
using(IDataReader thisReader = cmd.ExecuteReader() )
{
while (thisReader.Read())
{
Console.WriteLine(thisReader["fieldname"]);
Console.ReadKey();
}
}
};
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}

Display query result depending on user input

I am working on a code in C#.NET to create a web service that will take in a particular input. It will then connect to the database , where depending on the input provided, the entire result must be fetched from my table and displayed accordingly.
However, I am not that familiar with C#.NET and so I am not able to implement my code properly. can someone please help me
Here is what I have do so far:
using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;
namespace test3
{
/// <summary>
/// Summary description for Service1
/// </summary>
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ToolboxItem(false)]
// 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 Service1 : System.Web.Services.WebService
{
[WebMethod]
public String GetAttendance(String rollno)
{
String result="";
try
{
using (SqlConnection myConnection = new SqlConnection(#"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123"))
{
myConnection.Open();
using (SqlCommand myCommand = new SqlCommand())
{
myCommand.Connection = myConnection;
myCommand.CommandText = "SELECT COUNT(*) FROM studentdata WHERE rollno = #rollno";
myCommand.Parameters.Add("#rollno", SqlDbType.VarChar).Value = rollno;
SqlDataReader myReader = myCommand.ExecuteReader();
while (myReader.Read())
{
result = myReader.ToString();
}
}
}
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return "an error occured";
}
return result;
}
}
}
If I run this code, I get output as "System.Data.SqlClient.SqlDataReader" which is not what i want
Don't use a data reader for this you only have one result which is a row count so use ExecuteScalar() and use an int as type for result:
int result = Convert.ToInt32(myCommand.ExecuteScalar());
(Alternatively you can get the string value with your current query using result = myReader.GetInt32(0).ToString(); - don't do this though)

Categories

Resources