I have got below code in c#.
SqlConnection conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;");
conn.Open();
if (conn != null)
{
//create command
SqlCommand cmd = new SqlCommand("dbo.GETTridionLinkData", conn);
cmd.Parameters.AddWithValue("#PageID", "637518");
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 500;
StringBuilder sbXML = new StringBuilder();
//Adding Root node
sbXML.Append("<TridionLinks>");
//Reading all the values of Stored procedure return
using (XmlReader reader = cmd.ExecuteXmlReader())
{
while (reader.Read())
{
sbXML.Append(reader.ReadOuterXml().Replace("//", "/"));
}
}
//Closing the root node tag
sbXML.Append("</TridionLinks>");
XmlDocument xDoc = new XmlDocument();
//Loading string xml in XML Document
xDoc.LoadXml(sbXML.ToString());
}
In above code you can see that, I have set the cmd.CommandTimeout = 500;, now I want to give user an error message if the timeout is more than this or you can say database is down.
Please suggest!!
Please refer to
How to catch SQLServer timeout exceptions
The question has already been answered..
To improve coding, you can use
try{
using (sqlconnection Conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;"){
...
}
}catch(sqlException ex){
if (ex.Number == -2) {
//return your message to the control or display the error
}
}
well just an example..
Related
Help
Why can't I get serilog to log to sqlserver
I have used forever to get this to work
It logs fine to the console
I have installed the nuget packages
Serilog
Serilog.Sinks.Console
Serilog.Sinks.MSSqlServer
//First a quick test if the connection string works (db can open, and if the table exists, it works but no rows
var connection = new ConnectionStringSettings();
connection.ConnectionString = "Data Source=server-name;Initial Catalog=db-name;Persist Security Info=True;User ID=user-name;Password='password-name'";
var sqlc = new SqlConnection(connection.ConnectionString);
string query = "select * from LogEvents";
sqlc.Open();
using (var command = new SqlCommand(query, sqlc))
{
var reader = command.ExecuteReader();
if (reader.HasRows)
{
while (reader.Read())
{
}
}
reader.Close();
}
sqlc.Close();
var log = new LoggerConfiguration()
.WriteTo
.MSSqlServer(
connectionString: connection.ConnectionString,
sinkOptions: new MSSqlServerSinkOptions { TableName = "LogEvents", AutoCreateSqlTable = true }
)
.WriteTo.Console()
.CreateLogger();
Log.Logger = log;
Log.Information("123");
Log.CloseAndFlush();
Console.WriteLine("Hello, World!");
I've created a project in Visual Studio 2019 which has several user controls in a form called Home.
All goes right until today. After rebuilding my project Home form shows an error saying
The control system.windows.forms.form has thrown an unhandled exception in the designer and has been desabled.
Exception :
An attempt to attach an auto-named database for file c:\program files(x86)\Microsoft Visual Studio\2019\Enterprise\common7\ide\database\pharmacy.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on unc share.
I checked the connection code, and it looks ok. But still the error isn't solved.
Code:
SqlConnection con = new SqlConnection(#"Data Source=LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True");
con.Open()
String str = "Select max(id) from supp;";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
String val = dr[0].ToString();
if (val == "")
{
.....
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True");
con.Open();
try
{
String str = "Insert into supp(name,email,mobile,addr,s_code) values('" + Sup_Name.Text + "','" + Sup_Email.Text + "','" + Sup_Mobile.Text + "','" + Sup_Add.Text + "','" + Sup_Code.Text + "');";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
String str1 = "select max(ID) from supp;";
SqlCommand cmd1 = new SqlCommand(str1, con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Inserted Supplier Data SuccessFully..");
using (SqlConnection con1 = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True"))
{
String str2 = "Select * from supp";
SqlCommand cmd2 = new SqlCommand(str2, con1);
SqlDataAdapter sda = new SqlDataAdapter(cmd2);
DataTable dt = new DataTable();
sda.Fill(dt);
SupplierDataGV.DataSource = new BindingSource(dt, null);
}
Sup_Name.Text = "";
Sup_Code.Text = "";
Sup_Email.Text = "";
Sup_Mobile.Text = "";
Sup_Add.Text = "";
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}
i am trying to convert my code to a sync but when i run it
i get in one of my vars the value "System.Threading.Tasks.Task`1[System.Int32]" instead of the expected ans
i have read most of the same questions asked in this topic but none of them helped me solved the problem
i tried to use properly the await but its isn't helped
public async Task<int> userloginAsync(string name,string pass)
{
using (SqlConnection con = new SqlConnection(#"/////:P//////"))
{
using (SqlCommand cmd = new SqlCommand("UserLoginPro"))
{
cmd.Connection = con;
cmd.CommandText = "SELECT count(id) FROM user_table where name =#name and password =#password; ";
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#password", pass);
await con.OpenAsync();
var ans1 = await cmd.ExecuteScalarAsync();
var ans = ans1.ToString();
con.Close();
int res = Convert.ToInt32(ans);
con.Close();
return res;
}
}
}
its should query the mssql if there is an match to inputs(username and password)
and if there is return 1
if not 0
(in the DB there is unique usernames so it can be only one )
How to solve this, help me out I'm new
Please explain your question... If you want to fetch from http, below code will help you. you may need to add some libraries too.
HttpClient httpclient = new DefaultHttpClient();
Httppost httppost = new HttpPost("www.example.com");
HttpResponse response = httpclient.execute(httppost);
entity = response.getEntity();
InputStream is = entity.getContent();
BufferedReader reader = new BufferedReader(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
String result = sb.toString();
JSONObject jsonObj = new JSONObject(result);
continue your code after this...
Add the libraries to the gradle file.
Look for this line:
dependencies {
...
}
and add this:
dependencies {
...
compile 'com.android.support:appcompat-v7:23.0.0'
compile 'org.apache.httpcomponents:httpclient:4.5'
compile 'org.apache.httpcomponents:httpcore:4.4'
}
In my program , I read data by using HTTPURLConnection for example
URL url = new URL("https://twitter.com/search?q="+kw+"%20lang%3Aeng%20"+"&src=typd&lang=en");
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
conn.setRequestMethod("GET");
conn.setRequestProperty("Accept", "application/json");
if (conn.getResponseCode() != 200) {
throw new RuntimeException("Failed : HTTP error code : "
+ conn.getResponseCode());
}
String line;
StringBuilder builder = new StringBuilder();
BufferedReader reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
while ((line = reader.readLine()) != null) {
builder.append(line);
builder.append("\n");
}
String html = builder.toString();
The problem is only reading data on response page , but I need to read all data that can be retrieved
How I can Load more data in result page