What is the replacement for Microsoft.Azure.WebHosts.JobHostConfiguration - c#

Trying to follow #matthoneycutt 's tutorial on Azure IoT Hub it seems like
Microsoft.Azure.WebHosts.JobHostConfiguration vanished between 3.0.0-beta5
and 3.0.0-rc1 releases of Microsoft.Azure.WebHosts.Host in the Microsoft.Azure.WebHosts nuget package?
What would be the approach to get this code up running in Microsoft.Azure.WebHosts 3.0.0-rc1?
var processorHost = new EventProcessorHost(hubName, consumerGroupName, iotHubConnectionString, storageConnectionString,storageContainerName);
processorHost.RegisterEventProcessorAsync<LoggingEventProcessor>().Wait();
var eventHubConfig = new EventHubConfiguration();
eventHubConfig.AddEventProcessorHost(hubName, processorHost);
var configuration = new JobHostConfiguration(storageConnectionString);
configuration.UseEventHub(eventHubConfig);
var host = new JobHost(configuration);
host.RunAndBlock();
Seems related to this post, though in a different context

You should be able to do that thru the AddEventHubs extension methods (available in Microsoft.Azure.WebJobs.Extensions.EventHubs package)
var builder = new HostBuilder()
.ConfigureWebJobs(b =>
{
b.AddAzureStorageCoreServices()
.AddAzureStorage()
.AddEventHubs(eventHubOptions => {
var hubName = "hubName";
var iotHubConnectionString = "iotHubConnectionString";
var storageContainerName = "storageContainerName";
var storageConnectionString = "storageConnectionString";
var consumerGroupName = "consumerGroupName";
var processorHost = new EventProcessorHost(hubName, consumerGroupName, iotHubConnectionString, storageConnectionString, storageContainerName);
eventHubOptions.AddEventProcessorHost("eventHubName", processorHost);
})

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.

Adding multiple event type to same kafka topic in .net

I am trying to add multiple schemas to the same subject in the schema registry, so I have set ValueSubjectNameStrategy to SubjectNameStrategy.TopicRecord, also set the register automatically to AutomaticRegistrationBehavior.Always. But while auto registering the schema it still using the SubjectNameStrategy.Topic strategy.
var schemaRegistryConfig = new SchemaRegistryConfig { Url = "http://localhost:8081", ValueSubjectNameStrategy = SubjectNameStrategy.TopicRecord };
var registry = new CachedSchemaRegistryClient(schemaRegistryConfig);
var builder = new ProducerBuilder<string, SplitLineKGN>(KafkaConfig.Producer.GetConfig(_config.GetSection("KafkaProducer")))
.SetAvroValueSerializer(registry, registerAutomatically: AutomaticRegistrationBehavior.Always)
.SetErrorHandler((_, error) => Console.Error.WriteLine(error.ToString()));
_producerMsg = builder.Build();
await _producerMsg.ProduceAsync("MyTopic", new Message<string, SampleMessage> { Key = key, Value = line });
how to auto register multiple schemas to a topic?
Ensure that you changed a subject naming strategy for a topic
SchemaRegistryConfig.ValueSubjectNameStrategy is deprecated, it should now be configured using the serializer's configuration: code
For producing multiple event types with a single producer you have to use AvroSerializer<ISpecificRecord> as described below:
var schemaRegistryConfig = new SchemaRegistryConfig { Url = "http://localhost:8081" };
using var schemaRegistryClient = new CachedSchemaRegistryClient(schemaRegistryConfig);
var avroSerializerConfig = new AvroSerializerConfig
{
SubjectNameStrategy = SubjectNameStrategy.TopicRecord,
AutoRegisterSchemas = true // (the default)
};
// Assuming this is your own custom code because the Confluent
// producer doesn't have anything like this.
var producerConfig = KafkaConfig.Producer.GetConfig(_config.GetSection("KafkaProducer"));
using var producer = new ProducerBuilder<string, ISpecificRecord>(producerConfig)
.SetValueSerializer(new AvroSerializer<ISpecificRecord>(schemaRegistryClient, avroSerializerConfig))
.SetErrorHandler((_, error) => Console.Error.WriteLine(error))
.Build();
var deliveryResult = await producer.ProduceAsync("MyTopic", new Message<string, ISpecificRecord>
{
Key = key,
Value = line
});
Console.WriteLine($"Delivered to: {deliveryResult.TopicPartitionOffset}");

Consume and Configure Graphql request from .Net C# console application client

I'm trying to consume a Graphql Api from a C# client. For that I'm using the GraphQl.Net Nuget package. The problem is that, I have no idea how to set the Api Url as I don't have HttpRequest object and this results also with additional problems that I can't set the authentcation header and send the token with the request. My code looks like:
public void Post(TestGraphQl.GraphQLQuery query)
{
var inputs = query.Variables.ToInputs();
var queryToExecute = query.Query;
var result = _executer.ExecuteAsync(_ =>
{
_.Schema = _schema;
_.Query = queryToExecute;
_.OperationName = query.OperationName;
_.Inputs = inputs;
//_.ComplexityConfiguration = new ComplexityConfiguration { MaxDepth = 15 };
_.FieldMiddleware.Use<InstrumentFieldsMiddleware>();
}).Result;
var httpResult = result.Errors?.Count > 0
? HttpStatusCode.BadRequest
: HttpStatusCode.OK;
var json = _writer.Write(result);
}
And the caller looks like this:
var jObject = new Newtonsoft.Json.Linq.JObject();
jObject.Add("id", deviceId);
client.Post(new GraphQLQuery { Query = "query($id: String) { device (id: $id) { displayName, id } }", Variables = jObject });
I'm totally new to this topic and appreciate any help. Many thanks!!
This worked out for me. You will need the GraphQL.Client Package. My_class is the class for the deserialization.
var client = new GraphQLHttpClient(Api_Url, new NewtonsoftJsonSerializer());
var request = new GraphQLRequest
{
Query = {query}
};
var response = await client.SendQueryAsync<my_class>(request);
Not sure if you are still looking for it. One can always use GraphQl.Client nuget to achieve this. Sample code to consume is
var query = #"query($id: String) { device (id: $id) { displayName, id } }";
var request = new GraphQLRequest(){
Query = query,
Variables = new {id =123}
};
var graphQLClient = new GraphQLClient("http://localhost:8080/api/GraphQL");
graphQLClient.DefaultRequestHeaders.Add("Authorization", "yourtoken");
var graphQLResponse = await graphQLClient.PostAsync(request);
Console.WriteLine(graphQLResponse.Data);

remote object server is never synchronized

hi i cannot seem to get realm synced with the realm object server i am working xamarin and it's working great localing i just can't seem to sync to the cloud , not even the schema
my code is:
var credentials = Credentials.UsernamePassword(usernameField.Text.ToLower(), passField.Text, createUser: true);
var authURL = new System.Uri("https://game-object.us1.cloud.realm.io/");
var user = await User.LoginAsync(credentials, authURL);
var serverURL = new System.Uri("realm://game-object.us1.cloud.realm.io/~/default");
var configuration = new SyncConfiguration(user, serverURL);
var permission= await user.GetGrantedPermissionsAsync(Recipient.CurrentUser,millisecondTimeout:2111);
var realm = Realm.GetInstance(configuration);
bool m;
if (realm.Config == configuration)
m=true;
var realmSession= realm.GetSession();
var state = realmSession.State;
var permissionCondition = PermissionCondition.UserId(user.Identity);
/* await user.ApplyPermissionsAsync(permissionCondition, "realm://game-object.us1.cloud.realm.io/~/default", AccessLevel.Write);
permission = await user.GetGrantedPermissionsAsync(Recipient.CurrentUser, millisecondTimeout: 2111);
*/
var players = realm.All<Player>();
realm.Write(() =>
{
realm.Add(new Player { Health = 1, name = "apex" });
});
var count = players.Count();
i feel embraced, but the reason i wasn't getting updates is because the client object browser doesn't auto update

Couchbase configuring client programmatically

I want to configure couchbase c# driver programmatically, without web/app.config.
It looks like, configuration does not allow Urls to be set.
var cfg = new CouchbaseClientConfiguration()
{
Bucket = "a",
Urls = new List<Uri> () { .... } // It's readonly
};
Do i have to hack client? Is there another simple way?
this sample from documentation doesn't work?
var config = new CouchbaseClientConfiguration();
foreach (var uri in uris)
{
config.Urls.Add(uri);
}
config.Bucket = bucketName;
config.BucketPassword = bucketPassword;
_cbc = new CouchbaseClient(config);

Categories