protected KeyValueStorageTest(string name)
        {
            _settings = new ConfigurationBuilder <ITestSettings>()
                        .UseIniFile("c:\\tmp\\integration-tests.ini")
                        .UseEnvironmentVariables()
                        .Build();

            _name = name;

            if (_name == "csv-files")
            {
                _tables = StorageFactory.KeyValue.CsvFiles(TestDir);
            }
            else if (_name == "azure")
            {
                _tables = StorageFactory.KeyValue.AzureTableStorage(
                    _settings.AzureStorageName,
                    _settings.AzureStorageKey);
            }
            else if (_name == "azure-emulator")
            {
                _tables = StorageFactory.KeyValue.AzureTableDevelopmentStorage();
            }

            _tableName = "TableStorageTest" + Guid.NewGuid().ToString().Replace("-", "");
        }
Example #2
0
        private static void TestStorage(IKeyValueStorage <Guid, object> storage, int maxElements)
        {
            Console.WriteLine("Testing " + storage.GetType().Name);
            Console.WriteLine("Items,Avg insert (ms),Inserts per second,Avg read (ms),Reads per second,Avg update (ms),Updates per second, Memory(MB)");
            Stopwatch sw = new Stopwatch();

            sw.Start();

            for (int iter = 0; iter < maxElements / reportingFrequency; iter++)
            {
                Collection <Guid> ids = new Collection <Guid>();
                for (int inner = 0; inner < reportingFrequency; inner++)
                {
                    Guid id = Guid.NewGuid();
                    ids.Add(id);
                }

                var avgInsertMs = TestInsert(storage, sw, ids);
                var avgReadMs   = TestRead(storage, sw, ids);
                var avgUpdateMs = TestUpdate(storage, sw, ids);

                long memoryStatus = GC.GetTotalMemory(false) - startMemory;

                Console.WriteLine(((iter + 1) * reportingFrequency).ToString()
                                  + "," + avgInsertMs.ToString() + "," + 1000 / avgInsertMs
                                  + "," + avgReadMs.ToString() + "," + 1000 / avgReadMs
                                  + "," + avgUpdateMs.ToString() + "," + 1000 / avgUpdateMs
                                  + "," + memoryStatus / 1024 / 1024
                                  );
            }
        }
Example #3
0
        public SettingsStorage(Version version, IKeyValueStorage keyValueStorage)
        {
            Ensure.Argument.IsNotNull(keyValueStorage, nameof(keyValueStorage));

            this.version         = version;
            this.keyValueStorage = keyValueStorage;
        }
 public TfIdfSimilarityScoring(
     ITextPreprocessor textPreprocessor,
     IKeyValueStorage keyValueStorage)
 {
     _textPreprocessor = textPreprocessor;
     _keyValueStorage  = keyValueStorage;
 }
Example #5
0
 public LocalFlightsProvider(IKeyValueStorage keyValueStorage, string flightsKey)
 {
     CodeContract.RequiresArgumentNotNull <IKeyValueStorage>(keyValueStorage, "keyValueStorage");
     CodeContract.RequiresArgumentNotNullAndNotEmpty(flightsKey, "flightsKey");
     this.keyValueStorage = keyValueStorage;
     pathToSettings       = PathToSettingsPrefix + flightsKey;
 }
Example #6
0
        /// <summary>
        /// Gets first value by partitionkey and rowkey
        /// </summary>
        /// <param name="source"></param>
        /// <param name="tableName"></param>
        /// <param name="partitionKey"></param>
        /// <param name="rowKey"></param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public static async Task <Value> FindOneAsync(this IKeyValueStorage source, string tableName, string partitionKey, string rowKey)
        {
            EnsureArg.IsNotNullOrEmpty(partitionKey, nameof(partitionKey));
            EnsureArg.IsNotNullOrEmpty(rowKey, nameof(rowKey));

            return(await source.FindOneAsync(tableName, new Key(partitionKey, rowKey)).AnyContext());
        }
        protected BaseMessagingActor(ActorService actorService, ActorId actorId,
                                     IBinaryMessageSerializer binaryMessageSerializer,
                                     IActorClient actorClient,
                                     IKeyValueStorage <string> storage,
                                     ILogger logger) : base(actorService, actorId, logger)
        {
            /*
             * Flow = BaseDependencyResolver.ResolveFlow();
             * if (Flow != null)
             * {
             *  CurrentRefStep = Flow.GetCurrentStep(CurrentActorServiceWithActorIdNotSpecified);
             *  NextStep = Flow.GetNextStep(CurrentRefStep);
             *  Orders = NextStep.Orders;
             * }*/

            Orders = OrchestrationOrderCollection.NoOrder();

            //resolve binary serializer

            BinaryMessageSerializer = binaryMessageSerializer ?? throw new ArgumentNullException(nameof(binaryMessageSerializer));
            ActorClient             = actorClient ?? throw new ArgumentNullException(nameof(actorClient));
            StorageService          = storage;

            //resolve storage
            //StorageService = BaseDependencyResolver.ResolveStorageService<string>();

            //resolve flowservice
            //AsyncFlowService = BaseDependencyResolver.ResolveFlowService();

            //resolve actorclient to be able to chain next
        }
Example #8
0
        private static void TestStorage(IKeyValueStorage<Guid, object> storage, int maxElements)
        {
            Console.WriteLine("Testing " + storage.GetType().Name);
            Console.WriteLine("Items,Avg insert (ms),Inserts per second,Avg read (ms),Reads per second,Avg update (ms),Updates per second, Memory(MB)");
            Stopwatch sw = new Stopwatch();
            sw.Start();

            for (int iter = 0; iter < maxElements / reportingFrequency; iter++)
            {
                Collection<Guid> ids = new Collection<Guid>();
                for (int inner = 0; inner < reportingFrequency; inner++)
                {
                    Guid id = Guid.NewGuid();
                    ids.Add(id);
                }

                var avgInsertMs = TestInsert(storage, sw, ids);
                var avgReadMs = TestRead(storage, sw, ids);
                var avgUpdateMs = TestUpdate(storage, sw, ids);

                long memoryStatus = GC.GetTotalMemory(false) - startMemory;

                Console.WriteLine(((iter + 1) * reportingFrequency).ToString()
                    + "," + avgInsertMs.ToString() + "," + 1000 / avgInsertMs
                    + "," + avgReadMs.ToString() + "," + 1000 / avgReadMs
                    + "," + avgUpdateMs.ToString() + "," + 1000 / avgUpdateMs
                    + "," + memoryStatus / 1024 / 1024
                    );
            }
        }
Example #9
0
        public async Task Blobs_list_files_in_a_folder()
        {
            IKeyValueStorage kv = StorageFactory.KeyValue.AzureTableStorage("my account", "my key");

            IBlobStorage s = StorageFactory.Blobs.FromConnectionString("azure.blobs://...parameters...");


            IMessagePublisher publisher = StorageFactory.Messages.InMemoryPublisher("name");

            IMessageReceiver receiver = StorageFactory.Messages.InMemoryReceiver("name");

            IBlobStorage storage = StorageFactory.Blobs.AmazonS3BlobStorage(
                _settings.AwsAccessKeyId,
                _settings.AwsSecretAccessKey,
                _settings.AwsTestBucketName);

            await storage.WriteAsync("folder1/file1", RandomGenerator.RandomString.ToMemoryStream(), false);

            await storage.WriteAsync("folder1/file2", RandomGenerator.RandomString.ToMemoryStream(), false);

            await storage.WriteAsync("folder2/file1", RandomGenerator.RandomString.ToMemoryStream(), false);

            BlobId[] folderBlobs = (await storage.ListAsync(new ListOptions {
                FolderPath = "folder1", Recurse = true
            })).ToArray();
        }
Example #10
0
        public static ParamContainer CreateParamContainer(ILogger loggerController, IActionExecuter actionExecuter)
        {
            ILogReader         logReader         = Logger.GetLogReader();
            IAppSettingService appSettingService = AppSettingService.Instance;
            ParamContainer     paramContainer    = new ParamContainer();

            IDBService       dbService       = ApplicationConfig.DependencyResolver.GetInstance <IDBService>();
            IPingService     pingService     = ApplicationConfig.DependencyResolver.GetInstance <IPingService>();
            IViewEngine      viewEngine      = ApplicationConfig.DependencyResolver.GetInstance <IViewEngine>();
            IEncryption      encryption      = ApplicationConfig.DependencyResolver.GetInstance <IEncryption>();
            IKeyValueStorage keyValueStorage = ApplicationConfig.DependencyResolver.GetInstance <IKeyValueStorage>();

            ISMSService   smsService   = new SMSService(loggerController, dbService, actionExecuter, viewEngine, paramContainer);
            IEmailService emailService = new EmailService(loggerController, dbService, actionExecuter, viewEngine, paramContainer);
            IOTPService   otpService   = new OTPService(loggerController, dbService, smsService, emailService, appSettingService);

            paramContainer.AddKey(CommonConst.CommonValue.PARAM_DBPROXY, () => { return(dbService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_LOGGER, () => { return(loggerController); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_ACTIONEXECUTER, () => { return(actionExecuter); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_PING_SERVICE, () => { return(pingService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_PING_SERVICE, () => { return(pingService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_APP_SETTING, () => { return(appSettingService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_VIEW_ENGINE, () => { return(viewEngine); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_OTP_SERVICE, () => { return(otpService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_SMS_SERVICE, () => { return(smsService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_EMAIL_SERVICE, () => { return(emailService); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_ENCRYPTION_SERVICE, () => { return(encryption); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_KEY_VALUE_STORAGE, () => { return(keyValueStorage); });
            paramContainer.AddKey(CommonConst.CommonValue.PARAM_HTTP_CLIENT, () => { return(new HttpRestClient()); });

            return(paramContainer);
        }
Example #11
0
        public SettingsStorage(Version version, IKeyValueStorage keyValueStorage)
        {
            Ensure.Argument.IsNotNull(keyValueStorage, nameof(keyValueStorage));

            this.version         = version;
            this.keyValueStorage = keyValueStorage;

            (isNewUserSubject, IsNewUser) = prepareSubjectAndObservable(isNewUserKey, keyValueStorage.GetBool);
            (enabledCalendarsSubject, EnabledCalendars) = prepareSubjectAndObservable(EnabledCalendarIds());
            (isManualModeEnabledSubject, IsManualModeEnabledObservable) = prepareSubjectAndObservable(preferManualModeKey, keyValueStorage.GetBool);
            (areRunningTimerNotificationsEnabledSubject, AreRunningTimerNotificationsEnabledObservable) = prepareSubjectAndObservable(runningTimerNotificationsKey, keyValueStorage.GetBool);
            (areStoppedTimerNotificationsEnabledSubject, AreStoppedTimerNotificationsEnabledObservable) = prepareSubjectAndObservable(stoppedTimerNotificationsKey, keyValueStorage.GetBool);
            (hasTappedTimeEntrySubject, HasTappedTimeEntry)                     = prepareSubjectAndObservable(hasTappedTimeEntryKey, keyValueStorage.GetBool);
            (hasEditedTimeEntrySubject, HasEditedTimeEntry)                     = prepareSubjectAndObservable(hasEditedTimeEntryKey, keyValueStorage.GetBool);
            (hasSelectedProjectSubject, HasSelectedProject)                     = prepareSubjectAndObservable(hasSelectedProjectKey, keyValueStorage.GetBool);
            (stopButtonWasTappedSubject, StopButtonWasTappedBefore)             = prepareSubjectAndObservable(stopButtonWasTappedBeforeKey, keyValueStorage.GetBool);
            (userSignedUpUsingTheAppSubject, UserSignedUpUsingTheApp)           = prepareSubjectAndObservable(userSignedUpUsingTheAppKey, keyValueStorage.GetBool);
            (startButtonWasTappedSubject, StartButtonWasTappedBefore)           = prepareSubjectAndObservable(startButtonWasTappedBeforeKey, keyValueStorage.GetBool);
            (projectOrTagWasAddedSubject, ProjectOrTagWasAddedBefore)           = prepareSubjectAndObservable(projectOrTagWasAddedBeforeKey, keyValueStorage.GetBool);
            (calendarNotificationsEnabledSubject, CalendarNotificationsEnabled) = prepareSubjectAndObservable(calendarNotificationsEnabledKey, keyValueStorage.GetBool);
            (navigatedAwayFromMainViewAfterTappingStopButtonSubject, NavigatedAwayFromMainViewAfterTappingStopButton) = prepareSubjectAndObservable(navigatedAwayFromMainViewAfterTappingStopButtonKey, keyValueStorage.GetBool);
            (hasTimeEntryBeenContinuedSubject, HasTimeEntryBeenContinued) = prepareSubjectAndObservable(hasTimeEntryBeenContinuedKey, keyValueStorage.GetBool);
            (timeSpanBeforeCalendarNotificationsSubject, TimeSpanBeforeCalendarNotifications) = prepareSubjectAndObservable(keyValueStorage.GetTimeSpan(timeSpanBeforeCalendarNotificationsKey) ?? defaultTimeSpanBeforeCalendarNotificationsSubject);
            (swipeActionsEnabledSubject, SwipeActionsEnabled) = prepareSubjectAndObservable(swipeActionsDisabledKey, key => !keyValueStorage.GetBool(key));
        }
        public static FoundationMvvmCross RegisterServices(this Foundation self,
                                                           IDialogService dialogService,
                                                           IBrowserService browserService,
                                                           IKeyValueStorage keyValueStorage,
                                                           IAccessRestrictionStorage accessRestrictionStorage,
                                                           IUserPreferences userPreferences,
                                                           IOnboardingStorage onboardingStorage,
                                                           IMvxNavigationService navigationService,
                                                           IPasswordManagerService passwordManagerService = null)
        {
            Ensure.Argument.IsNotNull(self, nameof(self));
            Ensure.Argument.IsNotNull(dialogService, nameof(dialogService));
            Ensure.Argument.IsNotNull(browserService, nameof(browserService));
            Ensure.Argument.IsNotNull(keyValueStorage, nameof(keyValueStorage));
            Ensure.Argument.IsNotNull(accessRestrictionStorage, nameof(accessRestrictionStorage));
            Ensure.Argument.IsNotNull(userPreferences, nameof(userPreferences));
            Ensure.Argument.IsNotNull(onboardingStorage, nameof(onboardingStorage));
            Ensure.Argument.IsNotNull(navigationService, nameof(navigationService));

            var timeService = self.TimeService;

            var apiErrorHandlingService = new ApiErrorHandlingService(navigationService, accessRestrictionStorage);

            Mvx.RegisterSingleton(self.BackgroundService);
            Mvx.RegisterSingleton(dialogService);
            Mvx.RegisterSingleton(self.Database);
            Mvx.RegisterSingleton(browserService);
            Mvx.RegisterSingleton(self.UserAgent);
            Mvx.RegisterSingleton(self.TimeService);
            Mvx.RegisterSingleton(self.Scheduler);
            Mvx.RegisterSingleton(self.ShortcutCreator);
            Mvx.RegisterSingleton(self.MailService);
            Mvx.RegisterSingleton(self.ShortcutCreator);
            Mvx.RegisterSingleton(self.AnalyticsService);
            Mvx.RegisterSingleton(self.PlatformConstants);
            Mvx.RegisterSingleton(self.Database.IdProvider);
            Mvx.RegisterSingleton(self.SuggestionProviderContainer);
            Mvx.RegisterSingleton(userPreferences);
            Mvx.RegisterSingleton(onboardingStorage);
            Mvx.RegisterSingleton(accessRestrictionStorage);
            Mvx.RegisterSingleton <IApiErrorHandlingService>(apiErrorHandlingService);
            Mvx.RegisterSingleton(passwordManagerService ?? new StubPasswordManagerService());

            Mvx.LazyConstructAndRegisterSingleton <IInteractorFactory, InteractorFactory>();

            return(new FoundationMvvmCross(
                       self.ApiFactory,
                       self.Database,
                       timeService,
                       self.Scheduler,
                       self.AnalyticsService,
                       self.GoogleService,
                       self.ShortcutCreator,
                       self.BackgroundService,
                       onboardingStorage,
                       accessRestrictionStorage,
                       navigationService,
                       apiErrorHandlingService));
        }
Example #13
0
 public RemoteFlightsProvider(IKeyValueStorage keyValueStorage, string flightsKey, IRemoteFileReaderFactory remoteFileFactory, IFlightsStreamParser flightsStreamParser)
     : base(keyValueStorage, flightsStreamParser, 1800000)
 {
     CodeContract.RequiresArgumentNotNull <IRemoteFileReaderFactory>(remoteFileFactory, "remoteFileFactory");
     CodeContract.RequiresArgumentNotNullAndNotEmpty(flightsKey, "flightsKey");
     remoteFileReader = new Lazy <IRemoteFileReader>(() => remoteFileFactory.Instance());
     this.flightsKey  = flightsKey;
 }
Example #14
0
 public EnumerationOperation(IKeyValueStorage keyValueStorage, string name, Func <long, long> enumration, Func <long> defaultTimestampFunc)
 {
     this.keyValueStorage = keyValueStorage;
     Name                      = name;
     State                     = OperationState.Idle;
     this.enumration           = enumration;
     this.defaultTimestampFunc = defaultTimestampFunc;
 }
Example #15
0
        /// <summary>
        /// Gets first value by key
        /// </summary>
        /// <param name="source"></param>
        /// <param name="tableName"></param>
        /// <param name="key"></param>
        /// <returns>A <see cref="Task"/> representing the asynchronous operation.</returns>
        public static async Task <Value> FindOneAsync(this IKeyValueStorage source, string tableName, Key key)
        {
            EnsureArg.IsNotNull(key, nameof(key));

            var values = await source.FindAllAsync(tableName, key).AnyContext();

            return(values.FirstOrDefault());
        }
 /// <summary>
 /// Creates and returns a content for a GraphViz (.gv) file (using DOT language), for the visualisation of types that are in the storage.
 /// For this purpose, a Context is created only for this purpose, and cannot be used for any other.
 /// </summary>
 /// <param name="storage">Storage from where the types are extracted</param>
 /// <returns>content for the GraphViz file</returns>
 public String GetGraphVizContentFromStorage(IKeyValueStorage<Guid, object> storage)
 {
     String graphVizContent;
     IDictionary<String, TypeVisualUnit> typeUnits = GetTypeVisualUnits(GetRootTypeId());
     GVTemplate template = new GVTemplate(typeUnits);
     graphVizContent = template.TransformText();
     return graphVizContent;
 }
        private bool shouldScheduleSyncJob(IKeyValueStorage keyValueStorage)
        {
            var now = DateTimeOffset.Now;
            var hasPendingJobScheduled = keyValueStorage.GetBool(HasPendingSyncJobServiceScheduledKey);
            var lastSyncJobScheduledAt = keyValueStorage.GetDateTimeOffset(LastSyncJobScheduledAtKey).GetValueOrDefault();

            return(!hasPendingJobScheduled || now.Subtract(lastSyncJobScheduledAt).TotalHours > jobScheduleExpirationInHours);
        }
 /// <summary>
 /// Automaticaly find handler.
 /// </summary>
 public static void InitDependencies()
 {
     _handler = IocGlob.CreateTypeInstance <IKeyValueStorage>(
         IocGlob.FindAssignable <IKeyValueStorage>(
             new string[] { "RollingOutTools.Storage.JsonFileStorage" }
             )
         );
 }
Example #19
0
        public static DateTime GetDate(this IKeyValueStorage self, string key, out bool ok)
        {
            var  v = self.GetString(key);
            long bin;

            ok = long.TryParse(v, out bin);
            return(DateTime.FromBinary(bin));
        }
Example #20
0
        private IKeyValueStorage <Guid, object> ConfigureStorage(String dataFilePath)
        {
            string fileName = dataFilePath + "data.dat";
            var    file     = new FileStream(fileName, FileMode.Create);

            storage = new IndexedFileStorage(file, 256, true);
            return(storage);
        }
 public RegularOperationsFactory(
     IDateTimeFactory dateTimeFactory,
     IKeyValueStorage keyValueStorage
     )
 {
     this.dateTimeFactory = dateTimeFactory;
     this.keyValueStorage = keyValueStorage;
 }
Example #22
0
        /// <summary>
        /// Creates new instance of ClientContext type
        /// </summary>
        /// <param name="serverContext">Server context interface</param>
        /// <param name="localStorage">Storage for local data</param>
        public ClientContext(IServerContext serverContext, IKeyValueStorage <Guid, object> localStorage)
        {
            this.serverContext            = serverContext;
            this.provider                 = new CachedReadNodeProvider <Guid, object, EdgeData>(serverContext, new DirectNodeProviderUnsafe <Guid, object, EdgeData>(localStorage, localStorage is IForceUpdateStorage));
            this.snapshotIsolationEnabled = serverContext.SnapshotIsolationEnabled;
            this.defaultWorkspaceTimeout  = serverContext.DefaultWorkspaceTimeout;

            InitializeServices();
        }
Example #23
0
        public static async Task InsertAsync(this IKeyValueStorage source, string tableName, Value value)
        {
            EnsureArg.IsNotNullOrEmpty(tableName, nameof(tableName));
            EnsureArg.IsNotNull(value, nameof(value));

            await source.InsertAsync(new List <Value> {
                value
            }).AnyContext();
        }
Example #24
0
 /// <summary>
 /// Creates new instance of Context type and upgrades the data from existing storage.
 /// </summary>
 /// <param name="rootEntityType">Type of root entity</param>
 /// <param name="entityTypes">Array of entity interface types to register. All reachable sub-types are registered automatically.</param>
 /// <param name="storage">Storage to be used</param>
 /// <param name="upgradeConfiguration">Upgrade configuration</param>
 public Context(Type rootEntityType, Type[] entityTypes, IKeyValueStorage <Guid, object> storage, UpgradeConfiguration upgradeConfiguration)
 {
     InitializeProvider(storage);
     if (entityTypes == null)
     {
         entityTypes = new Type[] { rootEntityType };
     }
     InitializeServices(rootEntityType, entityTypes, upgradeConfiguration);
 }
Example #25
0
 public GetJavascriptController(IResponseBuilder responseBuilder, ILogger logger, IHttpContextProxy httpContextProxy, IDBService dBService, IKeyValueStorage keyValueStorage, IStaticContentHandler staticContentHandler)
 {
     _httpContextProxy     = httpContextProxy;
     _responseBuilder      = responseBuilder;
     _logger               = logger;
     _dBService            = dBService;
     _keyValueStorage      = keyValueStorage;
     _staticContentHandler = staticContentHandler;
 }
            public void ThrowsWhenTheArgumentIsNull(bool useTimeService, bool useKeyValueStorage, bool useFetchRemoteConfigService)
            {
                ITimeService              timeService              = useTimeService ? Substitute.For <ITimeService>() : null;
                IKeyValueStorage          keyValueStorage          = useKeyValueStorage ? Substitute.For <IKeyValueStorage>() : null;
                IFetchRemoteConfigService fetchRemoteConfigService = useFetchRemoteConfigService ? Substitute.For <IFetchRemoteConfigService>() : null;
                Action constructor = () => new UpdateRemoteConfigCacheService(timeService, keyValueStorage, fetchRemoteConfigService);

                constructor.Should().Throw <ArgumentNullException>();
            }
Example #27
0
 public KeyValueStorageSecure(
     string prefix,
     string version,
     VersionedCrypterProvider crypterProvider,
     IKeyValueStorage kvs) : base(prefix, kvs)
 {
     _crypterProvider = crypterProvider;
     _version         = version;
 }
        /// <summary>
        /// Creates and returns a content for a GraphViz (.gv) file (using DOT language), for the visualisation of types that are in the storage.
        /// For this purpose, a Context is created only for this purpose, and cannot be used for any other.
        /// </summary>
        /// <param name="storage">Storage from where the types are extracted</param>
        /// <returns>content for the GraphViz file</returns>
        public String GetGraphVizContentFromStorage(IKeyValueStorage <Guid, object> storage)
        {
            String graphVizContent;
            IDictionary <String, TypeVisualUnit> typeUnits = GetTypeVisualUnits(GetRootTypeId());
            GVTemplate template = new GVTemplate(typeUnits);

            graphVizContent = template.TransformText();
            return(graphVizContent);
        }
Example #29
0
        /// <summary>
        /// Must throw exception.
        /// </summary>
        /// <param name="storage"></param>
        public static async Task TestGetNull(IKeyValueStorage storage)
        {
            var key = "value_TestGetNull";
            await storage.Set(key, null);

            var value = await storage.Get <string>(key);

            Assert.IsNull(value);
        }
Example #30
0
        public static async Task TestGetOrDefaultForValueType(IKeyValueStorage storage)
        {
            var key = "testValue1_c34a33";
            await storage.Set(key, null);

            var num = await storage.GetOrDefault <int>(key);

            Assert.AreEqual(num, default(int));
        }
Example #31
0
        public static void TaskWaitDefaultCall(IKeyValueStorage storage)
        {
            var key = "D991231h323";

            storage.Set(key, 100).Wait();
            var val = storage.Get <int>(key).Result;

            Assert.AreEqual(val, 100);
        }
Example #32
0
        public static async Task DefaultCall(IKeyValueStorage storage)
        {
            var key = "D99h323";
            await storage.Set(key, 100);

            var val = await storage.Get <int>(key);

            Assert.AreEqual(val, 100);
        }
Example #33
0
        private static double TestRead(IKeyValueStorage<Guid, object> storage, Stopwatch sw, Collection<Guid> ids)
        {
            var startTicks = sw.ElapsedTicks;

            for (int inner = 0; inner < reportingFrequency; inner++)
            {
                storage.Value(ids[inner]);
            }

            return (double)1000 * (sw.ElapsedTicks - startTicks) / Stopwatch.Frequency / reportingFrequency;
        }
 public AccountManager(IKeyValueStorage storage, 
     CommandBuilder commandBuilder,
     IUserIdProvider userIdProvider,
     TransportManager transportManager)
 {
     _storage = storage;
     _commandBuilder = commandBuilder;
     _userIdProvider = userIdProvider;
     _transportManager = transportManager;
     Number = _storage.GetValue(NumberKey, string.Empty);
     UserId = _storage.GetValue(UserIdKey, string.Empty);
 }
        /// <summary>
        /// Constructor
        /// </summary>
        /// <param name="storage">The storage from which the types needed for visualisation are loaded</param>
        public TypesVisualisationService(IKeyValueStorage<Guid, object> storage)
        {
            if (storage is ISerializingStorage)
            {
                (storage as ISerializingStorage).Serializer = objectSerializationService;
            }

            var storageProvider = new DirectNodeProviderSafe<Guid, object, EdgeData>(storage, storage is IForceUpdateStorage);
            provider = new CachedReadNodeProvider<Guid, object, EdgeData>(storageProvider, new DirectNodeProviderSafe<Guid, object, EdgeData>(new LimitedMemoryStorageSafe<Guid, object>(Properties.Settings.Default.DataCacheMinimumCount, Properties.Settings.Default.DataCacheMaximumCount), false));
            typesService = new TypesService(provider);
            typesService.InitializeTypeSystem(null);
            objectSerializationService.TypesService = typesService;
        }
Example #36
0
 /// <summary>
 /// Creates new instance of UpgradeConfiguration type
 /// </summary>
 /// <param name="source">Source of data for the upgrade</param>
 public UpgradeConfiguration(IKeyValueStorage<Guid, object> source)
 {
     this.Source = source;
 }
 /// <summary>
 /// Creates and returns a content for a GraphViz (.gv) file (using DOT language), for the visualisation of types that are in the storage.
 /// <para>For this purpose, a Context is created only for this purpose, and cannot be used for any other.</para>
 /// </summary>
 /// <param name="storage">Storage from where the types are extracted</param>
 /// <returns>content for the GraphViz file</returns>
 public String GetGraphVizContentFromStorage(string typeName, IKeyValueStorage<Guid, object> storage)
 {
     String graphVizContent;
     Guid typeId = GetIdFromTypeName(typeName);
     if (typeId.Equals(Guid.Empty))
         throw new Exception("Type with the following name : " + typeName + " doesn't exist in this Context");
     IDictionary<String, TypeVisualUnit> typeUnits = GetTypeVisualUnits(typeId);
     GVTemplate template = new GVTemplate(typeUnits);
     graphVizContent = template.TransformText();
     return graphVizContent;
 }
Example #38
0
        /// <summary>
        /// Creates new delta tree describing the new snapshot
        /// </summary>
        /// <param name="baseSnapshotId">Base snapshot of the change set</param>
        /// <param name="newSnapshotId">New snapshot of the change set</param>
        /// <returns>Delta tree nodes</returns>
        private INodeProvider<Guid, object, EdgeData> CreateAppendableChangeSetTree(Guid baseSnapshotId, Guid newSnapshotId, IKeyValueStorage<Guid, object> storage, Dictionary<Guid, Guid> nodeMapping, Dictionary<Guid, NodeState> nodeStates, IsolatedChangeSet<Guid, object, EdgeData> changeSet, Hashtable reusedNodes)
        {
            DirectNodeProviderUnsafe<Guid, object, EdgeData> delta = new DirectNodeProviderUnsafe<Guid, object, EdgeData>(storage, storage is IForceUpdateStorage);

            // Create snapshot in delta
            nodeMapping.Add(baseSnapshotId, newSnapshotId);
            var snapshotNode = new Node<Guid, object, EdgeData>(NodeType.Snapshot, null);
            snapshotNode.Previous = baseSnapshotId;
            // Link to root object
            snapshotNode.AddEdge(new Edge<Guid, EdgeData>(snapshotsService.GetRootObjectId(baseSnapshotId), new EdgeData(EdgeType.RootObject, null)));
            // Set node to provider
            delta.SetNode(newSnapshotId, snapshotNode);

            // Add all changes and parent nodes
            foreach (Guid nodeId in changeSet.Nodes.EnumerateNodes())
            {
                AddNodeToAppendableTreeRecursive(delta, nodeId, nodeMapping, nodeStates, changeSet);
            }

            // Prepare list of unreferenced node IDs
            Dictionary<Guid, Collection<Guid>> references = new Dictionary<Guid, Collection<Guid>>();

            // Resolve edges based on mapping
            foreach (Guid nodeId in delta.EnumerateNodes())
            {
                references.Add(nodeId, new Collection<Guid>());
            }

            // Resolve edges based on mapping
            foreach (Guid nodeId in delta.EnumerateNodes())
            {
                var node = delta.GetNode(nodeId, NodeAccess.ReadWrite);

                foreach (var edge in node.Edges.Values)
                {
                    // Permanent edges should not be touched
                    if (!Utils.IsPermanentEdge(edge))
                    {
                        // Reroute based on node mapping
                        if (nodeMapping.ContainsKey(edge.ToNodeId))
                        {
                            edge.ToNodeId = nodeMapping[edge.ToNodeId];
                        }
                        else
                        {
                            if (!reusedNodes.ContainsKey(edge.ToNodeId))
                            {
                                reusedNodes.Add(edge.ToNodeId, null);
                            }
                        }

                        // Change edge data if it points to changed node
                        if (edge.Data.Data != null && edge.Data.Data is Guid)
                        {
                            if (nodeMapping.ContainsKey((Guid)edge.Data.Data))
                            {
                                edge.Data = new EdgeData(edge.Data.Semantic, nodeMapping[(Guid)edge.Data.Data]);
                            }
                        }
                    }
                    else
                    {
                        if (!reusedNodes.ContainsKey(edge.ToNodeId))
                        {
                            reusedNodes.Add(edge.ToNodeId, null);
                        }
                    }

                    if (references.ContainsKey(edge.ToNodeId))
                    {
                        references[edge.ToNodeId].Add(nodeId);
                    }
                }
            }

            // Remove remaining unreferenced nodes
            bool removed = false;

            do
            {
                removed = false;

                foreach (Guid key in delta.EnumerateNodes())
                {
                    // There are no references to the key
                    if ((key!=newSnapshotId) && (references[key].Count == 0))
                    {
            #if DEBUG
                        Debug.WriteLine("Removed unreferenced key " + key);
            #endif
                        delta.Remove(key);

                        reusedNodes.Remove(key);

                        nodeStates.Remove(key);

                        foreach (Guid otherKey in references.Keys)
                        {
                            references[otherKey].Remove(key);
                        }

                        foreach (var mappingKey in nodeMapping.Keys)
                        {
                            if (nodeMapping[mappingKey] == key)
                            {
                                nodeMapping.Remove(mappingKey);
                                break;
                            }
                        }

                        removed = true;
                        break;
                    }
                }
            }
            while (removed);

            // Isolated provider nodes have been corrupted, perform clear
            changeSet.Nodes.Clear();
            changeSet.NodeStates.Clear();

            return delta;
        }
Example #39
0
 private void Dispose(bool disposing)
 {
     if (!isDisposed)
     {
         isDisposed = true;
         if (disposing)
         {
             if (storage != null)
             {
                 storage = null;
             }
             if (dataFileStream != null)
             {
                 dataFileStream.Flush();
                 dataFileStream.Dispose();
                 dataFileStream = null;
             }
         }
     }
 }
Example #40
0
 private IKeyValueStorage<Guid, object> ConfigureStorage(String dataFilePath)
 {
     string fileName = dataFilePath + "data.dat";
     var file = new FileStream(fileName, FileMode.Create);
     storage = new IndexedFileStorage(file, 256, true);
     return storage;
 }