Esempio n. 1
0
        public static Compilation Build(string code,
                                        IPersistentStorage storage = null,
                                        List <string> errors       = null,
                                        bool generateJSFiles       = false)
        {
            var analysis = generateJSFiles
                ? new CompilationAnalysisBase <SyntaxToken, SyntaxNode, SemanticModel>()
                : null;

            var compilation = createCompilation(code,
                                                storage: storage ?? (generateJSFiles
                    ? new MockStorage()
                    : null),
                                                analysis: analysis);

            if (generateJSFiles)
            {
                var environment = compilation.Scope.get <ICompilerEnvironment>();
                Assert.IsNotNull(environment);

                environment.setting("servicePath", "");
            }

            if (compilation.build() == null && errors != null)
            {
                foreach (var error in compilation.errors())
                {
                    errors.Add(error.ToString());
                }
            }

            return(compilation);
        }
Esempio n. 2
0
        private static Compilation createCompilation(string text,
                                                     List <Diagnostic> errors     = null,
                                                     IPersistentStorage storage   = null,
                                                     CompilationAnalysis analysis = null)
        {
            var injector = new CompositeInjector <SyntaxToken, SyntaxNode, SemanticModel>(new[]
            {
                new DelegateInjector <SyntaxToken, SyntaxNode, SemanticModel>(compiler => compiler
                                                                              .Environment()
                                                                              .dependency <ExcessOwinMiddleware>("Excess.Server.Middleware")
                                                                              .dependency <IAppBuilder>("Owin")
                                                                              .dependency <IOwinRequest>("Microsoft.Owin")
                                                                              .dependency <__Scope>("Excess.Runtime")),

                new DelegateInjector <SyntaxToken, SyntaxNode, SemanticModel>(
                    compiler => ConcurrentExtension.Apply((RoslynCompiler)compiler)),

                new DelegateInjector <SyntaxToken, SyntaxNode, SemanticModel>(
                    compiler => ServerExtension.Apply(compiler, new Scope(null))),

                new DelegateInjector <SyntaxToken, SyntaxNode, SemanticModel>(
                    compiler => Functions.Apply(compiler))
            });

            if (analysis != null)
            {
                ServerExtension.Compilation(analysis);
            }

            var compilation = new Compilation(storage, analysis: analysis);

            compilation.addDocument("test", text, injector);
            return(compilation);
        }
 public PostingListBinaryWriter(IPersistentStorage storage)
 {
     this.persistentStorage = storage;
     this.buffer            = new int[MemoryBufferSize];
     this.flushBuffer       = new byte[GroupVarint.GetMaxEncodedSize(MemoryBufferSize)];
     this.bufferIndex       = 0;
 }
        public AzureMonitorTransmitter(AzureMonitorExporterOptions options)
        {
            if (options == null)
            {
                throw new ArgumentNullException(nameof(options));
            }

            options.Retry.MaxRetries = 0;
            ConnectionString.ConnectionStringParser.GetValues(options.ConnectionString, out _instrumentationKey, out string ingestionEndpoint);
            _applicationInsightsRestClient = new ApplicationInsightsRestClient(new ClientDiagnostics(options), HttpPipelineBuilder.Build(options), host: ingestionEndpoint);

            if (!options.DisableOfflineStorage)
            {
                try
                {
                    _storage = new FileStorage(options.StorageDirectory);
                }
                catch (Exception)
                {
                    // TODO:
                    // log exception
                    // Remove this when we add an option to disable offline storage.
                    // So if someone opts in for storage and we cannot initialize, we can throw.
                    // Change needed on persistent storage side to throw if not able to create storage directory.
                }
            }
        }
            public NodeManager(IPersistentStorage persistentStorage, IFixedSizeDataSerializer <TKey> keySerializer, IFixedSizeDataSerializer <TValue> valueSerializer)
            {
                if (persistentStorage == null)
                {
                    throw new ArgumentNullException(nameof(persistentStorage));
                }

                if (keySerializer == null)
                {
                    throw new ArgumentNullException(nameof(keySerializer));
                }

                if (valueSerializer == null)
                {
                    throw new ArgumentNullException(nameof(valueSerializer));
                }

                this.syncRoot          = new object();
                this.Header            = new Header();
                this.persistentStorage = persistentStorage;
                this.keySerializer     = keySerializer;
                this.valueSerializer   = valueSerializer;

                if (persistentStorage.Length == 0)
                {
                    Header.SaveHeader(persistentStorage);
                }
                else
                {
                    Header.ReadHeader(persistentStorage);
                }
            }
Esempio n. 6
0
 public CommandHandler(IUnifiedMediator mediator, IFlickrClient flickrClient, IAuthCodeProvider authCodeProvider, IPersistentStorage persistentStorage)
 {
     _mediator          = mediator;
     _flickrClient      = flickrClient;
     _authCodeProvider  = authCodeProvider;
     _persistentStorage = persistentStorage;
 }
Esempio n. 7
0
 public TransactionEventInvoker(
     IPersistentStorage persistentStorage,
     ITypeConverter typeConverter)
 {
     _persistentStorage = persistentStorage;
     _typeConverter     = typeConverter;
 }
		public AnalyticsManager(INotificationManager notificationManager, IEnvironmentInformation environmentInformation, IPersistentStorage persistentStorage, IRegistrationController registrationController)
		{
			_notificationManager = notificationManager;
			_environmentInformation = environmentInformation;
			_persistentStorage = persistentStorage;
			_registrationController = registrationController;
		}
Esempio n. 9
0
        public static IOccurrenceReader CreateReader(string readerType, IPersistentStorage storage)
        {
            if (readerType == PersistentIndexName.DefaultValue || readerType == PostingListWriter.Id)
            {
                return(new PostingListReader(storage));
            }

            if (readerType == PostingListBinaryWriter.Id)
            {
                return(new PostingListBinaryReader(storage));
            }

            if (readerType == PostingListBinaryDeltaWriter.Id)
            {
                return(new PostingListBinaryDeltaReader(storage));
            }

            if (readerType == PostingListVarIntDeltaWriter.Id)
            {
                return(new PostingListVarIntDeltaReader(storage));
            }

            if (readerType == PostingListPackedIntDeltaWriter.Id)
            {
                return(new PostingListPackedIntDeltaReader(storage));
            }

            throw new NotSupportedException($"Not supported Posting Type {readerType}");
        }
Esempio n. 10
0
 public ReaderEnumerator(IPersistentStorage storage, PostingListAddress address)
 {
     this.persistentStorage = storage;
     this.address           = address;
     this.buffer            = new byte[ReadBufferSize];
     Reset();
 }
Esempio n. 11
0
        private static Assembly buildServer(string text,
                                            List <Diagnostic> errors   = null,
                                            List <Type> configurations = null,
                                            IPersistentStorage storage = null)
        {
            var compilation = createCompilation(text, errors, storage);
            var assembly    = compilation.build();

            if (assembly == null)
            {
                if (errors != null)
                {
                    errors.AddRange(compilation.errors());
                }

                return(null);
            }

            foreach (var type in assembly.GetTypes())
            {
                if (type.BaseType != typeof(IConcurrentObject) && configurations != null)
                {
                    checkForConfiguration(type, configurations);
                }
            }

            return(assembly);
        }
Esempio n. 12
0
        public BaseRuntime(IPersistentStorage storage)
        {
            _compilation = new Compilation(storage);
            _compilation.ToolStarted += (sender, args) => notify(NotificationKind.System, "Starting tool: " + args.Tool.displayName + " for " + args.Document);
            _compilation.ToolFinished += (sender, args) =>
            {
                if (args.Result != null)
                {
                    bool hasError = args.Result.ContainsKey("error");
                    if (hasError)
                        notify(NotificationKind.Error, "Tool failed: " + args.Result["error"]);
                    else
                    {
                        foreach(var msg in args.Result)
                            notify(NotificationKind.System, msg.Key);
                    }
                }

                notify(NotificationKind.System, "Finished: " + args.Tool.displayName + " for " + args.Document);
            };

            foreach (var tool in _tools)
            {
                _compilation.registerTool(tool.Key, tool.Value);
            }

            _compilation.addCSharpFile("console", consoleTree);
            _compilation.addCSharpFile("random", randomTree);
        }
Esempio n. 13
0
        private static Compilation createCompilation(string text,
                                                     List <Diagnostic> errors   = null,
                                                     IPersistentStorage storage = null)
        {
            var injector = new CompositeInjector <SyntaxToken, SyntaxNode, SemanticModel>(new[]
            {
                new DelegateInjector <SyntaxToken, SyntaxNode, SemanticModel>(compiler => compiler
                                                                              .Environment()
                                                                              .dependency <ExcessOwinMiddleware>("Middleware")
                                                                              .dependency <IAppBuilder>("Owin")),

                new DelegateInjector <SyntaxToken, SyntaxNode, SemanticModel>(compiler => Excess
                                                                              .Extensions
                                                                              .Concurrent
                                                                              .ConcurrentExtension
                                                                              .Apply((RoslynCompiler)compiler)),

                new DelegateInjector <SyntaxToken, SyntaxNode, SemanticModel>(compiler => LanguageExtension
                                                                              .ServerExtension
                                                                              .Apply(compiler, new Scope(null)))
            });

            var compilation = new Compilation(storage);

            compilation.addDocument("test", text, injector);
            return(compilation);
        }
Esempio n. 14
0
        public BaseRuntime(IPersistentStorage storage)
        {
            _compilation               = new Compilation(storage);
            _compilation.ToolStarted  += (sender, args) => notify(NotificationKind.System, "Starting tool: " + args.Tool.displayName + " for " + args.Document);
            _compilation.ToolFinished += (sender, args) =>
            {
                if (args.Result != null)
                {
                    bool hasError = args.Result.ContainsKey("error");
                    if (hasError)
                    {
                        notify(NotificationKind.Error, "Tool failed: " + args.Result["error"]);
                    }
                    else
                    {
                        foreach (var msg in args.Result)
                        {
                            notify(NotificationKind.System, msg.Key);
                        }
                    }
                }

                notify(NotificationKind.System, "Finished: " + args.Tool.displayName + " for " + args.Document);
            };


            foreach (var tool in _tools)
            {
                _compilation.registerTool(tool.Key, tool.Value);
            }

            _compilation.addCSharpFile("console", consoleTree);
            _compilation.addCSharpFile("random", randomTree);
        }
 public TernaryDictionary(IPersistentStorage persistentStorage, IComparer <TKey> comparer)
 {
     this.comparer        = comparer;
     this.keySerializer   = (IFixedSizeDataSerializer <TKey>)DataSerializer.GetDefault <TKey>();
     this.valueSerializer = (IFixedSizeDataSerializer <TValue>)DataSerializer.GetDefault <TValue>();
     this.nodeManager     = new NodeManager(persistentStorage, keySerializer, valueSerializer);
 }
Esempio n. 16
0
 public TychaiaLevelAPIImpl(
     ITychaiaLevelFactory tychaiaLevelFactory,
     IPersistentStorage persistentStorage)
 {
     this.m_TychaiaLevelFactory = tychaiaLevelFactory;
     this.m_PersistentStorage = persistentStorage;
 }
        private bool TryCreatePersistentStorage(
            Solution solution,
            string workingFolderPath,
            out IPersistentStorage persistentStorage)
        {
            persistentStorage = null;

            var databaseFilePath = GetDatabaseFilePath(workingFolderPath);

            try
            {
                if (!TryOpenDatabase(solution, workingFolderPath, databaseFilePath, out persistentStorage))
                {
                    return(false);
                }

                return(true);
            }
            catch (Exception ex)
            {
                StorageDatabaseLogger.LogException(ex);

                if (ShouldDeleteDatabase(ex))
                {
                    // this was not a normal exception that we expected during DB open.
                    // Report this so we can try to address whatever is causing this.
                    FatalError.ReportWithoutCrash(ex);
                    IOUtilities.PerformIO(() => Directory.Delete(Path.GetDirectoryName(databaseFilePath), recursive: true));
                }

                return(false);
            }
        }
Esempio n. 18
0
 public LanguageProvider(IPersistentStorage storage, Random rand, ILogger logger)
 {
     _langCollection = storage.RestoreSingle <LanguageResourceCollection>(Collection, LangKey);
     _rand           = rand;
     _logger         = logger;
     AssertNotNull(_langCollection);
 }
        protected override bool TryOpenDatabase(
            Solution solution, string workingFolderPath, string databaseFilePath, out IPersistentStorage storage)
        {
            // try to get db ownership lock. if someone else already has the lock. it will throw
            var dbOwnershipLock = TryGetDatabaseOwnership(databaseFilePath);

            if (dbOwnershipLock == null)
            {
                storage = null;
                return(false);
            }

            SQLitePersistentStorage sqlStorage = null;

            try
            {
                sqlStorage = new SQLitePersistentStorage(
                    workingFolderPath, solution.FilePath, databaseFilePath, dbOwnershipLock, _faultInjectorOpt);

                sqlStorage.Initialize(solution);
            }
            catch (Exception)
            {
                sqlStorage?.Dispose();
                throw;
            }

            storage = sqlStorage;
            return(true);
        }
Esempio n. 20
0
 /// <summary>
 /// Quik interface in .NET constructor
 /// </summary>
 public Quik(int port = DefaultPort, IPersistentStorage storage = null)
 {
     if (storage == null)
     {
         Storage = new InMemoryStorage();
     }
     else
     {
         Storage = storage;
     }
     QuikService = QuikService.Create(port);
     // poor man's DI
     QuikService.Storage = Storage;
     Events                    = QuikService.Events;
     Debug                     = new DebugFunctions(port);
     Service                   = new ServiceFunctions(port);
     Class                     = new ClassFunctions(port);
     OrderBook                 = new OrderBookFunctions(port);
     Trading                   = new TradingFunctions(port);
     StopOrders                = new StopOrderFunctions(port, this);
     Orders                    = new OrderFunctions(port, this);
     Candles                   = new CandleFunctions(port);
     QuikService.Candles       = Candles;
     QuikService.StopOrders    = StopOrders;
     QuikService.WorkingFolder = Service.GetWorkingFolder().Result;
 }
Esempio n. 21
0
        private static async Task WriteToDependentSemanticVersionAsync(IPersistentStorage storage, Project project, CancellationToken cancellationToken)
        {
            var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);

            var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

            await WriteToVersionAsync(storage, DependentSemanticVersion, projectVersion, semanticVersion, cancellationToken).ConfigureAwait(false);
        }
Esempio n. 22
0
 public PersistentDictionaryTst(IPersistentStorage storage,
                                int maxTokenLength,
                                ITextEncoding encoding)
 {
     this.maxTokenByteLength = encoding.GetMaxEncodedLength(maxTokenLength);
     this.encoding           = encoding;
     this.dictionary         = new TernaryDictionary <byte, long>(storage);
 }
 public ReaderEnumerator(IPersistentStorage storage, long listStart, ulong firstValue)
 {
     this.persistentStorage = storage;
     this.listStart         = listStart;
     this.state             = 0;
     this.firstValue        = firstValue;
     this.buffer            = new byte[DeltaVarIntListWriter.BlockSize];
     Reset();
 }
 public ReaderEnumerator(IPersistentStorage storage, PostingListAddress address, Occurrence firstOccurrence)
 {
     this.persistentStorage = storage;
     this.address           = address;
     this.state             = 0;
     this.buffer            = new byte[PostingListVarIntDeltaWriter.BlockSize];
     this.firstOccurrence   = firstOccurrence;
     Reset();
 }
            public void ReadHeader(IPersistentStorage persistentStorage)
            {
                persistentStorage.ReadAll(0, headerData, 0, headerData.Length);

                if (Text != HeaderText)
                {
                    throw new InvalidOperationException("Header text mismatch");
                }
            }
Esempio n. 26
0
        protected virtual RoslynEnvironment createEnvironment(IPersistentStorage storage)
        {
            var result = new RoslynEnvironment(_scope, storage, null);

            result.dependency <object>(new[] { "System", "System.Collections" });
            result.dependency <Queue <object> >(new[] { "System.Collections.Generic" });
            result.dependency <Expression>(new[] { "System.Linq" });

            return(result);
        }
Esempio n. 27
0
        //init
        /// <summary>
        /// Initialize with another persistent storage that will actually insert entities and a dropOutChance between 0 and 1 to remove some portion on entities.
        /// </summary>
        /// <param name="persistentStorage"></param>
        /// <param name="dropOutChance"></param>
        public DropOutPersistentStorage(IPersistentStorage persistentStorage, double dropOutChance)
        {
            if (dropOutChance < 0 || 1 < dropOutChance)
            {
                throw new ArgumentOutOfRangeException(nameof(dropOutChance), "Range should be between 0 and 1");
            }

            _persistentStorage = persistentStorage;
            _dropOutChance     = dropOutChance;
        }
Esempio n. 28
0
 public PersistentList(IPersistentStorage persistentStorage)
 {
     this.serializer        = (IFixedSizeDataSerializer <TValue>)DataSerializer.GetDefault <TValue>();
     this.persistentStorage = persistentStorage;
     this.headerSize        = sizeof(long);
     this.recordSize        = serializer.Size;
     this.buffer            = new byte[recordSize * 1000];
     this.bufferFileOffset  = long.MinValue;
     this.bufferDataSize    = 0;
 }
Esempio n. 29
0
 public ReaderEnumerator(IPersistentStorage storage, PostingListAddress address)
 {
     this.persistentStorage = storage;
     this.address           = address;
     this.buffer            = new byte[ReadBufferSize];
     this.selectors         = new int[4];
     this.data      = null;
     this.dataIndex = 0;
     Reset();
 }
Esempio n. 30
0
        private Task <bool> WriteStreamAsync(IPersistentStorage storage, object documentOrProject, string key, Stream stream, CancellationToken cancellationToken)
        {
            if (documentOrProject is Document document)
            {
                return(storage.WriteStreamAsync(document, key, stream, cancellationToken));
            }

            var project = (Project)documentOrProject;

            return(storage.WriteStreamAsync(project, key, stream, cancellationToken));
        }
Esempio n. 31
0
 public TransactionManager(
     IQuik quik,
     IIdProvider idProvider,
     IPersistentStorage persistentStorage,
     ILogger <TransactionManager> logger)
 {
     _quik              = quik;
     _idProvider        = idProvider;
     _persistentStorage = persistentStorage;
     _logger            = logger;
 }
Esempio n. 32
0
        private Task <Stream> ReadStreamAsync(IPersistentStorage storage, string key, object documentOrProject, CancellationToken cancellationToken)
        {
            if (documentOrProject is Document document)
            {
                return(storage.ReadStreamAsync(document, key, cancellationToken));
            }

            var project = (Project)documentOrProject;

            return(storage.ReadStreamAsync(project, key, cancellationToken));
        }
Esempio n. 33
0
        private Task<bool> WriteStreamAsync(IPersistentStorage storage, object documentOrProject, string key, Stream stream, CancellationToken cancellationToken)
        {
            var document = documentOrProject as Document;
            if (document != null)
            {
                return storage.WriteStreamAsync(document, key, stream, cancellationToken);
            }

            var project = (Project)documentOrProject;
            return storage.WriteStreamAsync(project, key, stream, cancellationToken);
        }
Esempio n. 34
0
        public BackupController(CancellationToken cancel, IBackupManager backupmgr, INameService namesvc, IPersistentStorage pstore, ITaskQueue taskqueue)
        {
            this.m_backupmgr = backupmgr;
            this.m_cancel    = cancel;
            this.m_dmc       = Global.CloudStorage as DynamicMemoryCloud;
            this.m_namesvc   = namesvc;
            this.m_pstore    = pstore;
            this.m_taskqueue = taskqueue;

            m_backupmgr.RequestPartitionBackup  += OnBackupManagerRequestBackup;
            m_backupmgr.RequestPartitionRestore += OnBackupManagerRequestRestore;
        }
Esempio n. 35
0
 public TychaiaProfilerEntity(
     TychaiaProfiler profiler,
     I2DRenderUtilities twodRenderUtilities,
     IAssetManagerProvider assetManagerProvider,
     IPersistentStorage persistentStorage)
 {
     this.Profiler = profiler;
     this.m_2DRenderUtilities = twodRenderUtilities;
     this.m_DefaultFontAsset = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
     this.m_ProfilingInformation = new List<FrameProfileInfo>();
     this.m_PersistentStorage = persistentStorage;
     this.m_TychaiaProfilerEntityUtil = new TychaiaProfilerEntityUtil();
 }
Esempio n. 36
0
        public static void Startup()
        {
            SnapInContext.Instance.AuthTokenManager = new AuthTokenManager();
            var filePath = Path.Combine(SnapInContext.Instance.ApplicationPath, Constants.LocalStorageFileName);
            _store = new LocalFileStorage(filePath);
            SnapInContext.Instance.AuthTokenManager.CacheAuthTokens(_store.Load());

            var httpTransportFilePath = Path.Combine(SnapInContext.Instance.ApplicationPath, Constants.HttpTransportLocalStorageFileName);
            _httpTransportStore = new HttpTransportLocalFileStorage(httpTransportFilePath);

            var httpData = _httpTransportStore.Load();
            var service = SnapInContext.Instance.ServiceGateway;
            service.HttpTransport.SetAll(httpData);
        }
Esempio n. 37
0
        public IRuntimeProject createRuntime(string projectType, string projectName, dynamic config, dynamic path, IPersistentStorage storage)
        {
            var result = null as IRuntimeProject;
            switch (projectType)
            {
                case "console": result = new ConsoleRuntime(storage); break;
                case "extension": result = new ExtensionRuntime(storage); break;
                case "concurrent": result = new ConcurrentRuntime(storage); break;
            }

            if (result == null)
                throw new InvalidOperationException("Invalid project type " + projectType);

            result.setFilePath(path);
            return result;
        }
Esempio n. 38
0
 /// <summary>
 /// Quik interface in .NET constructor
 /// </summary>
 public Quik(int port = DefaultPort, IPersistentStorage storage = null) {
     if (storage == null) { Storage = new EsentStorage(); } else { Storage = storage; }
     QuikService = QuikService.Create(port);
     // poor man's DI
     QuikService.Storage = Storage;
     Events = QuikService.Events;
     Debug = new DebugFunctions(port);
     Service = new ServiceFunctions(port);
     Class = new ClassFunctions(port);
     OrderBook = new OrderBookFunctions(port);
     Trading = new TradingFunctions(port);
     StopOrders = new StopOrderFunctions(port, this);
     Orders = new OrderFunctions(port, this);
     Candles = new CandleFunctions(port);
     QuikService.Candles = Candles;
     QuikService.StopOrders = StopOrders;
 }
 public void Init(IPersistentStorage storage)
 {
     _storage = storage;
 }
Esempio n. 40
0
        protected virtual RoslynEnvironment createEnvironment(IPersistentStorage storage)
        {
            var result = new RoslynEnvironment(_scope, storage);
            result.dependency<object>(new[] { "System", "System.Collections", "System.Collections.Generic" });
            result.dependency<IEnumerable<object>>(new[] { "System.Collections", "System.Collections.Generic" });

            return result;
        }
 /**
 * This is an example of a bad constructor. We have a hard dependency on a concrete implementation,
 * resulting in tight coupling and no flexibility to swap out implementations. We may decide
 * we don't want to write to a database in future, requiring this class to be altered. It also
 * makes this class difficult to test, requiring a functional database to do so.
 */
 private MessageWriter()
 {
     _storage = new DatabasePersistentStorage();
 }
Esempio n. 42
0
 public ConsoleRuntime(IPersistentStorage storage)
     : base(storage)
 {
 }
Esempio n. 43
0
 public ConcurrentRuntime(IPersistentStorage storage) : base(storage) { }
        private static async Task WriteToDependentSemanticVersionAsync(IPersistentStorage storage, Project project, CancellationToken cancellationToken)
        {
            var projectVersion = await project.GetDependentVersionAsync(cancellationToken).ConfigureAwait(false);
            var semanticVersion = await project.GetDependentSemanticVersionAsync(cancellationToken).ConfigureAwait(false);

            await WriteToVersionAsync(storage, DependentSemanticVersion, projectVersion, semanticVersion, cancellationToken).ConfigureAwait(false);
        }
		public DonkyClientDataContext(IPersistentStorage storage, ILogger logger) : base(storage, logger)
		{
		}
		internal ServiceContext(IPersistentStorage storage)
			: base(storage)
		{
			PublicServiceBaseUrl = "https://client-api.mobiledonky.com/";
		}
		public RichDataContext(IPersistentStorage storage, ILogger logger) : base(storage, logger)
		{
		}
Esempio n. 48
0
 public NameCommand(INetworkAPIProvider networkAPIProvider, IPersistentStorage persistentStorage)
 {
     this.m_NetworkAPIProvider = networkAPIProvider;
     this.m_PersistentStorage = persistentStorage;
 }
Esempio n. 49
0
        private Task<Stream> ReadStreamAsync(IPersistentStorage storage, string key, object documentOrProject, CancellationToken cancellationToken)
        {
            var document = documentOrProject as Document;
            if (document != null)
            {
                return storage.ReadStreamAsync(document, key, cancellationToken);
            }

            var project = (Project)documentOrProject;
            return storage.ReadStreamAsync(project, key, cancellationToken);
        }
Esempio n. 50
0
        /// <summary>
        /// Initialize ClientTracker instance
        /// </summary>
        /// <param name="collectorUrl">required, set from config</param>
        /// <param name="sharedSecretKey">required, set from config</param>
        /// <param name="deviceId">required</param>
        /// <param name="clientId">required</param>
        /// <param name="systemVersion">required</param>
        /// <param name="productVersion"></param>
        /// <param name="system"></param>
        /// <param name="productGitHash"></param>
        /// <param name="queueSize">default: 20</param>
        /// <param name="queueRetentionMinutes">default: 1440 (minutes = 24 hours)</param>
        public ClientTracker(
            string collectorUrl,
            string sharedSecretKey,
            string deviceId,
            string clientId,
            string systemVersion,
            string productVersion,
            string system,
            string productGitHash,
            int queueSize,
            int queueRetentionMinutes,
            IPersistentStorage persistentStorage,
            IEventPublisher eventPublisher,
            IIpResolver ipResolver
            )
        {
            collectorUrl.Check(s => !string.IsNullOrWhiteSpace(s), "collectorUrl");
            sharedSecretKey.Check(s => !string.IsNullOrWhiteSpace(s), "sharedSecretKey");
            deviceId.Check(s => !string.IsNullOrWhiteSpace(s), "deviceId");
            clientId.Check(s => !string.IsNullOrWhiteSpace(s), "clientId");
            systemVersion.Check(s => !string.IsNullOrWhiteSpace(s), "systemVersion");

            this._collectorUrl = collectorUrl;

            this._sharedSecretKey = sharedSecretKey;

            this._deviceIdHash = HashUtil.HashSha256ToString(StringEncoding.GetBytes(deviceId));

            this._clientId = clientId;

            this._systemVersion = systemVersion;

            this._productVersion = productVersion;

            this._system = system;

            this._productGitHash = productGitHash;

            this._queueSize = Math.Max(0, queueSize);

            this._queueRetentionMinutes = Math.Max(0, queueRetentionMinutes);

            this._persistentStorage = persistentStorage;

            this._eventPublisher = eventPublisher;

            this._ipResolver = ipResolver;
        }
		internal RegistrationContext(IPersistentStorage storage) : base(storage)
		{
		}
 /**
 * This is the Inversion of Control method. We inject an abstraction of our storage, telling
 * the writer where we want the serialized messages to be written to. This allows us to swap
 * our implementations depending on configurations, and enables Dependancy Injection to take place.
 * We can now easily test our MessageWriter with a mock implementation of our storage abstraction.
 */
 public MessageWriter(IPersistentStorage storage)
 {
     _storage = storage;
 }
        private static async Task WriteToVersionAsync(
            IPersistentStorage storage, string keyName, VersionStamp projectVersion, VersionStamp semanticVersion, CancellationToken cancellationToken)
        {
            using (var stream = SerializableBytes.CreateWritableStream())
            using (var writer = new ObjectWriter(stream, cancellationToken: cancellationToken))
            {
                writer.WriteInt32(SerializationFormat);
                projectVersion.WriteTo(writer);
                semanticVersion.WriteTo(writer);

                stream.Position = 0;
                await storage.WriteStreamAsync(keyName, stream, cancellationToken).ConfigureAwait(false);
            }
        }
 public PersistedMemoryStorage(IPersistentStorage persistentStorage = null)
 {
     _fs = persistentStorage ?? new EsentStorage();
     _fs.CopyTo(_mem);
 }
Esempio n. 55
0
 public ExtensionRuntime(IPersistentStorage storage) : base(storage) { }
Esempio n. 56
0
 public SaveCommand(
     IPersistentStorage persistentStorage)
 {
     this.m_PersistentStorage = persistentStorage;
 }
Esempio n. 57
0
        public ConnectWorld(
            IKernel kernel, 
            I2DRenderUtilities twodRenderUtilities, 
            IAssetManagerProvider assetManagerProvider, 
            IBackgroundCubeEntityFactory backgroundCubeEntityFactory, 
            ISkin skin, 
            IProfiler profiler,
            IPersistentStorage persistentStorage,
            bool startServer, 
            IPAddress address, 
            int port)
            : base(twodRenderUtilities, assetManagerProvider, backgroundCubeEntityFactory, skin)
        {
            this.m_2DRenderUtilities = twodRenderUtilities;
            this.m_PersistentStorage = persistentStorage;

            this.m_DefaultFont = assetManagerProvider.GetAssetManager().Get<FontAsset>("font.Default");
            this.m_Address = address;
            this.m_Port = port;
            TychaiaClient client = null;
            byte[] initial = null;
            Action cleanup = () =>
            {
                kernel.Unbind<INetworkAPI>();
                kernel.Unbind<IClientNetworkAPI>();
                if (client != null)
                {
                    client.Close();
                }

                this.TerminateExistingProcess();
            };

            if (startServer)
            {
                this.m_Actions = new Action[]
                {
                    () => this.m_Message = "Closing old process...", () => this.TerminateExistingProcess(),
                    () => this.m_Message = "Starting server...", () => this.StartServer(),
                    () => this.m_Message = "Creating client...", () => client = new TychaiaClient(port + 2, port + 3),
                    () => client.AttachProfiler(profiler),
                    () => this.m_Message = "Connecting to server...",
                    () => client.Connect(new DualIPEndPoint(address, port, port + 1)),
                    () => this.m_Message = "Binding node to kernel...",
                    () => kernel.Bind<INetworkAPI>().ToMethod(x => client),
                    () => kernel.Bind<IClientNetworkAPI>().ToMethod(x => client), () => this.m_Message = "Joining game...",
                    () => this.m_UniqueClientIdentifier = this.JoinGame(client), () => this.m_Message = "Retrieving initial game state...",
                    () => initial = client.LoadInitialState(), () => this.m_Message = "Starting client...",
                    () => this.m_PerformFinalAction = true
                };
            }
            else
            {
                this.m_Actions = new Action[]
                {
                    () => this.m_Message = "Creating client...", () => client = new TychaiaClient(port + 2, port + 3),
                    () => client.AttachProfiler(profiler),
                    () => this.m_Message = "Connecting to server...",
                    () => client.Connect(new DualIPEndPoint(address, port, port + 1)),
                    () => this.m_Message = "Binding node to kernel...",
                    () => kernel.Bind<INetworkAPI>().ToMethod(x => client),
                    () => kernel.Bind<IClientNetworkAPI>().ToMethod(x => client),
                    () => this.m_Message = "Joining game...",
                    () => this.m_UniqueClientIdentifier = this.JoinGame(client), () => this.m_Message = "Retrieving initial game state...",
                    () => initial = client.LoadInitialState(), () => this.m_Message = "Starting client...",
                    () => this.m_PerformFinalAction = true
                };
            }

            this.m_FinalAction =
                () =>
                this.TargetWorld =
                this.GameContext.CreateWorld<IWorldFactory>(x => x.CreateTychaiaGameWorld(this.m_UniqueClientIdentifier, cleanup));

            var thread = new Thread(this.Run) { IsBackground = true };
            thread.Start();

            AppDomain.CurrentDomain.ProcessExit += (sender, e) =>
            {
                if (this.m_Process != null)
                {
                    try
                    {
                        this.m_Process.Kill();
                        this.m_Process = null;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            };
            AppDomain.CurrentDomain.UnhandledException += (sender, e) =>
            {
                if (this.m_Process != null)
                {
                    try
                    {
                        this.m_Process.Kill();
                        this.m_Process = null;
                    }
                    catch (InvalidOperationException)
                    {
                    }
                }
            };
        }
Esempio n. 58
0
 public Compilation(IPersistentStorage storage)
 {
     _environment = createEnvironment(storage);
     _scope.set<ICompilerEnvironment>(_environment);
 }
		public ApnsCategoryProvider(IPersistentStorage persistentStorage)
		{
			_persistentStorage = persistentStorage;
		}
Esempio n. 60
0
 public ProfilingCommand(
     IPersistentStorage persistentStorage)
 {
     this.m_PersistentStorage = persistentStorage;
 }