GithubHelp home page GithubHelp logo

Comments (1)

Justrebl avatar Justrebl commented on July 1, 2024

Repro : Azure Function Runs (POCO doesn't work) :

[Function(nameof(GetUsersEntById))]
        public HttpResponseData GetUsersEntById(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "UsersEnt/{userId}")] HttpRequestData req,
            [TableInput(
                tableName: "%AZURE_TABLE_SOURCE%",
                partitionKey: "%AZURE_TABLE_PARTITION_KEY%",
                rowKey: "{userId}",
                Connection = "AZURE_TABLE_STORAGE_ACCOUNT")] UserEntity user,
                string userId)
        {
            _logger.LogInformation("Retrieving user with id: {UserId} in the table : {SourceTable}", user.RowKey, _sourceTable);

            // Preparing user entity to be returned
            var response = req.CreateResponse(HttpStatusCode.OK);
            response.Headers.Add("Content-Type", "application/json; charset=utf-8");
            response.WriteString($"{JsonSerializer.Serialize(user)}");

            return response;
        }

But TableEntity is fine !

        [Function(nameof(GetUsersById))]
        public HttpResponseData GetUsersById(
            [HttpTrigger(AuthorizationLevel.Anonymous, "get", Route = "Users/{userId}")] HttpRequestData req,
            [TableInput(
                tableName: "%AZURE_TABLE_SOURCE%",
                partitionKey: "%AZURE_TABLE_PARTITION_KEY%",
                rowKey: "{userId}",
                Connection = "AZURE_TABLE_STORAGE_ACCOUNT")] TableEntity userEntity,
                string userId)
        {
            _logger.LogInformation("Retrieving user with id: {UserId} in the table : {SourceTable}", userId, _sourceTable);

            HttpResponseData response;

            if (!userEntity.ContainsKey("firstname") || !userEntity.ContainsKey("lastname")){
                response = req.CreateResponse(HttpStatusCode.InternalServerError);
                response.Headers.Add("Content-Type", "plain/text; charset=utf-8");
                response.WriteString($"Internal Server Error : user {userId} cannot be fetched");
                return response;
            }

            UserEntity fetchedUser = _userEntityFactory.CreateUserEntity(
                    userEntity["firstname"].ToString(),
                    userEntity["lastname"].ToString(),
                    userEntity["RowKey"].ToString());

            //Preparing user entity to be returned
            response = req.CreateResponse(HttpStatusCode.OK);

            response.Headers.Add("Content-Type", "application/json; charset=utf-8");
            response.WriteString($"{JsonSerializer.Serialize(fetchedUser)}");

            return response;
        }

Here is UserEntity Definition :

using System.Text.Json.Serialization;
using System.Text.Json;
using Azure;
using Azure.Data.Tables;
using Microsoft.Extensions.Configuration;
using System.Diagnostics;
using System.Runtime.Serialization;

namespace CafeReadConf.Backend.Models
{
    public class UserEntity : ITableEntity
    {
        [JsonPropertyName("firstname")]
        public string FirstName { get; set; }

        [JsonPropertyName("lastname")]
        public string LastName { get; set; }

        [JsonPropertyName("partitionkey")]
        public string PartitionKey { get; set; }

        [JsonPropertyName("rowkey")]
        public string RowKey { get; set; }

        [JsonPropertyName("timestamp")]
        [JsonIgnore(Condition = JsonIgnoreCondition.Always)]
        public DateTimeOffset? Timestamp { get; set; }

        [JsonPropertyName("odata.etag")]
        [JsonIgnore(Condition = JsonIgnoreCondition.Always)]
        public ETag ETag { get; set; }

        public UserEntity() { }

        public UserEntity(string partitionKey, string rowKey)
        {
            PartitionKey = partitionKey;
            RowKey = rowKey;
        }

        public UserEntity(string firstName, string lastName, string partitionKey, string rowKey)
        {
            FirstName = firstName;
            LastName = lastName;
            PartitionKey = partitionKey;
            RowKey = rowKey;
        }

        public UserEntity(string firstName, string lastName, string partitionKey, string rowKey,
        DateTimeOffset? timestamp,
        ETag eTag)
        {
            FirstName = firstName;
            LastName = lastName;
            PartitionKey = partitionKey;
            RowKey = rowKey;
            Timestamp = timestamp;
            ETag = eTag;
        }
    }

    public class UserEntityFactory
    {
        private readonly IConfiguration _configuration;

        public UserEntityFactory(IConfiguration configuration)
        {
            _configuration = configuration;
        }

        public UserEntity CreateUserEntity(string firstName, string lastName, string? rowKey = null, DateTimeOffset? timestamp = null, ETag? eTag = null)
        {
            return new UserEntity(
                    firstName,
                    lastName,
                    _configuration.GetValue<string>("AZURE_TABLE_PARTITION_KEY"),
                    rowKey ?? System.Guid.NewGuid().ToString(),
                    timestamp ?? DateTimeOffset.Now,
                    ETag.All);
        }
    }

}

And the associated local.settings.json based on ManagedIdentity (local AzureDefaultCredentials mechanism)

{
  "IsEncrypted": false,
  "Values": {
    "AzureWebJobsStorage": "UseDevelopmentStorage=true",
    "FUNCTIONS_WORKER_RUNTIME": "dotnet-isolated",
    "AZURE_TABLE_STORAGE_ACCOUNT__tableServiceUri": "https://stoappinnoday.table.core.windows.net",
    "AZURE_TABLE_SOURCE": "usersdev",
    "AZURE_TABLE_PARTITION_KEY": "users"
  }
}

from app-innovation-day.

Related Issues (1)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.