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;
Related
Our azure function was working fine with Newtonsoft.json nuget package version 13.0.1. We updated a code that is not related to the nuget and once deployed to Azure function ( the code referenced via nuget); we got the exception"Could not load file or assembly 'Newtonsoft.Json, Version=13.0.0.0, Culture=neutral, PublicKeyToken=30ad4fe6b2a6aeed'. The system cannot find the file specified "
I am sure it is the runtime issue , we have not changed the newtonsoft reference version. Any idea?
My .csproj code for below Azure Functions Test Case in checking the breaking changes for the NewtonSoft.Json NuGet Package:
<Project Sdk="Microsoft.NET.Sdk">
<PropertyGroup>
<TargetFramework>net6.0</TargetFramework>
<AzureFunctionsVersion>v4</AzureFunctionsVersion>
</PropertyGroup>
<ItemGroup>
<PackageReference Include="Microsoft.NET.Sdk.Functions" Version="4.1.3" />
<PackageReference Include="Newtonsoft.Json" Version="13.0.2" />
</ItemGroup>
<ItemGroup>
<None Update="host.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
</None>
<None Update="local.settings.json">
<CopyToOutputDirectory>PreserveNewest</CopyToOutputDirectory>
<CopyToPublishDirectory>Never</CopyToPublishDirectory>
</None>
</ItemGroup>
</Project>
Check if your Newtonsoft.Json NuGet Package version is compatible with the .NET version and Azure Functions Core Tools version.
The Same issue registered in SO 62853320 and resolved by the user #ThiagoCustodio like downgrading the Version of that NuGet Package and check the version compatibility with the other dependencies used in the Function Code.
Following these MS Doc1 & Doc2, Created a Sample code snippet to test any breaking changes in that NuGet Pakcage with the .NET 6 Azure Functions:
using System;
using System.IO;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Logging;
using Newtonsoft.Json;
namespace KrishNet6FunAppAWJTest
{
public class Account
{
public string Name { get; set; }
public string Email { get; set; }
public DateTime DOB { get; set; }
}
public static class Function1
{
[FunctionName("Function1")]
public static async Task<IActionResult> Run(
[HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req,
ILogger log)
{
log.LogInformation("C# HTTP trigger function processed a request.");
Account account = new Account
{
Name = "John Doe",
Email = "john#nuget.org",
DOB = new DateTime(1980, 2, 20, 0, 0, 0, DateTimeKind.Utc),
};
string json = JsonConvert.SerializeObject(account, Formatting.Indented);
Console.WriteLine(json);
string responseMessage = "Hello Krishna, This HTTP triggered function executed successfully.";
return new OkObjectResult(responseMessage);
}
}
}
Checked with the latest version of the NuGet Package Newtonsoft.Json with the Azure Functions .NET 6 Core with the sample code snippet and working successfully and check by downgrading the NuGet Package Version along with all other Code, Dependencies Versions Compatibility.
I am new to testing/development. I have created a x unit test project in .net core for testing the UI of my website using selenium. My file structure looks like this
This is my appsettings.json:
{
"Base_Url": "https://pretendurl/",
"AllowedHosts": "*"
}
This is my test class:
using Xunit;
using OpenQA.Selenium;
using OpenQA.Selenium.Chrome;
using OpenQA.Selenium.Support.UI;
using System;
using Microsoft.Extensions.Configuration;
using System.Configuration;
namespace XUnitTestProject1.UI.Tests
{
public class HomePageShould
{
[Fact]
public void LoadHomepage()
{
using IWebDriver driver = new ChromeDriver();
var settings = new ConfigurationBuilder()
.AddJsonFile("appsettings.json")
.Build();
var homeUrl = settings["Base_Url"];
driver.Navigate().GoToUrl(homeUrl);
}
}
}
I get this error: The configuration file 'appsettings.json' was not found and is not optional. My test project is in a separate repo from the system I am testing.
You need to update the XUnitTestProject1.UI.Tests.csproj to export your appsettings to the build folder.
<ItemGroup>
<None Update="appsettings.Test.json" CopyToOutputDirectory="PreserveNewest" />
</ItemGroup>
You should reate a separate appsettings.Test.json file in your test project with your test settings, and the code above will copy it to the build folder.
Change the 'Copy to output folder' property of the json file in VS. It needs to be copied to the output folder where the app will run.
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.
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.
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.