I would like to inform you that I am using DevExpress Xamarin ComboBox but I cannot connect SQL Database. Can you please give me any idea how to connect with the Microsoft SQL server database? My code is mentioned below for your reference.
sqlConnection.Open();
SqlCommand sc = new SqlCommand("Select (R_Status) from Room_Status", sqlConnection);
SqlDataReader reader;
reader = sc.ExecuteReader();
DataTable dt = new DataTable();
dt.Columns.Add("R_Status", typeof(string));
dt.Load(reader);
CBRoomStatus.ValueMember = "R_Status";
CBRoomStatus.ItemsSource = dt.de;
sqlConnection.Close();
You can try to use the following code to check how many line record you get from the table.
sqlConnection.Open();
SqlCommand sc = new SqlCommand("Select (R_Status) from Room_Status", sqlConnection);
SqlDataReader reader;
reader = sc.ExecuteReader();
var resource = new List<string>();
while (reader.Read())
{
resource.Add((string)reader["R_Status"]);
}
CBRoomStatus.ItemsSource = resource;
sqlConnection.Close();
You can add a break point at the resource.Add() to check how many times have read.
Related
i wonder how to implement M-V-C ADO without using EF.
just like a pure ADO implementation. any suggestions and sample are appreciated Thanks guys.
Basic ADO.NET connections haven't really changed at all with MVC coming around. They still rely on things like SqlConnection objects and their associated commands.
If you wanted to build a simply query, it might look like the following :
// Build your connection
using(var connection = new SqlConnection("{your-connection-string-here"}))
{
// Build your query
var query = "SELECT * FROM YourTable WHERE foo = #bar";
// Create a command to execute your query
using(var command = new SqlCommand(query,connection))
{
// Open the connection
connection.Open();
// Add any parameters if necessary
command.Parameters.AddWithValue("#bar", 42);
// Execute your query here (in this case using a data reader)
using(var reader = command.ExecuteReader())
{
// Iterate through your results
while(reader.Read())
{
// The current reader object will contain each row here, so you
// can access the values as expected
}
}
}
}
You can use the type of ADO commands and paramaterized SQL seen here to retrieve data:
conn.Open();
cmd.CommandText = "SELECT id, desc FROM mytable WHERE id = #id";
cmd.Parameters.AddWithValue("#id", myid);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
{
return null;
}
return new myItem
{
Id = reader.GetInt32(reader.GetOrdinal("id")),
Desc = reader.GetString(reader.GetOrdinal("desc")),
}
}
There are lot of examples on MSDN for CRUD.
I have ASP.Net MVC 5 Web API project.
I cant use asp.net web API 2 web service in android
my web service is under mvc5, Then I have created mobile app in Eclipse Juno and i use Android sdk 21
below is my edited code
namespace AppServices.Models
{
public class AdvertisingRepository
{
private List<Advertising> Advertising = new List<Advertising>();
private int _nextId = 1;
public AdvertisingRepository()
{
}
public List<Advertising> GetAll()
{
Advertising.Clear();
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = #"Server=.;Database=AppServices;User ID=sa;Password=123;";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "SELECT * FROM tblAdvertising";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
Advertising emp = null;
while (reader.Read())
{
emp = new Advertising();
emp.Id = Convert.ToInt32(reader.GetValue(0));
emp.SearchString = reader.GetValue(1).ToString();
emp.OstanID = Convert.ToInt32(reader.GetValue(2));
emp.AdsGroupID = Convert.ToInt32(reader.GetValue(3));
Advertising.Add(emp);
}
myConnection.Close();
return Advertising;
}
public Advertising Get(int id)
{
Advertising.Clear();
SqlDataReader reader = null;
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = #"Server=.;Database=AppServices;User ID=sa;Password=123;";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "SELECT * FROM tblAdvertising WHERE Id=" + id + "";
sqlCmd.Connection = myConnection;
myConnection.Open();
reader = sqlCmd.ExecuteReader();
Advertising emp = null;
while (reader.Read())
{
emp = new Advertising();
emp.Id = Convert.ToInt32(reader.GetValue(0));
emp.SearchString = reader.GetValue(1).ToString();
emp.OstanID = Convert.ToInt32(reader.GetValue(2));
emp.AdsGroupID = Convert.ToInt32(reader.GetValue(3));
Advertising.Add(emp);
}
myConnection.Close();
return Advertising.Find(p => p.Id == id);
}
public Advertising Add(Advertising item)
{
SqlConnection myConnection = new SqlConnection();
myConnection.ConnectionString = #"Server=.;Database=AppServices;User ID=sa;Password=123;";
SqlCommand sqlCmd = new SqlCommand();
sqlCmd.CommandType = CommandType.Text;
sqlCmd.CommandText = "INSERT INTO tblAdvertising (SearchString, OstanID, AdsGroupID) VALUES (#SearchString, #OstanID, #AdsGroupID)";
sqlCmd.Connection = myConnection;
sqlCmd.Parameters.AddWithValue("#SearchString", item.SearchString);
sqlCmd.Parameters.AddWithValue("#OstanID", item.OstanID);
sqlCmd.Parameters.AddWithValue("#AdsGroupID", item.AdsGroupID);
myConnection.Open();
int rowInserted = sqlCmd.ExecuteNonQuery();
// Get new record id
sqlCmd.CommandText = "SELECT TOP (1) Id FROM tblAdvertising ORDER BY Id DESC";
if (sqlCmd.ExecuteScalar() != DBNull.Value)
_nextId = (int)sqlCmd.ExecuteScalar();
////////////////////
myConnection.Close();
// old code
if (item == null)
{
throw new ArgumentNullException("item");
}
item.Id = _nextId;
Advertising.Add(item);
return item;
}
public void Remove(int id)
{
Advertising.RemoveAll(p => p.Id == id);
}
public bool Update(Advertising item)
{
if (item == null)
{
throw new ArgumentNullException("item");
}
int index = Advertising.FindIndex(p => p.Id == item.Id);
if (index == -1)
{
return false;
}
Advertising.RemoveAt(index);
Advertising.Add(item);
return true;
}
}
}
I have ASP.Net MVC 5 Web API project. I cant use asp.net web API 2 web service in android my web service is under mvc5, Then I have created mobile app in Eclipse Juno and i use Android sdk 21 below is my edited code
There are many issues.
It starts with what looks a little careless "SELECT * FROM tblAdvertising"
That is three sins against the rules of SQL.
First there is no table called tblAdvertising. There is one called dbo.tblAdvertising. So lacking the real name SQL assumes that you mean dbo, but that might be something else as well. This will dump your performance. Best always use fully qualified names.
The second issue is that you use * as items to select. I have been a long in SQL development and can tell from own experience how often tables are changed. The person doing so might not even be aware of your application so a simple add will cause your code to break. Always use fully qualified SQL column names as well.
The final issue with your SQL is that you use a command and yet poke in text strings, even those that are unprotected against SQL injection. What if someone adds this as string "'',0,0; truncate table tblAdvertising; --". You might be surprised how often, certainly in the past i could log in websites simply with some variation of "'' or 1=1 --". Best avoid unprotected strings that go to MSSQL or MySQL or any SQL for that matter. Also your SQLstring needs to be compiled taking a further performance hit. There is also no protection against wrong parameters or proper feedback if the result does not exist.
Besides you really do not want to select an entire table. There should be like a top 100 or you could implement some paging.
So the solution is that you use a proper stored procedure, check the parameter input and provide limited and properly formatted output.
Also your
INSERT INTO tblAdvertising (SearchString, OstanID, AdsGroupID) VALUES (#SearchString, #OstanID, #AdsGroupID)
can be much improved.
If you update or insert there is an output statement in SQL that is massive faster than querying the max number
create type dbo.IntTable as table(i int)
go
create proc dbo.AdvertisementInsert
#SearchString varchar
, #OstanID int
, #AdsGroupID int
, #NewID int = 0 output
as
set nocount on -- important to avoid second roundtrip over the network
declare #i as dbo.IntTable -- use predefined table variable
-- always check quality of input first
if #SearchString is null return 50001
-- also avoid rollback transaction since that is costly.
-- Better to ask first if this not already exist
if exists(select 42 from dbo.tblAdvertising where SearchString = #SearchString) return 50002
INSERT INTO tblAdvertising (SearchString, OstanID, AdsGroupID)
output inserted.Id into #i -- catch new id directly into table variable
VALUES (#SearchString, #OstanID, #AdsGroupID)
-- report the result
select #NewID = i from #i -- convert table variable to single int
go
So now your proc can be called just using the parameters and will tell you back either 0 .. in which case the result code will tell you why it failed, or some other number matching the new identity
Enjoy
May be this question will be duplicate but I'm unable to find. I'm using signalR and sqldependency for my application. I've performed one query operation successfully. but will i write separate sqldependency code for every query. sqldependency code is on application level or is separate for each query.
1) how to use different query for each operation?
2) how to call different onchange event
public void RegisterNotification()
{ string connectionString = ConfigurationManager.ConnectionStrings["FFFConnention"].ConnectionString;
//We have selected the entire table as the command, so SQL Server executes this script and sees if there is a change in the result, raise the event
// how to use different query for each operation
string commandText = #"
Select
dbo.Notification.UserName
From dbo.Notification
";
//Start the SQL Dependency
SqlDependency.Start(connectionString);
using (SqlConnection connection = new SqlConnection(connectionString))
{
using (SqlCommand command = new SqlCommand(commandText, connection))
{
connection.Open();
var sqlDependency = new SqlDependency(command);
NotificationHub hub = new NotificationHub();
//how to call different onchange event
sqlDependency.OnChange += new OnChangeEventHandler(hub.sqlDependency_OnChange);
// NOTE: You have to execute the command, or the notification will never fire.
command.ExecuteScalar();
}
}
}
I have a couple of pages in my asp.net (vb) website.
All of the pages need DB so I have created a class and in it I have added the next function:
Public Shared Function query(ByVal sql_str As String) As DataTable
conn As New SqlConnection()
conn.ConnectionString = connStringReadOnly
conn.Open()
Dim cmd As SqlCommand = conn.CreateCommand()
cmd.CommandText = sql_str
Dim ors As SqlDataReader = cmd.ExecuteReader()
Dim tmp_dt As New DataTable
tmp_dt.Load(ors)
ors.Close()
conn.Close()
Return tmp_dt
End Function
now, when I use this in my code, I get timed out pretty fast...
I am closing the conn...
Where am I wrong?
Can we return a multiple result set in stored procedure and how to handle it in .net
???
if yes how??
if no why not ??
please explain
If you are retrieving data using DataReader, you can use NextResult method to iterate through multiple resultsets returned by stored procedure. More information can be found here.
The following code is a simple example from MSDN:
static void RetrieveMultipleResults(SqlConnection connection)
{
using (connection)
{
SqlCommand command = new SqlCommand(
"SELECT CategoryID, CategoryName FROM dbo.Categories;" +
"SELECT EmployeeID, LastName FROM dbo.Employees",
connection);
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.HasRows)
{
Console.WriteLine("\t{0}\t{1}", reader.GetName(0),
reader.GetName(1));
while (reader.Read())
{
Console.WriteLine("\t{0}\t{1}", reader.GetInt32(0),
reader.GetString(1));
}
reader.NextResult();
}
}
}
If you are populating a Dataset from a DataAdapter, note that if DataAdapter encounters multiple resultsets, it will create multiple DataTables (one for each resultset) and will add them to the resulting DataSet.
http://msdn.microsoft.com/en-us/library/yf1a7f4f.aspx has some good examples.
you need to change your connectionString to support it. MultipleActiveResultSets=True
http://msdn.microsoft.com/en-us/library/h32h3abf.aspx for config settings;