public static async Task <CloudTable> CreateTableIfNotExistsAsync(string tableName) { // Retrieve storage account information from connection string. Microsoft.Azure.Cosmos.Table.CloudStorageAccount storageAccount = CreateStorageAccountFromConnectionString(storageConnectionString); // Create a table client for interacting with the table service CloudTableClient tableClient = storageAccount.CreateCloudTableClient(new TableClientConfiguration()); Console.WriteLine("Create a Table for the demo"); // Create a table client for interacting with the table service CloudTable table = tableClient.GetTableReference(tableName); if (await table.CreateIfNotExistsAsync()) { Console.WriteLine("Created Table named: {0}", tableName); } else { Console.WriteLine("Table {0} already exists", tableName); } Console.WriteLine(); return(table); }
public async Task OnPostAsync(string firstname, string lastname, IFormFile file) { CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); var sbc = storageAccount.CreateCloudBlobClient(); //Blob Containers var writeContainer = sbc.GetContainerReference("samples-images"); var readContainer = sbc.GetContainerReference("sample-images-sm"); await writeContainer.CreateIfNotExistsAsync(); await readContainer.CreateIfNotExistsAsync(); // Queue CloudQueueClient queueClient = storageAccount.CreateCloudQueueClient(); CloudQueue queue = queueClient.GetQueueReference("bjornosqueue"); await PublishToQueueAsync(queue, new Person(firstname, lastname)); PublishToBlobStorage(writeContainer, $"{firstname}_{lastname}.png", file); // De person die net is gepost zit nog in de queue deze moet nog door de azure function // naar table gestorage gezet worden Oftewel wij lopen hier in principe 1 post achter En // dat is prima voor test doeleinden var selectAllQuery = new TableQuery <Person>(); var account = CosmosCloudStorageAccount.Parse(connectionString); var client = account.CreateCloudTableClient(); var table = client.GetTableReference("persons"); Persons = table.ExecuteQuery(selectAllQuery).ToList(); }
/// <summary> /// Initializes a new instance of the <see cref="AzureTableRepository" /> class. /// </summary> /// <param name="connectionString">The connection string.</param> public AzureTableRepository(string connectionString) { CloudStorageAccount account = CloudStorageAccount.Parse(connectionString); _client = account.CreateCloudTableClient(); _tables = new ConcurrentDictionary <string, CloudTable>(); }
public CloudTable GetStorageTable(string tableName) { Microsoft.Azure.Cosmos.Table.CloudStorageAccount storageAccount = Microsoft.Azure.Cosmos.Table.CloudStorageAccount.Parse("UseDevelopmentStorage=true"); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); CloudTable table = tableClient.GetTableReference(tableName); table.CreateIfNotExists(); return(table); }
private static CloudTable CreateTableAsync() { var account = CosmosStorageAccount.Parse(_connection); var tableClient = account.CreateCloudTableClient(); var table = tableClient.GetTableReference("userdetails"); table.CreateIfNotExists(); return(table); }
public CommandAuditWriter(ICommandAuditOptions options = null) { auditContainer = new Lazy <CloudBlobContainer>(() => BlobCloudStorageAccount .Parse((options ?? CommandAuditOptions.Default).ConnectionString) .CreateCloudBlobClient().GetContainerReference(GetAuditContainerName(options))); auditTable = new Lazy <CloudTable>(() => TableCloudStorageAccount .Parse((options ?? CommandAuditOptions.Default).ConnectionString) .CreateCloudTableClient().GetTableReference(GetAuditTableName(options))); }
/// <summary> /// Set Table service properties /// </summary> /// <param name="account">Cloud storage account</param> /// <param name="properties">Service properties</param> /// <param name="options">Request options</param> /// <param name="operationContext">Operation context</param> public void SetStorageTableServiceProperties(XTable.ServiceProperties properties, XTable.TableRequestOptions options, XTable.OperationContext operationContext) { XTable.CloudStorageAccount account = StorageContext.TableStorageAccount; try { Task.Run(() => account.CreateCloudTableClient().SetServicePropertiesAsync(properties, options, operationContext)).Wait(); } catch (AggregateException e) when(e.InnerException is XTable.StorageException) { throw e.InnerException; } }
/// <summary> /// Get the Table service properties /// </summary> /// <param name="account">Cloud storage account</param> /// <param name="options">Request options</param> /// <param name="operationContext">Operation context</param> /// <returns>The service properties of the specified service type</returns> public XTable.ServiceProperties GetStorageTableServiceProperties(XTable.TableRequestOptions options, XTable.OperationContext operationContext) { XTable.CloudStorageAccount account = StorageContext.TableStorageAccount; try { return(account.CreateCloudTableClient().GetServicePropertiesAsync(options, operationContext).Result); } catch (AggregateException e) when(e.InnerException is XTable.StorageException) { throw e.InnerException; } }
public async Task <IBinding> TryCreateAsync(BindingProviderContext context) { var parameter = context.Parameter; var parameterName = context.Parameter.Name; var parameterType = context.Parameter.ParameterType; var attribute = parameter.GetCustomAttribute <GenesysAttribute>(); if (attribute == null) { return(null); } if (parameterType != typeof(string) && parameterType != typeof(IGenesysAccessToken)) { throw new InvalidOperationException("Can't bind entity to type '" + parameterType + "'."); } var connectionString = GetConnectionString(attribute.Connection); if (!TableStorageAccount.TryParse(connectionString, out TableStorageAccount tableStorageAccount)) { throw new InvalidOperationException($"Storage account connection string for '{IConfigurationExtensions.GetPrefixedConnectionStringName(attribute.Connection)}' is invalid"); } var tableClient = tableStorageAccount.CreateCloudTableClient(); var table = tableClient.GetTableReference(attribute.TokenTable ?? GenesysConfigNames.GenesysTokensTable); await table.CreateIfNotExistsAsync(); var tokenCtx = new GenesysTokenContext { TokenTable = table, ClientId = attribute.ClientId, ClientSecret = attribute.ClientSecret, Environment = attribute.Environment, }; IBinding binding = new GenesysAttributeBinding(parameterName, parameterType, _tokenProvider, tokenCtx); return(binding); }
static CloudStorageAccount CreateStorageAccountFromConnectionString() { CloudStorageAccount storageAccount; try { storageAccount = CloudStorageAccount.Parse(storageConnectionString); } catch (FormatException) { Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the application."); throw; } catch (ArgumentException) { Console.WriteLine("Invalid storage account information provided. Please confirm the AccountName and AccountKey are valid in the app.config file - then restart the sample."); Console.ReadLine(); throw; } return(storageAccount); }
public async Task InitializeAsync() { if (!string.IsNullOrEmpty(_functionsWorkerLanguage)) { Environment.SetEnvironmentVariable(RpcWorkerConstants.FunctionWorkerRuntimeSettingName, _functionsWorkerLanguage); } IConfiguration configuration = TestHelpers.GetTestConfiguration(); string connectionString = configuration.GetWebJobsConnectionString(ConnectionStringNames.Storage); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); QueueClient = storageAccount.CreateCloudQueueClient(); BlobClient = storageAccount.CreateCloudBlobClient(); TableStorageAccount tableStorageAccount = TableStorageAccount.Parse(connectionString); TableClient = tableStorageAccount.CreateCloudTableClient(); await CreateTestStorageEntities(); // ApiHubTestHelper.SetDefaultConnectionFactory(); //ILoggerProviderFactory loggerProviderFactory = new TestLoggerProviderFactory(LoggerProvider); // Reset the timer logs first, since one of the tests will // be checking them TestHelpers.ClearFunctionLogs("TimerTrigger"); TestHelpers.ClearFunctionLogs("ListenerStartupException"); Host = new HostBuilder() .ConfigureDefaultTestWebScriptHost(webjobsBuilder => { webjobsBuilder.AddAzureStorage(); // This needs to added manually at the ScriptHost level, as although FunctionMetadataManager is available through WebHost, // it needs to change the services during its lifetime. webjobsBuilder.Services.AddSingleton <IFunctionMetadataManager, FunctionMetadataManager>(); }, o => { o.ScriptPath = _rootPath; o.LogPath = TestHelpers.GetHostLogFileDirectory().Parent.FullName; }, runStartupHostedServices: true) .ConfigureServices(services => { services.Configure <ScriptJobHostOptions>(o => { o.FileLoggingMode = FileLoggingMode.Always; if (_functions != null) { o.Functions = _functions; } }); if (_proxyClient != null) { services.AddSingleton <ProxyClientExecutor>(_proxyClient); } // Shared memory data transfer if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { services.AddSingleton <IMemoryMappedFileAccessor, MemoryMappedFileAccessorWindows>(); } else { services.AddSingleton <IMemoryMappedFileAccessor, MemoryMappedFileAccessorUnix>(); } services.AddSingleton <ISharedMemoryManager, SharedMemoryManager>(); ConfigureServices(services); }) .ConfigureLogging(b => { b.AddProvider(LoggerProvider); }) .Build(); JobHost = Host.GetScriptHost(); if (_startHost) { JobHost.HostStarted += (s, e) => _hostStartedEvent.Set(); await Host.StartAsync(); _hostStartedEvent.Wait(TimeSpan.FromSeconds(30)); } }
public static async Task <HttpResponseMessage> Run( [HttpTrigger(AuthorizationLevel.Anonymous, "get", "post", Route = null)] HttpRequest req, [Table("Users")] CloudTable UserTable, ILogger log) { log.LogInformation("C# HTTP trigger function processed a request."); //string valueToReturn; //var customresponse = new HttpRequestMessage(); // var codereturntoclient = new ObjectResult(""); /*string signInName = req.Query["signInName"]; * string password = req.Query["password"]; //"Nelite1234";//req.Query["password"]; */ string requestBody = await new StreamReader(req.Body).ReadToEndAsync(); //dynamic data = await req.Content.ReadAsAsync<User>(); dynamic data = JsonConvert.DeserializeObject(requestBody); log.LogInformation($" body: {data}"); string SignInName = data?.SignInName; log.LogInformation($"SignInName : {SignInName}"); string password = data?.password; log.LogInformation($"password : {password}"); /* string SignInName = data?.SignInName; * string password = data?.password;*/ //emailAdress = emailAdress ?? data?.emailAdress; //password = password ?? data?.password; // string enc = Encryptor.MD5Hash(password); var userinfo = new User(SignInName, password) { SignInName = SignInName ?? data?.SignInName, //password =Encryptor.MD5Hash(password ?? data?.password) password = Encryptor.MD5Hash(password ?? data.password) //password ?? data?.password }; /*string messagelog2 = $"user {userinfo.password} exists"; * var serializedUser2 = JsonConvert.SerializeObject(messagelog2); * return new OkObjectResult(serializedUser2);*/ string accountName = "oneeappstorage"; string accountKey = "RdSHMEZ6ODYs8Q7srEiHoFeF3FUFf00qYoLxzCV1DKQ9iQB79QsYYF6l3YnVv0b1OJwhfT99BsAh6B3ApAemUw=="; var creds = new Microsoft.Azure.Cosmos.Table.StorageCredentials(accountName, accountKey); var account = new Microsoft.Azure.Cosmos.Table.CloudStorageAccount(creds, useHttps: true); // Retrieve the role assignments table var client = account.CreateCloudTableClient(); var table = client.GetTableReference("Users"); var entities = table.ExecuteQuery(new TableQuery <UserEntity>().Where( TableQuery.CombineFilters( TableQuery.GenerateFilterCondition("Email", QueryComparisons.Equal, userinfo.SignInName), TableOperators.And, TableQuery.GenerateFilterCondition("UserPassword", QueryComparisons.Equal, userinfo.password)))).ToList(); var queryResult = table.ExecuteQuerySegmentedAsync(new TableQuery <UserEntity>(), null ).Result.ToList(); //string messagelog; if (entities.Count() > 0) { userinfo.UserExist = true; // codereturntoclient.Value = "User exists"; //codereturntoclient.StatusCode = StatusCodes.Status200OK; //messagelog = $"user {userinfo.emailAdress} exists"; //return (IActionResult)customresponse.CreateResponse(HttpStatusCode.OK); //customresponse.CreateResponse(HttpStatusCode.OK); } else { userinfo.UserExist = false; // codereturntoclient.Value = "User doesn't exist"; //codereturntoclient.StatusCode = StatusCodes.Status404NotFound; //messagelog = $"User {userinfo.emailAdress} doesn't exist"; //customresponse.CreateResponse(HttpStatusCode.NotFound); } /*Microsoft Doc ------------------------------------------------------------------------------- * TableQuery<UserEntity> rangeQuery = new TableQuery<UserEntity>().Where( * TableQuery.CombineFilters( * TableQuery.GenerateFilterCondition("Email", QueryComparisons.Equal, * userinfo.emailAdress), * TableOperators.And, * TableQuery.GenerateFilterCondition("UserPassword", QueryComparisons.Equal, * userinfo.password))); * //var ExecutionQuery = UserTable.ExecuteQuerySegmentedAsync(rangeQuery,null); * var ExecutionQuery = UserTable.ExecuteQuery(rangeQuery); * UserEntity user = ExecutionQuery as UserEntity; * var list = ExecutionQuery.ToList(); * * if(ExecutionQuery.Count()>0) * { * foreach (UserEntity entity in * ExecutionQuery) * { * log.LogInformation( * $"{entity.Email}\t{entity.CIN}\t{entity.Timestamp}\t{entity.ID_Partenaire}"); * * * * } * } */ /*Microsoft Doc -------------------------------------------------------------------------------*/ //var results = Storage.ValidateUser(userinfo.emailAdress); /*TableQuery code --------------------------------------------------------------------------------------------------------------- * * * var tableQuery = new TableQuery<UserEntity>(); * //var query = TableQuery.GenerateFilterCondition(nameof(UserEntity.EMAIL), QueryComparisons.Equal, userinfo.emailAdress); * //var tableUserQuery = new TableQuery().Where("EMAIL == ?string? && USERPASSWORD == ?string?", userinfo.emailAdress, userinfo.password); * * tableQuery.SelectColumns = new List<string> { nameof(UserEntity.EMAIL)}; * tableQuery.FilterString = TableQuery.GenerateFilterCondition(nameof(UserEntity.EMAIL), QueryComparisons.Equal,userinfo.emailAdress); * * //var result = UserTable.ExecuteQuerySegmentedAsync(tableQuery, null); * var res = UserTable.ExecuteQuery(tableQuery).ToList(); * * * /*TableQuery code ---------------------------------------------------------------------------------------------------------------*/ // return new OkObjectResult(res); //var res = UserTable.ExecuteQuery(tableQuery); //string Uservalidation = Storage.ValidateUserV2(userinfo.emailAdress); /*------------------------------------------------------------------------------------------------------------ * string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; * string sourceContainerName = ConfigurationManager.AppSettings["azure-webjobs-hosts"]; * string sourceBlobFileName = "Users.xlsx"; * _ = new GetExcelBlob(); * _ = GetExcelBlob.GetExcelBlobData(connectionString, sourceBlobFileName, sourceContainerName); */ /*static async Task<IEnumerable<T>> GetAll<T>(string tableName) where T : class * { * * var table = this.GetCloudTable(tableName); * TableContinuationToken token = null; * do * { * var q = new TableQuery<T>(); * var queryResult = await table.ExecuteQuerySegmentedAsync(q, token); * foreach (var item in queryResult.Results) * { * yield return item; * } * token = queryResult.ContinuationToken; * } * while (token != null); * }*/ /*Azure Storage -------------------------------------------------------------------------------------- * * * * * string connectionString = ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString; * string sourceContainerName = ConfigurationManager.AppSettings["azure-webjobs-hosts"]; * string sourceBlobFileName = "Users.xlsx"; * _ = new ExcelReader(); * _ = ExcelReader.GetExcelBlobData(sourceBlobFileName, connectionString, sourceContainerName); * * * * string connectionString = CloudConfigurationManager.GetSetting("StorageConnectionString"); //blob connection string * string sourceContainerName = ConfigurationManager.AppSettings["sourcecontainerName"]; //source blob container name * string sourceBlobFileName = "test.xlsx"; //source blob name * _ = new ExcelReader(); * _ = ExcelReader.GetExcelBlobData(sourceBlobFileName, connectionString, sourceContainerName); * * /*Azure Storage ------------------------------*/ var serializedUser = JsonConvert.SerializeObject(userinfo, Formatting.Indented); /* string responseMessage = string.IsNullOrEmpty(serializedUser) * ? "This HTTP triggered function executed successfully. Pass a name in the query string or in the request body for a personalized response." * : $"Hello, {serializedUser}. This HTTP triggered function executed successfully.";*/ //return codereturntoclient; //return customresponse. // return new ObjectResult(serializedUser); log.LogInformation("C# SEND HTTP RESPONSE"); log.LogInformation($"serializedUser: {serializedUser}"); //return new ObjectResult(serializedUser); //log.LogInformation("C# END HTTP REQUEST"); return(new HttpResponseMessage(HttpStatusCode.OK) { Content = new StringContent(serializedUser, Encoding.UTF8, "application/json") }); }
public async Task InitializeAsync() { string nowString = DateTime.UtcNow.ToString("yyMMdd-HHmmss"); string GetDestPath(int counter) { return(Path.Combine(Path.GetTempPath(), "FunctionsE2E", $"{nowString}_{counter}")); } // Prevent collisions. int i = 0; _copiedRootPath = GetDestPath(i++); while (Directory.Exists(_copiedRootPath)) { _copiedRootPath = GetDestPath(i++); } FileUtility.CopyDirectory(_rootPath, _copiedRootPath); var extensionsToInstall = GetExtensionsToInstall(); if (extensionsToInstall != null && extensionsToInstall.Length > 0) { TestFunctionHost.WriteNugetPackageSources(_copiedRootPath, "http://www.myget.org/F/azure-appservice/api/v2", "https://www.myget.org/F/azure-appservice-staging/api/v2", "https://api.nuget.org/v3/index.json"); var options = new OptionsWrapper <ScriptJobHostOptions>(new ScriptJobHostOptions { RootScriptPath = _copiedRootPath }); var manager = new ExtensionsManager(options, NullLogger <ExtensionsManager> .Instance, new TestExtensionBundleManager()); await manager.AddExtensions(extensionsToInstall); } string logPath = Path.Combine(Path.GetTempPath(), @"Functions"); if (!string.IsNullOrEmpty(_functionsWorkerRuntime)) { Environment.SetEnvironmentVariable(RpcWorkerConstants.FunctionWorkerRuntimeSettingName, _functionsWorkerRuntime); Environment.SetEnvironmentVariable(RpcWorkerConstants.FunctionsWorkerProcessCountSettingName, _workerProcessCount.ToString()); } if (!string.IsNullOrEmpty(_functionsWorkerRuntimeVersion)) { Environment.SetEnvironmentVariable(RpcWorkerConstants.FunctionWorkerRuntimeVersionSettingName, _functionsWorkerRuntimeVersion); } FunctionsSyncManagerMock = new Mock <IFunctionsSyncManager>(MockBehavior.Strict); FunctionsSyncManagerMock.Setup(p => p.TrySyncTriggersAsync(It.IsAny <bool>())).ReturnsAsync(new SyncTriggersResult { Success = true }); Host = new TestFunctionHost(_copiedRootPath, logPath, configureScriptHostWebJobsBuilder: webJobsBuilder => { ConfigureScriptHost(webJobsBuilder); }, configureScriptHostServices: s => { s.AddSingleton <IFunctionsSyncManager>(_ => FunctionsSyncManagerMock.Object); s.AddSingleton <IMetricsLogger>(_ => MetricsLogger); }, configureWebHostServices: s => { s.AddSingleton <IEventGenerator>(_ => EventGenerator); ConfigureWebHost(s); }); string connectionString = Host.JobHostServices.GetService <IConfiguration>().GetWebJobsConnectionString(ConnectionStringNames.Storage); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); QueueClient = storageAccount.CreateCloudQueueClient(); BlobClient = storageAccount.CreateCloudBlobClient(); TableStorageAccount tableStorageAccount = TableStorageAccount.Parse(connectionString); TableClient = tableStorageAccount.CreateCloudTableClient(); await CreateTestStorageEntities(); MasterKey = await Host.GetMasterKeyAsync(); }
public async Task InitializeAsync() { if (!string.IsNullOrEmpty(_functionsWorkerLanguage)) { Environment.SetEnvironmentVariable(RpcWorkerConstants.FunctionWorkerRuntimeSettingName, _functionsWorkerLanguage); } IConfiguration configuration = TestHelpers.GetTestConfiguration(); string connectionString = configuration.GetWebJobsConnectionString(ConnectionStringNames.Storage); CloudStorageAccount storageAccount = CloudStorageAccount.Parse(connectionString); QueueClient = storageAccount.CreateCloudQueueClient(); BlobClient = storageAccount.CreateCloudBlobClient(); TableStorageAccount tableStorageAccount = TableStorageAccount.Parse(connectionString); TableClient = tableStorageAccount.CreateCloudTableClient(); await CreateTestStorageEntities(); // ApiHubTestHelper.SetDefaultConnectionFactory(); //ILoggerProviderFactory loggerProviderFactory = new TestLoggerProviderFactory(LoggerProvider); // Reset the timer logs first, since one of the tests will // be checking them TestHelpers.ClearFunctionLogs("TimerTrigger"); TestHelpers.ClearFunctionLogs("ListenerStartupException"); Host = new HostBuilder() .ConfigureDefaultTestWebScriptHost(webjobsBuilder => { webjobsBuilder.AddAzureStorage(); }, o => { o.ScriptPath = _rootPath; o.LogPath = TestHelpers.GetHostLogFileDirectory().Parent.FullName; }, runStartupHostedServices: true) .ConfigureServices(services => { services.Configure <ScriptJobHostOptions>(o => { o.FileLoggingMode = FileLoggingMode.Always; if (_functions != null) { o.Functions = _functions; } }); if (_proxyClient != null) { services.AddSingleton <ProxyClientExecutor>(_proxyClient); } ConfigureServices(services); }) .ConfigureLogging(b => { b.AddProvider(LoggerProvider); }) .Build(); JobHost = Host.GetScriptHost(); if (_startHost) { JobHost.HostStarted += (s, e) => _hostStartedEvent.Set(); await Host.StartAsync(); _hostStartedEvent.Wait(TimeSpan.FromSeconds(30)); } }
private static void Main(string[] args) { string configPath = "config.json"; if (!File.Exists(configPath)) { Console.WriteLine("================================"); Console.WriteLine("There is no config. Please select the transport you would like:"); Console.WriteLine("[R]uffles"); Console.WriteLine("[U]net"); ConsoleKey key = ConsoleKey.Escape; do { key = Console.ReadKey(true).Key; }while (key != ConsoleKey.R && key != ConsoleKey.U); if (key == ConsoleKey.U) { Transport = new UnetTransport(); Console.WriteLine("================================"); Console.WriteLine("Please select a template for the UNET config file:"); Console.WriteLine("[M]LAPI - Copies the same UNET settings as the MLAPI uses by default"); Console.WriteLine("[H]LAPI - Copies the same UNET settings as the HLAPI uses by default"); Console.WriteLine("[E]mpty - Default UNET settings"); key = ConsoleKey.Escape; do { key = Console.ReadKey(true).Key; }while (key != ConsoleKey.M && key != ConsoleKey.H && key != ConsoleKey.E); if (key == ConsoleKey.M) { UnetTransport.UnetConfig config = (UnetTransport.UnetConfig)Transport.GetConfig(); config.ConnectionConfig.AddChannel(QosType.ReliableFragmentedSequenced); config.ConnectionConfig.AddChannel(QosType.ReliableSequenced); config.ConnectionConfig.AddChannel(QosType.UnreliableSequenced); config.ConnectionConfig.AddChannel(QosType.Unreliable); config.ConnectionConfig.AddChannel(QosType.Unreliable); config.ConnectionConfig.AddChannel(QosType.Reliable); config.ConnectionConfig.AddChannel(QosType.UnreliableSequenced); config.ConnectionConfig.AddChannel(QosType.ReliableSequenced); config.ConnectionConfig.AddChannel(QosType.ReliableSequenced); config.ConnectionConfig.AddChannel(QosType.UnreliableSequenced); Config = new RelayConfig() { Transport = TransportType.UNET, AllowTemporaryAlloc = true, MaxTemporaryAlloc = 1024 * 16, BandwidthGracePrediodLength = 60 * 2, BandwidthLimit = -1, EnableRuntimeMetaLogging = true, GracePeriodBandwidthLimit = -1, TransportConfig = config, BufferSize = 1024 * 8, ListenPort = 8888 }; } else if (key == ConsoleKey.H) { UnetTransport.UnetConfig config = (UnetTransport.UnetConfig)Transport.GetConfig(); config.ConnectionConfig.AddChannel(QosType.ReliableSequenced); config.ConnectionConfig.AddChannel(QosType.Unreliable); Config = new RelayConfig() { Transport = TransportType.UNET, BufferSize = 1024 * 8, AllowTemporaryAlloc = true, BandwidthGracePrediodLength = 60 * 2, BandwidthLimit = -1, EnableRuntimeMetaLogging = true, GracePeriodBandwidthLimit = -1, ListenPort = 8888, MaxTemporaryAlloc = 1024 * 16, TransportConfig = config }; } else if (key == ConsoleKey.E) { UnetTransport.UnetConfig config = (UnetTransport.UnetConfig)Transport.GetConfig(); Config = new RelayConfig() { Transport = TransportType.UNET, BufferSize = 1024 * 8, AllowTemporaryAlloc = true, BandwidthGracePrediodLength = 60 * 2, BandwidthLimit = -1, EnableRuntimeMetaLogging = true, GracePeriodBandwidthLimit = -1, ListenPort = 8888, MaxTemporaryAlloc = 1024 * 16, TransportConfig = config }; } } else if (key == ConsoleKey.R) { Transport = new RufflesTransport(); RufflesTransport.RufflesConfig config = (RufflesTransport.RufflesConfig)Transport.GetConfig(); Config = new RelayConfig() { Transport = TransportType.Ruffles, AllowTemporaryAlloc = true, BandwidthGracePrediodLength = 60 * 2, BandwidthLimit = -1, BufferSize = 1024 * 8, EnableRuntimeMetaLogging = true, GracePeriodBandwidthLimit = -1, ListenPort = 8888, MaxTemporaryAlloc = 1024 * 16, TransportConfig = config }; } if (Config != null) { object config = Transport.BeforeSerializeConfig(Config); string serializedJson = JsonConvert.SerializeObject(config, Formatting.Indented); File.WriteAllText(configPath, Transport.ProcessSerializedJson(serializedJson)); } else { // TODO: Something went wrong. No config?? } } else { try { Config = JsonConvert.DeserializeObject <RelayConfig>(File.ReadAllText(configPath)); switch (Config.Transport) { case TransportType.Ruffles: Transport = new RufflesTransport(); break; case TransportType.UNET: Transport = new UnetTransport(); break; } // Post deserialization job Config = (RelayConfig)Transport.AfterDeserializedConfig(Config); } catch (Exception e) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[ERROR] Error parsing config file: " + e); Console.Read(); Environment.Exit(1); return; } } Program.MESSAGE_BUFFER = new byte[Config.BufferSize]; if (string.IsNullOrWhiteSpace(Config.IpAddress)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[ERROR] Set the IpAddress of the relay in the config file."); Environment.Exit(1); } if (string.IsNullOrWhiteSpace(Config.AzureTableConnectionString)) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("[ERROR] Set the connection string of the rooms Azure table in the config file."); Environment.Exit(1); } CloudStorageAccount storageAccount = CloudStorageAccount.Parse(Config.AzureTableConnectionString); CloudTableClient tableClient = storageAccount.CreateCloudTableClient(); roomsTable = tableClient.GetTableReference("rooms"); try { Console.WriteLine("[INFO] Starting server..."); Transport.Start(Config.TransportConfig); Console.WriteLine("[INFO] Server started!"); } catch (DllNotFoundException e) { Console.WriteLine("[FATAL] Could not locate one or more shared libraries! Message: \n" + e); } catch (Exception e) { Console.WriteLine("[FATAL] An unexpected error occurred! Message: \n" + e); } Stopwatch watch = new Stopwatch(); while (true) { try { watch.Restart(); RunLoop(); int timeBetweenTicks = (int)((1f / Config.TicksPerSecond) * 1000f); int timeToSleep = timeBetweenTicks - (int)watch.ElapsedMilliseconds; if (timeToSleep > 0) { Thread.Sleep(timeToSleep); } } catch (Exception e) { Console.WriteLine("[ERROR] Exception during loop: " + e); } } }
public AzureTables(string connectionString) { stAcc = Microsoft.Azure.Cosmos.Table.CloudStorageAccount.Parse(connectionString); tblClient = stAcc.CreateCloudTableClient(new TableClientConfiguration()); }