I have created a web form in asp.NET, unfortunately i do not have the pleasure of being able to use SQL due to some restrictions (internal). I had the idea of exporting the data to a CSV file every time the user clicks submit.
The purpose of this is so that we have a list of computer names, softwares installed, Serial #, ect to keep track.
I have never done anything like this, as i am used to SQL (beginner level), is this even possible, and how would i do it (in code form). I've googled it and all i'm getting is grid view and other forms that i don't want to use, even those seem more complicated than what i want to do. Any help would be appreciated.
I'm using a C# back end to code this.
To clarify, this will be a single CSV file on our network, this web form will only be used internally. So every time someone clicks the submit button it will add a new "row" to the same CSV file. So in the end we have one CSV file with a list of computer names and other information.
Typically you have a model class that represents the data. Here's one:
public class Computer
{
public string SerialNumber {get; set;}
public string Name {get; set;}
public List<string> InstalledSoftware {get; set;}
}
Now that you have a class that can represent the data, it's just a matter of saving or serializing it. You don't have access to a SQL Server database. That's fine. There's other options. You can store it in a structured file format. CSV is not good for this, as you might have multiple pieces of InstalledSoftware per computer, and it's hard to properly handle that with CSV. But other text based formats such as XML and JSON are perfect for this. You can also use "NoSQL" type databases such as MongoDB or RavenDB. You may also be able to use SQLite, which is very lightweight.
Let's start off with some sample data.
List<Computer> computers = new List<Computer>();
computers.Add(new Computer(){
SerialNumber="ABC123",
Name="BOB-LAPTOP",
InstalledSoftware = new List<string>(){
"Notepad", "Visual Studio", "Word"
}
});
computers.Add(new Computer(){
SerialNumber="XYZ456",
Name="JASON-WORKSTATION",
InstalledSoftware = new List<string>(){
"Notepad++", "Visual Studio Code", "Word"
}
});
computers.Add(new Computer(){
SerialNumber="LMN789",
Name="NANCY-SURFACE3",
InstalledSoftware = new List<string>(){
"Outlook", "PowerPoint", "Excel"
}
});
Then it's just a matter of saving the data. Let's try with XML:
var xmlSerializer = new XmlSerializer(typeof(Computer));
using(var stringWriter = new StringWriter())
{
using (var xmlWriter = XmlWriter.Create(stringWriter))
{
xmlSerializer .Serialize(writer, computers);
var xml = stringWriter.ToString();
File.WriteAllText(Server.MapPath("~/App_Data/computers.xml"));
}
}
Or with JSON:
var serializer = new JavaScriptSerializer();
var json = serializer.Serialize(computers);
File.WriteAllText(Server.MapPath("~/App_Data/computers.json"));
Using MongoDB:
var client = new MongoClient(connectionString);
var server = client.GetServer();
var database = server.GetDatabase("ComputerDB");
var computerCollection= database.GetCollection<Computer>("Computers");
foreach(var computer in computers)
{
computerCollection.Insert(computer);
}
Note, I have not tested this code. There's likely bugs. My goal is to give you a starting point, not necessarily 100% working code. I haven't serialized XML in a while and I typically use JSON.NET instead of the built in JavaScriptSerializer.
Also note that if there's any possibility that two users might access the data at the same time, you'll need to take care with the XML and JSON approaches to avoid two people trying to write to the file at once. That's where MongoDB would be better, but you'll have to install the server software somewhere.
Related
So, the title may be misleading. I am building an android app that reads information from a text file, which is located on a cloud server (I would prefer to use either OneDrive, DropBox, or Google Drive [whichever is easiest]; others are fine). Periodically, the program will write information to the text file, still located on the cloud server. So, my question is twofold: Is it possible to read and write to a text file that is located on a cloud server? If so, how in the world would I complete this task? I have noticed the use of WebClient but I can't find a reasonable method or explanation on how this works. This program is coded in C#. This is what I have so far:
private string filename = "datafile.txt";
private List<Category> myList; //A list of an object that I developed ('Category')
//Allow the user interface to handle the error
public void readDatabase() {
//Here is where the magic has to occur, in order to read the file
...
//The usual reader that I use to read standard text files
StreamReader fileReader = new StreamReader(filename);
string line = "";
while ((line = fileReader.ReadLine()) != null)
//convertToCategory is my private method to convert the string to
myLine.Add(convertToCategory(line);
fileReader.close();
}
public void writeDatabase() {
//Here is where the magic has to occur, in order to write to the file
...
//The usual writer that I use to write standard text files
StreamWriter fileWriter = new StreamWriter(filename);
for (int i = 0; i < this.myList.Count; i++)
//toString() is something was developed in my object called 'Category'
fileWriter.WriteLine(fileWriter[i].toString());
fileWriter.close();
}
I would love to use Google Drive as my cloud server, but I am open to other possibilities, if necessary. I just want an easy and efficient method to read/write to the text file.
Possible Implementations:
Have seen possible solutions, where the file is downloaded locally and then read like normal and then uploaded at time of closing. However, if I could get away with it, I don't want the text file to be downloaded.
I have, also, seen several places where a SQL database is used in this instance. But the unfortunate thing is that I don't have any knowledge in developing with SQL. So, using a SQL server would be ideal (because speed is very important for this application) but it will be difficult for me to understand how it works.
Currently trying to make a system that will change a button's color based on if the streamer on the button is live or not. I have a way to download the json string into a variable but I don't know what to do with that. I know I have to check if the variable "stream" in the json output is null which means the streamer is offline but I have 0 clue on how to do that.
I'll edit it with the code that I currently have. I got the json being properly parsed, doing r.stream gives me the appropriate data, but I can't figure out how to figure out if the stream is live or not. This is supposed to check on button press which will refresh the data.
private void Refresh_Click(object sender, RoutedEventArgs e)
{
string url = #"https://api.twitch.tv/kraken/streams/camoduck?client_id=xskte44y2wfqin464ayecyc09nikcj";
var json = new WebClient().DownloadString(url);
Rootobject r = JsonConvert.DeserializeObject<Rootobject>(json);
Console.WriteLine(r.stream);
if r.stream.game = "Grand Theft Auto V"
{
_1GUnit1.Background = Brushes.Red;
}
}
.......
var json = new WebClient().DownloadString(url);
var r = JsonConvert.DeserializeObject<Rootobject>(json);
Console.WriteLine(r.stream);
if (r.stream==null) //How a null check can be done
{
_1GUnit1.Background = Brushes.Red;
}
BTW: If you are using "http://json2csharp.com/", It is propably RootObject not Rootobject
Without you providing more details about what doesn't work in your case, I can't give an in-depth explanation or guidance.
What I can suggest is that you a use an API wrapper, e.g. TwitchLib.
That should help you get started and should provide enough documentation for your case.
You should do more reading on the Twitch API and search for examples. When the stream is offline, consider dropping in some sort of template as there is no data to from the request to parse. When a stream is online, you will have access to the stream object's properties. For example, if your success function returns data, you can assign the results as:
game = data.stream.game;
logo = data.stream.channel.logo;
name = data.stream.channel.name;
url = data.stream.channel.url;
stream = data.stream.stream_type;
This assumes you've setup the appropriate variables (you didn't provide any code).
I would also recommend you spend some time learning how to debug in the browser. More specifically in this case, learn how to inspect your result data. This will demystify what's in the object as you'll see the data and its properties, etc.
Have a look at the following Stack post:
Inspecting large JSON data in Chrome
I have an xml file on server www.testsite.com/sample_file.xml
the structure of xml is like this
<mobileclients>
<clientitem>
<code>SXPFBD</code>
<api>http://SPFD.azurewebsites.net/APIs/</api>
</clientitem>
<clientitem>
<code>STYPFBD</code>
<api>http://SPFD.azurewebsites.net/APIs/</api>
</clientitem>
</mobileclients>
I like to check the code input is present in xml or not using a xamarin cross platform application
I cant keep the file as a resource Since it will keep updating So is it possible to read from an online xml file on the go
Sure, although I would recommend switching to JSON if you can, it is still possible to work with XML.
Here is a code snippet from an app I have developed.
public List<NewsItem> GetNewsItems()
{
var newsXml = XDocument.Load("http://xxxxxxxx.nl/index.php?page=news");
var newsItems = (from newsitem in newsXml.Descendants("newsitem")
select new NewsItem
{
Title = WebUtility.HtmlDecode(newsitem.Element("title").Value),
Message = newsitem.Element("message").Value,
Date = DateTime.ParseExact(newsitem.Element("date").Value, "dd-MM-yyyy HH:mm", CultureInfo.InvariantCulture), // TODO better error handling
User = newsitem.Element("user").Value,
Replies = Convert.ToInt32(newsitem.Element("replies").Value),
Url = newsitem.Element("budgetgamingurl").Value,
Views = Convert.ToInt32(newsitem.Element("views").Value)
}).ToList();
return newsItems;
}
As you can see it loads the document from a URL and handles the XPath queries in-memory.
It is a bit rough, it could use some error handling, but you'll get the basic idea.
I'm working on an UWP application where a user can input data which is placed in a listview. All fine and dandy, but how can I save the user data to a separate file and load it the next time a user boots up the app?
I've tried to find a solution, but I had great difficulty to understand these code snippets and on how to apply these (since I'm fairly new to C# and App development). Would somebody like to explain how I can achieve the saving/loading of the data and explain what the code does?
Thanks in advance! :)
You can create a file like this:
StorageFile ageFile = await local.CreateFileAsync("Age.txt", CreationCollisionOption.FailIfExists);
I can read and write to a file like this:
StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
var ageFile = await local.OpenStreamForReadAsync(#"Age.txt");
// Read the data.
using (StreamReader streamReader = new StreamReader(ageFile))
{
//Use like a normal streamReader
}
if you are trying to write, use OpenStreamForWriteAsync;
If I understood well, you have some kind of object structure that serves as a model for your ListView. When the application is started, you want to read a file where the data is present. When closing the application (or some other event) write the file with the changes done. Right?
1) When your application is loaded / closed (or upon modifications or some event of your choice), use the Windows.Storage API to read / write the text into the file.
2) If the data you want to write is just a liste of strings, you can save this as is in the file. If it is more complicated, I would recommend serializing it in JSON format. Use JSON.NET to serialize (object -> string) and deserialize (object <- string) the content of your file and object structure.
Product product = new Product();
product.Name = "Apple";
...
string json = JsonConvert.SerializeObject(product);
I have a text file with a list of 300,000 words and the frequency with wich they occur. Each line is in the format Word:FequencyOfOccurence.
I want this information to be accessible from within the C# code. I can't hard code the list since it is too long, and I'm not sure how to go about accessing it from a file on the server. Ideally I'd ideally like the information to be downloaded only if it's used (To save on bandwidth) but this is not a high priority as the file is not too big and internet speeds are always increasing.
It doesn't need to be useable for binding.
The information does not need to be editable once the project has been built.
Here is another alternative. Zip the file up and stick it in the clientBin folder next to the apllication XAP. Then at the point in the app where the content is needed do something like this:-
public void GetWordFrequencyResource(Action<string> callback)
{
WebClient client = new WebClient();
client.OpenReadAsync += (s, args) =>
{
try
{
var zipRes = new StreamResourceInfo(args.Result, null)
var txtRes = Application.GetResourceStream(zipRes, new Uri("WordFrequency.txt", UriKind.Relative));
string result = new StreamReader(txtRes.Stream).ReadToEnd();
callback(result);
}
catch
{
callback(null); //Fetch failed.
}
}
client.OpenReadAsync(new Uri("WordFrequency.zip", UriKind.Relative"));
}
Usage:-
var wordFrequency = new Dictionary<string, int>();
GetWordFrequencyResource(s =>
{
// Code here to burst string into dictionary.
});
// Note code here is asynchronous with the building of the dictionary don't attempt to
// use the dictionary here.
The above code allows you to store the file in an efficient zip format but not in the XAP itself. Hence you can download it on demand. It makes use of the fact that a XAP is a zip file so Application.GetResourceStream which is designed to pull resources from XAP files can be used on a zip file.
BTW, I'm not actually suggesting you use a dictionary, I'm just using a dictionary as simple example. In reality I would imagine the file is in sorted order. If that is the case you could use a KeyValuePair<string, int> for each entry but create a custom collection type that holds them in an array or List and then use some Binary search methods to index into it.
Based on your comments, you could download the word list file if you are required to have a very thin server layer. The XAP file containing your Silverlight application is nothing more than a ZIP file with all the referenced files for your Silverlight client layer. Try adding the word list as content that gets compiled into the XAP and see how big the file gets. Text usually compresses really well. In general, though, you'll want to be friendly with your users in how much memory your application consumes. Loading a huge text file into memory, in addition to everything else you need in your app, may untimately make your app a resource hog.
A better practice, in general, would be to call a web service. The service could would perform whatever look up logic you need. Here's a blog post from a quick search that should get you started: (This was written for SL2, but should apply the same for SL3.)
Calling web services with Silverlight 2
Even better would be to store your list in a SQL Server. It will be much easier and quicker to query.
You could create a WCF service on the server side that will send the data to the Silverlight application. Once you retrieve the information you could cache it in-memory inside the client. Here's an example of calling a WCF service method from Silverlight.
Another possibility is to embed the text file into the Silverlight assembly that is deployed to the client:
using (var stream = Assembly.GetExecutingAssembly()
.GetManifestResourceStream("namespace.data.txt"))
using (var reader = new StreamReader(stream))
{
string data = reader.ReadToEnd();
// Do something with the data
}