GoogleCredential.FromFile stuck and throw exception - c#

I have a strange issue:
if (_Credential is null && OsEnvironment.IsLocal)
{
_Credential = GoogleCredential.FromFile(path);
}
return _Credential;
this code in my local PC stuck and after some time throw exception but in another computer (virtual computer) it run ok:
The type initializer for 'System.Security.Cryptography.CngKeyLite' threw an exception.
StackTrace: at System.Security.Cryptography.CngKeyLite.ImportKeyBlob(String blobType, ReadOnlySpan`1 keyBlob, Boolean en
crypted, ReadOnlySpan`1 password)
at System.Security.Cryptography.RSAImplementation.RSACng.ImportKeyBlob(Byte[] rsaBlob, Boolean includePrivate)
at System.Security.Cryptography.RSAImplementation.RSACng.ImportParameters(RSAParameters parameters)
at Google.Apis.Auth.OAuth2.ServiceAccountCredential.Initializer.FromPrivateKey(String privateKey)
at Google.Apis.Auth.OAuth2.DefaultCredentialProvider.CreateServiceAccountCredentialFromParameters(JsonCredentialParameters credentialPara
meters)
at Google.Apis.Auth.OAuth2.DefaultCredentialProvider.CreateDefaultCredentialFromParameters(JsonCredentialParameters credentialParameters)
at Google.Apis.Auth.OAuth2.DefaultCredentialProvider.CreateDefaultCredentialFromStream(Stream stream)
at Google.Apis.Auth.OAuth2.GoogleCredential.FromStream(Stream stream)
at Google.Apis.Auth.OAuth2.GoogleCredential.FromFile(String path)
at Irony.Anaconda.Helpers.CredentialManager.GetCredential(String path) in
one more things is that it dont work in my PC as console app (work great as webapi)
work with Google.Cloud.SecretManager.V1 1.5.0
Is anyone know how to fix it ?

Related

WebSocketSharp cannot catch exceptions

I am having trouble catching and handling exceptions thrown by websocketsharp
When I connect to the server with the client, and I close the client just by ALT+F4 or X button, the server receives the exception of connection forcibly closed.
Even though, these exceptions won't crash the program, this will cause the console to be spammed by those exceptions, important messages and logs will be pushed down and nothing can be read (there is a lot of clients).
This is the exception:
7/28/2021 6:41:56 AM|Fatal|<>c__DisplayClass71_0.<receiveRequest>b__0:0|WebSocketSharp.WebSocketException: An exception has occurred while reading an HTTP request/response.
---> System.IO.IOException: Unable to read data from the transport connection: An existing connection was forcibly closed by the remote host..
---> System.Net.Sockets.SocketException (10054): An existing connection was forcibly closed by the remote host.
--- End of inner exception stack trace ---
at System.Net.Sockets.NetworkStream.Read(Span`1 buffer)
at System.Net.Sockets.NetworkStream.ReadByte()
at WebSocketSharp.HttpBase.readHeaders(Stream stream, Int32 maxLength)
at WebSocketSharp.HttpBase.Read[T](Stream stream, Func`2 parser, Int32 millisecondsTimeout)
--- End of inner exception stack trace ---
at WebSocketSharp.HttpBase.Read[T](Stream stream, Func`2 parser, Int32 millisecondsTimeout)
at WebSocketSharp.HttpRequest.Read(Stream stream, Int32 millisecondsTimeout)
at WebSocketSharp.Net.WebSockets.TcpListenerWebSocketContext..ctor(TcpClient tcpClient, String protocol, Boolean secure, ServerSslConfiguration sslConfig, Logger logger)
at WebSocketSharp.Ext.GetWebSocketContext(TcpClient tcpClient, String protocol, Boolean secure, ServerSslConfiguration sslConfig, Logger logger)
at WebSocketSharp.Server.WebSocketServer.<>c__DisplayClass71_0.<receiveRequest>b__0(Object state)
I tried using
public class Echo : WebSocketBehavior
{
protected override void OnError(ErrorEventArgs e)
{
//handle
}
I tried wrapping the websocket server in a try catch
try
{
string path = "ws://localhost:111";
WebSocketServer wssv = new WebSocketServer(path);
wssv.Start();
while (Console.ReadKey(true).Key != ConsoleKey.Enter) { }
wssv.Stop();
} catch { }
Nothing works, the exception will the thrown and shown on the console whatever I tried.
So the question is, how do you catch those exceptions?
I was able to solve the issue disabling/hiding completely the logs output.
public static void Disable(this Logger logger)
{
var field = logger.GetType().GetField("_output", BindingFlags.NonPublic | BindingFlags.Instance);
field?.SetValue(logger, new Action<LogData, string>((d, s) => { }));
}

Using static async Task in order to get a mac vendor in C# LookupMac(string MacAddress)

I'm going to be modifying a script I've found at Rosetta Code which will check MAC addresses against the excellent api at http://api.macvendors.com.
I can do this in Python and Go without any problem but in C# (because it has to be run from a desktop via an Icon) I'm running into problems...not least of all is the fact that the code doesn't make a whole lot of sense to me. I've omitted (from here) the 'Using...' lines
class Program
{
static async Task<string> LookupMac(string MacAddress)
{
var uri = new Uri("http://api.macvendors.com/" + WebUtility.UrlEncode(MacAddress));
using (var wc = new HttpClient())
return await wc.GetStringAsync(uri);
}
static void Main(string[] args)
{
foreach (var mac in new string[] { "88:53:2E:67:07:BE", "FC:FB:FB:01:FA:21", "D4:F4:6F:C9:EF:8D" })
Console.WriteLine(mac + "\t" + LookupMac(mac).Result);
Console.ReadLine();
}
}
I'm falling over at the whole async side of things! When I try running the code here is the error message from Vis Studio:
System.AggregateException
HResult=0x80131500
Message=One or more errors occurred.
Source=mscorlib
StackTrace:
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at System.Threading.Tasks.Task`1.get_Result()
at GetMacVend.Program.Main(String[] args) in C:\Users\wildm\VisC#\GetMacVend\GetMacVend\Program.cs:line 24
Inner Exception 1:
TaskCanceledException: A task was canceled.

RandomNumberGenerator.GetBytes throws "Unable to load DLL 'BCrypt.dll'"

I have an aws Lambda function that I am making using .NET core. When running the lambda function I get the following error:
(Unable to load DLL 'BCrypt.dll': The specified module could not be found.
(Exception from HRESULT: 0x8007007E)): AggregateException
at System.Threading.Tasks.Task.ThrowIfExceptional(Boolean includeTaskCanceledExceptions)
at System.Threading.Tasks.Task`1.GetResultCore(Boolean waitCompletionNotification)
at lambda_method(Closure , Stream , Stream , ContextInfo )
at Interop.BCrypt.BCryptGenRandom(IntPtr hAlgorithm, Byte* pbBuffer, Int32 cbBuffer, Int32 dwFlags)
at Interop.BCrypt.BCryptGenRandom(Byte[] pbBuffer, Int32 cbBuffer)
at System.Security.Cryptography.RNGCryptoServiceProvider.GetBytes(Byte[] data)
at User.Util.GetSalt(ILambdaContext context)
at User.Functions.d__1.MoveNext()
It is being thrown from the following code:
public static string GetSalt()
{
byte[] bytes = new byte[128 / 8];
using(var keyGenerator = RandomNumberGenerator.Create())
{
keyGenerator.GetBytes(bytes);
return BitConverter.ToString(bytes).Replace("-", "").ToLower();
}
}
The code is breaking on this line:
keyGenerator.GetBytes(bytes);
It was my belief that .net core should work well cross platform (As aws uses unix machines).
From everything I can find online this seems to be the best way to do this.

RabbiMQ C# driver Causes System.AccessViolationException

We have an ASP.Net WebAPI 2.0 application that publishes messages to our RabbitMQ Server. In 99% of the cases, all is well... but randomly the application terminates with a System.AccessViolationException for no apparent reason.
How can I prevent this failure? Could it be related to our recent upgrade to the 3.6.6 C# driver (it worked fine before the upgrade)?
Things I have already eliminated:
A new IModel is used for each publish (I know IModel is not thread
safe)
A call is made to CreateConnection for each call as well (I
know I could reuse the connection, but we do not currently). The connection is AutoClose = true;
The Channel is used in a using block... so it is disposed each time
Here is a sample stack trace of where it explodes:
Exception Details
System.AccessViolationException
Attempted to read or write protected
memory. This is often an indication that other memory is corrupt.
at System.Net.UnsafeNclNativeMethods.SafeNetHandlesXPOrLater.GetAddrInfoW(String
nodename, String servicename, AddressInfo& hints, SafeFreeAddrInfo&
handle)
at System.Net.Dns.TryGetAddrInfo(String name, AddressInfoHints flags, IPHostEntry& hostinfo)
at System.Net.Dns.InternalGetHostByName(String hostName, Boolean includeIPv6)
at System.Net.Dns.GetHostAddresses(String hostNameOrAddress)
at RabbitMQ.Client.TcpClientAdapter.BeginConnect(String host, Int32 port, AsyncCallback requestCallback, Object state)
at RabbitMQ.Client.Impl.SocketFrameHandler.Connect(ITcpClient socket, AmqpTcpEndpoint endpoint, Int32 timeout)
at RabbitMQ.Client.Impl.SocketFrameHandler..ctor(AmqpTcpEndpoint endpoint, Func`2 socketFactory, Int32 connectionTimeout, Int32
readTimeout, Int32 writeTimeout)
at RabbitMQ.Client.Framing.Impl.ProtocolBase.CreateFrameHandler(AmqpTcpEndpoint
endpoint, Func'2 socketFactory, Int32 connectionTimeout, Int32
readTimeout, Int32 writeTimeout)
at RabbitMQ.Client.ConnectionFactory.CreateConnection(IList'1 endpoints, String clientProvidedName)
And another
System.Net.UnsafeNclNativeMethods+SafeNetHandlesXPOrLater.GetAddrInfoW(System.String,
System.String, System.Net.AddressInfo ByRef,
System.Net.SafeFreeAddrInfo ByRef)
System.Net.Dns.TryGetAddrInfo(System.String, System.Net.AddressInfoHints, System.Net.IPHostEntry ByRef)
System.Net.Dns.InternalGetHostByName(System.String, Boolean)
System.Net.Dns.GetHostAddresses(System.String)
RabbitMQ.Client.TcpClientAdapter.BeginConnect(System.String, Int32, System.AsyncCallback, System.Object)
RabbitMQ.Client.Impl.SocketFrameHandler.Connect(RabbitMQ.Client.ITcpClient,
RabbitMQ.Client.AmqpTcpEndpoint, Int32)
RabbitMQ.Client.Impl.SocketFrameHandler..ctor(RabbitMQ.Client.AmqpTcpEndpoint,
System.Func'2,
Int32, Int32, Int32)
RabbitMQ.Client.Framing.Impl.ProtocolBase.CreateFrameHandler(RabbitMQ.Client.AmqpTcpEndpoint,
System.Func'2,
Int32, Int32, Int32)
RabbitMQ.Client.ConnectionFactory.CreateConnection(System.Collections.Generic.IList'1,
System.String)
I'm not sure exactly why your error is occurring I would need to see some of your code for that, but I use RabbitMQ quite a bit and to publish I use a class like so:
(Changed some parts as they are not relevant for your situation such as encryption, compression etc. But this would be the basic format of it)
using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Framing;
namespace Messaging
{
public class MessageSender : IDisposable
{
private const string EXCHANGE_NAME = "MY_EXCHANGE";
private readonly ConnectionFactory factory;
private readonly IConnection connection;
private readonly IModel channel;
public MessageSender(string address, string username, string password)
{
factory = new ConnectionFactory {UserName = username, Password = password, HostName = address};
connection = factory.CreateConnection();
channel = connection.CreateModel();
channel.ExchangeDeclare(EXCHANGE_NAME, "topic");
}
public void Send(string payload, string topic)
{
var prop = new BasicProperties();
var data = Encoding.ASCII.GetBytes(payload);
channel.BasicPublish(EXCHANGE_NAME, topic.ToUpper(), prop, data);
}
public void Dispose()
{
try
{
channel.Dispose();
connection.Dispose();
}
catch (Exception e)
{
Console.WriteLine(e);
}
}
}
}
The idea is to let you issue multiple calls or a single one and dispose of the class when you wish. Wrap it with a using statement and your set.
Never had a single problem with this in about 3-4 years of using it, so you might be able to contrast this vs your code to find the differences.
Managed to get a (partial) resolution on this from RabbitMQ users group.
Details here: Rabbit MQ Users Group
Basic idea is that the IConnection object should be shared, as it is heavy to open and close. Only the IModel should be opened fresh for each thread

E_ACCESSDENIED (0x8007005) when calling DsDevice.GetDevicesOfCat() function from DirectShowLib

I have the following piece of code which is called from a IIS web service:
private IBaseFilter CreateFilter(Guid category, string friendlyname)
{
object source = null;
Guid iid = typeof(IBaseFilter).GUID;
foreach (DsDevice device in DsDevice.GetDevicesOfCat(category))
if (device.Name != null && device.Name.CompareTo(friendlyname) == 0)
{
device.Mon.BindToObject(null, null, ref iid, out source);
break;
}
return (IBaseFilter)source;
}
When DsDevice.GetDevicesOfCat()is called, the service throws the following exception:
Creating an instance of the COM component with CLSID
{62BE5D10-60EB-11D0-BD3B-00A0C911CE86} from the IClassFactory failed
due to the following error: 80070005 (Exception from
HRESULT: 0x80070005 (E_ACCESSDENIED)).
at DirectShowLib.DsDevice.GetDevicesOfCat(Guid FilterCategory) at
MyVideoRenderer.CreateFilter(Guid category, String
friendlyname) at MyVideoRenderer.Constructor(String
filepath, Int32 width, Int32 height, ISampleGrabberCB BufferCB,
ISampleGrabberCB BufferCBSource, Rectangle sourceRect)
This has happened both in a server running Windows Server 2008 R2 and a PC running Windows 7. I do have a Windows Form which calls the same code and it works in both machines.
I don't know which category/filter caused this error, but it does require a couple of .ax/dll to be regsvr32-ed before usage. These dlls are inside the webservice directory, so there should be no problem with permissions.
Any tips on how to fix this? Thanks.

Categories