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();
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 the below code that is supposed to return me a String (either with a value or empty) but instead I am getting the following text value inside the String result "System.Threading.Tasks.UnwrapPromise 1[System.Object]"because of which my call to (String.IsNullOrEmpty(result)) gives an unexpected result.
private bool UserLogin(string un, string pw)
{
SqlConnection con = new SqlConnection(strcon);
SqlCommand cmd = new SqlCommand("Select username from CTM_DATABASE.dbo.users where username=#un and password=#pw", con);
cmd.Parameters.AddWithValue("#un", un);
cmd.Parameters.AddWithValue("#pw", pw);
con.Open();
string result = Convert.ToString(cmd.ExecuteScalarAsync());
if(String.IsNullOrEmpty(result)) return false; return true;
}
Any ideas what I am doing wrong?
PS: it is my first time coding in ASP.net
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;
}
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.
I am using a function to import data from a access db into SQL server:
public string importDataFromAccess(string table, string fileName)
{
OleDbConnection OleDbConn = new OleDbConnection(String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}", fileName));
try
{
string sSQLTable = table;
string myExcelDataQuery = "Select * from " + sSQLTable;
string sSqlConnectionString = connStr;
string sClearSQL = "DELETE FROM " + sSQLTable;
SqlConnection SqlConn = new SqlConnection(sSqlConnectionString);
SqlCommand SqlCmd = new SqlCommand(sClearSQL, SqlConn);
SqlConn.Open();
SqlCmd.ExecuteNonQuery();
SqlConn.Close();
OleDbCommand OleDbCmd = new OleDbCommand(myExcelDataQuery, OleDbConn);
OleDbConn.Open();
OleDbDataReader dr = OleDbCmd.ExecuteReader();
SqlBulkCopy bulkCopy = new SqlBulkCopy(sSqlConnectionString);
bulkCopy.DestinationTableName = sSQLTable;
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
OleDbConn.Close();
return "Done";
}
catch (Exception ex)
{
OleDbConn.Close();
return ex.ToString();
}
}
I noticed it isnt importing the first record of each table, can anyone help notice why and how to fix? Hopefully it is only the first row...
You shouldn't need the
while (dr.Read())
{
bulkCopy.WriteToServer(dr);
}
And you just need to replace that with
bulkCopy.WriteToServer(dr);
The WriteToServer method
Copies all rows in the supplied IDataReader to a destination table
specified by the DestinationTableName property of the SqlBulkCopy
object.
But the dr.Read() that you have called has read the first line out of the Reader and advanced the IDataReader to the next record (so it is not accessible to the WriteServer method).