Error when creating ServiceBus Queue using Azure.Messaging.ServiceBus.Administration - c#

I am (trying) to use this code to create ServiceBus Queue:
using Azure.Messaging.ServiceBus;
using Azure.Messaging.ServiceBus.Administration;
...
class blabla
{
private string connectionString = "Endpoint=sb://XXXX.servicebus.windows.net/;SharedAccessKeyName=RootManageSharedAccessKey;SharedAccessKey=XXXYYY";
private string queueName = "testqueue";
...
public doit()
{
var adminClient = new ServiceBusAdministrationClient(connectionString);
bool queueExists = adminClient.QueueExistsAsync(queueName).Result;
if (!queueExists)
{
var options = new CreateQueueOptions(queueName)
{
DefaultMessageTimeToLive = TimeSpan.FromDays(2),
LockDuration = TimeSpan.FromSeconds(45),
MaxDeliveryCount = 8,
MaxSizeInMegabytes = 2048
};
options.AuthorizationRules.Add(new SharedAccessAuthorizationRule(
"allClaims",
new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));
QueueProperties createdQueue = adminClient.CreateQueueAsync(options).Result;
}
}
}
but constantly getting this error:
System.AggregateException: One or more errors occurred. (SubCode=40900. Conflict. You're requesting an operation that isn't allowed in the resource's current state. To know more visit https://aka.ms/sbResourceMgrExceptions. . TrackingId:bc79fd98-73c8-4301-b6b9-05d0eae6ed6a_G17, SystemTracker:xxx.servicebus.windows.net:yyy, Timestamp:2021-05-09T00:24:57
Status: 409 (Conflict)
ErrorCode: 40900
Using old (NET) way with NamespaceManager from Microsoft.ServiceBus works with no problems.
var namespaceManager = NamespaceManager.CreateFromConnectionString(connectionString);
if (!namespaceManager.QueueExists(queueName))
{
namespaceManager.CreateQueue(queueName);
}
So, does anyone knows what am I doing wrong here?
*

Below is the updated working code, you need to make sure you have shared access policy with full access.
using Azure.Messaging.ServiceBus.Administration;
using System;
using System.Threading.Tasks;
namespace ServiceBusDemo
{
class Program
{
private static string connectionString = "Endpoint=sb://ns-servicebusshu.servicebus.windows.net/;SharedAccessKeyName=fullAccess;SharedAccessKey=oB+IsK8Aqp0/xfXnF9HCz6x9pqPIOysTXaJofSmHEYs=";
private static string queueName = "testqueue";
async static Task Main(string[] args)
{
await doit();
}
public static async Task doit()
{
var adminClient = new ServiceBusAdministrationClient(connectionString);
bool queueExists = await adminClient.QueueExistsAsync(queueName);
if (!queueExists)
{
var options = new CreateQueueOptions(queueName)
{
DefaultMessageTimeToLive = TimeSpan.FromDays(2),
LockDuration = TimeSpan.FromSeconds(45),
MaxDeliveryCount = 8,
MaxSizeInMegabytes = 2048
};
options.AuthorizationRules.Add(new SharedAccessAuthorizationRule("allClaims", new[] { AccessRights.Manage, AccessRights.Send, AccessRights.Listen }));
QueueProperties createdQueue = await adminClient.CreateQueueAsync(options);
}
}
}
}
Once you ran the application its successfully created the queue as below :

Maybe it's not your case... But if you have a TOPIC with the same name that you try to create your new QUEUE, QueueExistsAsync will return false, but you'll be spitted with this bizarre error at creation time. The fix is easy... changing the queue name or deleting the offending topic.

Sorry for the confusion.
My code (and Rahul Shukla as well) is working now (????).
I had to create a few new shared access policies with full access (????).
The third created started working (??).
The previous 2 I created are still not working (????).
There are no differences between the 3 policies created. Hence the question marks in my answer.
Posted question on MS NET SB forum about 1 out of 3 policies working. No answer/acknowledgment so far.

Related

It takes too long to send transaction to the smart contract which is already deployed. (Nethereum + Unity)

I'm making some dApp using Unity & Nethereum.
I deployed one contract to the Ropsten Test Net using Remix. And I had abi & bytecode of that, so I made Definition & Service C# code using solodity package of VS Code.
I wanted to mint new NFT, and below is the code that I tried.
string url = "my infura - ropsten url";
string privateKey = "private Key of my MetaMask account";
string userAddress = "public address of my MetaMask account";
string contractAddress = "address of deployed contract";
var account = new Account(privateKey);
var web3 = new Web3(account, url);
var service = new MyNFTService(web3, contractAddress);
var mintReceipt = await service.MintRequestAndWaitForReceiptAsync(userAddress, "address of metadata");
But I can't get receipt even after a long time... Why is this happening? I can't get any answer about that, and I just have to wait.
I have tried everything that I can do, like SendTransactionAndWaitForReceiptAsnyc(), SignAndSendTransaction(), and so on.
The version of Nethereum is 4.1.1, and the version of Unity is 2019.4.21f1.
Below is the part of definition code. (mint)
public partial class MintFunction : MintFunctionBase { }
[Function("mint", "uint256")]
public class MintFunctionBase : FunctionMessage
{
[Parameter("address", "user", 1)]
public virtual string User { get; set; }
[Parameter("string", "tokenURI", 2)]
public virtual string TokenURI { get; set; }
}
And below is the part of service code. (mint)
public Task<string> MintRequestAsync(MintFunction mintFunction)
{
return ContractHandler.SendRequestAsync(mintFunction);
}
public Task<TransactionReceipt> MintRequestAndWaitForReceiptAsync(MintFunction mintFunction, CancellationTokenSource cancellationToken = null)
{
return ContractHandler.SendRequestAndWaitForReceiptAsync(mintFunction, cancellationToken);
}
public Task<string> MintRequestAsync(string user, string tokenURI)
{
var mintFunction = new MintFunction();
mintFunction.User = user;
mintFunction.TokenURI = tokenURI;
return ContractHandler.SendRequestAsync(mintFunction);
}
public Task<TransactionReceipt> MintRequestAndWaitForReceiptAsync(string user, string tokenURI, CancellationTokenSource cancellationToken = null)
{
var mintFunction = new MintFunction();
mintFunction.User = user;
mintFunction.TokenURI = tokenURI;
return ContractHandler.SendRequestAndWaitForReceiptAsync(mintFunction, cancellationToken);
}
I am struggle with this problem for five days... Please help me..
I solved it today! (But I didn't use my service code)
In my opinion, the reason why the transaction didn't work is that the miner can't mine my transaction. (Exactly, they can mine, but they didn't because mining other transaction will give them more money.)
In the document of Netherum, they speak nethereum can set the gas price as the average, but I though it didn't work. After I added a code to estimate and set the gas price, SendRequestAndWaitForReceiptAsync() worked very well. (And I could receive transaction hash.)
Below is the code that I used to solve this problem.
var mintHandler = web3.Eth.GetContractTransactionHandler<MintFunction>();
var mint = new MintFunction()
{
User = userAddress,
TokenURI = "Token URI"
};
mint.GasPrice = Web3.Convert.ToWei(25, UnitConversion.EthUnit.Gwei);
var estimate = await mintHandler.EstimateGasAsync(contractAddress, mint);
mint.Gas = estimate.Value;
var mintReceipt = await mintHandler.SendRequestAndWaitForReceiptAsync(contractAddress, mint);
Debug.Log(mintReceipt.TransactionHash);

C# Google API throws exception

I am using Google API for the first time and I want to use Natural Language API.
But I don't know how.
So I search the internet and found an example code.
But when it uses APIs, the program throws an exception.
problem source code and thrown exception:
using Google.Cloud.Language.V1;
using System;
namespace GoogleCloudSamples
{
public class QuickStart
{
public static void Main(string[] args)
{
// The text to analyze.
string text = "Hello World!";
try
{
var client = LanguageServiceClient.Create();
var response = client.AnalyzeSentiment(new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
});
var sentiment = response.DocumentSentiment;
Console.WriteLine($"Score: {sentiment.Score}");
Console.WriteLine($"Magnitude: {sentiment.Magnitude}");
}
catch (Exception e)
{
Console.WriteLine(e.Message);
}
}
}
}
The console output:
The Application Default Credentials are not available.
They are available if running on Google Compute Engine.
Otherwise, the environment variable GOOGLE_APPLICATION_CREDENTIALS must be defined pointing to a file defining the credentials.
See https://developers.google.com/accounts/docs/application-default-credentials for more information.
What should I do?
I had used NLP a year ago for entity analysis. I had used Google.Apis.CloudNaturalLanguage.v1. I put together my code with what you have written for sentiment analysis. You will need the API key for this:
var service = new CloudNaturalLanguageService(new CloudNaturalLanguageService.Initializer { ApiKey = ApiKey });
var req = new AnalyzeSentimentRequest {
Document = new Document()
{
Content = text,
Type = Document.Types.Type.PlainText
},
EncodingType = "UTF8"
};
var output = service.Documents.AnalyzeSentiment(req);
var exe = output.Execute();
Hope this works.

How to create new topic in c# by using kafka-net

I have HomeController as below,
#region Properties
const string topic = "AnotherTestTopic";
const string host = "http://localhost:9092";
#endregion
[HttpPost]
public ActionResult Save(FormCollection form)
{
var kafkaOptions = new KafkaOptions(new Uri(host));
var brokerRouter = new BrokerRouter(kafkaOptions);
var producer = new Producer(brokerRouter);
producer.SendMessageAsync(topic, new[] { new Message("Test message") }).Wait();
return RedirectToAction("Index", "Home");
}
I am using kafka-net dll and my SendMessageAsync method as below
public async Task<List<ProduceResponse>> SendMessageAsync(string topic, IEnumerable<Message> messages, Int16 acks = 1,
TimeSpan? timeout = null, MessageCodec codec = MessageCodec.CodecNone)
{
if (_stopToken.IsCancellationRequested)
throw new ObjectDisposedException("Cannot send new documents as producer is disposing.");
if (timeout == null) timeout = TimeSpan.FromMilliseconds(DefaultAckTimeoutMS);
var batch = messages.Select(message => new TopicMessage
{
Acks = acks,
Codec = codec,
Timeout = timeout.Value,
Topic = topic,
Message = message
}).ToList();
_asyncCollection.AddRange(batch);
await Task.WhenAll(batch.Select(x => x.Tcs.Task));
return batch.Select(topicMessage => topicMessage.Tcs.Task.Result)
.Distinct()
.ToList();
}
Question:
I just started learning kafka.I really do not know how can i create topic from c# code.How can i add topic from c# ?
Any help will be appreciated.
Thanks.
You can set auto.create.topics.enable=true in your broker configuration to let Kafka create the topic for you when it is not previously created.
You may also want to set num.partitions and default.replication.factor to appropriate values in your broker configuration as well.

Azure resource management API not showing virtual machine state?

So I've been poking around at read-only api access into azure with the resource management api. Right now I'm focusing on Virtual Machines. I've been using this pre-release package with TokenCredentials:
https://www.nuget.org/packages/Microsoft.Azure.Management.Compute/13.0.1-prerelease
I get a bunch of rich info about my vms but I'm missing a pretty criticle piece of data and that's whether the vm is on or off. I've found a couple of meta data properties like InstanceView and Plan to be null when I expected them to be populated. It may because of how I launched my vms, it may be a unfinished or buggy new package, I can't tell. I was thinking InstanceViews statues would tell me what state the vm is in.
https://msdn.microsoft.com/en-us/library/microsoft.azure.management.compute.models.virtualmachineinstanceview.aspx
So I suppose I have to look elsewhere. I did find this older stackoverflow question that may be what I'm looking for:
azure management libraries virtual machine state
However I'm not sure what dll this GetAzureDeyployment is part of or if it's even TokenCredential compatible. Anyone know whats up?
You can use the following c# code to get the power status of your VM.
using System;
using System.Security;
using Microsoft.Azure.Management.Compute;
using Microsoft.Azure.Management.Compute.Models;
using Microsoft.IdentityModel.Clients.ActiveDirectory;
using Microsoft.Rest;
namespace GetVmARM
{
class Program
{
private static String tenantID = "<your tenant id>";
private static String loginEndpoint = "https://login.windows.net/";
private static Uri redirectURI = new Uri("urn:ietf:wg:oauth:2.0:oob");
private static String clientID = "1950a258-227b-4e31-a9cf-717495945fc2";
private static String subscriptionID = "<your subscription id>";
private static String resource = "https://management.core.windows.net/";
static void Main(string[] args)
{
var token = GetTokenCloudCredentials();
var credential = new TokenCredentials(token);
var computeManagementClient = new ComputeManagementClient(credential);
computeManagementClient.SubscriptionId = subscriptionID;
InstanceViewTypes expand = new InstanceViewTypes();
var vm = computeManagementClient.VirtualMachines.Get("<the resource group name>", "<the VM>", expand);
System.Console.WriteLine(vm.InstanceView.Statuses[1].Code);
System.Console.WriteLine("Press ENTER to continue");
System.Console.ReadLine();
}
public static String GetTokenCloudCredentials(string username = null, SecureString password = null)
{
String authString = loginEndpoint + tenantID;
AuthenticationContext authenticationContext = new AuthenticationContext(authString, false);
var promptBehaviour = PromptBehavior.Auto;
var userIdentifierType = UserIdentifierType.RequiredDisplayableId;
var userIdentifier = new UserIdentifier("<your azure account>", userIdentifierType);
var authenticationResult = authenticationContext.AcquireToken(resource, clientID, redirectURI, promptBehaviour, userIdentifier);
return authenticationResult.AccessToken;
}
}
}
As you can see in this piece of code, I am using InstanceViewTypes which is not available in the document. This is new in the 13.0.1 pre-release version. But yes, if you adding this to your computeManagementClient.VirtualMachines.Get method, you will be able to get extra information for your VM.
Furthermore, I am using vm.InstanceView.Statuses[1] because vm.InstanceView.Statuses[0] is the ProvisioningState. And, I am not sure if the order is always like this, so you may need to loop through the whole status list.

C# Mono Linux - Grab contents of global clipboard

I am trying to simply "grab" text from the clipboard and put into a variable. I'm having a lot of trouble doing this. I've tried to use
Gtk.Clipboard.Get(Gdk.Atom.Intern("PRIMARY", true))
The code that I have so far, just returns "Gtk.Clipboard" to TextBox entry1.
Gtk.Clipboard clipboard = Gtk.Clipboard.Get(Gdk.Atom.Intern("PRIMARY", true));
string textClip = clipboard.ToString ();
entry1.Text = textClip;
So I am unable to do anything productive with this.
Try this piece of code to get text from system clipboard;
Gtk.Clipboard clipboard = Gtk.Clipboard.Get(Gdk.Atom.Intern("CLIPBOARD", false));
var text = clipboard.WaitForText();
For more information mono documentation
You could also have used the klipper DBus-interface.
That way, you can avoid a dependency on GTK#.
Here's the code for the Klipper DBus-Interface (a bit large for stackoverflow): https://pastebin.com/HDsRs5aG
And the abstract class:
https://pastebin.com/939kDvP8
And the actual clipboard-code (requires Tmds.Dbus - for handling DBus)
using System.Threading.Tasks;
namespace TestMe
{
using NiHaoRS; // TODO: Rename namespaces to TestMe
public class LinuxClipboard
: GenericClipboard
{
public LinuxClipboard()
{ }
public static async Task TestClipboard()
{
GenericClipboard lc = new LinuxClipboard();
await lc.SetClipboardContentsAsync("Hello KLIPPY");
string cc = await lc.GetClipboardContentAsync();
System.Console.WriteLine(cc);
} // End Sub TestClipboard
public override async Task SetClipboardContentsAsync(string text)
{
Tmds.DBus.ObjectPath objectPath = new Tmds.DBus.ObjectPath("/klipper");
string service = "org.kde.klipper";
using (Tmds.DBus.Connection connection = new Tmds.DBus.Connection(Tmds.DBus.Address.Session))
{
await connection.ConnectAsync();
Klipper.DBus.IKlipper klipper = connection.CreateProxy<Klipper.DBus.IKlipper>(service, objectPath);
await klipper.setClipboardContentsAsync(text);
} // End using connection
} // End Task SetClipboardContentsAsync
public override async Task<string> GetClipboardContentAsync()
{
string clipboardContents = null;
Tmds.DBus.ObjectPath objectPath = new Tmds.DBus.ObjectPath("/klipper");
string service = "org.kde.klipper";
using (Tmds.DBus.Connection connection = new Tmds.DBus.Connection(Tmds.DBus.Address.Session))
{
await connection.ConnectAsync();
Klipper.DBus.IKlipper klipper = connection.CreateProxy<Klipper.DBus.IKlipper>(service, objectPath);
clipboardContents = await klipper.getClipboardContentsAsync();
} // End Using connection
return clipboardContents;
} // End Task GetClipboardContentsAsync
} // End Class LinuxClipBoardAPI
} // End Namespace TestMe
AsyncEx is required in the abstract class for synchronizing in the get/set property.
AsyncEx not required for the actual clipboard handling, as long as you don't want to utilize the get/set clipboard contents in a synchronous context.
Note: klipper must be running (which it is, if you use KDE).

Categories

Resources