Connection must be valid and open. where is the problem ? .net Frmework version 2.0
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
Connection must be valid and open. where is the problem ? .net Frmework version 2.0
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Security.Cryptography;
using MySql.Data.MySqlClient;
namespace Student_Portal_Password
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
public static string GetMd5Hash(string input)
{
MD5 md5Hash = MD5.Create();
// Convert the input string to a byte array and compute the hash.
byte[] data = md5Hash.ComputeHash(Encoding.UTF8.GetBytes(input));
// Create a new Stringbuilder to collect the bytes
// and create a string.
StringBuilder sBuilder = new StringBuilder();
// Loop through each byte of the hashed data
// and format each one as a hexadecimal string.
for (int i = 0; i < data.Length; i++)
{
sBuilder.Append(data[i].ToString("x2"));
}
// Return the hexadecimal string.
return sBuilder.ToString();
}
public void check()
{
if (txtid.Text == "")
{
MessageBox.Show("Please enter Student ID ", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK);
}
else if (txtpassword.Text == "")
{
MessageBox.Show("Please enter new password", MessageBoxIcon.Warning.ToString(), MessageBoxButtons.OK);
}
}
private void button1_Click(object sender, EventArgs e)
{
try
{
//check();
txtpassword.Text.Trim();
string hash = GetMd5Hash(txtpassword.Text);
string db = "server=localhost;uid=root;password=usbw;database=dum;";
MySqlConnection dbcon = new MySqlConnection(db);
MySqlCommand cmd = new MySqlCommand(db);
dbcon.Open();
cmd.CommandText = "SELECT * FROM members;";
cmd.ExecuteNonQuery();
MessageBox.Show("Success!");
dbcon.Close();
}
catch (MySqlException ex)
{
MessageBox.Show(ex.Message);
}
}
private void txtid_KeyPress(object sender, KeyPressEventArgs e)
{
const char Delete = (char)8;
e.Handled = !Char.IsDigit(e.KeyChar) && e.KeyChar != Delete;
}
}
}
A couple of things;
You're using ExecuteNonQuery for a Query. Try for example ExecuteReader instead.
You're not setting a connection for your DbCommand, so executing it won't find the database.
Try this instead;
MySqlConnection dbcon = new MySqlConnection(db);
string sql = "SELECT * FROM members";
MySqlCommand cmd = new MySqlCommand(sql, dbcon); //<-- pass connection to command
Your current code;
MySqlCommand cmd = new MySqlCommand(db);
...passes in the connection string as the SQL to execute, and does not associate the command with any database connection. That will give the error you're asking about.
Related
Just starting to experiment with F#. I have this code working in C#:
using MySql.Data.MySqlClient;
using System;
using System.IO;
namespace SandboxExecuteReader
{
class Program
{
static void Main(string[] args)
{
MySqlConnection myConnection = new MySqlConnection();
MySqlCommand myCommand = new MySqlCommand();
if (!SQLdbOpen(myConnection, myCommand)) return;
DoWork(myCommand);
myConnection.Close();
return;
}
private static void DoWork(MySqlCommand myCommand)
{
myCommand.CommandText = "SELECT * FROM xxx.mytable";
using (var reader = myCommand.ExecuteReader())
{
while (reader.Read())
{
string Field1 = reader.GetString(reader.GetOrdinal("Field1"));
string Field2 = reader.GetString(reader.GetOrdinal("Field2"));
string Field3 = reader.GetString(reader.GetOrdinal("Field3"));
Console.WriteLine("{0} {1} {2}", Field1, Field2, Field3);
}
}
}
private static bool SQLdbOpen(MySqlConnection myConnection, MySqlCommand myCommand)
{
/*
* Open Connection to SQL DB
*/
string ConnectionString = "server=(someIP); uid=Me; password=MyPass";
try
{
myConnection.ConnectionString = ConnectionString;
myConnection.Open();
myCommand.Connection = myConnection;
}
catch (MySqlException E)
{
Console.WriteLine("Open Error: {0}", E.Message);
Console.WriteLine("Press RETURN to continue or CONTROL-C to abort");
Console.ReadLine();
return false;
}
return true;
}
}
}
Questions:
In C#, I add a reference to MySql.Data.dll. How do I do that in F#?
There seems to be something about #r ... where does that line go? Somewhere in the .fsproj file?
How would this code look in F#?
The first thing you need to decide is whether you are going to run this as a standalone script (.fsx file) or a project (consisting of .fs source files and a .fsproj project file).
If this is going to be a project, it works just like a C# project: you add a reference to MySql.Data.dll in your .fsproj file. If you're using Visual Studio, you can right-click on the project and find MySql.Data in NuGet via the "Manage NuGet Packages..." menu item.
If it's going to be a standalone script, you can add a NuGet reference to MySql by placing this line at the very top: #r "nuget: MySql.Data".
Converting your code from C# is a bit more involved, but your main function might look like this (assuming this is a .fs file):
open MySql.Data.MySqlClient
let sQLdbOpen (myConnection : MySqlConnection) (myCommand : MySqlCommand) =
// ...
true
let doWork (myCommand : MySqlCommand) =
// ...
()
[<EntryPoint>]
let main args =
use myConnection = new MySqlConnection()
use myCommand = new MySqlCommand()
if sQLdbOpen myConnection myCommand then
doWork myCommand
myConnection.Close()
0
(Caveat: I did this translation by eye, so it might not be exactly right.)
I have made a simple Azure Functions v2 Web Service that connects to an Azure SQL database, runs a stored procedure with 3 parameters and returns the result as JSON output. It works as it is now (with the connectionstring in the run.csx file).
But how do I get it to get the connectionstring from Applications Settings?
I have tried various guides both here and other places. But all I can find is a long list of references and a whole bunch of code I need to add. I have followed the guides to the letter (also set the values in App Settings), but it just wont work. I'm rather new to C#, so it might be I just don't understand what I'm supposed to do.
Anyways this is my code and the suggested fix, as far as I'm able to tell:
#r "Newtonsoft.Json"
#r "System.Data"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
public static async Task<ActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string login = req.Query["login"];
string pwd = req.Query["password"];
string TransID = req.Query["TransID"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
login = login ?? data?.login;
pwd = pwd ?? data?.password;
TransID = TransID ?? data?.TransID;
var cnnString = "Server=MyServer;Database=WebServices;User Id=MyUser;Password=MyPassword;Encrypt=True;";
try
{
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_GetRegRW", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Login", login));
cmd.Parameters.Add(new SqlParameter("#Password", pwd));
cmd.Parameters.Add(new SqlParameter("#TransID", TransID));
await connection.OpenAsync();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}
return (ActionResult)new OkObjectResult(JsonConvert.SerializeObject(table));
}
catch (SqlException sqlex)
{
return (ActionResult)new OkObjectResult($"The following SqlException happened: {sqlex.Message}");
}
catch (Exception ex)
{
return (ActionResult)new OkObjectResult($"The following Exception happened: {ex.Message}");
}
}
suggested solution:
#r "Newtonsoft.Json"
#r "System.Data"
#r "Microsoft.Extensions.Configuration"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using System.Data;
using System.Data.SqlClient;
using Microsoft.Extensions.Configuration;
public static async Task<ActionResult> Run(HttpRequest req, ILogger log, ExecutionContext context)
{
var config = new ConfigurationBuilder()
.SetBasePath(context.FunctionAppDirectory)
.AddJsonFile("local.settings.json", optional: true, reloadOnChange: true)
.AddEnvironmentVariables()
.Build();
var cnnString =config.GetConnectionString("connWS");
var setting1 = config["Setting1"];
log.LogInformation(cnnString);
log.LogInformation(setting1);
log.LogInformation("C# HTTP trigger function processed a request.");
string login = req.Query["login"];
string pwd = req.Query["password"];
string TransID = req.Query["TransID"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
login = login ?? data?.login;
pwd = pwd ?? data?.password;
TransID = TransID ?? data?.TransID;
try
{
DataTable table = new DataTable();
SqlConnection connection = new SqlConnection(cnnString);
SqlCommand cmd = new SqlCommand("sp_GetRegRW", connection);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("#Login", login));
cmd.Parameters.Add(new SqlParameter("#Password", pwd));
cmd.Parameters.Add(new SqlParameter("#TransID", TransID));
await connection.OpenAsync();
using (SqlDataAdapter adapter = new SqlDataAdapter(cmd))
{
adapter.Fill(table);
}
return (ActionResult)new OkObjectResult(JsonConvert.SerializeObject(table));
}
catch (SqlException sqlex)
{
return (ActionResult)new OkObjectResult($"The following SqlException happened: {sqlex.Message}");
}
catch (Exception ex)
{
return (ActionResult)new OkObjectResult($"The following Exception happened: {ex.Message}");
}
}
In function v2, you should use Environment.GetEnvironmentVariable("string_name",EnvironmentVariableTarget.Process) to get values from Application settings and connection strings.
Note: When use the above method, the first parameter depends on the Type. It means that when the type of the connection string is SQLAZURE, then the first parameter should be SQLAZURE + CONNSTR + _stringName.
The screenshot is as below:
The code sample:
//for connection string
string connStr = Environment.GetEnvironmentVariable("SQLAZURECONNSTR_sqldb_connection",EnvironmentVariableTarget.Process);
log.LogInformation("the connection string is: " + connStr);
And the result snapshot:
I get the following error: The ConnectionString property has not been initialized.
You should probably create an instance of SqlConnection, with your connection string and open this connection before try to make any command.
SqlConnection con = new SqlConnection("connStr");
await con.OpenAsync();
I was trying to salt password in asp.net web application mysql but its shows this error.While running getting the error.Please anyone tell me the error?
Error:
Server Error in '/' Application.
Parser Error
Description: An error occurred during the parsing of a resource required to service this request. Please review the following specific parse error details and modify your source file appropriately.
Parser Error Message: Could not load type 'DemoPage.Default'.
Source Error:
Line 1: <%# Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="DemoPage.Default" %>
Line 2:
Line 3: <!DOCTYPE html>
Source File: /Default.aspx Line: 1
Version Information: Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3163.0
Code default.aspx:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace WebPage1
{
public partial class _default : System.Web.UI.Page
{
MySql.Data.MySqlClient.MySqlConnection conn;
MySql.Data.MySqlClient.MySqlCommand cmd;
MySql.Data.MySqlClient.MySqlDataReader reader;
String queryStr;
String name;
protected void Page_Load(object sender, EventArgs e)
{
DoSQLQuery();
}
protected void submit_click(object sender, EventArgs e)
{
String connString = System.Configuration.ConfigurationManager.ConnectionStrings["WebAppConnString"].ToString();
conn = new MySql.Data.MySqlClient.MySqlConnection(connString);
conn.Open();
String queryStr = "";
cmd = new MySql.Data.MySqlClient.MySqlCommand("SELECT * FROM webapp.userregistration WHERE username = #name and password=#pas", conn);
cmd.Parameters.AddWithValue("#name", usernameTextBox.Text);
cmd.Parameters.AddWithValue("#pas", passwordTextBox.Text);
reader = cmd.ExecuteReader();
name = "";
while (reader.HasRows && reader.Read())
{
{
name = reader.GetString(reader.GetOrdinal("username")) + " " + reader.GetString(reader.GetOrdinal("password"));
}
//if the data matches the rows (username, password), then you enter to the page
if (reader.HasRows)
{
Session["uname"] = name;
Response.BufferOutput = true;
Response.Redirect("login.aspx", false);
}
else
{
passwordTextBox.Text = "invalid user";
}
}
reader.Close();
conn.Close();
}
private void DoSQLQuery()
{
try
{
}
catch (Exception e)
{
passwordTextBox.Text = e.ToString();
}
}
}
}
Hai I have to add details from one table to another which should be within to dates. These dates are read from text boxes.
But i'm getting Error:
"An exception of type 'MySql.Data.MySqlClient.MySqlException' occurred in MySql.Data.dll but was not handled in user code
Additional information: Incorrect datetime value: '11/25/2015 12:00:00 AM' for column 'debissuedate' at row 1"
The first table is t_bondridapp with fields : id,cancode,canname,debissuedate...etc
And I have to copy from this table to new one named as bondlocal with fields :
bondid,cancode,canname,bonddate.
I've used the code
public class DBConnection
{
private DBConnection()
{
}
private string dbname = string.Empty;
public string DBName
{
get { return dbname;}
set { dbname = value;}
}
public string Password { get; set; }
private MySqlConnection mycon = null;
public MySqlConnection Connection
{
get { return mycon; }
}
private static DBConnection _instance = null;
public static DBConnection Instance()
{
if(_instance==null)
_instance=new DBConnection();
return _instance;
}
public bool IsConnect()
{
bool result = true;
if(mycon==null)
{
if (String.IsNullOrEmpty(dbname))
result = false;
string constr = string.Format("server=localhost;user id=root;password=mysql;database=pnys;",dbname);
mycon = new MySqlConnection(constr);
mycon.Open();
result = true;
}
return result;
}
public void Close()
{
mycon.Close();
}
}
protected void Page_Load(object sender, EventArgs e)
{
}
protected void Button1_Click1(object sender, EventArgs e)
{
MySqlDateTime fdate =new MySqlDateTime(DateTime.Parse(TextBox3.Text));
MySqlDateTime sdate = new MySqlDateTime(DateTime.Parse(TextBox4.Text));
var dbCon = DBConnection.Instance();
dbCon.DBName = "pnys";
if (dbCon.IsConnect())
{
string query = "INSERT INTO bondlocal (cancode,canname,bonddate) SELECT t_bondridapp.cancode,t_bondridapp.canname,t_bondridapp.debissuedate FROM t_bondridapp WHERE debissuedate>='" + fdate + "'AND debissuedate<='" + sdate + "'";
MySqlCommand cmd = new MySqlCommand(query, dbCon.Connection);
cmd.ExecuteNonQuery();
}
Server.Transfer("ReportBonds.aspx");
}
Pls Help Me...
Basically, the problem is how you're passing parameters into the database. You shouldn't need to create a MySqlDateTime yourself - just use parameterized SQL and it should be fine:
// TODO: Use a date/time control instead of parsing text to start with
DateTime fdate = DateTime.Parse(TextBox3.Text);
DateTime sdate = DateTime.Parse(TextBox4.Text);
string query = #"INSERT INTO bondlocal (cancode,canname,bonddate)
SELECT t_bondridapp.cancode,t_bondridapp.canname,t_bondridapp.debissuedate
FROM t_bondridapp
WHERE debissuedate >= #fdate AND debissuedate <= #sdate";
using (var command = new MySqlCommand(query, dbCon))
{
command.Parameters.Add("#fdate", MySqlDbType.Datetime).Value = fdate;
command.Parameters.Add("#sdate", MySqlDbType.Datetime).Value = sdate;
command.ExecuteNonQuery();
}
Basically, you should never specific values within SQL by just using string concatenation. Parameterized SQL prevents SQL injection attacks and conversion issues, and improves code readability.
(As an aside, I would urge you to ditch your current connection sharing, and instead always create and open a new MySqlDbConnection and dispose of it at the end of your operation - rely on the connection pool to make it efficient.)
Im trying to connect my mobile to PC database using this code:
string cString = #"Persist Security Info=False;Integrated Security=false;Initial Catalog=myDB;server=192.168.1.11,1433\SqlExpress";
SqlConnection connection = new SqlConnection(cString);
connection.Open();
using (SqlCommand cmd = new SqlCommand("SELECT name1 FROM Product", connection))
{
using (SqlDataReader rdr = cmd.ExecuteReader())
{
while (rdr.Read())
{
t.Text += rdr.GetString(rdr.GetOrdinal("name1")) + System.Environment.NewLine;
}
}
}
Unfortunately I'm getting error: "Input string was not in the correcr format", source: mscorlib.
I know that there's error in connectionString (throwin exception after connection.Open())
Any ideas? Thanks in advance!
your current Culture is not in correct format
protected override void OnResume()
{
base.OnResume();
//Here you would read it from where ever.
var userSelectedCulture = new CultureInfo("en-US");
Thread.CurrentThread.CurrentCulture = userSelectedCulture;
}