Skip to content

Instantly share code, notes, and snippets.

@gvoysey
Last active October 10, 2015 23:50
Show Gist options
  • Select an option

  • Save gvoysey/3cff1700cb631c9a9cd6 to your computer and use it in GitHub Desktop.

Select an option

Save gvoysey/3cff1700cb631c9a9cd6 to your computer and use it in GitHub Desktop.
serialization and hashing extensions.
public static class JsonExtensions
{
public static T AsDeserialized<T>(this string instance)
{
T item;
try
{
item = JsonConvert.DeserializeObject<T>(instance, JsonSerializerSettings);
}
catch (Exception exception)
{
var error = "caught JSON exception on deserialization: " + exception.Message;
if (exception.InnerException != null)
{
error += "\r\nwith inner exception " + exception.InnerException;
}
Log(error, true);
Log("caught JSON exception on deserialization: " + exception.Message, true);
throw;
}
return item;
}
public static string AsSerialized(this object instance)
{
string result;
try
{
result = JsonConvert.SerializeObject(instance, Formatting.Indented, JsonSerializerSettings);
Log("JSON serialized correctly");
}
catch (Exception e)
{
Log("Serialization caught exception of type " + e.GetType(), true);
Log(" :" + e.Message, true);
if (e.InnerException != null)
{
Log(" inner: " + e.InnerException, true);
}
throw;
}
if (string.IsNullOrEmpty(result)) Log("serialization returned an empty string.");
return result;
}
public static T FromStream<T>(this Stream stream)
{
var serializer = JsonSerializer.Create(JsonSerializerSettings);
using (var reader = new StreamReader(stream))
using (var jsonreader = new JsonTextReader(reader))
{
T result = default(T);
try
{
result = serializer.Deserialize<T>(jsonreader);
return result;
}
catch (Exception e)
{
Log("Getting object from stream failed: " + e.Message);
}
return result;
}
}
public static string SHA1<T>(this T instance) where T : IAsset
{
return instance.AsSerialized().SHA1();
}
public static string SHA1(this string inputString)
{
HashAlgorithm algorithm = System.Security.Cryptography.SHA1.Create(); // SHA1.Create()
return Convert.ToBase64String(algorithm.ComputeHash(Encoding.UTF8.GetBytes(inputString)));
}
public static string SHA1(this int input)
{
HashAlgorithm algorithm = System.Security.Cryptography.SHA1.Create(); // SHA1.Create()
return Convert.ToBase64String(algorithm.ComputeHash(BitConverter.GetBytes(input)));
}
private static readonly JsonSerializerSettings JsonSerializerSettings = new JsonSerializerSettings
{
NullValueHandling = NullValueHandling.Ignore,
ReferenceLoopHandling = ReferenceLoopHandling.Ignore,
TypeNameHandling = TypeNameHandling.Objects,
TypeNameAssemblyFormat = System.Runtime.Serialization.Formatters.FormatterAssemblyStyle.Simple
};
private static void Log(string msg, bool isThisWrong = false)
{
if (isThisWrong) EngineLog.Warning(msg);
else EngineLog.Print(msg);
Debug.WriteLine(msg);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment