Azure function app: "Microsoft.ServiceBus cannot be found" - azure-iot-hub

I want to use EventData class to read event message from iot hub but I keep getting error below regarding adding the namespace Microsoft.ServiceBus.Messaging
Appreciate any help to identify what could be wrong?
#r "Newtonsoft.Json"
#r "Microsoft.ServiceBus"
using System;
using Newtonsoft.Json.Linq;
using Microsoft.ServiceBus.Messaging;
public static void Run(EventData myIoTHubMessage, out object outDocument, ILogger log)
{
dynamic msg = JObject.Parse(myIoTHubMessage);
outDocument = new {msg};
log.LogInformation($"C# IoT Hub trigger function processed a message: {myIoTHubMessage}");
}
2020-06-06T23:05:31Z [Error] Function compilation error
2020-06-06T23:05:31Z [Error] run.csx(8,24): error CS0246: The type or namespace name 'EventData' could not be found (are you missing a using directive or an assembly reference?)
2020-06-06T23:05:31Z [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?)
2020-06-06T23:05:31Z [Error] run.csx(2,1): error CS0006: Metadata file 'Microsoft.ServiceBus' could not be found
2020-06-06T23:05:31Z [Warning] You may be referencing NuGet packages incorrectly. Learn more: https://go.microsoft.com/fwlink/?linkid=2091419

So, managed to get this working by adding in "using Microsoft.Azure.EventHubs;"
The code below works for me at the moment but not sure about best practices etc...
To figure it out I went back and created a new EventHub Trigger Function and took the code from there since the template already includes code using the EventData class. Not sure why they wouldnt use a similar template with IoT Hub trigger as well?
#r "Newtonsoft.Json"
#r "Microsoft.Azure.EventHubs"
using System;
using System.Text;
using Newtonsoft.Json.Linq;
using Microsoft.Azure.EventHubs;
public static void Run(EventData myIoTHubMessage, out object outDocument, ILogger log)
{
string messageBody = Encoding.UTF8.GetString(myIoTHubMessage.Body.Array,
myIoTHubMessage.Body.Offset, myIoTHubMessage.Body.Count);
dynamic msg = JObject.Parse(messageBody);
var deviceId = myIoTHubMessage.SystemProperties["iothub-connection-device-id"];
var enqueuedtime = myIoTHubMessage.SystemProperties["iothub-enqueuedtime"];
var messageSource = myIoTHubMessage.SystemProperties["iothub-message-source"];
outDocument = new {msg, deviceId, enqueuedtime, messageSource};
log.LogInformation($"C# IoT Hub trigger function processed a message {myIoTHubMessage}");
}

Related

Error CS0246 The type or namespace name 'Microsoft' could not be found

i have downloaded project from github https://github.com/miroslavpopovic/production-ready-apis-sample-2.2 . while i build the project getting lot of compilation error coming .
Error CS0246 The type or namespace name 'Microsoft' could not be found (are you missing a using directive or an assembly reference
code
using BoardGamesApi.Data;
using BoardGamesApi.Models;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging;
using Microsoft.AspNetCore.Http;
namespace BoardGamesApi.Controllers
{
/// <summary>
/// Games endpoint of Board Games API.
/// </summary>
[ApiController]
[ApiConventionType(typeof(DefaultApiConventions))]
[ApiVersion("1", Deprecated = true)]
[Authorize]
[Route("api/games")]
[Route("api/v{api-version:apiVersion}/games")]
public class GamesController : Controller
{
private readonly IGamesRepository _gamesRepository;
private readonly ILogger<GamesController> _logger;
........
}

Sap.Data.SQLAnywhere.SAException: Cannot find the language resource file (dblgen17.dll) when connecting to Sybase SQL Anywhere using .NET

I am trying to establish a connection to a Sybase database, using Sap.Data.SQLAnywhere. Using an SQL Anywhere client works perfect from a workstation, but I am having some trouble running the code within an Azure Function.
This is the beginning of my simple code:
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs;
using Microsoft.Azure.WebJobs.Extensions.Http;
using System.Data.SqlClient;
using Microsoft.Extensions.Logging;
using System;
using Sap.Data.SQLAnywhere;
namespace SBCTest
{
public static class SybaseTest
{
static string DB_CS_SOURCE = "Host=myIP;UID=myUID;PWD=myPWD;Data Source=myDb;"; static int bulkSize = 5000;
[FunctionName("SybaseTest")]
public static async Task<HttpResponseMessage> Run([HttpTrigger(AuthorizationLevel.Function, "get", "post", Route = null)]HttpRequestMessage req, ILogger log)
{
try
{
var dbSourceCon = new SAConnection()
dbSourceCon.ConnectionString = DB_CS_SOURCE;
dbSourceCon.Open();
//etc... etc...
The problem I am facing, which I can't seem to manage is the following error I get when running the app:
[Error] System.TypeInitializationException: The type initializer for 'Sap.Data.SQLAnywhere.SAConnection' threw an exception. ---> Sap.Data.SQLAnywhere.SAException: Cannot find the language resource file (dblgen17.dll).
at Sap.Data.SQLAnywhere.SAUnmanagedDll..ctor()
at Sap.Data.SQLAnywhere.SAUnmanagedDll.get_Instance()
at Sap.Data.SQLAnywhere.SAConnection..cctor()
--- End of inner exception stack trace ---
at Sap.Data.SQLAnywhere.SAConnection..ctor()
at SBCTest.SybaseTest.<Run>d__3.MoveNext()
dblgen17.dll is included in the SAP SQL Anywhere Database Client found here, and has been added to my project, with Build Action set to None, and Copy to Output Directory set to Copy Always.
The "missing file" dblgen17.dll can be found in /site/wwwroot/bin after publish, as expected, along with Sap.Data.SQLAnywhere.v4.5.dll.
Why does it still say that it's missing? My Google results point me to the fact that it might have something to do with the PATH variable, but since this is an Azure Function I'm not sure what to do here.
I also noted an additional, odd behavior, described below.
Sometimes, sporadically when re-publishing a non-altered code, I can also get this error message all of a sudden:
[Error] Sap.Data.SQLAnywhere.SAException (0x80004005)
at Sap.Data.SQLAnywhere.SAConnection.Open()
at SBCTest.SybaseTest.<Run>d__3.MoveNext()
How can I make my code recognize the file, and hopefully connect successfully?
In my case, it worked out by reseting IIS, this can be done via cmd, with the iisreset command.
Here's the solution that I found based on this SO answer and it actually worked!
/// <summary>
/// Updates PATH variable in hosting instance to allow referring to items in this project's /bin folder.
/// Very helpful with Azure.
/// </summary>
public static void CheckAddBinPath()
{
// find path to 'bin' folder
var binPath = Path.Combine(new string[] { AppDomain.CurrentDomain.BaseDirectory, "bin" });
// get current search path from environment
var path = Environment.GetEnvironmentVariable("PATH") ?? "";
// add 'bin' folder to search path if not already present
if (!path.Split(Path.PathSeparator).Contains(binPath, StringComparer.CurrentCultureIgnoreCase))
{
path = string.Join(Path.PathSeparator.ToString(), new string[] { path, binPath });
Environment.SetEnvironmentVariable("PATH", path);
}
}
Then in Application_Start
// Sometimes files aren't loaded properly from bin. Hint to the app to load from /bin, too.
CheckAddBinPath();

ASP.NET Core using Azure KeyVault - Error on delegating the KeyVaultClient.AuthenticationCallback

I want to integrate my project on ASP.NET Core 1.0 with Microsoft Azure KeyVault. But it seems like Microsoft.Azure.KeyVault package is not compatible yet with "netcoreapp1.0" framework (I try to download the package using NuGet package manager and the "incompatible package" error message is shown). Therefore I import "net451" framework in the project.json shown in this block:
"frameworks": {
"netcoreapp1.0": {
"imports": [
"net451",
"dotnet5.6",
"portable-net45+win8"
]
}
},
After importing "net451" framework, the error is now gone. Now I want to initiate a new KeyVaultClient class shown in this block:
public void GetKeyVaultSecret()
{
var keyVaultClient = new KeyVaultClient(this.GetTokenAsync);
// ....
}
private async Task<string> GetTokenAsync(string authority, string resource, string scope)
{
var authenticationContext = new AuthenticationContext(authority);
var authenticationResult =
await authenticationContext.AcquireTokenAsync(resource, this.clientAssertionCertificate);
return authenticationResult.AccessToken;
}
The problem is I got this error message on this.GetTokenAsync which I have search the solution for hours without any luck: Argument 1:cannot convert from 'method group' to 'KeyVaultClient.AuthenticationCallback'
If I change
var keyVaultClient = new KeyVaultClient(this.GetTokenAsync);
to:
var keyVaultClient = new KeyVaultClient((authority, resource, scope) => this.GetTokenAsync(authority, resource, string.Empty));
I still got error message: Cannot convert lambda expression to type 'KeyVaultClient.AuthenticationCallback' because it is not a delegate type
Anybody knows how to solve this problem? Thanks.
Regards,
Alvin
The error cannot convert from 'method group' is because you have overloads or extensions (ie more than one method) with the name GetTokenAsync. Try to rename one of them, and it should work.
So after a long time abandoning this question, I've decided to look into it once more thanks to #fernacolo's answer. Turns out that at that time I used version 1.0.0 of the Microsoft.Azure.KeyVault package (which was the latest version back then, shown in Figure 1). Now version 2.0.0 of the package is available and when I find the changelog, I saw this post https://learn.microsoft.com/en-us/azure/key-vault/key-vault-dotnet2api-release-notes which stated that ".NET Core is supported by the 2.0 version of the Azure Key Vault .NET/C# library".
Figure 1. Version history of Microsoft.Azure.KeyVault package
The error is now gone without the need of importing "net451" framework in the project.json.

Move to Web API RC, Get: Method not found: 'System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()'

I moved a site from WebAPI Beta to WebAPI RC, and am now getting an error upon loading the site: Method not found: 'System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()'.
The error occurs the first time that I am trying to register my AutoFacWebApiDependencyResolver (per instructions here):
var resolver = new AutofacWebApiDependencyResolver(IoCManager.Container);
GlobalConfiguration.Configuration.DependencyResolver = resolver;
The stacktrace shows the following:
[MissingMethodException: Method not found: 'System.Web.Http.Services.DependencyResolver System.Web.Http.HttpConfiguration.get_ServiceResolver()'.]
System.Web.Http.GlobalConfiguration.<.cctor>b__0() +0
System.Lazy`1.CreateValue() +12775823
System.Lazy`1.LazyInitValue() +355
StatusBoard.Web.MvcApplication.RegisterDependencyInjection() in C:\path-tp-app\Global.asax.cs:125
StatusBoard.Web.MvcApplication.Application_Start() in C:\path-to-app\Global.asax.cs:75
Based on this, it appears that the error is occurring during initialization of the static GlobalConfiguration class. When I drill down into the source for that class, I see the following:
private static Lazy<HttpConfiguration> _configuration = new Lazy<HttpConfiguration>((Func<HttpConfiguration>) (() =>
{
local_0 = new HttpConfiguration((HttpRouteCollection) new HostedHttpRouteCollection(RouteTable.Routes));
local_0.get_ServiceResolver().SetService(typeof (IBuildManager), (object) new WebHostBuildManager());
return local_0;
}));
private static Lazy<HttpControllerDispatcher> _dispatcher = new Lazy<HttpControllerDispatcher>((Func<HttpControllerDispatcher>) (() => new HttpControllerDispatcher(GlobalConfiguration._configuration.Value)));
public static HttpConfiguration Configuration
{
get
{
return GlobalConfiguration._configuration.Value;
}
}
The fourth line here seems to be the issue - it is trying to call a get_ServiceResolver() method that no longer exists in the HttpConfiguration class (should be DependncyResolver instead, probably).
Is this just a bug with the RC for WebAPI? Is there some way that I can get around this? Or am I stuck in some DLL/Nuget hell (and if so, how can I extricate myself)?
be sure to include the correct nuget package (RC!) and install the new mvc4rc on the machine where you build your package.
Dependency Resolution has been completely re-written in RC. Best is to uninstall beta DLLs and then your problems most likely go away.
Just uninstall the one flagged as "(bundle)" in windows' "Uninstall a program".

The type initializer for 'NHibernate.Cfg.Configuration' threw an exception

After upgrading from nhibernate 1.0.4.0 to nhibernate 3.3 im encountering the following error when I try to run "Configuration cfg = new Configuration();"
System.TypeInitializationException was caught
Message="The type initializer for 'NHibernate.Cfg.Configuration' threw an exception."
Source="NHibernate"
TypeName="NHibernate.Cfg.Configuration"
StackTrace:
at NHibernate.Cfg.Configuration..ctor()
at KEH.Web.Data.NHibernateUtil..cctor() in F:\Projects\KEH nHibernate\KEHWeb\Data\Data\NHibernateUtil.cs:line 24
InnerException: System.NotSupportedException
Message="The invoked member is not supported in a dynamic assembly."
Source="mscorlib"
StackTrace:
at System.Reflection.Emit.AssemblyBuilder.get_Location()
at log4net.Util.SystemInfo.AssemblyLocationInfo(Assembly myAssembly)
at log4net.Core.DefaultRepositorySelector.GetInfoForAssembly(Assembly assembly, String& repositoryName, Type& repositoryType)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType, String repositoryName, Boolean readAssemblyAttributes)
at log4net.Core.DefaultRepositorySelector.CreateRepository(Assembly repositoryAssembly, Type repositoryType)
at log4net.Core.DefaultRepositorySelector.GetRepository(Assembly repositoryAssembly)
at log4net.Core.LoggerManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Assembly repositoryAssembly, String name)
at log4net.LogManager.GetLogger(Type type)
at lambda_method(ExecutionScope , Type )
at NHibernate.Log4NetLoggerFactory.LoggerFor(Type type)
at NHibernate.LoggerProvider.LoggerFor(Type type)
at NHibernate.Cfg.Configuration..cctor()
InnerException:
Any help would be greatly appreciated.
The NHibernateUtil class code is as follows :
public class NHibernateUtil
{
private static readonly Configuration cfg;
private static readonly ISessionFactory sessionFactory;
private static readonly ILog logger = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
static NHibernateUtil()
{
try
{
logger.Debug("Before Initializing NHibernate");
cfg = new Configuration();
cfg.AddAssembly("KEH.Web.Data");
sessionFactory = cfg.BuildSessionFactory();
logger.Debug("Initialized NHibernate");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
public static ISession OpenSession()
{
logger.Debug("Before Getting Connection");
return sessionFactory.OpenSession();
}
}
I had the same problem.
The actual reason was i used a library that used old version of log4net.
NHibernate tries to use it if find.
So i had to force it to use (or actually not use) other logger by adding such line:
LoggerProvider.SetLoggersFactory(new NoLoggingLoggerFactory());
Not sure why it's not working, but I'd just replace
cfg.AddAssembly("KEH.Web.Data");
with
cfg.AddAssembly(typeof(Entity).Assembly);
where Entity is some class that exists in the assembly of your mapping files.
For the benefit of others who might find this question via Google:
For us, this error was a red-herring. Our app ran fine until we deployed a new component AND it would fail (in an unknown way) AND IIS would recycle the app pool. The problem was an HTML to JPG component we were using was erroring somehow and causing all of our w3wp.exe worker processes to consume maximum CPU. When the app pool was recycled via IIS, the entire site would go down and NHibernate would throw this error continuously until an iisreset. Before the recycle, the site would still be very responsive even with the CPU load.
While we still don't know how the component was failing or why it was cascading to problems with NHibernate initializing, the point is it was a red-herring. Be sure to watch for this error "suddenly" occurring shortly after a new deployment, and keep logs of your CPU utilization so it can help spot when trouble is brewing. Finally, if the downtime is happening near the same time every day, it's probably an automatic IIS app pool recycle, and that should be another clue that something is bugging out your application and surfacing during the recycle.
Ultimately, we disabled the HTML to JPG component until a workaround can be found and our up-time sprung back to 100%.
Hope this helps someone.