Maxime Esprit
Maxime Esprit

Reputation: 1015

Azure Function App C# HTTP Trigger connected to an Azure Database

I try to create a serverless backend for mobile app, following that sample (cheers James) : https://blog.xamarin.com/creating-a-serverless-backend-for-mobile-apps/

Everything works fine for me, until I want to connect my script to a database.

I would like to use that Azure Function App with an Azure Database. For instance, I want my mobile app to call an http request (that triggers the function app), the function app makes a query to the database, and then send an http request back to the mobile. I tried to follow that video : https://channel9.msdn.com/Series/Windows-Azure-Web-Sites-Tutorials/Create-an-event-processing-Azure-Function?ocid=player In this video, the developer connects its scripts to a database and performs a query to the database.

It is that step that makes me fail :(

Here is my code :

#r "System.Configuration"
#r "System.Data"

using System.Net;
using System.Configuration;
using System.Data.Sql;
using System.Threading.Tasks;

public static async Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
{
    if (req == null)
        log.Info("req is null");
    else
        log.Info("req is not null");

    //log.Info($"C# HTTP trigger function processed a request. RequestUri={req.RequestUri}");

    string sConnexionString = "Name=MS_TableConnectionString";

    log.Info(sConnexionString);

    if (ConfigurationManager.ConnectionStrings[sConnexionString] == null)
        log.Info("ConfigurationManager.ConnectionStrings[sConnexionString] is null");
    else
        log.Info("ConfigurationManager.ConnectionStrings[sConnexionString] is not null");

        var str = ConfigurationManager.ConnectionStrings[sConnexionString].ConnectionString;

    if (str == null)
        log.Info("str is null");
    else
        log.Info("str is not null");

    using (SqlConnection conn = new SqlConnection(str))
    {
    if (conn == null)
        log.Info("conn is null");
    else
        log.Info("conn is not null");

        conn.Open();
        var text = "INSERT INTO MyEasyTable(id) values (1)";
        using (SqlCommand cmd = new SqlCommand(text, conn))
        {
            var rows = await cmd.ExecuteNonQueryAsync();
            log.Info($"{rows} inserted.");
        }
    }


    // parse query parameter
    string name = req.GetQueryNameValuePairs()
        .FirstOrDefault(q => string.Compare(q.Key, "name", true) == 0)
        .Value;

    // Get request body
    dynamic data = await req.Content.ReadAsAsync<object>();

    // Set name to query string or body data
    name = name ?? data?.name;

    return name == null
        ? req.CreateResponse(HttpStatusCode.BadRequest, "Please pass a name on the query string or in the request body")
        : req.CreateResponse(HttpStatusCode.OK, "Hello " + name);
}

And here is the output log :

2016-10-24T13:19:09.452 Compilation succeeded.
2016-10-24T13:19:13.257 Function started (Id=6ffaade4-58b0-4005-8fe7-7dc06b96c2b7)
2016-10-24T13:19:14.018 req is not null
2016-10-24T13:19:14.018 Name=MS_TableConnectionString
2016-10-24T13:19:14.018 ConfigurationManager.ConnectionStrings[sConnexionString] is null
2016-10-24T13:19:14.018 Function completed (Failure, Id=6ffaade4-58b0-4005-8fe7-7dc06b96c2b7)
2016-10-24T13:19:14.037 Exception while executing function: Functions.HttpTriggerCSharp1. HttpTriggerCSharp1: Object reference not set to an instance of an object.

Thanks to that log, I understand that ConfigurationManager cannot connect to my Azure database :(

I tried many string for sConnexionString :

And it never works :(

Please, anybody has an idea ?

Upvotes: 2

Views: 2280

Answers (1)

Maxime Esprit
Maxime Esprit

Reputation: 1015

Okay I found the answer...

I need to go to the Function App's settings, and add the Connection String in the settings, as mentioned here : Azure Functions Database Connection String

Then, I need to use this line of code :

string sConnexionString = "MS_TableConnectionString";

And it works well !

Thanks to Adrian Hall that allowed me to refine my searches

Upvotes: 3

Related Questions