Имя типа или пространства имен не найдено в функциях Azure - PullRequest
0 голосов
/ 10 октября 2018

Я пытаюсь перенести некоторые смоделированные данные в Azure iot Hub и сохранить полученные данные в IOT HUB в Mongo DB, используя функции Azure (C #).Получение сообщений от iot-концентратора до лазурных функций работает.когда я пытаюсь подтолкнуть их к mongo db следующим образом, выдается следующая ошибка.При этом я следовал этому учебнику.

мой run.csx

using System;
using System.Runtime.Serialization;
using System.ServiceModel.Description;
using MongoDB.Bson.IO;
using MongoDB.Bson;
using MongoDB;
using MongoDB.Driver;
using System.Security.Authentication;
using System.Text;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public static void Run(string myIoTHubMessage, TraceWriter log)
{
    log.Info($"C# IoT Hub trigger function processed a message: {myIoTHubMessage}");
    string deviceId="",data="";
    var raw_obj=JObject.Parse(myIoTHubMessage);
    deviceId=(string)raw_obj["device_id"];
    data=(string)raw_obj["Data"];
    Cosmos cosmos= new Cosmos(deviceId,data);
    cosmos.pushData();
}

//CosmosDB class
public class Cosmos
{
    string deviceId="",data="";
    public BsonDocument document = new BsonDocument();
    public Cosmos(string deviceId, string data)
    {
        this.deviceId=deviceId;
        this.data=data;
    }
    public void pushData()
    {
        MainAsync().Wait();
    }
    public async Task MainAsync()
    {
        string connectionString = 
    @"mongodb://xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx";
    MongoClientSettings settings = MongoClientSettings.FromUrl(new MongoUrl(connectionString));
        settings.SslSettings = new SslSettings() { EnabledSslProtocols = SslProtocols.Tls12};
        var mongoClient = new MongoClient(settings);
        IMongoDatabase db = mongoClient.GetDatabase("iot");
        var icollection = db.GetCollection<BsonDocument>(deviceId);
        document.Add("Data",data);
        await icollection.InsertOneAsync(document);
    }

}

мой файл project.json

{
  "frameworks": {
    "net46":{
      "dependencies": {
        "Newtonsoft.Json": "10.0.3",
        "System.ServiceModel.Primitives":"4.4.0",
        "MongoDB.Bson": "2.4.0",
        "MongoDB.Driver": "2.4.0",
        "MongoDB.Driver.Core": "2.4.0"
      }
    }
   }
}

когда я запускаю код, он выдает следующую ошибку

2018-10-10T18:34:25.990 [Error] Function compilation error
2018-10-10T18:34:26.119 [Error] run.csx(3,27): error CS0234: The type or namespace name 'Description' does not exist in the namespace 'System.ServiceModel' (are you missing an assembly reference?)
2018-10-10T18:34:26.242 [Error] run.csx(4,7): error CS0246: The type or namespace name 'MongoDB' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:26.332 [Error] run.csx(5,7): error CS0246: The type or namespace name 'MongoDB' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:26.435 [Error] run.csx(6,7): error CS0246: The type or namespace name 'MongoDB' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:26.548 [Error] run.csx(7,7): error CS0246: The type or namespace name 'MongoDB' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:26.666 [Error] run.csx(10,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:26.771 [Error] run.csx(11,7): error CS0246: The type or namespace name 'Newtonsoft' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:26.828 [Warning] run.csx(13,48): warning CS0618: 'TraceWriter' is obsolete: 'Will be removed in an upcoming version. Use ILogger instead.'
2018-10-10T18:34:26.946 [Error] run.csx(28,12): error CS0246: The type or namespace name 'BsonDocument' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:27.058 [Error] run.csx(17,17): error CS0103: The name 'JObject' does not exist in the current context
2018-10-10T18:34:27.201 [Error] run.csx(28,40): error CS0246: The type or namespace name 'BsonDocument' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:27.304 [Error] run.csx(42,5): error CS0246: The type or namespace name 'MongoClientSettings' could not be found (are you missing a using directive or an assembly reference?)
2018-10-10T18:34:27.431 [Error] run.csx(42,36): error CS0103: The name 'MongoClientSettings' does not exist in the current context
2018-10-10T18:34:27.632 [Error] Executed 'Functions.EventHubTriggerCSharp1' (Failed, Id=32bc6c5d-73fa-4082-b74b-c86a901f6656)

Может кто-нибудь помочь мне решить эту проблему?

Ответы [ 2 ]

0 голосов
/ 12 октября 2018

Проблема вызвана разницей времени выполнения функции.

Учебное пособие, которое вы выполняете, создает функцию в ~ 1 среде выполнения, где код нацелен на .NET Framework, а созданная вами - в среде выполнения ~ 2, которая работает на.NET Core env.Когда мы создаем новое приложение-функцию, его время выполнения по умолчанию теперь равно ~ 2.

Решение состоит в том, чтобы установить FUNCTIONS_EXTENSION_VERSION в ~1 в настройках приложения на портале.Затем нажмите View Files на функциональной панели и отредактируйте function.json, чтобы заставить его работать в v1 - измените eventHubName на path.См. Настройка триггера концентратора событий .

И некоторые улучшения, удалите те, которые не используются в контексте, вместе с System.ServiceModel.Primitives в project.json.Newtonsoft.Json сборка существует, но не добавлена ​​к хосту, необходимо явно ссылаться на нее.

  1. сборка и пространство имен с использованием проекта

    #r "Newtonsoft.Json"
    
    using Newtonsoft.Json.Linq;
    using MongoDB.Bson;
    using MongoDB.Driver;
    using System.Security.Authentication;
    
  2. .json.

    {
      "frameworks": {
        "net46":{
          "dependencies": {
            "MongoDB.Bson": "2.7.0",
            "MongoDB.Driver": "2.7.0"
          }
        }
       }
    }
    
0 голосов
/ 10 октября 2018

Если вы используете run.csx, вам нужно «импортировать» ваши сборки, на которые есть ссылки, с помощью # r.

Пример ниже взят из документации.

#r "System.Web.Http"

using System.Net;
using System.Net.Http;
using System.Threading.Tasks;

public static Task<HttpResponseMessage> Run(HttpRequestMessage req, TraceWriter log)
...