Beispiel #1
0
        public async Task Init(string name, Providers.IProviderRuntime providerRuntime, Providers.IProviderConfiguration config)
        {
            existingCollections = new ConcurrentDictionary <string, bool>();
            createdCollections  = new ConcurrentDictionary <string, bool>();
            Log = providerRuntime.GetLogger("Storage.DocumentDBStorageProvider");
            try
            {
                isFaultTolerant = false; //by default, unless we found otherwise later

                this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(), config);
                var url = config.Properties[URL];
                var key = config.Properties[KEY];
                OfferType    = config.Properties[OFFER_TYPE]; //if V1 => S1, S2, S3 else if V2 => RU as integer
                DatabaseName = config.Properties[DATABASE];
                IndexMode    = config.Properties.ContainsKey(INDEXING_MODE) ? config.Properties[INDEXING_MODE] : INDEXING_MODE_CONSISTENT;
                this.Client  = new DocumentClient(new Uri(url), key, new ConnectionPolicy
                {
                    ConnectionMode     = ConnectionMode.Direct,
                    ConnectionProtocol = Protocol.Tcp
                });

                await this.Client.OpenAsync();

                var databases = await this.Client.ReadDatabaseFeedAsync();

                this.Database = databases.Where(d => d.Id == DatabaseName).FirstOrDefault()
                                ?? await this.Client.CreateDatabaseAsync(new Database { Id = DatabaseName });
            }
            catch (Exception ex)
            {
                Log.Error(0, "Error in DocumentDBStorageProvider Init.", ex);
            }
        }
        private Task Init(CancellationToken ct)
        {
            // Settings could be made configurable from Options.
            jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory), false, false, null);

            return(Task.CompletedTask);
        }
 /// <summary>
 /// Initializes the storage provider.
 /// </summary>
 /// <param name="name">The name of this provider instance.</param>
 /// <param name="providerRuntime">A Orleans runtime object managing all storage providers.</param>
 /// <param name="config">Configuration info for this provider instance.</param>
 /// <returns>Completion promise for this operation.</returns>
 public virtual Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
 {
     this.Name = name;
     this.jsonSerializerSettings = OrleansJsonSerializer.GetDefaultSerializerSettings();
     Log = providerRuntime.GetLogger(this.GetType().FullName);
     return(TaskDone.Done);
 }
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            _jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(
                OrleansJsonSerializer.GetDefaultSerializerSettings(
                    providerRuntime.ServiceProvider.GetRequiredService <SerializationManager>(),
                    providerRuntime.GrainFactory),
                config);

            Name = name;
            if (string.IsNullOrWhiteSpace(config.Properties["RootDirectory"]))
            {
                throw new ArgumentException("RootDirectory property not set");
            }

            var directory = new DirectoryInfo(config.Properties["RootDirectory"]);

            if (!directory.Exists)
            {
                directory.Create();
            }

            RootDirectory = directory.FullName;

            return(Task.CompletedTask);
        }
        public static JsonSerializerSettings GetJsonSerializerSettings(IServiceProvider serviceProvider)
        {
            var serializerSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(serviceProvider);

            serializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
            return(serializerSettings);
        }
Beispiel #6
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Log = providerRuntime.GetLogger("Storage.AzureBlobStorage");

            try
            {
                this.Name         = name;
                this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(), config);

                if (!config.Properties.ContainsKey(DataConnectionStringPropertyName))
                {
                    throw new BadProviderConfigException($"The {DataConnectionStringPropertyName} setting has not been configured in the cloud role. Please add a {DataConnectionStringPropertyName} setting with a valid Azure Storage connection string.");
                }

                var account       = CloudStorageAccount.Parse(config.Properties[DataConnectionStringPropertyName]);
                var blobClient    = account.CreateCloudBlobClient();
                var containerName = config.Properties.ContainsKey(ContainerNamePropertyName) ? config.Properties[ContainerNamePropertyName] : ContainerNameDefaultValue;
                container = blobClient.GetContainerReference(containerName);
                await container.CreateIfNotExistsAsync().ConfigureAwait(false);

                Log.Info((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, "Init: Name={0} ServiceId={1} {2}", name, providerRuntime.ServiceId.ToString(), string.Join(" ", FormatPropertyMessage(config)));
                Log.Info((int)AzureProviderErrorCode.AzureBlobProvider_ParamConnectionString, "AzureBlobStorage Provider is using DataConnectionString: {0}", ConfigUtilities.PrintDataConnectionInfo(config.Properties["DataConnectionString"]));
            }
            catch (Exception ex)
            {
                Log.Error((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, ex.ToString(), ex);
                throw;
            }
        }
Beispiel #7
0
        /// <summary> Initialization function for this storage provider. </summary>
        private async Task Init(CancellationToken ct)
        {
            var stopWatch = Stopwatch.StartNew();

            try
            {
                this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage initializing: {this.options.ToString()}");
                this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableGrainStorage is using DataConnectionString: {0}", ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString));
                this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.services), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);

                this.options.ConfigureJsonSerializerSettings?.Invoke(this.jsonSettings);

                var client = this.options.ServiceUri != null ? new BlobServiceClient(this.options.ServiceUri, this.options.TokenCredential) : new BlobServiceClient(this.options.ConnectionString);
                container = client.GetBlobContainerClient(this.options.ContainerName);
                await container.CreateIfNotExistsAsync().ConfigureAwait(false);

                stopWatch.Stop();
                this.logger.LogInformation((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
            }
            catch (Exception ex)
            {
                stopWatch.Stop();
                this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex);
                throw;
            }
        }
        public static JsonSerializerSettings GetJsonSerializerSettings(ITypeResolver typeResolver, IGrainFactory grainFactory)
        {
            var serializerSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory);

            serializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
            return(serializerSettings);
        }
        /// <summary> Initialization function for this storage provider. </summary>
        private async Task Init(CancellationToken ct)
        {
            var stopWatch = Stopwatch.StartNew();

            try
            {
                this.logger.LogInformation((int)RavenDBProviderErrorCode.RavenDBProvider_InitProvider, $"AzureTableGrainStorage initializing: {this.options.ToString()}");
                this.logger.LogInformation((int)RavenDBProviderErrorCode.RavenDBProvider_ParamConnectionString, "AzureTableGrainStorage is using DataConnectionString: {0}", ConfigUtilities.RedactConnectionStringInfo(this.options.ConnectionString));
                this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);

                this.options.ConfigureJsonSerializerSettings?.Invoke(this.jsonSettings);

                // TODO: RavenDB Specific Code here.

                /*
                 * var account = CloudStorageAccount.Parse(this.options.ConnectionString);
                 * var blobClient = account.CreateCloudBlobClient();
                 * container = blobClient.GetContainerReference(this.options.ContainerName);
                 * await container.CreateIfNotExistsAsync().ConfigureAwait(false);
                 */
                stopWatch.Stop();
                this.logger.LogInformation((int)RavenDBProviderErrorCode.RavenDBProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
            }
            catch (Exception ex)
            {
                stopWatch.Stop();
                this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex);
                throw;
            }
        }
Beispiel #10
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider#Init"/>
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            serviceId = providerRuntime.ServiceId.ToString();
            Log       = providerRuntime.GetLogger("StorageProvider.SimpleSQLServerStorage." + serviceId);

            try
            {
                Name = name;
                this.jsonSettings =
                    OrleansJsonSerializer.UpdateSerializerSettings(
                        OrleansJsonSerializer.GetDefaultSerializerSettings(), config);

                if (!config.Properties.ContainsKey(CONNECTION_STRING) ||
                    string.IsNullOrWhiteSpace(config.Properties[CONNECTION_STRING]))
                {
                    throw new BadProviderConfigException($"Specify a value for: {CONNECTION_STRING}");
                }
                var connectionString = config.Properties[CONNECTION_STRING];
                sqlconnBuilder = new SqlConnectionStringBuilder(connectionString);

                //a validation of the connection would be wise to perform here
                var sqlCon = new SqlConnection(sqlconnBuilder.ConnectionString);
                await sqlCon.OpenAsync();

                sqlCon.Close();
            }
            catch (Exception ex)
            {
                throw;
            }
        }
Beispiel #11
0
        /// <summary> Initialization function for this storage provider. </summary>
        private async Task Init(CancellationToken ct)
        {
            var stopWatch = Stopwatch.StartNew();

            try
            {
                this.logger.LogInformation((int) AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureBlobGrainStorage initializing: {this.options.ToString()}");
                this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.services), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);

                this.options.ConfigureJsonSerializerSettings?.Invoke(this.jsonSettings);

                if (options.CreateClient is not {
                } createClient)
                {
                    throw new OrleansConfigurationException($"No credentials specified. Use the {options.GetType().Name}.{nameof(AzureBlobStorageOptions.ConfigureBlobServiceClient)} method to configure the Azure Blob Service client.");
                }

                var client = await createClient();

                container = client.GetBlobContainerClient(this.options.ContainerName);
                await container.CreateIfNotExistsAsync().ConfigureAwait(false);

                stopWatch.Stop();
                this.logger.LogInformation((int)AzureProviderErrorCode.AzureBlobProvider_InitProvider, $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
            }
            catch (Exception ex)
            {
                stopWatch.Stop();
                this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", ex);
                throw;
            }
        }
        private ICollection <IStorageSerializer> ConfigureSerializers(AdoNetGrainStorageOptions options, IProviderRuntime providerRuntime)
        {
            var serializers = new List <IStorageSerializer>();

            if (options.UseJsonFormat)
            {
                var typeResolver = providerRuntime.ServiceProvider.GetRequiredService <ITypeResolver>();
                var jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, providerRuntime.GrainFactory),
                                                                                  options.UseFullAssemblyNames, options.IndentJson, options.TypeNameHandling);
                options.ConfigureJsonSerializerSettings?.Invoke(jsonSettings);
                serializers.Add(new OrleansStorageDefaultJsonSerializer(jsonSettings, JsonFormatSerializerTag));
            }
            if (options.UseXmlFormat)
            {
                serializers.Add(new OrleansStorageDefaultXmlSerializer(XmlFormatSerializerTag));
            }

            //if none are set true, configure binary format serializer by default
            if (!options.UseXmlFormat && !options.UseJsonFormat)
            {
                serializers.Add(new OrleansStorageDefaultBinarySerializer(this.serializationManager, BinaryFormatSerializerTag));
            }

            return(serializers);
        }
Beispiel #13
0
 public static ISiloBuilder AddCouchbaseDefaultSerializer(this ISiloBuilder builder, string name)
 => builder.AddCouchbaseSerializer <JsonSerializer>(
     name,
     provider => new object[]
 {
     OrleansJsonSerializer.GetDefaultSerializerSettings(provider.GetRequiredService <ITypeResolver>(), provider.GetRequiredService <IGrainFactory>())
 }
     );
Beispiel #14
0
 public AzureTableTransactionalStateStorageFactory(string name, AzureTableTransactionalStateOptions options, IOptions <ClusterOptions> clusterOptions, ITypeResolver typeResolver, IGrainFactory grainFactory, ILoggerFactory loggerFactory)
 {
     this.name           = name;
     this.options        = options;
     this.clusterOptions = clusterOptions.Value;
     this.jsonSettings   = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory);
     this.loggerFactory  = loggerFactory;
 }
Beispiel #15
0
        private Task Init(CancellationToken ct)
        {
            _jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(_typeResolver, _grainFactory), false, false, TypeNameHandling.None);

            _dbClient = new MongoClient(_options.atlasConnectionString);

            return(Task.CompletedTask);
        }
Beispiel #16
0
 private async Task Init(CancellationToken ct)
 {
     this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_InitProvider, $"AzureTableGrainStorage initializing: {this.options.ToString()}");
     this.logger.LogInformation((int)AzureProviderErrorCode.AzureTableProvider_ParamConnectionString, "AzureTableGrainStorage is using DataConnectionString: {0}", ConfigUtilities.RedactConnectionStringInfo(this.options.DataConnectionString));
     this.JsonSettings     = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory), this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);
     this.tableDataManager = new GrainStateTableDataManager(this.options.TableName, this.options.DataConnectionString, this.loggerFactory);
     await this.tableDataManager.InitTableAsync();
 }
Beispiel #17
0
        private T NewtonsoftJsonSerializeRoundtrip <T>(T obj)
        {
            var settings = OrleansJsonSerializer.GetDefaultSerializerSettings(this.HostedCluster.SerializationManager, this.GrainFactory);
            // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm
            string json  = JsonConvert.SerializeObject(obj, settings);
            object other = JsonConvert.DeserializeObject(json, typeof(T), settings);

            return((T)other);
        }
Beispiel #18
0
        private async Task Init(CancellationToken ct)
        {
            _jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(_typeResolver, _grainFactory), false, false, null);

            if (!await _storage.ContainerExits(_container))
            {
                await _storage.CreateContainerAsync(_container);
            }
        }
        public static JsonSerializerSettings GetJsonSerializerSettings(ITypeResolver typeResolver, IGrainFactory grainFactory)
        {
            var serializerSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory);

            serializerSettings.TypeNameHandling           = TypeNameHandling.Auto;
            serializerSettings.PreserveReferencesHandling = PreserveReferencesHandling.None;
            serializerSettings.Converters.Add(new TransactionParticipantExtensionWrapper.CustomJsonConverter(grainFactory));
            return(serializerSettings);
        }
        private T NewtonsoftJsonSerializeRoundtrip <T>(T obj)
        {
            var typeResolver = this.HostedCluster.Client.ServiceProvider.GetRequiredService <ITypeResolver>();
            var settings     = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, this.GrainFactory);
            // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm
            string json  = JsonConvert.SerializeObject(obj, settings);
            object other = JsonConvert.DeserializeObject(json, typeof(T), settings);

            return((T)other);
        }
Beispiel #21
0
 internal static ISiloBuilder AddRedisDefaultHumanReadableSerializer(this ISiloBuilder builder, string name)
 => builder.AddRedisHumanReadableSerializer <JsonSerializer>(
     name,
     provider => new object[] {
     OrleansJsonSerializer.GetDefaultSerializerSettings(
         provider.GetRequiredService <ITypeResolver>(),
         provider.GetRequiredService <IGrainFactory>()
         )
 }
     );
        /// <summary>
        /// Initializes a new instance of the <see cref="JsonGrainStorageSerializer"/> class.
        /// </summary>
        /// <param name="options">The serializer options.</param>
        /// <param name="services">The service provider.</param>
        public JsonGrainStorageSerializer(IOptions <JsonGrainStorageSerializerOptions> options, IServiceProvider services)
        {
            this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(
                OrleansJsonSerializer.GetDefaultSerializerSettings(services),
                options.Value.UseFullAssemblyNames,
                options.Value.IndentJson,
                options.Value.TypeNameHandling);

            options.Value.ConfigureJsonSerializerSettings?.Invoke(this.jsonSettings);
        }
Beispiel #23
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider.Init"/>
        public Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Name      = name;
            serviceId = providerRuntime.ServiceId.ToString();
            this.serializationManager = providerRuntime.ServiceProvider.GetRequiredService <SerializationManager>();

            if (config.Properties.ContainsKey(TABLE_NAME_PROPERTY_NAME))
            {
                tableName = config.Properties[TABLE_NAME_PROPERTY_NAME];
            }

            isDeleteStateOnClear = config.Properties.ContainsKey(DELETE_ON_CLEAR_PROPERTY_NAME) &&
                                   "true".Equals(config.Properties[DELETE_ON_CLEAR_PROPERTY_NAME], StringComparison.OrdinalIgnoreCase);
            var loggerFactory = providerRuntime.ServiceProvider.GetRequiredService <ILoggerFactory>();
            var loggerName    = $"{this.GetType().FullName}.{name}";

            logger = loggerFactory.CreateLogger(loggerName);
            Log    = new LoggerWrapper(logger, loggerName, loggerFactory);
            var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}",
                                        Name, serviceId, tableName, isDeleteStateOnClear);

            if (config.Properties.ContainsKey(USE_JSON_FORMAT_PROPERTY_NAME))
            {
                useJsonFormat = "true".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY_NAME], StringComparison.OrdinalIgnoreCase);
            }

            var grainFactory = providerRuntime.ServiceProvider.GetRequiredService <IGrainFactory>();

            this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(this.serializationManager, grainFactory), config);

            initMsg = string.Format("{0} UseJsonFormat={1}", initMsg, useJsonFormat);

            logger.Info(ErrorCode.StorageProviderBase, "AWS DynamoDB Provider: {0}", initMsg);

            storage = new DynamoDBStorage(config.Properties[DATA_CONNECTION_STRING_PROPERTY_NAME], providerRuntime.ServiceProvider.GetRequiredService <ILoggerFactory>());
            return(storage.InitializeTable(tableName,
                                           new List <KeySchemaElement>
            {
                new KeySchemaElement {
                    AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, KeyType = KeyType.HASH
                },
                new KeySchemaElement {
                    AttributeName = GRAIN_TYPE_PROPERTY_NAME, KeyType = KeyType.RANGE
                }
            },
                                           new List <AttributeDefinition>
            {
                new AttributeDefinition {
                    AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S
                },
                new AttributeDefinition {
                    AttributeName = GRAIN_TYPE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S
                }
            }));
        }
Beispiel #24
0
        /// <summary>
        /// Initializes the storage provider.
        /// </summary>
        /// <param name="name">The name of this provider instance.</param>
        /// <param name="providerRuntime">A Orleans runtime object managing all storage providers.</param>
        /// <param name="config">Configuration info for this provider instance.</param>
        /// <returns>Completion promise for this operation.</returns>
        public virtual Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            Log = providerRuntime.GetLogger(GetType().FullName);
            var serializationManager = (SerializationManager)providerRuntime.ServiceProvider.GetService(typeof(SerializationManager));

            serializerSettings                      = OrleansJsonSerializer.GetDefaultSerializerSettings(serializationManager, providerRuntime.GrainFactory);
            serializerSettings.Formatting           = config.GetBoolProperty(OrleansJsonSerializer.IndentJsonProperty, false) ? Formatting.Indented : Formatting.None;
            serializerSettings.TypeNameHandling     = TypeNameHandling.None;
            serializerSettings.DefaultValueHandling = DefaultValueHandling.Include;
            serializerSettings.NullValueHandling    = NullValueHandling.Include;
            return(Task.CompletedTask);
        }
Beispiel #25
0
        /// <summary> Initialization function for this storage provider. </summary>
        /// <see cref="IProvider#Init"/>
        public async Task Init(string name, IProviderRuntime providerRuntime, IProviderConfiguration config)
        {
            serviceId = providerRuntime.ServiceId.ToString();
            Log       = providerRuntime.GetLogger("StorageProvider.SimpleSQLServerStorage." + serviceId);

            try
            {
                Name = name;
                this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(), config);

                if (!config.Properties.ContainsKey(CONNECTION_STRING) || string.IsNullOrWhiteSpace(config.Properties[CONNECTION_STRING]))
                {
                    throw new BadProviderConfigException($"Specify a value for: {CONNECTION_STRING}");
                }
                var connectionString = config.Properties[CONNECTION_STRING];
                sqlconnBuilder = new SqlConnectionStringBuilder(connectionString);

                //a validation of the connection would be wise to perform here
                var sqlCon = new SqlConnection(sqlconnBuilder.ConnectionString);
                await sqlCon.OpenAsync();

                sqlCon.Close();

                //initialize to use the default of JSON storage (this is to provide backwards compatiblity with previous version
                useJsonOrBinaryFormat = StorageFormatEnum.Binary;

                if (config.Properties.ContainsKey(USE_JSON_FORMAT_PROPERTY))
                {
                    if ("true".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase))
                    {
                        useJsonOrBinaryFormat = StorageFormatEnum.Json;
                    }

                    if ("both".Equals(config.Properties[USE_JSON_FORMAT_PROPERTY], StringComparison.OrdinalIgnoreCase))
                    {
                        useJsonOrBinaryFormat = StorageFormatEnum.Both;
                    }
                }

                if (config.Properties.ContainsKey(THROW_ON_DESERIALIZE_ERROR))
                {
                    if ("false".Equals(config.Properties[THROW_ON_DESERIALIZE_ERROR], StringComparison.OrdinalIgnoreCase))
                    {
                        throwOnDeserializeError = false;
                    }
                }
            }
            catch (Exception ex)
            {
                Log.Error((int)SimpleSQLServerProviderErrorCodes.SimpleSQLServerProvider_InitProvider, ex.ToString(), ex);
                throw;
            }
        }
        /// <summary> Initialization function for this storage provider. </summary>
        public async Task Init(CancellationToken ct)
        {
            var stopWatch = Stopwatch.StartNew();

            try
            {
                var initMsg = string.Format("Init: Name={0} ServiceId={1} Table={2} DeleteStateOnClear={3}",
                                            this.name, this.options.ServiceId, this.options.TableName, this.options.DeleteStateOnClear);

                this.jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(
                    OrleansJsonSerializer.GetDefaultSerializerSettings(this.typeResolver, this.grainFactory),
                    this.options.UseFullAssemblyNames, this.options.IndentJson, this.options.TypeNameHandling);
                this.options.ConfigureJsonSerializerSettings?.Invoke(this.jsonSettings);

                this.logger.LogInformation((int)ErrorCode.StorageProviderBase, $"AWS DynamoDB Grain Storage {this.name} is initializing: {initMsg}");

                this.storage = new DynamoDBStorage(this.logger, this.options.Service, this.options.AccessKey, this.options.SecretKey,
                                                   this.options.ReadCapacityUnits, this.options.WriteCapacityUnits, this.options.UseProvisionedThroughput);

                await storage.InitializeTable(this.options.TableName,
                                              new List <KeySchemaElement>
                {
                    new KeySchemaElement {
                        AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, KeyType = KeyType.HASH
                    },
                    new KeySchemaElement {
                        AttributeName = GRAIN_TYPE_PROPERTY_NAME, KeyType = KeyType.RANGE
                    }
                },
                                              new List <AttributeDefinition>
                {
                    new AttributeDefinition {
                        AttributeName = GRAIN_REFERENCE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S
                    },
                    new AttributeDefinition {
                        AttributeName = GRAIN_TYPE_PROPERTY_NAME, AttributeType = ScalarAttributeType.S
                    }
                },
                                              secondaryIndexes : null,
                                              ttlAttributeName : this.options.TimeToLive.HasValue?GRAIN_TTL_PROPERTY_NAME : null);

                stopWatch.Stop();
                this.logger.LogInformation((int)ErrorCode.StorageProviderBase,
                                           $"Initializing provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} took {stopWatch.ElapsedMilliseconds} Milliseconds.");
            }
            catch (Exception exc)
            {
                stopWatch.Stop();
                this.logger.LogError((int)ErrorCode.Provider_ErrorFromInit, $"Initialization failed for provider {this.name} of type {this.GetType().Name} in stage {this.options.InitStage} in {stopWatch.ElapsedMilliseconds} Milliseconds.", exc);
                throw;
            }
        }
Beispiel #27
0
        private Task Init(CancellationToken ct)
        {
            _jsonSettings = OrleansJsonSerializer.UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(_typeResolver, _grainFactory), false, false, null);

            var directory = new DirectoryInfo(_options.RootDirectory);

            if (!directory.Exists)
            {
                directory.Create();
            }

            return(Task.CompletedTask);
        }
Beispiel #28
0
        public JsonGrainStateSerializer(ITypeResolver typeResolver, IGrainFactory grainFactory, MongoDBGrainStorageOptions options)
        {
            var jsonSettings = OrleansJsonSerializer.GetDefaultSerializerSettings(typeResolver, grainFactory);

            options?.ConfigureJsonSerializerSettings?.Invoke(jsonSettings);
            this.serializer = JsonSerializer.Create(jsonSettings);

            if (options?.ConfigureJsonSerializerSettings == null)
            {
                //// https://github.com/OrleansContrib/Orleans.Providers.MongoDB/issues/44
                //// Always include the default value, so that the deserialization process can overwrite default
                //// values that are not equal to the system defaults.
                this.serializer.NullValueHandling    = NullValueHandling.Include;
                this.serializer.DefaultValueHandling = DefaultValueHandling.Populate;
            }
        }
        private Task Init(CancellationToken ct)
        {
            try
            {
                _jsonSettings = OrleansJsonSerializer
                                .UpdateSerializerSettings(OrleansJsonSerializer.GetDefaultSerializerSettings(_typeResolver, _grainFactory),
                                                          _options.UseFullAssemblyNames, _options.IndentJson, _options.TypeNameHandling);
                _dataManager = new GrainStateDataManager(_options);
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(Task.CompletedTask);
        }
        private T NewtonsoftJsonSerializeRoundtrip <T>(T obj)
        {
            var settings = OrleansJsonSerializer.GetDefaultSerializerSettings(this.HostedCluster.SerializationManager, this.GrainFactory);
            // http://james.newtonking.com/json/help/index.html?topic=html/T_Newtonsoft_Json_JsonConvert.htm
            string json  = Newtonsoft.Json.JsonConvert.SerializeObject(obj, settings);
            object other = Newtonsoft.Json.JsonConvert.DeserializeObject(json, obj.GetType(), settings);

#if NETSTANDARD_TODO
            // On .NET Standard, currently we need to manually fixup grain references.
            var otherAsRef = other as Orleans.Runtime.GrainReference;
            if (otherAsRef != null)
            {
                this.GrainFactory.BindGrainReference(otherAsRef);
            }
#endif
            return((T)other);
        }