Azure service bus subscription metrics - c#

I am trying to find the best way to see the last date a subscription in a topic was accessed via c# (SDK or otherwise) i.e. to purge the queue if not accessed in over x hours. I know there is that functionality built into the service bus explorer but have not been able to find any SDK functionality. If anyone could point me in the right direction it would be appreciated.

Please see the code below. It uses Azure.Messaging.ServiceBus SDK. The properties you're interested in is available in SubscriptionRuntimeProperties class.
using System;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus.Administration;
namespace ConsoleApp1
{
class Program
{
static async Task Main(string[] args)
{
string connectionString =
"connection-string";
string topicName = "topic-name";
string subscriptionName = "subscription-name";
ServiceBusAdministrationClient administrationClient = new ServiceBusAdministrationClient(connectionString);
var result = await administrationClient.GetSubscriptionRuntimePropertiesAsync(topicName, subscriptionName);
Console.WriteLine(result.Value.AccessedAt.ToString("yyyy-MM-ddTHH:mm:ss"));
}
}
}

Related

Check for completed pipeline in Azure DevOps from WorkItem

For a project I'm working on I have to get a Pull Request and Repository from an Azure DevOps WorkItem ID.
I'm using the Microsoft.TeamFoundationServer.Client NuGet-Package for this.
Now i also want to be able to check if a build pipeline ran successfully before moving on to further steps.
After trying to figure it out myself and not finding a single article on how to do that, I'm just gonna ask the question myself.
So, I already have:
the WorkItem object
the GitRepository object
the PullRequest object
And I want:
some form of pipeline object of that specific Pull Request/Commit
I hope there even is a way to get that.
Any help or references are apprechiated. Thanks!
I'm working on I have to get a Pull Request and Repository from an
Azure DevOps WorkItem ID.
For pull request that related to work item, I can write a C# code for you. But for the repository, I think there doesn't have a relationship between repository itself and work item in DevOps concept(link commit and work item is possible.).
Now i also want to be able to check if a build pipeline ran
successfully before moving on to further steps.
Do you mean you want the pipeline run status related to pull request? I checked the sdk definition, there doesn't have such definition, also no in the REST API. A possible solution is following the f12 to capture the API to get the build pipeline run id and it status.
Just a demo:
using System;
using System.Threading.Tasks;
using Microsoft.TeamFoundation.Build.WebApi;
using Microsoft.TeamFoundation.SourceControl.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi;
using Microsoft.TeamFoundation.WorkItemTracking.WebApi.Models;
using Microsoft.VisualStudio.Services.Common;
using Microsoft.VisualStudio.Services.WebApi;
namespace GetPipelineResults
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
string url_string = "https://dev.azure.com/xxx/";
string personalAccessToken = "xxx";
Uri orgUrl = new Uri(url_string);
string project = "xxx";
int workitemId = 122;
var workitem = GetPullRequestAndRepositoryFromWorkItemId(orgUrl,personalAccessToken,workitemId);
var pullRequestUrl = workitem.Result.Relations[0].Url.ToString();
var pullRequestUrl2 = pullRequestUrl.Substring(pullRequestUrl.LastIndexOf('/') + 1);
string[] pullRequestUrl2Array = pullRequestUrl2.Split("%2F");
string pullRequestIdString = pullRequestUrl2Array[pullRequestUrl2Array.Length - 1];
Console.WriteLine(pullRequestIdString);
}
//Get Pull request from work item id
public static async Task<WorkItem> GetPullRequestAndRepositoryFromWorkItemId(Uri orgUrl, string personalAccessToken, int workItemId)
{
VssConnection connection = new VssConnection(orgUrl, new VssBasicCredential(string.Empty, personalAccessToken));
WorkItemTrackingHttpClient workItemTrackingHttpClient = connection.GetClient<WorkItemTrackingHttpClient>();
WorkItemExpand workItemExpand = WorkItemExpand.All;
var workItem = workItemTrackingHttpClient.GetWorkItemAsync(workItemId, expand: workItemExpand).Result;
return workItem;
}
}
}

Migrate WindowsAzure.ServiceBus to Azure.Messaging.ServiceBus

Microsoft will deprecated support of Classic API for Service Bus at November 2021 (as described here)
In our code we use WindowsAzure.ServiceBus package.
It is an ol package and Microsoft suggets to use new Azure.Messaging.ServiceBus package.
WindowsAzure.ServiceBus package contain GetQueues(String) method. This method can use filter parameter for filtration queues by name or properties. It is very useful if a ServiceBus has many Queues.
But I can't find equivalent of this feature in new Azure.Messaging.ServiceBus package.
How can I implement filter feature in new package?
Thanks for any help.
How can I implement filter feature in new package?
You will need to use GetQueuesAsync method in ServiceBusAdministrationClient class to get this information.
Please see the sample code:
using System;
using System.Threading.Tasks;
using Azure.Messaging.ServiceBus.Administration;
namespace SO67703647
{
class Program
{
static string connectionString = "your-connection-string";
static async Task Main(string[] args)
{
var adminClient = new ServiceBusAdministrationClient(connectionString);
var queuesListingResult = adminClient.GetQueuesAsync();
await foreach (var item in queuesListingResult)
{
Console.WriteLine(item.Name);
}
Console.WriteLine("=======================");
Console.WriteLine("Press any key to terminate the application.");
Console.ReadKey();
}
}
}

Google Vision API not working Grpc.Core.RpcException

I'm trying to get Google Vision API to work with my project but having trouble. I keep getting the following error:
Grpc.Core.RpcException: 'Status(StatusCode=PermissionDenied, Detail="This API method requires billing to be enabled
I've created a service account, billing is enabled and I have the .json file. I've got the Environment variable for my account for GOOGLE_APPLICATION_CREDENTIALS pointing to the .json file.
I've yet to find a solution to my problem using Google documentation or checking StackOverFlow.
using Google.Cloud.Vision.V1;
using System;
using System.Collections.Generic;
namespace Vision
{
internal static class GoogleVision
{
public static EntityAnnotation[] GetAnnotations(EventManager em, string filePath, string EventNr)
{
{
ImageAnnotatorClient Client = ImageAnnotatorClient.Create();
Image Image = Google.Cloud.Vision.V1.Image.FromFile(filePath);
IReadOnlyList<EntityAnnotation> Response = Client.DetectLabels(Image);
EntityAnnotation[] annotations = new EntityAnnotation[Response.Count];
for (int i = 0; i < annotations.Length; i++)
{
annotations[i] = Response[i];
}
return annotations;
}
}
}
}
Not sure why but by setting the environment variable in the code rather than manually with windows, it fixed the problem.
Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", "thejsonfile");

Clear kafka topic programmatically using C#

I need to clear or delete Kafka topics programmatically using C# language. Currently, I have used Confluent.Kafka library for publishing and consuming Kafka topics.
I can delete Kafka topics using the command line like this
kafka-topics.bat --zookeeper 192.108.94.79:2181 --delete --topic test-topic3
Is any library or way available for clearing Kafka topic programmatically using C# language?
In version 1.3.0 of confluent.kafka AdminClient class is internal,
so you have to use AdminClientBuilder
Example:
AdminClientBuilder builder = new AdminClientBuilder(new AdminClientConfig() { BootstrapServers =""})
builder.Build();
We can quickly delete the Kafka topics using Confluent.Kafka library version 1.0.0. But currently, it's in beta release. This library support Kafka admin utilities. Following code helps to clear/delete Kafka topics.
using Confluent.Kafka;
using System;
using System.Collections.Generic;
namespace deleteKafkaTopic
{
public class Program
{
public static void Main(string[] args)
{
Console.WriteLine($"librdkafka Version: {Library.VersionString} ({Library.Version:X})");
Console.WriteLine($"Debug Contexts: {string.Join(", ", Library.DebugContexts)}");
IEnumerable<string> topicList = new List<string>() { "test-topic4" };
deleteTopics("192.168.64.49:9092", topicList);
}
static void deleteTopics(string brokerList, IEnumerable<string> topicNameList)
{
using (var adminClient = new AdminClient(new AdminClientConfig { BootstrapServers = brokerList }))
{
adminClient.DeleteTopicsAsync(topicNameList, null);
}
}
}
}

.NET HBase REST API client library - calling from MVC5 Controller

Looking at the sample code given on https://azure.microsoft.com/en-us/documentation/articles/hdinsight-hbase-tutorial-get-started/#use-the-net-hbase-rest-api-client-library,
I'm trying to connect to HBase from an MVC Controller as follows:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace MyHBaseTest.Controllers
{
[RoutePrefix("api/myhbasetestcontroller")]
public class MyHBaseTestController : ApiController
{
HBaseReader hbase = new HBaseReader();
[HttpGet]
[Route("")]
public IHttpActionResult Index()
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername = "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
return Ok();
}
}
}
When I try to view the URL /api/myhbasetestcontroller in my browser when it is run in debug mode, it keeps loading the page forever without throwing any exception or anything in Visual Studio. I have waited for 15-20 minutes but nothing changes.
When I put try to do the same in a console application, it gets the version information in a matter of seconds though:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Microsoft.HBase.Client;
using org.apache.hadoop.hbase.rest.protobuf.generated;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string clusterURL = "https://<yourHBaseClusterName>.azurehdinsight.net";
string hadoopUsername= "<yourHadoopUsername>";
string hadoopUserPassword = "<yourHadoopUserPassword>";
// Create a new instance of an HBase client.
ClusterCredentials creds = new ClusterCredentials(new Uri(clusterURL), hadoopUsername, hadoopUserPassword);
HBaseClient hbaseClient = new HBaseClient(creds);
// Retrieve the cluster version
var version = hbaseClient.GetVersion();
Console.WriteLine("The HBase cluster version is " + version);
}
}
}
I just don't understand how it makes a difference really.
Could you please advice?
Many thanks.
As of today, you need to run your calls on a background thread. I ran into this same exact issue. My calls are consolidated under a single function. I run that function on a background thread and everything works great.
// POST: api/Vizzini
[ResponseType(typeof(string))]
public async Task<IHttpActionResult> GetResponse(string tweet)
{
string s = await Task.Run(() =>
{
return ResponseEngine.GetBestResponse(tweet);
});
return Ok(s);
}
You are using blocking synchronous APIs, which won't work in the context of MVC/Web app (due to using wrong async context by default). You need to use async version of the methods. E.g. for GetVersion use GetVersionAsync.

Categories

Resources