I used to get values of my configuration like this:
public Startup(IConfiguration Configuration)
{
GraphDBL.Config.Uri = Configuration.GetSection("neo4j:host").Value;
GraphDBL.Config.UserName = Configuration.GetSection("neo4j:user_name").Value;
GraphDBL.Config.Password = Configuration.GetSection("neo4j:password").Value;
}
my Config class `
public class Config
{
public static string Uri { get; set; }
public static string UserName { get; set; }
public static string Password { get; set; }
}
How can i get the result of this in one process? not in turn?
If you examine IConfigurationSection, you will see it has a Value property that you can use to get the value.
You have to specify the full path as a paramter to GetSection, using a colon like this:
GetSection("neo4j:host").Value
You need to add Microsoft.Extensions.Configuration.Binder package to be able to use GetValue extension method.
To map section to a class you need to have properties with same names as configuration
public class Conf
{
public string Host { get; set; }
public string User_Name { get; set; }
public string Password { get; set; }
}
And get configuration like this
GraphDBL.Config = Configuration.GetSection("neo4j").Get<Config>();
Or if you don't want change properties names you can use this trick
public class Config
{
private string host { get; set; }
private string user_name { get; set; }
public string Uri
{
get
{
return host;
}
set
{
host = value;
}
}
public string UserName
{
get { return user_name; }
set
{
user_name = value;
}
}
public string Password { get; set; }
}
And get config
GraphDBL.Config = Configuration.GetSection("neo4j").Get<Config>(options => options.BindNonPublicProperties = true);
Related
I have the below classes.
public class Source { public string ConfigData { get; set; } }
public class Configuration { public IEnumerable<IpAddress> IpAddresses { get; set; } }
public class IpAddress
{
public string Start { get; set; }
public string End { get; set; }
public bool IsValid { get; set; }
public Family IPFamily { get; set; }
}
First, I am getting the ConfigData as string from a source and deserializing it below:
var storedIPAddresses = JsonConvert.DeserializeObject<Configuration>( source.ConfigData).IpAddresses;
Next I am doing some checks, which essentially sets the values of IsValid and IPFamily.
if (storedIPAddresses.Any())
{
foreach (var ipDetail in storedIPAddresses)
{
if (!string.IsNullOrEmpty(ipDetail.StartIpAddress) && !string.IsNullOrEmpty(ipDetail.EndIpAddress))
{
if (bla == blabla)
{
ipDetail.IsValid = true;
ipDetail.IPFamily = IPAddressFamily.IPV4;
}
}
}
}
Lastly, I am supposed to return the souce object by chucking in the updated storedIPAddresses inside, which is where I need some guidance.
I am able to do in following way; but looking for any more elegant way?
var config = new Configuration();
config = JsonConvert.DeserializeObject<Configuration>(source.ConfigData);
config.IpAddresses = storedIPAddresses;
source.ConfigData = JsonConvert.SerializeObject(config);
return source;
I am using ef core and mapster. I have some columns in my db that are nullable.
When I get them from the db, C# stores them as nulls(which makes sense). I want to return these fields are empty strings though when I send them back via my api.
public class CompanyDto
{
public string Website { get; set; }
}
public class Company
{
public int Id { get; set; }
public string Website { get; set; } = "";
}
company.Adapt<CompanyDto>()
what is the best way to make it so Website in the CompanyDto is an empty string.
Classic setter will do the job as well
public class Company
{
public int Id { get; set; }
private string _website;
public string Website
{
get { return _website; }
set { _website = value ?? string.Empty; }
};
public Company ()
{
_website = string.empty;
}
}
I am invoking a method in my constructor like below.Is this the right way to do to set properties based on some validations.Please suggest.
public class Asset
{
public Asset(string id)
{
SetStorageId(id);
}
public string AssetId { get; set; }
public string UtilId { get; set; }
public string MappingId { get; set; }
public bool IsActive { get; set; }
private void SetStorageId(string id)
{
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
AssetId = id;
}
else
{
UtilId = id;
}
}
}
In my opinion your design should be like below,
You should abstract common items to base class and create specific class inheriting this,
and decide from client(consumer) which instance do you need and construct it
public class AssetBase
{
public string MappingId { get; set; }
public bool IsActive { get; set; }
}
public class Asset : AssetBase
{
public string AssetId { get; set; }
}
public class Util : AssetBase
{
public string UtilId { get; set; }
}
static void Main(string[] args)
{
string id = Console.ReadLine();
if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
{
Asset asset = new Asset();
asset.AssetId = id;
}
else
{
Util util = new Util();
util.UtilId = id;
}
}
simply try this
public class Asset
{
private string id;
public string AssetId { get; set; }
public string UtilId { get; set; }
public string Id
{
set
{
if (Regex.Match(value, "^[A-Z][a-zA-Z]*$").Success)
{
this.id = value;
}
else
{
UtilId = value;
}
}
get
{
return id;
}
}
}
When you create a property in c#, a private variable is created for that property on compile time. When you try to set the Id property in the code above the Id you pass goes into the value keyword and you can perform your validations on the value keyword and set your property accordingly.
No need to complicate your code with set methods, constructors or deriving classes
or you can even use data annotations which is a more elegant way https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx#Properties
using System.ComponentModel.DataAnnotations;
public class Asset
{
[RegularExpression("^[A-Z][a-zA-Z]*$")]
public string Id { get; set; }
}
It's not wrong. It can possibly grow to be a little confusing. Maybe you can make it clearer by moving the bod of SetStorageId to the constructor. Perhaps there is no need to complicate with subclassing, relative to other code within the project.
i have json string as
{"AccountNo":"345234533466","AuthValue":"{\"TopUpMobileNumber\":\"345234533466\",\"VoucherAmount\":\"100\"}"}
to parse this string i have created class as
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
}
in AuthValue it gives me output as {\"TopUpMobileNumber\":\"345234533466\",\"VoucherAmount\":\"100\"} which is absolutely correct. now i want to modify my class in such way that i want AuthValue in string format as well and in seprate member variable format.
so i modify my class in this way but it gives error
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
public Auth ????? { get; set; }
}
public class Auth
{
public string TopUpMobileNumber { get; set; }
public string VoucherAmount { get; set; }
}
My requirement is
AuthValue whole json string i required
in another variable i want member wise values
Parsing Logic
UserContext conObj1 = new UserContext();
conObj1 = JsonConvert.DeserializeObject<UserContext>(context);
Note : No modification in json string is allowed.
I'm not very familiar with JsonConvert or Json.NET so I'm not sure what options are available for that. Personally I'd just call the deserializer again immediately afterwards.
UserContext conObj1 = new UserContext();
conObj1 = JsonConvert.DeserializeObject<UserContext>(context);
conObj1.AuthObject = JsonConvert.DeserializeObject<Auth>(conObj1.AuthValue);
You could move this into the class if you wanted and call it directly off the deserialized class.
public class UserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
public Auth AuthObject { get; private set; }
internal UserContext Deserialize()
{
// Serialize the object
this.AuthObject = JsonConvert.DeserializeObject<Auth>(this.AuthValue);
// Return this object for a simple single-line call.
return this;
}
}
// Single object
UserContext conObj1 = new UserContext();
conObj1 = JsonConvert.DeserializeObject<UserContext>(context).Deserialize();
// Enumeration of object (given that this is supported in JsonConvert)
IEnumerable<UserContext> conObjs = JsonConvert.DeserializeObject<IEnumerable<UserContext>(contexts).Select(c => c.Deserialize()).ToList();
Or if you feel self hating you could go as far as doing the deserialization at the time the property is accessed (although I would avoid this at almost all costs due to the numerous issues it can cause).
public class UserContext
{
private Auth m_auth;
public string AccountNo { get; set; }
public string AuthValue { get; set; }
public Auth AuthObject
{
get
{
if (this.m_auth == null)
{
this.m_auth = JsonConvert.DeserializeObject<Auth>(this.AuthValue);
}
return this.m_auth;
}
}
}
I would suggest using two classes - one for the JSON you're actually receiving, and then one for the object model you want to use:
public class JsonUserContext
{
public string AccountNo { get; set; }
public string AuthValue { get; set; }
}
public class UserContext
{
public string AccountNo { get; set; }
public Auth AuthValue { get; set; }
}
public class Auth
{
public string TopUpMobileNumber { get; set; }
public string VoucherAmount { get; set; }
}
...
var jsonUserContext = JsonConvert.DeserializeObject<JsonUserContext>(json);
var authJson = jsonUserContext.AuthValue;
var userContext = new UserContext {
AccountNo = jsonUserContext.AccountNo,
AuthValue = JsonConvert.DeserializeObject<JsonUserContext>(authJson);
};
I have this model class "UserProfile", it's the original UserProfile class of Membership with a few added properties and methods.
[Table("UserProfile")]
public class UserProfile
{
public UserProfile()
{
this.DictionaryFrom = "eng";
this.DictionaryTo = "hun";
this.trainingType = "normal";
}
[Key]
[DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]
public int UserId { get; set; }
public string UserName { get; set; }
public string DictionaryFrom { get; set; }
public string DictionaryTo { get; set; }
public string trainingType { get; set; }
public virtual ICollection<ForeignExpression> learnedexpressions { get ; set ; }
}
My problem is that upon registering a new user, the three fields in the constructor don't get the values assigned to them (so, there's a NULL in the database for each of them).
The user can set them by choosing values from a list, but I'd like to have a default value for all of them. What am I doing wrong?
Not being a C# aficionado, I'd do something like this... there's probably a "better" way of doing it.
private string myValue = "default value";
public string MyValue {
get { return myValue; }
set {
if (null != value) { myValue = value; }
}
}