Moved Filehandler, better error handling

This commit is contained in:
2015-10-19 22:26:32 +02:00
parent d75419d92e
commit 2319c86320
4 changed files with 33 additions and 167 deletions
-1
View File
@@ -53,7 +53,6 @@
<Compile Include="Helper.cs" />
<Compile Include="NetCommand.cs" />
<Compile Include="ComPort.cs" />
<Compile Include="FileHandler.cs" />
<Compile Include="Meting.cs" />
<Compile Include="NetHelper.cs" />
<Compile Include="Properties\AssemblyInfo.cs" />
-150
View File
@@ -1,150 +0,0 @@
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace ErgometerLibrary
{
public class FileHandler
{
public static string DataFolder { get; } = Path.Combine(System.Environment.GetFolderPath(System.Environment.SpecialFolder.MyDocuments), "Ergometer");
public static string UsersFile { get; } = Path.Combine(DataFolder, "users.ergo");
public static void CheckStorage()
{
if(! Directory.Exists(DataFolder))
{
Directory.CreateDirectory(DataFolder);
}
if(! File.Exists(UsersFile))
{
using (Stream stream = File.Open(UsersFile, FileMode.Create))
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(1);
writer.Write("Doctor0tVfW");
writer.Write("password");
}
}
}
//SESSION
public static int GenerateSession()
{
string[] existingSessions = Directory.GetDirectories(DataFolder);
Random rand = new Random();
int sessionID = rand.Next(0, int.MaxValue);
while (existingSessions.Contains(sessionID.ToString()))
{
sessionID = rand.Next(int.MinValue, int.MaxValue);
}
return sessionID;
}
public static void CreateSession(int session, string naam)
{
Directory.CreateDirectory(GetSessionFolder(session));
using (File.Create(Path.Combine(GetSessionFile(session)))) ;
using (File.Create(Path.Combine(GetSessionMetingen(session)))) ;
using (File.Create(Path.Combine(GetSessionChat(session)))) ;
File.WriteAllText(GetSessionFile(session), naam + Environment.NewLine + Helper.Now);
Console.WriteLine("Created session at " + Helper.MillisecondsToTime(Helper.Now));
}
public static void WriteMetingen(int session, List<Meting> metingen)
{
string json = Newtonsoft.Json.JsonConvert.SerializeObject(metingen);
File.WriteAllText(GetSessionMetingen(session), json);
Console.WriteLine("Writing metingen: " + GetSessionMetingen(session));
}
public static List<Meting> ReadMetingen(int session)
{
object metingString = Newtonsoft.Json.JsonConvert.DeserializeObject(GetSessionMetingen(session));
Console.WriteLine("Reading metingen: " + GetSessionMetingen(session));
return (List<Meting>) metingString;
}
public static int[] GetAllSessions()
{
string[] directories = Directory.GetDirectories(DataFolder);
int[] sessions = new int[directories.Length];
for (int i = 0; i < directories.Length; i++)
{
sessions[i] = int.Parse(directories[i]);
}
return sessions;
}
public static void WriteChat(int session, List<ChatMessage> chat)
{
string write = "";
foreach(ChatMessage c in chat)
{
write += c.ToString() + "\n";
}
File.WriteAllText(GetSessionChat(session), write);
Console.WriteLine("Writing chat: " + GetSessionChat(session));
}
private static string GetSessionFolder(int session)
{
return Path.Combine(DataFolder, session.ToString());
}
private static string GetSessionFile(int session)
{
return Path.Combine(DataFolder, session.ToString(), "session.prop");
}
private static string GetSessionMetingen(int session)
{
return Path.Combine(DataFolder, session.ToString(), "metingen.ergo");
}
private static string GetSessionChat(int session)
{
return Path.Combine(DataFolder, session.ToString(), "chat.log");
}
//USER MANAGEMENT
public static Dictionary<string, string> LoadUsers()
{
Dictionary<string, string> users = new Dictionary<string, string>();
using (Stream stream = File.Open(UsersFile, FileMode.Open))
{
BinaryReader reader = new BinaryReader(stream);
int count = reader.ReadInt32();
for (int n = 0; n < count; n++)
{
var key = reader.ReadString();
var value = reader.ReadString();
users.Add(key, value);
}
}
return users;
}
public static void SaveUsers(Dictionary<string, string> users)
{
using(Stream stream = File.Open(UsersFile, FileMode.Open))
{
BinaryWriter writer = new BinaryWriter(stream);
writer.Write(users.Count);
foreach (var kvp in users)
{
writer.Write(kvp.Key);
writer.Write(kvp.Value);
}
writer.Flush();
}
}
}
}
+15 -8
View File
@@ -8,11 +8,11 @@ namespace ErgometerLibrary
{
public class NetCommand
{
public enum CommandType { LOGIN, DATA, CHAT, LOGOUT, SESSION, VALUESET, USER, RESPONSE, REQUEST, LENGTH, SESSIONDATA }
public enum CommandType { LOGIN, DATA, CHAT, LOGOUT, SESSION, VALUESET, USER, RESPONSE, REQUEST, LENGTH, SESSIONDATA, ERROR }
public enum RequestType { USERS, ALLSESSIONS, CURRENTSESSIONS, OLDDATA, SESSIONDATA }
public enum ResponseType { LOGINOK, LOGINWRONG, ERROR, NOTLOGGEDIN }
public enum ValueType { TIME, POWER, ENERGY, DISTANCE }
public enum LengthType { USERS, SESSIONS, SESSIONDATA, DATA, CURRENTSESSIONS}
public enum LengthType { USERS, SESSIONS, SESSIONDATA, DATA, CURRENTSESSIONS }
public double Timestamp { get; set; }
public int Session { get; set; }
@@ -28,7 +28,7 @@ namespace ErgometerLibrary
public string ChatMessage { get; set; }
public Meting Meting { get; set; }
public int LengthValue { get; set; }
//SESSION
public NetCommand(int session)
{
@@ -135,16 +135,23 @@ namespace ErgometerLibrary
{
string[] com = command.Split('»');
Console.WriteLine(command);
int comType = 0;
try
{
comType = int.Parse(com[0]);
}
catch(Exception e)
{
return new NetCommand(CommandType.ERROR, 0);
}
int comType = int.Parse(com[0]);
int session = 0;
if (com[1].StartsWith("ses"))
session = int.Parse(com[1].Substring(3));
else
throw new FormatException("Error in NetCommand: " + com[1] + " is not a valid session.");
string[] args = new string[com.Length-2];
string[] args = new string[com.Length - 2];
for (int i = 2; i < com.Length; i++)
{
args[i - 2] = com[i];
@@ -268,7 +275,7 @@ namespace ErgometerLibrary
if (args.Length != 1)
throw new MissingFieldException("Error in NetCommand: Response is missing arguments");
switch(args[0])
switch (args[0])
{
case "loginok":
return new NetCommand(ResponseType.LOGINOK, session);
@@ -344,7 +351,7 @@ namespace ErgometerLibrary
switch (Type)
{
case CommandType.LOGIN:
command += "1»ses" + Session + "»" + DisplayName + "»" + Helper.Base64Encode(Password) + "»" + IsDoctor;
command += "1»ses" + Session + "»" + DisplayName + "»" + Helper.Base64Encode(Password) + "»" + IsDoctor;
break;
case CommandType.DATA:
command += "2»ses" + Session + "»" + Meting.ToCommand();
+18 -8
View File
@@ -29,10 +29,15 @@ namespace ErgometerLibrary
if (client.Connected)
{
StreamWriter wr = new StreamWriter(client.GetStream(), Encoding.Unicode);
wr.WriteLine(command);
Console.WriteLine("sent " + command);
wr.Flush();
try {
StreamWriter wr = new StreamWriter(client.GetStream(), Encoding.Unicode);
wr.WriteLine(command);
wr.Flush();
}
catch(Exception e)
{
return;
}
}
}
@@ -61,10 +66,15 @@ namespace ErgometerLibrary
*/
if (client.Connected)
{
StreamReader rd = new StreamReader(client.GetStream(), Encoding.Unicode);
string str = rd.ReadLine();
Console.WriteLine("rec " + str);
return str;
try {
StreamReader rd = new StreamReader(client.GetStream(), Encoding.Unicode);
string str = rd.ReadLine();
return str;
}
catch(Exception e)
{
return "";
}
}
else
return "";