private int executeUpdate(SyncLogger logger, SyncRegionUpdate update) { logger.log(2, update.Statement); SQLiteCommand cmd = new SQLiteCommand(connection); cmd.CommandText = update.Statement; if (update.Executions == null) { return cmd.ExecuteNonQuery(); } else { int rowsAffected = 0; foreach (ParameterSet set in update.Executions) { logger.log(3, string.Join(",", set)); cmd.Parameters.Clear(); foreach (string param in set) { SQLiteParameter p = new SQLiteParameter(); p.Value = param; cmd.Parameters.Add(p); } rowsAffected += cmd.ExecuteNonQuery(); } return rowsAffected; } }
public bool NextSyncStep(SyncLogger logger) { if (currentRegionIsComplete) { if (!regionEnum.MoveNext()) { return false; } } SyncRegion region = regionEnum.Current; string localVersion = queryLocalVersion(region.Id); logger.log(1, "Requesting updates for region '" + region.Id + "', localVersion = " + localVersion); SyncRegionUpdates updates; updates = service.GetSyncRegionUpdates(region.Id, localVersion); if (updates.Sql != null) { foreach (SyncRegionUpdate update in updates.Sql) { executeUpdate(logger, update); } } updateLocalVersion(region.Id, updates.Version); currentRegionIsComplete = updates.Complete; logger.log(1, " now at version " + updates.Version + " [complete=" + updates.Complete + "]"); return true; }
private int executeUpdate(SyncLogger logger, SyncRegionUpdate update) { logger.log(2, update.Statement); SQLiteCommand cmd = new SQLiteCommand(connection); cmd.CommandText = update.Statement; if (update.Executions == null) { return(cmd.ExecuteNonQuery()); } else { int rowsAffected = 0; foreach (ParameterSet set in update.Executions) { logger.log(3, string.Join(",", set)); cmd.Parameters.Clear(); foreach (string param in set) { SQLiteParameter p = new SQLiteParameter(); p.Value = param; cmd.Parameters.Add(p); } rowsAffected += cmd.ExecuteNonQuery(); } return(rowsAffected); } }
public async Task <PropertySyncFinalResponse> ExecuteSyncProcess(int siteId) { var response = new PropertySyncFinalResponse(); var landlordsReponse = await UpdateLandlordInformationForSite(siteId); SyncLogger.WriteLog("Landlord information has been imported successfully"); var propertiesResponse = await UpdatePropertiesInformationForSite(siteId); SyncLogger.WriteLog("Properties information has been imported successfully"); var tenantsResponse = await UpdateTenantInformationForSite(siteId); SyncLogger.WriteLog("Tenant information has been imported successfully"); response.SyncedTenants = tenantsResponse; response.SyncedLandlords = landlordsReponse; response.SyncedProperties = propertiesResponse; var itemsToSync = PropertySyncItemsResponse.MapAll(tenantsResponse, SyncEntityTypeEnum.Tenants); itemsToSync.AddRange(PropertySyncItemsResponse.MapAll(landlordsReponse, SyncEntityTypeEnum.Landlords)); itemsToSync.AddRange(PropertySyncItemsResponse.MapAll(propertiesResponse, SyncEntityTypeEnum.Properties)); response.Responses = itemsToSync; SyncLogger.WriteLog("Responses has been mapped correctly"); return(response); }
public async Task Trigger_Create_One() { var dbName = HelperDatabase.GetRandomName("tcp_lo_"); await HelperDatabase.CreateDatabaseAsync(ProviderType.Sql, dbName, true); var cs = HelperDatabase.GetConnectionString(ProviderType.Sql, dbName); var sqlProvider = new SqlSyncProvider(cs); // Create default table var ctx = new AdventureWorksContext((dbName, ProviderType.Sql, sqlProvider), true, false); await ctx.Database.EnsureCreatedAsync(); var options = new SyncOptions(); var setup = new SyncSetup(new string[] { "SalesLT.Product" }); // 1) create a console logger //var loggerFactory = LoggerFactory.Create(builder => { builder.AddDebug().SetMinimumLevel(LogLevel.Debug); }); //var logger = loggerFactory.CreateLogger("Dotmim.Sync"); var logger = new SyncLogger().AddDebug().SetMinimumLevel(LogLevel.Debug); options.Logger = logger; var remoteOrchestrator = new RemoteOrchestrator(sqlProvider, options); var scopeInfo = await remoteOrchestrator.GetServerScopeInfoAsync(setup); var onCreating = 0; var onCreated = 0; var onDropping = 0; var onDropped = 0; remoteOrchestrator.OnTriggerCreating(tca => onCreating++); remoteOrchestrator.OnTriggerCreated(tca => onCreated++); remoteOrchestrator.OnTriggerDropping(tca => onDropping++); remoteOrchestrator.OnTriggerDropped(tca => onDropped++); var isCreated = await remoteOrchestrator.CreateTriggerAsync(scopeInfo, "Product", "SalesLT", DbTriggerType.Insert); Assert.True(isCreated); Assert.Equal(1, onCreating); Assert.Equal(1, onCreated); Assert.Equal(0, onDropping); Assert.Equal(0, onDropped); // Check using (var c = new SqlConnection(cs)) { await c.OpenAsync().ConfigureAwait(false); var check = await SqlManagementUtils.GetTriggerAsync(c, null, "Product_insert_trigger", "SalesLT").ConfigureAwait(false); Assert.Single(check.Rows); c.Close(); } HelperDatabase.DropDatabase(ProviderType.Sql, dbName); }
public SyncRoom(string code) { this.Logger = new SyncLogger("Room " + code, ConsoleColor.Cyan); this.Services = new List <SyncService>(); this.RoomCode = code; this.CurrentQueue = new PartialQueue(); this.likes = 0; Logger.Log("initialized."); }
static RecievedCommandInterpreter() { Logger = new SyncLogger("CommandInterpreter", ConsoleColor.Green); RegisteredInterpreters = new Dictionary <string, Action <dynamic, SyncService, SyncRoom> >(); // register interpreter modules RegisterCommandInterpreter(CommandType.ADDLIKE.Value, OnAddLike); RegisterCommandInterpreter(CommandType.REGISTERUSER.Value, OnRegisterUser); RegisterCommandInterpreter(CommandType.LOGINUSER.Value, OnLoginUser); RegisterCommandInterpreter(CommandType.MODIFYQUEUE.Value, OnModifyQueue); RegisterCommandInterpreter(CommandType.UPGRADEUSERPERMISSIONS.Value, OnUpgradeUserPermissions); RegisterCommandInterpreter(CommandType.SYNCSTATE.Value, OnSyncState); RegisterCommandInterpreter(CommandType.CHAT.Value, OnChat); RegisterCommandInterpreter(CommandType.KICKUSER.Value, OnKickUser); RegisterCommandInterpreter(CommandType.SENDUSERLIST.Value, OnUserListRequested); RegisterCommandInterpreter(CommandType.UPDATESTATUS.Value, OnStatusUpdate); RegisterCommandInterpreter(CommandType.UPDATEUSERNAME.Value, OnUsernameUpdate); }
public async Task <List <PropertySyncItemsResponse> > SyncImportedTenantsToWarehouseStore(int siteId, List <PTenant> tenants) { //Prepare the request as JSON var request = JSerializer.Serialize(new PTenantResponse() { Tenants = tenants }); var content = new StringContent(request, Encoding.UTF8, "application/json"); //Send the request to receive the Response var response = await Client.PostAsync("api/warehouse-sync/sync-tenants/" + GanedataGlobalConfigurations.WarehouseSyncSiteId, content); if (response.StatusCode != System.Net.HttpStatusCode.OK) { SyncLogger.WriteLog("Unexpected response from api : " + response.StatusCode + " : " + response.ReasonPhrase); } return(new List <PropertySyncItemsResponse>()); }
public void TestSyncLogger() { var writer = new LogWriterMock(); var logger = new SyncLogger(writer); writer.IsInitialized.Should().BeFalse("the writer should not initialize before the logger"); writer.LoggedEntries.Any().Should().BeFalse("no entries should be logged before initialization"); logger.Initialize(new InitializeContextMock(this.app)); writer.IsInitialized.Should().BeTrue("the writer should be initialized during the logger's initialization"); writer.LoggedEntries.Any().Should().BeFalse("no entries should be logged just after initialization"); string message = "Message"; Exception ex = new ArgumentException("Test"); this.app.GetLog().Info("Message", ex); writer.LoggedEntries.Count().Should().Be(1, "writer should have 1 entry passed in to it"); writer.LoggedEntries.Single().Message.Should().Be(message, "the logged message should be the same as the passed in message"); writer.LoggedEntries.Single().Exception.Should().Be(ex, "the logged exception should be the same as the passed in exception"); logger.Uninitialize(); this.app.Stop(); writer.IsInitialized.Should().BeFalse("the writer should be uninitialized during the logger's uninitialization"); }
public bool NextSyncStep(SyncLogger logger) { if (currentRegionIsComplete) { if (!regionEnum.MoveNext()) { return(false); } } SyncRegion region = regionEnum.Current; string localVersion = queryLocalVersion(region.Id); logger.log(1, "Requesting updates for region '" + region.Id + "', localVersion = " + localVersion); SyncRegionUpdates updates; updates = service.GetSyncRegionUpdates(region.Id, localVersion); if (updates.Sql != null) { foreach (SyncRegionUpdate update in updates.Sql) { executeUpdate(logger, update); } } updateLocalVersion(region.Id, updates.Version); currentRegionIsComplete = updates.Complete; logger.log(1, " now at version " + updates.Version + " [complete=" + updates.Complete + "]"); return(true); }
public async Task ImportDataFromSites() { try { var syncHistory = new PSyncHistory { SyncStartTime = DateTime.UtcNow }; var importResponse = await SiteSyncService.ExecuteSyncProcess(GanedataGlobalConfigurations.WarehouseSyncSiteId); syncHistory.ImportCompletedTime = DateTime.UtcNow; SyncLogger.WriteLog("ImportDataFromSites > ExecuteSyncProcess completed successfully"); syncHistory.TenantsSynced = importResponse.SyncedTenants.Count(); syncHistory.LandlordsSynced = importResponse.SyncedLandlords.Count(); syncHistory.PropertiesSynced = importResponse.SyncedProperties.Count(); await SyncServiceHelper.SyncImportedLandlordsToWarehouseStore(GanedataGlobalConfigurations.WarehouseSyncSiteId, importResponse.SyncedLandlords); SyncLogger.WriteLog("Landlords sent to warehouse store successfully :" + syncHistory.LandlordsSynced); foreach (var item in importResponse.SyncedLandlords) { //send info to web service and update locally as synced SiteSyncService.UpdateLandlordAsSynced(item.SiteId, item.LandlordCode); } await SyncServiceHelper.SyncImportedPropertiesToWarehouseStore(GanedataGlobalConfigurations.WarehouseSyncSiteId, importResponse.SyncedProperties); SyncLogger.WriteLog("Properties sent to warehouse store successfully: " + syncHistory.PropertiesSynced); foreach (var item in importResponse.SyncedProperties) { SiteSyncService.UpdatePropertyAsSynced(item.SiteId, item.PropertyCode); } var tenantBatches = importResponse.SyncedTenants.Batches(500); foreach (var batch in tenantBatches) { await SyncServiceHelper.SyncImportedTenantsToWarehouseStore(GanedataGlobalConfigurations.WarehouseSyncSiteId, batch.ToList()); } SyncLogger.WriteLog("Tenants sent to warehouse store successfully: " + syncHistory.TenantsSynced); foreach (var item in importResponse.SyncedTenants) { //send info to web service and update locally as synced SiteSyncService.UpdateTenantAsSynced(item.SiteId, item.TenantCode); } //## BELOW CODE MAY PROCESS NONE MOSTLY, BUT THIS WILL MAKE SURE ANY FAILED RECORDS WHICH ARE NOT SYNCED YET, WILL BE SENT AGAIN FOR SYNC Thread.Sleep(25000); Thread.CurrentThread.IsBackground = true; SyncLogger.WriteLog("Executing post sync process ExportSyncedItemsOnly."); await ExportSyncedItemsOnly(); syncHistory.SyncCompletedTime = DateTime.UtcNow; SiteSyncService.AddSyncHistory(syncHistory); } catch (Exception ex) { SyncLogger.WriteLog("Error Occurred : " + ex.Message + "\nTrace" + ex.StackTrace); } }
static DatabaseConnector() { Logger = new SyncLogger("DatabaseConnector", ConsoleColor.Magenta); connectionString = ConfigManager.Config.SQLConnectionString.Replace("{userid}", ConfigManager.Config.DBUsername).Replace("{pwd}", ConfigManager.Config.DBPassword); }
public static void Start() { Logger = new SyncLogger("Server", ConsoleColor.Red); rooms = new List <SyncRoom>(); httpsv = new HttpServer(ConfigManager.Config.Port); // Set the document root path. httpsv.RootPath = Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location), ConfigManager.Config.HTTPRelativeBasePath); var timer = new System.Threading.Timer((e) => { for (int i = 0; i < rooms.Count; ++i) { if (rooms[i].ActiveUsers == 0) { Logger.Log("[Cleanup] Deleting inactive room {0}.", rooms[i].RoomCode); DeleteRoom(rooms[i].RoomCode); } } }, null, 0, (int)TimeSpan.FromMinutes(1).TotalMilliseconds); // Set the HTTP GET request event. httpsv.OnGet += (sender, e) => { var req = e.Request; var res = e.Response; var path = req.RawUrl; if (path == "/roomcodeVer") { if (req.Headers.Get("x-verify-roomcode") != null) { var code = req.Headers.Get("x-verify-roomcode"); if (code.Length > 6) { code = code.Substring(code.Length - 6); } if (GetRoomByCode(code) != null) { res.StatusCode = 200; res.AppendHeader("x-verify-roomcode", "exists"); res.WriteContent(Encoding.UTF8.GetBytes(code)); return; } else { res.StatusCode = 200; res.AppendHeader("x-verify-roomcode", "does not exist"); res.WriteContent(Encoding.UTF8.GetBytes("fail")); return; } } } else { // if we might have a match for a valid room code if (path.Length == 7 && !path.Contains(".")) { // attempt to get the room by the code given var room = GetRoomByCode(path.Remove(0, 1)); // set the path to the html file so we don't request something like "/ABC123" path = "index.min.html"; if (room == null) { var sr = CreateRoom(); res.Redirect((req.Url.GetLeftPart(UriPartial.Authority) + "/" + sr.RoomCode)); } } else if (path == "/") { path = "landing/index.html"; } else if (path == "/newroom") { path = "index.min.html"; var room = CreateRoom(); res.Redirect((req.Url.GetLeftPart(UriPartial.Authority) + "/" + room.RoomCode)); } var content = httpsv.GetFile(path); if (content == null) { res.StatusCode = (int)HttpStatusCode.NotFound; return; } if (path.EndsWith(".html")) { res.ContentType = "text/html"; res.ContentEncoding = Encoding.UTF8; } else if (path.EndsWith(".js")) { res.ContentType = "application/javascript"; res.ContentEncoding = Encoding.UTF8; } else if (path.EndsWith(".css")) { res.ContentType = "text/css"; res.ContentEncoding = Encoding.UTF8; } res.WriteContent(content); } }; httpsv.Start(); if (httpsv.IsListening) { Logger.Log("Listening on port {0}, and providing WebSocket services", httpsv.Port); } }