Ejemplo n.º 1
0
        public virtual void Initializa(long local_player_pstid, CombatStartInfo combat_start_info)
        {
            //真正的local_player_pstid在局外,传进来就好;combat_start_info是给所有玩家、观战者、以及录像回放时,都一致的消息
            m_local_player_pstid = local_player_pstid;
            m_level_data         = GetConfigProvider().GetLevelData(combat_start_info.m_level_id);
            m_state            = CombatClientState.Loading;
            m_state_frame_cnt  = 0;
            m_state_start_time = -1;
            m_last_update_time = -1;
            m_waiting_cnt      = 0;
#if UNITY_EDITOR
            m_is_first_frame = true;
#endif

            AttributeSystem.Instance.InitializeAllDefinition(m_combat_factory.GetConfigProvider());
            ComponentTypeRegistry.RegisterDefaultComponents();
            BehaviorTreeNodeTypeRegistry.RegisterDefaultNodes();
            DamageModifier.RegisterDefaultModifiers();
            m_combat_factory.RegisterCommands();

            BehaviorTreeFactory.Instance.SetConfigProvider(m_combat_factory.GetConfigProvider());

            m_logic_world = m_combat_factory.CreateLogicWorld();
            m_logic_world.Initialize(this, combat_start_info.m_world_seed, true);
            m_render_world = m_combat_factory.CreateRenderWorld();
            m_render_world.Initialize(this, m_logic_world);
            m_logic_world.SetIRenderWorld(m_render_world);
            m_sync_client = m_combat_factory.CreateSyncClient();
            m_sync_client.Init(m_logic_world);

            BuildLogicWorld(combat_start_info);
            BuildRenderWorld(m_level_data);
        }
Ejemplo n.º 2
0
        private async void SyncBtnOnClick(object sender, EventArgs e)
        {
            _syncBtn.Enabled = false;

            try
            {
                if (FileSyncApp.Instance.ActiveClients.ContainsKey(_folderId))
                {
                    throw new Exception("WTF, sync in progress");
                }

                _client = SyncClientFactory.GetTwoWay(Common.Extensions.ParseEndpoint(_serverUrl), _folderItem.LocalPath, null, FileSyncApp.Instance.Config.ClientId, _folderItem.Id);

                FileSyncApp.Instance.ActiveClients[_folderId] = _client; // TODO

                _client.Log += AppendLog;

                await Task.Run(_client.Sync);

                FileSyncApp.Instance.ActiveClients.Remove(_folderId);

                _client.Log -= AppendLog;
                _client      = null;
            }
            finally
            {
                _syncBtn.Enabled = true;
                _client          = null;
            }
        }
        static Code1AddressVerificationService()
        {
            var environment = ConfigurationManager.AppSettings["NetTax.Environment"];
            if (string.IsNullOrEmpty(environment))
                environment = ConfigurationManager.AppSettings["Environment"];

            var region = ConfigurationManager.AppSettings["NetTax.Region"];
            if (string.IsNullOrEmpty(region))
                region = ConfigurationManager.AppSettings["Region"];

            var endpoint = EndpointsConfig
                .FromContractAssembly<ICode1Service>()
                .ForEnvironment(environment)
                .ForRegion(region)
                .WithParameters(key =>
                {
                    if (key.Equals("Region"))
                        return region;

                    return ConfigurationManager.AppSettings[key];
                })
                .ForContract<ICode1Service>()
                .NamedEndpoint("Code1Service");

            _client = SyncClient<ICode1Service>.Create(endpoint);
        }
        private void PrepareServerClient()
        {
            _testServerConfig = new TestServerConfig();
            _testServerConfig.Clients.Add(new RegisteredClient
            {
                Id = Guid.Empty,
                FolderEndpoints =
                {
                    new ClientFolderEndpoint
                    {
                        Id          = Guid.Empty,
                        DisplayName = "folder1",
                        LocalPath   = _serverFolder,
                    }
                }
            });

            SessionStorage.Instance.SetTimeout(0);

            _server      = new SyncServer(ServerPort, Guid.Empty, _testServerConfig);
            _server.Msg += ServerWrite;
            _server.Start();

            var serverEp = new IPEndPoint(IPAddress.Parse("127.0.0.1"), ServerPort);

            _client             = SyncClientFactory.GetTwoWay(serverEp, _clientFolder, null, Guid.Empty, Guid.Empty);
            _client.Log        += ClientWrite;
            _client.ErrorEvent += ClientOnErrorEvent;
        }
Ejemplo n.º 5
0
        internal WebServiceClient(
            int accountId,
            string licenseKey,
            IEnumerable <string>?locales,
            string host,
            int timeout,
            HttpMessageHandler?httpMessageHandler,
            // This is a hack so that we can keep this internal while adding
            // httpMessageHandler to the public constructor. We can remove
            // this when we drop .NET 4.5 support and get rid of ISyncClient.
            bool fakeParam = false
#if !NETSTANDARD1_4
            , ISyncClient?syncWebRequest = null
#endif
            , HttpClient?httpClient = null
            )
        {
            var auth = EncodedAuth(accountId, licenseKey);

            _host    = host;
            _locales = locales == null ? new List <string> {
                "en"
            } : new List <string>(locales);
#if !NETSTANDARD1_4
            _syncClient = syncWebRequest ?? new SyncClient(auth, timeout, UserAgent);
#endif
            _asyncClient = new AsyncClient(auth, timeout, UserAgent, httpMessageHandler, httpClient);
        }
Ejemplo n.º 6
0
 public void Destruct()
 {
     m_sync_client.Destruct();
     m_sync_client = null;
     m_render_world.Destruct();
     m_render_world = null;
     m_logic_world.Destruct();
     m_logic_world = null;
 }
Ejemplo n.º 7
0
        /// <summary>
        /// Uploads the given ISync Element using the ISyncClient
        /// If success the Element will be added or an existing element will be updated with
        /// the new values
        /// </summary>
        /// <param name="element"></param>
        /// <param name="client"></param>
        /// <param name="indexManager"></param>
        private void Upload(CancellationToken cancleToken, ISyncElement element, ISyncClient client, SyncIndexManager indexManager)
        {
            IRemoteProperty uploaded = element.Upload(cancleToken, client);

            if (uploaded != null)
            {
                //Upload was successfull, add as tracked element to index
                indexManager.AddOrUpdate(CreateIndexElement(element, uploaded));
            }
        }
Ejemplo n.º 8
0
 internal MensaClient(ISyncClient syncClient)
 {
     if (syncClient != null)
     {
         this._syncClient = syncClient;
     }
     else
     {
         this._syncClient = new MensaKLSyncClient();
     }
 }
Ejemplo n.º 9
0
 public FileUploadWorker(ISyncClient syncClient, string sourceDirectory,
                         Func <string, bool> validateFile,
                         Action <string, object[]> log,
                         Action <Exception> logError)
 {
     this.syncClient      = syncClient;
     this.sourceDirectory = sourceDirectory;
     this.validateFile    = validateFile;
     this.log             = log;
     this.logError        = logError;
 }
Ejemplo n.º 10
0
        public static void PushChanges(ISyncClient client, ISyncServer server)
        {
            while(true)
            {
                var entity = client.GetChangedOnClient();
                if (entity == null)
                    break;

                var server_sync_date = server.SendChangedToServer(entity);
                client.SetClientEntitySynced(entity, server_sync_date);
            }
        }
Ejemplo n.º 11
0
        public virtual void Destruct()
        {
            m_sync_client.Destruct();
            m_sync_client = null;
            m_render_world.Destruct();
            m_render_world = null;
            m_logic_world.Destruct();
            m_logic_world = null;

            m_combat_factory = null;
            m_level_data     = null;
        }
Ejemplo n.º 12
0
        private static void PullChanges(ISyncClient client, ISyncServer server)
        {
            var date = client.GetMaxServerSyncDate();
            while(true)
            {
                var proxy = server.GetChangedFromServer(date);
                if (proxy == null)
                    break;

                client.ApplyChangeFromServer(proxy);
                date = proxy.ServerSyncDate;
            }
        }
Ejemplo n.º 13
0
        public void Initializa(long local_player_pstid)
        {
            m_local_player_pstid = local_player_pstid;
            m_state       = TestCombatClientState.Loading;
            m_waiting_cnt = 0;

            m_logic_world  = new TestLogicWorld(this, true);
            m_render_world = new TestRenderWorld(this, m_logic_world);
            m_sync_client  = new MNLPSyncClient();
            m_sync_client.Init(m_logic_world);

            ++m_waiting_cnt;
            m_render_world.LoadScene();
        }
Ejemplo n.º 14
0
        public static void PushChanges(ISyncClient client, ISyncServer server)
        {
            while (true)
            {
                var entity = client.GetChangedOnClient();
                if (entity == null)
                {
                    break;
                }

                var server_sync_date = server.SendChangedToServer(entity);
                client.SetClientEntitySynced(entity, server_sync_date);
            }
        }
Ejemplo n.º 15
0
 /// <summary>
 /// Uploads the File of the FileSync element ot the
 /// Server using the provided ISync Client and returns the created or updated
 /// IRemote Property
 /// </summary>
 /// <param name="client"></param>
 /// <returns></returns>
 public IRemoteProperty Upload(CancellationToken cancleToken, ISyncClient client)
 {
     try
     {
         using (FileStream stream = _info.OpenRead())
         {
             return(client.PutFile(cancleToken, _relativePath, stream));
         }
     } catch (Exception exc)
     {
         _logger.Error("Error occured while uploading file " + RelativePath, exc);
         return(null);
     }
 }
Ejemplo n.º 16
0
 public CloudClient(ISyncClient client, int millisecondsTimeout, int maxBufferLength)
 {
     SyncWaitDic         = new ConcurrentDictionary <long, ReturnEventWaitHandle>(10, 10000);
     AsyncCallDiy        = new ConcurrentDictionary <long, AsyncCalls>();
     CallBackDiy         = new ConcurrentDictionary <long, AsyncCalls>();
     AsyncRunDiy         = new ConcurrentDictionary <long, AsyncRun>();
     Client              = client;
     MillisecondsTimeout = millisecondsTimeout;
     RingBuffer          = new ZYNetRingBufferPool(maxBufferLength);
     Sync                = new ZYSync();
     Sync.SyncSend       = SendData;
     Sync.SyncSendAsWait = SendDataAsWait;
     Module              = new ModuleDictionary();
 }
Ejemplo n.º 17
0
        private static void PullChanges(ISyncClient client, ISyncServer server)
        {
            var date = client.GetMaxServerSyncDate();

            while (true)
            {
                var proxy = server.GetChangedFromServer(date);
                if (proxy == null)
                {
                    break;
                }

                client.ApplyChangeFromServer(proxy);
                date = proxy.ServerSyncDate;
            }
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Downloads the File from the ISync client and
        /// patches the current local file with the downloaded version
        /// or creates new file
        /// </summary>
        /// <returns>An IFileInfo property continaing information about the overwritten File, or null if download failed</returns>
        public FileInfo PatchLocalFile(CancellationToken cancleToken, ISyncClient client)
        {
            //Get Temp File from Remote
            _logger.Debug("Patching " + _relativePath + " with version from server");
            FileInfo tempFile = client.DownloadRemoteFileToTemp(cancleToken, _relativePath.UrlDecode());

            if (tempFile != null)
            {
                if (cancleToken.IsCancellationRequested)
                {
                    return(null);
                }
                _info = FileManager.CopyFile(tempFile.FullName, _rootDirPath + _relativePath, true, _logger);
                return(_info);
            }
            return(null);
        }
Ejemplo n.º 19
0
        internal WebServiceClient(
            int accountId,
            string licenseKey,
            IEnumerable <string>?locales,
            string host,
            int timeout,
            HttpClient httpClient,
            ISyncClient?syncWebRequest = null
            )
        {
            var auth = EncodedAuth(accountId, licenseKey);

            _host        = host;
            _locales     = (locales == null ? new List <string> {
                "en"
            } : new List <string>(locales)).AsReadOnly();
            _syncClient  = syncWebRequest ?? new SyncClient(auth, timeout, UserAgent);
            _asyncClient = new AsyncClient(auth, timeout, UserAgent, httpClient);
        }
Ejemplo n.º 20
0
        protected override void OnCreate(Bundle savedInstanceState)
        {
            base.OnCreate(savedInstanceState);

            SetContentView(Resource.Layout.FolderView);

            Window.AddFlags(WindowManagerFlags.KeepScreenOn);

            _serverUrl  = Intent.GetStringExtra("server");
            _serverItem = FileSyncApp.Instance.Config.Servers.Single(x => x.Url == _serverUrl);
            _folderId   = Guid.ParseExact(Intent.GetStringExtra("folderId"), "D");
            _folderItem = _serverItem.Folders.Single(x => x.Id == _folderId);

            FindViewById <TextView>(Resource.Id.folderViewNameView).Text = _folderItem.DisplayName;
            FindViewById <TextView>(Resource.Id.folderViewPathView).Text = _folderItem.LocalPath;

            _logTxtView = FindViewById <TextView>(Resource.Id.folderViewLogTxtView);
            _logTxtView.MovementMethod = new ScrollingMovementMethod();

            _syncBtn        = FindViewById <Button>(Resource.Id.folderViewStartSyncBtn);
            _syncBtn.Click += SyncBtnOnClick;

            var btn = FindViewById <Button>(Resource.Id.folderViewDeleteFolderBtn);

            btn.Click += DeleteFolderBtn_Click;

            if (FileSyncApp.Instance.ActiveClients.TryGetValue(_folderId, out var client))
            {
                _syncBtn.Enabled = false;

                _client      = client;
                _client.Log += AppendLog;
                _client.SyncTask.ContinueWith(x =>
                {
                    RunOnUiThread(() => { _syncBtn.Enabled = true; });
                    FileSyncApp.Instance.ActiveClients.Remove(_folderId);
                    _client.Log -= AppendLog;
                    _client      = null;
                });
            }
        }
Ejemplo n.º 21
0
        internal WebServiceClient(
            int userId,
            string licenseKey,
            IEnumerable <string> locales,
            string host = "geoip.maxmind.com",
            int timeout = 3000,
            HttpMessageHandler httpMessageHandler = null
#if !NETSTANDARD1_4
            , ISyncClient syncWebRequest = null
#endif
            )
        {
            var auth = EncodedAuth(userId, licenseKey);

            _host    = host;
            _locales = new List <string>(locales);
#if !NETSTANDARD1_4
            _syncClient = syncWebRequest ?? new SyncClient(auth, timeout, UserAgent);
#endif
            _asyncClient = new AsyncClient(auth, timeout, UserAgent, httpMessageHandler);
        }
Ejemplo n.º 22
0
        internal WebServiceClient(
            int accountId,
            string licenseKey,
            IEnumerable <string> locales,
            string host,
            int timeout,
            HttpMessageHandler httpMessageHandler
#if !NETSTANDARD1_4
            , ISyncClient syncWebRequest = null
#endif
            )
        {
            var auth = EncodedAuth(accountId, licenseKey);

            _host    = host;
            _locales = locales == null ? new List <string> {
                "en"
            } : new List <string>(locales);
#if !NETSTANDARD1_4
            _syncClient = syncWebRequest ?? new SyncClient(auth, timeout, UserAgent);
#endif
            _asyncClient = new AsyncClient(auth, timeout, UserAgent, httpMessageHandler);
        }
Ejemplo n.º 23
0
        public async Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting synchronizer service...");

            if (_syncClient == null && _clientScope == null)
            {
                _clientScope = _dependencyScope.BeginLifetimeScope(
                    containerConfig => _syncClientFactory.ConfigureContainerBuilder(containerConfig));

                // The scope is disposed right after creation of the sync client. This should not be a problem as
                // the client holds references to all required instances after creation.
                _syncClient = _syncClientFactory.CreateSyncClient(_clientScope);

                var authenticator = _clientScope.Resolve <ISmintIoAuthenticator>();
                Debug.Assert(authenticator != null, nameof(authenticator) + " != null");

                // we have a system browser based authenticator here, which will work synchronously
                await authenticator.InitializeAuthenticationAsync();
            }

            await _syncClient.StartAsync(cancellationToken);

            _logger.LogInformation("Started synchronizer service");
        }
Ejemplo n.º 24
0
 protected virtual void InitClientTwo()
 {
     clientManifestTwo = new SyncManifest ();
     clientStorageTwo = new DiskStorage ();
     clientStorageTwo.SetPath (clientStorageDirTwo);
     clientEngineTwo = new Engine (clientStorageTwo);
     syncClientTwo = new FilesystemSyncClient (clientEngineTwo, clientManifestTwo);
 }
Ejemplo n.º 25
0
        /// <summary>
        /// Iterates trough all Index Elements and checks wheter the still exist
        /// If not they have been deleted locally and will be removed on the server
        /// </summary>
        /// <param name="dto"></param>
        /// <param name="client"></param>
        /// <param name="logger"></param>
        /// <param name="indexManager"></param>
        private void DetectLocalDeletedElements(CancellationToken cancleToken, Configuration dto, ISyncClient client, ILogger logger, SyncIndexManager indexManager)
        {
            IEnumerable <SyncIndexElementDTO> indexElements  = indexManager.GetOrCreateIndexFile();
            List <SyncIndexElementDTO>        removeElements = new List <SyncIndexElementDTO>();

            foreach (SyncIndexElementDTO element in indexElements)
            {
                if (cancleToken.IsCancellationRequested)
                {
                    return;
                }

                bool   exists       = true;
                string absolutePath = dto.Local.LocalSyncDir + element.ReleativeFilePath;
                try
                {
                    if (element.ElementType.Equals(SyncElementType.File))
                    {
                        exists = File.Exists(absolutePath);
                    }
                    else if (element.ElementType.Equals(SyncElementType.Directory))
                    {
                        exists = Directory.Exists(absolutePath);
                    }
                } catch (Exception exc) { _logger.Error("Error occured while checking " + element.ElementType + "existance: ", exc); }
                if (!exists)
                {
                    _logger.Debug(element.ElementType + " " + element.ReleativeFilePath + " does not exist anymore. Will be deleted from server and index.");
                    removeElements.Add(element);
                }
            }

            //Get List of Directories that are contained in the removeElements list
            List <SyncIndexElementDTO> directories = removeElements.Where(x => x.ElementType == SyncElementType.Directory).ToList();

            foreach (SyncIndexElementDTO element in directories)
            {
                //remove all Elements that are contained in removeElements list and
                //are part of this Directory
                removeElements.RemoveAll(x => x.ReleativeFilePath.Length > element.ReleativeFilePath.Length &&
                                         x.ReleativeFilePath.Substring(0, element.ReleativeFilePath.Length) == element.ReleativeFilePath);
            }

            //Remove all elements that can be removed
            foreach (SyncIndexElementDTO element in removeElements)
            {
                if (client.Remove(cancleToken, element.ReleativeFilePath))
                {
                    //If its a Directory delete all Elements that are contained in this Directory
                    //From the index!
                    if (element.ElementType == SyncElementType.Directory)
                    {
                        indexManager.RemoveAll(x => x.ReleativeFilePath.Length >= element.ReleativeFilePath.Length &&
                                               x.ReleativeFilePath.Substring(0, element.ReleativeFilePath.Length) == element.ReleativeFilePath);
                    }
                    else
                    {
                        indexManager.Remove(element);
                    }
                }
            }
        }
Ejemplo n.º 26
0
 /// <summary>
 /// Downloaded the given RemotePropery and adds it as a local file
 /// </summary>
 /// <param name="remoteProperty"></param>
 /// <param name="client"></param>
 /// <param name="conf"></param>
 /// <param name="logger"></param>
 /// <param name="indexManager"></param>
 private void FetchFileFromServer(CancellationToken cancleToken, IRemoteProperty remoteProperty, ISyncClient client, Configuration conf, ILogger logger, SyncIndexManager indexManager)
 {
     try
     {
         string localFilePath = conf.Local.LocalSyncDir + remoteProperty.DecodedRelativeRemotePath;
         if (!File.Exists(localFilePath))
         {
             //File does not exist local, will be downloaded and added
             _logger.Debug(remoteProperty.DecodedRelativeRemotePath + " does not exist locally. Will be downloaded and added to index");
             FileInfo temp = client.DownloadRemoteFileToTemp(cancleToken, remoteProperty.DecodedRelativeRemotePath);
             if (temp != null)
             {
                 FileInfo newFile = FileManager.CopyFile(temp.FullName, localFilePath, true, _logger);
                 if (newFile != null)
                 {
                     FileSyncElement newFileElement = new FileSyncElement(newFile, conf.Local.LocalSyncDir, logger);
                     indexManager.AddOrUpdate(CreateIndexElement(newFileElement, remoteProperty));
                 }
             }
         }
     } catch (Exception exc)
     {
         logger.Error("Unexpected error while fetching " + remoteProperty.RelativeRemotePath + " from server: ", exc);
     }
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Checks for the given elements children or remote updates, has the option to only check the children and ignore updates in case
 /// Can be usefull to give the server enough time to index new files
 /// </summary>
 /// <param name="cancleToken"></param>
 /// <param name="element"></param>
 /// <param name="client"></param>
 /// <param name="properties"></param>
 /// <param name="indexManager"></param>
 /// <param name="logger"></param>
 /// <param name="config"></param>
 /// <param name="ignoreUpdates"></param>
 private void HandleISyncElementChildrenOrUpdates(CancellationToken cancleToken, ISyncElement element, ISyncClient client,
                                                  IEnumerable <IRemoteProperty> properties, SyncIndexManager indexManager, ILogger logger,
                                                  Configuration config, bool ignoreUpdates)
 {
     //File: check for updates
     //Directoy: process with going one hierarchy deeper
     if (element.Type.Equals(SyncElementType.File))
     {
         if (!ignoreUpdates)
         {
             CheckForFileUpdates(cancleToken, (FileSyncElement)element, client, properties, indexManager);
         }
     }
     else if (element.Type.Equals(SyncElementType.Directory))
     {
         GetDataAndHandleSync(cancleToken, element.AbsolutePath, client, logger, config, indexManager);
     }
     else
     {
         throw new NotImplementedException();
     }
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Handles the synchronisation of the given ISyncElement
        /// </summary>
        /// <param name="element"></param>
        /// <param name="client"></param>
        /// <param name="properties"></param>
        /// <param name="indexManager"></param>
        private void HandleISyncElement(CancellationToken cancleToken, ISyncElement element, ISyncClient client, IEnumerable <IRemoteProperty> properties,
                                        SyncIndexManager indexManager, ILogger logger, Configuration config)
        {
            if (cancleToken.IsCancellationRequested)
            {
                return;
            }
            //The general rules defining when to synchronize what are the same
            //for all ISyncClients and they follow the following design:
            //
            //1. Iterate all local folder and their files, check for updates on server:
            //  Both:
            //      1. when it does not exist in index and server -> upload
            //      2. when it exists only in index -> delete (has been deleted remotely)
            //      3. when exists on server but not index -> update index
            //  Files:
            //      1. When is exists in server and index -> check for updates
            //2. Add all files that are not in index to local copy
            //3. Remove all files that exist in index and server but not local from server -> deleted local

            (bool existInIndex, bool existsRemote)existance = CheckForElementExistance(element, properties, indexManager);

            if (!existance.existInIndex && !existance.existsRemote)
            {
                //Not in index and not in remote -> upload
                logger.Debug(element.Type + " " + element.RelativePath + " does not exist in local Index and remote, " +
                             "File will be added to both");
                Upload(cancleToken, element, client, indexManager);
                //Set the Method to ignore Updates -> Just handle children in case of Directory
                //Because directly checking for updates may cause exceptions because the server is
                //slow and does not return the correct properties on request yet
                HandleISyncElementChildrenOrUpdates(cancleToken, element, client, properties, indexManager, logger, config, true);
            }
            else if (existance.existInIndex && !existance.existsRemote)
            {
                //In index but not remote -> delete (has been deleted remotely)
                logger.Debug(element.Type + " " + element.RelativePath + " exists in index but has been removed remote. Deleting " + element.Type);
                DeleteLocalElement(element, indexManager);
            }
            else if (!existance.existInIndex && existance.existsRemote)
            {
                //Remote but not in index -> Add to index
                logger.Debug(element.Type + " " + element.RelativePath + " was missing in the index -> will be added.");
                //As it cannot be said if there was changes remote, no remote revision is added
                indexManager.AddOrUpdate(CreateIndexElement(element, null));
                HandleISyncElementChildrenOrUpdates(cancleToken, element, client, properties, indexManager, logger, config, false);
            }
            else if (existance.existInIndex && existance.existsRemote)
            {
                HandleISyncElementChildrenOrUpdates(cancleToken, element, client, properties, indexManager, logger, config, false);
            }
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Gets all Files and Directories at the given Path and handles their synchronisation
        /// </summary>
        /// <param name="absolutePath"></param>
        private void GetDataAndHandleSync(CancellationToken cancleToken, string absolutePath, ISyncClient client,
                                          ILogger logger, Configuration config, SyncIndexManager indexManager)
        {
            //Get the remote Properties, Files and Folder of the root folder
            IEnumerable <IRemoteProperty>      remoteProperties = client.GetProperties(GetRemotePath(config, absolutePath));
            IEnumerable <FileSyncElement>      files            = GetFiles(absolutePath, config, logger);
            IEnumerable <DirectorySyncElement> directories      = GetDirectories(absolutePath, config, logger);

            //If there is no connection or something went wrong during request
            if (remoteProperties == null)
            {
                _logger.Error("Something went wrong during connection to server.");
                return;
            }
            //First the Directories -> ensure they are not deleted before processing everything else
            foreach (DirectorySyncElement dir in directories)
            {
                if (cancleToken.IsCancellationRequested)
                {
                    return;
                }
                HandleISyncElement(cancleToken, dir, client, remoteProperties, indexManager, logger, config);
            }
            foreach (FileSyncElement file in files)
            {
                if (cancleToken.IsCancellationRequested)
                {
                    return;
                }
                HandleISyncElement(cancleToken, file, client, remoteProperties, indexManager, logger, config);
            }
        }
Ejemplo n.º 30
0
        /// <summary>
        /// Checks wheter
        /// </summary>
        /// <param name="file"></param>
        /// <param name="client"></param>
        /// <param name="properties"></param>
        /// <param name="indexManager"></param>
        private void CheckForFileUpdates(CancellationToken cancleToken, FileSyncElement file, ISyncClient client, IEnumerable <IRemoteProperty> properties, SyncIndexManager indexManager)
        {
            //Get Index and property instances
            SyncIndexElementDTO index    = GetIndexElement(indexManager, file);
            IRemoteProperty     property = GetProperty(properties, file);

            //Compare the change dates
            if (!index.LocalRevision.Equals(file.Revision) && index.RemoteRevision.Equals(property.RemoteRevision))
            {
                //File has been changed locally
                _logger.Debug("File " + file.RelativePath + " has been changed locally. Index rev: " + index.LocalRevision + " current file rev: " + file.Revision);
                Upload(cancleToken, file, client, indexManager);
            }
            else if (index.LocalRevision.Equals(file.Revision) && !index.RemoteRevision.Equals(property.RemoteRevision))
            {
                //File has been changed remotely
                _logger.Debug("File " + file.RelativePath + " has been changed remotely. Index remote rev: " + index.RemoteRevision + " current remote rev: " + property.RemoteRevision);
                PatchLocalFile(cancleToken, file, client, indexManager, properties);
            }
            else if (!index.LocalRevision.Equals(file.Revision) && !index.RemoteRevision.Equals(property.RemoteRevision))
            {
                //Conflict! Remote and server version has been changed!
                //Priorise server version, patch Local file
                _logger.Debug("File " + file.RelativePath + " has been changed remote and locally. Will fetch server version over local version");
                _logger.Debug("File " + file.RelativePath + " local index local rev: " + index.LocalRevision + " file local rev: " + file.Revision);
                _logger.Debug("File " + file.RelativePath + " remote index rev: " + index.RemoteRevision + " file remote rev: " + property.RemoteRevision);
                PatchLocalFile(cancleToken, file, client, indexManager, properties);
            }
        }
Ejemplo n.º 31
0
        /// <summary>
        /// Patches the local file with the current File version provided by the ISyncClient
        /// </summary>
        /// <param name="file"></param>
        /// <param name="client"></param>
        /// <param name="indexManager"></param>
        private void PatchLocalFile(CancellationToken cancleToken, FileSyncElement file, ISyncClient client, SyncIndexManager indexManager,
                                    IEnumerable <IRemoteProperty> remoteProperties)
        {
            //File has been changed remotely
            FileInfo update = file.PatchLocalFile(cancleToken, client);

            if (update != null)
            {
                //Updte Index Manager
                indexManager.AddOrUpdate(CreateIndexElement(file, GetProperty(remoteProperties, file)));
            }
        }
 /// <summary>
 /// Creates a Remote Directory at the relative Path of the dir and returns
 /// the Createes IRemoteProperty
 /// </summary>
 /// <param name="client"></param>
 /// <returns></returns>
 public IRemoteProperty Upload(CancellationToken cancleToken, ISyncClient client)
 {
     return(client.CreateDirectory(cancleToken, _relativePath));
 }
Ejemplo n.º 33
0
 public SyncManager(ISyncClient client, ISyncServer server)
 {
     this.client = client;
     this.server = server;
 }
Ejemplo n.º 34
0
        /// <summary>
        /// Executes the synchronisation for the given configuration and using the
        /// given Client
        /// This Method can be called multiple times using different configurations or client
        /// to achive different synchronisations
        /// </summary>
        public void ExcecuteSynchronisation(CancellationToken cancleToken, Configuration config, ISyncClient client)
        {
            _logger.Debug("Executing synchronisation for Directory " + config.Local.LocalSyncDir + " using client of type " + client.GetType());
            //Check if default dir extists, else delete
            if (!Directory.Exists(config.Local.LocalSyncDir))
            {
                _logger.Debug("Creating sync directory at " + config.Local.LocalSyncDir);
                Directory.CreateDirectory(config.Local.LocalSyncDir);
            }

            //Read or create the index File
            _logger.Debug("Reading index File");
            SyncIndexManager indexManager = new SyncIndexManager(_logger, config);

            //The following three steps are performed for a synchronisation:
            //1. Iterate all local folder and their files, check for updates on server
            //2. Remove all files that exist in index and server but not local from server -> deleted local
            //3. Add all files that are not in index to local copy
            //Start getting Files at the root Folder
            GetDataAndHandleSync(cancleToken, config.Local.LocalSyncDir, client, _logger, config, indexManager);

            if (cancleToken.IsCancellationRequested)
            {
                return;
            }

            DetectLocalDeletedElements(cancleToken, config, client, _logger, indexManager);

            if (cancleToken.IsCancellationRequested)
            {
                return;
            }

            FetchNewFilesFromServer(cancleToken, config, client, _logger, indexManager);

            _logger.Debug("Synchronisation finished");
        }
Ejemplo n.º 35
0
        // forces re-readin from disk, and will make sure a client does not hold
        // Notes which are equal by reference as the server when using FilesystemSync
        protected void ClearClientOne(bool reset = false)
        {
            if (reset) {
                clientManifestOne = new SyncManifest ();
                CleanupClientDirectoryOne ();
            }

            clientStorageOne = new DiskStorage ();
            clientStorageOne.SetPath (clientStorageDirOne);
            clientEngineOne = new Engine (clientStorageOne);
            syncClientOne = new FilesystemSyncClient (clientEngineOne, clientManifestOne);
        }
Ejemplo n.º 36
0
 public static void PullAndPushChanges(ISyncClient client, ISyncServer server)
 {
     PullChanges(client, server);
     PushChanges(client, server);
 }
Ejemplo n.º 37
0
 protected void ClearClientTwo(bool reset = false)
 {
     if (reset) {
         clientManifestTwo = new SyncManifest ();
         CleanupClientDirectoryTwo ();
     }
     clientStorageTwo = new DiskStorage ();
     clientStorageTwo.SetPath (clientStorageDirTwo);
     clientEngineTwo = new Engine (clientStorageTwo);
     syncClientTwo = new FilesystemSyncClient (clientEngineTwo, clientManifestTwo);
 }
Ejemplo n.º 38
0
 protected virtual void InitClientOne()
 {
     clientStorageOne = new DiskStorage ();
     clientStorageOne.SetPath (clientStorageDirOne);
     clientEngineOne = new Engine (clientStorageOne);
     clientManifestOne = new SyncManifest ();
     syncClientOne = new FilesystemSyncClient (clientEngineOne, clientManifestOne);
 }
Ejemplo n.º 39
0
 public static void PullAndPushChanges(ISyncClient client, ISyncServer server)
 {
     PullChanges(client, server);
     PushChanges(client, server);
 }