private static void ShowConnectingDialogError(Form owner, IXenConnection connection, Exception error)
        {
            if (error is ExpressRestriction e)
            {
                Program.Invoke(Program.MainWindow, delegate()
                {
                    new LicenseWarningDialog(e.HostName, e.ExistingHostName).ShowDialog(owner);
                });
                return;
            }

            if (error is Failure f)
            {
                if (f.ErrorDescription[0] == Failure.HOST_IS_SLAVE)
                {
                    string oldHost        = connection.Name;
                    string poolMasterName = f.ErrorDescription[1];

                    string pool_name = XenConnection.ConnectedElsewhere(poolMasterName);
                    if (pool_name != null)
                    {
                        if (!Program.RunInAutomatedTestMode)
                        {
                            if (pool_name == oldHost)
                            {
                                using (var dlg = new InformationDialog(string.Format(Messages.OLD_CONNECTION_ALREADY_CONNECTED, pool_name))
                                {
                                    WindowTitle = Messages.ADD_NEW_CONNECT_TO
                                })
                                {
                                    dlg.ShowDialog(owner);
                                }
                            }
                            else
                            {
                                using (var dlg = new InformationDialog(string.Format(Messages.SLAVE_ALREADY_CONNECTED, oldHost, pool_name))
                                {
                                    WindowTitle = Messages.ADD_NEW_CONNECT_TO
                                })
                                {
                                    dlg.ShowDialog(owner);
                                }
                            }
                        }
                    }
                    else
                    {
                        DialogResult dialogResult;
                        using (var dlg = new WarningDialog(string.Format(Messages.SLAVE_CONNECTION_ERROR, oldHost, poolMasterName),
                                                           ThreeButtonDialog.ButtonYes,
                                                           ThreeButtonDialog.ButtonNo)
                        {
                            WindowTitle = Messages.CONNECT_TO_SERVER
                        })
                        {
                            dialogResult = dlg.ShowDialog(owner);
                        }
                        if (DialogResult.Yes == dialogResult)
                        {
                            ((XenConnection)connection).Hostname = poolMasterName;
                            BeginConnect(connection, true, owner, false);
                        }
                    }
                }
                else if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                {
                    AddError(owner, connection, Messages.ERROR_NO_PERMISSION, Messages.SOLUTION_NO_PERMISSION);
                }
                else if (f.ErrorDescription[0] == XenAPI.Failure.SESSION_AUTHENTICATION_FAILED)
                {
                    AddError(owner, connection, Messages.ERROR_AUTHENTICATION, Messages.SOLUTION_AUTHENTICATION);
                }
                else if (f.ErrorDescription[0] == Failure.HOST_STILL_BOOTING)
                {
                    AddError(owner, connection, Messages.ERROR_HOST_STILL_BOOTING, Messages.SOLUTION_HOST_STILL_BOOTING);
                }
                else
                {
                    AddError(owner, connection, string.IsNullOrEmpty(f.Message) ? Messages.ERROR_UNKNOWN : f.Message, string.Empty);
                }
            }
            else if (error is WebException w)
            {
                if (((XenConnection)connection).SuppressErrors)
                {
                    return;
                }

                var solutionCheckXenServer =
                    Properties.Settings.Default.ProxySetting != (int)HTTPHelper.ProxyStyle.DirectConnection ? Messages.SOLUTION_CHECK_XENSERVER_WITH_PROXY : Messages.SOLUTION_CHECK_XENSERVER;

                switch (w.Status)
                {
                case WebExceptionStatus.ConnectionClosed:
                    AddError(owner, connection, Messages.CONNECTION_CLOSED_BY_SERVER, string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.ConnectFailure:
                    AddError(owner, connection, Messages.CONNECTION_REFUSED, string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.ProtocolError:
                    if (w.Message != null && w.Message.Contains("(404)"))
                    {
                        AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    }
                    else if (w.Message != null && w.Message.Contains("(407)"))
                    {
                        string proxyAddress = Properties.Settings.Default.ProxyAddress;
                        AddError(owner, connection, string.Format(Messages.ERROR_PROXY_AUTHENTICATION, proxyAddress), string.Format(Messages.SOLUTION_CHECK_PROXY, proxyAddress));
                    }
                    else
                    {
                        AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN);
                    }
                    break;

                case WebExceptionStatus.NameResolutionFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_NOT_FOUND, ((XenConnection)connection).Hostname), Messages.SOLUTION_NOT_FOUND);
                    break;

                case WebExceptionStatus.ReceiveFailure:
                case WebExceptionStatus.SendFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(solutionCheckXenServer, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.SecureChannelFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_SECURE_CHANNEL_FAILURE, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN);
                    break;

                default:
                    AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN);
                    break;
                }
            }
            else if (error is UriFormatException)
            {
                AddError(owner, connection, string.Format(Messages.ERROR_INVALID_URI, connection.Name), Messages.SOLUTION_NOT_FOUND);
            }
            else if (error is FileNotFoundException)
            {
                // If you're using the DbProxy
                AddError(owner, connection, string.Format(string.Format(Messages.ERROR_FILE_NOT_FOUND, ((XenConnection)connection).Hostname), connection.Name), Messages.SOLUTION_UNKNOWN);
            }
            else if (error is ConnectionExists c)
            {
                ConnectionsManager.ClearCacheAndRemoveConnection(connection);

                if (!Program.RunInAutomatedTestMode)
                {
                    using (var dlg = new InformationDialog(c.GetDialogMessage(connection)))
                        dlg.ShowDialog(owner);
                }
            }
            else if (error is ArgumentException)
            {
                // This happens if the server API is incompatible with our bindings.  This should
                // never happen in production, but will happen during development if a field
                // changes type, for example.
                AddError(owner, connection, Messages.SERVER_API_INCOMPATIBLE, Messages.SOLUTION_UNKNOWN);
            }
            else if (error is ServerNotSupported)
            {
                // Server version is too old for this version of XenCenter
                AddError(owner, connection, string.Format(Messages.SERVER_TOO_OLD, BrandManager.ProductVersion70),
                         Messages.SERVER_TOO_OLD_SOLUTION);
            }
            else
            {
                if (((XenConnection)connection).SuppressErrors)
                {
                    return;
                }

                AddError(owner, connection, string.Format(Messages.ERROR_UNKNOWN, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN);
            }
        }
Exemple #2
0
        public OutoposManager(string bitmapPath, string cachePath, BufferManager bufferManager)
        {
            _bitmapPath    = bitmapPath;
            _cachePath     = cachePath;
            _bufferManager = bufferManager;

            _clientManager      = new ClientManager(_bufferManager);
            _serverManager      = new ServerManager(_bufferManager);
            _bitmapManager      = new BitmapManager(_bitmapPath, _bufferManager);
            _cacheManager       = new CacheManager(_cachePath, _bitmapManager, _bufferManager);
            _connectionsManager = new ConnectionsManager(_clientManager, _serverManager, _cacheManager, _bufferManager);
            _downloadManager    = new DownloadManager(_connectionsManager, _cacheManager, _bufferManager);
            _uploadManager      = new UploadManager(_connectionsManager, _cacheManager, _bufferManager);

            _clientManager.CreateCapEvent = (object sender, string uri) =>
            {
                if (_createCapEvent != null)
                {
                    return(_createCapEvent(this, uri));
                }

                return(null);
            };

            _serverManager.AcceptCapEvent = (object sender, out string uri) =>
            {
                uri = null;

                if (_acceptCapEvent != null)
                {
                    return(_acceptCapEvent(this, out uri));
                }

                return(null);
            };

            _clientManager.CheckUriEvent = (object sender, string uri) =>
            {
                if (_checkUriEvent != null)
                {
                    return(_checkUriEvent(this, uri));
                }

                return(true);
            };

            _serverManager.CheckUriEvent = (object sender, string uri) =>
            {
                if (_checkUriEvent != null)
                {
                    return(_checkUriEvent(this, uri));
                }

                return(true);
            };

            _connectionsManager.GetLockSignaturesEvent = (object sender) =>
            {
                if (_getLockSignaturesEvent != null)
                {
                    return(_getLockSignaturesEvent(this));
                }

                return(null);
            };

            _connectionsManager.GetLockWikisEvent = (object sender) =>
            {
                if (_getLockWikisEvent != null)
                {
                    return(_getLockWikisEvent(this));
                }

                return(null);
            };

            _connectionsManager.GetLockChatsEvent = (object sender) =>
            {
                if (_getLockChatsEvent != null)
                {
                    return(_getLockChatsEvent(this));
                }

                return(null);
            };
        }
Exemple #3
0
 public bool Logout(string uuid, string password)
 {
     return(ConnectionsManager.Remove(uuid, password));
 }
Exemple #4
0
        internal static void ShowConnectingDialogError_(Form owner, IXenConnection connection, Exception error)
        {
            if (error is ExpressRestriction)
            {
                ExpressRestriction e = (ExpressRestriction)error;
                Program.Invoke(Program.MainWindow, delegate()
                {
                    new LicenseWarningDialog(e.HostName, e.ExistingHostName).ShowDialog(owner);
                });
                return;
            }

            if (error is Failure)
            {
                Failure f = (Failure)error;
                if (f.ErrorDescription[0] == Failure.HOST_IS_SLAVE)
                {
                    string oldHost        = connection.Name;
                    string poolMasterName = f.ErrorDescription[1];

                    string pool_name = XenConnection.ConnectedElsewhere(poolMasterName);
                    if (pool_name != null)
                    {
                        if (!Program.RunInAutomatedTestMode)
                        {
                            if (pool_name == oldHost)
                            {
                                new ThreeButtonDialog(
                                    new ThreeButtonDialog.Details(
                                        SystemIcons.Information,
                                        string.Format(Messages.OLD_CONNECTION_ALREADY_CONNECTED, pool_name),
                                        Messages.ADD_NEW_CONNECT_TO)).ShowDialog(owner);
                            }
                            else
                            {
                                new ThreeButtonDialog(
                                    new ThreeButtonDialog.Details(
                                        SystemIcons.Information,
                                        string.Format(Messages.SLAVE_ALREADY_CONNECTED, oldHost, pool_name),
                                        Messages.ADD_NEW_CONNECT_TO)).ShowDialog(owner);
                            }
                        }
                    }
                    else
                    {
                        if (DialogResult.Yes ==
                            new ThreeButtonDialog(
                                new ThreeButtonDialog.Details(
                                    SystemIcons.Warning,
                                    String.Format(Messages.SLAVE_CONNECTION_ERROR, oldHost, poolMasterName),
                                    Messages.CONNECT_TO_SERVER),
                                ThreeButtonDialog.ButtonYes,
                                ThreeButtonDialog.ButtonNo).ShowDialog(owner))
                        {
                            ((XenConnection)connection).Hostname = poolMasterName;
                            BeginConnect(connection, true, owner, false);
                        }
                    }
                }
                else if (f.ErrorDescription[0] == Failure.RBAC_PERMISSION_DENIED)
                {
                    AddError(owner, connection, Messages.ERROR_NO_PERMISSION, Messages.SOLUTION_NO_PERMISSION);
                }
                else if (f.ErrorDescription[0] == XenAPI.Failure.SESSION_AUTHENTICATION_FAILED)
                {
                    AddError(owner, connection, Messages.ERROR_AUTHENTICATION, Messages.SOLUTION_AUTHENTICATION);
                }
                else if (f.ErrorDescription[0] == Failure.HOST_STILL_BOOTING)
                {
                    AddError(owner, connection, Messages.ERROR_HOST_STILL_BOOTING, Messages.SOLUTION_HOST_STILL_BOOTING);
                }
                else
                {
                    AddError(owner, connection, string.IsNullOrEmpty(f.Message) ? Messages.ERROR_UNKNOWN : f.Message, string.Empty);
                }
            }
            else if (error is WebException)
            {
                if (((XenConnection)connection).SupressErrors)
                {
                    return;
                }

                WebException w = (WebException)error;
                switch (w.Status)
                {
                case WebExceptionStatus.ConnectionClosed:
                    AddError(owner, connection, Messages.CONNECTION_CLOSED_BY_SERVER, string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.ConnectFailure:
                    AddError(owner, connection, Messages.CONNECTION_REFUSED, string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname));
                    break;

                case WebExceptionStatus.ProtocolError:
                    if (w.Message != null && w.Message.Contains("(404)"))
                    {
                        AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname));
                    }
                    else
                    {
                        AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN);
                    }
                    break;

                case WebExceptionStatus.NameResolutionFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_NOT_FOUND, ((XenConnection)connection).Hostname), Messages.SOLUTION_NOT_FOUND);
                    break;

                case WebExceptionStatus.ReceiveFailure:
                case WebExceptionStatus.SendFailure:
                    AddError(owner, connection, string.Format(Messages.ERROR_NO_XENSERVER, ((XenConnection)connection).Hostname), string.Format(Messages.SOLUTION_CHECK_XENSERVER, ((XenConnection)connection).Hostname));
                    break;

                default:
                    AddError(owner, connection, Messages.ERROR_UNKNOWN, Messages.SOLUTION_UNKNOWN);
                    break;
                }
            }
            else if (error is UriFormatException)
            {
                AddError(owner, connection, string.Format(Messages.ERROR_INVALID_URI, connection.Name), Messages.SOLUTION_NOT_FOUND);
            }
            else if (error is FileNotFoundException)
            {
                // If you're using the DbProxy
                AddError(owner, connection, string.Format(string.Format(Messages.ERROR_FILE_NOT_FOUND, ((XenConnection)connection).Hostname), connection.Name), Messages.SOLUTION_UNKNOWN);
            }
            else if (error is ConnectionExists)
            {
                ConnectionsManager.ClearCacheAndRemoveConnection(connection);

                if (!Program.RunInAutomatedTestMode)
                {
                    ConnectionExists c = error as ConnectionExists;

                    new ThreeButtonDialog(
                        new ThreeButtonDialog.Details(
                            SystemIcons.Information,
                            c.GetDialogMessage(connection),
                            Messages.XENCENTER)).ShowDialog(owner);
                }
            }
            else if (error is ArgumentException)
            {
                // This happens if the server API is incompatible with our bindings.  This should
                // never happen in production, but will happen during development if a field
                // changes type, for example.
                AddError(owner, connection, Messages.SERVER_API_INCOMPATIBLE, Messages.SOLUTION_UNKNOWN);
            }
            else if (error is ServerNotSupported)
            {
                // Server version is too old for this version of XenCenter
                AddError(owner, connection, Messages.SERVER_TOO_OLD, Messages.SERVER_TOO_OLD_SOLUTION);
            }
            else
            {
                if (((XenConnection)connection).SupressErrors)
                {
                    return;
                }

                AddError(owner, connection, string.Format(Messages.ERROR_UNKNOWN, ((XenConnection)connection).Hostname), Messages.SOLUTION_UNKNOWN);
            }
        }
Exemple #5
0
 public ConnectionsManagerController(DatabaseContext context, ConnectionsManager connectionsManager)
 {
     this._context            = context;
     this._connectionsManager = connectionsManager;
 }
        // This method gets called by the runtime. Use this method to add services to the container.
        public void ConfigureServices(IServiceCollection services)
        {
            services.Configure <CookiePolicyOptions>(options =>
            {
                // This lambda determines whether user consent for non-essential cookies is needed for a given request.
                options.CheckConsentNeeded    = context => true;
                options.MinimumSameSitePolicy = SameSiteMode.None;
            });

            services.AddOptions();

            // Application Configuration
            services.Configure <ConfigServerData>(Configuration.GetSection("workshopConfig"));

            // Optional: Adds ConfigServerClientOptions to service container
            services.ConfigureConfigServerClientOptions(Configuration);

            // Optional:  Adds IConfiguration and IConfigurationRoot to service container
            services.AddConfiguration(Configuration);

            // Optional:  Adds CloudFoundryApplicationOptions and CloudFoundryServicesOptions to service container
            services.ConfigureCloudFoundryOptions(Configuration);

            // Add managment endpoint services
            services.AddCloudFoundryActuators(Configuration);

            // Add your own IInfoContributor, making sure to register with the interface
            //services.AddSingleton<IInfoContributor, ArbitraryInfoContributor>();

            // Add your own IHealthContributor, registered with the interface
            //services.AddSingleton<IHealthContributor, CustomHealthContributor>();

            // Add management components which collect and forwards metrics to
            // the Cloud Foundry Metrics Forwarder service
            // Remove comments below to enable
            // services.AddMetricsActuator(Configuration);
            // services.AddMetricsForwarderExporter(Configuration);

            // Enable Redis function if not offline
            if (!Environment.IsDevelopment())
            {
                // Use Redis cache on CloudFoundry to DataProtection Keys
                services.AddRedisConnectionMultiplexer(Configuration);
                services.AddDataProtection()
                .PersistKeysToRedis()
                .SetApplicationName("webuicore");
            }
            // End Redis

            // Load Fortune Service Options
            services.Configure <FortuneServiceOptions>(Configuration.GetSection("fortuneService"));
            // End load Fortune Service

            // Add service client library for calling the Fortune Service
            services.AddScoped <IFortuneService, FortuneServiceClient>();
            // End add service client

            // Add Service Discovery - remove development env check if running eureka locally
            if (!Environment.IsDevelopment())
            {
                services.AddDiscoveryClient(Configuration);
            }
            // End Service Discovery

            // Add Credhub Client
            services.Configure <CredHubOptions>(Configuration.GetSection("CredHubClient"));
            services.AddCredHubClient(Configuration, logFactory);
            //

            // Add Session Caching function
            if (Environment.IsDevelopment())
            {
                services.AddDistributedMemoryCache();
            }
            else
            {
                // Use Redis cache on CloudFoundry to store session data
                services.AddDistributedRedisCache(Configuration);
            }
            services.AddSession();
            // End Session Cache

            // Add Circuit Breaker function
            services.AddHystrixCommand <FortuneServiceCommand>("FortuneService", Configuration);
            services.AddHystrixMetricsStream(Configuration);
            // End Add CB

            // Add RabbitMQ function
            services.AddRabbitMQConnection(Configuration);
            // End RabbitMQ

            // Update the connection strings from appSettings.json or Config Server from any User Provided Service of the same name
            // User Provided Service will take presidence over other sources
            ConnectionsManager.UpdateConnectionStrings(Configuration);
            var dbString = Configuration.GetConnectionString("AttendeeContext");

            try
            {
                services.AddDbContext <AttendeeContext>(options => options.UseSqlServer(dbString));
            }
            catch (Exception ex)
            {
                Console.WriteLine($"{ex.Message}");
            }
            // End connection strings

            services.AddMvc().SetCompatibilityVersion(CompatibilityVersion.Version_2_1);
        }
Exemple #7
0
 public void     Connect(string address, int port)
 {
     this.connectingThread = ConnectionsManager.OpenClient(this.console, new DefaultTcpClient(), address, port, this.OnClientConnected);
 }
Exemple #8
0
        public UploadManager(ConnectionsManager connectionsManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _connectionsManager = connectionsManager;
            _cacheManager       = cacheManager;
            _bufferManager      = bufferManager;

            _settings = new Settings(this.ThisLock);

            _threadCount = Math.Max(1, Math.Min(System.Environment.ProcessorCount, 32) / 2);

            _connectionsManager.UploadedEvent += (object sender, IEnumerable <Key> keys) =>
            {
                foreach (var key in keys)
                {
                    _uploadedKeys.Enqueue(key);
                }
            };

            _cacheManager.RemoveKeyEvent += (object sender, IEnumerable <Key> keys) =>
            {
                foreach (var key in keys)
                {
                    _uploadedKeys.Enqueue(key);
                }
            };

            _cacheManager.RemoveShareEvent += (object sender, string path) =>
            {
                _removeSharePaths.Enqueue(path);
            };

            _uploadedThread = new Thread(() =>
            {
                try
                {
                    for (; ;)
                    {
                        var key = _uploadedKeys.Dequeue();

                        while (_removeSharePaths.Count > 0)
                        {
                            Thread.Sleep(1000);
                        }

                        lock (this.ThisLock)
                        {
                            foreach (var item in _settings.UploadItems)
                            {
                                if (item.UploadKeys.Remove(key))
                                {
                                    item.UploadedKeys.Add(key);

                                    if (item.State == UploadState.Uploading)
                                    {
                                        if (item.UploadKeys.Count == 0)
                                        {
                                            item.State = UploadState.Completed;

                                            _settings.UploadedSeeds.Add(item.Seed.Clone());
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            });
            _uploadedThread.Priority = ThreadPriority.BelowNormal;
            _uploadedThread.Name     = "UploadManager_UploadedThread";
            _uploadedThread.Start();

            _removeShareThread = new Thread(() =>
            {
                try
                {
                    for (; ;)
                    {
                        var path = _removeSharePaths.Dequeue();

                        lock (this.ThisLock)
                        {
                            List <int> ids = null;

                            if (_shareLink.TryGetValue(path, out ids))
                            {
                                foreach (var id in ids.ToArray())
                                {
                                    this.Remove(id);
                                }
                            }
                        }
                    }
                }
                catch (Exception)
                {
                }
            });
            _removeShareThread.Priority = ThreadPriority.BelowNormal;
            _removeShareThread.Name     = "UploadManager_RemoveShareThread";
            _removeShareThread.Start();
        }
Exemple #9
0
        public BackgroundDownloadManager(ConnectionsManager connectionsManager, CacheManager cacheManager, BufferManager bufferManager)
        {
            _connectionsManager = connectionsManager;
            _cacheManager       = cacheManager;
            _bufferManager      = bufferManager;

            _settings = new Settings(this.ThisLock);

            _cacheManager.SetKeyEvent += (object sender, IEnumerable <Key> keys) =>
            {
                foreach (var key in keys)
                {
                    _setKeys.Enqueue(key);
                }
            };

            _cacheManager.RemoveKeyEvent += (object sender, IEnumerable <Key> keys) =>
            {
                foreach (var key in keys)
                {
                    _removeKeys.Enqueue(key);
                }
            };

            _setThread = new Thread(() =>
            {
                try
                {
                    for (; ;)
                    {
                        var key = _setKeys.Dequeue();

                        lock (this.ThisLock)
                        {
                            _existManager.Set(key, true);
                        }
                    }
                }
                catch (Exception)
                {
                }
            });
            _setThread.Priority = ThreadPriority.BelowNormal;
            _setThread.Name     = "BackgroundDownloadManager_SetThread";
            _setThread.Start();

            _removeThread = new Thread(() =>
            {
                try
                {
                    for (; ;)
                    {
                        var key = _removeKeys.Dequeue();

                        lock (this.ThisLock)
                        {
                            _existManager.Set(key, false);
                        }
                    }
                }
                catch (Exception)
                {
                }
            });
            _removeThread.Priority = ThreadPriority.BelowNormal;
            _removeThread.Name     = "BackgroundDownloadManager_RemoveThread";
            _removeThread.Start();

            _connectionsManager.GetLockSignaturesEvent = (object sender) =>
            {
                return(this.SearchSignatures);
            };
        }
Exemple #10
0
        /// <summary>
        /// Handles incoming <see cref="Packet"/>.
        /// </summary>
        /// <param name="p"><see cref="Packet"/> to handle.</param>
        internal void Handle(Packet p)
        {
            switch (p.FirstOpcode)
            {
            case ServiceLayer.Identity:
            {
                switch (p.SecondOpcode)
                {
                case ServiceLayer.InitializeRequest:
                {
                    Logger.WriteLine(Source.InnerNetwork, "Connected service requests connection initialization.");
                    return;
                }

                case ServiceLayer.SetSettingsRequest:
                {
                    LoginServiceSettings settings = ( LoginServiceSettings )SetSettingsRequest.FromPacket(p, ServiceType.LoginService);
                    ConnectionsManager.SetServiceSettings(settings);
                    return;
                }
                }

                break;
            }

            case UserDataLayer.Identity:
            {
                switch (p.SecondOpcode)
                {
                case UserDataLayer.AuthenticateUser:
                {
                    UserAuthenticationRequest request = new UserAuthenticationRequest(p);

                    if (RealtimeManager.ConnectedUsers.Connected(request.SessionID))
                    {
                        Send(new UserAuthenticationResponse(request.RequestID, UserAuthenticationResponseType.AccessFailed).ToPacket());
                        return;
                    }

                    if (RealtimeManager.ConnectedUsers.Connected(request.Login))
                    {
                        Send(new UserAuthenticationResponse(request.RequestID, UserAuthenticationResponseType.AccountInUse).ToPacket());
                        return;
                    }

                    Send(DataProvider.DataBase.User_Auth(request, ( LoginServiceSettings )Service.RemoteServiceSettings).ToPacket());

                    return;
                }

                case UserDataLayer.CacheUserSessionRequest:
                {
                    CacheUserSessionRequest request = new CacheUserSessionRequest(p);

                    if (RealtimeManager.ConnectedUsers.Connected(request.Session.ID) || RealtimeManager.ConnectedUsers.Connected(request.Session.AccountName))
                    {
                        Send(new CacheUserSessionResponse(request.RequestID, CacheUserSessionResponse.Failed).ToPacket());
                        return;
                    }

                    RealtimeManager.ConnectedUsers.Register(request.Session);

                    Send(new CacheUserSessionResponse(request.RequestID, CacheUserSessionResponse.Accepted).ToPacket());

                    return;
                }

                case UserDataLayer.WorldsListRequest:
                {
                    WorldsListRequest request = new WorldsListRequest(p);
                    Send(new WorldsListResponse(request.RequestID, RealtimeManager.WorldsInfo.Get()).ToPacket());
                    return;
                }

                case UserDataLayer.UnCacheUser:
                {
                    UnCacheUser request = new UnCacheUser(p);

                    // update user login / logout / used_time values in database.

                    UserSession session = RealtimeManager.ConnectedUsers.Find(request.SessionID);

                    if (session != UserSession.Null)
                    {
                        DataProvider.DataBase.User_Logout(session.AccountID, session.StartTime, session.IPAddress, session.LastWorld);
                        RealtimeManager.ConnectedUsers.Unregister(request.SessionID);
                    }

                    return;
                }

                case UserDataLayer.JoinWorldRequest:
                {
                    // check access level

                    JoinWorldRequest request = new JoinWorldRequest(p);

                    if (!RealtimeManager.ConnectedUsers.Connected(request.SessionID))
                    {
                        Send(new JoinWorldResponse(request.RequestID, JoinWorldRequestResult.AccessFailed).ToPacket());
                        return;
                    }

                    if (!RealtimeManager.WorldsInfo.Contains(request.WorldID) || !RealtimeManager.WorldsInfo.IsOnline(request.WorldID))
                    {
                        Send(new JoinWorldResponse(request.RequestID, JoinWorldRequestResult.SystemError).ToPacket());
                        return;
                    }

                    if (RealtimeManager.WorldsInfo.IsFull(request.WorldID))
                    {
                        Send(new JoinWorldResponse(request.RequestID, JoinWorldRequestResult.TooManyPlayers).ToPacket());
                        return;
                    }

                    Send(new JoinWorldResponse(request.RequestID, JoinWorldRequestResult.Accepted).ToPacket());
                    return;
                }
                }

                break;
            }

            default:
            {
                break;
            }
            }

            Logger.WriteLine(Source.InnerNetwork, "Unknown packet received from {0} service:{1}{2}", ServiceType.LoginService, Environment.NewLine, p.ToString());
        }
    private void LoadData()
    {
        //Objects can only be loaded when the have the correct tag.
        List <GameObject> loadedObjects   = GameObject.FindGameObjectsWithTag("NarrativeTrigger").ToList();
        List <GameObject> objectsToRemove = new List <GameObject>();

        //The triggers need a parent in the scene, that way it does not get messy in the scene. (This can be changed to a different tag etc).
        nodesParent = GameObject.FindGameObjectWithTag("ObjectsParent");
        if (nodesParent == null)
        {
            nodesParent      = new GameObject();
            nodesParent.name = "GeneratedTriggers";
            nodesParent.tag  = "ObjectsParent";
        }

        //Every gamobject that gets loaded in must have a TriggerNodeInfo script. Otherwise there's no data to be loaded.
        foreach (GameObject obj in loadedObjects)
        {
            TriggerNodeInfo tempScript = obj.GetComponent <TriggerNodeInfo>();
            if (tempScript != null)
            {
                sceneItems.Add(tempScript);
            }
            else
            {
                objectsToRemove.Add(obj);
            }
        }

        if (objectsToRemove.Count > 0)
        {
            Debug.LogWarning("WARNING: Some gameobjects with the tag NarrativeTrigger don't have a TriggerNodeInfo script. Please fix or remove those!");
        }

        if (nodes == null)
        {
            nodes = new List <Node>();
        }

        //For every node we load in the data and create a new node.
        foreach (TriggerNodeInfo info in sceneItems)
        {
            Node tempNode = new Node(info.rect, nodeStyle, selectedNodeStyle, inPointStyle, outPointStyle, titleStyle, OnClickRemoveNode, this, nodesCreated);

            //We need to update the highest node id to make sure we dont get duplicate IDs.
            if (info.ID > highestID)
            {
                highestID = info.ID;
            }

            tempNode.ID               = info.ID;
            tempNode.title            = info.stepDescription;
            tempNode.showAudio        = info.showAudio;
            tempNode.playedAudioClips = info.playedAudioClips;
            tempNode.delays           = info.delays;
            tempNode.pathType         = info.pathType;
            tempNode.scrollViewVector = info.scrollViewVector;
            tempNode.worldPosition    = info.transform.position;

            nodes.Add(tempNode);
            nodesCreated++;
        }

        //We need the ConnectionManager to load in the connecitions between nodes.
        ConnectionsManager conManager = GetConnectionManager();

        List <ConnectionInfo> connectionsToRemove = new List <ConnectionInfo>();

        if (connections == null)
        {
            connections = new List <Connection>();
        }

        if (nodes.Count > 0)
        {
            if (conManager.connections != null)
            {
                foreach (ConnectionInfo info in conManager.connections)
                {
                    bool bothNodesExist = false;

                    Node inPoint  = nodes.Where(t => t.ID == info.inPointID).First();
                    Node outPoint = nodes.Where(t => t.ID == info.outPointID).First();

                    Connection tempCon = new Connection(inPoint, outPoint, info.connectionType, OnClickRemoveConnection);

                    if (inPoint != null && outPoint != null)
                    {
                        bothNodesExist = true;
                    }
                    else
                    {
                        connectionsToRemove.Add(info);
                    }

                    if (bothNodesExist)
                    {
                        //The connection needs to be added to both nodes (This way, in the game it knows which node(s) it needs to enable) and the connection list.
                        inPoint.AddNewConnection(tempCon);
                        outPoint.AddNewConnection(tempCon);

                        connections.Add(tempCon);
                    }
                }
            }
        }
        else
        {
            //if there are no nodes, we need to clear the connections
            connectionsToRemove = conManager.connections;
        }

        if (connectionsToRemove != null)
        {
            if (connectionsToRemove.Count > 0)
            {
                foreach (ConnectionInfo inf in connectionsToRemove)
                {
                    conManager.connections.Remove(inf);
                }
                connectionsToRemove.Clear();
            }
        }
    }