EventHubTrigger C# with eventData object does not work - c#

after I followed the instructions on the following articles
https://learn.microsoft.com/en-us/azure/azure-functions/functions-create-first-azure-function
https://learn.microsoft.com/en-us/azure/azure-functions/functions-bindings-event-hubs
I have created an EventHubTrigger, which looks like this:
using System;
public static void Run(string myEventHubMessage, ILogger log)
{
log.LogInformation($'C# Event Hub trigger function processed a message: {myEventHubMessage}');
}
This did work without any problems, but since I do need additional meta information, I changed the code to the following (described in the second linked article):
#r 'Microsoft.ServiceBus'
using System.Text;
using System;
using Microsoft.ServiceBus.Messaging;
public static void Run(EventData myEventHubMessage, ILogger log)
{
log.LogInformation($'EnqueuedTimeUtc={myEventHubMessage.EnqueuedTimeUtc}');
log.LogInformation($'SequenceNumber={myEventHubMessage.SequenceNumber}');
log.LogInformation($'Offset={myEventHubMessage.Offset}');
}
But this code results in the following error messages (btw I have also tied to use the deprected TraceWriter instead of ILogger to exactly follow the article but this results in the same error)
2018-10-11T14:22:24.814 [Error] run.csx(1,1): error CS0006: Metadata file 'Microsoft.ServiceBus' could not be found
2018-10-11T14:22:24.903 [Error] run.csx(4,17): error CS0234: The type or namespace name 'ServiceBus' does not exist in the namespace 'Microsoft' (are you missing an assembly reference?)
My question is now, does anyone have a clue what to do in order to get this small piece of code running?
Of course it has to have something to do with the assemblies but the aricle states, that when working in the online portal-editor, there are no further steps to do,.
Man thanks in advance
Felix
PS:
host.json :
{
"version": "2.0"
}
Content of extensions.csproj is:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
<WarningsAsErrors />
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.EventHubs" Version="3.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions.ServiceBus" Version="3.0.0" />
<PackageReference Include="Microsoft.Azure.WebJobs.Script.ExtensionsMetadataGenerator" Version="1.0.1" />
</ItemGroup>
</Project>

Well, the sample is for function 1.x. After 2.x is generally available the function we create is on ~2 runtime by default, as we can see "version":"2.0" in host.json.
Have a try at code below, metadata is stored in SystemProperties of Microsoft.Azure.EventHubs.EventData.
#r "../bin/Microsoft.Azure.EventHubs.dll"
using System;
using Microsoft.Azure.EventHubs;
public static void Run(EventData myEventHubMessage, ILogger log)
{
log.LogInformation($"EnqueuedTimeUtc={myEventHubMessage.SystemProperties.EnqueuedTimeUtc}");
log.LogInformation($"SequenceNumber={myEventHubMessage.SystemProperties.SequenceNumber}");
log.LogInformation($"Offset={myEventHubMessage.SystemProperties.Offset}");
}
Also note that we need to use double quotation " for string in C#, see ' in your code.

Related

ActiproSoftware controls breaks Moq unit tests

Moq does not want to work with ActiroSoftware on net core 3.1
I'm having the following issue: creating a net core 3.1 project with the following structure:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFrameworks>netcoreapp3.1</TargetFrameworks>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Moq" Version="4.14.7" />
<PackageReference Include="Actiprosoftware.Controls.WPF" Version="20.1.0" />
</ItemGroup>
</Project>
then in Program.cs try to write the following:
using Moq;
namespace moqtest
{
class Program
{
static void Main(string[] args)
{
var q = It.IsAny<string>();
}
}
}
Note that this won't compile, due to the following error:
error CS0234: The type or namespace name 'IsAny' does not exist in the namespace 'It' (are you missing an assembly reference?)
Furthermore, specifying the namespace implicitly, will work:
var q = Moq.It.IsAny<string>();
I have looked into msbuild diagnostics and it seems everything is compatible with netcoreapp3.1, but when you compile it, it seems it does not recognize It class anymore.
Please help!
Open up View > Object Browser, and search for It. You'll notice that first result is a namespace called It brought in by ActiproSoftware.BarCode.Wpf.dll
It also happens to be an empty namespace, but that's irrelevant. If it did contain anything under it, you'd refer to them as It.Something. So what happens now is that, even after you do using Moq, It is still ambiguous to the compiler.
The presence of that silly empty namespace is what's forcing to qualify your calls with Moq.

Weird version conflict: The type 'CrontabSchedule' exists in both 'NCrontab.Signed, Version=3.2.20120.0' and 'NCrontab, Version=3.2.20120.0'

I am trying do a very simple thing in console app:
using Microsoft.Azure.WebJobs.Extensions.Timers;
using NCrontab;
using System;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
var nCrontabSchedule = CrontabSchedule.Parse("5 4 * * * *");
}
}
}
But it gives me this error:
Severity Code Description Project File Line Suppression State
Error CS0433 The type 'CrontabSchedule' exists in both 'NCrontab.Signed, Version=3.2.20120.0, Culture=neutral, PublicKeyToken=5247b4370afff365' and 'NCrontab, Version=3.2.20120.0, Culture=neutral, PublicKeyToken=null' ConsoleApp3 C:\Users\bowmanzh\source\repos\ConsoleApp3\Program.cs 12 Active
It didn't even finish compile! It’s hard for me to understand what’s going on here, I just want to use a simple thing.
Why is there a version conflict here? In fact, I referenced two packages, this is my .csproj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<OutputType>Exe</OutputType>
<TargetFramework>netcoreapp3.1</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.WebJobs.Extensions" Version="3.0.6" />
<PackageReference Include="NCrontab" Version="3.2.0" />
</ItemGroup>
</Project>
I have already googled, they say something like Aliases, but in fact on my side it doesn't have this property.
I have already tried:
using v2 = NCrontab;
using System;
using Microsoft.Azure.WebJobs.Extensions.Timers;
namespace ConsoleApp3
{
class Program
{
static void Main(string[] args)
{
v2.CrontabSchedule nCrontabSchedule = v2.CrontabSchedule.Parse("5 4 * * *");
}
}
}
But it didn't work.
How can I solve this problem?
Thank you so much for taking the time to check!
I encountered this same problem. Trying unstalling the NCrontab nuget package and installing NCrontab.Signed instead. This resolved the issue for me.

Use Microsoft.Azure.Storage in Azure Function csx

Somehow I cannot use package Microsoft.Azure.Storage.blob in Azure Function v2 using csx.
In extension.proj I have following:
<PackageReference Include="Microsoft.Azure.Storage.Blob" Version="11.1.0" />
In csx file I have:
using Microsoft.Azure.Storage;
using Microsoft.Azure.Storage.Blob;
And I have error:
run.csx(7,23): error CS0234: The type or namespace name 'Storage' does not exist in the namespace
'Microsoft.Azure' (are you missing an assembly reference?)
Full code is on GitHub: https://github.com/ptrstpp950/cognitive-service-azure-function
1.Are you sure of the extension.proj you are using?
From your code I know you are writing on the portal. So you should create function.proj instead of extension.proj on portal.
2. I see you write <PackageReference Include="Microsoft.Azure.Storage.Blob" Version="11.1.0" /> in .proj file. So you should use #r "Microsoft.WindowsAzure.Storage" instead of
using Microsoft.WindowsAzure.Storage
Below is the code of my function.proj, things works fine on my side. For more details, have a look of this Offical doc.(All of the solution is based on you are using function 2.x. If you are using function 1.x. It is not the same.)
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netstandard2.0</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.Azure.Storage.Blob" Version="11.1.0" />
</ItemGroup>
</Project>
Code of my .crx file:
#r "Newtonsoft.Json"
#r "Microsoft.WindowsAzure.Storage"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Newtonsoft.Json;
using Microsoft.Azure.Storage.Blob;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
You should import the package before using it:
#r "Microsoft.WindowsAzure.Storage"
using Microsoft.WindowsAzure.Storage.Table;
using Microsoft.Extensions.Logging;

Azure Functions - The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)

The Problem
I am trying to create an Azure function leveraging .NET Core 2.2 that accesses a Google Sheet via the Google Sheets API, calls the data, and inserts it into a SQL DB also hosted in Azure.
Here's the error I'm:
This after following this guide.
Note that all the packages are restored.
The code looks roughly like this:
#r "D:\home\site\wwwroot\bin\Google.Apis.Sheets.v4"
#r "D:\home\site\wwwroot\bin\Google.Apis.Auth.OAuth2"
#r "D:\home\site\wwwroot\bin\Google.Apis.Sheets.v4"
#r "D:\home\site\wwwroot\bin\Google.Apis.Sheets.v4.Data"
#r "D:\home\site\wwwroot\bin\Google.Apis.Services"
#r "D:\home\site\wwwroot\bin\System.Data.SqlClient"
using System;
using Google.Apis.Auth.OAuth2;
using Google.Apis.Sheets.v4;
using Google.Apis.Sheets.v4.Data;
using Google.Apis.Services;
using System;
using System.Collections.Generic;
using System.IO;
using System.Data.SqlClient;
public static string DBConn { get; set; }
public static ILogger Log {get; set;}
public static void Run(TimerInfo myTimer, ILogger log)
{
Log=log;
DBConn="MySQLSrvrConnectionString";
try
{
string spreadsheetId = "MyGoogleSheetId";
SheetsService service = GetSheetService();
if(service!=null)
{
DoSomethingFunc(GetInsertCommand(GetSheetVals(service,spreadsheetId)));
}
}
catch (Exception ex)
{
Log.LogInformation($"Error ({DateTime.Now.ToLongDateString()}): {ex.Message}");
}
finally
{
Log.LogInformation($"Function Completed at: {DateTime.Now.ToLongDateString()}");
}
}
I can provide more if need be.
I've also added a function.proj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.2</TargetFramework>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Apis.Sheets.v4" Version="1.40.3.1679" />
<PackageReference Include="System.Data.SqlClient" Version="4.6.1" />
</ItemGroup>
</Project>
Research
Haven't found much, honestly.
This is a similar error code, but it seems to a naming issue - having an apostrophe. My app is called "TopicsProvider"
This talks about a webparts XML file. That's not part of my project at all.
Update 1
Paring the code back to its simplest form, I am able to get it to run with the Google API referenced in function.proj. This code works:
using System;
using System.Collections.Generic;
using System.IO;
using System.Data.SqlClient;
public static void Run(TimerInfo myTimer, ILogger log)
{
log.LogInformation($"HELLO");
}
With function.proj like this:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Apis.Sheets.v4" Version="1.40.3.1679" />
</ItemGroup>
</Project>
What fails is adding using Google.Apis.Sheets.v4; at the top. This gives:
error CS0246: The type or namespace name 'Google' could not be found (are you missing a using directive or an assembly reference?)
Adding #r "Google.Apis.Sheets.v4" or D:\home\site\wwwroot\bin\Google.Apis.Sheets.v4" (note that in the console, there's not a bin folder to begin with...not sure why) to the top, doesn't fix the issue, and changes the error:
2019-09-03T17:48:31.700 [Information] Script for function 'TimerTrigger1' changed. Reloading.
2019-09-03T17:48:31.976 [Error] run.csx(1,1): error CS0006: Metadata file 'Google.Apis.Sheets.v4' could not be found
2019-09-03T17:48:32.051 [Error] run.csx(7,7): error CS0246: The type or namespace name 'Google' could not be found (are you missing a using directive or an assembly reference?)
2019-09-03T17:48:32.075 [Information] Compilation failed.
2019-09-03T17:48:32.549 [Information] Executing 'Functions.TimerTrigger1' (Reason='This function was programmatically called via the host APIs.', Id=bce27519-0236-4754-ac6c-66ae83808801)
2019-09-03T17:48:32.615 [Information] Package references have been updated.
2019-09-03T17:48:32.615 [Information] Restoring packages.
2019-09-03T17:48:32.647 [Information] Starting packages restore
2019-09-03T17:48:36.701 [Information] Restoring packages for D:\local\Temp\32a465b3-8a19-46c8-a533-799a91e1ec09\function.proj...
2019-09-03T17:48:38.434 [Information] Generating MSBuild file D:\local\Temp\32a465b3-8a19-46c8-a533-799a91e1ec09\obj\function.proj.nuget.g.props.
2019-09-03T17:48:38.435 [Information] Generating MSBuild file D:\local\Temp\32a465b3-8a19-46c8-a533-799a91e1ec09\obj\function.proj.nuget.g.targets.
2019-09-03T17:48:38.461 [Information] Restore completed in 2.56 sec for D:\local\Temp\32a465b3-8a19-46c8-a533-799a91e1ec09\function.proj.
2019-09-03T17:48:38.772 [Information] Packages restored.
2019-09-03T17:48:38.996 [Warning] You may be referencing NuGet packages incorrectly. Learn more: https://go.microsoft.com/fwlink/?linkid=2091419
2019-09-03T17:48:39.053 [Error] Function compilation error
Microsoft.CodeAnalysis.Scripting.CompilationErrorException : Script compilation failed.
at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.CreateFunctionTarget(CancellationToken cancellationToken) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 314
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.Azure.WebJobs.Script.Description.FunctionLoader`1.GetFunctionTargetAsync[T](Int32 attemptCount) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\FunctionLoader.cs : 55
at System.Runtime.ExceptionServices.ExceptionDispatchInfo.Throw()
at async Microsoft.Azure.WebJobs.Script.Description.DotNetFunctionInvoker.GetFunctionTargetAsync(Boolean isInvocation) at C:\azure-webjobs-sdk-script\src\WebJobs.Script\Description\DotNet\DotNetFunctionInvoker.cs : 183
2019-09-03T17:48:39.122 [Error] run.csx(1,1): error CS0006: Metadata file 'Google.Apis.Sheets.v4' could not be found
2019-09-03T17:48:39.203 [Error] run.csx(7,7): error CS0246: The type or namespace name 'Google' could not be found (are you missing a using directive or an assembly reference?)
2019-09-03T17:48:39.256 [Error] Executed 'Functions.TimerTrigger1' (Failed, Id=bce27519-0236-4754-ac6c-66ae83808801)
Script compilation failed.
The given assembly name or codebase was invalid. (Exception from HRESULT: 0x80131047)
As I understand it #r isn't necessary, not according to this answer. The packages should load on their own. Neither should I have to upload these files - they're nuget packages that should install automatically.
Update 2
Manually uploading the DLLs does not work. Selecting the file from "Upload", there's a moment where the interface acts like it's loading, but then nothing happens:
What am I missing? Is one of the packages not allowed? Is it a config issue?
Update:
I retry what you do and then it seems worked,
1.create an function.proj file
2.save the file and run:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Apis.Sheets.v4" Version="1.40.3.1679" />
<PackageReference Include="System.Data.SqlClient" Version="4.6.1" />
</ItemGroup>
</Project>
3.add code in .crx file:
#r "Newtonsoft.Json"
using System.Net;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Primitives;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
public static string DBConn = "123456";
public static ILogger Log = null;
public static async Task<IActionResult> Run(HttpRequest req, ILogger log)
{
Log=log;
DBConn="MySQLSrvrConnectionString";
try
{
string spreadsheetId = "MyGoogleSheetId";
//SheetsService service = GetSheetService();
//if(service!=null)
//{
// DoSomethingFunc(GetInsertCommand(GetSheetVals(service,spreadsheetId)));
//}
}
catch (Exception ex)
{
Log.LogInformation($"Error ({DateTime.Now.ToLongDateString()}): {ex.Message}");
}
finally
{
Log.LogInformation($"Function Completed at: {DateTime.Now.ToLongDateString()}");
}
string name = req.Query["name"];
string requestBody = await new StreamReader(req.Body).ReadToEndAsync();
dynamic data = JsonConvert.DeserializeObject(requestBody);
name = name ?? data?.name;
return name != null
? (ActionResult)new OkObjectResult($"Hello, {name}")
: new BadRequestObjectResult("Please pass a name on the query string or in the request body");
}
4.then compilation succeeded:
PS: The google .net client library does not have a method called get sheets service.
Original Answer:
This is my code:
public static class Function1
{
public static string DBConn { get; set; }
public static ILogger Log { get; set; }
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
Log = log;
DBConn = "MySQLSrvrConnectionString";
try
{
string spreadsheetId = "MyGoogleSheetId";
}
catch (Exception ex)
{
Log.LogInformation($"Error ({DateTime.Now.ToLongDateString()}): {ex.Message}");
}
finally
{
Log.LogInformation($"Function Completed at: {DateTime.Now.ToLongDateString()}");
}
return (ActionResult)new OkObjectResult($"");
}
}
I delete the
SheetsService service = GetSheetService();
if(service!=null)
{
DoSomethingFunc(GetInsertCommand(GetSheetVals(service,spreadsheetId)));
}
because i don't find which nuget package has these methods.
and this is my function.proj file:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>netcoreapp2.1</TargetFramework>
<AzureFunctionsVersion>v2</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Google.Apis" Version="1.40.3" />
<PackageReference Include="Google.Apis.Auth" Version="1.40.3" />
<PackageReference Include="Google.Apis.Auth.Mvc" Version="1.40.3" />
<PackageReference Include="Google.Apis.Sheets.v4" Version="1.40.3.1694" />
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="1.0.28" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
and then it works fine. I don't know which packages contain those methods because I don’t know much about Google API. I hope my answer will give you some help.

Issue with using TestContext.Datarow in VSCode

This is my first question here and I am hoping I will be able to receive some help.
To preface what I am trying to do is run a Data Driven test script using MSTest on VSCode.
When I attempt to get the value from the file by using
string webSiteTwo = TestContext.DataRow["Website"];
DataRow is showing an error saying:
'TestContext' does not contain a definition for 'DataRow' and no
extension method 'DataRow' accepting a first argument of type
'TestContext' could be found (are you missing a using directive or an
assembly reference?)
When looking online the DataRow object seems to come from System.Data so I added using System.Data to my program to see if that settled it, but that did not work. I then tried to add using System.Data.Datarow to see if that worked but it seems that I do not have the assemblies for that.
I was wondering if anyone has run into this problem and if they have how did they fix it.
I am using a Macbook Pro, with VSCode 1.20.1, C#
.csproj file includes these References.
<PackageReference Include="Microsoft.NET.Test.Sdk" Version="15.5.0"/>
<PackageReference Include="MSTest.TestAdapter" Version="1.2.0"/>
<PackageReference Include="MSTest.TestFramework" Version="1.2.0"/>
<PackageReference Include="Selenium.WebDriver" Version="3.10.0"/>
<PackageReference Include="Appium.WebDriver" Version="3.0.0.2"/>
<PackageReference Include="System.Data.Common" Version="4.3.0"/>
I have set up both the Datasource and
private TestContext testContextInstance;
public TestContext TestContext
{
get { return testContextInstance; }
set { testContextInstance = value; }
}
According to the docs, the correct Namespace is:
using Microsoft.VisualStudio.TestTools.UnitTesting;
Take a look here: TestContext.DataRow

Categories

Resources