Created
July 17, 2022 17:02
-
-
Save programmersommer/8b08e264073dcd51ecd4158c16d59cd2 to your computer and use it in GitHub Desktop.
Getting data from IoT Hub and saving it into SQL database
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#r "System.Configuration" | |
#r "System.Data" | |
#r "System.Data.SqlClient" | |
#r "Newtonsoft.Json" | |
using System; | |
using System.Configuration; | |
using System.Data.SqlClient; | |
using System.Threading.Tasks; | |
using System.Net; | |
using Newtonsoft.Json; | |
public static async Task Run(string myIoTHubMessage, ILogger log) | |
{ | |
log.LogInformation($"C# IoT Hub trigger function processed a message: {myIoTHubMessage}"); | |
var e = JsonConvert.DeserializeObject<EventData>(myIoTHubMessage); | |
// return; | |
var str = Environment.GetEnvironmentVariable("SQLServerDB_connection"); | |
using (SqlConnection conn = new SqlConnection(str)) | |
{ | |
conn.Open(); | |
var text = "INSERT INTO [dbo].[SensorData] (DeviceId, Temp, Time) Values (@deviceId, @temp, @time);"; | |
using (SqlCommand cmd = new SqlCommand(text, conn)) | |
{ | |
cmd.Parameters.AddWithValue("@temp", Math.Round(e.temp, 2)); | |
cmd.Parameters.AddWithValue("@time", e.time); | |
cmd.Parameters.AddWithValue("@deviceId", e.deviceId); | |
var result = await cmd.ExecuteNonQueryAsync(); | |
log.LogInformation($"Inserted: {result.ToString()}"); | |
} | |
} | |
} | |
public class EventData | |
{ | |
public string deviceId { get; set; } | |
public int time { get; set; } | |
public double temp { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment