예제 #1
0
        public void Task_Then_Action__Cancelled()
        {
            var source = new CancellationTokenSource();
            CancellationToken token = source.Token;

            var syncer = new Syncer();

            var  mock = new Mock <IAfter>();
            Task task = SimpleTaskFactory.Run(() =>
            {
                syncer.Step(1);
                syncer.Step(4);
                token.ThrowIfCancellationRequested();
            }, token)
                        .Then(() => SimpleTaskFactory.Run(() => mock.Object.NextAction(), token), token);

            syncer.Step(2);
            source.Cancel();
            syncer.Step(3);

            try
            {
                // ReSharper disable once MethodSupportsCancellation
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf <TaskCanceledException>(e.InnerException);
                mock.Verify(then => then.NextAction(), Times.Never);
                Assert.Pass();
            }
        }
예제 #2
0
        public void Init()
        {
            InMemoryHelper.FillData(sCfg, sSession, true);
            s = new Syncer(serverCon.ConnectionString, clientCon.ConnectionString, serverCon.ProviderName);

            Poster.MessagePosted += Syncer_MessagePosted;
        }
예제 #3
0
        bool IMainMaster.SetBot(Tank aiTank, int id)
        {
            int botSeatID = Singletons.gameRoutineController.RegisterNewTank(id);

            if (botSeatID == -1)
            {
                return(false);
            }
            aiTank.transform.position = birthPoints.points[botSeatID].position;
            aiTank.transform.rotation = birthPoints.points[botSeatID].rotation;
            clientTanks[botSeatID]    = aiTank;
            if (!isOffline)
            {
                Syncer newSyncer = PhotonNetwork.Instantiate(syncerPrefab.name,
                                                             clientTanks[botSeatID].transform.position,
                                                             clientTanks[botSeatID].transform.rotation, 0).GetComponent <Syncer>();

                int newSyncerID = newSyncer.photonView.viewID;
                aiTank.InitAI(botSeatID, true, newSyncer);
                photonView.RPC("RPCSetBot", PhotonTargets.Others, botSeatID, newSyncerID);
            }
            else
            {
                aiTank.InitAI(botSeatID, false);
            }
            statManager.AddTank(aiTank);
            return(true);
        }
예제 #4
0
        public async Task SaveVocToExchangeCreatesDoctorTable()
        {
            // выгружаем словари с сервера
            var sdfFileCon = new ConnectionInfo("exch.sdf", Constants.SqlCeProvider);
            var syncer     = new Syncer(
                serverConStr: serverCon.ConnectionString,
                clientConStr: sdfFileCon.ConnectionString,
                serverProviderName: serverCon.ProviderName);

            SqlHelper.CreateSqlCeByConStr(sdfFileCon.ConnectionString);

            var scopes = Scopes.GetOrderedDownloadScopes();
            await syncer.WithoutDoctors().SendFrom(Side.Server, scopes);

            // пробуем достать словари
            var nhib = NHibernateHelper.FromConnectionInfo(sdfFileCon, Side.Server);

            int exVocsCount;

            using (var s = nhib.OpenSession())
                using (var tr = s.BeginTransaction())
                {
                    exVocsCount = s.Query <Vocabulary>().Count();
                    // значит создана Doctors
                    var docsCount = s.Query <Doctor>().Count();
                }

            var serverVocsCount = sSession.Query <Vocabulary>().Count(); // даже пользовательские, их не должно быть на сервере

            Assert.AreEqual(serverVocsCount, exVocsCount);
        }
예제 #5
0
        public async Task LoadVoc_AddNewWt_SendVocScopeFromServer()
        {
            var l = new VocLoader(clSession);

            // load voc from server
            var voc = sSession.Get <Vocabulary>(IntToGuid <Vocabulary>(1));
            await s.OnlySelectedVocs(sSession, voc.ToEnumerable())
            .SendFrom(Side.Server, Scope.Voc);

            // добавляем шаблон в словарь на сервере
            voc.AddTemplates(new[] { "qwe" });
            sSession.DoSave(voc);

            // загружаем новые шаблоны для установленных словарей
            var cWtCount      = clSession.Query <WordTemplate>().Count();
            var installedVocs = sSession.Query <Vocabulary>();

            s = new Syncer(serverCon.ConnectionString, clientCon.ConnectionString, serverCon.ProviderName);
            await s.WithInstalledVocs(installedVocs)
            .SendFrom(Side.Server, Scope.Voc);

            new VocLoader(clSession).AfterSyncVocs(s.DeletedOnServerIdsPerType);

            Assert.AreEqual(cWtCount + 1, clSession.Query <WordTemplate>().Count());
        }
예제 #6
0
        public override void UpdateOnceBeforeFrame()
        {
            try
            {
                if (Drill.CubeGrid.Physics?.Enabled != true || !Networker.Inited)
                {
                    NeedsUpdate |= MyEntityUpdateEnum.BEFORE_NEXT_FRAME;
                    if (!Networker.Inited)
                    {
                        Networker.Init(SessionCore.ModID);
                    }
                    return;
                }
                SyncHarvestEfficiency = new Syncer <float>(Drill, "HarvestEfficiency", 1, Checker: val => val >= 1 && val <= 4);
                SyncHarvestEfficiency.GotValueFromServer += Drill.UpdateVisual;
                Drill.PowerConsumptionMultiplier          = PowerConsumptionMultiplier();

                CheckInitControls();
                Load();

                SessionCore.SaveRegister(Save);
                NeedsUpdate |= MyEntityUpdateEnum.EACH_FRAME;
                DebugNote    = MyAPIGateway.Utilities.CreateNotification($"{Drill?.CustomName}", int.MaxValue, "Blue");
                Owner        = MyAPIGateway.Players.GetPlayer(Drill.OwnerId);
                if (SessionCore.Settings.Debug)
                {
                    DebugNote.Show();
                }
            }
            catch { }
        }
예제 #7
0
        private async Task SetupBasic()
        {
            colClient = await Utils.GetEmptyCollection(tempFolder);

            var f = colClient.NewNote();

            f.SetItem("Front", "foo");
            f.SetItem("Back", "bar");
            f.Tags.Add("foo");
            colClient.AddNote(f);
            colClient.Reset();
            colClient.Sched.AnswerCard(colClient.Sched.PopCard(), Sched.AnswerEase.Easy);

            colServer = await Utils.GetEmptyCollection(tempFolder2, true);

            f = colServer.NewNote();
            f.SetItem("Front", "bar");
            f.SetItem("Back", "bar");
            f.Tags.Add("bar");
            colServer.AddNote(f);
            colServer.Reset();
            colServer.Sched.AnswerCard(colServer.Sched.PopCard(), Sched.AnswerEase.Easy);

            //Start with same schema and sync time
            colClient.Scm = 0;
            colServer.Scm = 0;

            //And same modified time, so sync does nothing
            long t = DateTimeOffset.Now.ToUnixTimeMilliseconds();

            colClient.Save(mod: t);
            colServer.Save(mod: t);
            server = new LocalServer(colServer);
            client = new Syncer(colClient, server);
        }
예제 #8
0
 public void InitAI(int _seatID, bool isOnServer, Syncer syncer = null)
 {
     if (isInitialized)
     {
         return;
     }
     seatID = _seatID;
     body.Init();
     motion.SetMode(isOnServer ? TankMode.Server : TankMode.Local);
     if (isOnServer)
     {
         motion.tankNetworkComponents.Set(syncer);
     }
     AIController.Init(TankAIState.waiting);
     isInitialized = true;
     if (seatID != Global.GameState.playerID)
     {
         textDisplayer.Init(Colors[2 * seatID / Global.Global.playerPerRoom], seatID.ToString());
     }
     else
     {
         textDisplayer.gameObject.SetActive(false);
     }
     UpdateTankInfo();
 }
예제 #9
0
        public void Task_CatchSpecificException__FirstCancelled()
        {
            var source = new CancellationTokenSource();
            var token  = source.Token;
            var syncer = new Syncer();

            var mock = new Mock <IAfter>();

            Task task = SimpleTaskFactory
                        .Run(() =>
            {
                syncer.Step(1);
                syncer.Step(4);
                token.ThrowIfCancellationRequested();
            }, token)
                        .Catch <Ex1>(exception => mock.Object.CatchExceptionHandler(exception));

            syncer.Step(2);
            source.Cancel();
            syncer.Step(3);

            try
            {
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf <OperationCanceledException>(e.InnerException);
                mock.Verify(then => then.CatchExceptionHandler(It.IsAny <Exception>()), Times.Never);
                Assert.Pass();
            }
        }
예제 #10
0
        public void TaskT1_Then_FuncT1T2__SecondCancelled()
        {
            var source = new CancellationTokenSource();
            CancellationToken token = source.Token;

            var syncer = new Syncer();

            var  mock = new Mock <IAfter>();
            Task task = SimpleTaskFactory.Run(() => 12, token)
                        .Then(result => SimpleTaskFactory.Run(() =>
            {
                syncer.Step(1);
                syncer.Step(4);
                token.ThrowIfCancellationRequested();
                return(mock.Object.NextFunctionWithInput(result));
            }, token), token);

            syncer.Step(2);
            source.Cancel();
            syncer.Step(3);

            try
            {
                // ReSharper disable once MethodSupportsCancellation
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf <OperationCanceledException>(e.InnerException);
                mock.Verify(then => then.NextFunctionWithInput(It.IsAny <int>()), Times.Never);
                Assert.Pass();
            }
        }
예제 #11
0
        public void TaskT_CatchAllException__FirstCancelled()
        {
            var source = new CancellationTokenSource();
            var token  = source.Token;
            var syncer = new Syncer();

            var mock = new Mock <IAfter>();

            Task <int> task = SimpleTaskFactory
                              .Run(() =>
            {
                syncer.Step(1);
                syncer.Step(4);
                token.ThrowIfCancellationRequested();
                return(12);    // T
            }, token)
                              .Catch <int, Exception>(exception => mock.Object.CatchExceptionHandlerWithOutput(exception));

            syncer.Step(2);
            source.Cancel();
            syncer.Step(3);

            try
            {
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf <OperationCanceledException>(e.InnerException);
                // REMARK!!! The Catch doesn't cancel the OperationCanceledException!
                mock.Verify(then => then.CatchExceptionHandlerWithOutput(It.IsAny <Exception>()), Times.Never);
                Assert.Pass();
            }
        }
예제 #12
0
 public void WaitForSyncFromPeer(PeerInfo peerIp, int timeout)
 {
     _syncer             = new Syncer(Id);
     _remoteEndpoint     = _syncer.WaitForSyncFromPeer(peerIp, timeout, _udpClient);
     _peer               = peerIp;
     IsTunnelEstablished = true;
     StartCheckerForPings();
 }
예제 #13
0
 public void SyncWithPeer(PeerInfo peerIp, int timeout)
 {
     _syncer             = new Syncer(Id);
     _remoteEndpoint     = _syncer.SyncWithPeer(peerIp, timeout, _udpClient);
     _peer               = peerIp;
     IsTunnelEstablished = true;
     StartPinger();
 }
예제 #14
0
        /// <summary>
        /// Не синхронизируем врачей при отправке только словарей с сервера.
        /// Таблица Doctors нужна для словарей.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Syncer WithoutDoctors(this Syncer s)
        {
            Contract.Requires(s != null);

            s.IgnoreAddingFilterPerType.Add(Names.tblToTypeMap[Names.Doctor], (row) => true);

            return(s);
        }
예제 #15
0
        public void RPCSetBot(int botSeat, int botSyncerView)
        {
            Players[botSeat] = Instantiate(playerPrefab, birthPoints.points[botSeat].position, birthPoints.points[botSeat].rotation).
                               GetComponentInChildren <Tank>();
            Syncer syncer = PhotonView.Find(botSyncerView).transform.GetComponent <Syncer>();

            Players[botSeat].InitSyncMode(botSeat, syncer);
        }
예제 #16
0
 public MainWindow()
     : base()
 {
     InitializeComponent();
     _updateDataBaseDialog = null;
     _syncer = new Syncer();
     InicializeBackgroundWorker();
 }
예제 #17
0
 public override void Init()
 {
     SyncBeamLength      = new Syncer <float>(ToolComp.Tool, "BeamLength", 1, Checker: val => val >= ToolComp.BeamCtlModule.MinBeamLengthBlocks && val <= ToolComp.BeamCtlModule.MaxBeamLengthBlocks);
     SyncDistanceMode    = new Syncer <bool>(ToolComp.Tool, "DistanceBasedMode");
     SyncSpeedMultiplier = new Syncer <float>(ToolComp.Tool, "SpeedMultiplier", 1, Checker: val => val >= 1 && val <= 4);
     SyncBeamLength.GotValueFromServer      += ToolComp.Tool.UpdateVisual;
     SyncDistanceMode.GotValueFromServer    += ToolComp.Tool.UpdateVisual;
     SyncSpeedMultiplier.GotValueFromServer += ToolComp.Tool.UpdateVisual;
 }
예제 #18
0
 void Awake()
 {
     CurrentController = this;
     //arena = new Arena(new Vector3(6,6,6));
     Runners     = new List <Runner>();
     Pagodas     = new List <PagodaController>();
     syncObjects = new List <iSyncable>();
     Solids      = new List <SolidController> ();
     syncer      = new Syncer(this, syncerInterval, syncObjects);
 }
예제 #19
0
        /// <summary>
        /// Не синхронизируем ссылку на пользовательский словарь при отправке на сервер.
        /// </summary>
        /// <param name="s"></param>
        /// <returns></returns>
        public static Syncer WithoutCustomVocsInDoc(this Syncer s)
        {
            Contract.Requires(s != null);

            s.ShaperPerType.Add(Names.tblToTypeMap[Names.Doctor], (row) =>
            {
                row[Names.Col.DoctorCustomVocabulary] = DBNull.Value;
            });

            return(s);
        }
예제 #20
0
        public IPEndPoint Sync(PeerInfo peer, string syncId, List <SyncType> syncTypes = null)
        {
            var syncer    = new Syncer(syncId, syncTypes);
            var activeIp  = syncer.SyncWithPeer(peer, 60000, _udpClient);
            var udtSocket = SetupUdtSocket();

            udtSocket.Bind(_udpClient.Client);
            udtSocket.Connect(activeIp.Address, activeIp.Port);
            UdtConnection = udtSocket;
            UdtConnection.BlockingReceive = true;
            Logger.Debug("[" + Thread.CurrentThread.ManagedThreadId + "] Successfully completed outgoing tunnel with " + activeIp + "-" + syncId);
            return(activeIp);
        }
예제 #21
0
        public IPEndPoint WaitForSync(PeerInfo peer, String syncId, List <SyncType> syncTypes = null)
        {
            var syncer   = new Syncer(syncId, syncTypes);
            var activeIp = syncer.WaitForSyncFromPeer(peer, 60000, _udpClient);

            ListeningSocket = SetupUdtSocket();
            ListeningSocket.Bind(_udpClient.Client);
            ListeningSocket.Listen(10);
            Udt.Socket udtClient = ListeningSocket.Accept();
            UdtConnection = udtClient;
            UdtConnection.BlockingReceive = true;
            Logger.Debug("Successfully completed incoming tunnel with " + activeIp + "-" + syncId);
            return(activeIp);
        }
    // Update is called once per frame
    void LateUpdate()
    {
        if (pursueTime == 0f && targetRB.velocity.sqrMagnitude < (0.25f * 0.25f))
        {
            pursueTime = Time.time + maxWait;
            //Debug.Log(pursueTime);
        }
        if (targetRB.velocity.sqrMagnitude > (0.25f * 0.25f))
        {
            pursueTime = 0f;
        }

        float sqrDist = ((Vector2)playerTransform.position - (Vector2)transform.position).sqrMagnitude;

        if (playerTransform != null)
        {
            if (sqrDist < SnapTreshold && targetRB.velocity.sqrMagnitude < (MaxTargetVelocity * MaxTargetVelocity) && !LockOn && !Ptime)
            {
                if (sqrDist > (ignoreRadius * ignoreRadius) && targetRB.velocity.sqrMagnitude < (MaxTargetVelocity * MaxTargetVelocity))
                {
                    Vector3 intendedPosition = transform.position + (Vector3)((Vector2)(playerTransform.position - transform.position)).normalized * ignoreRadius + new Vector3(0, 0, depth);
                    transform.position = Vector3.Lerp(transform.position, intendedPosition, speed * 4);
                }
                else
                {
                    caughtUp = false;
                }
            }
            else if ((targetRB.velocity.sqrMagnitude >= (MaxTargetVelocity * MaxTargetVelocity) || Ptime) && !caughtUp)
            {
                //Debug.Log("Moving Fast or Waiting Long");
                float multiplier = Ptime ? 2f : (targetRB.velocity.sqrMagnitude / (MaxTargetVelocity * MaxTargetVelocity));
                transform.position = Vector3.Lerp(transform.position, playerTransform.position, speed * multiplier) + new Vector3(0, 0, depth);
                if (sqrDist < (1f))
                {
                    caughtUp = true;
                }
                else
                {
                    caughtUp = false;
                }
            }
            else
            {
                transform.position = playerTransform.position + new Vector3(0, 0, depth);
            }

            transform.position = (Vector3)Syncer.pixelPerfectVector((Vector2)transform.position) + new Vector3(0, 0, depth);
        }
    }
예제 #23
0
        public void Init()
        {
            GameState.playerID = 0;
            playerList         = GameState.AllPlayerIDs;

            /*At the beginning of the mainGame, the server will get playerList from server's roomController
             * Then instantiaite all the player tanks locally
             * */
            if (!isOffline)
            {
                instructionReceiver.Init();
                for (int i = 0; i < playerList.Length; i++)
                {
                    int index = Singletons.gameRoutineController.RegisterNewTank(playerList[i]);
                    if (index != -1)
                    {
                        Transform  startTransform = birthPoints.points[i];
                        GameObject newPlayer      = Instantiate(playerPrefab, startTransform.position, startTransform.rotation);
                        clientTanks[i] = newPlayer.GetComponentInChildren <Tank>();
                        Syncer newSyncer = PhotonNetwork.Instantiate(syncerPrefab.name,
                                                                     clientTanks[i].transform.position, clientTanks[i].transform.rotation, 0).GetComponent <Syncer>();
                        SyncerViewIDs[i] = newSyncer.gameObject.GetPhotonView().viewID;
                        clientTanks[i].motion.tankNetworkComponents.Set(newSyncer);
                        clientTanks[i].InitOnServer(i, instructionReceiver.ReceivedInstructions[index], newSyncer);
                    }
                }
            }
            else
            {
                serverUIController.Init();
                sensoringSimulator.Init(clientTanks);
            }
            statManager.Init(clientTanks);

            if (GameState.isRecording)
            {
                recorder.Init(clientTanks, statManager.GetAllStats(), System.DateTime.Now.ToLocalTime().ToString("yyyyMMdd_HHmmss") + ".rec");
                recorder.StartRecord();
            }
            else
            {
                recorder.enabled = false;
            }
            serverCameraController = Instantiate(serverCameraPreafab,
                                                 birthPoints.points[0].position + new Vector3(0, 5, 0),
                                                 birthPoints.points[0].rotation).GetComponent <ServerCameraController>();
            serverCameraController.Init(serverInputManager);
            serverInfoHUD.Init(statManager.GetAllStats(), clientTanks, serverCameraController.GetComponent <Camera>());
        }
예제 #24
0
 public void RPCSetPlayers(int[] SeatToID, int[] SyncerViewIDs)
 {
     for (int i = 0; i < SeatToID.Length; i++)
     {
         if (SeatToID[i] != -1)
         {
             int index = SeatToID[i];
             Players[i] =
                 Instantiate(playerPrefab, birthPoints.points[i].position, birthPoints.points[i].rotation).
                 GetComponentInChildren <Tank>();
             Syncer syncer = PhotonView.Find(SyncerViewIDs[i]).transform.GetComponent <Syncer>();
             Players[i].InitSyncMode(i, syncer);
         }
     }
 }
예제 #25
0
        public async Task TestThreeway()
        {
            await TestSyncSuccess();

            colClient.Close(false);
            StorageFolder tempFolder3 = await Utils.localFolder.CreateFolderAsync("tempFolder3");

            foreach (var file in await tempFolder.GetFilesAsync())
            {
                await file.CopyAsync(tempFolder3);
            }
            colClient.ReOpen();
            Collection col3 = await Storage.OpenOrCreateCollection(tempFolder3, Utils.collectionName);

            var client2 = new Syncer(col3, server);

            Assert.AreEqual("noChanges", (await client2.Sync())[0]);

            //Client 1 adds a card at time 1
            await Task.Delay(TimeSpan.FromSeconds(1));

            var f = colClient.NewNote();

            f.SetItem("Front", "1");
            colClient.AddNote(f);
            colClient.Save();

            //At time 2, client 2 syncs to server
            await Task.Delay(TimeSpan.FromSeconds(1));

            col3.SetIsModified();
            col3.Save();
            Assert.AreEqual("success", (await client2.Sync())[0]);

            //At time 3, client 1 syncs, adding the older note
            await Task.Delay(TimeSpan.FromSeconds(1));

            Assert.AreEqual("success", (await client.Sync())[0]);
            Assert.AreEqual(colClient.NoteCount(), colServer.NoteCount());

            //Syncing client2 should pick it up
            Assert.AreEqual("success", (await client2.Sync())[0]);
            Assert.AreEqual(colClient.NoteCount(), colServer.NoteCount());
            Assert.AreEqual(colClient.NoteCount(), col3.NoteCount());

            col3.Close(false);
            await tempFolder3.DeleteAsync();
        }
예제 #26
0
 public void Sync()
 {
     using (var syncer = new Syncer(GetCredentials(), null, ConsoleLogger))
     {
         foreach (var map in Mapper())
         {
             var diff = syncer.Diff(map);
             foreach (var output in  syncer.Sync(diff, SyncOutput.CreatePullRequest))
             {
                 if (!string.IsNullOrEmpty(output))
                 {
                     Console.Out.WriteLine("Done " + output);
                 }
             }
         }
     }
 }
예제 #27
0
        public async Task SyncVocsToLoad(ConnectionInfo remote, string local, IEnumerable <Vocabulary> vocsToLoad)
        {
            Contract.Requires(Constants.IsClient);

            var syncer = new Syncer(
                serverConStr: remote.ConnectionString,
                clientConStr: local,
                serverProviderName: remote.ProviderName);

            using (var s = NHib.OpenSession())
                syncer = syncer.OnlySelectedVocs(s, vocsToLoad);

            Mouse.OverrideCursor = Cursors.AppStarting;
            await syncer.SendFrom(Side.Server, Scope.Voc);

            Mouse.OverrideCursor = null;
        }
예제 #28
0
        static async Task Main(string[] args)
        {
            Dictionary <object, object>[] configDictionary = ReadConfig("Config.yaml");
            _loggerFactory = LoggerFactory.Create(builder => builder.AddConsole());
            ILogger _logger = _loggerFactory.CreateLogger <Program>();

            if (configDictionary != null)
            {
                try
                {
                    UserSourceModel = new YamlConnection("UserSource.yaml");

                    PluginLoader loader = new PluginLoader();
                    loader.LoadPlugins(configDictionary);
                }
                catch (Exception e)
                {
                    _logger.LogError($"Plugins couldn't be loaded: {e.Message}");
                }
            }

            IDestination[] destinations = PluginLoader.Plugins.ToArray();

            if (destinations != null)
            {
                Syncer syncer = new Syncer(UserSourceModel, destinations, _loggerFactory);
                await syncer.Sync(args);

                //if (UserSourceModel.ServiceAction.ToLower() == "save")
                //{
                //    await syncer.CreateUser();
                //}
                //else if (UserSourceModel.ServiceAction.ToLower() == "update")
                //{
                //    await syncer.UpdateUser();
                //}
                //else if (UserSourceModel.ServiceAction.ToLower() == "delete")
                //{
                //    await syncer.DeleteUser(args);
                //}
            }
            else
            {
                throw new Exception($"No plugins found");
            }
        }
예제 #29
0
        public async Task SendAddedPatientFromClient()
        {
            InMemoryHelper.FillData(clCfg, clSession, false);
            var clPatCount = clSession.Query <Patient>().Count();

            await s.WithoutCustomVocsInDoc().SendFrom(Side.Client, Scope.Holder);

            // новый пациент на клиенте
            var p = new Patient("x");

            session.DoSave(p);


            s = new Syncer(serverCon.ConnectionString, clientCon.ConnectionString, serverCon.ProviderName);
            await s.WithoutCustomVocsInDoc().SendFrom(Side.Client, Scope.Holder);

            Assert.AreEqual(clPatCount + 1, sSession.Query <Patient>().Count());
        }
예제 #30
0
    // Use this for initialization
    void Start()
    {
        Instance = this;
        DontDestroyOnLoad(this);
        SceneManager.sceneLoaded += OnLevelFinishedLoading;
        pcs = new List <GameObject>();
        PlayGamesClientConfiguration config = new
                                              PlayGamesClientConfiguration.Builder()
                                              .EnableSavedGames()
                                              .Build();

        // Enable debugging output (recommended)
        PlayGamesPlatform.DebugLogEnabled = true;

        // Initialize and activate the platform
        PlayGamesPlatform.InitializeInstance(config);

        PlayGamesPlatform.Activate();
    }
예제 #31
0
        /// <summary>
        /// Не синхронизируем область словарей
        /// но загружаем новые шаблоны для установленных словарей
        /// вызвать LoadOrUpdateVoc после синхронизации
        /// </summary>
        /// <param name="s"></param>
        /// <param name="installedVocs"></param>
        /// <returns></returns>
        public static Syncer WithInstalledVocs(this Syncer s, IEnumerable <Vocabulary> installedVocs)
        {
            Contract.Requires(s != null);
            Contract.Requires(installedVocs != null);

            var installedVocsIds = installedVocs.Select(x => x.Id).ToList().Cast <object>();

            foreach (var table in Scopes.GetVocOnlyTablesToDownload())
            {
                if (table == Names.WordTemplate)
                {
                    s.IgnoreAddingFilterPerType.Add(Names.tblToTypeMap[table], (row) => !installedVocsIds.Contains(row[Names.Id.Vocabulary]));
                }
                else
                {
                    s.IgnoreAddingFilterPerType.Add(Names.tblToTypeMap[table], (row) => true);
                }
            }
            return(s);
        }
예제 #32
0
        public override async Task Execute(string[] parameters, IResponse response)
        {
            var branchName = parameters[3];

            var ghRepo = await GitHubClientBuilder.Build().Repository.Get("Particular", parameters[1]);

            //we need the exact name since the sync is case sensitive for eg. the .dotSettings file
            var repoName = ghRepo.Name;

            await response.Send($"Got it! Initiating a sync for {repoName}/{branchName}");

            using (var som = new Syncer(GitHubHelper.Credentials, null, logEntry =>
            {
                //no-op logging for low, until we figure out log channels
            }))
            {
                var toSync = new RepoToSync
                {
                    Name = repoName,
                    Branch = branchName,
                    SolutionName = repoName,
                    SrcRoot = "src"
                };

                var diff = som.Diff(toSync.GetMapper(DefaultTemplateRepo.ItemsToSync));

                ExceptionDispatchInfo capturedException = null;
                try
                {
                    await diff;
                    var sync = som.Sync(diff.Result, SyncOutput.CreatePullRequest, new[]
                    {
                        ClassificationLabels.RefactoringLabelName,
                    });
                    await sync;

                    var createdSyncBranch = sync.Result.FirstOrDefault();

                    if (string.IsNullOrEmpty(createdSyncBranch))
                    {
                        await response.Send($"Repo {repoName} is already in sync, nothing for me to do!");
                    }
                    else
                    {
                        await response.Send($"Pull created for {repoName}, click here to review and pull: {createdSyncBranch}");
                    }
                }
                catch (AggregateException aggEx)
                {
                    var ex = aggEx.Flatten().InnerException;

                    if (ex is Octokit.NotFoundException)
                    {
                        // The github api is weird. NotFound is actually a
                        // permission error.
                        capturedException = ExceptionDispatchInfo.Capture(ex);
                    }
                }
                catch (Octokit.NotFoundException ex)
                {
                    // The github api is weird. NotFound is actually a
                    // permission error.
                    capturedException = ExceptionDispatchInfo.Capture(ex);
                }
                if (capturedException != null)
                {
                    await response.Send($"I do not have commit access to repo {repoName}. Please add 'particularbot' to the list of contributers.");

                    //capturedException.Throw();
                }

                await response.Send($"Want to know more about repo syncing? Go here: {"https://github.com/Particular/PlatformDevelopment/wiki/Repository%20synchronisation"}");
            }
        }
예제 #33
0
        public void Task_CatchSpecificException__FirstCancelled()
        {
            var source = new CancellationTokenSource();
            var token = source.Token;
            var syncer = new Syncer();

            var mock = new Mock<IAfter>();

            Task task = SimpleTaskFactory
                .Run(() =>
                {
                    syncer.Step(1);
                    syncer.Step(4);
                    token.ThrowIfCancellationRequested();
                }, token)
                .Catch<Ex1>(exception => mock.Object.CatchExceptionHandler(exception));

            syncer.Step(2);
            source.Cancel();
            syncer.Step(3);

            try
            {
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf<OperationCanceledException>(e.InnerException);
                mock.Verify(then => then.CatchExceptionHandler(It.IsAny<Exception>()), Times.Never);
                Assert.Pass();
            }

        }
예제 #34
0
        public void TaskT_CatchAllException__FirstCancelled()
        {
            var source = new CancellationTokenSource();
            var token = source.Token;
            var syncer = new Syncer();

            var mock = new Mock<IAfter>();

            Task<int> task = SimpleTaskFactory
                .Run(() =>
                {
                    syncer.Step(1);
                    syncer.Step(4);
                    token.ThrowIfCancellationRequested();
                    return 12; // T
                }, token)
                .Catch<int, Exception>(exception => mock.Object.CatchExceptionHandlerWithOutput(exception));

            syncer.Step(2);
            source.Cancel();
            syncer.Step(3);

            try
            {
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf<OperationCanceledException>(e.InnerException);
                // REMARK!!! The Catch doesn't cancel the OperationCanceledException!
                mock.Verify(then => then.CatchExceptionHandlerWithOutput(It.IsAny<Exception>()), Times.Never);
                Assert.Pass();
            }


        }
예제 #35
0
        public void TaskT1_Then_FuncT1T2__SecondCancelled()
        {
            var source = new CancellationTokenSource();
            CancellationToken token = source.Token;

            var syncer = new Syncer();

            var mock = new Mock<IAfter>();
            Task task = SimpleTaskFactory.Run(() => 12, token)
                .Then(result =>
                {
                    syncer.Step(1);
                    syncer.Step(4);
                    token.ThrowIfCancellationRequested();
                    mock.Object.NextFunctionWithInput(result);
                }, token);

            syncer.Step(2);
            source.Cancel();
            syncer.Step(3);

            try
            {
                // ReSharper disable once MethodSupportsCancellation
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf<OperationCanceledException>(e.InnerException);
                mock.Verify(then => then.NextFunctionWithInput(It.IsAny<int>()), Times.Never);
                Assert.Pass();
            }
        }
예제 #36
0
        public void Task_Then_Action__FirstCancelled()
        {
            var source = new CancellationTokenSource();
            CancellationToken token = source.Token;
            
            var syncer = new Syncer();

            var mock = new Mock<IAfter>();
            Task task = SimpleTaskFactory.Run(() =>
                {
                    syncer.Step(1);
                    syncer.Step(4);
                    token.ThrowIfCancellationRequested();
                }, token)
                .Then(() => mock.Object.NextAction(), token);

            syncer.Step(2); 
            source.Cancel();
            syncer.Step(3);

            try
            {
                // ReSharper disable once MethodSupportsCancellation
                task.Wait();
                Assert.Fail("task must bubble up the TaskCanceledException");
            }
            catch (AggregateException e)
            {
                Assert.IsInstanceOf<TaskCanceledException>(e.InnerException);
                mock.Verify(then => then.NextAction(), Times.Never);
                Assert.Pass();
            }
        }