Regarding WPF, need advice on data sources and data binding - c#

I am not new to WPF, but I am still a rookie. Let's say, I want to build an application which stores data about a person in an unique and separate file, and not in a database, sort of, like, Notepad. My application should do the following things.
It should be able to save a person's info in an unique file.
It should be able to open an user specified file and auto fill the properties/form.
How do I achieve this? Is the XML binding only way to achieve this, or is there an any other alternative? What I mean is, If I use XML binding I can write code which will enable the user to open and save different XML files, but I also read that binding to XML should be avoided from the architecture perspective. So, is there an alternative solution for my problem?

I think if you try doing the stuff by using a Reading and writing the things to a CSV(Comma separated values) file(If not planning to implement databases) then you can achieve what you wanted.
Also if you are planning to have a separate file for each user its not at all a good idea.
Its not possible to explain everything thing here . So please have a look to link posted below , in which it has explained in detail how to achieve Reading and Writing to a csv file .
This example has been posted from here for getting full detail please look to following link Reading and writing to a csv file

Apparently your requirement is to save person details into a unique file. If you really want to use that approach, one option is using XMLSerialization.
You can create your normal person object for data binding.
When you want to save data into the specific person's file you can serialize the object and save file with a proper name (person id or so)
When you want to get Person data back from the file, you can deserialize the it directly to a person object.
// Serialize and write to file
Person person = myPerson;
var serializer = new XmlSerializer(person.GetType());
using (var writer = XmlWriter.Create("person1.xml"))
{
serializer.Serialize(writer, person);
}
// Deserialize back to an instance
var serializer = new XmlSerializer(typeof(Person));
using (var reader = XmlReader.Create("person1.xml"))
{
var person= (Person)serializer.Deserialize(reader);
}

For saving user data, such as sessions and settings. There are plenty of ways you can do this.
Saving to data to txt files. See here.
Saving data to a database. See here.
My personal favourite, saving to the Settings file. See here.
These are only some of the ways you can save data locally.
Note that I mentioned saving data to a database because it is something that you shouldn't completely knock, especially if you will be saving lots of data.
To answer your question more directly, I would suggest that you go with option 3. For relatively small sets of data, like user info and user settings, it would be your best bet to save them to the built in Settings file. It's dead easy.
Good luck!

Related

Change the table that Orchard reads from

I have followed tutorial on how to write content part in Orchard CMS.
http://docs.orchardproject.net/Documentation/Writing-a-content-part
So, my content part writes the data from the backend to the record table that I wanted to, but the backend isn't reading saved custom content from the same table, i.e. when I manually change the record value in the database and refresh orchard admin, I don't see it changed.
How to change this?
That documentation article is slightly misleading because while the code it provides does store your data in the table you created in the database, it also stores the data within Orchards document storage (xml stored in the ContentVersionRecord table, column called data I believe). So basically for fetching data it will use the document storage, for any querying/filtering it will use the data stored in your record. You can change your code so it will only store it in your table if you'd prefer.
public double Latitude
{
get { return Record.Latitude; }
set { Record.Latitude = value; }
}
So yeah, I shall try to update the documentation tonight because that article is particularly confusing. Have a look at Bertrand's article on Orchard's document storage model: The Shift. Useful read
And I know it's annoying to hear this, but when you are playing with Orchard, it's best to play by its rules. Is there a particular reason you need to modify data directly in the db? Or just playing around?

How to store list of static data in C#?

I am working on a website and I want a drop-down to display the list of cities. Where should I store the list of cities for faster access? I do not want to store this data in DB.
Is it a good idea to store it in XML file?
I would store it in Cache, possibly with a Sql Dependency or File Dependency.
public DataTable GetCities(bool BypassCache)
{
string cacheKey = "CitiesDataTable";
object cacheItem = Cache[cacheKey] as DataTable;
if((BypassCache) || (cacheItem == null))
{
cacheItem = GetCitiesFromDataSource();
Cache.Insert(cacheKey, cacheItem, null,
DateTime.Now.AddSeconds(GetCacheSecondsFromConfig(cacheKey),
TimeSpan.Zero);
}
return (DataTable)cacheItem;
}
If you want to store it in XML, that's fine too but you'll have to publish the file to all servers in the farm each time there is a change.
Store it in a text file. This avoids the overhead of XML parsing. Load using File.ReadAllLines().
You can store the list in an XML file or other flat file format, but I guess it depends on what your reasons are for not wanting to store it in the database.
You mentioned faster access, but you might want to expound on that. If you mean you don't want the overhead of accessing the database on every request, then have you thought about storing it in the database and caching the list on application start-up instead? This way, you get the benefits of a database, yet only pay the overhead once.
For small applications, however, an XML file would be just fine.
If the list will never change, then just declare it as a const array of strings in your code.
If it may change occasionally, then put it in an xml file or a database table, but cache it when you have read it so it only needs to be read once in any session.
I believe XML is the best solution, and it would be better to use DOM parser rather than SAX.
You can also load the file into the session whenever it is not loaded to decrease the number of reads of the XML, but this will use more RAM on the server, be sure not to load unnecessary data because it will be loaded into the server's RAM for each session. You can load it only for logged in users if it makes sense.
What I'm about to suggest is HORID style, but I think the quickest you can get and with the smallest "footprint":
public static readonly string [] CityList = new string []
{
"Sydney",
"New York",
"London"
};
Now, I hope you don't like the solution, and can give us all a little more context so that we might be able to offer an elegant and maintainable solution to your problem; but if all your after is speed...

Making a Simple Database Program in C#

I'm currently writing a simple text analysis program in C#. Currently it takes simple statistics from the text and prints them out. However, I need to get it to the point where in input mode you input sample text, specifying an author, and it writes the statistics to a database entry of that specific author. Then in a different mode the program will take text, and see if it can accurately identify the author by pulling averages from the DB files and comparing the text's statistics to sample statistics. What I need help with is figuring out the best way to make a database out of text statistics. Is there some library I could use for this? Or should I simply do simple reading and writing from text files that I'll store the information in? Any and all ideas are welcome, as I'm struggling to come up with a solution to this problem.
Thanks,
PardonMyRhetoric
You can use and XmlSerializer to persist your data to file really easily. There are numerous tutorials you can find on google that will teach you how in just a few minutes. However, most of them want to show you how to add attributes to your properties to customize the way it serializes, so I'll just point out that those aren't really necessary. So long as you have the [Serializeable] tag over your class all you need is something that looks like this to save:
void Save()
{
using (var sw = new StreamWriter("somefile.xml"))
(new XmlSerializer(typeof(MyClass))).Serialize(sw, this);
}
and something like this in a function to read it:
MyClass Load()
{
XmlSerializer xSer = new XmlSerializer(typeof(MyClass));
using (var sr = new StreamReader("somefile.xml"))
return (MyClass)xSer.Deserialize(sr);
}
I don't think in this stage you'll need a database. Try to select appropriate data structures from the .NET framework itself. Try to use dictionary or lists, don't use arrays for this, and the methods you write will become simpler. Try to learn LINQ - it's like queries to database, but to regular data structures. When you'll get this and the project will grow, try to add a database.

how to insert data into db as a serialized object

my basic question is how to insert data into DB as a serialized object and how to extract and use it then ... any suggestion !!?
e.g :
{id:1, userId:1, type:PHOTO, time:2008-10-15 12:00:00, data:{photoId:2089, photoName:A trip to the beach}}
as you see how could I insert data into column Data and then to use it !?
another question is that if I stored the photoName inside Data instead of using JOINS and get the name from it's table (photos) according to it's Id thats will not implement the last update on the photoName (right !?) besides that I'll not be able to make a relation between table photos and the Current table - (Id => photoId) - if I stored data like that .. so part of the problem is that I don't know exactly what kind of information are going to be stored in colum Data So I can't customize a separate column for every type of these information ...
Typically I see two options for you here.
You can store an XML serialized object into the database, and simply use standard XML Serialization, here is an example that you can adapt for your needs.
You can create a true table for this object, and do things the "Standard" way.
With option 1, filtering/joining/searching on the information in the "data" column although still technically possible, is NOT something i would recommend and would be more for a static storage process in my opinion. Something like a user settings entity, or some other item that is VERY unlikely to be needed for a backend query.
With option 2, yes, you have to do more work, but if you define the object well, it will be possible.
Clarification
With regards to my example in #1 above. You would write out to a memory stream, etc for the serialization rather than a file.
If you don't want to store the data relationally, you're really better off not using a relational database. Several object databases speak JSON and would be able to handle this kind of problem pretty easily.
You can store it as JSON string and use JSONSerializer of JSON lib
http://json-lib.sourceforge.net/apidocs/index.html
to convert javabean into json string/object and vice versa.
Generally we use this to store the configuration where no of config parameters are unknown.
Regarding saving an object in your database; you can serialize your object into xml using XDocument.ToString() and save it in database's xml datatype column.
cmd.Parameters.AddWithValue("#Value", xmldoc.ToString());
Checkout, Work with XML Data Type in SQL Server

XML tag name being overwritten with a type defined

We are communicating with a 3rd party service using via an XML file based on standards that this 3rd party developed. They give us an XML template for each "transaction" and we read it into a DataSet using System.Data.DataSet.ReadXML, set the proper values in the DataSet, and then write the XML back using System.Data.DataSet.WriteXML. This process has worked for several different files. However, I am now adding an additional file which requires that an integer data type be set on one of the fields. Here is a scaled down version:
<EngineDocList>
<DocVersion>1.0</DocVersion>
<EngineDoc>
<MyData>
<FieldA></FieldA>
<FieldB></FieldB>
<ClientID DataType="S32"></ClientID>
</MyData>
</EngineDoc>
</EngineDocList>
When I look at the DataSet created by my call to ReadXML to this file, the MyData table has columns of FieldA, FieldB, and MyData_ID. If I then set the value of MyData_ID and then make the call to WriteXML, the export XML has no value for ClientID. Once again, if I take a way the DataType, then I do have a ClientID column, I can set it properly, and the exported XML has the proper value. However, the third party requires that this data type be defined.
Any thoughts on why the ReadXML would be renaming this tag or how I could otherwise get this process to work? Alternatively, I could revamp the way we are reading and writing the XML, but would obviously rather not go down this path although these suggestions would also be welcome. Thanks.
I would not do this with a DataSet. It has a specific focus on simulating a relational model. Much XML will not follow that model. When the DataSet sees things that don't match it's idea of the world, it either ignores them or changes them. In neither case is it a good thing.
I'd use an XmlDocument for this.

Categories