예제 #1
0
 public ResultsApiService(
     HttpClient httpClient,
     ISerialiser serialiser)
 {
     this.httpClient = httpClient;
     this.serialiser = serialiser;
 }
        public ReplySendChannelBuilder(
            MessageSender messageSender,
            ISerialiser serialiser,
            ISystemTime systemTime,
            ITaskRepeater taskRepeater,
            MessageCacheFactory messageCacheFactory,
            MessageAcknowledgementHandler acknowledgementHandler,
            ITaskScheduler taskScheduler,
            ReplyAuthenticationSessionAttacherFactory authenticationSessionAttacherFactory,
            ReplyCorrelationLookup correlationLookup)
        {
            Contract.Requires(messageSender != null);
            Contract.Requires(serialiser != null);
            Contract.Requires(systemTime != null);
            Contract.Requires(taskRepeater != null);
            Contract.Requires(messageCacheFactory != null);
            Contract.Requires(acknowledgementHandler != null);
            Contract.Requires(taskScheduler != null);
            Contract.Requires(authenticationSessionAttacherFactory != null);
            Contract.Requires(correlationLookup != null);

            this.messageSender = messageSender;
            this.serialiser = serialiser;
            this.systemTime = systemTime;
            this.taskRepeater = taskRepeater;
            this.messageCacheFactory = messageCacheFactory;
            this.acknowledgementHandler = acknowledgementHandler;
            this.taskScheduler = taskScheduler;
            this.authenticationSessionAttacherFactory = authenticationSessionAttacherFactory;
            this.correlationLookup = correlationLookup;
        }
 public HttpMessagingServer(ISerialiser serialiser, params IMessagingServerHandler[] handlers)
 {
     Contract.Requires(serialiser != null);
     
     this.serialiser = serialiser;
     this.handlers = handlers;
 }
예제 #4
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            // URL Postfix Extension: Update the configuration to recognise postfix extensions and map known
            // extensions to MIME Types. Additional changes to WebApiConfig.cs are required to fully enable this
            // feature.
            GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

            // XML Serialisation: Define the specific XML serialiser to use to ensure that SIF Data Model Objects (as
            // defined by the SIF Specification with XML Schema Definitions (XSDs)) are serialised correctly.
            XmlMediaTypeFormatter formatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;

            formatter.UseXmlSerializer = true;

            // XML Serialisation: For each SIF Data Model Object used by each SIF Provider, the following entries are
            // required to define the root element for each collection object.
            XmlRootAttribute studentPersonalsXmlRootAttribute = new XmlRootAttribute("StudentPersonals")
            {
                Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false
            };
            ISerialiser <List <StudentPersonal> > studentPersonalsSerialiser = SerialiserFactory.GetXmlSerialiser <List <StudentPersonal> >(studentPersonalsXmlRootAttribute);

            formatter.SetSerializer <List <StudentPersonal> >((XmlSerializer)studentPersonalsSerialiser);

            // Configure global exception loggers for unexpected errors.
            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

            // Configure a global exception handler for unexpected errors.
            GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new GlobalUnexpectedExceptionHandler());

            Trace.TraceInformation("********** Application_Start **********");
            Register();
        }
예제 #5
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);
        }
예제 #6
0
        public async Task <GenericResult <Common.LoadResult, Vault> > Load(
            ISerialiser serialiser,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            bool exists = await Native.Native.FileHandler.Exists(FullPath);

            if (exists)
            {
                Byte[] encrypted = await Native.Native.FileHandler.ReadAsync(FullPath);

                Vault             vault  = (Vault)serialiser.Read(encrypted, masterPassphrase, parameters);
                Common.LoadResult result = vault != null ? Common.LoadResult.Success : Common.LoadResult.UnknownError;
                if (result == Common.LoadResult.Success)
                {
                    vault.SetSaveParams(serialiser,
                                        FullPath,
                                        masterPassphrase,
                                        false);
                    vault.SetLoaded();
                }
                return(new GenericResult <Common.LoadResult, Vault>(result, vault));
            }
            else
            {
                return(new GenericResult <Common.LoadResult, Vault>(Common.LoadResult.FileNotFound, null));
            }
        }
 public PublisherChannelBuilder(
     IPublisherRegistry publisherRegistry, 
     ISerialiser serialiser, 
     ITaskRepeater taskRepeater,
     MessageCacheFactory messageCacheFactory, 
     ISubscriberSendChannelBuilder subscriberChannelBuilder, 
     ISystemTime systemTime, 
     ChangeStore changeStore,
     ICheckpointStrategy checkPointStrategy)
 {
     Contract.Requires(publisherRegistry != null);
     Contract.Requires(serialiser != null);
     Contract.Requires(taskRepeater != null);
     Contract.Requires(messageCacheFactory != null);
     Contract.Requires(subscriberChannelBuilder != null);
     Contract.Requires(systemTime != null);
     Contract.Requires(changeStore != null);
     Contract.Requires(checkPointStrategy != null);
     
     this.publisherRegistry = publisherRegistry;
     this.serialiser = serialiser;
     this.taskRepeater = taskRepeater;
     this.messageCacheFactory = messageCacheFactory;
     this.subscriberChannelBuilder = subscriberChannelBuilder;
     this.systemTime = systemTime;
     this.changeStore = changeStore;
     this.checkPointStrategy = checkPointStrategy;
 }
        internal PointToPointReceiveChannelBuilder(
            MessageReceiver messageReceiver, 
            ISerialiser serialiser, 
            AcknowledgementSender acknowledgementSender, 
            MessageHandlerRouter messageHandlerRouter,
            MessageCacheFactory messageCacheFactory, 
            ISystemTime systemTime, 
            ITaskRepeater taskRepeater, 
            ServerAddressRegistry serverAddressRegistry, 
            AuthenticationSessionCache authenticationSessionCache, 
            AuthenticatedServerRegistry authenticatedServerRegistry)
        {
            Contract.Requires(messageReceiver != null);
            Contract.Requires(serialiser != null);
            Contract.Requires(acknowledgementSender != null);
            Contract.Requires(messageHandlerRouter != null);
            Contract.Requires(messageCacheFactory != null);
            Contract.Requires(systemTime != null);
            Contract.Requires(taskRepeater != null);
            Contract.Requires(serverAddressRegistry != null);
            Contract.Requires(authenticationSessionCache != null);
            Contract.Requires(authenticatedServerRegistry != null);

            this.messageReceiver = messageReceiver;
            this.serialiser = serialiser;
            this.acknowledgementSender = acknowledgementSender;
            this.messageHandlerRouter = messageHandlerRouter;
            this.messageCacheFactory = messageCacheFactory;
            this.systemTime = systemTime;
            this.taskRepeater = taskRepeater;
            this.serverAddressRegistry = serverAddressRegistry;
            this.authenticationSessionCache = authenticationSessionCache;
            this.authenticatedServerRegistry = authenticatedServerRegistry;
        }
예제 #9
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);
        }
        public SubscriberSendChannelBuilder(
            MessageSender messageSender, 
            MessageCacheFactory messageCacheFactory, 
            ISystemTime systemTime, 
            ITaskRepeater taskRepeater, 
            MessageAcknowledgementHandler acknowledgementHandler, 
            ISerialiser serialiser, 
            ITaskScheduler taskScheduler,
            SenderAuthenticationSessionAttacherFactory authenticationSessionAttacherFactory)
        {
            Contract.Requires(messageSender != null);
            Contract.Requires(messageCacheFactory != null);
            Contract.Requires(systemTime != null);
            Contract.Requires(taskRepeater != null);
            Contract.Requires(acknowledgementHandler != null);
            Contract.Requires(serialiser != null);
            Contract.Requires(taskScheduler != null);
            Contract.Requires(authenticationSessionAttacherFactory != null);

            this.messageSender = messageSender;
            this.messageCacheFactory = messageCacheFactory;
            this.systemTime = systemTime;
            this.taskRepeater = taskRepeater;
            this.acknowledgementHandler = acknowledgementHandler;
            this.serialiser = serialiser;
            this.taskScheduler = taskScheduler;
            this.authenticationSessionAttacherFactory = authenticationSessionAttacherFactory;
        }
예제 #11
0
        protected void Application_Start()
        {
            log4net.Config.XmlConfigurator.Configure();

            GlobalConfiguration.Configure(WebApiConfig.Register);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

            // Add a text/plain formatter (WebApiContrib also contains CSV and other formaters)
            GlobalConfiguration.Configuration.Formatters.Add(new PlainTextFormatter());

            XmlMediaTypeFormatter formatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;

            formatter.UseXmlSerializer = true;

            // Set up serializer configuration for data object:
            XmlRootAttribute studentPersonalsXmlRootAttribute = new XmlRootAttribute("LearnerPersonals")
            {
                Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false
            };
            ISerialiser <List <LearnerPersonal> > studentPersonalsSerialiser = SerialiserFactory.GetXmlSerialiser <List <LearnerPersonal> >(studentPersonalsXmlRootAttribute);

            formatter.SetSerializer <List <LearnerPersonal> >((XmlSerializer)studentPersonalsSerialiser);

            // Configure global exception loggers for unexpected errors.
            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

            // Configure a global exception handler for unexpected errors.
            GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new GlobalUnexpectedExceptionHandler());

            Trace.TraceInformation("********** Application_Start **********");
            log.Info("********** Application_Start **********");
            Register();
        }
예제 #12
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);
        }
        public object Read(
            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 from JSON using serialiser '{0}'.", formatVersion);

            JObject       dataJSON               = (JObject)data;
            String        id                     = JSONHelpers.ReadString(dataJSON, "ID");
            String        glyphKey               = JSONHelpers.ReadString(dataJSON, "GlyphKey");
            String        glyphColour            = JSONHelpers.ReadString(dataJSON, "GlyphColour");
            String        name                   = JSONHelpers.ReadString(dataJSON, "Name");
            String        description            = JSONHelpers.ReadString(dataJSON, "Description");
            String        website                = JSONHelpers.ReadString(dataJSON, "Website");
            DateTime      createdAt              = JSONHelpers.ReadDateTime(dataJSON, "CreatedAt");
            DateTime      lastUpdatedAt          = JSONHelpers.ReadDateTime(dataJSON, "LastUpdatedAt");
            DateTime      passwordLastModifiedAt = JSONHelpers.ReadDateTime(dataJSON, "PasswordLastModifiedAt", createdAt);
            String        username               = JSONHelpers.ReadString(dataJSON, "Username");
            String        password               = JSONHelpers.ReadString(dataJSON, "Password");
            JArray        tagsArray              = JSONHelpers.ReadJArray(dataJSON, "Tags", true);;
            List <String> tags                   = new List <String>();

            foreach (JValue curValue in tagsArray)
            {
                tags.Add(curValue.Value <String>());
            }
            String notes = JSONHelpers.ReadString(dataJSON, "Notes");
            List <AuditLogEntry> auditLogEntriesList = new List <AuditLogEntry>();

            if (dataJSON.ContainsKey("AuditLogEntries"))
            {
                ISerialiser auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(AuditLogEntry));
                JArray      auditLogEntries         = JSONHelpers.ReadJArray(dataJSON, "AuditLogEntries", true);
                foreach (JObject curEntry in auditLogEntries)
                {
                    AuditLogEntry entry = (AuditLogEntry)auditLogEntrySerialiser.Read(curEntry, String.Empty);
                    auditLogEntriesList.Add(entry);
                }
                if (auditLogEntriesList.Count > 0)
                {
                    auditLogEntriesList = auditLogEntriesList.OrderByDescending(ale => ale.DateTime).ToList();
                }
            }
            return(new Credential(id,
                                  glyphKey,
                                  glyphColour,
                                  name,
                                  description,
                                  website,
                                  createdAt,
                                  lastUpdatedAt,
                                  passwordLastModifiedAt,
                                  username,
                                  password,
                                  tags.ToArray(),
                                  notes,
                                  auditLogEntriesList.ToArray()));
        }
예제 #14
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter
            .AddUriPathExtensionMapping("json", "application/json");
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

            XmlMediaTypeFormatter formatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;

            formatter.UseXmlSerializer = true;

            var studentsXmlRootAttribute = new XmlRootAttribute("xStudents")
            {
                Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false
            };
            ISerialiser <List <xStudent> > studentsSerialiser =
                SerialiserFactory.GetXmlSerialiser <List <xStudent> >(studentsXmlRootAttribute);

            formatter.SetSerializer <List <xStudent> >((XmlSerializer)studentsSerialiser);

            // Configure global exception loggers for unexpected errors.
            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

            // Configure a global exception handler for unexpected errors.
            GlobalConfiguration.Configuration.Services
            .Replace(typeof(IExceptionHandler), new GlobalUnexpectedExceptionHandler());

            Trace.TraceInformation("********** Application_Start **********");
            Register();
        }
예제 #15
0
 public ServiceBusClientFixture()
 {
     this.bus = new FakeServiceBus();
     this.connectionString = "ConnectionString";
     this.queueName        = "queuename";
     this.serialiser       = A.Fake <ISerialiser>();
 }
 public ServiceBusListenerFixture()
 {
     this.bus = new FakeServiceBus();
     this.connectionString = "ConnectionString";
     this.queueName = "queuename";
     this.serialiser = A.Fake<ISerialiser>();
 }
예제 #17
0
        public static ISerialiser GetLatestSerialiser(Type objectType)
        {
            ISerialiser serialiser = FormatVersions.Instance.GetSerialiser(
                Common.LATEST_VAULT_VERSION,
                objectType);

            return(serialiser);
        }
        public RequestSenderBuilder(ISerialiser serialser, RequestSender requestSender)
        {
            Contract.Requires(serialser != null);
            Contract.Requires(requestSender != null);

            this.serialser = serialser;
            this.requestSender = requestSender;
        }
예제 #19
0
        protected ChangeStore(ISerialiser serialiser, ChangeUpcasterRunner upcasterRunner)
        {
            Contract.Requires(serialiser != null);
            Contract.Requires(upcasterRunner != null);

            this.serialiser = serialiser;
            this.upcasterRunner = upcasterRunner;
        }
예제 #20
0
 public CustomerCapturer(ICsvWriter csvWriter, ISerialiser serialiser, IDataCleaner dataCleaner)
 {
     if (csvWriter == null) throw new ArgumentNullException(nameof(csvWriter));
     if (serialiser == null) throw new ArgumentNullException(nameof(serialiser));
     _csvWriter = csvWriter;
     _serialiser = serialiser;
     _dataCleaner = dataCleaner;
 }
        public MessageTransporter(IInProcessMessageServer messageServer, ISerialiser serialiser)
        {
            Contract.Requires(messageServer != null);
            Contract.Requires(serialiser != null);

            this.messageServer = messageServer;
            this.serialiser = serialiser;
        }
예제 #22
0
        public MemoryAggregateRootEventStorage(ILoggerFactory loggerFactory
                                               , ISerialiser serialiser
                                               , IEventToAggregateEventMapper eventToAggregateEventMapper)
        {
            _serialiser = serialiser;
            _eventToAggregateEventMapper = eventToAggregateEventMapper;

            logger = loggerFactory.Create();
        }
 public EsentChangeStore(
     IFileSystem fileSystem, 
     ISerialiser serialiser, 
     ChangeUpcasterRunner changeUpcasterRunner)
     : base(serialiser, changeUpcasterRunner)
 {
     Contract.Requires(fileSystem != null);
     this.fileSystem = fileSystem;
 }
예제 #24
0
 public void SetSaveParams(ISerialiser serialiser,
                           String fullPath,
                           String masterPassphrase,
                           Boolean isDirty)
 {
     _serialiser       = serialiser;
     _fullPath         = fullPath;
     _masterPassphrase = masterPassphrase;
     _isDirty          = isDirty;
 }
 public NHibAggregateRootEventStorage(ILoggerFactory loggerFactory
                                      , IEventToAggregateEventMapper eventToAggregateEventMapper
                                      , ISerialiser serialiser
                                      , IGenericEntityService genericEntityService)
 {
     _eventToAggregateEventMapper = eventToAggregateEventMapper;
     _serialiser           = serialiser;
     _genericEntityService = genericEntityService;
     _logger = loggerFactory.Create();
 }
        public RequestReceiverBuilder(MessageReceiver messageReceiver, MessageHandlerRouter messageHandlerRouter, ISerialiser serialiser)
        {
            Contract.Requires(messageReceiver != null);
            Contract.Requires(messageHandlerRouter != null);
            Contract.Requires(serialiser != null);

            this.messageReceiver = messageReceiver;
            this.messageHandlerRouter = messageHandlerRouter;
            this.serialiser = serialiser;
        }
예제 #27
0
        public ResultsApiServiceTests()
        {
            serialiser = new NewtonsoftSerialiser();

            httpMessageHandler     = new MockHttpMessageHandler();
            httpClient             = httpMessageHandler.ToHttpClient();
            httpClient.BaseAddress = new Uri("https://localhost/resultsapi");

            resultsApiService = new ResultsApiService(httpClient, serialiser);
        }
예제 #28
0
        protected void Application_Start()
        {
            GlobalConfiguration.Configure(WebApiConfig.Register);

            GlobalConfiguration.Configuration.Formatters.JsonFormatter.AddUriPathExtensionMapping("json", "application/json");
            GlobalConfiguration.Configuration.Formatters.XmlFormatter.AddUriPathExtensionMapping("xml", "text/xml");

            XmlMediaTypeFormatter formatter = GlobalConfiguration.Configuration.Formatters.XmlFormatter;

            formatter.UseXmlSerializer = true;

            XmlRootAttribute studentPersonalsXmlRootAttribute = new XmlRootAttribute("StudentPersonals")
            {
                Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false
            };
            ISerialiser <List <StudentPersonal> > studentPersonalsSerialiser = SerialiserFactory.GetXmlSerialiser <List <StudentPersonal> >(studentPersonalsXmlRootAttribute);

            formatter.SetSerializer <List <StudentPersonal> >((XmlSerializer)studentPersonalsSerialiser);

            XmlRootAttribute schoolInfosXmlRootAttribute = new XmlRootAttribute("SchoolInfos")
            {
                Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false
            };
            ISerialiser <List <SchoolInfo> > schoolInfosSerialiser = SerialiserFactory.GetXmlSerialiser <List <SchoolInfo> >(schoolInfosXmlRootAttribute);

            formatter.SetSerializer <List <SchoolInfo> >((XmlSerializer)schoolInfosSerialiser);

            XmlRootAttribute studentSchoolEnrollmentsXmlRootAttribute = new XmlRootAttribute("StudentSchoolEnrollments")
            {
                Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false
            };
            ISerialiser <List <StudentSchoolEnrollment> > studentSchoolEnrollmentsSerialiser = SerialiserFactory.GetXmlSerialiser <List <StudentSchoolEnrollment> >(studentSchoolEnrollmentsXmlRootAttribute);

            formatter.SetSerializer <List <StudentSchoolEnrollment> >((XmlSerializer)studentSchoolEnrollmentsSerialiser);

            // Alternative 1.
            //XmlRootAttribute xmlRootAttribute = new XmlRootAttribute("StudentPersonals") { Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false };
            //formatter.SetSerializer<List<StudentPersonal>>(new XmlSerializer(typeof(List<StudentPersonal>), xmlRootAttribute));

            // Alternative 2.
            //XmlAttributes attributes = new XmlAttributes();
            //attributes.XmlRoot = new XmlRootAttribute("StudentPersonals") { Namespace = SettingsManager.ProviderSettings.DataModelNamespace, IsNullable = false };
            //XmlAttributeOverrides overrides = new XmlAttributeOverrides();
            //overrides.Add(typeof(List<StudentPersonal>), attributes);
            //formatter.SetSerializer<List<StudentPersonal>>(new XmlSerializer(typeof(List<StudentPersonal>), overrides));

            // Configure global exception loggers for unexpected errors.
            GlobalConfiguration.Configuration.Services.Add(typeof(IExceptionLogger), new TraceExceptionLogger());

            // Configure a global exception handler for unexpected errors.
            GlobalConfiguration.Configuration.Services.Replace(typeof(IExceptionHandler), new GlobalUnexpectedExceptionHandler());

            Trace.TraceInformation("********** Application_Start **********");
            Register();
        }
예제 #29
0
 public AssessmentApiService(
     HttpClient httpClient,
     ISerialiser serialiser,
     IDataProcessor <GetQuestionResponse> getQuestionResponseDataProcessor,
     IDataProcessor <GetAssessmentResponse> getAssessmentResponseDataProcessor)
 {
     this.httpClient = httpClient;
     this.serialiser = serialiser;
     this.getQuestionResponseDataProcessor   = getQuestionResponseDataProcessor;
     this.getAssessmentResponseDataProcessor = getAssessmentResponseDataProcessor;
 }
예제 #30
0
 private void checkBoxExt_CheckedChanged(object sender, EventArgs e)
 {
     if (checkBoxExt.Checked)
     {
         serialiser = serialiserDict["xml"];
     }
     else
     {
         serialiser = serialiserDict["json"];
     }
 }
        public DapperAggregateRootEventStorage(ILoggerFactory loggerFactory
                                             , ISerialiser serialiser
                                             , IConnectionStringProvider connectionStringProvider
                                             , IEventToAggregateEventMapper eventToAggregateEventMapper)
        {
            _serialiser = serialiser;
            _eventToAggregateEventMapper = eventToAggregateEventMapper;

            logger = loggerFactory.Create();
            _connectionString = connectionStringProvider.Get("events");
        }
        /// <summary>
        /// Initializes a new instance of the <see cref="EventStoreContext" /> class.
        /// </summary>
        /// <param name="eventStoreConnectionSettings">The event store connection settings.</param>
        /// <param name="connectionResolver">The connection resolver.</param>
        public EventStoreContext(EventStoreConnectionSettings eventStoreConnectionSettings, Func <EventStoreConnectionSettings, IEventStoreConnection> connectionResolver, ISerialiser serialiser)
        {
            Guard.ThrowIfNull(eventStoreConnectionSettings, nameof(eventStoreConnectionSettings));

            // Cache the settings
            this.EventStoreConnectionSettings = eventStoreConnectionSettings;
            this.ConnectionResolver           = connectionResolver;
            this.Serialiser = serialiser;

            // Create a set of Cached User Credentials
            this.UserCredentials = new UserCredentials(eventStoreConnectionSettings.UserName, eventStoreConnectionSettings.Password);
        }
        public void Setup()
        {
            this.serialiser = (ISerialiser)Activator.CreateInstance(this.SerialiserType);

            var fixture = new Fixture();

            this.simple  = fixture.Create <SimpleObject>();
            this.complex = fixture.Create <ComplexObject>();

            this.serialisedSimple  = this.serialiser.Serialise(this.simple);
            this.serialisedComplex = this.serialiser.Serialise(this.complex);
        }
예제 #34
0
        public AssessmentApiServiceTests()
        {
            serialiser = new NewtonsoftSerialiser();
            getQuestionResponseDataProcessor   = A.Fake <IDataProcessor <GetQuestionResponse> >();
            getAssessmentResponseDataProcessor = A.Fake <IDataProcessor <GetAssessmentResponse> >();

            httpMessageHandler     = new MockHttpMessageHandler();
            httpClient             = httpMessageHandler.ToHttpClient();
            httpClient.BaseAddress = new Uri("https://localhost");

            assessmentApiService = new AssessmentApiService(httpClient, serialiser, getQuestionResponseDataProcessor, getAssessmentResponseDataProcessor);
        }
        public AcknowledgementRecieveChannelBuilder(
            MessageReceiver messageReceiver, 
            MessageAcknowledgementHandler handler, 
            ISerialiser serialiser)
        {
            Contract.Requires(messageReceiver != null);
            Contract.Requires(handler != null);
            Contract.Requires(serialiser != null);

            this.messageReceiver = messageReceiver;
            this.handler = handler;
            this.serialiser = serialiser;
        }
 public HttpServerTransportBuilder(
     IHttpServerBuilder httpServerBuilder, 
     ISerialiser serialiser, 
     MessageReceiver messageReceiver)
 {
     Contract.Requires(httpServerBuilder != null);
     Contract.Requires(serialiser != null);
     Contract.Requires(messageReceiver != null);
     
     this.httpServerBuilder = httpServerBuilder;
     this.serialiser = serialiser;
     this.messageReceiver = messageReceiver;
 }
        public object Read(
            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, "Reading Vault from JSON using serialiser '{0}'.", formatVersion);

            JObject dataJSON = (JObject)data;

            String            id             = JSONHelpers.ReadString(dataJSON, "ID");
            String            name           = JSONHelpers.ReadString(dataJSON, "Name");
            String            description    = JSONHelpers.ReadString(dataJSON, "Description");
            DateTime          createdAt      = JSONHelpers.ReadDateTime(dataJSON, "CreatedAt");
            DateTime          lastUpdatedAt  = JSONHelpers.ReadDateTime(dataJSON, "LastUpdatedAt");
            List <Credential> credentialList = new List <Credential>();

            ISerialiser credentialSerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(Credential));
            JArray      credentials          = JSONHelpers.ReadJArray(dataJSON, "Credentials", true);

            foreach (JObject curCredential in credentials)
            {
                Credential credential = (Credential)credentialSerialiser.Read(curCredential, String.Empty);
                credentialList.Add(credential);
            }
            List <AuditLogEntry> auditLogEntriesList = new List <AuditLogEntry>();

            if (dataJSON.ContainsKey("AuditLogEntries"))
            {
                ISerialiser auditLogEntrySerialiser = FormatVersions.Instance.GetSerialiser(formatVersion.Version, typeof(AuditLogEntry));
                JArray      auditLogEntries         = JSONHelpers.ReadJArray(dataJSON, "AuditLogEntries", true);
                foreach (JObject curEntry in auditLogEntries)
                {
                    AuditLogEntry entry = (AuditLogEntry)auditLogEntrySerialiser.Read(curEntry, String.Empty);
                    auditLogEntriesList.Add(entry);
                }
                if (auditLogEntriesList.Count > 0)
                {
                    auditLogEntriesList = auditLogEntriesList.OrderByDescending(ale => ale.DateTime).ToList();
                }
            }
            return(new Vault(id,
                             name,
                             description,
                             createdAt,
                             lastUpdatedAt,
                             credentialList.ToArray(),
                             auditLogEntriesList.ToArray()));
        }
예제 #38
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));
        }
예제 #39
0
 public CustomerCapturer(ICsvWriter csvWriter, ISerialiser serialiser, IDataCleaner dataCleaner)
 {
     if (csvWriter == null)
     {
         throw new ArgumentNullException(nameof(csvWriter));
     }
     if (serialiser == null)
     {
         throw new ArgumentNullException(nameof(serialiser));
     }
     _csvWriter   = csvWriter;
     _serialiser  = serialiser;
     _dataCleaner = dataCleaner;
 }
        public HttpRemoteServerBuilder(
            IHttpServerBuilder httpServerBuilder, 
            ISystemTime systemTime, 
            ISerialiser serialiser, 
            ServerAddressRegistry serverAddressRegistry)
        {
            Contract.Requires(httpServerBuilder != null);
            Contract.Requires(systemTime != null);
            Contract.Requires(serialiser != null);
            Contract.Requires(serverAddressRegistry != null);

            this.httpServerBuilder = httpServerBuilder;
            this.systemTime = systemTime;
            this.serialiser = serialiser;
            this.serverAddressRegistry = serverAddressRegistry;
        }
        public ReplyReceiverBuilder(
            MessageReceiver messageReceiver,
            ISerialiser serialiser,
            IMainThreadMarshaller mainThreadMarshaller,
            MessageHandlerRouter router)
        {
            Contract.Requires(messageReceiver != null);
            Contract.Requires(serialiser != null);
            Contract.Requires(mainThreadMarshaller != null);
            Contract.Requires(router != null);

            this.messageReceiver = messageReceiver;
            this.serialiser = serialiser;
            this.mainThreadMarshaller = mainThreadMarshaller;
            this.router = router;
        }
예제 #42
0
        public object Read(
            object data,
            string masterPassphrase,
            params KeyValuePair <string, string>[] parameters)
        {
            DLoggerManager.Instance.Logger.Log(DFramework.Logging.Interfaces.LoggerMessageType.VerboseHigh | DFramework.Logging.Interfaces.LoggerMessageType.Information, "Reading Vault from JObject.");

            JObject dataJSON      = (JObject)data;
            JObject header        = JSONHelpers.ReadJObject(dataJSON, "Header", true);
            string  formatVersion = header["FormatVersion"].Value <String>();

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

            return(serialiser.Read(
                       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);
        }
예제 #44
0
        public LongPoller(
            IWebRequestor requestor, 
            ISerialiser formatter, 
            ITaskScheduler scheduler, 
            MessageReceiver receiver, 
            ITaskStarter starter)
        {
            Contract.Requires(requestor != null);
            Contract.Requires(formatter != null);
            Contract.Requires(scheduler != null);
            Contract.Requires(receiver != null);
            Contract.Requires(starter != null);

            this.requestor = requestor;
            this.formatter = formatter;
            this.scheduler = scheduler;
            this.receiver = receiver;
            this.starter = starter;
        }
예제 #45
0
        /// <summary>
        /// Serialize method.
        /// </summary>
        public void Serialize <T>(T obj, string path)
        {
            ISerialiser serialiser = (ISerialiser)Serialiser;

            if (CheckISerialize)
            {
                if (obj is MarkerISerialize.ISerialize)
                {
                    serialiser.Serialize(obj, path);
                }
                else
                {
                    throw new System.InvalidCastException();
                }
            }
            else
            {
                serialiser.Serialize(obj, path);
            }
        }
예제 #46
0
        /// <summary>
        /// Deserialize method.
        /// </summary>
        public T Deserialize <T>(string path)
        {
            ISerialiser deserialize    = (ISerialiser)Serialiser;
            var         deserializeObj = deserialize.Deserialize <T>(path);

            if (CheckVersion)
            {
                Version version = (Version)deserializeObj.GetType().GetProperty("Version").GetValue(deserializeObj, null);

                if (!Version.Equals(version))
                {
                    throw new System.ArgumentException("Version do not equal");
                }
                return(deserializeObj);
            }
            else
            {
                return(deserializeObj);
            }
        }
예제 #47
0
        public void SendBroadcastMessage(BroadcastMessageType msgType, ISerialiser <AutoDiscoveryMessage, byte[]> serialiser, Int32 multicastPort)
        {
            if (msgType == BroadcastMessageType.None)
            {
                throw new InvalidOperationException("The specified BroadcastMessageType is not valid");
            }

            if (serialiser == null)
            {
                throw new ArgumentException("The specified serialiser is not valid");
            }

            // Create and prepare the arguments
            byte[] temp = serialiser.Serialise(new AutoDiscoveryMessage(_socket.LocalEndPoint, msgType));
            byte[] data = BitConverter.GetBytes(temp.Length).Merge(temp);
            // send the data
            UdpClient cli = new UdpClient();

            cli.Send(data, data.Length, new IPEndPoint(IPAddress.Broadcast, Port));
        }
        internal RequestRecieveChannelBuilder(
            ReplyAddressLookup replyAddressLookup,
            ISerialiser serialiser,
            MessageHandlerRouter messageHandlerRouter,
            AcknowledgementSender acknowledgementSender,
            MessageCacheFactory messageCacheFactory,
            ISystemTime systemTime,
            ITaskRepeater taskRepeater,
            ServerAddressRegistry serverAddressRegistry,
            IMainThreadMarshaller mainThreadMarshaller,
            AuthenticationSessionCache authenticationSessionCache,
            AuthenticatedServerRegistry authenticatedServerRegistry,
            ReplyCorrelationLookup correlationLookup)
        {
            Contract.Requires(replyAddressLookup != null);
            Contract.Requires(serialiser != null);
            Contract.Requires(messageHandlerRouter != null);
            Contract.Requires(acknowledgementSender != null);
            Contract.Requires(messageCacheFactory != null);
            Contract.Requires(systemTime != null);
            Contract.Requires(taskRepeater != null);
            Contract.Requires(serverAddressRegistry != null);
            Contract.Requires(mainThreadMarshaller != null);
            Contract.Requires(authenticationSessionCache != null);
            Contract.Requires(authenticatedServerRegistry != null);
            Contract.Requires(correlationLookup != null);

            this.replyAddressLookup = replyAddressLookup;
            this.serialiser = serialiser;
            this.messageHandlerRouter = messageHandlerRouter;
            this.acknowledgementSender = acknowledgementSender;
            this.messageCacheFactory = messageCacheFactory;
            this.systemTime = systemTime;
            this.taskRepeater = taskRepeater;
            this.serverAddressRegistry = serverAddressRegistry;
            this.mainThreadMarshaller = mainThreadMarshaller;
            this.authenticationSessionCache = authenticationSessionCache;
            this.authenticatedServerRegistry = authenticatedServerRegistry;
            this.correlationLookup = correlationLookup;
        }
 internal MessageBodyService(IRestClient restClient, ISerialiser serialiser)
     : base(restClient, serialiser)
 {
 }
예제 #50
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FavouriteHandler"/> class.
 /// </summary>
 private FavouriteHandler()
 {
     this._Serializer = new XmlSerialiser<List<Favourite>>();
     this._Favourites = new List<Favourite>();
 }
예제 #51
0
 /// <summary>
 /// Initializes a new instance of the <see cref="FavouriteHandler"/> class.
 /// </summary>
 /// <param name="filePath">The file path.</param>
 private FavouriteHandler(String filePath)
 {
     this._Serializer = new XmlSerialiser<List<Favourite>>(filePath);
     this._Favourites = new List<Favourite>();
 }
 /// <summary>
 /// Constructs a new instance of the service bus listener
 /// </summary>
 /// <param name="subscribers">Collection of subscribers</param>
 /// <param name="serialiser">Serialiser to use (defaults to SimpleJson)</param>
 /// <param name="serviceBus">Raw service bus (defaults to "real" service bus)</param>
 public ServiceBusListener(IEnumerable<ISubscriber> subscribers, ISerialiser serialiser = null, IServiceBus serviceBus = null)
 {
     this.subscribers = subscribers.ToArray();
     this.serialiser = serialiser ?? new SimpleJsonSerialiser();
     this.serviceBus = serviceBus ?? new ServiceBus.ServiceBus();
 }
예제 #53
0
 private HistoryHandler()
 {
     this._Serializer = new XmlSerialiser<History>();
     this._History = new History();
 }
 public MessagePayloadCopier(ISerialiser serialiser)
 {
     Contract.Requires(serialiser != null);
     this.serialiser = serialiser;
 }
예제 #55
0
 private HistoryHandler(String filePath)
 {
     this._Serializer = new XmlSerialiser<History>(filePath);
     this._History = new History();
 }
 InMemoryChangeStore(ISerialiser serialiser) : base(serialiser, new ChangeUpcasterRunner(new ApplicationTypeActivator()))
 {
     this.serialiser = serialiser;
     changes = new ConcurrentDictionary<int, ChangeContainer>();
 }
예제 #57
0
 internal SessionService(IRestClient restClient, ISerialiser serialiser)
     : base(restClient, serialiser)
 {
 }
 internal GroupService(IRestClient restClient, ISerialiser serialiser)
     : base(restClient, serialiser)
 {
 }
예제 #59
0
 private static CustomerCapturer CreateCustomerCapturer(ICsvWriter csvWriter = null, ISerialiser serialiser = null, IDataCleaner dataCleaner = null)
 {
     csvWriter = csvWriter ?? Substitute.For<ICsvWriter>();
     serialiser = serialiser ?? Substitute.For<ISerialiser>();
     dataCleaner = dataCleaner ?? new DataCleaner();
     return new CustomerCapturer(csvWriter, serialiser, dataCleaner);
 }
예제 #60
0
 internal ContactService(IRestClient restClient, ISerialiser serialiser)
     : base(restClient, serialiser)
 {
 }