How to get an array from appsettings.json file in .Net 6? - arrays

I've read this excellent SO post on how to get access to the appsettings.json file in a .Net 6 console app.
However, in my json file I have several arrays:
"logFilePaths": [
"\\\\server1\\c$\\folderA\\Logs\\file1.log",
"\\\\server2\\c$\\folderZ\\Logs\\file1A1.log",
"\\\\server3\\c$\\folderY\\Logs\\file122.log",
"\\\\server4\\c$\\folderABC\\Logs\\fileAB67.log"
],
And I get the results if I do something like this:
var builder = new ConfigurationBuilder().AddJsonFile($"appsettings.json", true, true);
var config = builder.Build();
string logFile1 = config["logFilePaths:0"];
string logFile2 = config["logFilePaths:1"];
string logFile3 = config["logFilePaths:2"];
But I don't want to have to code what is effectively an array into separate lines of code, as shown.
I want to do this:
string[] logFiles = config["logFilePaths"].Split(new char[] { '|' }, StringSplitOptions.RemoveEmptyEntries);
But it gives me an error on config["logFilePaths"] saying it's null.
Why would that be null?

To access the logFilePaths as an array, you want to use the Get<T> extension method:
string[] logFilePaths = config.GetSection("logFilePaths").Get<string[]>();

One option is to install Microsoft.Extensions.Configuration.Binder nuget and use Bind (do not forget to setup CopyToOutputDirectory for appsettings.json):
var list = new List<string>();
config.Bind("logFilePaths", list);
Another - via GetSection (using the same nuget to bind a collection):
var list = config.GetSection("logFilePaths").Get<List<string>>();

Related

Is it possible to get multiple random api key from .env?

In my .env file there is something like this:
GOOGLE_MAP_API=AIzaSyByfXuuwxOIaWlefhSxqhMweF-0
Another_API_KEY=5893978af2537e042beb233b1
I would like to create a .env file in which "Another_API_KEY" is randomly choosen from multiple api keys list.
Something like this:
GOOGLE_MAP_API=AIzaSyByfXuuwxOIaWlefhSxqhMweF-0
var r_text = new Array();
r_text[0] = "a3219d4e2772db6e34c62144b27f";
r_text[1] = "5bbe61fe6db548e665a49663eba2";
r_text[2] = "d74ae61790a9937e3f6d5d3ddc83";
var nn = Math.floor(3 * Math.random());
var Another_API_KEY = r_text[nn]
But this is'n working. Is this possible to get random keys from the list to React JS Application from .env file?
.env files store strings so it's not possible to run Javascript inside it.
What you can do, however, is store all keys you want to randomly pick up from in .env and, when you use them inside your app, you pick one of them.
.env
GOOGLE_MAP_API=AIzaSyByfXuuwxOIaWlefhSxqhMweF-0
RANDOM_KEYS="a3219d4e2772db6e34c62144b27f 5bbe61fe6db548e665a49663eba2 d74ae61790a9937e3f6d5d3ddc83"
Then on your code:
// Choose random key from all options
const RANDOM_KEYS_ARRAY = process.env.RANDOM_KEYS.split(" ")
const RANDOM_KEY = RANDOM_KEYS_ARRAY[Math.floor(RANDOM_KEYS_ARRAY.length * Math.random())]
Here's a sandbox with working code:
https://codesandbox.io/s/getting-random-key-from-env-xuup4r
I managed it.
I the file app.js where the command was to get api key from .env: &appid=${process.env.REACT_API_KEY}
I deleted: process.env.
and inserted
'var r_text = new Array();
r_text[0] = "456afa82537e042beb233b25";
r_text[1] = "s54667e042b33b1fa525";
r_text[2] = "456a82537e042beb233b525";
var nn = Math.floor(3 * Math.random());
var REACT_API_KEY = r_text[nn];'
And it works. Thank you

How do I get an array of file names from the iOS File Manager

I'm creating an Audio Recording app and have declared an empty array to store all the names of the files.
var recordingTitles: [String] = []
When I launch the app, I have a function that checks what files are already stored in the File Manager and returns the number of files in order to display the correct number of cells in the collectionView.
override func viewDidLoad() {
super.viewDidLoad()
getNumberOfRecordings()
}
// Get number of actual recording files stored in the File Manager Directory
func getNumberOfRecordings() {
let directoryUrl = getDirectory()
do {
contentsOfFileManager = try myFileManager.contentsOfDirectory(at: directoryUrl, includingPropertiesForKeys: [URLResourceKey(rawValue: recordingsKey)], options: .skipsHiddenFiles)
} catch let error {
print(error.localizedDescription)
}
numberOfRecordings = contentsOfFileManager.count
}
I would like to obtain the names of the files and assign them to the "recordingTitles" array in order to display the correct title for each cell. I've tried reading over the Apple docs for File Manager but haven't found a solution yet. Thank you in advance for your help!
So, contentsOfFileManager is going to consist of NSURL objects. These objects have different fields you can pluck out and use. It looks like you're interested in just the filename so I'd like to draw your attention to the lastPathComponent field of NSURL. From the docs:
This property contains the last path component, unescaped using the replacingPercentEscapes(using:) method. For example, in the URL file:///path/to/file, the last path component is file.
In other words, calling myNsurl.lastPathComponent should yield you the filename. So you can loop through the array that's returned by myFileManager.contentsOfDirectory and get the lastPathComponent of each one and add them to another array which will contain just the filenames.
Use the map function. You probably want something like this:
recordingTitles = try myFileManager.contentsOfDirectory(at:directoryURL,
includingPropertiesForKeys: nil).map {$0.lastPathComponent}

Watson language identification

I had implemented the following curl code using RESTSharp to find the language of sentence "What is your name?".
I followed the "Identify language" under : http://www.ibm.com/smarterplanet/us/en/ibmwatson/developercloud/language-translation/api/v2/#identify
string source = "What is your name?";
string credentials;
string auth = string.Format("{0}:{1}", tuid, tpwd);
string auth64 = Convert.ToBase64String(Encoding.ASCII.GetBytes(auth));
credentials = string.Format("{0} {1}", "Basic", auth64);
var langDet = new RestClient(detURL);
var requestDet = new RestRequest("?text={authToken}",Method.POST);
requestDet.Credentials = new NetworkCredential(tuid, tpwd);
requestDet.AddParameter("text", source, ParameterType.UrlSegment);
IRestResponse responseDet = langDet.Execute(requestDet);
However, when this code is executed I get a list of languages and confidence level while I still am not sure how to accurately specify which language the above sentence goes to. Please help me where I am wrong.
My detUrl variable above is: https://gateway.watsonplatform.net/language-translation/api/v2/identify
you can get what you want using the Alchemy API, which is also available in Bluemix. Here's an example using Java + Watson SDK
AlchemyLanguage service = new AlchemyLanguage();
service.setApiKey("XXXXXXXXX");
Map<String,Object> params = new HashMap<String, Object>();
params.put(AlchemyLanguage.TEXT, "What is your name?");
Language language = service.getLanguage(params);
System.out.println(language);
I use this Java SDK above, but there's a .NET port for it here
https://github.com/dennyboy/WatsonCSharp
Thank you !
I found the answer.
(1) In my code above, I have been passing the {authtoken} instead of the string I had wanted to send (string source in example below
var requestDet = new RestRequest("?text=" + source, Method.POST);
(2) Once done, I had to deserialize the output from "responseDet" and filter the first value (as below). I had used Jsonconvert class.
DataSet data = JsonConvert.DeserializeObject<DataSet>(responseDet.Content);
return data.Tables[0].Rows[0][0].ToString();
My code is working fine. Thanks for your help !

How do I add tags / keywords to a windows file properties details tab using C#

Ideally I would like to use the shell class to add tags to my office documents but I think the tags property is a read only item this way. Does anyone have any other ways?
There is very little on the subject. Thank you for your help.
I looked into the shellfile class a little more. The answer was staring me right in the face.
string[] keywords = new string[x];
var shellFile = ShellFile.FromFilePath(file);
shellFile.Properties.System.Keywords.Value = keywords;
to get the keywords already added to the file use:
var tags = (string[])shellFile.Properties.System.Keywords.ValueAsObject;
tags = tags ?? new string[0];
if (tags.Length != 0)
{
foreach (string str in tags)
{
// code here
}
}
and done!

How can I read the Active Directory schema programmatically

I did some programming for reading the data from Active Directory such as user account or Orgnization info and so on. The code below is like something what I did.
DirectoryEntry entry = new DirectoryEntry(
"LDAP://CN=Users,DC=domain,DC=com",
null,
null,
AuthenticationTypes.Secure
);
DirectorySearcher search = new DirectorySearcher(entry);
using (SearchResultCollection src = search.FindAll())
{
foreach (SearchResult result in src)
{
Console.WriteLine(result.Properties["name"][0] + " : " +
result.Properties["department"][0]);
}
}
The problem is how can I know what properties that target objects have then I can use them to filter the data before get it all.
Any ideas?
If you have a DirectoryEntry, you can inspect its .SchemaEntry:
DirectoryEntry entry = new DirectoryEntry("LDAP://......");
DirectoryEntry schema = entry.SchemaEntry;
This should - if you have the necessary permissions - give you access to the properties defined in the schema - things like MandatoryProperties or OptionalProperties:
foreach (var prop in schema.Properties.PropertyNames)
{
string propName = prop.ToString();
var propValue = schema.Properties[propName].Value;
}
Does that help you get started??
You might also want to have a look at BeaverTail - my C# open-source LDAP browser.
(source: mvps.org)
It will allow you to inspect any LDAP node and see all its properties.

Resources