Skip to content

Instantly share code, notes, and snippets.

@CipherLab
Last active August 29, 2015 14:03
Show Gist options
  • Save CipherLab/7cabd265666472bed220 to your computer and use it in GitHub Desktop.
Save CipherLab/7cabd265666472bed220 to your computer and use it in GitHub Desktop.
Serialize/deserialize objects
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using System.IO.IsolatedStorage;
using System.Data;
using System.ComponentModel;
public class AdInfo
{
public string LastApp = "";
}
public class Serializers
{
#region pc code
public bool SaveObjectPC(string fileName, object data)
{
bool result = true;
string tempFile = fileName + ".temp";
try
{
if ((File.Exists(tempFile)))
{
File.Delete(tempFile);
}
if (!(Directory.Exists(GetFilePathPC(fileName))))
{
Directory.CreateDirectory(GetFilePathPC(fileName));
}
string strwrite = SerializeToString(data);
Stream stream = File.OpenWrite(tempFile);
byte[] bytes = System.Text.Encoding.UTF8.GetBytes(strwrite);
stream.Write(bytes, 0, bytes.Length);
stream.Flush();
stream.Close();
//stream.Dispose();
File.Copy(tempFile, fileName, true);
if ((File.Exists(tempFile)))
{
File.Delete(tempFile);
}
}
catch (Exception ex)
{
string msg = ex.Message;
result = false;
}
return result;
}
public object LoadObjectPC(string fileName, Type type)
{
object data = null;
string path = fileName;
if ((File.Exists(fileName)))
{
try
{
Stream stream = File.OpenRead(fileName);
byte[] bytes = new byte[Convert.ToInt32(stream.Length - 1) + 1];
stream.Read(bytes, 0, bytes.Length);
stream.Close();
//stream.Dispose();
//converting the encoding otherwise it's not readable in windows mobile
byte[] unicodeString = Encoding.Convert(Encoding.UTF8, Encoding.Unicode, bytes);
Stream memStream = new MemoryStream();
memStream.Write(unicodeString, 0, unicodeString.Length);
data = new object();
XmlSerializer s = new XmlSerializer(type);
memStream.Position = 0;
data = s.Deserialize(memStream);
memStream.Close();
//memStream.Dispose();
return data;
}
catch (Exception ex)
{
string msg = ex.Message;
}
}
return null;
}
public string GetFilePathPC(string directory_in)
{
string check_char = "\\";
if ((directory_in.IndexOf(@"/") > 0))
{
check_char = "/";
}
if (!string.IsNullOrEmpty(directory_in.Trim()))
{
directory_in = directory_in.Substring(0, directory_in.LastIndexOf(check_char) + 1);
}
return directory_in;
}
public void DeleteFilePC(string file_name)
{
try
{
if ((File.Exists(file_name)))
{
File.Delete(file_name);
}
}
catch (Exception ex)
{
}
}
#endregion
public string ByteArrayToStringUtf8(byte[] value)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetString(value, 0, value.Length);
}
public byte[] StringToByteArrayUtf8(string value)
{
UTF8Encoding encoding = new UTF8Encoding();
return encoding.GetBytes(value);
}
public string SerializeToString(object data)
{
XmlSerializer s = new XmlSerializer(data.GetType());
StringWriter sw = new StringWriter();
s.Serialize(sw, data);
string strwrite = sw.ToString();
return strwrite;
}
public static DataTable ConvertToDatatable<T>(List<T> data)
{
PropertyDescriptorCollection props =
TypeDescriptor.GetProperties(typeof(T));
DataTable table = new DataTable();
for (int i = 0; i < props.Count; i++)
{
PropertyDescriptor prop = props[i];
if (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>))
table.Columns.Add(prop.Name, prop.PropertyType.GetGenericArguments()[0]);
else
table.Columns.Add(prop.Name, prop.PropertyType);
}
object[] values = new object[props.Count];
foreach (T item in data)
{
for (int i = 0; i < values.Length; i++)
{
values[i] = props[i].GetValue(item);
}
table.Rows.Add(values);
}
return table;
}
#if WINDOWS_PHONE || ANDROID || IPHONE
public string LoadContentFileDevice(string filename)
{
string str = new System.IO.StreamReader(TitleContainer.OpenStream(filename)).ReadToEnd();
// Stream stream = Assembly.GetExecutingAssembly().GetManifestResourceStream("xnaTemplate.levels.shinto.xml");
//StreamReader sr = new StreamReader(stream);
//string str = sr.ReadToEnd();
//sr.Close();
MemoryStream ms = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(str));
string retVal = "";
using (StreamReader sr = new StreamReader(ms))
{
retVal = sr.ReadToEnd();
}
return retVal;
}
public bool SaveObjectDevice(string path, object data)
{
bool result = true;
try
{
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, isf))
{
using (StreamWriter sww = new StreamWriter(isfs, Encoding.Unicode))
{
sww.Write(SerializeToString(data));
}
}
}
}
catch (Exception ex)
{
string msg = ex.Message;
result = false;
}
return result;
}
public object LoadFileFromDevice(string path, Type objectType)
{
try
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
string[] files = isf.GetFileNames(path);
List<string> file_list = new List<string>(files);
if ((files != null) && (files.Length > 0) && (file_list.Contains(path)))
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, isf))
{
isfs.Position = 0;
StreamReader sr = new StreamReader(isfs, Encoding.Unicode);
XmlSerializer s = new XmlSerializer(objectType);
object data = s.Deserialize(sr);
return data;
}
}
}
catch { }
return null;
}
public string LoadFileFromDevice(string path)
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
string[] files = isf.GetFileNames(path);
List<string> file_list = new List<string>(files);
if ((files != null) && (files.Length > 0) && (file_list.Contains(path)))
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, isf))
{
isfs.Position = 0;
StreamReader sr = new StreamReader(isfs, Encoding.Unicode);
string data = "";
XmlSerializer s = new XmlSerializer(data.GetType());
data = s.Deserialize(sr).ToString();
return data;
}
}
return null;
}
public bool DeviceFileExists(string path)
{
bool exists = false;
try
{
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
string[] files = isf.GetFileNames(path);
List<string> file_list = new List<string>(files);
if ((files != null) && (files.Length > 0) && (file_list.Contains(path)))
{
exists = true;
}
}
catch { }
return exists;
}
public void SaveObjectToDevice(object data, string path)
{
try
{
XmlSerializer s = new XmlSerializer(data.GetType());
StringWriter sw = new StringWriter();
s.Serialize(sw, data);
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, isf))
{
using (StreamWriter sww = new StreamWriter(isfs, Encoding.Unicode))
{
sww.Write(sw.ToString());
}
}
}
}
catch { }
}
#endif
public void SaveGame(RoundSesssion data)
{
string path = "rndsess.dat";
data.SecondsRemaining = (int)data.time_remaining.TotalSeconds;
XmlSerializer s = new XmlSerializer(data.GetType());
StringWriter sw = new StringWriter();
s.Serialize(sw, data);
using (IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication())
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(path, FileMode.Create, FileAccess.Write, isf))
{
using (StreamWriter sww = new StreamWriter(isfs, Encoding.Unicode))
{
sww.Write(sw.ToString());
}
}
}
}
public RoundSesssion LoadGame()
{
string path = "rndsess.dat";
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
string[] files = isf.GetFileNames(path);
List<string> file_list = new List<string>(files);
if ((files != null) && (files.Length > 0) && (file_list.Contains(path)))
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, isf))
{
isfs.Position = 0;
StreamReader sr = new StreamReader(isfs, Encoding.Unicode);
RoundSesssion data = new RoundSesssion();
XmlSerializer s = new XmlSerializer(data.GetType());
data = (RoundSesssion)s.Deserialize(sr);
data.time_remaining = TimeSpan.FromSeconds(data.SecondsRemaining);
return data;
}
}
return null;
}
public bool SaveGameExists()
{
bool exists = false;
string path = "rndsess.dat";
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
string[] files = isf.GetFileNames(path);
List<string> file_list = new List<string>(files);
if ((files != null) && (files.Length > 0) && (file_list.Contains(path)))
{
using (IsolatedStorageFileStream isfs = new IsolatedStorageFileStream(path, FileMode.Open, FileAccess.Read, isf))
{
isfs.Position = 0;
StreamReader sr = new StreamReader(isfs, Encoding.Unicode);
RoundSesssion data = new RoundSesssion();
XmlSerializer s = new XmlSerializer(data.GetType());
data = (RoundSesssion)s.Deserialize(sr);
exists = true;
}
}
return exists;
}
public void RemoveSaveGame()
{
string path = "rndsess.dat";
IsolatedStorageFile isf = IsolatedStorageFile.GetUserStoreForApplication();
string[] files = isf.GetFileNames(path);
List<string> file_list = new List<string>(files);
if ((files != null) && (files.Length > 0) && (file_list.Contains(path)))
{
isf.DeleteFile(path);
}
}
public static string SerializeEntityToString(object data)
{
//StringWriter sw = new StringWriter();
//using (XmlWriter writer = XmlWriter.Create(sw))
//{
// DataContractSerializer serializer = new DataContractSerializer(data.GetType());
// writer.WriteStartElement("Products");
// serializer.WriteObject(writer, data);
// writer.WriteEndElement();
//}
//return sw.ToString();
using (MemoryStream memoryStream = new MemoryStream())
{
DataContractSerializer serializer = new DataContractSerializer(data.GetType());
serializer.WriteObject(memoryStream, data);
return Encoding.UTF8.GetString(memoryStream.ToArray());
}
}
public static string CsvToJson(string value, char delim, bool hasHeader)
{
// Get lines.
if (value == null) return null;
value = value.Replace("\r\n", "\r");
value = value.Replace("\r", "\r\n");
value = value.Replace(delim, ',');
string[] lines = value.Split(new string[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries);
if (lines.Length < 2) throw new InvalidDataException("Must have header line.");
// Get headers.
List<string> headers = new List<string>();
int startIdx = 0;
if (hasHeader)
{
headers.AddRange(lines.First().Split(','));
startIdx = 1;
}
else
{
//fix any empty headers
for (int i = 0; i < headers.Count; i++)
{
if (string.IsNullOrEmpty(headers[i]))
{
headers[i] = "Field" + i;
}
}
}
// Build JSON array.
StringBuilder sb = new StringBuilder();
sb.AppendLine("[");
for (int i = startIdx; i < lines.Length; i++)
{
//string[] fields = lines[i].Split(',');
List<string> fields = new List<string>();
var regex = new Regex("(?<=^|,)(\"(?:[^\"]|\"\")*\"|[^,]*)");
foreach (Match m in regex.Matches(lines[i]))
{
fields.Add(m.Value.Replace("\"", ""));
}
int x = headers.Count;
if (fields.Count != headers.Count)
{
while (headers.Count < fields.Count)
{
headers.Add("Field" + x++);
}
//throw new InvalidDataException("Field count must match header count.");
}
var jsonElements = headers.Zip(fields, (header, field) => string.Format("\"{0}\": \"{1}\"", header, field)).ToArray();
string jsonObject = "{" + string.Format("{0}", string.Join(",", jsonElements)) + "}";
if (i < lines.Length - 1)
jsonObject += ",";
sb.AppendLine(jsonObject);
}
sb.AppendLine("]");
return sb.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment