Created
April 19, 2018 19:09
-
-
Save programmersommer/492d61c8422c7a1b6bdcdf629cb65c8f to your computer and use it in GitHub Desktop.
Save from IoT hub to SQL Server database Azure function
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 "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, TraceWriter log) | |
{ | |
log.Info($"Message: {myIoTHubMessage}"); | |
var e = JsonConvert.DeserializeObject<EventData>(myIoTHubMessage); | |
var str = ConfigurationManager.ConnectionStrings["SQLServerDB_connection"].ConnectionString; | |
using (SqlConnection conn = new SqlConnection(str)) | |
{ | |
conn.Open(); | |
var text = "INSERT INTO [dbo].[SensorData] (DeviceName, SensorValue) Values (@deviceId, @iotdata);"; | |
using (SqlCommand cmd = new SqlCommand(text, conn)) | |
{ | |
cmd.Parameters.AddWithValue("@iotdata", e.iotdata); | |
cmd.Parameters.AddWithValue("@deviceId", e.deviceId); | |
var result = await cmd.ExecuteNonQueryAsync(); | |
log.Info($"Inserted: {result.ToString()}"); | |
} | |
} | |
} | |
public class EventData | |
{ | |
public string deviceId { get; set; } | |
public int iotdata { get; set; } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment