示例#1
0
        /// <summary>
        /// Write an object to a target stream using a certain serialiser.
        /// All related objects along the object graph are properly stored using the <see cref="ISerialisationNotifier"/> contract.
        /// </summary>
        /// <param name="obj">The object.</param>
        /// <param name="target">The target stream.</param>
        /// <param name="serialiser">The serialiser.</param>
        /// <param name="autoClose">Optionally indicate if the stream should be automatically closed.</param>
        /// <param name="verbose">Optionally indicate where the log messages should written to (verbose = Info, otherwise Debug).</param>
        /// <returns>The number of bytes written (if exposed by the used target stream).</returns>
        public static long Write(object obj, Stream target, ISerialiser serialiser, bool autoClose = true, bool verbose = true)
        {
            if (obj == null)
            {
                throw new ArgumentNullException(nameof(obj));
            }
            if (target == null)
            {
                throw new ArgumentNullException(nameof(target));
            }
            if (serialiser == null)
            {
                throw new ArgumentNullException(nameof(serialiser));
            }

            LoggingUtils.Log(verbose ? Level.Info : Level.Debug, $"Writing {obj.GetType().Name} {obj} of type {obj.GetType()} to target stream {target} using serialiser {serialiser}...", ClazzLogger);

            Stopwatch stopwatch      = Stopwatch.StartNew();
            long      beforePosition = target.Position;

            TraverseObjectGraph(obj, new HashSet <object>(), (p, f, o) => (o as ISerialisationNotifier)?.OnSerialising());
            serialiser.Write(obj, target);
            TraverseObjectGraph(obj, new HashSet <object>(), (p, f, o) => (o as ISerialisationNotifier)?.OnSerialised());

            target.Flush();

            long bytesWritten = target.Position - beforePosition;

            target.Close();

            LoggingUtils.Log(verbose ? Level.Info : Level.Debug, $"Done writing {obj.GetType().Name} {obj} to target stream {target} using serialiser {serialiser}, " +
                             $"wrote {(bytesWritten / 1024.0):#.#}kB, took {stopwatch.ElapsedMilliseconds}ms.", ClazzLogger);

            return(bytesWritten);
        }
示例#2
0
        public async Task <Common.SaveResult> SaveAs(
            ISerialiser serialiser,
            String fullPath,
            String masterPassphrase,
            Boolean overwrite,
            params KeyValuePair <string, string>[] parameters)
        {
            bool exists = await Native.Native.FileHandler.Exists(fullPath);

            if (!exists || (exists && overwrite))
            {
                AddAuditEntry(
                    AuditLogEntry.EntryType.Saved,
                    new KeyValuePair <String, String>("Version", AssemblyVersion().ToString()));
                Byte[] serialised = (Byte[])serialiser.Write(this, masterPassphrase, parameters);
                await Native.Native.FileHandler.WriteAsync(
                    fullPath,
                    serialised);

                SetSaveParams(
                    serialiser,
                    fullPath,
                    masterPassphrase,
                    false);
                return(Common.SaveResult.Success);
            }
            return(Common.SaveResult.UnknownError);
        }
示例#3
0
        public void SequentialUpgradeTest()
        {
            Vault testVault = VaultTests.CreateRandomVault(_rng);
            IEnumerable <FormatVersionAttribute> vaultSerialisers = FormatVersions.Instance.VersionSerialisers.Keys.Where(fva => fva.ObjectType == typeof(Vault)).OrderBy(fva => double.Parse(fva.Version));

            FormatVersionAttribute[] filteredOrderedSerialisers = vaultSerialisers.ToArray();
            object curSerialised = null;
            Vault  curVault      = null;
            string lastVersion   = String.Empty;

            for (int curVersion = 0; curVersion < filteredOrderedSerialisers.Length; curVersion++)
            {
                if (curSerialised != null)
                {
                    FormatVersionAttribute prevSerialiserAttrib = filteredOrderedSerialisers[curVersion - 1];
                    ISerialiser            prevSerialiser       = FormatVersions.Instance.GetSerialiser(prevSerialiserAttrib.Version, typeof(Vault));
                    curVault = (Vault)prevSerialiser.Read(curSerialised, String.Empty);
                }
                else
                {
                    curVault = testVault;
                }
                FormatVersionAttribute nextSerialiserAttrib = filteredOrderedSerialisers[curVersion];
                lastVersion = nextSerialiserAttrib.Version;
                ISerialiser nextSerialiser = FormatVersions.Instance.GetSerialiser(nextSerialiserAttrib.Version, typeof(Vault));
                curSerialised = nextSerialiser.Write(curVault, String.Empty);
            }
            Assert.IsTrue(lastVersion == Framework.Serialisers.JSON.Common.LATEST_VAULT_VERSION);
            ISerialiser latestSerialiser = FormatVersions.GetLatestSerialiser(typeof(Vault));

            curVault = (Vault)latestSerialiser.Read(curSerialised, String.Empty);
            Assert.IsTrue(curVault.CompareTo(testVault) == 0);
        }
示例#4
0
        public object Write(
            object data,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Writing JObject to Vault.");

            ISerialiser serialiser = FormatVersions.Instance.GetSerialiser(Common.LATEST_VAULT_VERSION, typeof(Vault));

            return(serialiser.Write(
                       data,
                       masterPassphrase,
                       parameters));
        }
        public object Write(
            object data,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            FormatVersionAttribute formatVersion = FormatVersionAttribute.GetAttributeFromType(this.GetType());

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Writing Vault to JSON using serialiser '{0}'.", formatVersion);

            Dictionary <string, string> parametersDict = parameters.ToDictionary(x => x.Key, x => x.Value);

            Vault   vault = (Vault)data;
            JObject json  = new JObject();

            JObject header = new JObject();

            header.Add("FormatVersion", new JValue(formatVersion.Version));
            json.Add("Header", header);

            json.Add("ID", new JValue(vault.ID));
            json.Add("Name", new JValue(vault.Name));
            json.Add("Description", new JValue(vault.Description));
            json.Add("CreatedAt", new JValue(vault.CreatedAt.ToString(Common.DATETIMESERIALISATIONFORMAT)));
            json.Add("LastUpdatedAt", new JValue(vault.LastUpdatedAt.ToString(Common.DATETIMESERIALISATIONFORMAT)));

            ISerialiser credentialSerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(Credential));
            JArray      credentialJSON       = new JArray();

            foreach (Credential curCredential in vault.Credentials)
            {
                credentialJSON.Add(credentialSerialiser.Write(curCredential, String.Empty));
            }

            json.Add("Credentials", credentialJSON);
            ISerialiser auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(AuditLogEntry));
            JArray      auditLogEntries         = new JArray();

            foreach (AuditLogEntry curEntry in vault.AuditLogEntries)
            {
                auditLogEntries.Add(auditLogEntrySerialiser.Write(curEntry, String.Empty));
            }
            json.Add("AuditLogEntries", auditLogEntries);
            return(json);
        }
示例#6
0
        public void ToAndFromJSON()
        {
            String name = String.Empty;
            String type = String.Empty;

            AuditLogEntry.EntryType entryType = AuditLogEntry.EntryType.None;

            AuditLogEntry random = CreateRandomAuditLogEntry(_rng,
                                                             out name,
                                                             out type,
                                                             out entryType);

            DateTime dateTime = random.DateTime;

            ISerialiser   auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(devoctomy.cachy.Framework.Serialisers.JSON.Common.LATEST_VAULT_VERSION, typeof(AuditLogEntry));
            JObject       json     = (JObject)auditLogEntrySerialiser.Write(random, String.Empty);
            AuditLogEntry fromJSON = (AuditLogEntry)auditLogEntrySerialiser.Read(json, String.Empty);

            Assert.IsTrue(random.CompareTo(fromJSON) == 0);
        }
示例#7
0
        public void JSONSerialiser()
        {
            string   id                     = String.Empty;
            string   glyphKey               = String.Empty;
            string   glyphColour            = String.Empty;
            string   name                   = String.Empty;
            string   description            = String.Empty;
            string   website                = String.Empty;
            DateTime createdAt              = DateTime.MinValue;
            DateTime lastUpdatedAt          = DateTime.MinValue;
            DateTime passwordLastModifiedAt = DateTime.MinValue;
            string   username               = String.Empty;
            string   password               = String.Empty;

            string[] tags  = null;
            string   notes = String.Empty;

            AuditLogEntry[] auditLogEntries = null;

            Credential credential = CreateRandomCredential(_rng,
                                                           out id,
                                                           out glyphKey,
                                                           out glyphColour,
                                                           out name,
                                                           out description,
                                                           out website,
                                                           out createdAt,
                                                           out lastUpdatedAt,
                                                           out passwordLastModifiedAt,
                                                           out username,
                                                           out password,
                                                           out tags,
                                                           out notes,
                                                           out auditLogEntries);

            ISerialiser serialiser         = FormatVersions.GetLatestSerialiser(typeof(Credential));
            JObject     json               = (JObject)serialiser.Write(credential, String.Empty);
            Credential  credentialReloaded = (Credential)serialiser.Read(json, String.Empty);

            Assert.IsTrue(credential.CompareTo(credentialReloaded) == 0);
        }
        public object Write(
            object data,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            FormatVersionAttribute formatVersion = FormatVersionAttribute.GetAttributeFromType(this.GetType());

            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Writing Credential to JSON using serialiser '{0}'.", formatVersion);

            Credential credential = (Credential)data;
            JObject    json       = new JObject();

            json.Add("ID", new JValue(credential.ID));
            json.Add("GlyphKey", new JValue(credential.GlyphKey));
            json.Add("GlyphColour", new JValue(credential.GlyphColour));
            json.Add("Name", new JValue(credential.Name));
            json.Add("Description", new JValue(credential.Description));
            json.Add("Website", new JValue(credential.Website));
            json.Add("CreatedAt", new JValue(credential.CreatedAt.ToString(Common.DATETIMESERIALISATIONFORMAT)));
            json.Add("LastUpdatedAt", new JValue(credential.LastModifiedAt.ToString(Common.DATETIMESERIALISATIONFORMAT)));
            json.Add("PasswordLastModifiedAt", new JValue(credential.PasswordLastModifiedAt.ToString(Common.DATETIMESERIALISATIONFORMAT)));
            json.Add("Username", new JValue(credential.Username));
            json.Add("Password", new JValue(credential.Password));
            JArray tagsArray = new JArray();

            foreach (String curTag in credential.Tags)
            {
                tagsArray.Add(new JValue(curTag));
            }
            json.Add("Tags", tagsArray);
            ISerialiser auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(AuditLogEntry));
            JArray      auditLogEntries         = new JArray();

            foreach (AuditLogEntry curEntry in credential.AuditLogEntries)
            {
                auditLogEntries.Add(auditLogEntrySerialiser.Write(curEntry, String.Empty));
            }
            json.Add("Notes", credential.Notes);
            json.Add("AuditLogEntries", auditLogEntries);
            return(json);
        }