• Ivy Seo

Azure Function, Postgresql, JSON format, C#

this Azure function grabs data from cloud database (which is Azure cloud postgres)

and data is sent in JSON format.


using Npgsql;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using System.Collections.Generic;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace MartenAzureDocDbDemo
    public static class QuotesGet
        public class M7Data
            public M7Data(int Id_, string Text_, string TruckID_)
                Id = Id_;
                Text = Text_;
                TruckID = TruckID_;
            public int Id { get; set; }
            public string Text { get; set; }
            public string TruckID { get; set; }
        public static async Task<IActionResult> Run(
            [HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
            ILogger log)
            // connect to postgresql
            var cs = "Host=##; Username=##; Password=##; Database=##";
            var con = new NpgsqlConnection(cs);
            // run query
            string sql = "SELECT id, Company, TruckID  FROM m7_data_table LIMIT 5";
            var cmd = new NpgsqlCommand(sql, con);
            NpgsqlDataReader rdr = cmd.ExecuteReader();
            var M7Data = new List<M7Data>();
            string test = "";
            // save each row of data
            while (rdr.Read())
                int id = rdr.GetInt32(0);
                string text = rdr.GetString(1);
                string truckID = rdr.GetString(2);
                M7Data.Add(new M7Data(id, text, truckID));
                test = text;
            // convert into Json format
            string _output = JsonConvert.SerializeObject(M7Data);
            // if there is no data: otherwise it shows data in Json format
            string responseMessage = string.IsNullOrEmpty(test)
                           ? "There is no data"
                           : $"Hello, {_output}";
            // will show responseMessage 
            return new OkObjectResult(responseMessage);

<output when you run>

Recent Posts

See All

Generate unique filename: UUID, Path

A: using UUID let my_uuid = Uuid::new_v4(); let file_created = File::create(my_uuid.to_string()).expect("create file failed");     println!("uuid: {}", my_uuid); //  buffer write let mut file_ge

JSON - write .txt file in Rust

pub fn serialize_writeFile(data : &full_data ) -> Result<bool, modbus::Error> { // 1) takes data  // this function takes the m7_data object and serializes the contents and saves the results to a text

Serialize/Deserialize JSON in Rust

This README has some good examples. To deserialize in Rust: use serde::{Deserialize, Serialize}; use serde_json::Result; #[derive(Serialize, Deserialize)] struct Person {     name: String,     age: u