示例#1
0
        private void to_ApplyChangeFailed(object sender, DbApplyChangeFailedEventArgs e)
        {
            var toProvider = sender as RelationalSyncProvider;

#if DEBUG
            if (toProvider.ScopeName == Scope.Icd.ToScopeString())
            {
                return;
            }
#endif
            if (e.Conflict.Type == DbConflictType.ErrorsOccurred)
            {
                Poster.PostMessage("ApplyChangeFailed. Error: {0}", e.Error);
            }
            else if (SyncTracer.IsVerboseEnabled() == false)
            {
                SyncTracer.Warning(1, "CONFLICT DETECTED FOR CLIENT {0}", toProvider.Connection);
                SyncTracer.Warning(2, "** Local change **");
                SyncTracer.Warning(2, TableToStr(e.Conflict.LocalChange));
                SyncTracer.Warning(2, "** Remote change **");
                SyncTracer.Warning(2, TableToStr(e.Conflict.RemoteChange));
            }

            if (!ConflictsCounter.Keys.Contains(e.Conflict.Type))
            {
                ConflictsCounter[e.Conflict.Type] = 0;
            }

            ConflictsCounter[e.Conflict.Type]++;

            if (e.Conflict.Type != DbConflictType.ErrorsOccurred)
            {
                e.Action = ApplyAction.RetryWithForceWrite;
            }
        }
示例#2
0
        /// <summary>
        /// Read and parse the incoming request details for a DownloadChanges GET request.
        /// </summary>
        private void ReadIncomingRequestStreamForGet()
        {
            _syncBlob = null;

            // The syncblob is in the headers or querystring for a get request and there are no entities sent from the client.

            // Check the query string for the server blob since it overrides the header.
            string syncServerBlobQueryValue = _serviceHost.QueryStringCollection[SyncServiceConstants.SYNC_SERVERBLOB_QUERYKEY];

            if (!String.IsNullOrEmpty(syncServerBlobQueryValue) && syncServerBlobQueryValue.Trim().Length > 0)
            {
                SyncTracer.Verbose("Server blob read from query string for HTTP GET: {0}", syncServerBlobQueryValue);

                _syncBlob = Convert.FromBase64String(syncServerBlobQueryValue.Trim());
            }
            // Check the request headers for the blob.
            else if (!String.IsNullOrEmpty(_serviceHost.RequestHeaders.Get(SyncServiceConstants.SYNC_SERVERBLOB_HEADERKEY)) &&
                     _serviceHost.RequestHeaders[SyncServiceConstants.SYNC_SERVERBLOB_HEADERKEY].Trim().Length > 0)
            {
                SyncTracer.Verbose("Server blob read from request headers for HTTP GET: {0}", syncServerBlobQueryValue);

                _syncBlob = Convert.FromBase64String(_serviceHost.RequestHeaders[SyncServiceConstants.SYNC_SERVERBLOB_HEADERKEY].Trim());
            }
            else
            {
                SyncTracer.Info("No server blob in query string or header.");
            }
        }
示例#3
0
 static void Main()
 {
     SyncTracer.Info("Starting Application");
     Application.EnableVisualStyles();
     Application.SetCompatibleTextRenderingDefault(false);
     Application.Run(new SyncForm());
 }
示例#4
0
        internal static SchemaException ReadingSchemaFromDataSetError(Collection <string> tableNames, string source, string helpLink, SyncErrorNumber code, Exception inner)
        {
            StringBuilder stringBuilder = new StringBuilder();

            foreach (string str in tableNames)
            {
                stringBuilder.Append(str).Append(", ");
            }
            string str1 = "";

            if (stringBuilder.Length > 2 && ((object)stringBuilder).ToString().EndsWith(", ", StringComparison.Ordinal))
            {
                str1 = ((object)stringBuilder).ToString().Substring(0, stringBuilder.Length - 2);
            }
            SchemaException schemaException = new SchemaException(SyncResource.FormatString("ServerSyncProvider_GetSchemaFromDatabase_Failed", new object[1]
            {
                (object)str1
            }), inner);

            schemaException.SyncSource  = source;
            schemaException.SyncStage   = SyncStage.ReadingSchema;
            schemaException.ErrorNumber = code;
            schemaException.TableName   = str1;
            schemaException.HelpLink    = helpLink;
            SyncTracer.Warning("{0}", new object[1]
            {
                (object)schemaException
            });
            return(schemaException);
        }
示例#5
0
        internal static void CheckForAdapterRowIds(DbSyncAdapterCollection adapters)
        {
            List <string> list = new List <string>();

            foreach (DbSyncAdapter dbSyncAdapter in (Collection <DbSyncAdapter>)adapters)
            {
                if (dbSyncAdapter.RowIdColumns.Count == 0)
                {
                    list.Add(dbSyncAdapter.TableName);
                }
            }
            if (list.Count <= 0)
            {
                return;
            }
            StringBuilder stringBuilder = new StringBuilder();
            string        str1          = string.Empty;

            foreach (string str2 in list)
            {
                stringBuilder.Append(str1 + str2);
                str1 = ", ";
            }
            SyncTracer.Error(SyncResource.FormatString("MissingAdapterRowIdColumns", new object[0]), new object[1]
            {
                (object)((object)stringBuilder).ToString()
            });
            throw new DbSyncException(SyncResource.FormatString("MissingAdapterRowIdColumns", new object[1]
            {
                (object)((object)stringBuilder).ToString()
            }));
        }
        //Note: This method changes the state of a static class. So results may not be as expected in multi-threaded scenarios.
        internal void InvokeTestHookInitializeMethod(Type type)
        {
            if (WebUtil.IsFriendClass(type))
            {
                const BindingFlags bindingAttr = BindingFlags.Public | BindingFlags.Static | BindingFlags.DeclaredOnly;
                MethodInfo         info        = type.GetMethod("InitializeConfigurationTestHook", bindingAttr, null, new[] { typeof(ISyncServiceConfiguration) }, null);

                if ((info != null) && (info.ReturnType == typeof(void)))
                {
                    ParameterInfo[] parameters = info.GetParameters();
                    if ((parameters.Length == 1) && !parameters[0].IsOut)
                    {
                        var objArray = new object[] { this };
                        try
                        {
                            info.Invoke(null, objArray);
                        }
                        catch (TargetInvocationException exception)
                        {
                            SyncTracer.Warning("Exception invoking the TestHookInitialization method. Details {0}", WebUtil.GetExceptionMessage(exception));
                            ErrorHandler.HandleTargetInvocationException(exception);
                            throw;
                        }
                        return;
                    }
                }
            }
        }
示例#7
0
 public void TruncateTable(string tableName, SqlConnection connection)
 {
     try
     {
         Log.Info("[DistributedDb] TruncateTable Start - [" + tableName + "]", this);
         connection.Open();
         var command = @"
             TRUNCATE TABLE " + tableName + @";
         ";
         using (var sqlCommand = new SqlCommand(command, connection))
         {
             SyncTracer.Info("Truncate table " + tableName);
             SyncTracerExtended.TraceCommandAndParameters((IDbCommand)sqlCommand);
             sqlCommand.ExecuteNonQuery();
         }
         connection.Close();
         Log.Info("[DistributedDb] TruncateTable End - " + tableName + "]", this);
     }
     catch (Exception ex)
     {
         if (connection.State == ConnectionState.Open)
         {
             connection.Close();
         }
         Log.Error("[DistributedDb] TruncateTable Error - " + tableName + "]", ex, this);
     }
 }
        private void LoguearNivelDeTracingConfigurador()
        {
            if (SyncTracer.IsErrorEnabled() || SyncTracer.IsWarningEnabled() || SyncTracer.IsInfoEnabled() || SyncTracer.IsVerboseEnabled())
            {
                Loguear("Tracing activado! revisar en config cual es el archivo.");
            }
            else
            {
                Loguear("Tracing desactivado, activar en el config.");
            }

            if (SyncTracer.IsErrorEnabled())
            {
                Loguear("Tracing de errores Activado");
            }

            if (SyncTracer.IsWarningEnabled())
            {
                Loguear("Tracing de advertencias Activado");
            }

            if (SyncTracer.IsInfoEnabled())
            {
                Loguear("Tracing de información Activado");
            }

            if (SyncTracer.IsVerboseEnabled())
            {
                Loguear("Tracing de todo Activado");
            }
        }
示例#9
0
 public void RebuildTableIndexes(string tableName, string indexName, SqlConnection connection)
 {
     try
     {
         Log.Info("[DistributedDb] RebuildTableIndexes Start - [" + tableName + "] ON " + indexName, this);
         connection.Open();
         var command = @"
             ALTER INDEX " + indexName + @" ON " + tableName + @" REBUILD WITH (FILLFACTOR = 80);
         ";
         using (var sqlCommand = new SqlCommand(command, connection))
         {
             //sqlCommand.CommandTimeout = 30;
             SyncTracer.Info("Rebuild index table " + indexName + " ON " + tableName);
             SyncTracerExtended.TraceCommandAndParameters((IDbCommand)sqlCommand);
             sqlCommand.ExecuteNonQuery();
         }
         connection.Close();
         Log.Info("[DistributedDb] RebuildTableIndexes End - [" + tableName + "] ON " + indexName, this);
     }
     catch (Exception ex)
     {
         if (connection.State == ConnectionState.Open)
         {
             connection.Close();
         }
         Log.Error("[DistributedDb] RebuildTableIndexes Error - [" + tableName + "] ON " + indexName, ex, this);
     }
 }
示例#10
0
        /// <summary>
        /// This method tries to look up the service configuration from the MetadataCache.
        /// For the first request, there will be no item in the cache and so, an object of type
        /// SyncServiceConfiguration is created, initialized and added to the MetadataCache.
        /// </summary>
        private void CreateConfiguration(string scope)
        {
            Type serviceType = base.GetType();

            // Check if we already have a configuration for the service in the metadata cache.

            //MetadataCacheItem item = MetadataCache.TryLookup(serviceType);
            MetadataCacheItem item = MetadataCache.TryLookup(serviceType);

            if (null == item)
            {
                SyncTracer.Info("Creating SyncServiceConfiguration for service type {0}", serviceType);

                item = new MetadataCacheItem(serviceType);

                // Initialize the private member since it will then have default values.
                // In case of an error in the static initializer, we can refer to the default values
                // of configuration.
                _syncConfiguration = new SyncServiceConfiguration(typeof(T));

                // This will invoke the static initialization method.
                _syncConfiguration.Initialize(serviceType, scope);

                String conflictPolicy = Common.Logon.GetConflictPolicy(scope);
                if (!String.IsNullOrEmpty(conflictPolicy))
                {
                    String p = conflictPolicy.ToLower();
                    switch (p)
                    {
                    case "serverwins":
                        _syncConfiguration.SetConflictResolutionPolicy(ConflictResolutionPolicy.ServerWins);
                        break;

                    case "clientwins":
                        _syncConfiguration.SetConflictResolutionPolicy(ConflictResolutionPolicy.ClientWins);
                        break;

                    default:
                        throw new Exception("Invalid conflictPolicy value");
                    }
                }

                item.Configuration = _syncConfiguration;

                //MetadataCache.AddCacheItem(serviceType, item);
                MetadataCache.AddCacheItem(serviceType, item);

                SyncTracer.Info("SyncServiceConfiguration for service type {0} created successfully!", serviceType);
            }
            else
            {
                _syncConfiguration = item.Configuration;
            }

            // Invoke the testhook Initialize method.
            // Note: This needs to be called regardless of whether we find the configuration in the
            // cache or not because this is on a per request basis.
            _syncConfiguration.InvokeTestHookInitializeMethod(serviceType);
        }
示例#11
0
        //
        // ****** Methods for adding unsorted data
        //
        public void AddUnsortedDataSet(DataSet dataSet)
        {
            // for each table in the DataSet
            foreach (DataTable curTable in dataSet.Tables)
            {
                int numColumns = curTable.Columns.Count;
                // this table should already be in the list of added
                // tables
                SortedTable sortedTable;
                if (!_sortedTables.TryGetValue(curTable.TableName, out sortedTable))
                {
                    SyncTracer.Error("Cannot Apply Changes since Adapters are missing for the following tables: {0}.  " +
                                     "Please ensure that the local and global names on the Adapters are set properly.", curTable);

                    throw new DbSyncException("MissingProviderAdapter");
                }
                if (sortedTable._schema == null)
                {
                    // add a new row storage dictionary and schema if we
                    // need one
                    sortedTable._schema = curTable.Clone();
                    Debug.Assert(sortedTable._schema.DataSet == null);
                    sortedTable._rows = new SortedDictionary <SyncId, SortedRow>(_syncIdComparer);
                }
                if (curTable.Rows.Count == 0)
                {
                    continue;
                }
                object[] idColVals = new object[sortedTable._idCols.Count];
                // for each row
                foreach (DataRow curRow in curTable.Rows)
                {
                    DataRowVersion viewVersion =
                        (curRow.RowState == DataRowState.Deleted)
                        ? DataRowVersion.Original
                        : DataRowVersion.Current;
                    for (int idx = 0; idx < idColVals.Length; idx += 1)
                    {
                        idColVals[idx] = curRow[sortedTable._idCols[idx], viewVersion];
                    }

                    // Add the row to this tables row storage dictionary
                    SyncId curRowId = SyncUtil.InitRowId(curTable.TableName, idColVals);

                    // Note: There is an issue with batching in the provider which causes the same primary key to be repeated across files.
                    // This crashes the .Add call below. To work-around this problem, we need to check if the key already exists.
                    // If it does, then remove it and add it again so that the latest record is always used.

                    if (sortedTable._rows.ContainsKey(curRowId))
                    {
                        sortedTable._rows.Remove(curRowId);
                    }

                    sortedTable._rows.Add(curRowId, new SortedRow(curRow, numColumns));
                }
            }
        }
示例#12
0
        internal static bool OpenConnection(IDbConnection connection)
        {
            SyncExpt.CheckArgumentNull((object)connection, "connection");
            bool flag = false;

            switch (connection.State)
            {
            case ConnectionState.Closed:
                if (SyncTracer.IsVerboseEnabled())
                {
                    if (connection is SqlConnection)
                    {
                        SqlConnectionStringBuilder connectionStringBuilder = new SqlConnectionStringBuilder();
                        connectionStringBuilder.ConnectionString = connection.ConnectionString;
                        if (!string.IsNullOrEmpty(connectionStringBuilder.Password))
                        {
                            connectionStringBuilder.Password = "******";
                        }
                        SyncTracer.Verbose("Connecting using string: {0}", new object[1]
                        {
                            (object)connectionStringBuilder.ConnectionString
                        });
                    }
                    else
                    {
                        SyncTracer.Verbose("Connecting to database: {0}", new object[1]
                        {
                            (object)connection.Database
                        });
                    }
                }
                if (connection is SqlConnection || connection is IConnectionWrapper)
                {
                    SyncUtil.TryOpenConnection(connection);
                }
                else
                {
                    connection.Open();
                }
                flag = true;
                goto case ConnectionState.Open;

            case ConnectionState.Open:
                return(flag);

            case ConnectionState.Broken:
                SyncTracer.Verbose("Closing broken connection");
                connection.Close();
                goto case ConnectionState.Closed;

            default:
                throw new DbSyncException(SyncResource.FormatString("UnhandledConnectionState", new object[1]
                {
                    (object)((object)connection.State).ToString()
                }));
            }
        }
示例#13
0
        internal static NotSupportedException NotSupported(string reason)
        {
            NotSupportedException supportedException = new NotSupportedException(reason);

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)supportedException
            });
            return(supportedException);
        }
示例#14
0
        internal static InvalidOperationException InvalidCreationOptionDirectionError(string tableName, TableCreationOption creationOption, SyncDirection direction)
        {
            InvalidOperationException operationException = new InvalidOperationException(SyncResource.FormatString("InvalidCreationOptionDirection", (object)tableName, (object)((object)creationOption).ToString(), (object)((object)direction).ToString()));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#15
0
        internal static InvalidOperationException CannotRemoveColumn(string columnName, string tableName)
        {
            InvalidOperationException operationException = new InvalidOperationException(SyncResource.FormatString("SyncSchema_CannotRemoveColumn", (object)columnName, (object)tableName));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#16
0
        internal static ArgumentNullException ArgumentNull(string parameter)
        {
            ArgumentNullException argumentNullException = new ArgumentNullException(parameter);

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)argumentNullException
            });
            return(argumentNullException);
        }
示例#17
0
        internal static ArgumentOutOfRangeException ArgumentOutOfRange(string parameter)
        {
            ArgumentOutOfRangeException ofRangeException = new ArgumentOutOfRangeException(parameter);

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)ofRangeException
            });
            return(ofRangeException);
        }
示例#18
0
        internal static InvalidOperationException NoTableNameError()
        {
            InvalidOperationException operationException = new InvalidOperationException(SyncResource.GetString("NoTableName"));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#19
0
        internal static ArgumentException InvalidNumericColumnOperation(string tableName, string columnName)
        {
            ArgumentException argumentException = new ArgumentException(SyncResource.FormatString("SyncSchema_NotNumeric", (object)tableName, (object)columnName));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)argumentException
            });
            return(argumentException);
        }
示例#20
0
        internal static ArgumentException Argument(string error)
        {
            ArgumentException argumentException = new ArgumentException(error);

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)argumentException
            });
            return(argumentException);
        }
示例#21
0
        internal static InvalidOperationException InvalidOperation(string error)
        {
            InvalidOperationException operationException = new InvalidOperationException(error);

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#22
0
        internal static ArgumentException ColumnNotExistsInTableError(string tableName, string columnName)
        {
            ArgumentException argumentException = new ArgumentException(SyncResource.FormatString("ColumnNotExistsInTable", (object)tableName, (object)columnName));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)argumentException
            });
            return(argumentException);
        }
示例#23
0
        internal static InvalidOperationException DynamicSQLNestedQuote(string name, string quote)
        {
            InvalidOperationException operationException = new InvalidOperationException(SyncResource.FormatString("DynamicSQLNestedQuote", (object)name, (object)quote));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#24
0
        internal static InvalidOperationException DynamicSQLNoTableInfo()
        {
            InvalidOperationException operationException = new InvalidOperationException(SyncResource.GetString("DynamicSQLNoTableInfo"));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#25
0
        internal static ArgumentException SyncMetadataColumnNotExists(string tableName, string columnName, string columnType)
        {
            ArgumentException argumentException = new ArgumentException(SyncResource.FormatString("SyncMetadataColumnNotExists", (object)columnType, (object)columnName, (object)tableName));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)argumentException
            });
            return(argumentException);
        }
示例#26
0
        internal static ArgumentException InvalidProviderDataType(string providerType, string columnName, string tableName)
        {
            ArgumentException argumentException = new ArgumentException(SyncResource.FormatString("InvalidProviderDataType", (object)providerType, (object)columnName, (object)tableName));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)argumentException
            });
            return(argumentException);
        }
示例#27
0
        internal static InvalidOperationException SyncNonMatchingKeys(string baseTableName, string tombstoneTableName)
        {
            InvalidOperationException operationException = new InvalidOperationException(SyncResource.FormatString("SyncNonMatchingKeys", (object)baseTableName, (object)tombstoneTableName));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#28
0
        internal static InvalidOperationException InvalidSyncMetadataError(string obj1, string obj2, string tableName)
        {
            InvalidOperationException operationException = new InvalidOperationException(SyncResource.FormatString("InvalidSyncMetadata", (object)obj1, (object)obj2, (object)tableName));

            SyncTracer.Warning("{0}", new object[1]
            {
                (object)operationException
            });
            return(operationException);
        }
示例#29
0
        private void InvokeOnEndSyncRequest(Message message)
        {
            EventHandler <OnEndSyncRequestEventArgs> request = OnEndSyncRequest;

            if (request != null)
            {
                SyncTracer.Verbose("Raising OnEndSyncRequest event");
                request(this, new OnEndSyncRequestEventArgs(message));
                SyncTracer.Verbose("Done: Raising OnEndSyncRequest event");
            }
        }
示例#30
0
        /// #DOWNLOAD (not in batches)
        public SpSyncAnchor SelectAll(SpSyncAnchor anchor, int rowLimit, DataTable dataTable, SpConnection connection)
        {
            if (anchor == null)
            {
                throw new ArgumentNullException("anchor");
            }

            if (connection == null)
            {
                throw new ArgumentNullException("connection");
            }

            if (dataTable == null)
            {
                throw new ArgumentNullException("dataTable");
            }

            QueryOptions queryOptions = new QueryOptions()
            {
                PagingToken = anchor.PagingToken,
                DateInUtc   = false
            };

            IEnumerable <string> viewFields = GetViewFields();

            ListItemCollection listItems = connection.GetListItems(
                this.ListName,
                this.ViewName,
                this.FilterClause,
                viewFields,
                IncludeProperties,
                rowLimit,
                queryOptions);

            if (dataTable != null)
            {
                foreach (ListItem item in listItems)
                {
                    DataRow   row = dataTable.NewRow();
                    Exception e;
                    MapListItemToDataRow(item, row, out e);
                    if (e != null)
                    {
                        if (SyncTracer.IsErrorEnabled())
                        {
                            SyncTracer.Error(e.ToString());
                        }
                    }
                    dataTable.Rows.Add(row);
                }
            }
            dataTable.AcceptChanges();
            return(CalculateNextAnchor(anchor, listItems.NextPage));
        }