Null reference exception on c# grpc request - c#

As the title described, I'm having a problem with this proto message:
(Proto file)
message StreamingRecognizeRequest{
oneof streaming_request{
StreamingRecognitionConfig streaming_config = 1;
bytes audio_content = 2;
}
}
Here is how I called it:
(C# main function)
await voice.RequestStream.WriteAsync(new StreamingRecognizeRequest
{
StreamingConfig =
{
SingleUtterance = true,
InterimResults = true,
Config =
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
MaxAlternatives = 1,
SampleRateHertz = 8000,
Enhanced = true,
SpeechContexts =
{
}
}
}
});
But the debugger keep marking my Stream Recognize Reuqest as null reference exception, the same pattern works fine in NodeJS but I only have this error in C#. Note that the first message send to the gRPC server doesn't require "Audio Content". So what is the root cause of this error and how to solve it? Or this is gRPC bug on c#?
Thank you!

It's pretty funny how I fixed it. Just not putting them inside each other but seperately create new object:
RecognitionConfig regcfg = new RecognitionConfig
{
Encoding = RecognitionConfig.Types.AudioEncoding.Linear16,
MaxAlternatives = 1,
SampleRateHertz = 8000,
Enhanced = true,
};
StreamingRecognitionConfig stc = new StreamingRecognitionConfig
{
Config = regcfg,
SingleUtterance = true,
InterimResults = true,
};
//Create new gRPC stream listener
var voice = vaisclient.StreamingRecognize(meta);
await voice.RequestStream.WriteAsync(new StreamingRecognizeRequest
{
StreamingConfig = stc
}) ;

Related

How to dynamically Configure different "SubscriptionProperties" for Azure ServiceSub Subscription in C#

I'm trying to configure Azure ServiceBus Topic Subscription dynamically(using C#) with all of its properties which we can set up using Azure Portal.
I have tried the below code, but it's giving me an "object reference error" for SubscriptionProperties while setting up its values.
static SubscriptionProperties subscriptionProperties;
static async Task Main(string[] args)
{
adminClient = new ServiceBusAdministrationClient(connectionString);
client = new ServiceBusClient(connectionString);
subscriptionProperties.AutoDeleteOnIdle = TimeSpan.FromDays(14);
subscriptionProperties.DefaultMessageTimeToLive = TimeSpan.FromDays(14);
subscriptionProperties.TopicName = topicName;
subscriptionProperties.SubscriptionName = subscriptionName;
subscriptionProperties.MaxDeliveryCount = 3;
subscriptionProperties.LockDuration = TimeSpan.FromSeconds(5.00);
subscriptionProperties.DeadLetteringOnMessageExpiration = true;
subscriptionProperties.EnableDeadLetteringOnFilterEvaluationExceptions = true;
Console.WriteLine($"Creating the subscription {subscriptionName} with a correlation filter");
if (!await adminClient.SubscriptionExistsAsync(topicName, subscriptionName))
{
await adminClient.CreateSubscriptionAsync(
new CreateSubscriptionOptions(subscriptionProperties),
new CreateRuleOptions(subscriptionFilterName, new CorrelationRuleFilter() { Subject = correlationFilterValue }));
}
}
Let me know if this is the correct way of setting the property values for "SubscriptionProperties" class or how can I do so?
I was able to fix this issue by following this link https://github.com/Azure/azure-sdk-for-net/blob/main/sdk/servicebus/Azure.Messaging.ServiceBus/samples/Sample07_CrudOperations.md#create-a-topic-and-subscription
var client = new ServiceBusAdministrationClient(connectionString);
string subscriptionName = "<subscription_name>";
var subscriptionOptions = new CreateSubscriptionOptions(topicName, subscriptionName)
{
AutoDeleteOnIdle = TimeSpan.FromDays(7),
DefaultMessageTimeToLive = TimeSpan.FromDays(2),
EnableBatchedOperations = true,
UserMetadata = "some metadata"
};
SubscriptionProperties createdSubscription = await client.CreateSubscriptionAsync(subscriptionOptions);
This might be helpful for other readers as well as having similar doubuts.

Can ZXing can read multiple barcode in the single image using C#?

I am trying to read multiple barcodes in a jpg image using the ZXing library. But it's returning only one barcode. I am not getting any source on how I can modify my code so that it read multiple barcodes. My code is:
private string readPDFBarcode(String fname) {
IBarcodeReader reader = new BarcodeReader()
{
AutoRotate = true,
TryInverted = true,
Options = new DecodingOptions
{
TryHarder = true,
PureBarcode = false,
ReturnCodabarStartEnd = true,
PossibleFormats = new List<BarcodeFormat> { BarcodeFormat.CODE_128, BarcodeFormat.CODE_39, BarcodeFormat.UPC_E }
}
};
Bitmap oBitmap = new Bitmap(fname);
var result = reader.Decode(oBitmap);
if (result != null)
{
return result.ToString();
}
else {
return "";
}
}
Any suggestions will be of great help. Thank you!
Try this one:
var results = reader.DecodeMultiple(oBitmap);
If it isn't available in your environment, please give some information about the target .net framework (classic or core).

Making DialogFlow v2 DetectIntent Calls w/ C# (including input context)

So I finally figured out a way to successfully make detect intent calls and provide an input context. My question is whether or not this is the CORRECT (or best) way to do it:
(And yes, I know you can just call DetectIntent(agent, session, query) but I have to provide a input context(s) depending on the request)
var query = new QueryInput
{
Text = new TextInput
{
Text = model.Content,
LanguageCode = string.IsNullOrEmpty(model.Language) ? "en-us" : model.Language,
}
};
var commonContext = new global::Google.Cloud.Dialogflow.V2.Context
{
ContextName = new ContextName(agent, model.sessionId, "my-input-context-data"),
LifespanCount = 3,
Parameters = new Struct
{
Fields = {
{ "Source", Value.ForString(model.Source) },
{ "UserId" , Value.ForString(model.UserId.ToString())},
{ "Name" , Value.ForString(model.FirstName)}
}
}
};
var request = new DetectIntentRequest
{
SessionAsSessionName = new SessionName(agent, model.sessionId),
QueryParams = new QueryParameters
{
GeoLocation = new LatLng {Latitude = model.Latitude, Longitude = model.Longitude},
TimeZone = model.TimeZone ?? "MST"
},
QueryInput = query
};
request.QueryParams.Contexts.Add(commonContext);
// ------------
var creds = GetGoogleCredentials("myCredentials.json");
var channel = new Grpc.Core.Channel(SessionsClient.DefaultEndpoint.Host, creds.ToChannelCredentials());
var client = SessionsClient.Create(channel);
var response = client.DetectIntent(request);
channel.ShutdownAsync();
return response;
Note: I included the explicit ShutDownAsync (it's not in an async call) because I was getting some file locking issues when attempting to re-deploy the WebAPI project (and only after having executed this code).
Thanks
Chris
Updated 4/25: The most basic way I use this is to integrate the user's name into intent responses:
It can also be read from within the webhook/inline fulfillment index.js:
const name = request.body.queryResult && request.body.queryResult.outputContexts && request.body.queryResult.outputContexts[0].parameters.Name

RabbitMQ exception case data

I am new at RabbitMQ and doing first application. But I am confused a bit about exception stuations. For example I get a message from Queue. And an error occured while saving data to database. The data wil be lose. What is the solution of this problem?
var factory = new ConnectionFactory { HostName = "10.1.2.34" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "business.orders", durable: false, exclusive: false, autoDelete: false, arguments: null);
var data = channel.BasicGet(queue: "business.orders", noAck: true);
using (var stream = new MemoryStream(data.Body))
{
var order = (PlaceOrder)new BinaryFormatter().Deserialize(stream);
// Throw exception. ????
}
}
}
you have to use the manual ack:
var data = channel.BasicGet(queue: "business.orders", noAck: false);
insert into DB, if you don't have errors:
channel.BasicAck(result.DeliveryTag, false);
Please read here: https://www.rabbitmq.com/dotnet-api-guide.html
bool noAck = false;
BasicGetResult result = channel.BasicGet(queueName, noAck);
if (result == null) {
// No message available at this time.
} else {
IBasicProperties props = result.BasicProperties;
byte[] body = result.Body;
...
Since noAck = false above, you must also call IModel.BasicAck to acknowledge that you have successfully received and processed the message:
...
// acknowledge receipt of the message
channel.BasicAck(result.DeliveryTag, false);
}
btw I suggest to read also: https://www.rabbitmq.com/dotnet-api-guide.html section:
Retrieving Messages By Subscription ("push API")
The basicGet is slower respect to the EventingBasicConsumer

PCAP.net RAW DNS query not giving any response

I have create a DNS request using C# and PCAP. I checked the request using the wireshark. but there are not response.
I have compared DNS request which have a response. The flags and DNS query values are same.
I cant figure out why the dns resolver is not sending the response. Please help me.
Thank you.
My packet generating method:
private Packet getPacket(string s, string d,string domain)
{
Random r = new Random();
EthernetLayer ethernetLayer =
new EthernetLayer
{
Source = new MacAddress("00:0C:29:E5:FA:36"),
Destination = new MacAddress("00:0c:29:e5:fa:36"),
EtherType = EthernetType.None, // Will be filled automatically.
};
IpV4Layer ipV4Layer =
new IpV4Layer
{
Source = new IpV4Address(s),
CurrentDestination = new IpV4Address(d),
Fragmentation = IpV4Fragmentation.None,
HeaderChecksum = null, // Will be filled automatically.
Identification = 123,
Options = IpV4Options.None,
Protocol = null, // Will be filled automatically.
Ttl = 100,
TypeOfService = 0,
};
UdpLayer udpLayer =
new UdpLayer
{
SourcePort =ushort.MaxValue,
DestinationPort = 53,
Checksum = null, // Will be filled automatically.
CalculateChecksumValue = true,
};
DnsLayer dnsLayer =
new DnsLayer
{
Id = ushort.Parse(r.Next(0,99999).ToString()),
IsResponse = false,
OpCode = DnsOpCode.Query,
IsAuthoritativeAnswer = false,
IsTruncated = false,
IsRecursionDesired = true,
IsRecursionAvailable = false,
FutureUse = false,
IsAuthenticData = false,
IsCheckingDisabled = false,
ResponseCode = DnsResponseCode.NoError,
Queries = new[]
{
new DnsQueryResourceRecord(new DnsDomainName("col.stc.s-msn.com"),
DnsType.A,
DnsClass.Internet),
},
Answers = null,
Authorities = null,
Additionals = null,
DomainNameCompressionMode = DnsDomainNameCompressionMode.All,
};
PacketBuilder builder = new PacketBuilder(ethernetLayer, ipV4Layer, udpLayer, dnsLayer);
return builder.Build(DateTime.Now);
}
}
This is my packet sending function:
private static void performRequest(LivePacketDevice device)
{
using (PacketCommunicator communicator = device.Open(100,PacketDeviceOpenAttributes.Promiscuous,1000))
{
for (int i = 0; i < threadCount; i++)
{
Thread requester= new Thread(() =>
{
try
{
Program p = new Program();
Random r = new Random();
string resolve = resolvers[r.Next(0, resolvers.Count-1)].ToString();
communicator.SendPacket(p.getPacket(destinationIP.ToString(), resolve, domainName));
p = null;
r = null;
}
catch (Exception ex) { Console.WriteLine(ex.Message); }
});
requester.Start();
Thread.Sleep(1000);
}
}
}
I checked your "getPacket" method but have not found obvious problem, so I just tried it, of course, changed mac addresses and IP addresses, I did get response.
But your packet sending method seems wrong, what is the "DestinationIP", it should source IP, in other words, local IP address of the selected device.

Categories