Inheritance: ISynchronizeInvoke, IDisposable
Beispiel #1
0
        /// <summary>
        /// Program Main Entry
        /// </summary>
        /// <param name="args">Program Arguments</param>
        public static void Main(string[] args)
        {
            Trace.TraceInformation("Starting...");

            try
            {
                var parameters = new Parameters(args);
                var config = parameters.Process();

                Trace.TraceInformation("SQL Server Connection String: '{0}'{3}{3}Storage Account: '{1}'{3}Table Name: '{2}'{3}"
                    , config.SqlConnection
                    , config.StorageAccountConnection
                    , config.StorageTableName
                    , Environment.NewLine);

                var sync = new Synchronizer(config);
                sync.Run().Wait();
            }
            catch (Exception ex)
            {
                Trace.Fail(ex.ToString());
            }

            Trace.TraceInformation("Completed.");

            Thread.Sleep(2000);
        }
Beispiel #2
0
        public Main(IList<string> args)
        {
            InitializeComponent();

            // let's instantiate our Synchronizer
            _synchronizer = new Synchronizer();
            _synchronizer.ErrorWhileSyncing += SynchronizerErrorWhileSyncing;
            _synchronizer.AutoFetchAllEntriesFinished += AutoFetchAllEntriesFinished;
            _synchronizer.InitializeSynchronizer();
            _synchronizer.Start();

            // if arguments contain a txt-file to be opened, let's add that as a new tab instead of creating a new one
            if (args != null && args.Count > 0 && File.Exists(args[0]))
            {
                ReadAndLoadLocalFile(args[0]);
            }
            else
            {
                // let's then create a new tab (Noc) for the editor and add the editor inside the tab
                AddNoc();
            }

            // let's also initialize the timer for automatically retrieving all documents
            _autoFetchAllEntriesTimer = new Timer
            {
                Enabled = true,
                Interval = AutoFetchAllEntriesInterval * 60 * 1000
            };
            _autoFetchAllEntriesTimer.Elapsed += AutoFetchAllEntriesTimerElapsed;
        }
        public async Task ConstructorSqlToTable()
        {
            var c = new ConfigValues()
            {
                StorageAccountConnection = "UseDevelopmentStorage=true;",
                SqlConnection = "Server=localhost;Database=King.BTrak.Data;Trusted_Connection=True;",
                SqlTableName = "TableData",
                StorageTableName = "sqlserverdata",
                Direction = Direction.SqlToTable,
            };

            var id = Guid.NewGuid();
            var data = Guid.NewGuid();
            var statement = string.Format("INSERT INTO [dbo].[TestSqlToTable] ([Id], [Data]) VALUES ('{0}', '{1}');", id, data);
            var executor = new Executor(new SqlConnection(c.SqlConnection));
            await executor.NonQuery(statement);

            var s = new Synchronizer(c);
            await s.Run();

            await executor.NonQuery("TRUNCATE TABLE [dbo].[TestSqlToTable]");

            var table = new TableStorage(c.StorageTableName, c.StorageAccountConnection);
            var e = await table.QueryByPartitionAndRow("[dbo].[TestSqlToTable]", id.ToString());
            Assert.IsNotNull(e);
            Assert.AreEqual(data, e["Data"]);
        }
        public async Task ConstructorTableToSql()
        {
            var c = new ConfigValues()
            {
                StorageAccountConnection = "UseDevelopmentStorage=true;",
                SqlConnection = "Server=localhost;Database=King.BTrak.Data;Trusted_Connection=True;",
                SqlTableName = "TableData",
                StorageTableName = "sqlserverdata",
                Direction = Direction.TableToSql,
            };

            var tableName = "testsynctabletosql";
            var table = new TableStorage(tableName, c.StorageAccountConnection);
            await table.CreateIfNotExists();
            var entity = new TableEntity
            {
                PartitionKey = Guid.NewGuid().ToString(),
                RowKey = Guid.NewGuid().ToString(),
            };
            await table.InsertOrReplace(entity);

            var s = new Synchronizer(c);
            await s.Run();

            await table.Delete();

            var statement = string.Format("SELECT 1 AS [Exists] FROM [dbo].[TableData] WHERE TableName='{0}' AND PartitionKey = '{1}' AND RowKey = '{2}';", tableName, entity.PartitionKey, entity.RowKey);
            var executor = new Executor(new SqlConnection(c.SqlConnection));
            var ds = await executor.Query(statement);
            var r = ds.Model<DataRow>();
            Assert.IsNotNull(r);
            Assert.IsTrue(r.Exists);
        }
        public void Init()
        {
            //string timestamp = DateTime.Now.Ticks.ToString();
            if (_logUpdateHandler == null)
            {
                _logUpdateHandler = new Logger.LogUpdatedHandler(Logger_LogUpdated);
                Logger.LogUpdated += _logUpdateHandler;
            }

            string gmailUsername;
            //string gmailPassword;
            string syncProfile;
            string syncContactsFolder;
            string syncNotesFolder;
            string syncAppointmentsFolder;

            GoogleAPITests.LoadSettings(out gmailUsername, out syncProfile, out syncContactsFolder, out syncNotesFolder, out syncAppointmentsFolder);

            sync = new Synchronizer();
            sync.SyncContacts = true;
            sync.SyncNotes = false;
            sync.SyncAppointments = false;
            sync.SyncProfile = syncProfile;
            Synchronizer.SyncContactsFolder = syncContactsFolder;

            sync.LoginToGoogle(gmailUsername);
            sync.LoginToOutlook();
        }
 public IMobeelizerAuthenticateResponse Authenticate(string user, string password, String notificationChanelUri)
 {
     WebRequest request = WebRequest.Create(GetUrl("/authenticate?cache="+Guid.NewGuid().ToString()));
     request.Method = "GET";
     SetHeaders(request, false, false);
     request.Headers["mas-user-name"] = user;
     request.Headers["mas-user-password"] = password;
     try
     {
         MobeelizerResponse result = new Synchronizer().GetResponse(request);
         if (result.StatusCode == HttpStatusCode.OK)
         {
             JObject jObject = (result as MobeelizerJsonResponse).Json;
             return new MobeelizerAuthenticateResponse((String)jObject["instanceGuid"], (String)jObject["role"]);
         }
         else if(result.StatusCode == HttpStatusCode.InternalServerError)
         {
             return new MobeelizerAuthenticateResponse(MobeelizerOperationError.ServerError((result as MobeelizerJsonResponse).Json));
         }
         else
         {
             throw new IOException("Http connection status code: " + result.StatusCode.ToString());
         }
     }
     catch (WebException e)
     {
         return new MobeelizerAuthenticateResponse(MobeelizerOperationError.ConnectionError(e.Message));
     }
     catch (JsonException e)
     {
         return new MobeelizerAuthenticateResponse(MobeelizerOperationError.Other(e.Message));
     }
 }
        public SynchronizerInstance(Synchronizer s)
        {
            synchronizer = s;
            int a = synchronizer.EnteringTransitions.Count;
            int b = synchronizer.LeavingTransitions.Count;
            this.Volume = a * b;

            //		System.out.println("synchronizer "+synchronizer.Name+"'s volume is "+volume);
        }
 public MainWindowViewModel(ITodoItemRepository todoItemRepository)
 {
     this.todoItemRepository = todoItemRepository;
     AddNewItemCommand = new SimpleCommand(AddNewItem);
     CancelChangesCommand = new SimpleCommand(RefreshChanges);
     updater = new Synchronizer<MainWindowViewModel>(() => PropertyChanged);
     TodoItems = new ObservableCollection<TodoItemViewModel>();
     RefreshChanges();
 }
Beispiel #9
0
        public Browse(ref Synchronizer synchronizer)
        {
            InitializeComponent();
            // activates double buffering
            SetStyle(ControlStyles.UserPaint | ControlStyles.AllPaintingInWmPaint | ControlStyles.DoubleBuffer, true);

            _synchronizer = synchronizer;
            _synchronizer.AutoFetchAllEntriesFinished += SynchronizerAutoFetchAllEntriesFinished;
        }
Beispiel #10
0
        private void EBCs_verdrahten() {
            var twitterSearch = new TwitterSearch();
            var timer = new PeriodicDispenser<string>();
            var synchronizer = new Synchronizer<IEnumerable<Tweet>>();

            Out_Search += timer.In_Event;
            timer.Out_Event += twitterSearch.In_Search;
            twitterSearch.Out_Update += synchronizer.In_Event;
            synchronizer.Out_Event += In_Update;
        }
 public TodoItemViewModel(ITodoItemRepository todoItemRepository)
 {
     this.todoItemRepository = todoItemRepository;
     SaveCommand = new SimpleCommand(Save, CanSave);
     DeleteCommand = new SimpleCommand(Delete);
     synchronizer = new Synchronizer<TodoItemViewModel>(() => PropertyChanged);
     validations = new Dictionary<string, IValidation>
                       {
                           {"Description", new Validation(() => !string.IsNullOrEmpty(Description), "Cannot have an empty description.")},
                           {"DueDate", new Validation(() => DueDate >= DateTime.Today, "Due Date must occur on or after today.")}
                       };
 }
Beispiel #12
0
        public Noc(Synchronizer synchronizer, ContextMenuStrip contextMenuEditor)
        {
            // let's set up the reference to the main form's synchronizer
            // so we can access it through individual tabs (Noc's)
            _synchronizer = synchronizer;
            Document = new Document
            {
                Title = "Untitled",
                Content = string.Empty,
                AtomEntry = { IsDraft = true }
            };

            InitializeNoc(contextMenuEditor);
        }
        private void SyncSyncCountdownTick(object sender, Synchronizer.SyncCountdownTickEventArgs e)
        {
            Dispatcher.Invoke(
                new MethodInvoker(
                    () =>
                    {
                        if (e.RemainingTime.TotalSeconds < 1)
                        {
                            lblNextSync.Content = "Sincronizando!";
                        }
                        else
                            lblNextSync.Content = string.Format("{0:00}:{1:00}:{2:00}", e.RemainingTime.Hours, e.RemainingTime.Minutes, e.RemainingTime.Seconds);

                    }), null);
        }
Beispiel #14
0
        public void Result_Event_wird_auf_Zielthread_ausgeführt_wenn_das_Ziel_WinForms_ist() {
            var myForm = new Form();
            sut = new Synchronizer<int>();

            var mainThreadId = Thread.CurrentThread.ManagedThreadId;

            sut.Result += _ => {
                Assert.That(Thread.CurrentThread.ManagedThreadId, Is.EqualTo(mainThreadId));
                myForm.Close();
            };

            var thread = new Thread(() => sut.Process(1));
            thread.Start();
            Application.Run(myForm);
        }
Beispiel #15
0
        public StringTrackView(TLStringTrack track, TimelineView tv, RulerView rv)
            : base(track, tv, rv)
        {
            Keyframes = new EditableList<StringKeyframeView>();

            KFSyncer = Keyframes.SyncWith(Model.Keyframes,
                                          kf =>
                                          {
                                          	var kv = new StringKeyframeView(kf, this);
                                          	kf.NeighbourChanged += NeedsRebuild;
                                          	var kfs = Model.Keyframes.ToList();
                                          	var prev = kfs.FindLastIndex(x => x.Time.Value < kf.Time.Value);
                                          	kv.AddToSceneGraphAt(KeyframeGroup, Keyframes.Count - 1 - prev);
                                          	return kv;
                                          },
                                          kv =>
                                          {
                                          	kv.Dispose();
                                          });

            Background.Click += Background_MouseClick;

            KeyframeDefinition.StartX = 0;
            KeyframeDefinition.StartY = -25f;
            KeyframeDefinition.EndX = 0;
            KeyframeDefinition.EndY = 25f;
            KeyframeDefinition.ID = Model.GetID() + "_KF";
            KeyframeDefinition.Transforms = new SvgTransformCollection();
            KeyframeDefinition.Transforms.Add(new SvgScale(1, 1));

            CollapsedKeyframeDefinition.ID = Model.GetID() + "_CKF";
            CollapsedKeyframeDefinition.StartX = 0;
            CollapsedKeyframeDefinition.StartY = -25f;
            CollapsedKeyframeDefinition.EndX = 0;
            CollapsedKeyframeDefinition.EndY = 25f;
            CollapsedKeyframeDefinition.Transforms = new SvgTransformCollection();
            CollapsedKeyframeDefinition.Transforms.Add(new SvgScale(1, 1));

            KeyframeGroup.ID = "Keyframes";

            CurrentValue.FontSize = 12;
            CurrentValue.X = 5;
            CurrentValue.CustomAttributes["class"] = "trackfont";
            CurrentValue.CustomAttributes["pointer-events"] = "none";
            CurrentValue.Y = 24;

            UpdateScene();
        }
    protected bool SynchronizeInternal (IInitialSyncStateCreationStrategy<Identifier, int, string, Identifier, int, string> strategy)
    {
      var synchronizer = new Synchronizer<Identifier, int, string, Identifier, int, string> (
          _localRepository,
          _serverRepository,
          strategy,
          _entityRelationDataAccess,
          _entityRelationDataFactory,
          MockRepository.GenerateStub<IInitialEntityMatcher<string, Identifier, int, string, Identifier, int>>(),
          IdentifierEqualityComparer.Instance,
          IdentifierEqualityComparer.Instance,
          NullTotalProgressFactory.Instance,
          MockRepository.GenerateMock<IExceptionLogger>());

      return synchronizer.Synchronize().Result;
    }
Beispiel #17
0
    public void DealWithRelativePaths()
    {
      // This one checks for a bug I found where relative path names confuse
      // the engine

      // Set up the wiki directory
      sync.Initialize(); 

      Directory.SetCurrentDirectory(AppDomain.CurrentDomain.BaseDirectory); 

      // Make a new synchronizer that's pointed at a relative path
      sync = new Synchronizer(dir, proxy); 

      // A simple update should succeed. As long as we get no exceptions, we're good
      sync.Update(); 
    }
Beispiel #18
0
		public static string CreateTopicFile(Synchronizer sync, string nsname, string topicname, 
			string content)
		{
			string dir = Path.Combine(sync.BaseDirectory, nsname); 

			if (!Directory.Exists(dir))
			{
				Directory.CreateDirectory(dir); 
			}

			string path = Path.Combine(dir, topicname + ".wiki"); 
			FileStream fs = new FileStream(path, FileMode.CreateNew, FileAccess.Write); 
			StreamWriter sw = new StreamWriter(fs, System.Text.Encoding.ASCII); 
			sw.Write(content); 
			sw.Close();

			return path; 
		}
Beispiel #19
0
    public static void AddAndCommit(Synchronizer sync)
    {
      sync.Initialize();
      sync.Update(); 

      string topicname = "ThreeTopic"; 
      string content = "A-" + topicname; 

      string path = UnitTests.CreateTopicFile(sync, "A", topicname, content);

      sync.SyncToLocal(); 

      Assert.IsNotNull(sync.Namespaces["A"].Topics[topicname], "Checking that local file has been picked up"); 

      Assert.AreEqual(Status.LocallyAdded, sync.Namespaces["A"].Topics[topicname].Status, "Checking that local file has status of 'LocallyAdded'");

      sync.Commit("CraigAndera"); 

    }
Beispiel #20
0
        public void TestSync()
        {
            // create new note to sync
            Outlook.NoteItem outlookNote = Synchronizer.CreateOutlookNoteItem(Synchronizer.SyncNotesFolder);
            //outlookNote.Subject = name;
            outlookNote.Body = body;

            outlookNote.Save();

            sync.SyncOption = SyncOption.OutlookToGoogleOnly;

            Document googleNote = new Document();

            googleNote.Type = Document.DocumentType.Document;
            sync.UpdateNote(outlookNote, googleNote);
            NoteMatch match = new NoteMatch(outlookNote, googleNote);

            //save Note to google.
            sync.SaveGoogleNote(match);
            for (int i = 0; match.AsyncUpdateCompleted.HasValue && !match.AsyncUpdateCompleted.Value && i < 10; i++)
            {
                Thread.Sleep(1000);//DoNothing, until the Async Update is complete, but only wait maximum 10 seconds
            }
            googleNote = null;

            sync.SyncOption = SyncOption.GoogleToOutlookOnly;
            //load the same Note from google.
            sync.MatchNotes();
            match = FindMatch(match.GoogleNote);
            //NotesMatcher.SyncNote(match, sync);

            Outlook.NoteItem recreatedOutlookNote = Synchronizer.CreateOutlookNoteItem(Synchronizer.SyncNotesFolder);
            sync.UpdateNote(match.GoogleNote, recreatedOutlookNote);

            // match recreatedOutlookNote with outlookNote
            //Assert.AreEqual(outlookNote.Subject, recreatedOutlookNote.Subject);
            Assert.AreEqual(outlookNote.Body, recreatedOutlookNote.Body);

            DeleteTestNotes(match);
        }
Beispiel #21
0
        SqlPreCommand?SyncViews(Replacements replacements)
        {
            var isPostgres = Schema.Current.Settings.IsPostgres;
            var oldView    = Schema.Current.DatabaseNames().SelectMany(db =>
            {
                if (isPostgres)
                {
                    if (db != null)
                    {
                        throw new InvalidOperationException("Multi-database not supported in postgress");
                    }

                    return((from p in Database.View <PgClass>()
                            where p.relkind == RelKind.View
                            let ns = p.Namespace()
                                     where !PostgresCatalogSchema.systemSchemas.Contains(ns.nspname)
                                     let definition = PostgresFunctions.pg_get_viewdef(p.oid)
                                                      select KeyValuePair.Create(new ObjectName(new SchemaName(db, ns.nspname, isPostgres), p.relname, isPostgres), definition)).ToList());
                }
                else
                {
                    using (Administrator.OverrideDatabaseInSysViews(db))
                    {
                        return((from v in Database.View <SysViews>()
                                join s in Database.View <SysSchemas>() on v.schema_id equals s.schema_id
                                join m in Database.View <SysSqlModules>() on v.object_id equals m.object_id
                                select KeyValuePair.Create(new ObjectName(new SchemaName(db, s.name, isPostgres), v.name, isPostgres), m.definition)).ToList());
                    }
                }
            }).ToDictionary();

            using (replacements.WithReplacedDatabaseName())
                return(Synchronizer.SynchronizeScript(Spacing.Double,
                                                      Views,
                                                      oldView,
                                                      createNew: (name, newView) => newView.CreateView(),
                                                      removeOld: null,
                                                      mergeBoth: (name, newDef, oldDef) => Clean(newDef.CreateView().Sql) == Clean(oldDef) ? null : newDef.AlterView()
                                                      ));
        }
Beispiel #22
0
 protected ConnectableNotifier()
 {
     PropertyChanged += (s, e) =>
     {
         e.Case(() => KeepAliveInterval, p =>
         {
             //Si KeepAliveInterval es menor que 1 lanzo una ArgumentException
             if (p.ActualValue.TotalMilliseconds < 1)
             {
                 throw new ArgumentException(
                     "El valor de '" + s.GetMemberName(() => s.KeepAliveInterval) + "' no puede ser cero o negativo, para deshabilitar el KeepAlive establezca la propiedad '" + s.GetMemberName(() => s.IsKeepAliveEnable) + "' en False.",
                     s.GetMemberName(() => s.KeepAliveInterval));
             }
         });
         e.Case(() => ConnectionMode, p =>
         {
             //Si cambia el modo de conexión a automática y no estoy conectado o conectando debo llamar a Connect
             if (p.ActualValue == ConnectionMode.Automatic && State != ConnectionState.Opened && State != ConnectionState.Opening)
             {
                 Connect();
             }
         });
         e.Case(() => State, p =>
         {
             //Si cambia el estado hacia o desde Opened abrá que disparar el cambio de la propiedad IsConnected y el evento IsConnectedChanged
             if (p.PreviousValue == ConnectionState.Opened || p.ActualValue == ConnectionState.Opened)
             {
                 RaisePropertyChanged(() => IsConnected, p.PreviousValue == ConnectionState.Opened, p.ActualValue == ConnectionState.Opened);
                 if (Synchronizer != null)
                 {
                     Synchronizer.Invoke(actualValue => IsConnectedChanged?.Invoke(this, new EventArgs <bool>(actualValue == ConnectionState.Opened)), p.ActualValue);
                 }
                 else
                 {
                     IsConnectedChanged?.Invoke(this, new EventArgs <bool>(p.ActualValue == ConnectionState.Opened));
                 }
             }
         });
     };
 }
Beispiel #23
0
        SqlPreCommand?SyncProcedures(Replacements replacements)
        {
            var isPostgres    = Schema.Current.Settings.IsPostgres;
            var oldProcedures = Schema.Current.DatabaseNames().SelectMany(db =>
            {
                if (isPostgres)
                {
                    if (db != null)
                    {
                        throw new InvalidOperationException("Multi-database not supported in postgress");
                    }

                    return((from v in Database.View <PgProc>()
                            let ns = v.Namespace()
                                     where !ns.IsInternal()
                                     let definition = PostgresFunctions.pg_get_viewdef(v.oid)
                                                      select KeyValuePair.Create(new ObjectName(new SchemaName(db, ns.nspname, isPostgres), v.proname, isPostgres), definition)).ToList());
                }
                else
                {
                    using (Administrator.OverrideDatabaseInSysViews(db))
                    {
                        return((from p in Database.View <SysObjects>()
                                join s in Database.View <SysSchemas>() on p.schema_id equals s.schema_id
                                where p.type == "P" || p.type == "IF" || p.type == "FN"
                                join m in Database.View <SysSqlModules>() on p.object_id equals m.object_id
                                select KeyValuePair.Create(new ObjectName(new SchemaName(db, s.name, isPostgres), p.name, isPostgres), m.definition)).ToList());
                    }
                }
            }).ToDictionary();

            return(Synchronizer.SynchronizeScript(
                       Spacing.Double,
                       StoreProcedures,
                       oldProcedures,
                       createNew: (name, newProc) => newProc.CreateSql(),
                       removeOld: null,
                       mergeBoth: (name, newProc, oldProc) => Clean(newProc.CreateSql().Sql) == Clean(oldProc) ? null : newProc.AlterSql()
                       ));
        }
Beispiel #24
0
        public Transfering(Stream sendStream, Stream receiveStream, uint quantSize)
        {
            _sendStream    = sendStream;
            _receiveStream = receiveStream;
            _quantSize     = quantSize;
            _synchronizer  = new ConcurrentDictionary <ulong, Action <byte[]> >();

            var pingRap = (ulong)0;

            var sync = new Synchronizer(true);

            _synchronizer[pingRap] = (rslt) => {
                sync.Unlock();
            };

            new Thread(() => {
                while (true)
                {
                    sync.Lock();
                    SendManager(new byte[0], 0);

                    if (!sync.Wait(25000))
                    {
                        isConnectionStabilised = false;
                        Console.WriteLine("PING TIMEOUT ON CURRENT CONNECTION");
                    }

                    if (isTranferDead)
                    {
                        return; // kill current thread
                    }

                    Thread.Sleep(11000);
                }
            })
            {
                IsBackground = true, Priority = ThreadPriority.AboveNormal
            }.Start();
        }
Beispiel #25
0
        public static void SynchronizeProgressForeachNonTransactional <K, N, O>(this ExecutingProcess ep,
                                                                                Dictionary <K, N> newDictionary,
                                                                                Dictionary <K, O> oldDictionary,
                                                                                Action <K, N> createNew,
                                                                                Action <K, O> removeOld,
                                                                                Action <K, N, O> merge)
            where O : class
            where N : class
            where K : notnull
        {
            if (ep == null)
            {
                Synchronizer.SynchronizeProgressForeach(newDictionary, oldDictionary, createNew, removeOld, merge, transactional: false);
            }
            else
            {
                HashSet <K> keys = new HashSet <K>();
                keys.UnionWith(oldDictionary.Keys);
                keys.UnionWith(newDictionary.Keys);
                ep.ForEachNonTransactional(keys.ToList(), key => key.ToString() !, key =>
                {
                    var oldVal = oldDictionary.TryGetC(key);
                    var newVal = newDictionary.TryGetC(key);

                    if (oldVal == null)
                    {
                        createNew?.Invoke(key, newVal !);
                    }
                    else if (newVal == null)
                    {
                        removeOld?.Invoke(key, oldVal);
                    }
                    else
                    {
                        merge?.Invoke(key, newVal, oldVal);
                    }
                });
            }
        }
        public void Setup()
        {
            _dataFeed     = new TestableLiveTradingDataFeed(new FakeDataQueue());
            _algorithm    = new AlgorithmStub(createDataManager: false);
            _synchronizer = new LiveSynchronizer();
            var registeredTypesProvider = new RegisteredSecurityDataTypesProvider();
            var securityService         = new SecurityService(_algorithm.Portfolio.CashBook,
                                                              MarketHoursDatabase.FromDataFolder(),
                                                              SymbolPropertiesDatabase.FromDataFolder(),
                                                              _algorithm,
                                                              registeredTypesProvider,
                                                              new SecurityCacheProvider(_algorithm.Portfolio));
            var universeSelection = new UniverseSelection(
                _algorithm,
                securityService,
                new DataPermissionManager(),
                new DefaultDataProvider(),
                Resolution.Second);

            _dataManager = new DataManager(_dataFeed, universeSelection, _algorithm, new TimeKeeper(DateTime.UtcNow, TimeZones.NewYork),
                                           MarketHoursDatabase.FromDataFolder(),
                                           true,
                                           new RegisteredSecurityDataTypesProvider(),
                                           new DataPermissionManager());
            _synchronizer.Initialize(_algorithm, _dataManager);
            _dataFeed.Initialize(_algorithm,
                                 new LiveNodePacket(),
                                 new TestResultHandler(),
                                 new LocalDiskMapFileProvider(),
                                 new LocalDiskFactorFileProvider(),
                                 new DefaultDataProvider(),
                                 _dataManager,
                                 _synchronizer,
                                 new DataChannelProvider());
            _algorithm.SubscriptionManager.SetDataManager(_dataManager);
            _algorithm.Securities.SetSecurityService(securityService);
            _algorithm.SetFinishedWarmingUp();
            _algorithm.Transactions.SetOrderProcessor(new FakeOrderProcessor());
        }
Beispiel #27
0
        public void DoSynchronization_GroupHasDoDeletePolicy_DeletionIsPropagated()
        {
            using (var from = new TemporaryFolder("synctest_source"))
                using (var to = new TemporaryFolder("synctest_dest"))
                {
                    File.WriteAllText(from.Combine("test1.txt"), "Blah blah");
                    var source = new RawDirectoryGroup("1", from.Path, null, null);
                    var groups = new List <FileGroup>(new[] { source });
                    var sync   = new Synchronizer(to.Path, groups, 100, new NullProgress());
                    sync.DoSynchronization();

                    //should be there at the destination
                    AssertFileExists(sync, source, to, "test1.txt");
                    File.Delete(from.Combine("test1.txt"));

                    File.WriteAllText(from.Combine("test2.txt"), "Blah blah");
                    sync = new Synchronizer(to.Path, groups, 100, new NullProgress());
                    sync.DoSynchronization();

                    AssertFileDoesNotExist(sync, source, to, "test1.txt");
                }
        }
        public void Setup()
        {
            _genesisBlock   = Build.A.Block.WithNumber(0).TestObject;
            _blockTree      = Build.A.BlockTree(_genesisBlock).OfChainLength(1).TestObject;
            _stateDb        = new StateDb();
            _codeDb         = new StateDb();
            _receiptsDb     = new MemDb();
            _receiptStorage = Substitute.For <IReceiptStorage>();
            SyncConfig quickConfig = new SyncConfig();

            quickConfig.FastSync = false;

            ISealValidator  sealValidator  = Build.A.SealValidator.ThatAlwaysReturnsTrue.TestObject;
            IBlockValidator blockValidator = Build.A.BlockValidator.ThatAlwaysReturnsTrue.TestObject;
            ITxValidator    txValidator    = Build.A.TransactionValidator.ThatAlwaysReturnsTrue.TestObject;

            var stats = new NodeStatsManager(new StatsConfig(), LimboLogs.Instance);

            _pool         = new EthSyncPeerPool(_blockTree, stats, quickConfig, 25, LimboLogs.Instance);
            _synchronizer = new Synchronizer(MainNetSpecProvider.Instance, _blockTree, NullReceiptStorage.Instance, blockValidator, sealValidator, _pool, quickConfig, Substitute.For <INodeDataDownloader>(), LimboLogs.Instance);
            _syncServer   = new SyncServer(_stateDb, _codeDb, _blockTree, _receiptStorage, sealValidator, _pool, _synchronizer, quickConfig, LimboLogs.Instance);
        }
Beispiel #29
0
        /// <summary>
        /// Synchronizes resources with underlying storage
        /// </summary>
        /// <param name="builder">ASP.NET Core application builder</param>
        /// <returns>ASP.NET Core application builder to enable fluent API call chains</returns>
        public static IApplicationBuilder UseDbLocalizationProvider(this IApplicationBuilder builder)
        {
            var logger  = builder?.ApplicationServices.GetService <ILogger <LoggerAdapter> >();
            var context = ConfigurationContext.Current;

            if (logger != null)
            {
                context.Logger = new LoggerAdapter(logger);
            }

            // if we need to sync - then it's good time to do it now
            var sync = new Synchronizer();

            sync.SyncResources(context.DiscoverAndRegisterResources);

            if (!context.DiscoverAndRegisterResources)
            {
                context.Logger?.Info($"{nameof(context.DiscoverAndRegisterResources)}=false. Resource synchronization skipped.");
            }

            return(builder);
        }
Beispiel #30
0
        /// <summary>
        /// Draw the slide for printing.
        /// Note: This code first prints to an image and then to the page to allow for transparency and anti-aliasing
        /// </summary>
        /// <param name="traversal">The deck traversal to draw from</param>
        /// <param name="index">The slide index in the deck to draw</param>
        /// <param name="displayBounds">The bounds to draw the slide in</param>
        /// <param name="g">The graphics context to draw onto</param>
        private void DrawSlide3(DeckTraversalModel traversal, int index, System.Drawing.Rectangle displayBounds, System.Drawing.Graphics g)
        {
            using (Synchronizer.Lock(traversal.SyncRoot)) {
                using (Synchronizer.Lock(traversal.Deck.SyncRoot)) {
                    using (Synchronizer.Lock(traversal.Deck.TableOfContents.SyncRoot)) {
                        TableOfContentsModel.Entry currentEntry = traversal.Deck.TableOfContents.Entries[index];

                        // Get the background color and background template
                        Color background            = Color.Transparent;
                        BackgroundTemplate template = null;
                        using (Synchronizer.Lock(currentEntry.Slide.SyncRoot)) {
                            if (currentEntry.Slide.BackgroundTemplate != null)
                            {
                                template = currentEntry.Slide.BackgroundTemplate;
                            }
                            else if (traversal.Deck.DeckBackgroundTemplate != null)
                            {
                                template = traversal.Deck.DeckBackgroundTemplate;
                            }
                            if (currentEntry.Slide.BackgroundColor != Color.Empty)
                            {
                                background = currentEntry.Slide.BackgroundColor;
                            }
                            else if (traversal.Deck.DeckBackgroundColor != Color.Empty)
                            {
                                background = traversal.Deck.DeckBackgroundColor;
                            }
                        }

                        Bitmap toExport = PPTDeckIO.DrawSlide(currentEntry, template, background, SheetDisposition.Background | SheetDisposition.Public | SheetDisposition.Student | SheetDisposition.All);

                        Rectangle newRect = FillUpRectangle(displayBounds, new Rectangle(0, 0, toExport.Width, toExport.Height));
                        this.DrawSlideBorder(index + 1, newRect, g);
                        g.DrawImage(toExport, newRect);
                        toExport.Dispose();
                    }
                }
            }
        }
        private void BufferPackets(int stylusId, int strokeId, int[] packets)
        {
            using (Synchronizer.Lock(this)) {
                List <int> buffer;
                if (!this.PacketBuffers.TryGetValue(stylusId, out buffer))
                {
                    this.PacketBuffers.Add(stylusId, buffer = new List <int>());
                }

                buffer.AddRange(packets);

                long flushed;
                if (this.PacketFlushTimes.TryGetValue(stylusId, out flushed))
                {
                    long difference = DateTime.Now.Ticks - flushed;
                    if (difference >= PacketBufferFlushTime)
                    {
                        this.FlushPackets(stylusId, strokeId);
                    }
                }
            }
        }
Beispiel #32
0
        public void After2Syncs_WithFilter_OnlyFilteredItemsShown()
        {
            var synchronizer = Synchronizer.FromProjectConfiguration(_project, new NullProgress());

            synchronizer.SyncNow(new SyncOptions()
            {
                CheckinDescription = "show me"
            });
            WriteTestFile("two");
            synchronizer.SyncNow(new SyncOptions()
            {
                CheckinDescription = "hide me"
            });
            WriteTestFile("three");
            synchronizer.SyncNow(new SyncOptions()
            {
                CheckinDescription = "show me"
            });
            var items = _model.GetAllRevisions();

            Assert.AreEqual(2, items.Count());
        }
Beispiel #33
0
        public SyncControlModel(ProjectFolderConfiguration projectFolderConfiguration,
                                SyncUIFeatures uiFeatureFlags,
                                IChorusUser user)
        {
            _user          = user;
            _progress      = new MultiProgress();
            StatusProgress = new SimpleStatusProgress();
            _progress.Add(StatusProgress);
            Features          = uiFeatureFlags;
            _synchronizer     = Synchronizer.FromProjectConfiguration(projectFolderConfiguration, _progress);
            _backgroundWorker = new BackgroundWorker();
            _backgroundWorker.WorkerSupportsCancellation = true;
            _backgroundWorker.RunWorkerCompleted        += new RunWorkerCompletedEventHandler(_backgroundWorker_RunWorkerCompleted);
            _backgroundWorker.DoWork += worker_DoWork;

            //clients will normally change these
            SyncOptions = new SyncOptions();
            SyncOptions.CheckinDescription = "[" + Application.ProductName + ": " + Application.ProductVersion + "] sync";
            SyncOptions.DoPullFromOthers   = true;
            SyncOptions.DoMergeWithOthers  = true;
            SyncOptions.RepositorySourcesToTry.AddRange(GetRepositoriesToList().Where(r => r.Enabled));
        }
Beispiel #34
0
        public void GetInfo_FileExistsButHasChanged_WillBeReplaced()
        {
            using (var from = new TemporaryFolder("synctest_source"))
                using (var to = new TemporaryFolder("synctest_dest"))
                {
                    System.IO.File.WriteAllText(from.Combine("test1.txt"), "Blah blah");
                    System.IO.File.WriteAllText(from.Combine("test2.txt"), "dee dee dee");
                    var source = new RawDirectoryGroup("1", from.Path, null, null);
                    var groups = new List <FileGroup>(new[] { source });
                    var sync   = new Synchronizer(to.Path, groups, 100, new NullProgress());
                    sync.GatherPreview();
                    sync.DoSynchronization();
                    System.IO.File.WriteAllText(from.Combine("test1.txt"), "Blah blah Blah Blah Blah");
                    sync = new Synchronizer(to.Path, groups, 100, new NullProgress());
                    sync.GatherPreview();

                    Assert.AreEqual(1, source.UpdateFileCount);
                    Assert.AreEqual(0, source.DeleteFileCount);
                    Assert.AreEqual(0, source.NewFileCount);
                    Assert.AreEqual(15, source.NetChangeInBytes);
                }
        }
        public void SyncNow_UsbGetsBackwardCompatibleBareCloneWithReadme()
        {
            Synchronizer synchronizer = Synchronizer.FromProjectConfiguration(_project, _progress);
            SyncOptions  options      = new SyncOptions();

            options.DoMergeWithOthers = true;
            options.DoSendToOthers    = true;
            options.RepositorySourcesToTry.Add(synchronizer.UsbPath);

            WriteTestFile("version two");

            synchronizer.SyncNow(options);
            var projectDir = Path.Combine(UsbKeyRepositorySource.RootDirForUsbSourceDuringUnitTest, "foo project");

            Assert.IsTrue(Directory.Exists(projectDir));
            // SUT backward compatible clone has no dotencode in the requires file
            var requiresLines = File.ReadAllLines(Path.Combine(projectDir, ".hg", "requires"));

            CollectionAssert.DoesNotContain(requiresLines, "dotencode");
            // SUT bare clone should get this text file
            Assert.IsTrue(File.Exists(projectDir.CombineForPath(projectDir, "~~Folder has an invisible repository.txt")));
        }
Beispiel #36
0
            protected override void OnClick(EventArgs e)
            {
                base.OnClick(e);

                PrintDocument doc;

                using (Synchronizer.Lock(this.model.ViewerState.SyncRoot))
                    doc = this.model.ViewerState.Document;
                PrintDialog dialog = new PrintDialog();

                dialog.AllowPrintToFile = true;
                dialog.AllowSelection   = false;
                dialog.AllowCurrentPage = false;
                dialog.AllowSomePages   = true;
                dialog.UseEXDialog      = true;
                dialog.Document         = doc;
                // Set the page settings
                doc.DefaultPageSettings            = this.m_Parent.PageSettings;
                dialog.PrinterSettings.MinimumPage = 0;
                dialog.PrinterSettings.MaximumPage = 9999;

                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    // Set the deck
                    using (this.model.Workspace.Lock())
                        using (Synchronizer.Lock(this.model.ViewerState.SyncRoot))
                            this.model.ViewerState.PrintableDeck = this.model.Workspace.CurrentDeckTraversal;

                    // Get the maximum and minimum page
                    using (Synchronizer.Lock(this.model.ViewerState.SyncRoot)) {
                        doc.PrinterSettings.MinimumPage = 1;
                        using (Synchronizer.Lock(this.model.ViewerState.PrintableDeck.SyncRoot))
                            using (Synchronizer.Lock(this.model.ViewerState.PrintableDeck.Deck.SyncRoot))
                                doc.PrinterSettings.MaximumPage = this.model.ViewerState.PrintableDeck.Deck.Slides.Count;
                    }

                    doc.Print();
                }
            }
    public virtual void SetUp()
    {
      dir = this.TestDirectory; 
      dir = Path.GetFullPath(Path.Combine(AppDomain.CurrentDomain.BaseDirectory, dir)); 
  
      if (Directory.Exists(dir))
      {
        Directory.Delete(dir, true); 
      }
      Directory.CreateDirectory(dir); 

      Directory.SetCurrentDirectory(dir); 

      proxy = UnitTests.GetMockServiceProxy(); 

      sync = new Synchronizer(dir, proxy); 

      Assert.AreEqual(0, Directory.GetFiles(sync.BaseDirectory).Length, 
        "Checking that there are no local files"); 
      Assert.AreEqual(0, Directory.GetDirectories(sync.BaseDirectory).Length, 
        "Checking that there are no local files"); 
    }
Beispiel #38
0
        static SqlPreCommand SynchronizeQueries(Replacements replacements)
        {
            var should = GenerateQueries();

            var current = Administrator.TryRetrieveAll <QueryEntity>(replacements);

            Table table = Schema.Current.Table <QueryEntity>();

            using (replacements.WithReplacedDatabaseName())
                return(Synchronizer.SynchronizeScriptReplacing(
                           replacements,
                           QueriesKey,
                           should.ToDictionaryEx(a => a.Key, "query in memory"),
                           current.ToDictionaryEx(a => a.Key, "query in database"),
                           (n, s) => table.InsertSqlSync(s),
                           (n, c) => table.DeleteSqlSync(c),
                           (fn, s, c) =>
                {
                    c.Key = s.Key;
                    return table.UpdateSqlSync(c);
                }, Spacing.Double));
        }
                public PenWidthUpDown(ViewerStateModel vsm, Point location, Size size, int tabIndex)
                {
                    this.m_VSModel = vsm;
                    this.SuspendLayout();

                    this.Location = location;
                    this.Size     = size;
                    this.TabIndex = tabIndex;
                    this.Name     = "PenWidthUpDown";
                    this.Minimum  = 0;
                    this.Maximum  = 1024;
                    this.Enabled  = true;

                    int currValue;

                    using (Synchronizer.Lock(this.m_VSModel.SyncRoot)) {
                        currValue = this.m_VSModel.DefaultPenWidth;
                    }
                    this.Value = currValue;

                    this.ResumeLayout();
                }
                public UseLightColorCheckBox(ViewerStateModel model, Point location, Size size, int tabIndex)
                {
                    this.m_Model = model;

                    this.SuspendLayout();

                    this.FlatStyle = FlatStyle.System;
                    this.Location  = location;
                    this.Size      = size;
                    this.TabIndex  = tabIndex;
                    this.Name      = "UseLightColorCheckBox";
                    this.Text      = Strings.UseLightColorSet;

                    bool bShouldBeChecked;

                    using (Synchronizer.Lock(model.SyncRoot))
                        bShouldBeChecked = model.UseLightColorSet;
                    this.Checked    = bShouldBeChecked;
                    this.CheckState = bShouldBeChecked ? CheckState.Checked : CheckState.Unchecked;

                    this.ResumeLayout();
                }
Beispiel #41
0
        /// <summary>
        /// Constructor of LiNGS Client. Creates a new instance of <see cref="LiNGSClient"/>.
        /// </summary>
        /// <exception cref="ArgumentNullException">When any of the params is null.</exception>
        /// <param name="properties">Properties of the client. These properties cannot be changed after the server is running.</param>
        /// <param name="serverInfo">Information used to connect to the server.</param>
        /// <param name="networkedClient">Game logic to receive callbacks and manage game objects.</param>
        public LiNGSClient(ClientProperties properties, ServerInfo serverInfo, INetworkedClient networkedClient)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("The client properties cannot be null.");
            }

            if (serverInfo == null)
            {
                throw new ArgumentNullException("The server information cannot be null.");
            }

            if (networkedClient == null)
            {
                throw new ArgumentNullException("The networkedClient cannot be null.");
            }

            this.UpdateManager    = new UpdateManager();
            this.ClientProperties = new ClientProperties(properties);
            this.ServerInfo       = new ServerInfo(serverInfo);

            NetworkManager          = new NetworkManager(this, ServerInfo.IP, ServerInfo.Port);
            Router                  = new Router(this);
            MessageAggregator       = new MessageAggregator(this);
            Manager                 = new Manager(this);
            Analyzer                = new Analyzer(this);
            ClientLogicProcessor    = new ClientLogicProcessor(this);
            Simulator               = new Simulator(this);
            Synchronizer            = new Synchronizer(this);
            ClientStatus            = new ClientStatus(this);
            NetworkedClientInstance = networkedClient;

            this.UpdateManager.AddUpdatable(MessageAggregator);
            this.UpdateManager.AddUpdatable(Manager);
            this.UpdateManager.AddUpdatable(Analyzer);
            this.UpdateManager.AddUpdatable(ClientLogicProcessor);
            this.UpdateManager.AddUpdatable(Simulator);
            this.UpdateManager.AddUpdatable(Synchronizer);
        }
Beispiel #42
0
            public SyncingContext(SynchronizerType synchronizerType)
            {
                _logger = _logManager.GetClassLogger();
                ISyncConfig syncConfig = new SyncConfig();

                syncConfig.FastSync = synchronizerType == SynchronizerType.Fast;
                ISnapshotableDb stateDb     = new StateDb();
                ISnapshotableDb codeDb      = new StateDb();
                MemDb           blockInfoDb = new MemDb();

                BlockTree = new BlockTree(new MemDb(), new MemDb(), blockInfoDb, new ChainLevelInfoRepository(blockInfoDb), new SingleReleaseSpecProvider(Constantinople.Instance, 1), NullTxPool.Instance, NullBloomStorage.Instance, _logManager);
                NodeStatsManager stats = new NodeStatsManager(new StatsConfig(), _logManager);

                SyncPeerPool = new EthSyncPeerPool(BlockTree, stats, 25, _logManager);

                NodeDataFeed feed = new NodeDataFeed(codeDb, stateDb, _logManager);

                NodeDataDownloader nodeDataDownloader = new NodeDataDownloader(SyncPeerPool, feed, NullDataConsumer.Instance, _logManager);

                Synchronizer = new Synchronizer(
                    MainNetSpecProvider.Instance,
                    BlockTree,
                    NullReceiptStorage.Instance,
                    TestBlockValidator.AlwaysValid,
                    TestSealValidator.AlwaysValid,
                    SyncPeerPool,
                    syncConfig,
                    nodeDataDownloader,
                    stats,
                    _logManager);

                SyncServer = new SyncServer(stateDb, codeDb, BlockTree, NullReceiptStorage.Instance, TestBlockValidator.AlwaysValid, TestSealValidator.AlwaysValid, SyncPeerPool, Synchronizer, syncConfig, _logManager);
                SyncPeerPool.Start();

                Synchronizer.Start();
                Synchronizer.SyncEvent += SynchronizerOnSyncEvent;

                AllInstances.Add(this);
            }
Beispiel #43
0
        /// <summary>
        /// Paints the text of the textsheetmodel onto the slide using the DrawString method.
        /// </summary>
        /// <param name="args"></param>
        public override void Paint(PaintEventArgs args)
        {
            using (Synchronizer.Lock(this.SlideDisplay.SyncRoot)) {
                if (!m_Sheet.Visible)
                {
                    return;
                }
            }
            Graphics g = args.Graphics;

            using (Synchronizer.Lock(this.SlideDisplay.SyncRoot)) {
                ///transform what we will paint so that it will fit nicely into our slideview
                g.Transform = this.SlideDisplay.PixelTransform;
            }
            using (Synchronizer.Lock(this.m_Sheet.SyncRoot)) {
                Font  f = m_Sheet.Font;
                Brush b = new SolidBrush(m_Sheet.Color);
                bool  sheet_is_editable = m_Sheet.IsEditable;

                g.DrawString(this.m_Sheet.Text, f, b, this.m_Sheet.Bounds);
            }
        }
Beispiel #44
0
        public void Setup()
        {
            _progress       = new StringBuilderProgress();
            _pathToTestRoot = Path.Combine(Path.GetTempPath(), "ChorusTest");
            Directory.CreateDirectory(_pathToTestRoot);


            string pathToText = Path.Combine(_pathToTestRoot, "foo.txt");

            File.WriteAllText(pathToText, "version one of my pretend txt");

            RepositorySetup.MakeRepositoryForTest(_pathToTestRoot, "bob", _progress);

            _project            = new ProjectFolderConfiguration(_pathToTestRoot);
            _project.FolderPath = _pathToTestRoot;
            _project.IncludePatterns.Add(pathToText);
            _project.FolderPath = _pathToTestRoot;

            _synchronizer = Synchronizer.FromProjectConfiguration(_project, new NullProgress());
            _model        = new SyncControlModel(_project, SyncUIFeatures.Advanced, null);
            _model.AddMessagesDisplay(_progress);
        }
Beispiel #45
0
            protected override void TearDownMember(int index, object member, object tag)
            {
                //Remove a ClassroomModel so that it will not appear in the UI.
                //Note that we don't dispose the *ClassroomManager here because we don't want it to disconnect.
                TCPClientClassroomManager mgr = tag as TCPClientClassroomManager;

                if (mgr != null)
                {
                    using (Synchronizer.Lock(this.m_Parent.m_TCPConnectionMgr.Protocol.SyncRoot)) {
                        this.m_Parent.m_TCPConnectionMgr.Protocol.Classrooms.Remove(mgr.Classroom);
                    }
                }
#if RTP_BUILD
                RTPClassroomManager rtpMgr = tag as RTPClassroomManager;
                if (rtpMgr != null)
                {
                    using (Synchronizer.Lock(this.m_Parent.m_RTPConnectionMgr.Protocol.SyncRoot)) {
                        this.m_Parent.m_RTPConnectionMgr.Protocol.Classrooms.Remove(rtpMgr.Classroom);
                    }
                }
#endif
            }
Beispiel #46
0
        /// <summary>
        /// Handle when a basic change happens to the InstructorModel
        /// </summary>
        /// <param name="sender">The object that posted this event</param>
        /// <param name="args">The arguments for this event</param>
        private void HandleGenericChange(object sender, PropertyEventArgs args)
        {
            bool acceptingSS = false;
            bool acceptingQP = false;
            bool forceLink   = false;

            // Get the slide and deck index
            using (Synchronizer.Lock(this.m_Instructor.SyncRoot))
            {
                acceptingSS = this.m_Instructor.AcceptingStudentSubmissions;
                acceptingQP = this.m_Instructor.AcceptingQuickPollSubmissions;
                forceLink   = this.m_Instructor.ForcingStudentNavigationLock;
            }

            // Change the SimpleWebModel
            lock (WebService.Instance.GlobalModel) {
                WebService.Instance.GlobalModel.AcceptingSS = acceptingSS;
                WebService.Instance.GlobalModel.AcceptingQP = acceptingQP;
                WebService.Instance.GlobalModel.ForceLink   = forceLink;
            }
            WebService.Instance.UpdateModel();
        }
Beispiel #47
0
            public void HandleSecondMonitorChanged(object sender, PropertyEventArgs args)
            {
                bool bShouldBeChecked = true;

                if (this.m_Model != null)
                {
                    using (Synchronizer.Lock(this.m_Model.ViewerState.SyncRoot)) {
                        bShouldBeChecked = this.m_Model.ViewerState.SecondMonitorEnabled;
                    }
                }

                if (bShouldBeChecked)
                {
                    this.Checked    = true;
                    this.CheckState = CheckState.Checked;
                }
                else
                {
                    this.Checked    = false;
                    this.CheckState = CheckState.Unchecked;
                }
            }
        protected override Task <bool> TryGetChannelAsync(TimeSpan timeout)
        {
            CommunicationState currentState = State;
            TChannel           channel      = null;

            if ((currentState == CommunicationState.Created) ||
                (currentState == CommunicationState.Opening) ||
                (currentState == CommunicationState.Opened))
            {
                channel = _factory.CreateChannel(_to, Via);
                if (!Synchronizer.SetChannel(channel))
                {
                    channel.Abort();
                }
            }
            else
            {
                channel = null;
            }

            return(Task.FromResult(true));
        }
Beispiel #49
0
 void StartupForm_FormClosing(object sender, FormClosingEventArgs e)
 {
     if (!(this.m_StartJoinButton.clicked))
     {
         using (Synchronizer.Lock(this.m_Model.Participant.SyncRoot)) {
             if (!(this.m_Model.Participant.Role is InstructorModel))
             {
                 this.m_Model.Participant.Role = new InstructorModel(Guid.NewGuid());
             }
         }
         using (Synchronizer.Lock(this.m_Model.ViewerState.SyncRoot)) {
             this.m_Model.ViewerState.iRole = 0;
         }
         if (this.m_Connection != null &&
             this.m_Connection.m_ManualConnectionPanel != null)
         {
             this.m_Connection.m_ManualConnectionPanel.DisconnectAllButtons();
         }
         this.m_StartJoinButton.Association = null;
         StartJoinButton2.StartEmptyPresentation(this.m_Model);
     }
 }
Beispiel #50
0
        SqlPreCommand SyncViews(Replacements replacements)
        {
            var oldView = Schema.Current.DatabaseNames().SelectMany(db =>
            {
                using (Administrator.OverrideDatabaseInSysViews(db))
                {
                    return((from v in Database.View <SysViews>()
                            join s in Database.View <SysSchemas>() on v.schema_id equals s.schema_id
                            join m in Database.View <SysSqlModules>() on v.object_id equals m.object_id
                            select KVP.Create(new ObjectName(new SchemaName(db, s.name), v.name), m.definition)).ToList());
                }
            }).ToDictionary();

            using (replacements.WithReplacedDatabaseName())
                return(Synchronizer.SynchronizeScript(Spacing.Double,
                                                      Views,
                                                      oldView,
                                                      createNew: (name, newView) => newView.CreateView(),
                                                      removeOld: null,
                                                      mergeBoth: (name, newDef, oldDef) => Clean(newDef.CreateView().Sql) == Clean(oldDef) ? null : newDef.AlterView()
                                                      ));
        }
Beispiel #51
0
        private static ExitCode Invoke()
        {
            try
            {
                var args = Environment.GetCommandLineArgs().Skip(1).ToArray();
                Write.Trace.Line($"Argument List: {string.Join(",", args)}");

                Git.Git.Initialize(args);
                var synchronizer = new Synchronizer();
                synchronizer.Initialize(args);
                var command = Command.GetCommand(args);
                if (command == null)
                {
                    Write.Error.Line($"Invalid usage: {Path.GetFileName(Assembly.GetExecutingAssembly().Location)} {Command.GetCommandLineArgsList()} <\"Git Repository Path\"> [\"Post Command File Path\"] [\"Post Command Arguments\"]");
                    return ExitCode.ERROR_BAD_ARGUMENTS;
                }

                return command.Invoke(synchronizer);
            }
            catch (System.Net.WebException e) when (e.Status == System.Net.WebExceptionStatus.ConnectFailure)
            {
                Write.Error.Line($"GitHub synchronizer cannot continue, unable connect to '{e.Message}'");
                return ExitCode.ERROR_BAD_COMMAND;
            }
            catch (Exception e)
            {
                Write.Error.Line($"ERROR: {e.Message}");
                Write.Error.Line(e.StackTrace);
                Write.Error.PressAnyKeyToContinue();

                if (e is GitException)
                    return ((GitException)e).ExitCode;
                else
                    return ExitCode.ERROR_BAD_ENVIRONMENT;
            }
        }
 public Waiter(AtomicBoolean stop, AtomicBoolean checkPoint, DocumentsWriterStallControl ctrl, Synchronizer sync, IList<Exception> exceptions)
     : base("waiter")
 {
     this.Stop = stop;
     this.CheckPoint = checkPoint;
     this.Ctrl = ctrl;
     this.Sync = sync;
     this.Exceptions = exceptions;
 }
Beispiel #53
0
        private void Init()
        {
            memoryManager = new SimpleMemoryManager(this);
            PauseEvent = new ManualResetEvent(true);
            hooks = hooks ?? new Dictionary<uint, HookDescriptor>();
            sync = new Synchronizer();
            haltedFinishedEvent = new AutoResetEvent(false);
            waitHandles = interruptEvents.Cast<WaitHandle>().Union(new EventWaitHandle[] { PauseEvent, haltedFinishedEvent }).ToArray();

            if(currentMappings == null)
            {
                currentMappings = new List<SegmentMapping>();
            }
            onTranslationBlockFetch = OnTranslationBlockFetch;

            var libraryResource = string.Format("Emul8.translate_{0}-{1}-{2}.so", IntPtr.Size * 8, Architecture, Endianness == Endianess.BigEndian ? "be" : "le");
            libraryFile = GetType().Assembly.FromResourceToTemporaryFile(libraryResource);

            binder = new NativeBinder(this, libraryFile);
            TlibSetTranslationCacheSize(checked((IntPtr)translationCacheSize));
            MaximumBlockSize = DefaultMaximumBlockSize;
            var result = TlibInit(cpuType);
            if(result == -1)
            {
                throw new InvalidOperationException("Unknown cpu type");
            }
            if(cpuState != null)
            {
                var statePtr = TlibExportState();
                Marshal.Copy(cpuState, 0, statePtr, cpuState.Length);
                AfterLoad(statePtr);
            }
            HandleRamSetup();
            foreach(var hook in hooks)
            {
                TlibAddBreakpoint(hook.Key);
            }
            EmulSetCountThreshold(currentCountThreshold);
        }
    private OutlookSynchronizer CreateContactSynchronizer (Options options)
    {
      var atypeRepository = new OutlookContactRepository (
          _outlookSession,
          options.OutlookFolderEntryId,
          options.OutlookFolderStoreId);


      IEntityRepository<vCard, Uri, string> btypeRepository = new CardDavRepository (
          new CardDavDataAccess (
              new Uri (options.CalenderUrl),
              CreateWebDavClient (
                  options.UserName,
                  options.Password,
                  _calDavConnectTimeout,
                  options.ServerAdapterType,
                  options.CloseAfterEachRequest,
                  options.ProxyOptions)));

      var entityRelationDataFactory = new OutlookContactRelationDataFactory();

      var syncStateFactory = new EntitySyncStateFactory<string, DateTime, ContactItemWrapper, Uri, string, vCard> (
          new ContactEntityMapper(),
          atypeRepository,
          btypeRepository,
          entityRelationDataFactory,
          ExceptionHandler.Instance);

      var btypeIdEqualityComparer = EqualityComparer<Uri>.Default;
      var atypeIdEqulityComparer = EqualityComparer<string>.Default;

      var storageDataDirectory = _profileDataDirectoryFactory (options.Id);

      var storageDataAccess = new EntityRelationDataAccess<string, DateTime, OutlookContactRelationData, Uri, string> (storageDataDirectory);

      var synchronizer = new Synchronizer<string, DateTime, ContactItemWrapper, Uri, string, vCard> (
          atypeRepository,
          btypeRepository,
          InitialContactSyncStateCreationStrategyFactory.Create (
              syncStateFactory,
              syncStateFactory.Environment,
              options.SynchronizationMode,
              options.ConflictResolution),
          storageDataAccess,
          entityRelationDataFactory,
          new InitialContactEntityMatcher (btypeIdEqualityComparer),
          atypeIdEqulityComparer,
          btypeIdEqualityComparer,
          _totalProgressFactory,
          ExceptionHandler.Instance);

      return new OutlookSynchronizer (synchronizer, atypeRepository);
    }
Beispiel #55
0
 public Loop(WorkflowProcess workflowProcess, String name, Synchronizer fromNode, Synchronizer toNode)
     : base(workflowProcess, name)
 {
     this.FromNode = fromNode;
     this.ToNode = toNode;
 }
        public virtual void TestAccquireReleaseRace()
        {
            DocumentsWriterStallControl ctrl = new DocumentsWriterStallControl();
            ctrl.UpdateStalled(false);
            AtomicBoolean stop = new AtomicBoolean(false);
            AtomicBoolean checkPoint = new AtomicBoolean(true);

            int numStallers = AtLeast(1);
            int numReleasers = AtLeast(1);
            int numWaiters = AtLeast(1);
            var sync = new Synchronizer(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
            var threads = new ThreadClass[numReleasers + numStallers + numWaiters];
            IList<Exception> exceptions = new SynchronizedCollection<Exception>();
            for (int i = 0; i < numReleasers; i++)
            {
                threads[i] = new Updater(stop, checkPoint, ctrl, sync, true, exceptions);
            }
            for (int i = numReleasers; i < numReleasers + numStallers; i++)
            {
                threads[i] = new Updater(stop, checkPoint, ctrl, sync, false, exceptions);
            }
            for (int i = numReleasers + numStallers; i < numReleasers + numStallers + numWaiters; i++)
            {
                threads[i] = new Waiter(stop, checkPoint, ctrl, sync, exceptions);
            }

            Start(threads);
            int iters = AtLeast(10000);
            float checkPointProbability = TEST_NIGHTLY ? 0.5f : 0.1f;
            for (int i = 0; i < iters; i++)
            {
                if (checkPoint.Get())
                {
                    Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)), "timed out waiting for update threads - deadlock?");
                    if (exceptions.Count > 0)
                    {
                        foreach (Exception throwable in exceptions)
                        {
                            Console.WriteLine(throwable.ToString());
                            Console.Write(throwable.StackTrace);
                        }
                        Assert.Fail("got exceptions in threads");
                    }

                    if (ctrl.HasBlocked() && ctrl.Healthy)
                    {
                        AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
                    }

                    checkPoint.Set(false);
                    sync.Waiter.countDown();
                    sync.LeftCheckpoint.@await();
                }
                Assert.IsFalse(checkPoint.Get());
                Assert.AreEqual(0, sync.Waiter.Remaining);
                if (checkPointProbability >= (float)Random().NextDouble())
                {
                    sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
                    checkPoint.Set(true);
                }
            }
            if (!checkPoint.Get())
            {
                sync.Reset(numStallers + numReleasers, numStallers + numReleasers + numWaiters);
                checkPoint.Set(true);
            }

            Assert.IsTrue(sync.UpdateJoin.@await(new TimeSpan(0, 0, 0, 10)));
            AssertState(numReleasers, numStallers, numWaiters, threads, ctrl);
            checkPoint.Set(false);
            stop.Set(true);
            sync.Waiter.countDown();
            sync.LeftCheckpoint.@await();

            for (int i = 0; i < threads.Length; i++)
            {
                ctrl.UpdateStalled(false);
                threads[i].Join(2000);
                if (threads[i].IsAlive && threads[i] is Waiter)
                {
                    if (threads[i].State == ThreadState.WaitSleepJoin)
                    {
                        Assert.Fail("waiter is not released - anyThreadsStalled: " + ctrl.AnyStalledThreads());
                    }
                }
            }
        }
Beispiel #57
0
        private static void OnSelectedItemsChanged(DependencyObject dependencyObject, DependencyPropertyChangedEventArgs e)
        {
            if (e.OldValue != null)
            {
                Synchronizer synchronizer = GetSynchronizer(dependencyObject);
                synchronizer.Stop();

                SetSynchronizer(dependencyObject, null);
            }

            var list = dependencyObject as ListViewBase;
            var collection = e.NewValue as IList;
            var collectionEvents = e.NewValue as INotifyCollectionChanged;

            // check that this property is an IList, and that it is being set on a ListBox
            if (list != null && collection != null)
            {
                Synchronizer synchronizer = GetSynchronizer(dependencyObject);
                if (synchronizer == null)
                {
                    synchronizer = new Synchronizer(list, collection, collectionEvents);
                    SetSynchronizer(dependencyObject, synchronizer);
                }

                synchronizer.Start();
            }
        }
Beispiel #58
0
 public void Setup() {
     sut = new Synchronizer<int>();
     sut.Result += x => result = x;
 }
Beispiel #59
0
 public Program.ExitCode Invoke(Synchronizer synchronizer)
 {
     return _action.Invoke(synchronizer);
 }
Beispiel #60
0
 /// <summary>
 /// Sets the synchronizer for the list.
 /// </summary>
 private static void SetSynchronizer(DependencyObject dependencyObject, Synchronizer value)
 {
     dependencyObject.SetValue(SynchronizerProperty, value);
 }