コード例 #1
0
ファイル: ScriptServices.cs プロジェクト: jrusbatch/scriptcs
 public ScriptServices(
     IFileSystem fileSystem,
     IPackageAssemblyResolver packageAssemblyResolver,
     IScriptExecutor executor,
     IRepl repl,
     IScriptEngine engine,
     IFilePreProcessor filePreProcessor,
     IScriptPackResolver scriptPackResolver,
     IPackageInstaller packageInstaller,
     IObjectSerializer objectSerializer,
     ILog logger,
     IAssemblyResolver assemblyResolver,
     IEnumerable<IReplCommand> replCommands,
     IConsole console = null,
     IInstallationProvider installationProvider = null)
 {
     FileSystem = fileSystem;
     PackageAssemblyResolver = packageAssemblyResolver;
     Executor = executor;
     Repl = repl;
     Engine = engine;
     FilePreProcessor = filePreProcessor;
     ScriptPackResolver = scriptPackResolver;
     PackageInstaller = packageInstaller;
     ObjectSerializer = objectSerializer;
     Logger = logger;
     Console = console;
     AssemblyResolver = assemblyResolver;
     InstallationProvider = installationProvider;
     ReplCommands = replCommands;
 }
コード例 #2
0
 public AmfV3Formatter()
   {
   stream = new MemoryStream();
   writer = new FlashorbBinaryWriter( stream );
   objectSerializer = new V3ObjectSerializer();
   referenceCache = new V3ReferenceCache();
   }
コード例 #3
0
ファイル: ExecuteReplCommand.cs プロジェクト: selony/scriptcs
 public ExecuteReplCommand(
     string scriptName,
     string[] scriptArgs,
     IFileSystem fileSystem,
     IScriptPackResolver scriptPackResolver,
     IScriptEngine scriptEngine,
     IFilePreProcessor filePreProcessor,
     IObjectSerializer serializer,
     ILog logger,
     IConsole console,
     IAssemblyResolver assemblyResolver,
     IEnumerable<IReplCommand> replCommands)
 {
     _scriptName = scriptName;
     _scriptArgs = scriptArgs;
     _fileSystem = fileSystem;
     _scriptPackResolver = scriptPackResolver;
     _scriptEngine = scriptEngine;
     _filePreProcessor = filePreProcessor;
     _serializer = serializer;
     _logger = logger;
     _console = console;
     _assemblyResolver = assemblyResolver;
     _replCommands = replCommands;
 }
コード例 #4
0
 /// <summary>
 /// Initializes a new instance of the <see cref="CookieBasedSessions"/> class.
 /// </summary>
 /// <param name="encryptionProvider">The encryption provider.</param>
 /// <param name="hmacProvider">The hmac provider</param>
 /// <param name="objectSerializer">Session object serializer to use</param>
 public CookieBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)
 {
     this.currentConfiguration = new CookieBasedSessionsConfiguration
     {
         Serializer = objectSerializer,
         CryptographyConfiguration = new CryptographyConfiguration(encryptionProvider, hmacProvider)
     };
 }
コード例 #5
0
        public CookieBasedSessionsFixture()
        {
            this.fakeEncryptionProvider = A.Fake<IEncryptionProvider>();
            this.fakeHmacProvider = A.Fake<IHmacProvider>();
            this.fakeObjectSerializer = new Fakes.FakeObjectSerializer();
            this.cookieStore = new CookieBasedSessions(this.fakeEncryptionProvider, this.fakeHmacProvider, this.fakeObjectSerializer);

            this.rijndaelEncryptionProvider = new RijndaelEncryptionProvider(new PassphraseKeyGenerator("password", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
            this.defaultHmacProvider = new DefaultHmacProvider(new PassphraseKeyGenerator("anotherpassword", new byte[] { 1, 2, 3, 4, 5, 6, 7, 8 }, 1000));
            this.defaultObjectSerializer = new DefaultObjectSerializer();
        }
コード例 #6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="RedisBasedSessions"/> class.
        /// </summary>
        /// <param name="encryptionProvider">The encryption provider.</param>
        /// <param name="hmacProvider">The hmac provider</param>
        /// <param name="objectSerializer">Session object serializer to use</param>
        public RedisBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)
        {
            _currentConfiguration = new RedisBasedSessionsConfiguration
            {
                Serializer = objectSerializer,
                CryptographyConfiguration = new CryptographyConfiguration(encryptionProvider, hmacProvider)
            };

            if (_redis == null)
                _redis = ConnectionMultiplexer.Connect(_currentConfiguration.ConnectionString);

            _db = _redis.GetDatabase();
        }
コード例 #7
0
ファイル: Repl.cs プロジェクト: Jaydeep7/scriptcs
 public Repl(
     string[] scriptArgs,
     IFileSystem fileSystem,
     IScriptEngine scriptEngine,
     IObjectSerializer serializer,
     ILog logger,
     IConsole console,
     IFilePreProcessor filePreProcessor)
     : base(fileSystem, filePreProcessor, scriptEngine, logger)
 {
     _scriptArgs = scriptArgs;
     _serializer = serializer;
     Console = console;
 }
コード例 #8
0
        public When_an_Lrap1_attachment_is_submitted()
        {
            //Arrange
            _fakeObjectSerializer = A.Fake<IObjectSerializer>();
            _fakeRequestSender = A.Fake<IRequestSender>();

            _lrap1AttachmentRequest = new Lrap1AttachmentRequest()
            {
                Payload = "payload data"
            };

            _sut = new EdrsCommunicator(_fakeObjectSerializer);
            _sut.RequestSender = _fakeRequestSender;
        }
コード例 #9
0
ファイル: Repl.cs プロジェクト: jrusbatch/scriptcs
 public Repl(
     string[] scriptArgs,
     IFileSystem fileSystem,
     IScriptEngine scriptEngine,
     IObjectSerializer serializer,
     ILog logger,
     IConsole console,
     IFilePreProcessor filePreProcessor,
     IEnumerable<IReplCommand> replCommands)
     : base(fileSystem, filePreProcessor, scriptEngine, logger)
 {
     _scriptArgs = scriptArgs;
     _serializer = serializer;
     Console = console;
     Commands = replCommands != null ? replCommands.Where(x => x.CommandName != null).ToDictionary(x => x.CommandName, x => x) : new Dictionary<string, IReplCommand>();
 }
コード例 #10
0
ファイル: Repl.cs プロジェクト: selony/scriptcs
 public Repl(
     string[] scriptArgs,
     IFileSystem fileSystem,
     IScriptEngine scriptEngine,
     IObjectSerializer serializer,
     ILog logger,
     IConsole console,
     IFilePreProcessor filePreProcessor,
     IEnumerable<IReplCommand> replCommands)
     : base(fileSystem, filePreProcessor, scriptEngine, logger)
 {
     _scriptArgs = scriptArgs;
     _serializer = serializer;
     Console = console;
     Commands = replCommands != null ? replCommands.ToList() : new List<IReplCommand>();
 }
コード例 #11
0
ファイル: SerializerFactory.cs プロジェクト: babon/UnityMesh
        public void RegisterSerializer(IObjectSerializer serializer)
        {
            if (serializer.TypeID < 0) throw new InvalidDataException("serializers cannot have TypeIDs less than 0");
            IObjectSerializer existingSer;
            if (_serializers.TryGetValue(serializer.Type, out existingSer))
            {
                Debug.LogWarning(string.Format("Overwriting existing serializer {0} with {1}", existingSer, serializer));
            }
            _serializers[serializer.Type] = serializer;

            Type existingType;
            if (_typeMap.TryGetValue(serializer.TypeID, out existingType))
            {
                Debug.LogWarning(string.Format("Overwriting existing serializer for type {0} with {1}", existingType.Name, serializer));
            }
            _typeMap[serializer.TypeID] = serializer.Type;
        }
コード例 #12
0
 public LoadWorkflowAsyncResult
     (
     InstancePersistenceContext context, 
     InstancePersistenceCommand command, 
     SqlWorkflowInstanceStore store,
     SqlWorkflowInstanceStoreLock storeLock,
     Transaction currentTransaction,
     TimeSpan timeout, 
     AsyncCallback callback, 
     object state
     ) :
     base(context, command, store, storeLock, currentTransaction, timeout, callback, state)
 {
     this.associatedInstanceKeys = new Dictionary<Guid, IDictionary<XName, InstanceValue>>();
     this.completedInstanceKeys = new Dictionary<Guid, IDictionary<XName, InstanceValue>>();
     this.objectSerializer = ObjectSerializerFactory.GetDefaultObjectSerializer();
 }
コード例 #13
0
        public XmlDataStoreRepository()
        {
            dataStoreRepositoryPath = ConfigurationItem<string>.ReadSetting("XmlDataStoreRepositoryPath").GetValue();

            serializer = new XmlObjectSerializer();

            if (!File.Exists(dataStoreRepositoryPath))
            {
                dataStores = new XmlDataStoreCollection();

                File.WriteAllText(dataStoreRepositoryPath, serializer.Serialize(dataStores));

                return;
            }

            dataStores = serializer.Deserialize<XmlDataStoreCollection>(File.ReadAllText(dataStoreRepositoryPath));
        }
コード例 #14
0
        public SecureXmlDataStoreRepository()
        {
            key = ConfigurationItem<string>.ReadSetting("SecureXmlDataStoreRepositoryKey").GetValue();
            dataStoreRepositoryPath = ConfigurationItem<string>.ReadSetting("SecureXmlDataStoreRepositoryPath").GetValue();

            serializer = new XmlObjectSerializer();

            if (!File.Exists(dataStoreRepositoryPath))
            {
                dataStores = new XmlDataStoreCollection();

                File.WriteAllText(dataStoreRepositoryPath, serializer.Serialize(dataStores));

                return;
            }

            dataStores = serializer.Deserialize<XmlDataStoreCollection>(File.ReadAllText(dataStoreRepositoryPath));

            PersistStore(); // force encryption for any insecure connection strings
        }
コード例 #15
0
        public ReplExecutor(
            IRepl repl,
            IObjectSerializer serializer,
            IFileSystem fileSystem,
            IFilePreProcessor filePreProcessor,
            IScriptEngine scriptEngine,
            ILog logger,
            IEnumerable<IReplCommand> replCommands)
            : base(fileSystem, filePreProcessor, scriptEngine, logger)
        {
            this.repl = repl;
            this.serializer = serializer;
            this.replCommands = replCommands;

            replCompletion = new CSharpCompletion(true);
            replCompletion.AddReferences(GetReferencesAsPaths());

            //since it's quite expensive to initialize the "System." references we clone the REPL code completion
            documentCompletion = replCompletion.Clone();
        }
コード例 #16
0
ファイル: ReplExecutor.cs プロジェクト: nategreenwood/CShell
        public ReplExecutor(
            IRepl repl,
            IObjectSerializer serializer,
            IFileSystem fileSystem,
            IFilePreProcessor filePreProcessor,
            IScriptEngine scriptEngine,
            IPackageInstaller packageInstaller,
            IPackageAssemblyResolver resolver,
            ILog logger)
            : base(fileSystem, filePreProcessor, scriptEngine, logger)
        {
            this.repl = repl;
            this.serializer = serializer;
            this.packageInstaller = packageInstaller;
            this.resolver = resolver;

            replCompletion = new CSharpCompletion(true);
            replCompletion.AddReferences(GetReferencesAsPaths());

            //since it's quite expensive to initialize the "System." references we clone the REPL code completion
            documentCompletion = replCompletion.Clone();
        }
コード例 #17
0
ファイル: ScriptServices.cs プロジェクト: JamesLinus/scriptcs
        public ScriptServices(
            IFileSystem fileSystem,
            IPackageAssemblyResolver packageAssemblyResolver,
            IScriptExecutor executor,
            IRepl repl,
            IScriptEngine engine,
            IFilePreProcessor filePreProcessor,
            IScriptPackResolver scriptPackResolver,
            IPackageInstaller packageInstaller,
            IObjectSerializer objectSerializer,
            ILogProvider logProvider,
            IAssemblyResolver assemblyResolver,
            IEnumerable<IReplCommand> replCommands,
            IFileSystemMigrator fileSystemMigrator,
            IConsole console = null,
            IInstallationProvider installationProvider = null,
            IScriptLibraryComposer scriptLibraryComposer = null
            )
        {
            FileSystem = fileSystem;
            PackageAssemblyResolver = packageAssemblyResolver;
            Executor = executor;
            Repl = repl;
            Engine = engine;
            FilePreProcessor = filePreProcessor;
            ScriptPackResolver = scriptPackResolver;
            PackageInstaller = packageInstaller;
            ObjectSerializer = objectSerializer;
            LogProvider = logProvider;
#pragma warning disable 618
            Logger = new ScriptCsLogger(logProvider.ForCurrentType());
#pragma warning restore 618
            Console = console;
            AssemblyResolver = assemblyResolver;
            InstallationProvider = installationProvider;
            ReplCommands = replCommands;
            FileSystemMigrator = fileSystemMigrator;
            ScriptLibraryComposer = scriptLibraryComposer;
        }
コード例 #18
0
ファイル: Repl.cs プロジェクト: JamesLinus/scriptcs
        public Repl(
            string[] scriptArgs,
            IFileSystem fileSystem,
            IScriptEngine scriptEngine,
            IObjectSerializer serializer,
            ILogProvider logProvider,
            IScriptLibraryComposer composer,
            IConsole console,
            IFilePreProcessor filePreProcessor,
            IEnumerable<IReplCommand> replCommands)
            : base(fileSystem, filePreProcessor, scriptEngine, logProvider, composer)
        {
            Guard.AgainstNullArgument("serializer", serializer);
            Guard.AgainstNullArgument("logProvider", logProvider);
            Guard.AgainstNullArgument("console", console);

            _scriptArgs = scriptArgs;
            _serializer = serializer;
            _log = logProvider.ForCurrentType();
            Console = console;
            Commands = replCommands != null ? replCommands.Where(x => x.CommandName != null).ToDictionary(x => x.CommandName, x => x) : new Dictionary<string, IReplCommand>();
        }
コード例 #19
0
ファイル: Repl.cs プロジェクト: JamesLinus/scriptcs
 public Repl(
     string[] scriptArgs,
     IFileSystem fileSystem,
     IScriptEngine scriptEngine,
     IObjectSerializer serializer,
     Common.Logging.ILog logger,
     IScriptLibraryComposer composer,
     IConsole console,
     IFilePreProcessor filePreProcessor,
     IEnumerable<IReplCommand> replCommands)
     : this(
         scriptArgs,
         fileSystem,
         scriptEngine,
         serializer,
         new CommonLoggingLogProvider(logger),
         composer,
         console,
         filePreProcessor,
         replCommands)
 {
 }
コード例 #20
0
ファイル: ScriptServices.cs プロジェクト: JamesLinus/scriptcs
 public ScriptServices(
     IFileSystem fileSystem,
     IPackageAssemblyResolver packageAssemblyResolver,
     IScriptExecutor executor,
     IRepl repl,
     IScriptEngine engine,
     IFilePreProcessor filePreProcessor,
     IScriptPackResolver scriptPackResolver,
     IPackageInstaller packageInstaller,
     IObjectSerializer objectSerializer,
     Common.Logging.ILog logger,
     IAssemblyResolver assemblyResolver,
     IEnumerable<IReplCommand> replCommands,
     IFileSystemMigrator fileSystemMigrator,
     IConsole console = null,
     IInstallationProvider installationProvider = null,
     IScriptLibraryComposer scriptLibraryComposer = null
     )
     : this(
         fileSystem,
         packageAssemblyResolver,
         executor,
         repl,
         engine,
         filePreProcessor,
         scriptPackResolver,
         packageInstaller,
         objectSerializer,
         new CommonLoggingLogProvider(logger),
         assemblyResolver,
         replCommands,
         fileSystemMigrator,
         console,
         installationProvider,
         scriptLibraryComposer
     )
 {
 }
コード例 #21
0
 /// <summary>
 /// Checks if the filter applies to the object.
 /// </summary>
 /// <param name="Object">Object.</param>
 /// <param name="Serializer">Corresponding object serializer.</param>
 /// <param name="Provider">Files provider.</param>
 /// <returns>If the filter can be applied.</returns>
 public bool AppliesTo(object Object, IObjectSerializer Serializer, FilesProvider Provider)
 {
     return(this.customFilter.Passes(Object));
 }
コード例 #22
0
        /// <summary>
        /// Serializes an object to a binary destination.
        /// </summary>
        /// <param name="Writer">Binary destination.</param>
        /// <param name="WriteTypeCode">If a type code is to be output.</param>
        /// <param name="Embedded">If the object is embedded into another.</param>
        /// <param name="Value">The actual object to serialize.</param>
        public void Serialize(BinarySerializer Writer, bool WriteTypeCode, bool Embedded, object Value)
        {
            if (Value is GenericObject TypedValue)
            {
                BinarySerializer  WriterBak = Writer;
                IObjectSerializer Serializer;
                object            Obj;

                if (!Embedded)
                {
                    Writer = new BinarySerializer(Writer.CollectionName, Writer.Encoding, true);
                }

                if (WriteTypeCode)
                {
                    if (TypedValue == null)
                    {
                        Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6);
                        return;
                    }
                    else
                    {
                        Writer.WriteBits(ObjectSerializer.TYPE_OBJECT, 6);
                    }
                }
                else if (TypedValue == null)
                {
                    throw new NullReferenceException("Value cannot be null.");
                }

                if (string.IsNullOrEmpty(TypedValue.TypeName))
                {
                    Writer.WriteVariableLengthUInt64(0);
                }
                else
                {
                    Writer.WriteVariableLengthUInt64(this.provider.GetFieldCode(TypedValue.CollectionName, TypedValue.TypeName));
                }

                if (Embedded)
                {
                    Writer.WriteVariableLengthUInt64(this.provider.GetFieldCode(null, string.IsNullOrEmpty(TypedValue.CollectionName) ? this.provider.DefaultCollectionName : TypedValue.CollectionName));
                }

                foreach (KeyValuePair <string, object> Property in TypedValue)
                {
                    Writer.WriteVariableLengthUInt64(this.provider.GetFieldCode(TypedValue.CollectionName, Property.Key));

                    Obj = Property.Value;
                    if (Obj == null)
                    {
                        Writer.WriteBits(ObjectSerializer.TYPE_NULL, 6);
                    }
                    else
                    {
                        if (Obj is GenericObject)
                        {
                            this.Serialize(Writer, true, true, Obj);
                        }
                        else
                        {
                            Serializer = this.provider.GetObjectSerializer(Obj.GetType());
                            Serializer.Serialize(Writer, true, true, Obj);
                        }
                    }
                }

                Writer.WriteVariableLengthUInt64(0);

                if (!Embedded)
                {
                    if (!TypedValue.ObjectId.Equals(Guid.Empty))
                    {
                        WriterBak.Write(TypedValue.ObjectId);
                    }
                    else
                    {
                        Guid NewObjectId = ObjectBTreeFile.CreateDatabaseGUID();
                        WriterBak.Write(NewObjectId);
                        TypedValue.ObjectId = NewObjectId;
                    }

                    byte[] Bin = Writer.GetSerialization();

                    WriterBak.WriteVariableLengthUInt64((ulong)Bin.Length);
                    WriterBak.WriteRaw(Bin);
                }
            }
            else
            {
                IObjectSerializer Serializer = this.provider.GetObjectSerializer(Value.GetType());
                Serializer.Serialize(Writer, WriteTypeCode, Embedded, Value);
            }
        }
コード例 #23
0
 public SqlPersistenceProvider(IObjectSerializer objectSerializer, ISessionFactory sessionFactory)
 {
     this.sessionFactory = sessionFactory;
     workflowDefinitionTransformer = new WorkflowDefinitionTransformer();
     executionTransformer = new ExecutionDefinitionTransformer(objectSerializer);
 }
コード例 #24
0
 public ObjectSerializerToResponseContentDeserializer(IObjectSerializer objectSerializer)
 {
     _objectSerializer = objectSerializer ?? throw new ArgumentNullException(nameof(objectSerializer));
 }
コード例 #25
0
        protected BaseConnectionHandler(IObjectSerializer packetSerializer, IIncomingNetworkEventHandler networkEventProcessor, ILogger logger, IEventBus eventBus, IGamePlatformAccessor gamePlatformAccessor)
        {
            eventBus.Subscribe <GameQuitEvent>(this, (s, e) => { Dispose(); });

            m_EventBus              = eventBus;
            m_PacketSerializer      = packetSerializer;
            m_NetworkEventProcessor = networkEventProcessor;
            m_Logger = logger;

            int capacity = 1024;

            if (gamePlatformAccessor.GamePlatform == GamePlatform.Server)
            {
                capacity *= ServerConnectionHandler.MaxPlayersUpperLimit;
            }

            m_OutgoingQueue      = new RingBuffer <OutgoingPacket>(capacity);
            m_ConnectedPeers     = new List <INetworkPeer>();
            m_PacketDescriptions = new Dictionary <byte, PacketDescription>();

            RegisterPacket((byte)PacketType.Ping, new PacketDescription(
                               name: nameof(PacketType.Ping),
                               direction: PacketDirection.Any,
                               channel: (byte)NetworkChannel.PingPong,
                               packetFlags: PacketFlags.Reliable)
                           );

            RegisterPacket((byte)PacketType.Pong, new PacketDescription(
                               name: nameof(PacketType.Pong),
                               direction: PacketDirection.Any,
                               channel: (byte)NetworkChannel.PingPong,
                               packetFlags: PacketFlags.Reliable)
                           );

            RegisterPacket((byte)PacketType.Authenticate, new PacketDescription(
                               name: nameof(PacketType.Authenticate),
                               direction: PacketDirection.ClientToServer,
                               channel: (byte)NetworkChannel.Main,
                               packetFlags: PacketFlags.Reliable,
                               needsAuthentication: false)
                           );

            RegisterPacket((byte)PacketType.Authenticated, new PacketDescription(
                               name: nameof(PacketType.Authenticated),
                               direction: PacketDirection.ServerToClient,
                               channel: (byte)NetworkChannel.Main,
                               packetFlags: PacketFlags.Reliable)
                           );

            RegisterPacket((byte)PacketType.MapChange, new PacketDescription(
                               name: nameof(PacketType.MapChange),
                               direction: PacketDirection.ServerToClient,
                               channel: (byte)NetworkChannel.Main,
                               packetFlags: PacketFlags.Reliable)
                           );

            RegisterPacket((byte)PacketType.WorldUpdate, new PacketDescription(
                               name: nameof(PacketType.WorldUpdate),
                               direction: PacketDirection.ServerToClient,
                               channel: (byte)NetworkChannel.World,
                               packetFlags: PacketFlags.Reliable) //Todo: Make this Unsequenced after Snapshots get implemented fully
                           );

            RegisterPacket((byte)PacketType.InputUpdate, new PacketDescription(
                               name: nameof(PacketType.InputUpdate),
                               direction: PacketDirection.ClientToServer,
                               channel: (byte)NetworkChannel.Input,
                               packetFlags: PacketFlags.Unsequenced)
                           );

            RegisterPacket((byte)PacketType.Terminate, new PacketDescription(
                               name: nameof(PacketType.Terminate),
                               direction: PacketDirection.ServerToClient,
                               channel: (byte)NetworkChannel.Input,
                               packetFlags: PacketFlags.Reliable)
                           );

            RegisterPacket((byte)PacketType.Rpc, new PacketDescription(
                               name: nameof(PacketType.Rpc),
                               direction: PacketDirection.Any,
                               channel: (byte)NetworkChannel.Rpc,
                               packetFlags: PacketFlags.Reliable)
                           );
        }
コード例 #26
0
        /// <summary>
        /// Advances the enumerator to the previous element of the collection.
        /// </summary>
        /// <returns>true if the enumerator was successfully advanced to the previous element; false if
        /// the enumerator has passed the beginning of the collection.</returns>
        /// <exception cref="InvalidOperationException">The collection was modified after the enumerator was created.</exception>
        public async Task <bool> MovePreviousAsync()
        {
            int i;

            while (true)
            {
                if (this.currentRange is null)
                {
                    List <KeyValuePair <string, object> >            SearchParameters = new List <KeyValuePair <string, object> >();
                    List <KeyValuePair <string, IApplicableFilter> > StartFilters     = null;
                    List <KeyValuePair <string, IApplicableFilter> > EndFilters       = null;
                    RangeInfo Range;
                    object    Value;

                    for (i = 0; i < this.nrRanges; i++)
                    {
                        Range = this.currentLimits[i];

                        if (Range.IsPoint)
                        {
                            if (EndFilters is null)
                            {
                                EndFilters = new List <KeyValuePair <string, IApplicableFilter> >();
                            }

                            SearchParameters.Add(new KeyValuePair <string, object>(Range.FieldName, Range.Point));
                            EndFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldEqualTo(Range.FieldName, Range.Point)));
                        }
                        else
                        {
                            if (Range.HasMin)
                            {
                                Value = Range.Min;

                                if (this.ascending[i])
                                {
                                    if (EndFilters is null)
                                    {
                                        EndFilters = new List <KeyValuePair <string, IApplicableFilter> >();
                                    }

                                    if (Range.MinInclusive)
                                    {
                                        EndFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldGreaterOrEqualTo(Range.FieldName, Value)));
                                    }
                                    else
                                    {
                                        EndFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldGreaterThan(Range.FieldName, Value)));
                                    }
                                }
                                else
                                {
                                    if (StartFilters is null)
                                    {
                                        StartFilters = new List <KeyValuePair <string, IApplicableFilter> >();
                                    }

                                    if (Range.MinInclusive)
                                    {
                                        StartFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldGreaterOrEqualTo(Range.FieldName, Value)));
                                    }
                                    else
                                    {
                                        StartFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldGreaterThan(Range.FieldName, Value)));

                                        if (!Comparison.Increment(ref Value))
                                        {
                                            return(false);
                                        }
                                    }

                                    SearchParameters.Add(new KeyValuePair <string, object>(Range.FieldName, Value));
                                }
                            }

                            if (Range.HasMax)
                            {
                                Value = Range.Max;

                                if (this.ascending[i])
                                {
                                    if (StartFilters is null)
                                    {
                                        StartFilters = new List <KeyValuePair <string, IApplicableFilter> >();
                                    }

                                    if (Range.MaxInclusive)
                                    {
                                        StartFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldLesserOrEqualTo(Range.FieldName, Value)));
                                    }
                                    else
                                    {
                                        StartFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldLesserThan(Range.FieldName, Value)));

                                        if (!Comparison.Decrement(ref Value))
                                        {
                                            return(false);
                                        }
                                    }

                                    SearchParameters.Add(new KeyValuePair <string, object>(Range.FieldName, Value));
                                }
                                else
                                {
                                    if (EndFilters is null)
                                    {
                                        EndFilters = new List <KeyValuePair <string, IApplicableFilter> >();
                                    }

                                    if (Range.MaxInclusive)
                                    {
                                        EndFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldLesserOrEqualTo(Range.FieldName, Value)));
                                    }
                                    else
                                    {
                                        EndFilters.Add(new KeyValuePair <string, IApplicableFilter>(Range.FieldName, new FilterFieldLesserThan(Range.FieldName, Value)));
                                    }
                                }
                            }
                        }
                    }

                    if (this.firstAscending)
                    {
                        this.currentRange = await this.index.FindLastLesserOrEqualTo <T>(this.lockType, this.lockParent, SearchParameters.ToArray());
                    }
                    else
                    {
                        this.currentRange = await this.index.FindFirstGreaterOrEqualTo <T>(this.lockType, this.lockParent, SearchParameters.ToArray());
                    }

                    this.startRangeFilters = StartFilters?.ToArray();
                    this.endRangeFilters   = EndFilters?.ToArray();
                    this.limitsUpdatedAt   = this.nrRanges;
                }

                if (!await this.currentRange.MovePreviousAsync())
                {
                    this.currentRange.Dispose();
                    this.currentRange = null;

                    if (this.limitsUpdatedAt >= this.nrRanges)
                    {
                        return(false);
                    }

                    continue;
                }

                if (!this.currentRange.CurrentTypeCompatible)
                {
                    continue;
                }

                object            CurrentValue         = this.currentRange.Current;
                IObjectSerializer CurrentSerializer    = this.currentRange.CurrentSerializer;
                string            OutOfStartRangeField = null;
                string            OutOfEndRangeField   = null;
                bool Ok = true;
                bool Smaller;

                if (!(this.additionalfilters is null))
                {
                    foreach (IApplicableFilter Filter in this.additionalfilters)
                    {
                        if (!Filter.AppliesTo(CurrentValue, CurrentSerializer, this.provider))
                        {
                            Ok = false;
                            break;
                        }
                    }
                }

                if (!(this.startRangeFilters is null))
                {
                    foreach (KeyValuePair <string, IApplicableFilter> Filter in this.startRangeFilters)
                    {
                        if (!Filter.Value.AppliesTo(CurrentValue, CurrentSerializer, this.provider))
                        {
                            OutOfStartRangeField = Filter.Key;
                            Ok = false;
                            break;
                        }
                    }
                }

                if (!(this.endRangeFilters is null) && OutOfStartRangeField is null)
                {
                    foreach (KeyValuePair <string, IApplicableFilter> Filter in this.endRangeFilters)
                    {
                        if (!Filter.Value.AppliesTo(CurrentValue, CurrentSerializer, this.provider))
                        {
                            OutOfEndRangeField = Filter.Key;
                            Ok = false;
                            break;
                        }
                    }
                }

                for (i = 0; i < this.limitsUpdatedAt; i++)
                {
                    if (CurrentSerializer.TryGetFieldValue(this.ranges[i].FieldName, CurrentValue, out object FieldValue))
                    {
                        if (this.ascending[i])
                        {
                            if (this.currentLimits[i].SetMax(FieldValue, !(OutOfStartRangeField is null), out Smaller) && Smaller)
                            {
                                i++;
                                this.limitsUpdatedAt = i;

                                while (i < this.nrRanges)
                                {
                                    this.ranges[i].CopyTo(this.currentLimits[i]);
                                    i++;
                                }
                            }
                        }
                        else
                        {
                            if (this.currentLimits[i].SetMin(FieldValue, !(OutOfStartRangeField is null), out Smaller) && Smaller)
                            {
                                i++;
                                this.limitsUpdatedAt = i;

                                while (i < this.nrRanges)
                                {
                                    this.ranges[i].CopyTo(this.currentLimits[i]);
                                    i++;
                                }
                            }
                        }
                    }
                }

                if (Ok)
                {
                    return(true);
                }
                else if (!(OutOfStartRangeField is null) || !(OutOfEndRangeField is null))
                {
                    this.currentRange.Dispose();
                    this.currentRange = null;

                    if (this.limitsUpdatedAt >= this.nrRanges)
                    {
                        return(false);
                    }
                }
            }
        }
コード例 #27
0
        /// <summary>  </summary>
        private async Task <IScheduler> Instantiate()
        {
            if (cfg == null)
            {
                Initialize();
            }

            if (initException != null)
            {
                throw initException;
            }

            ISchedulerExporter   exporter = null;
            IJobStore            js;
            IThreadPool          tp;
            QuartzScheduler      qs      = null;
            IDbConnectionManager dbMgr   = null;
            Type instanceIdGeneratorType = null;
            NameValueCollection tProps;
            bool     autoId         = false;
            TimeSpan idleWaitTime   = TimeSpan.Zero;
            TimeSpan dbFailureRetry = TimeSpan.FromSeconds(15);

            SchedulerRepository schedRep = SchedulerRepository.Instance;

            // Get Scheduler Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string schedName   = cfg.GetStringProperty(PropertySchedulerInstanceName, "QuartzScheduler");
            string threadName  = cfg.GetStringProperty(PropertySchedulerThreadName, "{0}_QuartzSchedulerThread".FormatInvariant(schedName));
            string schedInstId = cfg.GetStringProperty(PropertySchedulerInstanceId, DefaultInstanceId);

            if (schedInstId.Equals(AutoGenerateInstanceId))
            {
                autoId = true;
                instanceIdGeneratorType = LoadType(cfg.GetStringProperty(PropertySchedulerInstanceIdGeneratorType)) ?? typeof(SimpleInstanceIdGenerator);
            }
            else if (schedInstId.Equals(SystemPropertyAsInstanceId))
            {
                autoId = true;
                instanceIdGeneratorType = typeof(SystemPropertyInstanceIdGenerator);
            }

            Type typeLoadHelperType = LoadType(cfg.GetStringProperty(PropertySchedulerTypeLoadHelperType));
            Type jobFactoryType     = LoadType(cfg.GetStringProperty(PropertySchedulerJobFactoryType, null));

            idleWaitTime = cfg.GetTimeSpanProperty(PropertySchedulerIdleWaitTime, idleWaitTime);
            if (idleWaitTime > TimeSpan.Zero && idleWaitTime < TimeSpan.FromMilliseconds(1000))
            {
                throw new SchedulerException("quartz.scheduler.idleWaitTime of less than 1000ms is not legal.");
            }

            dbFailureRetry = cfg.GetTimeSpanProperty(PropertySchedulerDbFailureRetryInterval, dbFailureRetry);
            if (dbFailureRetry < TimeSpan.Zero)
            {
                throw new SchedulerException(PropertySchedulerDbFailureRetryInterval + " of less than 0 ms is not legal.");
            }

            bool makeSchedulerThreadDaemon = cfg.GetBooleanProperty(PropertySchedulerMakeSchedulerThreadDaemon);
            long batchTimeWindow           = cfg.GetLongProperty(PropertySchedulerBatchTimeWindow, 0L);
            int  maxBatchSize = cfg.GetIntProperty(PropertySchedulerMaxBatchSize, 1);

            bool interruptJobsOnShutdown         = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdown, false);
            bool interruptJobsOnShutdownWithWait = cfg.GetBooleanProperty(PropertySchedulerInterruptJobsOnShutdownWithWait, false);

            NameValueCollection schedCtxtProps = cfg.GetPropertyGroup(PropertySchedulerContextPrefix, true);

            bool proxyScheduler = cfg.GetBooleanProperty(PropertySchedulerProxy, false);

            // Create type load helper
            ITypeLoadHelper loadHelper;

            try
            {
                loadHelper = ObjectUtils.InstantiateType <ITypeLoadHelper>(typeLoadHelperType ?? typeof(SimpleTypeLoadHelper));
            }
            catch (Exception e)
            {
                throw new SchedulerConfigException("Unable to instantiate type load helper: {0}".FormatInvariant(e.Message), e);
            }
            loadHelper.Initialize();

            // If Proxying to remote scheduler, short-circuit here...
            // ~~~~~~~~~~~~~~~~~~
            if (proxyScheduler)
            {
                if (autoId)
                {
                    schedInstId = DefaultInstanceId;
                }

                Type proxyType = loadHelper.LoadType(cfg.GetStringProperty(PropertySchedulerProxyType)) ?? typeof(RemotingSchedulerProxyFactory);
                IRemotableSchedulerProxyFactory factory;
                try
                {
                    factory = ObjectUtils.InstantiateType <IRemotableSchedulerProxyFactory>(proxyType);
                    ObjectUtils.SetObjectProperties(factory, cfg.GetPropertyGroup(PropertySchedulerProxy, true));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Remotable proxy factory '{0}' could not be instantiated.".FormatInvariant(proxyType), e);
                    throw initException;
                }

                string uid = QuartzSchedulerResources.GetUniqueIdentifier(schedName, schedInstId);

                RemoteScheduler remoteScheduler = new RemoteScheduler(uid, factory);

                schedRep.Bind(remoteScheduler);

                return(remoteScheduler);
            }

            IJobFactory jobFactory = null;

            if (jobFactoryType != null)
            {
                try
                {
                    jobFactory = ObjectUtils.InstantiateType <IJobFactory>(jobFactoryType);
                }
                catch (Exception e)
                {
                    throw new SchedulerConfigException("Unable to Instantiate JobFactory: {0}".FormatInvariant(e.Message), e);
                }

                tProps = cfg.GetPropertyGroup(PropertySchedulerJobFactoryPrefix, true);
                try
                {
                    ObjectUtils.SetObjectProperties(jobFactory, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobFactory of type '{0}' props could not be configured.".FormatInvariant(jobFactoryType), e);
                    throw initException;
                }
            }

            IInstanceIdGenerator instanceIdGenerator = null;

            if (instanceIdGeneratorType != null)
            {
                try
                {
                    instanceIdGenerator = ObjectUtils.InstantiateType <IInstanceIdGenerator>(instanceIdGeneratorType);
                }
                catch (Exception e)
                {
                    throw new SchedulerConfigException("Unable to Instantiate InstanceIdGenerator: {0}".FormatInvariant(e.Message), e);
                }
                tProps = cfg.GetPropertyGroup(PropertySchedulerInstanceIdGeneratorPrefix, true);
                try
                {
                    ObjectUtils.SetObjectProperties(instanceIdGenerator, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("InstanceIdGenerator of type '{0}' props could not be configured.".FormatInvariant(instanceIdGeneratorType), e);
                    throw initException;
                }
            }

            // Get ThreadPool Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            var threadPoolTypeString = cfg.GetStringProperty(PropertyThreadPoolType).NullSafeTrim();

            if (threadPoolTypeString != null &&
                threadPoolTypeString.NullSafeTrim().StartsWith("Quartz.Simpl.SimpleThreadPool", StringComparison.OrdinalIgnoreCase))
            {
                // default to use as synonym for now
                threadPoolTypeString = typeof(DefaultThreadPool).AssemblyQualifiedNameWithoutVersion();
            }

            Type tpType = loadHelper.LoadType(threadPoolTypeString) ?? typeof(DefaultThreadPool);

            try
            {
                tp = ObjectUtils.InstantiateType <IThreadPool>(tpType);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("ThreadPool type '{0}' could not be instantiated.".FormatInvariant(tpType), e);
                throw initException;
            }
            tProps = cfg.GetPropertyGroup(PropertyThreadPoolPrefix, true);
            try
            {
                ObjectUtils.SetObjectProperties(tp, tProps);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("ThreadPool type '{0}' props could not be configured.".FormatInvariant(tpType), e);
                throw initException;
            }

            // Set up any DataSources
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IList <string> dsNames = cfg.GetPropertyGroups(PropertyDataSourcePrefix);

            foreach (string dataSourceName in dsNames)
            {
                string datasourceKey = "{0}.{1}".FormatInvariant(PropertyDataSourcePrefix, dataSourceName);
                NameValueCollection propertyGroup = cfg.GetPropertyGroup(datasourceKey, true);
                PropertiesParser    pp            = new PropertiesParser(propertyGroup);

                Type cpType = loadHelper.LoadType(pp.GetStringProperty(PropertyDbProviderType, null));

                // custom connectionProvider...
                if (cpType != null)
                {
                    IDbProvider cp;
                    try
                    {
                        cp = ObjectUtils.InstantiateType <IDbProvider>(cpType);
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("ConnectionProvider of type '{0}' could not be instantiated.".FormatInvariant(cpType), e);
                        throw initException;
                    }

                    try
                    {
                        // remove the type name, so it isn't attempted to be set
                        pp.UnderlyingProperties.Remove(PropertyDbProviderType);

                        ObjectUtils.SetObjectProperties(cp, pp.UnderlyingProperties);
                        cp.Initialize();
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("ConnectionProvider type '{0}' props could not be configured.".FormatInvariant(cpType), e);
                        throw initException;
                    }

                    dbMgr = DBConnectionManager.Instance;
                    dbMgr.AddConnectionProvider(dataSourceName, cp);
                }
                else
                {
                    string dsProvider             = pp.GetStringProperty(PropertyDataSourceProvider, null);
                    string dsConnectionString     = pp.GetStringProperty(PropertyDataSourceConnectionString, null);
                    string dsConnectionStringName = pp.GetStringProperty(PropertyDataSourceConnectionStringName, null);

                    if (dsConnectionString == null && !string.IsNullOrEmpty(dsConnectionStringName))
                    {
                        ConnectionStringSettings connectionStringSettings = ConfigurationManager.ConnectionStrings[dsConnectionStringName];
                        if (connectionStringSettings == null)
                        {
                            initException = new SchedulerException("Named connection string '{0}' not found for DataSource: {1}".FormatInvariant(dsConnectionStringName, dataSourceName));
                            throw initException;
                        }
                        dsConnectionString = connectionStringSettings.ConnectionString;
                    }

                    if (dsProvider == null)
                    {
                        initException = new SchedulerException("Provider not specified for DataSource: {0}".FormatInvariant(dataSourceName));
                        throw initException;
                    }
                    if (dsConnectionString == null)
                    {
                        initException = new SchedulerException("Connection string not specified for DataSource: {0}".FormatInvariant(dataSourceName));
                        throw initException;
                    }
                    try
                    {
                        DbProvider dbp = new DbProvider(dsProvider, dsConnectionString);
                        dbp.Initialize();

                        dbMgr = DBConnectionManager.Instance;
                        dbMgr.AddConnectionProvider(dataSourceName, dbp);
                    }
                    catch (Exception exception)
                    {
                        initException = new SchedulerException("Could not Initialize DataSource: {0}".FormatInvariant(dataSourceName), exception);
                        throw initException;
                    }
                }
            }

            // Get JobStore Properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            Type jsType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreType));

            try
            {
                js = ObjectUtils.InstantiateType <IJobStore>(jsType ?? typeof(RAMJobStore));
            }
            catch (Exception e)
            {
                initException = new SchedulerException("JobStore of type '{0}' could not be instantiated.".FormatInvariant(jsType), e);
                throw initException;
            }

            // Get object serializer properties
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IObjectSerializer objectSerializer     = null;
            string            serializerTypeKey    = "quartz.serializer.type";
            string            objectSerializerType = cfg.GetStringProperty(serializerTypeKey);

            if (objectSerializerType != null)
            {
                // some aliases
                if (objectSerializerType.Equals("json", StringComparison.OrdinalIgnoreCase))
                {
                    objectSerializerType = "Quartz.Simpl.JsonObjectSerializer, Quartz.Serialization.Json";
                }
                if (objectSerializerType.Equals("binary", StringComparison.OrdinalIgnoreCase))
                {
                    objectSerializerType = typeof(BinaryObjectSerializer).AssemblyQualifiedNameWithoutVersion();
                }

                tProps = cfg.GetPropertyGroup(PropertyObjectSerializer, true);
                try
                {
                    objectSerializer = ObjectUtils.InstantiateType <IObjectSerializer>(loadHelper.LoadType(objectSerializerType));
                    log.Info("Using object serializer: " + objectSerializerType);

                    ObjectUtils.SetObjectProperties(objectSerializer, tProps);

                    objectSerializer.Initialize();
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Object serializer type '" + objectSerializerType + "' could not be instantiated.", e);
                    throw initException;
                }
            }
            else if (js.GetType() != typeof(RAMJobStore))
            {
                // when we know for sure that job store does not need serialization we can be a bit more relaxed
                // otherwise it's an error to not define the serialization strategy
                initException = new SchedulerException($"You must define object serializer using configuration key '{serializerTypeKey}' when using other than RAMJobStore. " +
                                                       "Out of the box supported values are 'json' and 'binary'. JSON doesn't suffer from versioning as much as binary serialization but you cannot use it if you already have binary serialized data.");
                throw initException;
            }

            SchedulerDetailsSetter.SetDetails(js, schedName, schedInstId);

            tProps = cfg.GetPropertyGroup(PropertyJobStorePrefix, true, new[] { PropertyJobStoreLockHandlerPrefix });

            try
            {
                ObjectUtils.SetObjectProperties(js, tProps);
            }
            catch (Exception e)
            {
                initException = new SchedulerException("JobStore type '{0}' props could not be configured.".FormatInvariant(jsType), e);
                throw initException;
            }

            JobStoreSupport jobStoreSupport = js as JobStoreSupport;

            if (jobStoreSupport != null)
            {
                // Install custom lock handler (Semaphore)
                Type lockHandlerType = loadHelper.LoadType(cfg.GetStringProperty(PropertyJobStoreLockHandlerType));
                if (lockHandlerType != null)
                {
                    try
                    {
                        ISemaphore      lockHandler;
                        ConstructorInfo cWithDbProvider = lockHandlerType.GetConstructor(new[] { typeof(DbProvider) });

                        if (cWithDbProvider != null)
                        {
                            // takes db provider
                            IDbProvider dbProvider = DBConnectionManager.Instance.GetDbProvider(jobStoreSupport.DataSource);
                            lockHandler = (ISemaphore)cWithDbProvider.Invoke(new object[] { dbProvider });
                        }
                        else
                        {
                            lockHandler = ObjectUtils.InstantiateType <ISemaphore>(lockHandlerType);
                        }

                        tProps = cfg.GetPropertyGroup(PropertyJobStoreLockHandlerPrefix, true);

                        // If this lock handler requires the table prefix, add it to its properties.
                        if (lockHandler is ITablePrefixAware)
                        {
                            tProps[PropertyTablePrefix]   = jobStoreSupport.TablePrefix;
                            tProps[PropertySchedulerName] = schedName;
                        }

                        try
                        {
                            ObjectUtils.SetObjectProperties(lockHandler, tProps);
                        }
                        catch (Exception e)
                        {
                            initException = new SchedulerException("JobStore LockHandler type '{0}' props could not be configured.".FormatInvariant(lockHandlerType), e);
                            throw initException;
                        }

                        jobStoreSupport.LockHandler = lockHandler;
                        Log.Info("Using custom data access locking (synchronization): " + lockHandlerType);
                    }
                    catch (Exception e)
                    {
                        initException = new SchedulerException("JobStore LockHandler type '{0}' could not be instantiated.".FormatInvariant(lockHandlerType), e);
                        throw initException;
                    }
                }
            }

            // Set up any SchedulerPlugins
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IList <string> pluginNames = cfg.GetPropertyGroups(PropertyPluginPrefix);

            ISchedulerPlugin[] plugins = new ISchedulerPlugin[pluginNames.Count];
            for (int i = 0; i < pluginNames.Count; i++)
            {
                NameValueCollection pp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyPluginPrefix, pluginNames[i]), true);

                string plugInType = pp[PropertyPluginType];

                if (plugInType == null)
                {
                    initException = new SchedulerException("SchedulerPlugin type not specified for plugin '{0}'".FormatInvariant(pluginNames[i]));
                    throw initException;
                }
                ISchedulerPlugin plugin;
                try
                {
                    plugin = ObjectUtils.InstantiateType <ISchedulerPlugin>(LoadType(plugInType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("SchedulerPlugin of type '{0}' could not be instantiated.".FormatInvariant(plugInType), e);
                    throw initException;
                }
                try
                {
                    ObjectUtils.SetObjectProperties(plugin, pp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobStore SchedulerPlugin '{0}' props could not be configured.".FormatInvariant(plugInType), e);
                    throw initException;
                }

                plugins[i] = plugin;
            }

            // Set up any JobListeners
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
            IList <string> jobListenerNames = cfg.GetPropertyGroups(PropertyJobListenerPrefix);

            IJobListener[] jobListeners = new IJobListener[jobListenerNames.Count];
            for (int i = 0; i < jobListenerNames.Count; i++)
            {
                NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyJobListenerPrefix, jobListenerNames[i]), true);

                string listenerType = lp[PropertyListenerType];

                if (listenerType == null)
                {
                    initException = new SchedulerException("JobListener type not specified for listener '{0}'".FormatInvariant(jobListenerNames[i]));
                    throw initException;
                }
                IJobListener listener;
                try
                {
                    listener = ObjectUtils.InstantiateType <IJobListener>(loadHelper.LoadType(listenerType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                try
                {
                    PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
                    if (nameProperty != null && nameProperty.CanWrite)
                    {
                        nameProperty.GetSetMethod().Invoke(listener, new object[] { jobListenerNames[i] });
                    }
                    ObjectUtils.SetObjectProperties(listener, lp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("JobListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                jobListeners[i] = listener;
            }

            // Set up any TriggerListeners
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            IList <string> triggerListenerNames = cfg.GetPropertyGroups(PropertyTriggerListenerPrefix);

            ITriggerListener[] triggerListeners = new ITriggerListener[triggerListenerNames.Count];
            for (int i = 0; i < triggerListenerNames.Count; i++)
            {
                NameValueCollection lp = cfg.GetPropertyGroup("{0}.{1}".FormatInvariant(PropertyTriggerListenerPrefix, triggerListenerNames[i]), true);

                string listenerType = lp[PropertyListenerType];

                if (listenerType == null)
                {
                    initException = new SchedulerException("TriggerListener type not specified for listener '{0}'".FormatInvariant(triggerListenerNames[i]));
                    throw initException;
                }
                ITriggerListener listener;
                try
                {
                    listener = ObjectUtils.InstantiateType <ITriggerListener>(loadHelper.LoadType(listenerType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("TriggerListener of type '{0}' could not be instantiated.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                try
                {
                    PropertyInfo nameProperty = listener.GetType().GetProperty("Name", BindingFlags.Public | BindingFlags.Instance);
                    if (nameProperty != null && nameProperty.CanWrite)
                    {
                        nameProperty.GetSetMethod().Invoke(listener, new object[] { triggerListenerNames[i] });
                    }
                    ObjectUtils.SetObjectProperties(listener, lp);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("TriggerListener '{0}' props could not be configured.".FormatInvariant(listenerType), e);
                    throw initException;
                }
                triggerListeners[i] = listener;
            }

            // Get exporter
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            string exporterType = cfg.GetStringProperty(PropertySchedulerExporterType, null);

            if (exporterType != null)
            {
                try
                {
                    exporter = ObjectUtils.InstantiateType <ISchedulerExporter>(loadHelper.LoadType(exporterType));
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Scheduler exporter of type '{0}' could not be instantiated.".FormatInvariant(exporterType), e);
                    throw initException;
                }

                tProps = cfg.GetPropertyGroup(PropertySchedulerExporterPrefix, true);

                try
                {
                    ObjectUtils.SetObjectProperties(exporter, tProps);
                }
                catch (Exception e)
                {
                    initException = new SchedulerException("Scheduler exporter type '{0}' props could not be configured.".FormatInvariant(exporterType), e);
                    throw initException;
                }
            }

            bool tpInited = false;
            bool qsInited = false;

            // Fire everything up
            // ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

            try
            {
                IJobRunShellFactory jrsf = new StdJobRunShellFactory();

                if (autoId)
                {
                    try
                    {
                        schedInstId = DefaultInstanceId;

                        if (js.Clustered)
                        {
                            schedInstId = await instanceIdGenerator.GenerateInstanceId().ConfigureAwait(false);
                        }
                    }
                    catch (Exception e)
                    {
                        Log.ErrorException("Couldn't generate instance Id!", e);
                        throw new InvalidOperationException("Cannot run without an instance id.");
                    }
                }

                jobStoreSupport = js as JobStoreSupport;
                if (jobStoreSupport != null)
                {
                    jobStoreSupport.DbRetryInterval  = dbFailureRetry;
                    jobStoreSupport.ObjectSerializer = objectSerializer;
                }

                QuartzSchedulerResources rsrcs = new QuartzSchedulerResources();
                rsrcs.Name                            = schedName;
                rsrcs.ThreadName                      = threadName;
                rsrcs.InstanceId                      = schedInstId;
                rsrcs.JobRunShellFactory              = jrsf;
                rsrcs.MakeSchedulerThreadDaemon       = makeSchedulerThreadDaemon;
                rsrcs.BatchTimeWindow                 = TimeSpan.FromMilliseconds(batchTimeWindow);
                rsrcs.MaxBatchSize                    = maxBatchSize;
                rsrcs.InterruptJobsOnShutdown         = interruptJobsOnShutdown;
                rsrcs.InterruptJobsOnShutdownWithWait = interruptJobsOnShutdownWithWait;
                rsrcs.SchedulerExporter               = exporter;

                SchedulerDetailsSetter.SetDetails(tp, schedName, schedInstId);

                rsrcs.ThreadPool = tp;

                tp.Initialize();
                tpInited = true;

                rsrcs.JobStore = js;

                // add plugins
                foreach (ISchedulerPlugin plugin in plugins)
                {
                    rsrcs.AddSchedulerPlugin(plugin);
                }

                qs       = new QuartzScheduler(rsrcs, idleWaitTime);
                qsInited = true;

                // Create Scheduler ref...
                IScheduler sched = Instantiate(rsrcs, qs);

                // set job factory if specified
                if (jobFactory != null)
                {
                    qs.JobFactory = jobFactory;
                }

                // Initialize plugins now that we have a Scheduler instance.
                for (int i = 0; i < plugins.Length; i++)
                {
                    await plugins[i].Initialize(pluginNames[i], sched).ConfigureAwait(false);
                }

                // add listeners
                foreach (IJobListener listener in jobListeners)
                {
                    qs.ListenerManager.AddJobListener(listener, EverythingMatcher <JobKey> .AllJobs());
                }
                foreach (ITriggerListener listener in triggerListeners)
                {
                    qs.ListenerManager.AddTriggerListener(listener, EverythingMatcher <TriggerKey> .AllTriggers());
                }

                // set scheduler context data...
                foreach (string key in schedCtxtProps)
                {
                    string val = schedCtxtProps.Get(key);
                    sched.Context.Put(key, val);
                }

                // fire up job store, and runshell factory

                js.InstanceId     = schedInstId;
                js.InstanceName   = schedName;
                js.ThreadPoolSize = tp.PoolSize;
                await js.Initialize(loadHelper, qs.SchedulerSignaler).ConfigureAwait(false);

                jrsf.Initialize(sched);
                qs.Initialize();

                Log.Info("Quartz scheduler '{0}' initialized".FormatInvariant(sched.SchedulerName));

                Log.Info("Quartz scheduler version: {0}".FormatInvariant(qs.Version));

                // prevents the repository from being garbage collected
                qs.AddNoGCObject(schedRep);
                // prevents the db manager from being garbage collected
                if (dbMgr != null)
                {
                    qs.AddNoGCObject(dbMgr);
                }

                schedRep.Bind(sched);

                return(sched);
            }
            catch (SchedulerException)
            {
                await ShutdownFromInstantiateException(tp, qs, tpInited, qsInited).ConfigureAwait(false);

                throw;
            }
            catch
            {
                await ShutdownFromInstantiateException(tp, qs, tpInited, qsInited).ConfigureAwait(false);

                throw;
            }
        }
コード例 #28
0
 /// <summary>
 /// Initializes a new instance of the <see cref="RoamingObjectStorageHelper"/> class,
 /// which can read and write data using the provided <see cref="IObjectSerializer"/>;
 /// if none is provided, a default Json serializer will be used.
 /// </summary>
 /// <param name="objectSerializer">The serializer to use.</param>
 public RoamingObjectStorageHelper(IObjectSerializer objectSerializer = null)
     : base(objectSerializer)
 {
     Settings = ApplicationData.Current.RoamingSettings;
     Folder   = ApplicationData.Current.RoamingFolder;
 }
コード例 #29
0
 public ObjectSerializer_Tests()
 {
     _serializer = GetRequiredService <IObjectSerializer>();
 }
コード例 #30
0
 public T GetDocument <T>(Guid id, IObjectSerializer objectSerializer)
 {
     return(GetDocument <T>(id, false, objectSerializer));
 }
コード例 #31
0
 /// <summary>
 /// Split to list<br />
 /// 分割为列表
 /// </summary>
 /// <typeparam name="TMiddle"></typeparam>
 /// <typeparam name="T"></typeparam>
 /// <param name="originalString"></param>
 /// <param name="serializer"></param>
 /// <param name="mapper"></param>
 /// <returns></returns>
 List <T> IFixedLengthSplitter.SplitToList <TMiddle, T>(string originalString, IObjectSerializer serializer, IGenericObjectMapper mapper)
 => ((IFixedLengthSplitter)this).Split <TMiddle, T>(originalString, serializer, mapper).ToList();
コード例 #32
0
 /// <summary>
 /// Using the specified serializer
 /// </summary>
 /// <param name="newSerializer">Formatter to use</param>
 public void WithSerializer(IObjectSerializer newSerializer)
 {
     this.currentConfiguration.Serializer = newSerializer;
 }
コード例 #33
0
ファイル: CouchDatabase.cs プロジェクト: kpisman/LoveSeat
 public T GetDocument <T>(Guid id, IObjectSerializer objectSerializer)
 {
     return(GetDocument <T>(id.ToString(), objectSerializer));
 }
 public AuthenticationEndpointMock(IObjectSerializer serializer)
 {
     _serializer = serializer ?? throw new ArgumentNullException(nameof(serializer));
 }
コード例 #35
0
 public void WithSerializer(IObjectSerializer newSerializer)
 {
 }
コード例 #36
0
 public HackerNewsProxy(HttpClient httpClient, IObjectSerializer objectSerializer) : base(httpClient, objectSerializer)
 {
     _httpClient = httpClient;
 }
コード例 #37
0
ファイル: CookieBasedSessions.cs プロジェクト: rspacjer/Nancy
 /// <summary>
 /// Initializes a new instance of the <see cref="CookieBasedSessions"/> class.
 /// </summary>
 /// <param name="encryptionProvider">The encryption provider.</param>
 /// <param name="hmacProvider">The hmac provider</param>
 /// <param name="objectSerializer">Session object serializer to use</param>
 public CookieBasedSessions(IEncryptionProvider encryptionProvider, IHmacProvider hmacProvider, IObjectSerializer objectSerializer)
 {
     this.encryptionProvider = encryptionProvider;
     this.hmacProvider = hmacProvider;
     this.serializer = objectSerializer;
 }
コード例 #38
0
        private static IMessageQueryProvider CreateSqlProvider(Dialect dialect, DbProviderFactory factory, IObjectSerializer serializer)
        {
            switch (dialect)
            {
            case Dialect.Auto:
                var provider = CreateSqlProviderByFactory(factory, serializer);
                if (provider == null)
                {
                    throw new NotImplementedException($"The sql provider for factory {factory} is not implemented yet.");
                }
                return(provider);

            case Dialect.MySql:
                return(new MySqlQueryProvider(serializer));

            case Dialect.SqlServer:
                return(new SqlServerQueryProvider(serializer));

            case Dialect.Sqlite:
                return(new SqliteQueryProvider(serializer));

            default:
                throw new NotImplementedException($"The sql provider {dialect} is not implemented yet.");
            }
        }
コード例 #39
0
ファイル: SettingsManager.cs プロジェクト: zarix908/di
 public SettingsManager(IObjectSerializer serializer, IBlobStorage storage)
 {
     this.serializer = serializer;
     this.storage    = storage;
 }
コード例 #40
0
        internal ObjectBTreeFileEnumerator(ObjectBTreeFile File, IRecordHandler RecordHandler, IObjectSerializer DefaultSerializer)
        {
            this.file = File;
            this.currentBlockIndex   = 0;
            this.currentBlock        = null;
            this.currentReader       = null;
            this.currentHeader       = null;
            this.blockUpdateCounter  = File.BlockUpdateCounter;
            this.locked              = false;
            this.recordHandler       = RecordHandler;
            this.startingPoint       = null;
            this.defaultSerializer   = DefaultSerializer;
            this.timeoutMilliseconds = this.file.TimeoutMilliseconds;

            this.Reset();

            if (this.defaultSerializer is null && typeof(T) != typeof(object))
            {
                this.defaultSerializer = this.file.Provider.GetObjectSerializer(typeof(T));
            }
        }
コード例 #41
0
ファイル: EventStore.cs プロジェクト: pretystart/apworks-core
 protected EventStore(IObjectSerializer payloadSerializer)
 {
     this.payloadSerializer = payloadSerializer;
 }
コード例 #42
0
        public static async Task <StreamSocketConnection> ConnectAsync(Guid serviceUuid, IObjectSerializer serializer)
        {
            // Find all paired instances of the Rfcomm service
            var serviceId      = RfcommServiceId.FromUuid(serviceUuid);
            var deviceSelector = RfcommDeviceService.GetDeviceSelector(serviceId);
            var devices        = await DeviceInformation.FindAllAsync(deviceSelector);

            if (devices.Count > 0)
            {
                var device = devices.First(); // TODO

                var deviceService = await RfcommDeviceService.FromIdAsync(device.Id);

                if (deviceService == null)
                {
                    // Access to the device is denied because the application was not granted access
                    return(null);
                }

                var attributes = await deviceService.GetSdpRawAttributesAsync();

                IBuffer serviceNameAttributeBuffer;

                if (!attributes.TryGetValue(SdpServiceNameAttributeId, out serviceNameAttributeBuffer))
                {
                    // The service is not advertising the Service Name attribute (attribute id = 0x100).
                    // Please verify that you are running a BluetoothConnectionListener.
                    return(null);
                }

                using (var attributeReader = DataReader.FromBuffer(serviceNameAttributeBuffer))
                {
                    var attributeType = attributeReader.ReadByte();

                    if (attributeType != SdpServiceNameAttributeType)
                    {
                        // The service is using an unexpected format for the Service Name attribute.
                        // Please verify that you are running a BluetoothConnectionListener.
                        return(null);
                    }

                    var serviceNameLength = attributeReader.ReadByte();

                    // The Service Name attribute requires UTF-8 encoding.
                    attributeReader.UnicodeEncoding = UnicodeEncoding.Utf8;
                    var serviceName = attributeReader.ReadString(serviceNameLength);

                    var socket = new StreamSocket();
                    await socket.ConnectAsync(deviceService.ConnectionHostName, deviceService.ConnectionServiceName);

                    var connection = await StreamSocketConnection.ConnectAsync(socket, serializer);

                    return(connection);
                }
            }

            // No devices found
            return(null);
        }
コード例 #43
0
 private void ValidateAndInit()
 {
     this.serializer    = serializer ?? new JsonObjectSerializer();
     this.queryProvider = CreateSqlProvider(this.dialect, this.factory, this.serializer);
 }
コード例 #44
0
 /// <summary>
 /// Split<br />
 /// 分割
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="originalString"></param>
 /// <param name="serializer"></param>
 /// <returns></returns>
 IEnumerable <T> ISplitter.Split <T>(string originalString, IObjectSerializer serializer)
 => InternalSplitToEnumerable(originalString, serializer.Deserialize <T>);
コード例 #45
0
        static IMessageQueryProvider CreateSqlProviderByFactory(DbProviderFactory factory, IObjectSerializer serializer)
        {
            var name = factory.GetType().Name.ToLowerInvariant();

            if (name.Contains("mysql"))
            {
                return(new MySqlQueryProvider(serializer));
            }
            if (name.Contains("sqlite"))
            {
                return(new SqliteQueryProvider(serializer));
            }
            if (name.Contains("sqlclient"))
            {
                return(new SqlServerQueryProvider(serializer));
            }
            return(null);
        }
コード例 #46
0
 /// <summary>
 /// Split<br />
 /// 分割
 /// </summary>
 /// <typeparam name="TMiddle"></typeparam>
 /// <typeparam name="T"></typeparam>
 /// <param name="originalString"></param>
 /// <param name="serializer"></param>
 /// <param name="mapper"></param>
 /// <returns></returns>
 IEnumerable <T> ISplitter.Split <TMiddle, T>(string originalString, IObjectSerializer serializer, IGenericObjectMapper mapper)
 => InternalSplitToEnumerable(originalString, s => mapper.MapTo <TMiddle, T>(serializer.Deserialize <TMiddle>(s)));
コード例 #47
0
 public ViewResult(HttpWebResponse response, HttpWebRequest request, IObjectSerializer objectSerializer)
     : base(response, request)
 {
     this.objectSerializer = objectSerializer;
 }
コード例 #48
0
 public EdrsCommunicator(IObjectSerializer objectSerializer)
 {
     _objectSerializer = objectSerializer;
     RequestSender = new RequestSender();
 }
コード例 #49
0
 public CustomInteractiveDiagnosticsHookFixture()
 {
     this.cryptoConfig     = CryptographyConfiguration.Default;
     this.objectSerializer = new DefaultObjectSerializer();
 }
 public void SetUp()
 {
     _subject = new ObjectSerializer();
 }
コード例 #51
0
ファイル: ValueElement.cs プロジェクト: loning/LibraTalk
 public ValueElement(Type objectType, IObjectSerializer objectSerializer)
 {
     ObjectType       = objectType;
     ObjectSerializer = objectSerializer;
 }
コード例 #52
0
 public CustomInteractiveDiagnosticsHookFixture()
 {
     this.cryptoConfig = CryptographyConfiguration.Default;
     this.objectSerializer = new DefaultObjectSerializer();
 }
コード例 #53
0
 /// <summary>
 /// Split to list<br />
 /// 分割为列表
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="originalString"></param>
 /// <param name="serializer"></param>
 /// <returns></returns>
 List <T> ISplitter.SplitToList <T>(string originalString, IObjectSerializer serializer)
 => ((ISplitter)this).Split <T>(originalString, serializer).ToList();
コード例 #54
0
ファイル: FileSerializer.cs プロジェクト: macieja79/budget
 public FileSerializer(IObjectSerializer <T> serializer)
 {
     _serializer = serializer;
 }
コード例 #55
0
 /// <summary>
 /// Split to array
 /// </summary>
 /// <typeparam name="T"></typeparam>
 /// <param name="originalString"></param>
 /// <param name="serializer"></param>
 /// <returns></returns>
 T[] ISplitter.SplitToArray <T>(string originalString, IObjectSerializer serializer)
 => ((ISplitter)this).Split <T>(originalString, serializer).ToArray();
コード例 #56
0
 /// <summary>
 /// Split to array
 /// </summary>
 /// <typeparam name="TMiddle"></typeparam>
 /// <typeparam name="T"></typeparam>
 /// <param name="originalString"></param>
 /// <param name="serializer"></param>
 /// <param name="mapper"></param>
 /// <returns></returns>
 T[] ISplitter.SplitToArray <TMiddle, T>(string originalString, IObjectSerializer serializer, IGenericObjectMapper mapper)
 => ((ISplitter)this).Split <TMiddle, T>(originalString, serializer, mapper).ToArray();
コード例 #57
0
ファイル: CsrfStartup.cs プロジェクト: rodrigoi/Nancy
 public CsrfStartup(CryptographyConfiguration cryptographyConfiguration, IObjectSerializer objectSerializer, ICsrfTokenValidator tokenValidator)
 {
     CryptographyConfiguration = cryptographyConfiguration;
     ObjectSerializer = objectSerializer;
     TokenValidator = tokenValidator;
 }
コード例 #58
0
ファイル: CookieBasedSessions.cs プロジェクト: rspacjer/Nancy
 /// <summary>
 /// Using the specified serializer
 /// </summary>
 /// <param name="newSerializer">Formatter to use</param>
 public void WithSerializer(IObjectSerializer newSerializer)
 {
     this.serializer = newSerializer;
 }
コード例 #59
0
ファイル: StdAdoDelegateTest.cs プロジェクト: zzhi/JobEngine
 public StdAdoDelegateTest(Type serializerType)
 {
     serializer = (IObjectSerializer)Activator.CreateInstance(serializerType);
     serializer.Initialize();
 }
コード例 #60
0
 public Neo4jPersistenceProvider(IGraphClient graphClient, IObjectSerializer objectSerializer)
 {
     this.graphClient = graphClient;
     this.objectSerializer = objectSerializer;
 }