XML config path through c# - c#

I have a xml file which the path to a particular report folder hardcoded.
eg. C:\git\ProjNew\Proj\Projects_2018\ and C:\git\ProjNew\Proj\Reports\
and xml looks like this:
<SampleFiles>
<SampleFileLocation>C:\git\ProjNew\Proj\Projects_2018\ </SampleFileLocation>
<ReportFileLocation>C:\git\ProjNew\Proj\Reports\</ReportFileLocation>
</SampleFiles>
when someone gets this project from git, they have to manually go to this path and make changes. In the background code, there is a lot of logic happening, is there a way to update it in c#
The c# file looks like this:
[XmlRoot(ElementName = "SampleFiles")]
public class SampleFiles
{
public string SampleFileLocation { get; set; }
public string ReportFileLocation { get; set; }
public SampleFiles()
{
SampleFileLocation = null;
ReportFileLocation = null;
}
}
how do i modify this code in c# so that it doesnt need to be updated by each user .
Thanks,

Related

Backendless c# desktop application saving data but by empty or null values

I have a desktop app written in c# and I added app id and key id
and used this code to add data to database but the data is always empty or null.
var film = new Film();
film.setName(“soooft”);
film.setGenre(“aaa”);
film.setPlot(“fdgveqw”);
film.setUrl(“gdfwrw”);
var f = Backendless.Data.Of<Film>().Save(film);
I googled Backendless and it's a third-party solution. (See https://github.com/Backendless/.NET-SDK)
Usage gets explained at https://backendless.com/docs/dotnet/data_data_object.html
But I'm suspicious about why you use setName(), setGenre(), setPlot and setUrl in your code. Seems your Film class is missing properties. I would expect you'd be writing this instead:
var film = new Film();
film.Name = “soooft”;
film.Genre = “aaa”;
film.Plot = “fdgveqw”;
film.Url = “gdfwrw”;
But that would mean those fields are declared as public properties in your class like this:
public class Film
{
public string Name { get; set; }
public string Genre { get; set; }
public string Plot { get; set; }
public string Url { get; set; }
}
So I don't know why you have those setName and other methods. The Backendless API specifies that these fields need to be public properties so it can read them through reflection. Your code seems to suggests that they're not proper properties as indicated by their example and my code of the Film() class.
Make sure to use public get/set properties instead of private fields and the data will be saved properly.

Is there a way to load object data in void Load() without assigning each property separately (C#)?

I'm working on a small WPF app to help me with file organisation. The class I store most of my data in is Project and it contains most of the data the app uses. Therefore, it has a lot of properties which I need to be saved and loaded from a file (around 20, using few as an example)
public DateTime Start { get; set; }
public DateTime End { get; set; }
public Int32 Count { get; set; }
public String Name { get; set; }
public HashSet<String> Files { get; set; }
As far as I know, loading an object can be done in 2 main ways:
I.
Project.cs
public Project Load( String file ) {
Project project = json( file ); //to shorten the question
return project;
}
MainWindow
Project project = new Project();
project = project.Load( file );
II.
Project.cs
public void Load( String file ) {
Project project = json( file );
Start = project.Start;
End = project.End;
Count = project.Count;
Name = project.Name;
Files = project.Files;
}
MainWindow
Project project = new Project();
project.Load( file );
Can I somehow still use void Load() function, but assign the whole object at once?
I tried using this = project;, but it is read-only.
Json .net has a method,
Quick and dirty way to do it using reflection
var project = Json(file); //to shorten the question
foreach (var prop in this.GetType().GetProperties())
{
prop.SetValue(this, prop.GetValue(project));
}
return project;
More performant way using compilation this one is more advanced.
But this looks like somewhat wrong in general when using wpf you should be using some MVVM pattern and the project should be the binding context of your view and you can set the created object from json with out making a copy of the object.

C# - Storing struct(s) in setting file

I only wanted to store some main configuration in a settings file, since the configuration may change any time.
The users of my application will be able to manage some stuff in several environments.
Each environment has its own configuration (Paths to network locations basicly).
I built an struct for each environment, but now we have to add some more environments, so it is helpful to store that configuration outside of the source code.
So, let me give you some code. I built two structs to describe each environment:
public struct env_conf
{
string title;
string path_to_xml;
string path_to_sharepoint;
List<subfolder> subfolders;
//Some more strings
public env_conf(string title, string path_to_xml, string path_to_sharepoint ...)
{
//Constructor which is setting the variables
}
}
public struct subfolder
{
string folder;
bool is_standard;
public env_conf(string folder, bool is_standard)
{
//Constructor which is setting the variables
}
}
And this is how the environment configs are set up:
var finance_conf = new env_conf("MyTitle","MyXMLPath","MySPPath",
new List<subfolder>{new subfolder("MySubFolder",true);new subfolder("MySubFolder2",false)}
);
var sales_conf = new env_conf("MySalesTitle","MySalesXMLPath","MySalesSPPath",
new List<subfolder>{new subfolder("MySalesSubFolder",true);new subfolder("MySalesSubFolder2",false)}
);
This last step - the definition of the config-instances shall now be inside of a settings file.
Saving string and also string[] in settings file was no problem for me so far. But now I have more than that...
More than that, I do NOT have Visual Studio. I work with SharpDevelop, which was very good so far.
Marking my structs as serializable was not helpful. Also, when I manually set the type of the setting to MyNamespace.env_conf, it wont appear in the settings designer - only a "?" appears in the Type-field.
So for now, I don't know how to proceed. Also, all the info I find in the internet doesn't seem to help me. Please help me.
How has my XML settings file to be edited?
How has my source code to be edited?
Greetings!
I would do it by creating serializable classes, then you can deserialize the config file to an instance of your class, and you'll have all the settings.
For example, the classes might look like:
[Serializable]
public class EnvironmentConfig
{
public string Title { get; set; }
public string XmlPath { get; set; }
public string SharepointPath { get; set; }
public List<SubFolder> SubFolders { get; set; }
public override string ToString()
{
return $"{Title}: {XmlPath}, {SharepointPath}, {string.Join(", ", SubFolders.Select(s => s.Folder))}";
}
}
[Serializable]
public class SubFolder
{
public string Folder { get; set; }
public bool IsStandard { get; set; }
}
And then in code, you can create an instance of your class, give it some values, and serialize it to a config file. Later, you can deserialize this file to load any changes your users may have made.
This example creates a default config and displays the values to the console. Then it gives the user a chance to modify the file, and displays the new values.
// Create a default config
var defaultEnvCfg = new EnvironmentConfig
{
Title = "USWE Environment",
XmlPath = #"\\server\share\xmlfiles",
SharepointPath = #"\\server\sites\enterpriseportal\documents",
SubFolders = new List<SubFolder>
{
new SubFolder { Folder = "Folder1", IsStandard = true },
new SubFolder { Folder = "Folder2", IsStandard = false }
}
};
// Display original values:
Console.WriteLine(defaultEnvCfg.ToString());
// Serialize the config to a file
var pathToEnvCfg = #"c:\public\temp\Environment.config";
var serializer = new XmlSerializer(defaultEnvCfg.GetType());
using (var writer = new XmlTextWriter(
pathToEnvCfg, Encoding.UTF8) { Formatting = Formatting.Indented })
{
serializer.Serialize(writer, defaultEnvCfg);
}
// Prompt user to change the file
Console.Write($"Please modify the file then press [Enter] when done: {pathToEnvCfg}");
Console.ReadLine();
// Deserialize the modified file and update our object with the new settings
using (var reader = XmlReader.Create(pathToEnvCfg))
{
defaultEnvCfg = (EnvironmentConfig)serializer.Deserialize(reader);
}
// Display new values:
Console.WriteLine(defaultEnvCfg.ToString());
Console.Write("\nDone!\nPress any key to exit...");
Console.ReadKey();

Load data from App.config and connect to property

I have defined:
public static string Firstname { get; set; }
public static string Surname { get; set; }
public static bool DocBook5 { get; set; }
public static string Language { get; set; }
I stored that information in a App.config.
Then i used that to load and connect:
Firstname = ConfigurationManager.AppSettings["firstname"];
Surname = ConfigurationManager.AppSettings["surname"];
DocBook5 = Convert.ToBoolean(ConfigurationManager.AppSettings["docbook5"]);
Language = ConfigurationManager.AppSettings["language"];
But if i'm giving out the properties content with Console.WriteLine it looks like the properties are empty.
The full code of the GetConfig class can be shown there
Maybe anyone knows why?
As mentioned in my comments you are reading the wrong section not from appsetting . If you need a custom section in you config please follow this link .http://haacked.com/archive/2007/03/12/custom-configuration-sections-in-3-easy-steps.aspx/ else move them to appsetting section
Look at your App.config.
The data you stored is in UserSettings and not in appSettings, but you fetched the data from appSettings.
Either you put all your data in appSettings, or you define configSections, in which you add the name UserSettings. (Use 'GetSection' instead of '
AppSettings')
Later, in code, you need to request the specific section, and get the data from there.
Edit: Let me know if you want code example, to match your App.config file

Json to c# Objects in .NET

I've been wanting to make my own dota 2 stats website/app. Basically, I'm using the steam API to gather all the essential data. Most of this data is stored in Json format.
I've been trying to deserialise the format so that I can have the data in a readable format. Ideally I want to turn it into objects and then put them into a data grid so I can present this data properly to the user.
Additionally, I am using the Portable Steam WebAPI Wrapper for C# and Newtonsoft packages.
Public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SteamWebAPI.SetGlobalKey("MysteamKey");
var r2 = SteamWebAPI.Game().Dota2().IDOTA2().GetHeroes().GetResponseString(RequestFormat.JSON);
var ds1 = Newtonsoft.Json.JsonConvert.DeserializeObject(r2);
RootObject hero = JsonConvert.DeserializeObject<RootObject>(r2);
Response.Write("Display Hero Data.. </br></br>");
Response.Write( hero.result.heroes );
Response.Write(hero);
}
}
Here is my Hero class: I basically used this website to come up with it - http://json2csharp.com/ Additionally, the Json file can be found here https://api.steampowered.com/IEconDOTA2_570/GetHeroes/v0001/?key=2D13D618DA712015812E970165632F02&language=en_us
public class Hero
{
public string name { get; set; }
public int id { get; set; }
public string localized_name { get; set; }
}
public class Result
{
public List<Hero> heroes { get; set; }
public int status { get; set; }
public int count { get; set; }
}
public class RootObject
{
public Result result { get; set; }
}
Currently, this is what is displayed from my current code:
" Display Hero Data..
System.Collections.Generic.List`1[Hero]RootObject "
It doesn't seem to display any of the data from the json file :/
I'm sure i'm missing something straighforward here, but I just can't put my finger on it :(
I really need some assistence here, If I can get this working, then I can start pulling all the other data I need. I'd appreciate any help whatsoever.
Thanks in advance.
Response.Write( hero.result.heroes );
That is just going to write out the "string" version of heroes. Since it's an object, it's just giving you List's (or Object's!) .ToString() function (which displays System.Collections.Generic.List`1[Hero]RootObject)
You're going to need to iterate over the collection. I see that you're directly writing out to the response, which I would discourage, but, if you want to see these written out with it, you can use something like this:
foreach(var hero in hero.result.heroes)
{
Response.Write(String.Format("<p>Name: {0}, ID: {1}</p>", hero.name, hero.id)
}
Since it looks like you're messing around with webforms, I suggest you take a look at some tutorials on how to use it (or mvc)

Categories