/// <summary>Обновление локальной базы после синхронизации</summary> /// <typeparam name="T"></typeparam> /// <param name="skipExists">Пропустить существующие</param> /// <param name="updId">Нужно обновить ID</param> private void updateObjOnLocalDb <T>(CatalogSynchronizer synchronizer, bool skipExists, bool updId) where T : dbObject { //Данные только по измененным элементам с "сервера" DataTable changesForTsd = ResultParameters[1] as DataTable; if (changesForTsd != null) { //Обновление элементов на локальной базе CreateSyncObject <T>(synchronizer, changesForTsd, skipExists, ref deferredProperty, updId); } }
public void Update_Existing_SellableItem() { var mockCommerceCommander = new Mock <CommerceCommander>(); var mockContext = new Mock <CommercePipelineExecutionContext>(); _sellableItemIdsToBeFound.AddRange(new List <string>() { "Entity-SellableItem-EXISTING_PRODUCT0001", "Entity-SellableItem-EXISTING_PRODUCT0002" }); mockCommerceCommander.Setup(s => s.Pipeline <IFindEntitiesPipeline>().Run(It.IsAny <FindEntitiesArgument>(), It.IsAny <CommercePipelineExecutionContext>())).Returns((FindEntitiesArgument arg, CommercePipelineExecutionContext context) => MockFoundEntities(arg, context)); var catalogSynchronizer = new CatalogSynchronizer(mockCommerceCommander.Object, mockContext.Object); }
/// <summary>Создание объектов синхронизации</summary> /// <param name="table">Данные о объектах</param> /// <param name="skipExists">Пропустить существующие</param> /// <param name="deferredProperty">Список отложеных свойств</param> /// <param name="updId">Нужно обновить ID</param> private static void CreateSyncObject <T>(CatalogSynchronizer synchronizer, DataTable table, bool skipExists, ref List <DataAboutDeferredProperty> deferredProperty, bool updId) where T : dbObject { if (synchronizer != null) { int rowsCount = table.Rows.Count; for (int rowIndex = 0; rowIndex < rowsCount; rowIndex++) { DataRow row = table.Rows[rowIndex]; synchronizer.Merge(row); //if (rowIndex % 10 == 0) { Trace.WriteLine(string.Format("{1} %, rowIndex = {0} from {2}", rowIndex, (int)(100 * rowIndex / rowsCount), rowsCount)); } //if (rowIndex % 500 == 0) // { // GC.Collect(); // GC.WaitForPendingFinalizers(); // } } return; } Type type = typeof(T); PropertyInfo[] properties = type.GetProperties(); string syncRef = string.Empty; string syncRefName = dbObject.SYNCREF_NAME.ToLower(); int lastDeferredIndex = deferredProperty.Count; foreach (DataRow row in table.Rows) { object newObj = Activator.CreateInstance(typeof(T)); T newObject = (T)newObj; bool needDeferred = false; foreach (PropertyInfo property in properties) { dbFieldAtt attribute = Attribute.GetCustomAttribute(property, typeof(dbFieldAtt)) as dbFieldAtt; if (attribute != null && table.Columns.Contains(property.Name)) { object value = row[property.Name]; //Не существует ли елемент с такой ссылкой? if (property.Name.ToLower().Equals(syncRefName)) { if (BarcodeWorker.IsRefExist(type, value.ToString())) { if (skipExists) { break; } newObject.SetNotNew(); } syncRef = value.ToString(); } else if (updId && property.Name.ToLower().Equals(dbObject.IDENTIFIER_NAME)) { continue; } if (property.PropertyType == typeof(int)) { value = string.IsNullOrEmpty(value.ToString()) ? 0 : Convert.ToInt32(value); } else if (property.PropertyType == typeof(double)) { value = string.IsNullOrEmpty(value.ToString()) ? 0D : Convert.ToDouble(value); } else if (property.PropertyType == typeof(long)) { if (attribute.dbObjectType == null) { value = string.IsNullOrEmpty(value.ToString()) ? 0L : Convert.ToInt64(value); } else { if (value != null && !string.IsNullOrEmpty(value.ToString())) { DataAboutDeferredProperty data = new DataAboutDeferredProperty(type, attribute.dbObjectType, property.Name, value); deferredProperty.Add(data); needDeferred = true; } value = 0L; } } else if (property.PropertyType == typeof(bool)) { value = Convert.ToBoolean(value); } else if (property.PropertyType == typeof(DateTime)) { value = StringParser.ParseDateTime(value); } else if (property.PropertyType.IsEnum) { value = Enum.Parse(property.PropertyType, value.ToString(), false); } else if (property.PropertyType == typeof(string)) { string fullValue = value.ToString(); value = value.ToString(); if (property.Name != CatalogObject.DESCRIPTION) { int length = attribute.StrLength == 0 ? dbFieldAtt.DEFAULT_STR_LENGTH : attribute.StrLength; if (fullValue.Length > length) { value = fullValue.Substring(0, length); } } } property.SetValue(newObject, value, null); } } ISynced syncObject = newObject as ISynced; if (syncObject != null) { syncObject.IsSynced = true; } if (updId && !skipExists && !string.IsNullOrEmpty(syncRef)) { newObject.Id = Convert.ToInt64(BarcodeWorker.GetIdByRef(type, syncRef)); } CatalogObject catalog = newObject as CatalogObject; if (catalog != null) { dbElementAtt attribute = Attribute.GetCustomAttribute(newObject.GetType(), typeof(dbElementAtt)) as dbElementAtt; int length = attribute == null || attribute.DescriptionLength == 0 ? dbElementAtt.DEFAULT_DES_LENGTH : attribute.DescriptionLength; if (catalog.Description.Length > length) { catalog.Description = catalog.Description.Substring(0, length); } } newObject.Sync <T>(updId); if (needDeferred) { for (int i = lastDeferredIndex; i < deferredProperty.Count; i++) { deferredProperty[i].Id = newObject.Id; } lastDeferredIndex = deferredProperty.Count; } } }
/// <summary>Синхронизация объекта</summary> /// <param name="tableName">Имя таблицы</param> /// <param name="wayOfSync">Способ синхронизации</param> /// <param name="filter">Фильтры</param> /// <param name="skipExists">Пропустить существующие</param> /// <param name="updId">Нужно обновить ID</param> private bool SyncObjects <T>(string tableName, WaysOfSync wayOfSync, FilterSettings filter, bool skipExists, bool updId) where T : dbObject { CatalogSynchronizer synchronizer = null; synchronizer = this.getCatalogSynchronizer(tableName); logBuilder.AppendLine(); logBuilder.AppendLine(); logBuilder.AppendLine(string.Format("{0}:", typeof(T).Name)); Stopwatch totalWatch = new Stopwatch(); totalWatch.Start(); Stopwatch stopWatch = new Stopwatch(); stopWatch.Start(); string forWarehousesAndMapsSelect = string.Format(@"SELECT RTRIM({0}){0},RTRIM({1}){1},RTRIM({2}) {2} FROM {3} WHERE {4}=0", dbObject.IS_SYNCED, dbObject.BARCODE_NAME, dbObject.SYNCREF_NAME, tableName, CatalogObject.MARK_FOR_DELETING); string forByLogProcessedSelect = string.Format(@"SELECT RTRIM({0}){0},RTRIM({1}){1},RTRIM({2}) {2} FROM {3} WHERE {4}=0 AND {5} = 0", dbObject.IS_SYNCED, dbObject.BARCODE_NAME, dbObject.SYNCREF_NAME, tableName, CatalogObject.MARK_FOR_DELETING, CatalogObject.IS_SYNCED); bool isWarehouseTable = tableName.Equals("Contractors") || tableName.Equals("Maps"); //Выбрать (Признак синхронизации, Штрих-код) всех не удаленных элементов с таблицы tableName string command = (useLoggingSyncronization & !isWarehouseTable) ? forByLogProcessedSelect : forWarehousesAndMapsSelect; DataTable table = null; using (SqlCeCommand query = dbWorker.NewQuery(command)) { table = query.SelectToTable(); } int rowsCount = (table ?? new DataTable()).Rows.Count; logBuilder.AppendLine(string.Format("init pdt query: {0} msec; rows: {1}", stopWatch.ElapsedMilliseconds, rowsCount)); stopWatch.Reset(); stopWatch.Start(); if (filter == FilterSettings.None) { PerformQuery("StartSyncProcess", this.serverIdProvider.ServerId, tableName, table, (int)FilterSettings.NotMarkForDelete); } else { PerformQuery("StartSyncProcess", this.serverIdProvider.ServerId, tableName, table, (int)FilterSettings.NotMarkForDelete, (int)filter); } logBuilder.AppendLine(string.Format("StartSyncProcess: {0} msec; rows: {1}", stopWatch.ElapsedMilliseconds, rowsCount)); stopWatch.Reset(); stopWatch.Start(); if (IsAnswerIsTrue) { removeMarkedObject(tableName); logBuilder.AppendLine(string.Format("removeMarkedObject: {0} msec", stopWatch.ElapsedMilliseconds)); stopWatch.Reset(); stopWatch.Start(); updateObjOnLocalDb <T>(synchronizer, skipExists, updId); int localRowsCount = ((ResultParameters[1] as DataTable) ?? new DataTable()).Rows.Count; logBuilder.AppendLine(string.Format("updateObjOnLocalDb: {0} msec; rows: {1}", stopWatch.ElapsedMilliseconds, localRowsCount)); stopWatch.Reset(); stopWatch.Start(); if (wayOfSync == WaysOfSync.TwoWay) { int remoteTableRows = ((ResultParameters[2] as DataTable) ?? new DataTable()).Rows.Count; updateObjOnServDb <T>(tableName); logBuilder.AppendLine(string.Format("update greenhouse: {0} msec; rows:{1}", stopWatch.ElapsedMilliseconds, remoteTableRows)); stopWatch.Reset(); stopWatch.Start(); } logBuilder.AppendLine(string.Format("{0} total: {1} msec", typeof(T).Name, totalWatch.ElapsedMilliseconds)); return(true); } else { return(false); } }