C# Google API throws exception - c#

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.

Related

C# MSGraph SDK and ipNamedLocation

I've been working on C# app to amend the ipaddress/s of a Named Location in conditional access in AAD.
I can authenticate and return the request collection. For whatever reason I cant access the isTrusted property or the ipRanges odata.
I can see the properties and the vales when I run through in debug, but cant output them.
I think its something to do with the list type, I'm using Microsoft.Graph.NamedLocation, there is Microsoft.Graph.IpNamedLocation type available but it can be converted from Microsoft.Graph.NamedLocation, which the api call makes.
The image shows what's available during runtime.
Code Below:
private static async Task GetnamedLocations(IConfidentialClientApplication app, string[] scopes)
{
GraphServiceClient graphServiceClient = GetAuthenticatedGraphClient(app, scopes);
var namedlocationsList = new List<Microsoft.Graph.NamedLocation>();
var namedLocations = await graphServiceClient.Identity.ConditionalAccess.NamedLocations
.Request()
.Filter("isof('microsoft.graph.ipNamedLocation')")
.GetAsync();
// var ipNamedLocations = new List<Microsoft.Graph.IpNamedLocation>();
namedlocationsList.AddRange(namedLocations.CurrentPage);
foreach (var namedLocation in namedlocationsList)
{
Console.WriteLine(namedLocation.Id + namedLocation.DisplayName + namedLocation.ODataType + namedLocation);
if (namedLocation.ODataType == "#microsoft.graph.ipNamedLocation")
{
Console.WriteLine("Write out all the properties");
}
}
Console.WriteLine(($"Named location: {namedLocations}"));
}
Any pointers gratefully received, I'm not a C# developer so be gentle :-)
You need to cast namedLocation to IpNamedLocation type.
foreach (var namedLocation in namedlocationsList)
{
Console.WriteLine(namedLocation.Id + namedLocation.DisplayName + namedLocation.ODataType + namedLocation);
if (namedLocation is IpNamedLocation ipNamedLocation)
{
var isTrusted = ipNamedLocation.IsTrusted;
var ipRanges = ipNamedLocation.IpRanges;
if (ipRanges is IEnumerable<IPv4CidrRange> ipv4cidrRanges)
{
foreach(var ipv4cidrRange in ipv4cidrRanges)
{
Console.WriteLine($"{ipv4cidrRange.CidrAddress}");
}
}
Console.WriteLine("Write out all the properties");
}
}
I couldn't get the updated answer to work, it still didn't evaluate the if statement to true, after a bit of googling and trying different options, the following returns the IP address, not sure if its the right way to go about it but it works.
var ipv4CidrRanges = ipRanges.Cast<IPv4CidrRange>().ToList();
foreach (var ipv4CidrRange in ipv4CidrRanges)
{
Console.WriteLine(ipv4CidrRange.CidrAddress);
}
Many thanks to user2250152 who solved the first conundrum for me.

Bot mentions to meetings groups are blank on Desktop/Web chat view

We're developing a bot that proactively messages people in a group chat.
Bot mentions are showing blank on Desktop/Web chat view. Interestingly, on mobile and in the notification bar on the left, the full text does show correctly.
This issue may apply to other chats, but I have not tested.
I'm using similar code to the following Microsoft guide by constructing the mention object:
https://learn.microsoft.com/en-us/microsoftteams/platform/bots/how-to/conversations/channel-and-group-conversations?tabs=dotnet#add-mentions-to-your-messages
Yes, I have tried using XMLConvert on the name as in the example, however, that does not make a difference, in fact, it puts the XML verbatim into the message sent by the bot.
I've also submitted a bug report here, as I suspect it's a bug in Teams itself (although, I could not find any other mentions of this or other similar example code):
https://microsoftteams.uservoice.com/forums/555103-public/suggestions/43922577-bot-mentions-to-meetings-groups-are-blank-on-deskt
Relevant C# code:
...
using (ConnectorClient _client = new ConnectorClient(new Uri(groupChat.ServiceUrl), GetMicrosoftAppCredentials(), new HttpClient()))
{
var theMessage = Activity.CreateMessageActivity();
theMessage.Text = messageDto.Message;
// Process the message text for <at>mentions</at>
var textMentions = System.Text.RegularExpressions.Regex.Matches(theMessage.Text, "<at>(.*?)</at>");
var mentionObjects = new List<Entity>(); // For storing the mentions
foreach (var textMention in textMentions)
{
// The mentioned person should be between the tags
var theName = textMention.ToString().Split(new string[] { "<at>", "</at>" }, StringSplitOptions.RemoveEmptyEntries)[0];
if (!String.IsNullOrEmpty(theName))
{
// Find the teamsUser based on their name
var teamsUser = _botContext.Users.FirstOrDefault(u => u.Name.Equals(theName));
if (teamsUser != null)
{
var mention = new Mention
{
Mentioned = new ChannelAccount(teamsUser.TeamsUserId),
Text = textMention.ToString()
};
mentionObjects.Add(mention);
}
}
}
theMessage.Entities = mentionObjects;
try
{
var response = await _client.Conversations.SendToConversationAsync(groupChat.GroupChatId, (Activity)theMessage);
return Ok(response.Id);
}
catch (Exception e)
{}
}
...
Desktop Teams Chat:
Activity shows name OK:
Mobile app looks OK:
Images edited for privacy
Try passing "User Name" also in ChannelAccount() like below:
var mention = new Mention
{
Mentioned = new ChannelAccount(
turnContext.Activity.From.Id,
**turnContext.Activity.From.Name,**
role: null,
aadObjectId: null),
Text = textMention.ToString()
};
I tried above code and it's working for me.

Error when creating ServiceBus Queue using Azure.Messaging.ServiceBus.Administration

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.

Change Project Owner Using PSI 2010(Project Server Interface)

I want to change ProjectOwnerUID Using PSI(Project Server Interface).I wrote that with follow similar code
var projectDataSet = this.GetProjectDataSet(projectInfo.ProjectUID);
var orginalProject = this.GetProject(projectInfo.ProjectUID, projectDataSet);
var sessionUID = this.CheckOutProject(projectInfo.ProjectUID);
if (!string.IsNullOrEmpty(projectInfo.ProjectOwnerName))
{
var resourceManager = new Resource();
var ownerResource = resourceManager.GetResource(projectInfo.ProjectOwnerName);
if (ownerResource == null)
{
throw new Exception("this is not valid");
}
orginalProject.ProjectOwnerID = ownerResource.ResourceUID;
}
this.UpdateProject(sessionUID, projectDataSet);
unfortunatly when cursor arrive to UpdateProject line it throws exception with code number
ProjectServerError(s) LastError=ProjectInvalidOwner Instructions: Pass this into PSClientError constructor to access all error information
Inner Error 1056(Invalid project owner).
I don't know what happen that Issued this exception
how can I solve this problem?
This problem occurs when you do not have permissions to edit project information using the following code snippet u can tell to project server to run this piece of code do not check permissions!!
using Microsoft.SharePoint;
public void MyVoid()
{
SPSecurity.RunWithElevatedPrivileges(delegate()
{
//Write ur Codes here :)
});
}
MSDN Reference

Examples of Quickbase API in C#

I am fairly new to the use of APIs and haven't touched Quickbase until today. I was researching the Quickbase API and it seemed as if all the examples I saw were written in XML or some similar variant. Is there a way to write code in C# that will do the same things that I saw could be done on the Quickbase website's API documentation? If you know of any code examples, please let me know.
There is a QuickBase C# SDK that might help get you started.
using System;
using Intuit.QuickBase.Client;
namespace MyProgram.QB.Interaction
{
class MyApplication
{
static void Main(string[] args)
{
var client = QuickBase.Client.QuickBase.Login("your_QB_username", "your_QB_password");
var application = client.Connect("your_app_dbid", "your_app_token");
var table = application.GetTable("your_table_dbid");
table.Query();
foreach(var record in table.Records)
{
Console.WriteLine(record["your_column_heading"]);
}
client.Logout();
}
}
}
There is also a QuickBase API Wrapper example as well.
Back in 2009 I wrote an .NET API for QuickBase which makes working with the platform easy, it also supports uploading and downloading of attached files.
IQuickBaseService svc = new QuickBaseService("user", "pass", "URL", "token");
Schema schema = svc.GetSchema("DBID");
Console.WriteLine("Schema : {0}", schema.Name);
Console.WriteLine("Variables - ");
for (KeyValuePair<string, string> ent in schema.Variables.OrderBy(en => en.Key)) {
Console.WriteLine("Var: {0} = {1}", ent.Key, ent.Value);
}
for (Query q : schema.Queries) {
// Work with queries.
}
// schema.Children
// schema.Fields
// ...
svc.SignOut();
Performing a query is simple.
QueryResult res;
res = svc.Query("tableid", 1); // Execute query number 1
res = svc.Query("tableid", "{{140.EX.'1'}}") // execute QB query text
foreach (QueryRow row in result.Rows) {
// Do something with row, use get<type>, not all shown here.
// row.GetBool(1);
// row.GetInt(1);
// row.GetLong(1);
// row.GetFloat(1);
// row.GetDouble(1);
// row.GetDecimal(1);
// row.GetString(1);
// row.GetDate(1);
// row.GetDateTime(1);
// row.GetObject(1);
}
QuickBase SDK Code is now moved to github https://github.com/QuickbaseAdmirer/QuickBase-C-Sharp-SDK

Categories

Resources