/// <summary> /// /// </summary> internal AccountLoginAck( ServerInfo[] serverInfo ) : base( 0x708, 0 /*6 + ?*/ ) { WriterStream.Write( (ushort)0 /*6 + ?*/ ); // ×ֶδóС WriterStream.Write( (ushort)base.PacketID ); // ×ֶαàºÅ WriterStream.Write( (ushort)0x00 ); // ×ֶα£Áô ////////////////////////////////////////////////////////////////////////// WriterStream.Write( (uint)0x0C000000 ); WriterStream.Write( (sbyte)0x0 ); // дÈëChannelsÐÅÏ¢ for ( int iIndex = 0; iIndex < serverInfo.Length; iIndex++ ) { WriterStream.Write( (sbyte)( 48 + iIndex ) ); WriterStream.WriteAsciiNull( serverInfo[iIndex].ServerName ); WriterStream.Write( (int)serverInfo[iIndex].ServerGuid ); } ////////////////////////////////////////////////////////////////////////// WriterStream.Seek( 0, SeekOrigin.Begin ); WriterStream.Write( (ushort)WriterStream.Length ); // ×ֶδóС }
public bool GetPcLockStatus(ServerInfo serverInfo) { string connString = String.Format(settingsHelper.connectionString, serverInfo.address); SqlConnection connection = new SqlConnection(connString); DataClassesDataContext database = new DataClassesDataContext(); try { connection.Open(); var queryPc = from c in database.Computers where c.PC_name == Environment.MachineName select c.Lock_status; if (queryPc.Count() > 0) { if (queryPc.First() == 1) return true; else return false; } else { return false; } } catch (Exception ex) { MessageBox.Show(ex.Message); return false; } finally { connection.Close(); } }
public void EndSession(ServerInfo serverInfo, int sessionId) { string connString = String.Format(settingsHelper.connectionString, serverInfo.address); SqlConnection connection = new SqlConnection(connString); DataClassesDataContext database = new DataClassesDataContext(); try { connection.Open(); var queryLogs = from l in database.Logs where l.ID == sessionId select l; if (queryLogs.Any()) { queryLogs.First().Time_logout = DateTime.Now; database.SubmitChanges(); } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { connection.Close(); } }
public void ConfirmActivity(ServerInfo serverInfo, List<Cert> certList) { string connString = String.Format(settingsHelper.connectionString, serverInfo.address); SqlConnection connection = new SqlConnection(connString); DataClassesDataContext database = new DataClassesDataContext(); try { connection.Open(); foreach (var cert in certList) { var queryRequest = from r in database.Requests join l in database.Logs on r.LogId equals l.ID join u in database.Users on l.ID_user equals u.ID join c in database.Computers on l.ID_pc equals c.ID where u.Username == cert.user && c.PC_name == SystemInformation.ComputerName select r; if (queryRequest.Any()) { queryRequest.First().Confirmed = 1; database.SubmitChanges(); } } } catch (Exception ex) { MessageBox.Show(ex.Message); } finally { connection.Close(); } }
private void ServerInfoCommandOnRoundStart(object sender, ServerInfo lastRoundServerInfo) { if (!_rconClient.ServerInfoCommand.ServerInfo.IsPregame) return; _rconClient.SendMessageAll("KD: Pre-game starting. In pre-game widget use is FREE."); }
public void SaveServerInfo(ServerInfo serverInfo) { if (!File.Exists(settingsHelper.userPath + settingsHelper.defaultSettingsFile)) { XDocument xSettings = new XDocument( new XDeclaration("1.0", "UTF-16", null), new XElement(settingsHelper.xNameSpace + "Emplokey_settings", new XElement("Server", new XElement("Address", serverInfo.address), new XElement("DbName", serverInfo.dbName) ))); xSettings.Save(settingsHelper.userPath + settingsHelper.defaultSettingsFile); } else { XDocument xSettings = XDocument.Load(settingsHelper.userPath + settingsHelper.defaultSettingsFile); var queryServer = (from q in xSettings.Descendants("Server") select q).First(); queryServer.Element("Address").Value = serverInfo.address; queryServer.Element("DbName").Value = serverInfo.dbName; xSettings.Save(settingsHelper.userPath + settingsHelper.defaultSettingsFile); } }
public void SerializeDeserialize() { const string logo = "logo"; const string name = "name"; const string desc = "description"; ServerInfo info = new ServerInfo (new ServerSettings { ServerLogo = logo, Name = name, Description = desc, ServerPassword = "******" }, new GuestUserProvider()); var stream = new MemoryStream (new byte[20480], true); var writer = new StreamValueWriter (stream); var reader = new StreamValueReader (stream); info.Serialize (null, writer); long length = stream.Position; stream.Position = 0; info = new ServerInfo (null, reader); Assert.AreEqual (length, stream.Position); Assert.AreEqual (logo, info.Logo); Assert.AreEqual (name, info.Name); Assert.AreEqual (desc, info.Description); Assert.AreEqual (true, info.Passworded); Assert.AreEqual (UserRegistrationMode.None, info.RegistrationMode); Assert.IsNull (info.RegistrationContent); }
internal static DataTable Query(string sql, ServerInfo info) { var data = QuerySet(sql, info); if (data != null && data.Tables.Count > 0) return data.Tables[0]; return null; }
private void UpdateAuthenticationManager() { // Register the server information with the AuthenticationManager ServerInfo portalServerInfo = new ServerInfo { ServerUri = new Uri(OAuthPage.PortalUrl), OAuthClientInfo = new OAuthClientInfo { ClientId = OAuthPage.AppClientId, RedirectUri = new Uri(OAuthPage.OAuthRedirectUrl) }, // Specify OAuthAuthorizationCode if you need a refresh token (and have specified a valid client secret) // Otherwise, use OAuthImplicit TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit }; // Get a reference to the (singleton) AuthenticationManager for the app AuthenticationManager thisAuthenticationManager = AuthenticationManager.Current; // Register the server information thisAuthenticationManager.RegisterServer(portalServerInfo); // Assign the method that AuthenticationManager will call to challenge for secured resources thisAuthenticationManager.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync); // Set the OAuth authorization handler to this class (Implements IOAuthAuthorize interface) thisAuthenticationManager.OAuthAuthorizeHandler = this; }
internal IrcContext(Message message, Connection connection, ServerInfo info) { _conn = connection; _info = info; _msg = message; Init(); }
// Delay for failed ping public int GetPingerDelayRetry(ServerInfo server) { int delay = Engine.Instance.Storage.GetInt("pinger.retry"); if (delay == 0) delay = Conversions.ToInt32(server.Provider.GetKeyValue("pinger_retry", "5")); return delay; }
private void UpdateAuthenticationManager() { // Register the server information with the AuthenticationManager Esri.ArcGISRuntime.Security.ServerInfo serverInfo = new ServerInfo { ServerUri = new Uri(ServerUrl), OAuthClientInfo = new OAuthClientInfo { ClientId = ClientId, RedirectUri = new Uri(RedirectUrl) } }; // If a client secret has been configured, set the authentication type to OAuthAuthorizationCode if (!string.IsNullOrEmpty(ClientSecret)) { // Use OAuthAuthorizationCode if you need a refresh token (and have specified a valid client secret) serverInfo.TokenAuthenticationType = TokenAuthenticationType.OAuthAuthorizationCode; serverInfo.OAuthClientInfo.ClientSecret = ClientSecret; } else { // Otherwise, use OAuthImplicit serverInfo.TokenAuthenticationType = TokenAuthenticationType.OAuthImplicit; } // Register this server with AuthenticationManager AuthenticationManager.Current.RegisterServer(serverInfo); // Use the OAuthAuthorize class in this project to handle OAuth communication AuthenticationManager.Current.OAuthAuthorizeHandler = new OAuthAuthorize(); // Use a function in this class to challenge for credentials AuthenticationManager.Current.ChallengeHandler = new ChallengeHandler(CreateCredentialAsync); }
public void ExportData(System.Xml.XmlWriter writer) { ServerInfo host = new ServerInfo(); writer.WriteStartElement("server"); host.WriteXml(writer); writer.WriteEndElement(); }
public void QueryFinished(ServerInfo server, string status, int httpStatusCode = 0, string diagnostics = null) { if (this.IsEnabled()) { this.QueryFinished(server.ToString(), status, httpStatusCode, diagnostics); } }
public void SendingBlockQuery(ServerInfo server, string urlString, IEnumerable<ServerInfo> sources, double timeOutInMilliseconds) { if (this.IsEnabled()) { this.SendingBlockQuery(server.Hostname, urlString, string.Join(",", sources), timeOutInMilliseconds); } }
/// <summary> /// Updates or inserts the server info. /// </summary> /// <param name="info">The info.</param> public void SetServerInfo(ServerInfo info) { var existingInfo = this.UnitOfWork.Get<ServerInfo>(info.Id); if (existingInfo != null) this.UnitOfWork.Update(info); else this.UnitOfWork.Insert(info); }
public override void OnHandshake(ServerInfo info) { if (ClientSession.Instance != null) { ClientSession.Instance.Handshake(info); } this.Send(frmMain.Instance.GetHashPacket()); }
public Client(IPAddress address, UInt16 port) { this.address = address; this.port = port; fetcher = new ContentFetcher (address, port); ContentNode node = ContentParser.Parse (ContentCodeBag.Default, fetcher.Fetch ("/server-info")); serverInfo = ServerInfo.FromNode (node); }
public void DiscoverIp(ServerInfo server) { string[] methods = Engine.Instance.Storage.Get("discover.ip_webservice.list").Split(';'); bool onlyFirstResponse = Engine.Instance.Storage.GetBool("discover.ip_webservice.first"); foreach (string method in methods) { try { if ((method.StartsWith("http://")) || (method.StartsWith("https://"))) { // Fetch a webservice string url = method; url = url.Replace("{@ip}", server.IpEntry); XmlDocument xmlDoc = Engine.Instance.XmlFromUrl(url, null, "iptitle", false); // Clodo: Bypass proxy? if (xmlDoc.DocumentElement.HasChildNodes) { // Node renaming Utils.XmlRenameTagName(xmlDoc.DocumentElement, "CountryCode", "country_code"); // Node parsing //string countryCode = Utils.XmlGetBody(Utils.XmlGetFirstElementByTagName(xmlDoc.DocumentElement, "country_code")).ToLowerInvariant().Trim(); string countryCode = Utils.XmlGetBody(xmlDoc.DocumentElement.SelectSingleNode(".//country_code") as XmlElement).ToLowerInvariant().Trim(); if (CountriesManager.IsCountryCode(countryCode)) { if(server.CountryCode != countryCode) { server.CountryCode = countryCode; Engine.Instance.MarkServersListUpdated(); Engine.Instance.MarkAreasListUpdated(); } } string cityName = Utils.XmlGetBody(xmlDoc.DocumentElement.SelectSingleNode(".//city_name") as XmlElement).Trim(); if (cityName == "N/A") cityName = ""; if (cityName != "") server.Location = cityName; if (onlyFirstResponse) break; } else { Engine.Instance.Logs.Log(LogType.Fatal, "Unable to fetch " + url); } } } catch (Exception) { } } }
public UserTableData(ServerInfo server, string table) : this() { rtbSQL.Font = Monitor.Instance.SetFont(); _server = server; _table = table; var sql = "SELECT TOP 100 * FROM " + _table; Utils.SetTextBoxStyle(rtbSQL); rtbSQL.Text = sql; Execute(); }
public void Add(ServerInfo e) { int offset = this.data.Length; Array.Resize(ref this.data, this.data.Length + 39); this.data[0]++; this.data[offset + 0] = e.Index; UnicodeEncoding.Unicode.GetBytes(e.Name, 0, Math.Min(16, e.Name.Length), this.data, offset + 1); this.data[offset + 35] = e.ping; this.data[offset + 36] = e.playercount; }
public RedisInfo() { Replication = new ReplicationInfo(); Clients = new ClientInfo(); Server = new ServerInfo(); Memory = new MemoryInfo(); Persistence = new PersistenceInfo(); Stats = new StatsInfo(); CPU = new CPUInfo(); Keyspace = new KeyspaceInfo(); }
public void LastUpdateTimeCannotBeSetBackwards() { var serverInfo = new ServerInfo(new ServerRegistration {Hostname = "foo", Port = 4200}); var timeToSet = DateTimeOffset.Now; serverInfo.LastUpdateTime = timeToSet; Assert.AreEqual(timeToSet, serverInfo.LastUpdateTime); serverInfo.LastUpdateTime = timeToSet.Subtract(TimeSpan.FromSeconds(1)); Assert.AreEqual(timeToSet, serverInfo.LastUpdateTime); }
/// <summary> /// Adds server and channel information to packet. /// </summary> /// <param name="packet"></param> /// <param name="server"></param> /// <param name="type"></param> public static void AddServerInfo(this Packet packet, ServerInfo server, ServerInfoType type) { packet.PutString(server.Name); packet.PutShort(0); // Server type? packet.PutShort(0); packet.PutByte(1); // Channels packet.PutInt((int)server.Channels.Count); foreach (var channel in server.Channels.Values) packet.AddChannelInfo(channel, type); }
private void AddServer(ServerInfo theServerInfo) { this.Dispatcher.BeginInvoke(new System.Windows.Forms.MethodInvoker(delegate() { svspServers.Visibility = Visibility.Collapsed; svwpServers.Visibility = Visibility.Visible; ServerSelector theControl = new ServerSelector(theServerInfo, myUserPrefs, false, myVariables); theControl.Checked += new RoutedEventHandler(theControl_Checked); theControl.Margin = thck; wpServers.Children.Add(theControl); }), System.Windows.Threading.DispatcherPriority.Normal); }
internal static object ExecuteScalar(string sql, ServerInfo server) { object result; using (var connection = CreateNewConnection(server)) { var command = new SqlCommand(sql, connection); connection.Open(); result = command.ExecuteScalar(); connection.Close(); } return result; }
public BotClient(string server, int port, bool ssl) { Server = server; Port = port; UsingSSL = ssl; _info = new ServerInfo(); _listeners = new List<IIrcBot> { (_pinger = new PingerBot(server)), (_ctcp = new CtcpBot()) }; }
internal static string ExecuteNonQuery(string sql, ServerInfo server) { using (var connection = CreateNewConnection(server)) { var result = new StringBuilder(); connection.InfoMessage += (s, e) => { result.AppendLine(e.Message); }; var command = new SqlCommand(sql, connection); connection.Open(); command.ExecuteNonQuery(); connection.Close(); return result.ToString(); } }
public QueryResults(ServerInfo serverInfo, IEnumerable<IChannelInfo> channels, IEnumerable<IUserInfo> users) { if (serverInfo == null) throw new ArgumentNullException ("serverInfo"); if (channels == null) throw new ArgumentNullException ("channels"); if (users == null) throw new ArgumentNullException ("users"); ServerInfo = serverInfo; Channels = channels; Users = users; }
internal static SqlConnection CreateNewConnection(ServerInfo info) { var builder = new SqlConnectionStringBuilder { ApplicationName = Settings.Title, IntegratedSecurity = info.AuthType == AuthTypes.Windows, DataSource = info.Server, UserID = info.User, Password = info.Password, InitialCatalog = info.Database ?? string.Empty, ConnectTimeout = Settings.Instance.ConnectionTimeout }; return new SqlConnection(builder.ConnectionString); }
public Scene(ServerInfo info) { }
/// <summary> /// 检查本地热更信息与服务器热更信息比较 /// </summary> /// <returns> false 不需要更新, true 需要更新</returns> private bool CheckLocalAndServerPatch() { #if JSON //if (!File.Exists(m_localJsonPath)) // return true; Branches branch = null; var branches = m_serverInfoDataModule.GameVersionInfos.FirstOrDefault(i => i.GameVersion == m_curVersion); Debug.Assert(null != branches, "未找到与当前App Version 所匹配的更新信息 : App Version " + m_curVersion); branch = branches.Branches.FirstOrDefault(i => i.BranchName == m_branchName); Debug.Assert(null != branches, "未找到与当前Branch Name 所匹配的更新信息 : Branch Name " + m_branchName); var assetVersion = LocalVersionInfoManager.Instance.GetVersionInfo(m_curVersion, m_branchName); if (null != assetVersion && "" != assetVersion) { // 获取与本地版本相匹配的版本序号 var localPatch = branch.Patches.FirstOrDefault(i => i.Version == assetVersion); m_localVersionIndex = branch.Patches.IndexOf(localPatch) + 1; m_localVersion = branch.Patches[m_localVersionIndex - 1].Version; Debug.Log("当前本地资源版本 : " + m_localVersion); } m_targetVersion = branch.Patches[m_currentBranch.Patches.Count - 1].Version; return("" != assetVersion && null != m_currentBranch.Patches && assetVersion != m_currentBranch.Patches[m_currentBranch.Patches.Count - 1].Version); // // 读取本地版本信息 // StreamReader sr = new StreamReader(m_localJsonPath); // var content = sr.ReadToEnd(); // m_localInfoDataModule = new ServerInfoDataModule(JsonMapper.ToObject(content)); // sr.Close(); // // 匹配与当前APP Version所匹配的资源信息 // //GameVersionInfo matchInfo = null; // if (null != m_localInfoDataModule) // { // var info = m_localInfoDataModule.GameVersionInfos.FirstOrDefault(i => i.GameVersion == m_curVersion); // if (null != info) // { // // 获取当前本地资源版本 // branch = info.Branches.FirstOrDefault(i => i.BranchName == m_branchName); // m_localVersionIndex = branch.Patches.Count; // m_localVersion = branch.Patches[m_localVersionIndex - 1].Version; // Debug.Log("当前本地资源版本 : " + m_localVersion); // } //} // // 与服务端对应的APP Version相关信息进行比对, 如果当前的热更好与服务器端最新的一样就返回true; // return null != branch && // null != m_currentBranch.Patches && // (null != branch.Patches && m_currentBranch.Patches.Count != 0) && // m_currentBranch.Patches[m_currentBranch.Patches.Count - 1].Version != m_localVersion; #elif XML if (!File.Exists(m_localXmlPath)) { return(true); } m_localInfo = BinarySerializeOpt.XmlDeserialize(m_localXmlPath, typeof(ServerInfo)) as ServerInfo; VersionInfo versionInfo1 = null; if (m_localInfo != null) { foreach (VersionInfo versionInfo2 in m_localInfo.GameVersion) { if (versionInfo2.Version == m_curVersion) { versionInfo1 = versionInfo2; break; } } } return(versionInfo1 != null && m_gameVersion.Patches != null && (versionInfo1.Patches != null && m_gameVersion.Patches.Length != 0) && m_gameVersion.Patches[m_gameVersion.Patches.Length - 1].Version != versionInfo1.Patches[versionInfo1.Patches.Length - 1].Version); #endif }
/// <summary> /// Obtain a list of AvailabilityGroup from XML config. /// </summary> private IEnumerable <AvailabilityGroup> _LegacyGetAvailabilityGroupList(XMLConfig config, string xml_section_name, string xml_server_info_entry_name, string xml_agroup_id_attribute_name) { var server_entry_list = config.GetEntries(xml_section_name, xml_server_info_entry_name); Dictionary <string, List <ServerInfo> > id_infolist_dict = new Dictionary <string, List <ServerInfo> >(); for (int i = 0; i < server_entry_list.Count; i++) { var str_ip_endpoint = server_entry_list[i].Value; string[] parts = str_ip_endpoint.Split(new char[] { ':' }); Dictionary <string, string> pvs = server_entry_list[i].Attributes().ToDictionary(attr => attr.Name.ToString(), attr => attr.Value); string assemblyPath = null; string Id = null; LogLevel loggingLevel = LoggingConfig.c_DefaultLogLevel; string storageRoot = null; if (pvs.ContainsKey(ConfigurationConstants.Attrs.LEGACY_ASSEMBLY_PATH)) { assemblyPath = FileUtility.CompletePath(pvs[ConfigurationConstants.Attrs.LEGACY_ASSEMBLY_PATH], false); } if (pvs.TryGetValue(ConfigurationConstants.Attrs.STORAGE_ROOT, out storageRoot)) { storageRoot = storageRoot.Trim(); } if (pvs.ContainsKey(ConfigurationConstants.Attrs.LOGGING_LEVEL)) { loggingLevel = (LogLevel)Enum.Parse(typeof(LogLevel), pvs[ConfigurationConstants.Attrs.LOGGING_LEVEL], true); } if (pvs.TryGetValue(xml_agroup_id_attribute_name, out Id)) { Id = Id.Trim(); } else { Id = i.ToString(CultureInfo.InvariantCulture); } ServerInfo si = ServerInfo._LegacyCreateServerInfo( hostName: parts[0].Trim(), port: int.Parse(parts[1]), //httpPort: TrinityConfig.HttpPort, assemblyPath: assemblyPath, availabilityGroup: Id, storageRoot: storageRoot, loggingLevel: loggingLevel.ToString()); List <ServerInfo> list = null; if (!id_infolist_dict.TryGetValue(si.Id, out list)) { list = new List <ServerInfo>(); id_infolist_dict.Add(si.Id, list); } list.Add(si); } return(id_infolist_dict.Select(_ => new AvailabilityGroup(_.Key, _.Value.Select(si => (ServerInfo)si)))); }
private void BindForm() { if (PanelSecurity.SelectedUser.Role == UserRole.Administrator && PanelSecurity.PackageId < 2) { ddlDestination.Items.Remove(ddlDestination.Items.FindByValue("1")); } if (PanelSecurity.LoggedUser.Role != UserRole.Administrator) { ddlDestination.Items.Remove(ddlDestination.Items.FindByValue("2")); } if (PanelSecurity.SelectedUser.Role != UserRole.Administrator) { chkDeleteBackup.Visible = false; } string modeText = "{0}"; string modeValue = ""; string filePrefix = ""; int userId = PanelSecurity.SelectedUserId, packageId = PanelSecurity.PackageId, serviceId = PanelRequest.ServiceId, serverId = PanelRequest.ServerId; if (PanelSecurity.PackageId > 0) { // load a single package PackageInfo backupPackage = ES.Services.Packages.GetPackage(PanelSecurity.PackageId); // load "store" packages PackageInfo[] packages = ES.Services.Packages.GetMyPackages(PanelSecurity.SelectedUser.UserId); foreach (PackageInfo package in packages) { ddlSpace.Items.Add(new ListItem(package.PackageName, package.PackageId.ToString())); } ddlSpace.SelectedValue = PanelSecurity.PackageId.ToString(); modeText = "Text.SpaceBackupMode"; modeValue = backupPackage.PackageName; filePrefix = "SpaceBackup"; } else if (PanelRequest.ServiceId > 0) { ddlDestination.Items.Remove(ddlDestination.Items.FindByValue("1")); ServiceInfo service = ES.Services.Servers.GetServiceInfo(PanelRequest.ServiceId); modeText = "Text.ServiceBackupMode"; modeValue = service.ServiceName; filePrefix = "ServiceBackup"; } else if (PanelRequest.ServerId > 0) { ddlDestination.Items.Remove(ddlDestination.Items.FindByValue("1")); ServerInfo server = ES.Services.Servers.GetServerById(PanelRequest.ServerId); modeText = "Text.ServerBackupMode"; modeValue = server.ServerName; filePrefix = "ServerBackup"; } else if (PanelSecurity.SelectedUserId > 0) { // load user spaces PackageInfo[] packages = ES.Services.Packages.GetMyPackages(PanelSecurity.SelectedUserId); foreach (PackageInfo package in packages) { ddlSpace.Items.Add(new ListItem(package.PackageName, package.PackageId.ToString())); } modeText = "Text.UserBackupMode"; modeValue = PanelSecurity.SelectedUser.Username; filePrefix = "UserBackup"; } // backupSetContent = ES.Services.Backup.GetBackupContentSummary(userId, packageId, serviceId, serverId); // rptBackupSetSummary.DataSource = backupSetContent.GetAllKeys(); rptBackupSetSummary.DataBind(); // backup type litBackupType.Text = String.Format(GetLocalizedString(modeText), modeValue); // backup file txtBackupFileName.Text = String.Format("{0}-{1}-{2}.wspak", filePrefix, Regex.Replace(modeValue, "[^\\w]", "_"), DateTime.Now.ToString("ddMMyyyy", System.Globalization.CultureInfo.InvariantCulture)); ToggleFormControls(); InitFolderBrowser(); }
private async Task TestDeathmatch(MultiPlayerServer server, ServerInfo serverInfo, MultiPlayerClient client1, MultiPlayerClient client2, int delayMs) { Exception undeliverableException = null; Exception deathmatchException = null; server.Undeliverable.SubscribeForLifetime((args) => undeliverableException = args.Exception, server); var deathmatch = new Deathmatch(new MultiPlayerContestOptions() { MaxPlayers = 2, Server = server }); deathmatch.OrchestrationFailed.SubscribeOnce((ex) => deathmatchException = ex); // the game starts await deathmatch.Start(); // both clients start waiting for the start of the game var client1StartTask = client1.EventRouter.GetAwaitable <StartGameMessage>(); var client2StartTask = client2.EventRouter.GetAwaitable <StartGameMessage>(); // both clients get notified of each other's presence var client1SeesClient2Task = client1.EventRouter.GetAwaitable <NewUserMessage>(); var client2SeesClient1Task = client2.EventRouter.GetAwaitable <NewUserMessage>(); // both clients connect, which should trigger the start of the game await client1.Connect(serverInfo); Console.WriteLine("client 1 connected"); await client2.Connect(serverInfo); Console.WriteLine("client 2 connected"); // make sure both clients got the start event await client1StartTask; await client2StartTask; await client1SeesClient2Task; await client2SeesClient1Task; Assert.AreEqual(client2.ClientId, client1SeesClient2Task.Result.NewUserId); Assert.AreEqual(client1.ClientId, client2SeesClient1Task.Result.NewUserId); var client1GameOverTask = client1.EventRouter.GetAwaitable <GameOverMessage>(); var client2GameOverTask = client2.EventRouter.GetAwaitable <GameOverMessage>(); var response = await client1.SendRequest(new DamageMessage() { DamagedClient = client2.ClientId, NewHP = 0 }, timeout : TimeSpan.FromDays(1)); // make sure both clients got the game over event event await Task.WhenAll(client1GameOverTask, client2GameOverTask); Assert.AreEqual(client1.ClientId, client1GameOverTask.Result.WinnerId); Assert.AreEqual(client1.ClientId, client2GameOverTask.Result.WinnerId); client1.Dispose(); client2.Dispose(); server.Dispose(); Assert.IsTrue(deathmatch.IsExpired); Assert.IsNull(undeliverableException); Assert.IsNull(deathmatchException); }
internal PrivateMessageEventArgs(IrcClient client, IrcMessage ircMessage, ServerInfo serverInfo) { IrcMessage = ircMessage; PrivateMessage = new PrivateMessage(client, IrcMessage, serverInfo); }
void OnGUI() { if (null != GetPlayerNet() && mxPlayerNet.GetPlayerState() == PlayerNet.PLAYER_STATE.E_PLAYER_GAMEING) { mxObjectElement.OnGUI(AFCKernel.Instance, 1024, 768); mxObjectElement.OnOpratorGUI(1024, 768); } if (null != GetPlayerNet()) { switch (GetPlayerNet().GetPlayerState()) { case PlayerNet.PLAYER_STATE.E_NONE: { if (strTargetIP.Length > 0) { mxPlayerNet.mxNet.StartConnect(strTargetIP, nPort); mxPlayerNet.ChangePlayerState(PlayerNet.PLAYER_STATE.E_WAITING_CONNET_NET); } } break; case PlayerNet.PLAYER_STATE.E_WAITING_CONNET_NET: { // Wait Reciving Connect event ,when connect sucessful ,enter status :E_CONNET_NET_SUCESS_WAITING_ACCOUNT } break; case PlayerNet.PLAYER_STATE.E_CONNET_NET_SUCESS_WAITING_ACCOUNT: { // wait user input account; mxPlayerNet.strAccount = GUI.TextField(new Rect(10, 10, 150, 50), mxPlayerNet.strAccount); mxPlayerNet.strPassword = GUI.TextField(new Rect(10, 100, 150, 50), mxPlayerNet.strPassword); if (GUI.Button(new Rect(10, 200, 150, 50), "Login")) { mxPlayerNet.mxSender.LoginPB(mxPlayerNet.strAccount, mxPlayerNet.strPassword, ""); mxPlayerNet.ChangePlayerState(PlayerNet.PLAYER_STATE.E_PLAYER_LOGINING_WAITING_lOGINRESULT); } } break; case PlayerNet.PLAYER_STATE.E_PLAYER_LOGINING_WAITING_lOGINRESULT: { // wait receiving msg EGMI_ACK_LOGIN, when receiving this msg,if receiving error result , show a error,and enter E_CONNET_NET_SUCESS_WAITING_ACCOUNT status // if login successful, enter E_PLAYER_LOGIN_SUCCESSFUL_WAITING_WORLD_LIST status } break; case PlayerNet.PLAYER_STATE.E_PLAYER_LOGIN_SUCCESSFUL: { // if login successful, enter E_PLAYER_LOGIN_SUCCESSFUL_WAITING_WORLD_LIST status PlayerSender sender = mxPlayerNet.mxSender; if (null != sender) { mxPlayerNet.ChangePlayerState(PlayerNet.PLAYER_STATE.E_PLAYER_WAITING_WORLD_LIST); sender.RequireWorldList(); } } break; case PlayerNet.PLAYER_STATE.E_PLAYER_WAITING_WORLD_LIST: { // wait receiving msg EGMI_ACK_WORLD_LIST, when receiving this msg,if receiving error result , show a error,and enter E_CONNET_NET_SUCESS_WAITING_ACCOUNT status // if successful, enter E_PLAYER_WORLD_LIST_SUCCESSFUL_WAITING_SELECT_WORLD status } break; case PlayerNet.PLAYER_STATE.E_PLAYER_WORLD_LIST_SUCCESSFUL_WAITING_SELECT_WORLD: { // show world list // wait user select world; int nHeight = 50; for (int i = 0; i < mxPlayerNet.aWorldList.Count; ++i) { ServerInfo xInfo = (ServerInfo)mxPlayerNet.aWorldList[i]; if (GUI.Button(new Rect(10, i * nHeight, 150, nHeight), xInfo.Name)) { AFStart.Instance.GetPlayerNet().nServerID = xInfo.ServerId; mxPlayerNet.mxSender.RequireConnectWorld(xInfo.ServerId); mxPlayerNet.ChangePlayerState(PlayerNet.PLAYER_STATE.E_PLAYER_SELECT_WORLD_WAIT_WORK_KEY); } } } break; case PlayerNet.PLAYER_STATE.E_PLAYER_GET_WORLD_KEY_SUCCESSFUL: { string strWorpdIP = AFStart.Instance.GetPlayerNet().strWorldIP; string strWorpdKey = AFStart.Instance.GetPlayerNet().strKey; string strAccount = AFStart.Instance.GetPlayerNet().strKey; int nPort = AFStart.Instance.GetPlayerNet().nWorldPort; PlayerNet xPlayerNet = new PlayerNet(); xPlayerNet.strWorldIP = strWorpdIP; xPlayerNet.strKey = strWorpdKey; xPlayerNet.strAccount = strAccount; xPlayerNet.nWorldPort = nPort; xPlayerNet.ChangePlayerState(PlayerNet.PLAYER_STATE.E_START_CONNECT_TO_GATE); xPlayerNet.mxNet.RegisteredConnectDelegation(OnGateConnect); xPlayerNet.mxNet.RegisteredDisConnectDelegation(OnGateDisConnect); xPlayerNet.mxNet.StartConnect(xPlayerNet.strWorldIP, nPort); SetFocusNet(xPlayerNet); } break; case PlayerNet.PLAYER_STATE.E_START_CONNECT_TO_GATE_SUCESS_FUL: { GetPlayerNet().mxSender.RequireVerifyWorldKey(GetPlayerNet().strAccount, GetPlayerNet().strKey); GetPlayerNet().ChangePlayerState(PlayerNet.PLAYER_STATE.E_WATING_VERIFY); } break; case PlayerNet.PLAYER_STATE.E_WATING_VERIFY: { //wait receiving msg EGMI_ACK_CONNECT_KEY, if receive failed ,show error enter none status //if have receiving successful Enter E_VERIFY_KEY_SUCCESS_FULL status; } break; case PlayerNet.PLAYER_STATE.E_VERIFY_KEY_SUCCESS_FULL: { // wait user select server; int nWidth = 200; for (int i = 0; i < mxPlayerNet.aServerList.Count; ++i) { ServerInfo xInfo = (ServerInfo)mxPlayerNet.aServerList[i]; if (GUI.Button(new Rect(nWidth, i * 50, 150, 50), xInfo.Name)) { GetPlayerNet().nServerID = xInfo.ServerId; GetFocusSender().RequireSelectServer(xInfo.ServerId); GetPlayerNet().ChangePlayerState(PlayerNet.PLAYER_STATE.E_WAIT_ROLELIST); } } } break; case PlayerNet.PLAYER_STATE.E_WAIT_ROLELIST: { // wait receiving EGMI_ACK_SELECT_SERVER msg, // when receiving this msg, send req role list; // and waiting EGMI_ACK_ROLE_LIST msg, if sucessful ,enter E_HAS_PLAYER_ROLELIST status; } break; case PlayerNet.PLAYER_STATE.E_GETROLELIST_SUCCESSFUL: { //AFCRenderInterface.Instance.LoadScene("SelectScene"); GetPlayerNet().ChangePlayerState(PlayerNet.PLAYER_STATE.E_WAIT_SELECT_ROLE); } break; case PlayerNet.PLAYER_STATE.E_WAIT_SELECT_ROLE: { if (mxPlayerNet.aCharList.Count > 0) { for (int i = 0; i < mxPlayerNet.aCharList.Count; ++i) { AFMsg.RoleLiteInfo xLiteInfo = (AFMsg.RoleLiteInfo)mxPlayerNet.aCharList[i]; if (GUI.Button(new Rect(200, i * 50, 150, 50), xLiteInfo.NoobName)) { mxPlayerNet.strRoleName = xLiteInfo.NoobName; GetPlayerNet().nMainRoleID = PlayerReciver.PBToAF(xLiteInfo.Id); GetPlayerNet().ChangePlayerState(PlayerNet.PLAYER_STATE.E_PLAYER_WAITING_TO_GAME); mxPlayerNet.mxSender.RequireEnterGameServer(AFStart.Instance.GetPlayerNet().nMainRoleID, mxPlayerNet.strAccount, mxPlayerNet.strRoleName, mxPlayerNet.nServerID); } } } else { mxPlayerNet.strRoleName = GUI.TextField(new Rect(10, 10, 150, 50), mxPlayerNet.strRoleName); if (GUI.Button(new Rect(10, 200, 150, 50), "CreateRole")) { GetPlayerNet().ChangePlayerState(PlayerNet.PLAYER_STATE.E_WAIT_CREATE_ROLE); mxPlayerNet.mxSender.RequireCreateRole(mxPlayerNet.strAccount, mxPlayerNet.strRoleName, 0, 0, mxPlayerNet.nServerID); } } } break; case PlayerNet.PLAYER_STATE.E_WAIT_CREATE_ROLE: { // wait receive EGMI_ACK_ROLE_LIST , when receive msg, enter E_WAIT_SELECT_ROLE status; } break; case PlayerNet.PLAYER_STATE.E_PLAYER_WAITING_TO_GAME: { // wait receive EGMI_ACK_SWAP_SCENE , when receive msg, enter E_PLAYER_GAMEING status; } break; case PlayerNet.PLAYER_STATE.E_PLAYER_GAMEING: //AFCSectionManager.Instance.SetGameState(AFCSectionManager.UI_SECTION_STATE.UISS_GAMEING); break; default: break; } } else { PlayerNet xPlayerNet = new PlayerNet(); xPlayerNet.mxNet.RegisteredConnectDelegation(OnConfigConnect); SetFocusNet(xPlayerNet); } }
public static void Init() { try { SetServerIP(); Console.WriteLine("测试方案:"); Console.WriteLine("1:(代理)Proxy-Bots 并发压测测试."); Console.WriteLine("2:(代理)Proxy-Bots 队列算法测试.(不支持Motd)"); int Method = int.Parse(Console.ReadLine()); ArrayList chat2 = new ArrayList(); List <string> chat = new List <string>(); ServerInfo info = new ServerInfo(ServerIP, ServerPort); if (info.StartGetServerInfo()) { int protocol = info.ProtocolVersion; PrintServerInfo(info, ref protocol); Helper.WriteLogs(info.ServerIP, info.ServerPort, info.GameVersion, Setting.threads); switch (Method) { case 1: chat.AddRange(File.ReadAllText(Setting.chatlist, Encoding.UTF8).Split('\n')); Bot.tBotsTask_a s_a; if (Setting.protocol == 0) { s_a = new Bot.tBotsTask_a(info, Setting.name, Setting.threads, chat, protocol); } else { s_a = new Bot.tBotsTask_a(info, Setting.name, Setting.threads, chat, Setting.protocol); } s_a.newTask(Setting.cooldown); break; case 2: chat.AddRange(File.ReadAllText(Setting.chatlist, Encoding.UTF8).Split('\n')); Bot.tBotsTask_b s_b; if (Setting.protocol == 0) { s_b = new Bot.tBotsTask_b(info, Setting.name, Setting.threads, chat2, protocol); } else { s_b = new Bot.tBotsTask_b(info, Setting.name, Setting.threads, chat2, Setting.protocol); } s_b.newTask(Setting.cooldown); break; default: Console.WriteLine("未提供相应方案,请重新选择"); Init(); break; } } else { Console.WriteLine("取服务器信息失败,请重试.."); Program.Exit(); } }catch (Exception e) { Console.WriteLine(e.Message); } }
public void AddServer(ServerInfo s) { }
void OnPingCompleted(object sender, PingCompletedEventArgs e) { ServerInfo infoServer = e.UserState as ServerInfo; PingResult(infoServer, e.Reply); }
private static void UpdateServerQuery(ServerList.Request query, Action <Networking.ServerInfo> onServerFound, Action <Networking.ServerInfo> onServerRulesReceived, bool includeUnresponsive) { IEnumerable <ServerList.Server> servers = includeUnresponsive ? new List <ServerList.Server>(query.Responded).Concat(query.Unresponsive) : query.Responded; foreach (ServerList.Server s in servers) { if (!ValidateServerInfo(s)) { continue; } bool responded = query.Responded.Contains(s); if (responded) { DebugConsole.Log(s.Name + " responded to server query."); } else { DebugConsole.Log(s.Name + " did not respond to server query."); } var serverInfo = new ServerInfo() { ServerName = s.Name, Port = s.ConnectionPort.ToString(), IP = s.Address.ToString(), PlayerCount = s.Players, MaxPlayers = s.MaxPlayers, HasPassword = s.Passworded, RespondedToSteamQuery = responded }; serverInfo.PingChecked = true; serverInfo.Ping = s.Ping; if (responded) { s.FetchRules(); } s.OnReceivedRules += (bool rulesReceived) => { if (!rulesReceived || s.Rules == null) { return; } if (s.Rules.ContainsKey("message")) { serverInfo.ServerMessage = s.Rules["message"]; } if (s.Rules.ContainsKey("version")) { serverInfo.GameVersion = s.Rules["version"]; } if (s.Rules.ContainsKey("contentpackage")) { serverInfo.ContentPackageNames.AddRange(s.Rules["contentpackage"].Split(',')); } if (s.Rules.ContainsKey("contentpackagehash")) { serverInfo.ContentPackageHashes.AddRange(s.Rules["contentpackagehash"].Split(',')); } if (s.Rules.ContainsKey("contentpackageurl")) { serverInfo.ContentPackageWorkshopUrls.AddRange(s.Rules["contentpackageurl"].Split(',')); } if (s.Rules.ContainsKey("usingwhitelist")) { serverInfo.UsingWhiteList = s.Rules["usingwhitelist"] == "True"; } if (s.Rules.ContainsKey("modeselectionmode")) { if (Enum.TryParse(s.Rules["modeselectionmode"], out SelectionMode selectionMode)) { serverInfo.ModeSelectionMode = selectionMode; } } if (s.Rules.ContainsKey("subselectionmode")) { if (Enum.TryParse(s.Rules["subselectionmode"], out SelectionMode selectionMode)) { serverInfo.SubSelectionMode = selectionMode; } } if (s.Rules.ContainsKey("allowspectating")) { serverInfo.AllowSpectating = s.Rules["allowspectating"] == "True"; } if (s.Rules.ContainsKey("allowrespawn")) { serverInfo.AllowRespawn = s.Rules["allowrespawn"] == "True"; } if (s.Rules.ContainsKey("traitors")) { if (Enum.TryParse(s.Rules["traitors"], out YesNoMaybe traitorsEnabled)) { serverInfo.TraitorsEnabled = traitorsEnabled; } } if (serverInfo.ContentPackageNames.Count != serverInfo.ContentPackageHashes.Count || serverInfo.ContentPackageHashes.Count != serverInfo.ContentPackageWorkshopUrls.Count) { //invalid contentpackage info serverInfo.ContentPackageNames.Clear(); serverInfo.ContentPackageHashes.Clear(); } onServerRulesReceived(serverInfo); }; onServerFound(serverInfo); } query.Responded.Clear(); }
public AdminPongEvent(ServerInfo server, uint pongValue) { this.Server = server; this.PongValue = pongValue; }
public void ReloadAll() { ReloadTrunkConfig(); //version_list_d.xml ReadLine(versionList_PC_Path, delegate(int currentLine, string line) { if (line.Contains("ip=")) { string[] ipport = GetKVValue(line).Split(':'); currentServerIP = ipport[0]; //int index = line.IndexOf("ip") + 2; //int endIndex = line.IndexOf("port"); //currentServerIP = line.Substring(index, endIndex - index); //currentServerIP = currentServerIP.Trim().Split('=')[1].Trim(); //currentServerIP = currentServerIP.Substring(1, currentServerIP.Length - 2); return(false); } return(true); }); //server_list.txt serverFloders.Clear(); ReadConfigLine("server_list.txt", delegate(int currentLine, string line) { ServerInfo digoutServer = null; foreach (var item in serverFloders) { ServerInfo si = item.Key; if (si.content.Equals(currentLine)) { digoutServer = si; break; } } Dictionary <ServerInfo, ProxyBool> .KeyCollection keys = serverFloders.Keys; //keys. if (digoutServer != null) { serverFloders.Remove(digoutServer); } digoutServer = new ServerInfo(); digoutServer.content = line; serverFloders.Add(digoutServer, new ProxyBool() { m_bool = currentServerIP.Equals(line.Split('=')[1]) }); return(true); }); ReadConfigLine(LOCK_TOKEN, delegate(int currentLine, string line) { UnityEngine.Debug.Log("LockToken:" + line); LockToken = line; return(true); }); string root = projAbsPath.Replace("/client", ""); //System.Diagnostics.Process.Start(root + "exe/bin");///GMClient.exe 运行起来会出问题. if (!root.Contains("/mobile_dancer/trunk/")) { root = Regex.Replace(root, "/mobile_dancer/.+", "/mobile_dancer/trunk/");//(.+?)+ //root = root.Replace("/mobile_dancer/*/", "/mobile_dancer/trunk/"); UnityEngine.Debug.Log("root: " + root); } gm_path = (root + "exe/bin/"); gm_config_path = (root + "../../mobile_dancer_resource/Resources/ResourcePublish/CDN/SourceFiles/crossplatform/config/"); //client_config.xml ywindow_clientConfigBean.Init(ReadLine, ReadConfigLine, configPath + "client_config.xml", editorPath); }
public Task SaveMedia(Windows.Storage.IStorageFile file, LocalItem localItem, ServerInfo server) { _logger.Debug("Saving media to " + localItem.LocalPath); return(_fileRepository.SaveFile(file, localItem.LocalPath)); }
public void SetSelectServer(int index) { CurSelectIndex = index; CurSelectServerInfo = serverInfoDic[index]; }
public Task SaveMedia(Stream stream, LocalItem localItem, ServerInfo server) { _logger.Debug("Saving media to " + localItem.LocalPath); return(_fileRepository.SaveFile(stream, localItem.LocalPath)); }
protected override void PutBody(ByteBuffer buf) { // 初始密钥 buf.PutChar((char)user.QQKey.LoginInfo_Magic_Token.Length); buf.Put(user.QQKey.LoginInfo_Magic_Token); ByteBuffer DecodedBuf = new ByteBuffer(); DecodedBuf.PutChar((char)0x0001); DecodedBuf.Put(VersionData.QQ09_VERSION_SPEC); DecodedBuf.Put(Client.QQUser.QQKey.LoginInfo_UnknowData2); DecodedBuf.Put(Client.ServerTime); DecodedBuf.Put(Client.ClientIP); DecodedBuf.Position += 4;//00 00 00 00 DecodedBuf.PutChar((char)Client.QQUser.QQKey.LoginInfo_Large_Token.Length); DecodedBuf.Put(Client.QQUser.QQKey.LoginInfo_Large_Token); DecodedBuf.Position += 35;// 00 00 00...... DecodedBuf.Put(VersionData.QQ09_EXE_HASH); DecodedBuf.Put((byte)Utils.Util.Random.Next()); DecodedBuf.Put((byte)Client.QQUser.LoginMode); DecodedBuf.Put(unknown5); ServerInfo si = Client.ServerInfo; si.CSP_dwConnIP = Client.QQUser.ServerIp; DecodedBuf.Put(0x00); DecodedBuf.Put(si.GetBytes()); DecodedBuf.Put(VersionData.QQ09_LOCALE); DecodedBuf.Position += 16; DecodedBuf.PutUShort((ushort)Client.QQUser.QQKey.Answer_Token.Length); DecodedBuf.Put(Client.QQUser.QQKey.Answer_Token); DecodedBuf.PutInt(0x00000007); DecodedBuf.PutInt(0x00000000); DecodedBuf.PutInt(0x08041001); DecodedBuf.Put(0x40);//length of the following DecodedBuf.Put(0x01); DecodedBuf.PutInt(Utils.Util.Random.Next()); //DecodedBuf.PutInt(0x0741E9748); DecodedBuf.PutChar((char)unknown6.Length); DecodedBuf.Put(unknown6); DecodedBuf.Put(unknown5); DecodedBuf.Put(0x00); DecodedBuf.Put(si.GetBytes()); DecodedBuf.Put(0x02); DecodedBuf.PutInt(Utils.Util.Random.Next()); //DecodedBuf.PutInt(0x8BED382E); DecodedBuf.PutChar((char)unknown7.Length); DecodedBuf.Put(unknown7); DecodedBuf.Position += 248;//all zeros DecodedBuf.Put(0x00); byte[] EncodedBuf = crypter.Encrypt(DecodedBuf.ToByteArray(), user.QQKey.LoginInfo_Key1); #if DEBUG Client.LogManager.Log(ToString() + " QQKey.LoginInfo_Key1:" + Utils.Util.ToHex(user.QQKey.LoginInfo_Key1)); Client.LogManager.Log(ToString() + " Uncoded Body:" + Utils.Util.ToHex(DecodedBuf.ToByteArray())); #endif buf.Put(EncodedBuf); #if DEBUG Client.LogManager.Log(ToString() + " Encoded Body:" + Utils.Util.ToHex(buf.ToByteArray())); #endif }
public void Connect(ClientProperties clientProperties, ServerInfo serverInfo) { lingsClient = new LiNGSClient(clientProperties, serverInfo, this); lingsClient.Connect(); }
public static Object ResolveServerPacket(PacketTypes packetType, Object receivedObj) { SocketAsyncEventArgs args = receivedObj as SocketAsyncEventArgs; Object retObj = null; int offset = 0; int vsHeader = BitConverter.ToInt32(args.Buffer, offset); int pSize = BitConverter.ToInt32(args.Buffer, offset += Constant.INT_SIZE); //패킷 사이즈가 템플렛(헤더+사이즈+풋터) 보다 작으면 null 리턴 if (pSize < Constant.INT_SIZE * 3) { return(retObj); } int vsFooter = BitConverter.ToInt32(args.Buffer, pSize - Constant.INT_SIZE); Byte[] packet = new Byte[pSize - Constant.INT_SIZE * 3]; Buffer.BlockCopy(args.Buffer, offset += Constant.INT_SIZE, packet, 0, packet.Length); if (vsHeader == Constant.PACKET_VELOSTEP_HEADER && vsFooter == Constant.PACKET_VELOSTEP_FOOTER && pSize == args.BytesTransferred) { offset = 0; switch (packetType) { case PacketTypes.FindServer: ServerInfo serverInfo = new ServerInfo(); IPEndPoint remoteEndPoint = args.RemoteEndPoint as IPEndPoint; serverInfo.ServerIP = remoteEndPoint.Address.ToString(); serverInfo.UdpPort = remoteEndPoint.Port; serverInfo.TcpPort = BitConverter.ToInt32(packet, offset); serverInfo.ServerName = Encoding.UTF8.GetString(packet, offset += Constant.INT_SIZE, packet.Length - Constant.INT_SIZE); retObj = serverInfo; break; case PacketTypes.Coordinates: break; case PacketTypes.Authentication: ServerExtraInfo serverExtraInfo = null; //결과 bool로 파싱하지만 실제 길이는 INT_SIZE임. if (BitConverter.ToBoolean(packet, offset)) { byte[] macAddr = null; int keybdCount = BitConverter.ToInt32(packet, offset += Constant.INT_SIZE); int macAddrCount = BitConverter.ToInt32(packet, offset += Constant.INT_SIZE); List <KeyboardLayoutTypes> keyboardList = new List <KeyboardLayoutTypes>(); List <Byte[]> macAddrList = new List <Byte[]>(); //키보드 리스트 for (int i = 0; i < keybdCount; i++) { keyboardList.Add((KeyboardLayoutTypes)BitConverter.ToInt32(packet, offset += Constant.INT_SIZE)); } offset += Constant.INT_SIZE; //맥 주소 리스트 for (int i = 0; i < macAddrCount; i++) { macAddr = new byte[6]; Buffer.BlockCopy(packet, offset, macAddr, 0, macAddr.Length); macAddrList.Add(macAddr); offset += macAddr.Length; //for (int j=0; j<6; j++) // System.Diagnostics.Debug.WriteLine(string.Format("{0:X}-", macAddr[j])); } if (keybdCount > 0 || macAddrCount > 0) { serverExtraInfo = new ServerExtraInfo(); serverExtraInfo.KeyboardList = keyboardList; serverExtraInfo.MacAddressList = macAddrList; } } retObj = serverExtraInfo; break; case PacketTypes.RequestImage: break; case PacketTypes.DeviceMode: break; case PacketTypes.VirtualButton: break; case PacketTypes.AutoConnect: break; case PacketTypes.CheckConnection: ServerExtraInfo serverStatusInfo = null; int nRet = BitConverter.ToInt32(packet, offset); if (nRet == 1) { serverStatusInfo = new ServerExtraInfo(); serverStatusInfo.ScreenType = (ScreenTypes)BitConverter.ToInt32(packet, offset += Constant.INT_SIZE); BitConverter.ToInt32(packet, offset += Constant.INT_SIZE); BitConverter.ToInt32(packet, offset += Constant.INT_SIZE); BitConverter.ToInt32(packet, offset += Constant.INT_SIZE); } retObj = serverStatusInfo; break; case PacketTypes.Keyboard: break; } } return(retObj); }
private void UpdateServerList(string masterServerData) { serverList.ClearChildren(); if (masterServerData.Substring(0, 5).ToLowerInvariant() == "error") { DebugConsole.ThrowError("Error while connecting to master server (" + masterServerData + ")!"); return; } string[] lines = masterServerData.Split('\n'); List <ServerInfo> serverInfos = new List <ServerInfo>(); for (int i = 0; i < lines.Length; i++) { string[] arguments = lines[i].Split('|'); if (arguments.Length < 3) { continue; } string ip = arguments[0]; string port = arguments[1]; string serverName = arguments[2]; bool gameStarted = arguments.Length > 3 && arguments[3] == "1"; string currPlayersStr = arguments.Length > 4 ? arguments[4] : ""; string maxPlayersStr = arguments.Length > 5 ? arguments[5] : ""; bool hasPassWord = arguments.Length > 6 && arguments[6] == "1"; string gameVersion = arguments.Length > 7 ? arguments[7] : ""; string contentPackageNames = arguments.Length > 8 ? arguments[8] : ""; string contentPackageHashes = arguments.Length > 9 ? arguments[9] : ""; int.TryParse(currPlayersStr, out int playerCount); int.TryParse(maxPlayersStr, out int maxPlayers); var serverInfo = new ServerInfo() { IP = ip, Port = port, ServerName = serverName, GameStarted = gameStarted, PlayerCount = playerCount, MaxPlayers = maxPlayers, HasPassword = hasPassWord, GameVersion = gameVersion }; foreach (string contentPackageName in contentPackageNames.Split(',')) { if (string.IsNullOrEmpty(contentPackageName)) { continue; } serverInfo.ContentPackageNames.Add(contentPackageName); } foreach (string contentPackageHash in contentPackageHashes.Split(',')) { if (string.IsNullOrEmpty(contentPackageHash)) { continue; } serverInfo.ContentPackageHashes.Add(contentPackageHash); } serverInfos.Add(serverInfo); } serverList.Content.ClearChildren(); if (serverInfos.Count() == 0) { new GUITextBlock(new RectTransform(new Vector2(1.0f, 1.0f), serverList.Content.RectTransform), TextManager.Get("NoServers"), textAlignment: Alignment.Center) { CanBeFocused = false }; return; } foreach (ServerInfo serverInfo in serverInfos) { AddToServerList(serverInfo); } }
private void UpdateServerInfo(ServerInfo serverInfo) { var serverFrame = serverList.Content.FindChild(serverInfo); if (serverFrame == null) { return; } var serverContent = serverFrame.Children.First() as GUILayoutGroup; serverContent.ClearChildren(); var compatibleBox = new GUITickBox(new RectTransform(new Vector2(columnRelativeWidth[0], 0.9f), serverContent.RectTransform, Anchor.Center), label: "") { Enabled = false, Selected = serverInfo.GameVersion == GameMain.Version.ToString() && serverInfo.ContentPackagesMatch(GameMain.SelectedPackages), UserData = "compatible" }; var passwordBox = new GUITickBox(new RectTransform(new Vector2(columnRelativeWidth[1], 0.5f), serverContent.RectTransform, Anchor.Center), label: "", style: "GUIServerListPasswordTickBox") { ToolTip = TextManager.Get((serverInfo.HasPassword) ? "ServerListHasPassword" : "FilterPassword"), Selected = serverInfo.HasPassword, Enabled = false, UserData = "password" }; var serverName = new GUITextBlock(new RectTransform(new Vector2(columnRelativeWidth[2] * 1.1f, 1.0f), serverContent.RectTransform), serverInfo.ServerName, style: "GUIServerListTextBox"); new GUITickBox(new RectTransform(new Vector2(columnRelativeWidth[3], 0.9f), serverContent.RectTransform, Anchor.Center), label: "") { ToolTip = TextManager.Get((serverInfo.GameStarted) ? "ServerListRoundStarted" : "ServerListRoundNotStarted"), Selected = serverInfo.GameStarted, Enabled = false }; var serverPlayers = new GUITextBlock(new RectTransform(new Vector2(columnRelativeWidth[4], 1.0f), serverContent.RectTransform), serverInfo.PlayerCount + "/" + serverInfo.MaxPlayers, style: "GUIServerListTextBox", textAlignment: Alignment.Right) { ToolTip = TextManager.Get("ServerListPlayers") }; var serverPingText = new GUITextBlock(new RectTransform(new Vector2(columnRelativeWidth[5], 1.0f), serverContent.RectTransform), "?", style: "GUIServerListTextBox", textColor: Color.White * 0.5f, textAlignment: Alignment.Right) { ToolTip = TextManager.Get("ServerListPing") }; if (serverInfo.PingChecked) { serverPingText.Text = serverInfo.Ping > -1 ? serverInfo.Ping.ToString() : "?"; serverPingText.TextColor = GetPingTextColor(serverInfo.Ping); } else if (!string.IsNullOrEmpty(serverInfo.IP)) { try { GetServerPing(serverInfo, serverPingText); } catch (NullReferenceException ex) { DebugConsole.ThrowError("Ping is null", ex); } } if (GameMain.Config.UseSteamMatchmaking && serverInfo.RespondedToSteamQuery.HasValue && serverInfo.RespondedToSteamQuery.Value == false) { string toolTip = TextManager.Get("ServerListNoSteamQueryResponse"); compatibleBox.Selected = false; serverContent.Children.ForEach(c => c.ToolTip = toolTip); serverName.TextColor *= 0.8f; serverPlayers.TextColor *= 0.8f; } else if (string.IsNullOrEmpty(serverInfo.GameVersion) || !serverInfo.ContentPackageHashes.Any()) { compatibleBox.Selected = false; new GUITextBlock(new RectTransform(new Vector2(0.8f, 0.8f), compatibleBox.Box.RectTransform, Anchor.Center), " ? ", Color.Yellow * 0.85f, textAlignment: Alignment.Center) { ToolTip = TextManager.Get(string.IsNullOrEmpty(serverInfo.GameVersion) ? "ServerListUnknownVersion" : "ServerListUnknownContentPackage") }; } else if (!compatibleBox.Selected) { string toolTip = ""; if (serverInfo.GameVersion != GameMain.Version.ToString()) { toolTip = TextManager.GetWithVariable("ServerListIncompatibleVersion", "[version]", serverInfo.GameVersion); } for (int i = 0; i < serverInfo.ContentPackageNames.Count; i++) { if (!GameMain.SelectedPackages.Any(cp => cp.MD5hash.Hash == serverInfo.ContentPackageHashes[i])) { if (toolTip != "") { toolTip += "\n"; } toolTip += TextManager.GetWithVariables("ServerListIncompatibleContentPackage", new string[2] { "[contentpackage]", "[hash]" }, new string[2] { serverInfo.ContentPackageNames[i], Md5Hash.GetShortHash(serverInfo.ContentPackageHashes[i]) }); } } serverContent.Children.ForEach(c => c.ToolTip = toolTip); serverName.TextColor *= 0.5f; serverPlayers.TextColor *= 0.5f; } serverContent.Recalculate(); SortList(sortedBy, toggle: false); FilterServers(); }
public async Task AddServer([Remainder] string parameters = null) { ServerInfo serverInfo = null; if (Context.Message.Attachments.Any()) { var attachments = Context.Message.Attachments; // Create a new WebClient instance. WebClient myWebClient = new WebClient(); string file = attachments.ElementAt(0).Filename; string url = attachments.ElementAt(0).Url; // Download the resource and load the bytes into a buffer. byte[] buffer = myWebClient.DownloadData(url); // Encode the buffer into UTF-8 string download = Encoding.UTF8.GetString(buffer); serverInfo = JsonConvert.DeserializeObject <ServerInfo>(download); serverInfo = _serverHandler.AddManualServer(serverInfo, Context.Message.Author.Id); } else { var args = parameters.Split('|'); if (args.Length == 4) { serverInfo = new ServerInfo() { ServerName = args.ElementAtOrDefault(0), ServerIP = args.ElementAtOrDefault(1), Description = args.ElementAtOrDefault(2) }; if (args.ElementAtOrDefault(2).Contains('-')) { var configInfo = args[3].Split('-'); serverInfo.Config = new ServerConfig() { GameType = configInfo[0], GameVersion = configInfo[1] }; } else { serverInfo.Config = new ServerConfig() { ConfigName = args.ElementAtOrDefault(3) }; } serverInfo = _serverHandler.AddManualServer(serverInfo); } else { throw new Exception("Invalid arguments! Expecting: !Add-Server [ServerName] [ServerIP] [Description] [ConfigName or GameType-GameVersion]"); } } await _serverHandler.WriteServerInfo(Context.Client); // Clean up message await Context.Channel.DeleteMessageAsync(Context.Message); await Context.Channel.SendMessageAsync($"Added Server: {serverInfo.ServerName}"); }
public ServersInfoServer(Server prototype) { Endpoint = prototype.Endpoint; Info = prototype.Info; }
internal static ServerInfo FromNetApi32(Win32MethodsNetwork.SERVER_INFO_101 info) { var result = new ServerInfo(info.sv101_name); return(result); }
private void Start() { serverInfo = GameObject.FindObjectOfType <ServerInfo>(); lobbyDots = GameObject.FindObjectOfType <LobbyDots>(); }
public UserInfo GetUserInfo(string apiVersion, string serverType, string organizationName, string environment, string serverUrl, string username, string password) { ServerInfo serverInfo = new ServerInfo(); OrganizationListing organization = new OrganizationListing(); string loginUrl = serverUrl; string documentsUrl = string.Empty; if (serverType == "Cloud" || serverType == "Documents") { var serviceRegistrationList = GetServiceRegistration(apiVersion, environment); if (serviceRegistrationList == null || serviceRegistrationList.Count() == 0) { throw new Exception("Service registration could not be found"); } foreach (var serviceRegistration in serviceRegistrationList) { if (serviceRegistration.ServiceTag == "OpenBots" && serverType == "Cloud") // Authentication { if (serviceRegistration.IsCurrentlyUnderMaintenance) { throw new Exception($"Server {serviceRegistration.Name} is currently undergoing maintenance and cannot be accessed at this time"); } else { loginUrl = serviceRegistration.ServiceBaseUri.ToString(); } } if (serviceRegistration.ServiceTag == "OpenBots.CloudServer" && serverType == "Cloud") // CloudServer Orchestration API { if (serviceRegistration.IsCurrentlyUnderMaintenance) { throw new Exception($"Server {serviceRegistration.Name} is currently undergoing maintenance and cannot be accessed at this time"); } else { serverUrl = serviceRegistration.ServiceBaseUri.ToString(); } } if (serviceRegistration.ServiceTag == "OpenBots.Documents" && serverType == "Documents") { if (serviceRegistration.IsCurrentlyUnderMaintenance) { throw new Exception($"Server {serviceRegistration.Name} is currently undergoing maintenance and cannot be accessed at this time"); } else { documentsUrl = serviceRegistration.ServiceBaseUri.ToString(); } } } } if (string.IsNullOrEmpty(serverUrl)) { throw new Exception("Server URL not found"); } if ((serverType == "Cloud" || serverType == "Local") && (username == null || password == null)) { throw new Exception("Agent credentials not found in registry"); } else if (serverType == "Documents" && (string.IsNullOrEmpty(username) || string.IsNullOrEmpty(password))) { throw new Exception("Credential values are null or an empty string"); } string token = GetAuthToken(apiVersion, serverType, username, password, loginUrl); if (serverType == "Cloud") { serverInfo = GetServerInfo(apiVersion, serverUrl, token); organization = GetOrganization(token, apiVersion, organizationName, serverUrl, serverInfo.MyOrganizations); } var userInfo = new UserInfo() { OrganizationId = organization?.Id.ToString(), OrganizationName = organization?.Name, ServerType = serverType, Token = token, ServerUrl = serverUrl, LoginUrl = loginUrl, DocumentsUrl = documentsUrl, ApiVersion = apiVersion, Environment = environment, UserId = serverInfo?.PersonId.ToString() }; return(userInfo); }
public PatchProgress(ServerInfo siServerInfo, UserPreferences theUserPrefernces) { InitializeComponent(); theServerInfo = siServerInfo; myUserPreferences = theUserPrefernces; }
public EmbyServiceTests() { _plugins = new List <PluginInfo> { new PluginInfo { Name = "EmbyStat plugin" }, new PluginInfo { Name = "Trakt plugin" } }; _authResult = new AuthenticationResult { AccessToken = "123456", ServerId = Guid.NewGuid().ToString(), SessionInfo = new SessionInfoDto(), User = new UserDto { ConnectUserName = "******", Policy = new UserPolicy { IsAdministrator = true } } }; _serverInfo = new ServerInfo { Id = Guid.NewGuid().ToString(), HttpServerPortNumber = 8096, HttpsPortNumber = 8097 }; _drives = new List <Drives> { new Drives() { Id = Guid.NewGuid().ToString(), Name = "C:\\" }, new Drives() { Id = Guid.NewGuid().ToString(), Name = "D:\\" } }; var embyDrives = new List <EmbyStat.Api.EmbyClient.Model.Drive> { new EmbyStat.Api.EmbyClient.Model.Drive() }; var systemInfo = new SystemInfo(); _embyClientMock = new Mock <IEmbyClient>(); _embyClientMock.Setup(x => x.GetInstalledPluginsAsync()).Returns(Task.FromResult(_plugins)); _embyClientMock.Setup(x => x.SetAddressAndUrl(It.IsAny <string>(), It.IsAny <string>())); _embyClientMock.Setup(x => x.GetServerInfoAsync()).Returns(Task.FromResult(systemInfo)); _embyClientMock.Setup(x => x.GetLocalDrivesAsync()).Returns(Task.FromResult(embyDrives)); _embyPluginRepositoryMock = new Mock <IPluginRepository>(); _embyPluginRepositoryMock.Setup(x => x.GetPlugins()).Returns(_plugins); _embyPluginRepositoryMock.Setup(x => x.RemoveAllAndInsertPluginRange(It.IsAny <List <PluginInfo> >())); _configurationRepositoryMock = new Mock <IConfigurationRepository>(); _configurationRepositoryMock.Setup(x => x.GetSingle()).Returns(new Configuration()); _embyServerInfoRepository = new Mock <IServerInfoRepository>(); _embyServerInfoRepository.Setup(x => x.UpdateOrAdd(It.IsAny <ServerInfo>())); _embyServerInfoRepository.Setup(x => x.GetSingle()).Returns(_serverInfo); _embyDriveRepository = new Mock <IDriveRepository>(); _embyDriveRepository.Setup(x => x.ClearAndInsertList(It.IsAny <List <Drives> >())); _embyDriveRepository.Setup(x => x.GetAll()).Returns(_drives); _subject = new EmbyService(_embyClientMock.Object, _embyPluginRepositoryMock.Object, _configurationRepositoryMock.Object, _embyServerInfoRepository.Object, _embyDriveRepository.Object); }
public EvokXJDevice(List <string> strfile, ServerInfo s0) : base(strfile, s0) { }
private void SortList(string sortBy, bool toggle) { GUIButton button = labelHolder.GetChildByUserData(sortBy) as GUIButton; if (button == null) { return; } sortedBy = sortBy; var arrowUp = button.GetChildByUserData("arrowup"); var arrowDown = button.GetChildByUserData("arrowdown"); //disable arrow buttons in other labels foreach (var child in button.Parent.Children) { if (child != button) { child.GetChildByUserData("arrowup").Visible = false; child.GetChildByUserData("arrowdown").Visible = false; } } bool ascending = arrowUp.Visible; if (toggle) { ascending = !ascending; } arrowUp.Visible = ascending; arrowDown.Visible = !ascending; serverList.Content.RectTransform.SortChildren((c1, c2) => { ServerInfo s1 = c1.GUIComponent.UserData as ServerInfo; ServerInfo s2 = c2.GUIComponent.UserData as ServerInfo; if (s1 == null && s2 == null) { return(0); } else if (s1 == null) { return(ascending ? 1 : -1); } else if (s2 == null) { return(ascending ? -1 : 1); } switch (sortBy) { case "ServerListCompatible": bool?s1Compatible = NetworkMember.IsCompatible(GameMain.Version.ToString(), s1.GameVersion); if (!s1.ContentPackageHashes.Any()) { s1Compatible = null; } if (s1Compatible.HasValue) { s1Compatible = s1Compatible.Value && s1.ContentPackagesMatch(GameMain.SelectedPackages); } ; bool?s2Compatible = NetworkMember.IsCompatible(GameMain.Version.ToString(), s2.GameVersion); if (!s2.ContentPackageHashes.Any()) { s2Compatible = null; } if (s2Compatible.HasValue) { s2Compatible = s2Compatible.Value && s2.ContentPackagesMatch(GameMain.SelectedPackages); } ; //convert to int to make sorting easier //1 Compatible //0 Unknown //-1 Incompatible int s1CompatibleInt = s1Compatible.HasValue ? (s1Compatible.Value ? 1 : -1) : 0; int s2CompatibleInt = s2Compatible.HasValue ? (s2Compatible.Value ? 1 : -1) : 0; return(s2CompatibleInt.CompareTo(s1CompatibleInt) * (ascending ? 1 : -1)); case "ServerListHasPassword": if (s1.HasPassword == s2.HasPassword) { return(0); } return((s1.HasPassword ? 1 : -1) * (ascending ? 1 : -1)); case "ServerListName": return(string.Compare(s1.ServerName, s2.ServerName) * (ascending ? 1 : -1)); case "ServerListRoundStarted": if (s1.GameStarted == s2.GameStarted) { return(0); } return((s1.GameStarted ? 1 : -1) * (ascending ? 1 : -1)); case "ServerListPlayers": return(s2.PlayerCount.CompareTo(s1.PlayerCount) * (ascending ? 1 : -1)); case "ServerListPing": return(s2.Ping.CompareTo(s1.Ping) * (ascending ? 1 : -1)); default: return(0); } }); }