Is there any standard way to load array from appSettings.config file in .NET 4.6.1 - appsettings

I have a setting like this in my appSettings.config file
<add key="logFilesLocations" value="[firstfile,secondfile]"/>
Is there any standard way to read these values as arrays directly?
I know I can play with the string after reading the value and split string to get the array, but that is ugly.
I tried this also
public static List<string> LogFilesLocations => (ConfigurationManager.AppSettings.GetValues("logFilesLocations") ?? Array.Empty<string>()).ToList();
But this actually does not return an array.

Got the solution from this answer
https://stackoverflow.com/a/46057375/804517
So I replaced appSettings.config with appSettings.json and put my setting like this
"logFilesLocations": [
"C:\\Users\\Desktop\\Logs",
"C:\\Users\\Desktop\\Logs2"
]
and started reading the values like this
public static List<string> LogFilesLocations => _config.GetSection("logFilesLocations").Get<List<string>>();
As suggested in the answer I had to add Microsoft.Extensions.Configuration, Microsoft.Extensions.Configuration.Binder and Microsoft.Extensions.Configuration.Json packages

Related

How to fix sonarlint warning for one line initialize?

response.setPeopleHealth(new ArrayList<String>() {{
for(HealthEnum e :HealthEnum.values()) {
add(e.getValue());
}
}})
sonarlint gives warning for this.
I tried to convert to singletone but it does not work with for, because it cant be added like arraylist.
Can i use lambda or stream?
For starters stop using the famous anti-pattern of new ArrayList<String>() {{..., than think about your problem to begin with, you have a array - need a List, thus:
List<String> list = Arrays.stream(HealthEnum.values())
.map(HealthEnum::getValue)
.collect(Collectors.toCollection(ArrayList::new));
and pass this ArrayList where you want to, like:
response.setPeopleHealth(list);

Laravel 5.1 translate an array pass to blade

I have this in my controller
public function editProfile(Request $request){
$question1 = Question::where('group',1)->lists('question', 'id');
$question2 = Question::where('group',2)->lists('question', 'id');
return view('user', compact(''question1', 'question2'));
}
$question = {\"1\":\"What is the first name of your best friend in high school?\",\"2\":\"What was the name of your first pet?\",\"3\":\"What was the first thing you learned to cook?\",\"4\":\"What was the first film you saw in the theater?\"}
$question2 = {\"5\":\"Where did you go the first time you flew on a plane?\",\"6\":\"What is the last name of your favorite elementary school teacher?\",\"7\":\"In What city or town does your nearest sibling live?\"}
I would like to translate the value in both question 1 and question 2 and pass it to user blade without changing the key, Any suggestions?
As specified at the localization doc, you need to populate a lang file with translation strings. So, let's say you want to show both Spanish and English strings. In this case you'd need to create two files: /resources/lang/en/messages.php and /resources/lang/es/messages.php. The content of one of those files would be somewhat like this:
<?php
// resources/lang/es/messages.php
return [
'welcome' => 'Bienvenido'
];
This way, you could access the strings in there with the following method: __('messages.welcome'), which would return the string for the language set on your config/app.php -- the default entry is en, by the way, but you can set it to whatever you want. The value in there will define which language will be chosen when selecting strings.
Another method to create translation strings is using the string itself as key, storing them in a JSON file instead of PHP. For example, the following translation string:
{
"I love programming.": "Me encanta programar."
}
would be accessible through this: __('I love programming.').
Having said that, you may solve your problem through the two methods presented above. You could store in your DB keywords for the questions instead of the whole text, and create translation for as many languages as you want. Also, you could keep the questions in your database and create translation strings for those questions. Finally, you'd need to iterate over the fetched entries and translate each one of them, or use some Collection helper to do the hard work for you, like transform or map.

get list of servers Ebean+Play

I need to get a list of all existing servers in the application.conf file, I take a look to EBean class, but i only found how to get an specific server Ebean.getServer("test"), also this returns an EbeanServer object, and i need a string value.
This is part of my application.conf:
db.default.driver=oracle.jdbc.OracleDriver
db.default.url="jdbc:oracle:thin:#//178.20.26.25:1521/orcl"
db.default.user="TEST1"
db.default.password="test1"
db.test.driver=oracle.jdbc.OracleDriver
db.test.url="jdbc:oracle:thin:#//178.20.26.26:1521/orcl"
db.test.user="TEST"
db.test.password="test"
ebean.default="models.*"
ebean.test="models.*"
My expected output is a list that contains (default,test). Does anybody know a way to get this without parsing hole file?
Thanks in advance.
Following code will give set instead of list:
Map<String, String> map = (Map<String, String>) play.Play.application().configuration().getObject("db");
Set<String> keys = map.keySet();
If you want to do it in type safe way and get rid of compiler warning:
Set<String> keys = play.Play.application().configuration().getConfig("db").subKeys();
Both examples will return subkeys of db key which is [default, test].

How can I convert a session variable to a string array?

I’m trying to store an array in a session variable then use it latter like this:
Session["sessionVariable"] = searchString;
Now here I’m trying to store the session variable into a string variable.
String[] sv = Session["sessionVariable"];
When I do I get his error.
Cannot explicitly convert type ‘Object’ to ‘String[]’, An explicit conversion exists, (are you mission a cast?)
I’ve tried various conversions but can’t find the correct one. Can you please help me to find the correct conversion? Thanks.
Try this:
Set:
Session["test"] = new string[] { "1", "2", "3" };
Get:
string[] array = Session["test"] as string[];

How do I use a guid in a mongodb shell query

When using the MongoDB shell, how do I use a guid datatype (which I have used as the _id in my collection).
The following format doesn't work:
>db.person.find({"_id","E3E45566-AFE4-A564-7876-AEFF6745FF"});
Thanks.
You can use easily:
.find({ "_id" : CSUUID("E3E45566-AFE4-A564-7876-AEFF6745FF")})
You have to compare the _id value against an instance of BinData (not against a string). Unfortunately the BinData constructor takes a Base64 string instead of a hex string.
Your GUID value is missing two hex digits at the end, so for the purposes of this example I will assume they are "00". The following values are equivalent:
hex: "E3E45566-AFE4-A564-7876-AEFF6745FF00" (ignoring dashes)
base64: "ZlXk4+SvZKV4dq7/Z0X/AA=="
So your query should be:
>db.person.find({_id : new BinData(3, "ZlXk4+SvZKV4dq7/Z0X/AA==")})
I am assuming that the binary subtype was correctly set to 3. If not, what driver was used to create the data?
You could use the following js function in front of your query like so:
function LUUID(uuid) {
var hex = uuid.replace(/[{}-]/g, ""); // removes extra characters
return new UUID(hex); //creates new UUID
}
db.person.find({"_id" : LUUID("E3E45566-AFE4-A564-7876-AEFF6745FF"});
You could save the function in .js file and load it or open it before you make your query and if you copy the value from your results you should rename the function with:
LUUID for Legacy UUID
JUUID for Java encoding
NUUID for .net encoding
CSUUID for c# encoding
PYUUID for python encoding
I know it's an old issue, but without any additional needs you can use this one:
find({_id:UUID('af64ab4f-1098-458a-a0a3-f0f6c93530b7')})
You can fix this issue by using split() and join() workaround:
for instance if I use "E3E45566-AFE4-A564-7876-AEFF6745FF" hex value with - inside UUID() function, it does not return BinData in mongo so please try removing all the - before passing to UUID function.
db.person.find({"_id":UUID("E3E45566-AFE4-A564-7876-AEFF6745FF".split("-").join(''))});
Or by defining a variable to do it in multiple line:
var uuid = UUID("E3E45566-AFE4-A564-7876-AEFF6745FF".split("-").join(''))
db.person.find({"_id":uuid});
or by creating a simple function:
function BUUID(uuid){
var str = uuid.split("-").join('');
return new UUID(str);
}
db.person.find({"_id": BUUID("E3E45566-AFE4-A564-7876-AEFF6745FF")}).pretty();

Resources