SQS : Getting Number of message in the SQS Queue - c#

I am working with Amazon-SQS, I tried to retrieve approximate number of attributes from the queue but the response is null
I am using C# following is the code:
GetQueueAttributesRequest attReq = new GetQueueAttributesRequest();
attReq.QueueUrl = "Link to queue";
GetQueueAttributesResponse response = client.GetQueueAttributes(attReq);
Console.WriteLine("App. messages: "+ response.ApproximateNumberOfMessages);
I am getting null response from the request, I am sure there are messages in the queue as well.

You have to explicitly specify which attributes you would like to return from GetQueueAttributes. You didn't specify any, so it didn't return any.
Try simply adding ApproximateNumberOfMessages to the AttributeNames collection on GetQueueAttributesRequest:
GetQueueAttributesRequest attReq = new GetQueueAttributesRequest();
attReq.QueueUrl = "Link to queue";
attReq.AttributeNames.Add("ApproximateNumberOfMessages");
GetQueueAttributesResponse response = client.GetQueueAttributes(attReq);
Notes:
This property might be called AttributeName without the last s if you're on an older version of the AWSSDK. It looks like this changed between versions 1.x and 2.x.
Full list of attributes can be found in the API documentation

Related

How to properly attach a bulk of small files to a task in graph api

Have the following code.
if (attachments != null)
{
if (attachments.Length > 0)
{
_newTask.Attachments = new TodoTaskAttachmentsCollectionPage();
foreach (var _attachment in attachments)
{
_newTask.Attachments.Add(new TaskFileAttachment
{
Name = _attachment.FileName,
ContentBytes = _attachment.ContentBytes,
ContentType = _attachment.ContentType
});
}
}
}
await _graphServiceClient.Users[idUser].Todo.Lists[idList].Tasks.Request().AddAsync(_newTask);
Im trying to add multiple small files to a task and then post it to the graph api.
But it results in the following error:
One or more errors occurred. (One or more errors occurred. (A type
named 'microsoft.toDo.taskFileAttachment' could not be resolved by the
model. When a model is available, each type name must resolve to a
valid type.
Basically saying that the type taskFileAttachment is not the correct type to add to the collection of attachments of a task.
But, according to MSdoc that's the correct type to add.
Cant see what i'm missing and there is not a lot of documentation of how to post small files to a task. I already done it through the api for mails and thought it was really straightforward but it looks as it is not the case.
As per the docs , there are list of property that are required when you create the todoTask , in that you can't find any property to attach the file
First try to create a new listItems , and attach the file
Sample to attach the file
GraphServiceClient graphClient = new GraphServiceClient( authProvider );
var attachmentBase = new TaskFileAttachment
{
Name = "smile",
ContentBytes = Convert.FromBase64String("a0b1c76de9f7="),
ContentType = "image/gif"
};
await graphClient.Me.Todo.Lists["{todoTaskList-id}"].Tasks["{todoTask-id}"].Attachments
.Request()
.AddAsync(attachmentBase);
So as they commented in my original post, there is no current way to attach a collection of files in one single request. They must attached to a created task one at a time.

In C# how to enumerate IEnumerable or FuncAsyncPageable or PageResponseEnumerator?

I am new to C#. I am trying to get a list of subscriptions from an azure message bus:
ServiceBusAdministrationClient client = new ServiceBusAdministrationClient(connectionString);
var getSubResponse = client.GetSubscriptionsAsync(topicPath);
Console.WriteLine("subs:" + getSubResponse.AsPages());
The response is of type Task<IEnumerable<SubscriptionDescription>> or AsyncPageable<SubscriptionProperties>, depending on which documentation you read.
Visual Studio says the response type is Azure.Core.PageResponseEnumerator.FuncAsyncPageable<Azure.Messaging.ServiceBus.Administration.SubscriptionProperties>
How do I write some C# code to display every value in the response?
If I look at the response in Visual Studio debugger, it has hundreds of nested fields, none of which are the actual subscription info, they are just pointers etc. There is a Non-Public members field with _pageFunc, and below this are "Method" and "Target" and under target is another pageFunc which also has Method and Target.
Any ideas how I get useful info form such an object?
Ok, found the answer, its this:
var getSubResponse = client.GetSubscriptionsAsync(topicPath);
await foreach (var sub in getSubResponse)
{
Console.WriteLine("sub name:" + sub.SubscriptionName);
Console.WriteLine("sub ttl:" + sub.DefaultMessageTimeToLive);
Console.WriteLine("sub max delivery count:" + sub.MaxDeliveryCount);
}
There does not seem to be a way to dump all the fields unfortunately.

How to create new AutoML DataSet for simple classification (C#)

As part of ML automation process I want to dynamically create new AutoML model. I'm using C# (.net framework) and Google.Cloud.AutoML.V1.
After trying to run CreateDataSet code:
var autoMlClient = AutoMlClient.Create();
var parent = LocationName.FromProjectLocation(_projectId, _locationId);
var dataset = new Google.Cloud.AutoML.V1.Dataset();
dataset.DisplayName = "NewDataSet";
var response = autoMlClient.CreateDataset(parent, dataset);
I get the following error:
Field: dataset.dataset_metadata; Message: Required field not set
According to this user manual I should set Dataset Metadata Type, but the list contains only specific types of classifications (Translation/ImageClassifications etc.), I can't find a simple classification type.
How do I create a simple classification data set with the API ? in the AutoML UI its just with a simple button click ("NEW DATASET") - and have to provide only name & region - no classification type.
I also tried to set:
dataset.TextClassificationDatasetMetadata =
new TextClassificationDatasetMetadata() { ClassificationType = ClassificationType.Multiclass };
But I was unable to import data to it (got too many errors of invalid inputs from the input CSV file), I guess its related to the reason that the input format is not suitable for Text Classification.
UPDATE
I've just notice that the Nuget works with AutoML v1 but v1 beta does contains TablesDatasetMetadata Dataset Metadata Type for normal classifications. I'm speechless.
I also experienced this scenario today while creating a dataset using the NodeJS client. Since the Google AutoML table service is in the beta level you need to use the beta version of the AutoML client. In the Google cloud documentation they have used the beta client to create a dataset.
In NodeJS importing the beta version require('#google-cloud/automl').v1beta1.AutoMlClient instead of importing the normal version (v1) require('#google-cloud/automl').v1 worked for me to successfully execute the create dataset functionality.
In C# you can achieve the same through a POST request. Hope this helps :)
After #RajithaWarusavitarana comment, and my last question update , below is the code that did the trick. The token is being generated by GoogleClientAPI nuget and AutoML is handled by REST.
string GcpGlobalEndPointUrl = "https://automl.googleapis.com";
string GcpGlobalLocation = "us-central1"; // api "parent" parameter
public string GetToken(string jsonFilePath)
{
var serviceAccountCredentialFileContents = System.IO.File.ReadAllText(jsonFilePath);
var credentialParameters = NewtonsoftJsonSerializer.Instance.Deserialize<JsonCredentialParameters>(serviceAccountCredentialFileContents);
var initializer = new ServiceAccountCredential.Initializer(credentialParameters.ClientEmail)
{
Scopes = new List<string> { "https://www.googleapis.com/auth/cloud-platform" }
};
var cred = new ServiceAccountCredential(initializer.FromPrivateKey(credentialParameters.PrivateKey));
string accessToken = cred.GetAccessTokenForRequestAsync("https://oauth2.googleapis.com/token").Result;
return accessToken;
}
public void GetDataSetList(string projectId, string token)
{
var restClient = new RestClient(GcpGlobalEndPointUrl);
var createDataSetReqUrl = $"v1beta1/projects/{projectId}/locations/{GcpGlobalLocation}/datasets";
var createDataSetReq = new RestRequest(createDataSetReqUrl, Method.GET);
createDataSetReq.AddHeader("Authorization", $"Bearer {token}");
var createDatasetResponse = restClient.Execute(createDataSetReq);
createDatasetResponse.Dump();
}
I took the token generation code from google-api-dotnet-client Test File

AWS Machine Learning RealTimePredictor returns UnknownoperationException in C#

Using Visual Studio, and AWS .NET V 3.0.
I'm trying to perform a real-time Predict operation, and to verify the basic setup works, I first perform a GetMLModel() which works and returns the endpoint (Somewhere in the documentation is was mentioned to use that result as the service endpoint, but it's the same that is listed in the console). Is has status "READY", so far so good.
The exception occurs below on the line below "Prediction P = RTP.Predict(Data)". Data contains a Dictionary with all the prediction values.
Error: Error making request with Error Code UnknownOperationException and Http Status Code BadRequest. No further error information was returned by the service.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate();
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
GetMLModelResponse MLMOdelResp = MLClient.GetMLModel("xxx"); // <-- WORKS
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
Console.WriteLine(MLConfig.ServiceURL);
MLConfig.Validate();
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data); // <----------------EXCEPTION HERE
}
(Obviously replace xxx with relevant values) :)
It turns out that this line:
MLConfig.ServiceURL = MLMOdelResp.EndpointInfo.EndpointUrl;
cases the MLConfig.RegionEndpoint to be reset. Even though the documentation indicates the RegionEndpoint can be determined from the ServiceURL (I'm pretty sure I read that), the RegionEndpoint needs to be set again before the RTP.Predict(Data) call.
Once I figured that out, I was able to reduce the code to just this, in case anyone else needs help. I guess adding too much information to the Configuration is NOT a good thing, as the AWS. NET library seems to figure all this out on its own.
public static APIResult GetRealTimePrediction(Dictionary<string, string> Data, string PayloadJSON = null) {
AmazonMachineLearningConfig MLConfig = new AmazonMachineLearningConfig();
MLConfig.RegionEndpoint = Amazon.RegionEndpoint.USEast1;
MLConfig.Validate(); // Just in case, not really needed
AmazonMachineLearningClient MLClient = new AmazonMachineLearningClient("xxx", "xxx", MLConfig);
Amazon.MachineLearning.Util.RealtimePredictor RTP = new Amazon.MachineLearning.Util.RealtimePredictor(MLClient, "xxx");
Prediction P = RTP.Predict(Data);
}

Magento SOAP V2 API - Additional attributes sets empty

For a few hours now I've been trying to create a product via the SOAP V2 API with additional attributes. The product is being added whenever I call catalogProductCreate but the additional attributes I send with the request are set empty. Whenever I don't add the additional attributes both attributes are set on their default, so I've figured that the attributes are being send and received but not processed properly? I've tried everything, I've Googled but came up empty.
This is my code: (C#)
catalogProductCreateEntity cpce = new catalogProductCreateEntity();
associativeEntity[] attributes = new associativeEntity[2];
attributes[0] = new associativeEntity();
attributes[0].key = "product_state1";
attributes[0].value = _stateofbox;
attributes[1] = new associativeEntity();
attributes[1].key = "product_state2";
attributes[1].value = _stateofproduct;
catalogProductAdditionalAttributesEntity additionalAttributes = new catalogProductAdditionalAttributesEntity();
additionalAttributes.single_data = attributes;
cpce.additional_attributes = additionalAttributes;
Thanks for the help.
Fixed it, I thought I had to set the plaintext/ID (0,1,2,3) of the pre-defined attributes inside the value of associativeEntity. Although, I found out that catalogProductAttributeOptions will tell you what ID your values have. Thus you have to call that method in order to find out what ID's you should use.

Categories