How to directly get option in C# Command-Line - c#

I'm testing C# console application cli tool (System.CommandLine) & I have this code:
using System.CommandLine.NamingConventionBinder;
using System.CommandLine;
internal class Program
{
private static async Task Main (string[] args)
{
var rootCommand = new RootCommand { };
var getCommand = new Command ("get")
{
new Option<string> (
"me",
description: "Gets the name of a takeep & shows its text.")
};
var setCommand = new Command ("set")
{
new Option<string> (
"the",
description: "Sets a takeep by name & text.")
};
getCommand.Handler = CommandHandler.Create<string> ((me) =>
{
Console.WriteLine ($"Build Version: {me}");
});
setCommand.Handler = CommandHandler.Create<string> ((set) =>
{
Console.WriteLine ($"Build Version: {set}");
});
rootCommand.Add (getCommand);
rootCommand.Add (setCommand);
await rootCommand.InvokeAsync (args);
}
}
When I call the command, this way:
.\takeep.cli.exe get me 'Name'
Is there a way to remove that "me", but keep its functionality (I mean, other commands also work)? Thanks for your help 💐

Related

System.CommandLine argument not being passed to handler

I'm trying to get to grips with System.CommandLine.
I can parse boolean options on the commandline such as -x and I can pass string options, eg -f myfile however what I'm having trouble with is the string argument that can optionally be passed to the program- not as an option.
The parser is on some level understanding the argument. If I provide zero or one strings on the commandline then there's no error. If I provide an extra string then I get the error "Unrecognized command or argument". In the handler, however, the parameter is always null. Even if I've specified a default and not marked the string as nullable.
The sandpit code I'm working with is below. Can anyone suggest what I'm doing wrong? I've found lots of discussion elsewhere about Options, but rather less about Arguments.
using System.CommandLine;
using System.CommandLine.IO;
using System.CommandLine.NamingConventionBinder;
namespace ConsoleApp1
{
public static class Program
{
public static int Main(string[] args)
{
RootCommand _cmd = new()
{
new Option<bool>(new[] { "--immediatecalc", "-c" }, () => { return false; }, "Automatically run calculations when a file is loaded"),
new Option<bool>(new[] { "--autoexit", "-x" }, () => { return false; }, "Exit after carrying out directed tasks"),
new Option<bool>(new[] { "--saveJSON", "-s" }, () => { return false; }, "Export on deck JSON file after calculating"),
new Option<string?>(new[] { "--JSONfile", "-f" }, () => { return null; }, "File name for exported JSON file"),
new Argument<string?>("Filename", () => { return null; }, "The file to load.")
};
_cmd.Handler = CommandHandler.Create<bool, bool, bool, string?, string?, IConsole>(Handler);
return _cmd.Invoke(args);
}
static void Handler(bool immediatecalc, bool autoexit, bool saveJSON, string? jsonFile, string? sourceFile, IConsole console)
{
console.WriteLine("Immediate calc " + immediatecalc);
console.WriteLine("Autoexit " + autoexit);
console.WriteLine("saveJSON " + saveJSON);
console.WriteLine("Json file is " + jsonFile);
console.WriteLine("Source file is " + sourceFile);
}
}
}
This is how I would set it up using the latest System.CommandLine version 2.0.0-beta3.22114.1
using System.CommandLine;
namespace ConsoleApp1
{
public static class Program
{
public static int Main(string[] args)
{
var immediateCalcOption = new Option<bool>(new[] { "--immediatecalc", "-c" }, () => { return false; }, "Automatically run calculations when a file is loaded");
var autoExitOption = new Option<bool>(new[] { "--autoexit", "-x" }, () => { return false; }, "Exit after carrying out directed tasks");
var saveJsonOption = new Option<bool>(new[] { "--saveJSON", "-s" }, () => { return false; }, "Export on deck JSON file after calculating");
var jsonFileOption = new Option<string?>(new[] { "--JSONfile", "-f" }, () => { return null; }, "File name for exported JSON file");
var fileNameArgument = new Argument<string?>("Filename", () => { return null; }, "The file to load.");
RootCommand _cmd = new()
{
immediateCalcOption,
autoExitOption,
saveJsonOption,
jsonFileOption,
fileNameArgument
};
_cmd.SetHandler<bool, bool, bool, string?, string?, IConsole>(Handler, immediateCalcOption, autoExitOption, saveJsonOption, jsonFileOption, fileNameArgument);
return _cmd.Invoke(args);
}
static void Handler(bool immediatecalc, bool autoexit, bool saveJSON, string? jsonFile, string? sourceFile, IConsole console)
{
console.WriteLine("Immediate calc " + immediatecalc);
console.WriteLine("Autoexit " + autoexit);
console.WriteLine("saveJSON " + saveJSON);
console.WriteLine("Json file is " + jsonFile);
console.WriteLine("Source file is " + sourceFile);
}
}
}
this worked for me with the args input filename -c -x -s -f hello gave me this output
Immediate calc True
Autoexit True
saveJSON True
Json file is hello
Source file is filename

can't Specify an audio profile using Google.Cloud.TextToSpeech.V1 in c#

I'm trying to convert Text To audio using Google.Cloud.TextToSpeech.V1. it works fine but I do not know how can I Specify an audio profile to use using c# while I found code in Node.js and python But Not anything in c# this is my code
static void Main(string[] args)
{
List<Word> lst = IntialData();
System.Environment.SetEnvironmentVariable("GOOGLE_APPLICATION_CREDENTIALS", #"C:\Users\Admin\TextToSpeechApiDemo\key.json");
var client = TextToSpeechClient.Create();
// The input to be synthesized, can be provided as text or SSML.
foreach (Word item in lst)
{
var input = new SynthesisInput
{
Text = item.Name,
};
// Build the voice request.
var voiceSelection = new VoiceSelectionParams
{
LanguageCode = "ar",
//SsmlGender = SsmlVoiceGender.Female,
Name = "ar-XA-Wavenet-A"
};
// Specify the type of audio file.
var audioConfig = new AudioConfig
{
AudioEncoding = AudioEncoding.Linear16,
};
// Perform the text-to-speech request.
var response = client.SynthesizeSpeech(input, voiceSelection, audioConfig);
// Write the response to the output file.
using (var output = File.Create(#"E:\Noursound\sim\ar-XA-Wavenet-A\" + item.Id.ToString() + ".wav"))
{
response.AudioContent.WriteTo(output);
}
}
}
I found this code in python he set effects_profile_id
audio_config = texttospeech.AudioConfig(
audio_encoding=texttospeech.AudioEncoding.MP3,
effects_profile_id=[effects_profile_id],
How can i do that using c#
The problem was in the version on the NuGet package i used 1.0.0-beta01 , and it's not have the EffectsProfileId property but after update it to version to Google.Cloud.TextToSpeech.V1 version 2.3.0 i found the property.
using Google.Cloud.TextToSpeech.V1;
class Program
{
static void Main(string[] args)
{
var config = new AudioConfig
{
AudioEncoding = AudioEncoding.Mp3,
EffectsProfileId = { "your profile ID" }
};
}
}
i created git issue for that on github Here's a link!

Initiate a call with Microsoft Graphs SDK to Teams User

I'm attempting to initiate a call with the Microsoft Graph SDK Create call API using the code sample below. The attempt fails with a Not Found exception.
I have registered the bot application, added the API call permissions and I am able to receive incoming calls from Teams.
It's not clear from the Microsoft documentation whether Teams users can be called directly or whether they have to be allocated a VoIP number. Has anyone been able to use the Graph SDK to call a Teams User? Is there some special configuration a User needs to have in order to be able to receive a call?
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Threading.Tasks;
using Microsoft.Graph.Communications.Common.Telemetry;
using Microsoft.Extensions.Logging;
using Microsoft.Graph;
using Microsoft.Graph.Communications.Calls;
using Microsoft.Graph.Communications.Calls.Media;
using Microsoft.Graph.Communications.Client;
using Microsoft.Skype.Bots.Media;
namespace sipbotcaller
{
class Program
{
private static string APP_NAME = "";
private static string APP_ID = "";
private static string APP_SECRET = "";
private static string TENANT_ID = "";
private static string CALLBACK_URI = "";
private static string CERTIFICATE_THUMBPRINT = "";
private static int MEDIA_PORT = 10000;
private static string PUBLIC_IP = "";
private static string HOSTNAME = "";
static async Task Main(string[] args)
{
Console.WriteLine("Teams Call Console:");
GraphLogger graphLogger = new GraphLogger(APP_NAME);
graphLogger.DiagnosticLevel = System.Diagnostics.TraceLevel.Verbose;
ILogger logger = new ConsoleLogger(graphLogger);
AuthenticationProvider authProvider = new AuthenticationProvider(
APP_NAME,
APP_ID,
APP_SECRET,
TENANT_ID,
graphLogger);
GraphServiceClient graphClient = new GraphServiceClient(authProvider);
var users = await graphClient.Users.Request().GetAsync();
foreach (var user in users)
{
Console.WriteLine($"user Id: {user.Id}.");
Console.WriteLine($"user Display Name: {user.DisplayName}.");
}
var mediaPlatformSettings = new MediaPlatformSettings()
{
MediaPlatformInstanceSettings = new MediaPlatformInstanceSettings()
{
CertificateThumbprint = CERTIFICATE_THUMBPRINT,
InstanceInternalPort = MEDIA_PORT,
InstancePublicIPAddress = IPAddress.Parse(PUBLIC_IP),
InstancePublicPort = MEDIA_PORT,
ServiceFqdn = HOSTNAME,
},
ApplicationId = APP_ID,
};
var builder = new Microsoft.Graph.Communications.Client.CommunicationsClientBuilder(
APP_NAME,
APP_ID,
graphLogger);
builder
.SetAuthenticationProvider(authProvider)
.SetNotificationUrl(new Uri(CALLBACK_URI))
.SetMediaPlatformSettings(mediaPlatformSettings)
.SetServiceBaseUrl(new Uri(CALLBACK_URI));
var client = builder.Build();
AudioSocketSettings audioSockSettings = new AudioSocketSettings {
CallId = Guid.NewGuid().ToString(),
SupportedAudioFormat = AudioFormat.Pcm16K,
StreamDirections = StreamDirection.Sendrecv
};
AudioSocket audioSock = new AudioSocket(audioSockSettings);
var mediaConfig = MediaPlatform.CreateMediaConfiguration(audioSock);
Console.WriteLine($"media config: {mediaConfig}");
Console.WriteLine($"Attempting to call {users.First().DisplayName}.");
var call = new Call
{
CallbackUri = CALLBACK_URI,
TenantId = TENANT_ID,
Targets = new List<InvitationParticipantInfo>()
{
new InvitationParticipantInfo
{
Identity = new IdentitySet
{
User = new Identity
{
DisplayName = users.First().DisplayName,
Id = users.First().Id
},
}
}
},
RequestedModalities = new List<Modality>()
{
Modality.Audio
},
MediaConfig = new AppHostedMediaConfig()
{
Blob = mediaConfig.ToString(Newtonsoft.Json.Formatting.None)
},
};
var callResult = await client.Calls().AddAsync(call);
Console.WriteLine($"Call result {callResult.Id}.");
Console.WriteLine("Finished.");
Console.WriteLine("Press any key to exit...");
Console.ReadLine();
}
}
}
Result:
<snip>
StatefulCall: Verbose
StatefulCall: Info
StatefulCall: Verbose
StatefulCall: Info
StatefulCall: Info
StatefulCall: Error {
"error": {
"code": "itemNotFound",
"message": "Unexpected exception returned from the service.\r\nStatus Code: NotFound"
}
}
StatefulCall: Info

How to write english transcription in console correctly?

I want to write english transcription in console.
In debugger I have this səˈdʒest
but in console I have s??d?est.
How to resolve this problem ? Thanks!
Up
Client for getting transcription
class TranslationFormattedResult
{
public string Transcription { get; set; }
public List<string> TranslatedWordList = new List<string>();
}
class TranslatorClient
{
private TranslationServiceSoapClient _client = new TranslationServiceSoapClient("TranslationServiceSoap");
public async Task<TranslationFormattedResult> GetTranslationAsync(string word)
{
var result = await _client.GetTranslationAsync("er", "General",
word,
lang: "ru",
limit: 3000,
useAutoDetect: true,
key: "",
ts: "MainSite",
tid: "");
var translationResult = new TranslationFormattedResult {Transcription = await GetTranscriptionAsync(result)};
return translationResult;
}
private async Task<string> GetTranscriptionAsync(TranslationResult result)
{
var task = new Task<string>(() =>
{
string pr = null;
string pattern = "\\[.+\\]";
var match = Regex.Match(result.result, pattern);
if(match.Success)
{
pr = match.Value.Trim('[', ']');
}
return pr;
});
task.Start();
return await task;
}
}
And main method
class Program
{
static void Main(string[] args)
{
//this works
var client = new TranslatorClient();
var ts = client.GetTranslationAsync("suggest")
.ContinueWith(r =>
{
var transcription = r.Result.Transcription;
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine(transcription);
Console.WriteLine("press any key");
Console.ReadKey();
}
);
ts.Wait();
}
}
You should:
set the OutputEncoding to Unicode: Console.OutputEncoding = Encoding.Unicode;
run your program
right click on the console window
in the properties window change the console font and set it to Consolas.
class Program {
static void Main( string[ ] args ) {
Console.OutputEncoding = Encoding.Unicode;
Console.WriteLine( "səˈdʒest" );
}
}
The result in the console is:
Is this Russian?
If so, try running chcp 866 at the command line.
Refer to this
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/chcp.mspx?mfr=true
This answer also suggests a specific (or at least, different) font may need to be selected (not sure if this applies to Russian or not) Unicode characters in Windows command line - how?

some delay processing message in MessageInterceptor

Sorry, my english is not quite well.
I'm new in programming world and tried to create an application using messageinterceptor on windows mobile 6.5.3.
but when i send text message to my phone, there was delay about 30 seconds or more before the message is processed, either text message which contain keywords or not.
I read several sources before deciding to try to make my own application, but these source are using Windows Form (GUI), instead of using Windows Form, i make it run in console mode.
here is the code:
using System;
using System.Linq;
using System.Collections.Generic;
using System.Text;
using Microsoft.WindowsMobile.PocketOutlook.MessageInterception;
using Microsoft.WindowsMobile.PocketOutlook;
using Microsoft.WindowsMobile;
using System.IO;
namespace PenerimaPesan
{
class Program
{
static void Main(string[] args)
{
string applicationID;
applicationID = "tracker";
MessageInterceptor pesanmasuk = null;
pesanmasuk = new MessageInterceptor();
pesanmasuk.EnableApplicationLauncher(applicationID);
if (MessageInterceptor.IsApplicationLauncherEnabled(applicationID))
{
string keyword;
StreamReader key = new StreamReader(#"\Windows\conf.txt");
string data = key.ReadToEnd();
string[] isi = data.Split(new char[] { '\n' });
keyword = isi[1];
keyword = keyword.Replace(" ", "");
pesanmasuk = new MessageInterceptor(InterceptionAction.NotifyAndDelete, false);
pesanmasuk.MessageCondition = new MessageCondition(MessageProperty.Body, MessagePropertyComparisonType.StartsWith, ""+keyword);
pesanmasuk.MessageReceived += new MessageInterceptorEventHandler(pesanmasuk_MessageReceived);
}
}
static void pesanmasuk_MessageReceived(object sender, MessageInterceptorEventArgs e)
{
SmsMessage pesan = e.Message as SmsMessage;
if (pesan != null)
{
string perintah;
string[] command = pesan.Body.Split(new char[] { '.' });
perintah = command[1];
if (perintah == "helo")
/*do some Stuff*/
}
}
}
I've never used MessageInterceptor, so I decided I'd try to implement this code in my application. To test it, I renamed Main to Main2, then cleaned it up to match "my style".
Anyway, I ran into errors when I tried wrapping the MessageInterceptor in a using block - not because MessageInterceptor does not implement IDispose, but because you have declared a new instance of it.
Take a look at this snippet of your code:
MessageInterceptor pesanmasuk = new MessageInterceptor();
pesanmasuk.EnableApplicationLauncher(applicationID);
if (MessageInterceptor.IsApplicationLauncherEnabled(applicationID)) {
string keyword;
StreamReader key = new StreamReader(#"\Windows\conf.txt");
string data = key.ReadToEnd();
string[] isi = data.Split(new char[] { '\n' });
keyword = isi[1];
keyword = keyword.Replace(" ", "");
pesanmasuk = new MessageInterceptor(InterceptionAction.NotifyAndDelete, false);
OK, right there. Stop. You created a new instance of your pesanmasuk variable, set Properties, did some checking, worked with data from a text file, then...
Created a new instance of your pesanmasuk variable.
All of your previous settings are now whipped out.
I'm guessing your first instance is running and perhaps the second instance has to wait for the first instance to time out before it can be created.
At this point, I'm interested to learn just how to use this MessageInterceptor on MSDN, looked into the example there, and came up with this [untested] version:
static void Main2(string[] args) {
const string stackOverflowUrl = #"http://stackoverflow.com/questions/8520488/some-delay-processing-message-in-messageinterceptor";
string empty = String.Empty;
StreamReader key = new StreamReader(#"\Windows\conf.txt");
string data = key.ReadToEnd();
string[] lines = data.Split(new char[] { '\n' });
string keyword = lines[1].Replace(" ", empty);
string applicationID = "trackingApplication";
using (MessageInterceptor smsInterceptor = new MessageInterceptor(applicationID, false)) {
smsInterceptor.InterceptionAction = InterceptionAction.NotifyAndDelete;
smsInterceptor.MessageCondition = new MessageCondition(MessageProperty.Body, MessagePropertyComparisonType.StartsWith, empty + keyword);
smsInterceptor.MessageReceived += new MessageInterceptorEventHandler(Intercept_MessageReceived);
smsInterceptor.EnableApplicationLauncher(applicationID);
if (MessageInterceptor.IsApplicationLauncherEnabled(applicationID)) {
// Here, you'd need to launch your Form1 or enable some timer,
// otherwise the code will return immediately and the MessageInterceptor
// instance will be disposed of.
}
smsInterceptor.MessageReceived -= MessageInterceptorEventHandler;
}
}
static void Intercept_MessageReceived(object sender, MessageInterceptorEventArgs e) {
SmsMessage newMessage = e.Message as SmsMessage;
if (newMessage != null) {
Console.WriteLine("From: {0}", newMessage.From.Address);
Console.WriteLine("Body: {0}", newMessage.Body);
string[] command = newMessage.Body.Split(new char[] { '.' });
string line = command[1];
if (line == "helo") {
/*do some Stuff*/
}
}
}
I hope this helps, but keep in mind that I've never actually used this control and my code has not been tested.

Categories