Controller won't load data from database - c#

I am currently making a controller to gather myself the data i need from a database. I am not allowed to use Entity Framework and i can't seem to find the reason my controller won't load the data from my SQL server... It is locally hosted on my computer and the connecntion string i am using is in the controller file itself.
Thanks in advance!
I have removed the data context from my controller because i can't share them
namespace ControllerFile.Controller
{
internal class ControllerFile
{
private static string connectionString = System.Configuration.ConfigurationManager.ConnectionStrings[""].ConnectionString;
public GroupModel GetModel(int Id)
{
string sqlQuery = " Query ";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.Parameters.AddWithValue("", );
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
try
{
Model user = new Model();
return user;
}
catch
{
MessageBox.Show("Error");
}
}
}
}
return new Model();
}
public void AddNewItem(Model, model)
{
string sqlQuery = " QUERY ";
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand(sqlQuery, con))
{
cmd.Parameters.AddWithValue("", model.id);
con.Open();
try
{
cmd.ExecuteNonQuery();
}
catch
{
MessageBox.Show("Error");
}
}
}
return;
}
}
}
The result should be a proper connection to my database where my listview loads the correct data. I have added a hardcoded variable with a filled model and that one did load into the listview. So we can rule that code out. It has to be in the controller.

You're not using the data you get from the database anywhere in that code. You do this:
while (reader.Read())
but then you never actually get any data from the data reader. You just do this:
Model user = new Model();
return user;
so you're just returning a new, empty model, no matter what you get from the database. You need to actually get the appropriate data from the data reader and put it in the model, e.g.
Model user = new Model {SomeProperty = reader.GetString(reader.GetOrdinal("SomeColumn"))};
return user;

Related

How to display a mysql View in ASP.NET Core

I've created a MySQL View from a database in Microsoft SQL Server Management Studio and I would like to get the information in the MySQL View to my Asp.net controller.
I've tried making an SqlCommand where it asks everything from the View containers. How do I set information from the containers view to a different model(for example B0[Product] and Bb[Vessel]) and display it in one view?
public IActionResult TablesColumnDisplay()
{
List<SomeModel> Context = new List<SomeModel>(); // i dont know what model i should be using, or no model whatsoever?
using (SqlConnection SqlConn = new SqlConnection(conn))
{
using (SqlCommand SqlComm = new SqlCommand("SELECT * FROM containers;")) //Containers is the final MySQL View
{
using (SqlCommand SqlComm = new SqlCommand("SELECT * FROM containers;")) //Containers is the final MySQL View
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
{
SqlComm.Connection = SqlConn;
SqlConn.Open();
sda.SelectCommand = SqlComm;
SqlDataReader sdr = SqlComm.ExecuteReader();
while (sdr.Read())
{
B0 b0 = new B0();
Bb bb = new Bb();
b0.Date = (string)sdr["Date"];
bb.VesselName= (string)sdr["Vessel_Name"];
SomeModel.Add(b0, bb); //doesn't take more than 1 arguments
}
}
return Context;
}
}
}
I will use ViewData to grab the information and so I can use that in my Index View.
Your "model" should be a custom class that can hold both informations (Date and VesselName):
public class SomeModel
{
public DateTime Date {get;set;}
public string VesselName {get;set;}
}
(Note that I used DateTime instead of string because I feel it's more appropriate to store a date)
Then you could create one model instead of b0 and bb:
SomeModel myModel = new SomeModel();
And set both properties.
myModel.Date = (DateTime)sdr["Date"];
myModel.VesselName = (string)sdr["Vessel_Name"];
Then you can use Context.Add(myModel); (note Context and not SomeModel) and here you are.
In short, your while loop would look like this:
while (sdr.Read())
{
SomeModel myModel = new SomeModel();
myModel.Date = (DateTime)sdr["Date"];
myModel.VesselName= (string)sdr["Vessel_Name"];
Context.Add(myModel);
}

How to Get Database Names With all Tables and procedures,views etc in c# Tree view

Actually I want to fetch Database Names just like in SQL Management Studio have on the left Spinner Bar same as in C# tree View.
I am working on a system in which database control through Application,
so I fetched all database Names and All Tables Names but I not getting each Database with their tables, just like in SQL Management Studio, in which A database have 4 to 5 nodes includes(tables,views,procedures,etc). and also I fetched in a List so I want to fetch in a tree View just Like in SQL Management Studio.
for Backend(Business Logic) I used this and fetched All Database Names and all Tables without respective sequences.
public List<string> GetDatabaseList()
{
List<string> list = new List<string>();
using (SqlConnection con = new SqlConnection(MyConString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT name from
sys.databases", con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
public List<string> GetTableList()
{
List<string> list = new List<string>();
using (SqlConnection con = new SqlConnection(MyConString))
{
con.Open();
using (SqlCommand cmd = new SqlCommand("SELECT name from
sys.Tables", con))
{
using (SqlDataReader dr = cmd.ExecuteReader())
{
while (dr.Read())
{
list.Add(dr[0].ToString());
}
}
}
}
return list;
}
and use it by front-end through anycomponents.datasource.
My expected output is that I want to get all respective nodes of database Just like in SQL Management Studio not only database and tables.
Well if you use sys.objects it'll list all database related objects. The only trick you need is to have a sysadmin account that can view all databases. Then, you can just target each database objects.
So, what you'll need is :
Get databases names list
Target each database objects
Filter objects as needed.
Here is a working example.
public enum DbObjectType
{
SYSTEM_TABLE,
USER_TABLE,
VIEW,
SQL_STORED_PROCEDURE
}
public class SqlServerDbObjects
{
const string connectionString = #"Data Source=.\;Initial Catalog=master;Integrated Security=True";
public IDictionary<string, IList<string>> GetDbObjects()
{
var dbNameList = GetDatabaseList();
var dbObj = new Dictionary<string, IList<string>>();
for (int x = 0; x < dbNameList.Count; x++)
{
var name = dbNameList[x];
var objList = GetDatabaseObjectsList(name, DbObjectType.USER_TABLE);
dbObj.Add(name, objList);
}
return dbObj;
}
public IList<string> GetDatabaseList()
{
const string sql = "SELECT [name] FROM sys.databases WHERE database_id > 4";
return Reader(sql, "name");
}
public IList<string> GetDatabaseObjectsList(string databaseName, DbObjectType objType)
{
StringBuilder sb = new StringBuilder(string.Empty);
if (string.IsNullOrEmpty(databaseName))
throw new NullReferenceException("You must specify a database");
else
sb.Append($"SELECT [name] FROM [{databaseName}].sys.objects WHERE [type_desc] = '{objType.ToString()}'");
return Reader(sb.ToString(), "name");
}
public IList<string> Reader(string query, string columnName)
{
var list = new List<string>();
try
{
using (SqlConnection connection = new SqlConnection(connectionString))
using (SqlCommand command = new SqlCommand(query, connection))
{
connection.Open();
using (SqlDataReader dataReader = command.ExecuteReader())
{
while (dataReader.Read())
{
list.Add(dataReader[columnName].ToString());
}
}
}
return list;
}
catch (SqlException ex)
{
// do stuff for handling sql errors.
return null;
}
}
}
Then you just do :
var test = new SqlServerDbObjects().GetDbObjects();
I have tried to make it as simple as I could, so you can get the idea.

execute reader doesn't respond

i have a php code.here is the code,i gonna to translate it to .NET but in some point i'm getting some trouble.
function processInput($conn, $MessageArray, $mobilenumber, $date, $odd)
{
$strSQLUSER="SELECT * FROM tbl_tiduser WHERE username='".addslashes($MessageArray[0])."' AND stat!='1' AND stat!='4'";
$result_user=odbc_exec($conn,$strSQLUSER) or die("Could not connect to database");
here is the converted .NET code
public class ProcessInput
{
private string msg_arr;
private string MooseSeenInput(string MobileNo,string Date,string odd,params Array[] msg_arr)
{
SqlCommand com = new SqlCommand("SELECT * FROM tbl_tiduser WHERE username=#username AND stat!='1' AND stat!='4'", mycon);
com.Parameters.AddWithValue("#username",username);
using (SqlDataReader reader = com.ExecuteReader())
// whats the next part need to come here ???
}
this is incomplete.i'm not going to compile it....
private static void ReadOrderData(string connectionString)
{
string queryString =
"SELECT OrderID, CustomerID FROM dbo.Orders;";
using (SqlConnection connection =
new SqlConnection(connectionString))
{
SqlCommand command =
new SqlCommand(queryString, connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
// Call Read before accessing data.
while (reader.Read())
{
Console.WriteLine(String.Format("{0}, {1}",
reader[0], reader[1]));
}
// Call Close when done reading.
reader.Close();
}
}
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx
I would use something like this to get the column(s) you're after:
string username = null;
using (SqlDataReader reader = com.ExecuteReader()) {
if (reader.read()) {
username = (string)reader["mydbcolumnname"];
}
reader.Close();
}
Note that if you want to pull all the result rows (as opposed to stepping through them) then you'd normally use a SqlDataAdapter to fill a DataSet (instead of the reader), eg:
string username;
using (SqlDataAdapter adapter = new SqlDataAdapter(com))
{
using (DataSet ds)
{
adapter.Fill(ds);
username = (string)ds.Tables[0].Rows[0]["mycolumnname"];
}
}
I'm all for easy; I would write a class that mirrors the record I'm reading, i.e.
public class User {
public int Id {get;set;}
public string Name {get;set;}
}
and use "dapper":
var user = myCon.Query<User>(
"SELECT * FROM tbl_tiduser WHERE username=#username AND stat not in ('1','4')",
new {username}).SingleOrDefault();
if(user == null) { /* not found, presumably throw an exception */ }
string name = user.Name; // etc
Then you don't need to mess with commands, readers, parameters etc (see how the username is being made into a db parameter cleanly?).

Using SqlDataReader to fill an ArrayList?

I'm trying to implement a method which will take a given connection string and return an ArrayList containing the contents of a SQL view.
I've verified the validity of the connection string and the view itself. However I don't see what the problem is in the code below. In debug, when it runs the ExecuteReader method and then try to enter the while loop to iterate through the records in the view, it immediately bails because for some reason sqlReader.Read() doesn't.
public ArrayList GetEligibles(string sConnectionString)
{
string sSQLCommand = "SELECT field1, field2 FROM ViewEligible";
ArrayList alEligible = new ArrayList();
using (SqlConnection sConn = new SqlConnection(sConnectionString))
{
// Open connection.
sConn.Open();
// Define the command.
SqlCommand sCmd = new SqlCommand(sSQLCommand, sConn);
// Execute the reader.
SqlDataReader sqlReader = sCmd.ExecuteReader(CommandBehavior.CloseConnection);
// Loop through data reader to add items to the array.
while (sqlReader.Read())
{
EligibleClass Person = new EligibleClass();
Person.field1 = sqlReader["field1"].ToString();
Person.field2 = sqlReader["field2"].ToString();
alEligible.Add(Person);
}
// Call Close when done reading.
sqlReader.Close();
}
return alEligible;
}
Note, EligibleClass is just a class object representing one row of the view's results.
A couple of things I would check:
Is the connection string ok
Does the user in your connection string have access to the database/view
Can you access that database from the pc your at
Does the ViewEligable view exist
Does the view contain a field1 and field2 column.
Here one way you could possibly clean up that code somewhat (assuming you have .net 2.0)
public List<EligibleClass> GetEligibles(string sConnectionString)
{
List<EligibleClass> alEligible = null;
try
{
using (SqlConnection sConn = new SqlConnection(sConnectionString))
{
sConn.Open();
using (SqlCommand sCmd = new SqlCommand())
{
sCmd.Connection = sConn;
sCmd.CommandText = "SELECT field1, field2 FROM ViewEligible";
using (SqlDataReader sqlReader = sCmd.ExecuteReader())
{
while (sqlReader.Read())
{
EligibleClass Person = new EligibleClass();
Person.field1 = sqlReader.GetString(0);
Person.field2 = sqlReader.GetString(1);
if (alEligible == null) alEligible = new List<EligibleClass>();
alEligible.Add(Person);
}
}
}
}
}
catch (Exception ex)
{
// do something.
}
return alEligible;
}

C# locking away SQLite

I have encountered a problem with getting locked out of SQLite file.
I am currently working on employee register for my company and use SQLite as a database of choice. From my program, I populated the database using scripts I prepared. Reading goes well and all, but once I make any change to the employee at all, the program freezes at "database is locked" exception.
I created a static class called SQLiteManager where I have all methods involving the DB. I then call them from Windows Forms like
foreach (Employee em in SQLiteManager.getEmployees()){
//filling the fields }
calls
public static List<Employee> getEmployees() {
List<Employee> ret = new List<Employee>();
SQLiteDataReader reader;
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = "select ID_Employee from Employee";
reader = cmd.ExecuteReader();
while (reader.Read()) { ret.Add(extractEmployee(reader["ID_Employee"].ToString(), false)); }
}
return ret;
}
I always use this "using" notations in ALL other methods that call ExecuteReader() in them.
Method that I use to crunch the script and populate the DB:
public static bool processSqlCommandFile(string file)
{
try
{
using (StreamReader sr = new StreamReader(file))
{
string line;
while ((line = sr.ReadLine()) != null)
{
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = line;
cmd.ExecuteNonQuery();
}
}
sr.Close();
}
}
catch (Exception ex)
{
return false;
}
return true;
}
and finally, the sore method
public static bool alterEmployee(Employee e) {
using (SQLiteConnection dbc = new SQLiteConnection(databaseConnectionString))
using (SQLiteCommand cmd = dbc.CreateCommand())
{
openConnection(dbc);
cmd.CommandText = "Update Employee SET name = '"+e.name+"' where ID_Employee = "+e.id;
//Alter the command once this shiet works
cmd.ExecuteNonQuery();
}
return true;
}
Yet it always gets frozen. By using the using(SQLiteConnection...) I thought I am getting rid of the "sleepy" connections that would somehow lock it, but the trouble is somewhere else.
Can you help me identify the problem or tell me steps to identify it myself?
Thank you

Categories

Resources