internal SmbTransport(UniAddress address, int port, IPAddress localAddr, int localPort ) { Server = new ServerData(this); this.Address = address; this.Port = port; this.LocalAddr = localAddr; this.LocalPort = localPort; }
private void addServerItem(ServerData server) { ListViewItem newItem = new ListViewItem(server.name); serverImageList.Images.Add( JpegImage.GetThumbnail(JpegImage.LoadFromBytes(server.pictureBytes), serverImageList.ImageSize)); newItem.ImageIndex = serverImageList.Images.Count - 1; itemsAndServerData[newItem] = server; this.Items.Add(newItem); }
public static void SendPlayerData() { ByteBuffer buffer = new ByteBuffer(); buffer.WriteLong((long)PacketType.PlayerData); ServerData sd = NetworkManager.FetchServerData(currentIP, currentPort); buffer.WriteString(sd.UID); buffer.WriteString(sd.Name); SendData(buffer.ToArray()); }
//Why commented this - explained in the article //public ServerData PostServerData(ServerData serverData) //{ // return serverDataRepository.Add(serverData); //} public HttpResponseMessage PostServerData(ServerData serverData) { serverData = ServerDataRepository.Add(serverData); var response = Request.CreateResponse(HttpStatusCode.Created, serverData); var uri = Url.Link("DefaultApi", new { id = serverData.Id }); response.Headers.Location = new Uri(uri); return(response); }
public ServerData Add(ServerData serverData) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { session.Save(serverData); transaction.Commit(); } return serverData; } }
public void Add(ServerData server) { serverToAdd = server; if (this.InvokeRequired) { this.Invoke(addInvokeHandler, server); } else { InvokedAdd(server); } }
public void Process(ServerData serverState) { Bombing bombing = new Bombing(serverState); foreach (Fleet fleet in serverState.IterateAllFleets()) { if (fleet.InOrbit != null && fleet.HasBombers) { bombing.Bomb(fleet, serverState.AllStars[fleet.InOrbit.Name]); } } }
public void CreationNextButton() { SoundManager.Play(SingletonSOSounds.Instance.Click01); HideAllPanels(); pendingCreationPanel.SetActive(true); nextCreationButton.SetActive(false); goBackCreationButton.SetActive(false); pleaseWaitCreationText.text = "Please wait.."; ServerData.TryCreateAccount(chosenUsernameInput.text, chosenPasswordInput.text, emailAddressInput.text, AccountCreationSuccess, AccountCreationError); }
public ServerData Add(ServerData serverData) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(serverData); transaction.Commit(); } return(serverData); } }
public bool SetSelected(ServerData server) { CharacterHost charToIP = FindServer(server); if (charToIP != null) { CurrentSelected = charToIP; return(true); } CurrentSelected = null; return(false); }
public async Task SetMovieCount([Summary("The number of movies to be selected.")] int number = 5) { try { SocketGuildUser user = Context.User as SocketGuildUser; ServerData sd = ServerData.Get(Context.Guild); var role = (user as IGuildUser).Guild.Roles.FirstOrDefault(x => x.Name == sd.AdminRoleName); if (user.Roles.Contains(role)) { try { //int count = -1; //Input sanitization and filtering if (number.Equals("")) { Console.WriteLine("Empty argument."); return; } //Empty argument if (number < 2) //Valid range check { Console.WriteLine("Can't be less than 2."); await Context.Channel.SendMessageAsync($"{Context.User.Username}, vote count can't be less than 2."); return; } if (number < sd.UserVoteLimit) { await Context.Channel.SendMessageAsync($"{Context.User.Username}, the number of movie options on a vote cannot be smaller than the number of movies a user is allowed to vote for!."); return; } //Set the limit in the server file. sd.MovieVoteOptionCount = number; await Context.Channel.SendMessageAsync($"{Context.User.Username}, from now on {number} movies will show up for votes."); } catch (Exception ex) { Console.WriteLine(ex.Message + "\n" + ex.StackTrace); } } else { await Context.Channel.SendMessageAsync($"{Context.User.Username}, you need to have the role {sd.AdminRoleName} to use this command."); } } catch (DataException ex) { await Program.Instance.Log(new LogMessage(LogSeverity.Error, "Server Settings", "A data related exception was raised.", ex)); await Context.Channel.SendMessageAsync("I'm not really sure what happened but something went wrong while executing that command, sorry. :flushed:"); } catch (Exception ex) { await Program.Instance.Log(new LogMessage(LogSeverity.Error, "Server Settings", "A general exception was raised.", ex)); await Context.Channel.SendMessageAsync("I'm not really sure what happened but something went wrong while executing that command, sorry. :flushed:"); } }
public async Task <ServerData> Get() { ServerData Data = new ServerData(); Data.ClientMessage = ""; // client Data.ServerMessage = "Response from Backup Server"; Data.ActionMessage = "Normal Action"; await Task.Delay(0); return(Data); }
public ResponseCommand Execute(object data, User user, ILoggerService logger) { var response = new ResponseCommand(); if (!(data is Login)) { response.Data = 5; response.TypeData = "error"; } var model = (Login)data; using (var db = new ServerData()) { //проверка на наличие нужного логина. if (db.Users.Any(u => u.Nickname.ToLower() == model.Nickname.ToLower())) { var userAuth = db.Users.Single(u => u.Nickname == model.Nickname); //Проверка хэша пароля var hashPassword = model.Password.GetSHA256(); if (hashPassword.VerifySHA256(userAuth.PasswordHash)) { //Пользователь авторизован. var resp = new LoginResponse(); resp.Token = model.ResetAuth ? (hashPassword + new Random().Next(1, 10000)).GetSHA256() : userAuth.Token; resp.UserId = userAuth.UserId; response.Data = resp; response.TypeData = "log"; return(response); } else { response.Data = 7; response.TypeData = "error"; return(response); } } else { response.Data = 6; response.TypeData = "error"; return(response); } } }
public void AddAddress(ServerData server) { knownServers.Add(new KnownServer { BuildServer = server.IpAddress.ToString(), Ip = server.IpAddress.ToString(), OldIp = server.OlderKnownIp, Port = server.Port, Username = server.Username, Fingerprint = server.Fingerprint, Platform = server.Platform, }); }
private void ReceiveCallback(IAsyncResult ar) { try { int bytesRead = SourceQuerySocket.EndReceive(ar); if (bytesRead > 0) { ReadIndex = 4; switch (ReadByte(ref BUFFER)) { case Recieve_INFO: SrvData = new ServerData(ReadByte(ref BUFFER), ReadString(ref BUFFER), ReadString(ref BUFFER), ReadString(ref BUFFER), ReadString(ref BUFFER), ReadShort(ref BUFFER), ReadByte(ref BUFFER), ReadByte(ref BUFFER), ReadByte(ref BUFFER), ReadByte(ref BUFFER), ReadByte(ref BUFFER), (ReadByte(ref BUFFER) == 1), (ReadByte(ref BUFFER) == 1)); SendChallenge(Send_PLAYER); break; case Recieve_CHALLENGE: SrvData.Ping = (int)((timeGetTime() - Ping) / 2); switch (ChallengePacket) { case Send_PLAYER: int Challenge = ReadInt(ref BUFFER); SendPacket(SourceQuerySocket, Send_PLAYER, BitConverter.GetBytes(Challenge), 4); break; } break; case Recieve_PLAYER: { string Name; long Score; float OnlineTime; for (int i = 0, Count = ReadByte(ref BUFFER); i < Count; i++) { ReadByte(ref BUFFER); Name = ReadString(ref BUFFER); Score = ReadLong(ref BUFFER); OnlineTime = ReadFloat(ref BUFFER); if (Name != string.Empty) { PlayersOnline.Add(new Players(Name, Score, OnlineTime)); } } SrvData.Players = (byte)PlayersOnline.Count; PlayersOnline.Clear(); SourceQuerySocket.Shutdown(SocketShutdown.Both); SourceQuerySocket.Close(); ServerListCallbackRemote(SrvData); } break; } } } catch { } }
private ServerData GetServerData(ServerName serverName) { ServerData data; if (!persistenceManager.Entity.ServerDatas.TryGetValue(serverName.Normalized, out data)) { data = new ServerData(); persistenceManager.Entity.ServerDatas.Add(serverName.Normalized, data); persistenceManager.FlagAsChanged(); } return(data); }
public static ServerData[] GetChannels(SyncReceiver sync) { var packet = sync.CreateIPC(IPC.ChannelList); sync.Send(packet); var recv = sync.ReadIPC(); if (recv == null) { return(null); } int num = recv.ReadInt32(); // im pretty sure there won't be more than 2 147 483 647 servers and/or channels out there // perhaps, change it to byte ..? if (num < 0) { return(null); } var serverList = new ServerData[num]; for (int i = 0; i < num; i++) { int serverId = recv.ReadInt32(); // should be replaced with byte int channelLength = recv.ReadInt32(); // same thing as with server count variable if (serverId < 0) { continue; } serverList[i] = new ServerData(serverId, channelLength); for (int j = 0; j < channelLength; j++) { int id = recv.ReadInt32(); // should be replaced with byte int type = recv.ReadInt32(); // hmmm... channel type is ulong? uint ip = recv.ReadUInt32(); short port = recv.ReadInt16(); // i think port should be ushort short maxPlayers = recv.ReadInt16(); // should be changed to ushort short curPlayers = recv.ReadInt16(); // should be changed to ushort var chd = new ChannelData(id, type, ip, port, maxPlayers, curPlayers); serverList[i].channels[j] = chd; } } return(serverList); }
static void Main(string[] args) { if (args == null) { throw new ArgumentNullException(nameof(args)); } ServerData config = new ServerData(); if (!config.ReadCongigFile()) { Console.WriteLine(@"Файл конфгурации не найден"); Console.WriteLine(@"Создан шаблон файла конфигурации."); Console.WriteLine(@"Имя: " + ServerData.ConfigFileName); config.CreateTemplateCfg(); Console.ReadKey(); return; } Server server = new Server(config); server.Start(); //управление сервером bool exit = false; do { var command = Console.ReadLine(); switch (command?.ToLower()) { case "stop": server.Stop(); break; case "restart": server.Stop(); server.Start(); break; case "start": server.Start(); break; case "exit": exit = true; break; default: Console.WriteLine("Неизвестная команда..."); break; } } while (!exit); }
public Constants.ServerResponse Login(ServerData sdata) { //email //password //computer //lockcomputer //status Constants.ServerResponse ret = Constants.ServerResponse.NoAccount; NameValueCollection nvm = new NameValueCollection(); nvm.Clear(); nvm["email"] = sdata.email; nvm["password"] = sdata.pass; nvm["computer"] = mid; nvm["lockcomputer"] = sdata.lockcomp; MyWeb.MyWeb web = new MyWeb.MyWeb(); string resp = string.Empty; while (resp == string.Empty) { resp = web.PostPage(urllogin, nvm, 0, 0); if (resp == string.Empty) { System.Threading.Thread.Sleep(2000); } } if (resp.Contains("login:noaccount")) { ret = Constants.ServerResponse.NoAccount; } else if (resp.Contains("login:expired")) { ret = Constants.ServerResponse.Expired; } else if (resp.Contains("login:notlocked")) { ret = Constants.ServerResponse.NotLocked; } else if (resp.Contains("login:wrongdevice")) { ret = Constants.ServerResponse.WrongComputer; } else if (resp.Contains("login:valid")) { ret = Constants.ServerResponse.Valid; } else if (resp.Contains("login:justlocked")) { ret = Constants.ServerResponse.JustLocked; } return(ret); }
public ResponseCommand Execute(object data, User user, ILoggerService logger) { var response = new ResponseCommand(); if (!(data is Shared.Models.Messages.Get)) { response.TypeData = "error"; response.Data = 5; } var model = (Shared.Models.Messages.Get)data; using (var db = new ServerData()) { var chats = db.UsersChats.Where(c => c.Owner == user.UserId).OrderBy(c => c.LastMessage).ToList(); var rsp = new GetResponseProxy(); rsp.Chats = new List <GetResponse>(); for (var i = model.Offset; i < model.Count; i++) { var chat = chats[Convert.ToInt32(i)]; var msgn = new GetResponse(); msgn.ChatId = chat.ChatId; if (msgn.ChatId > 0) //Чат с пользователем. { //получаем инфу о пользователе. var usr = db.Users.Single(u => u.UserId == msgn.ChatId); msgn.ChatTitle = usr.FirstName + " " + usr.LastName; //Получем последнее сообщение. var lastMsgId = long.Parse(chat.Messages.Split(",").Last()); var msg = db.Messages.Single(m => m.MsgId == lastMsgId); msgn.LastMessageText = msg.Text; msgn.Time = msg.Time; msgn.CountUnreadMessages = 0; //TODO: добавить проверку на непрочитаныне сообщения. } else { //TODO: работа с беседами } rsp.Chats.Add(msgn); } response.Data = rsp; response.TypeData = "msg.get"; return(response); } }
public override void AnnounceServer(string serverId, ServerContext context) { if (serverId == null) { throw new ArgumentNullException("serverId"); } if (context == null) { throw new ArgumentNullException("context"); } var data = new ServerData { WorkerCount = context.WorkerCount, Queues = context.Queues, StartedAt = DateTime.UtcNow }; _storage.UseConnection(connection => { var tableName = string.Format("[{0}.Server]", _storage.GetSchemaName()); // select by serverId var serverResult = connection.Query <Entities.Server>( string.Format("select * from {0} where Id = @id", tableName), new { id = serverId }).SingleOrDefault(); if (serverResult == null) { // if not found insert connection.Execute( string.Format("insert into {0} (Id, Data, LastHeartbeat) values (@id, @data, @lastHeartbeat)", tableName), new { id = serverId, data = JobHelper.ToJson(data), lastHeartbeat = DateTime.UtcNow }); } else { // if found, update data + heartbeart connection.Execute( string.Format("update {0} set Data = @data, LastHeartbeat = @lastHeartbeat where Id = @id", tableName), new { id = serverId, data = JobHelper.ToJson(data), lastHeartbeat = DateTime.UtcNow }); } }, true); //_connection.Execute( // @";merge [HangFire.Server] with (holdlock) as Target " // + @"using (VALUES (@id, @data, @heartbeat)) as Source (Id, Data, Heartbeat) " // << SOURCE // + @"on Target.Id = Source.Id " // + @"when matched then UPDATE set Data = Source.Data, LastHeartbeat = Source.Heartbeat " // + @"when not matched then INSERT (Id, Data, LastHeartbeat) values (Source.Id, Source.Data, Source.Heartbeat);", // new { id = serverId, data = JobHelper.ToJson(data), heartbeat = DateTime.UtcNow }); }
public override void OnInspectorGUI() { _serverData = target as ServerData; if (GUILayout.Button("Update Interface")) { var controllers = ServerEditor.Get(@"Interface/GetControllers", "Download interface", "Download"); _serverData.Controllers = JArray .Parse(controllers) .Select(ctrl => new ServerData.Controller { Name = (string)ctrl["Name"], Prefix = (string)ctrl["Prefix"], Methods = ctrl["Methods"] .Select(method => new ServerData.Controller.MethodData { Name = (string)method["Name"], Prefix = (string)method["Prefix"], ConnectionMethod = (ServerConnectionMethod) Enum.Parse( typeof(ServerConnectionMethod), (string)method["ConnectionMethod"]), Info = (string)method["Info"], Outputs = (method["Outputs"].Any() ? new string[] {} : new[] { "Success" }) .Concat( method["Outputs"] .Select(s => s.ToString()) .Concat(new[] { "Network Error", "Http Error" })) .ToList(), Parameters = method["Parameters"] .Select(param => new ServerData.Controller.MethodData.ParameterData() { Name = (string)param["Name"], TypeName = (string)param["TypeName"], AssemblyQualifiedName = (string)param["AssemblyQualifiedName"], FormBody = (bool)param["FormBody"] }) .ToList(), }) .ToList(), }) .ToList(); AssetDatabase.SaveAssets(); } DrawDefaultInspector(); }
public ServerData CheckUsage() { //uniqueid //#IREM#1000#/IREM##GREM#1000#/GREM##TREM#0#/TREM#GroupGatorv2.5 NameValueCollection nvm = new NameValueCollection(); nvm.Clear(); nvm["uniqueid"] = mid; MyWeb.MyWeb web = new MyWeb.MyWeb(); string resp = string.Empty; while (!resp.Contains("GroupGatorv2.5")) { resp = web.PostPage(urlchkusg, nvm, 0, 0); if (!resp.Contains("GroupGatorv2.5")) { System.Threading.Thread.Sleep(2000); } } MyUtils.MyUtils utils = new MyUtils.MyUtils(); string i = utils.GetStrBetween(resp, "#IREM#", "#/IREM#"); string g = utils.GetStrBetween(resp, "#GREM#", "#/GREM#"); string t = utils.GetStrBetween(resp, "#TREM#", "#/TREM#"); ServerData sdata = new ServerData(); try { sdata.iremain = Convert.ToInt32(i); } catch (Exception ex) { sdata.iremain = 0; } try { sdata.gremain = Convert.ToInt32(g); } catch (Exception ex) { sdata.gremain = 0; } try { sdata.tremain = Convert.ToInt32(t); } catch (Exception ex) { sdata.tremain = 0; } return(sdata); }
protected override void RunInternal() { Uri universeUri = new Uri(_client.BaseUri, "/api/universe.xml"); Uri alliancesUri = new Uri(_client.BaseUri, "/api/alliances.xml"); Uri playersUri = new Uri(_client.BaseUri, "/api/players.xml"); Uri serverDataUri = new Uri(_client.BaseUri, "/api/serverData.xml"); FileInfo universeFile = new FileInfo(Path.Combine(_baseDir.FullName, _client.BaseUri.Host + "-universe.xml")); FileInfo alliancesFile = new FileInfo(Path.Combine(_baseDir.FullName, _client.BaseUri.Host + "-alliances.xml")); FileInfo playersFile = new FileInfo(Path.Combine(_baseDir.FullName, _client.BaseUri.Host + "-players.xml")); FileInfo serverDataFile = new FileInfo(Path.Combine(_baseDir.FullName, _client.BaseUri.Host + "-serverData.xml")); if (NeedUpdate(universeUri, universeFile, "universe").Sync()) { Logger.Instance.Log(LogLevel.Info, "ApiImporterJob: Updating universe from API"); Update(universeUri, universeFile).Sync(); Universe model = XmlModelSerializer.Deserialize <Universe>(universeFile); ProcessData(model); } if (NeedUpdate(alliancesUri, alliancesFile, "alliances").Sync()) { Logger.Instance.Log(LogLevel.Info, "ApiImporterJob: Updating alliances from API"); Update(alliancesUri, alliancesFile).Sync(); AlliancesContainer model = XmlModelSerializer.Deserialize <AlliancesContainer>(alliancesFile); ProcessData(model); } if (NeedUpdate(playersUri, playersFile, "players").Sync()) { Logger.Instance.Log(LogLevel.Info, "ApiImporterJob: Updating players from API"); Update(playersUri, playersFile).Sync(); PlayersContainer model = XmlModelSerializer.Deserialize <PlayersContainer>(playersFile); ProcessData(model); } if (NeedUpdate(serverDataUri, serverDataFile, "serverData").Sync()) { Logger.Instance.Log(LogLevel.Info, "ApiImporterJob: Updating serverData from API"); Update(serverDataUri, serverDataFile).Sync(); ServerData model = XmlModelSerializer.Deserialize <ServerData>(serverDataFile); ProcessData(model); } }
public ResponseCommand Execute(object data, User user, ILoggerService logger) { var response = new ResponseCommand(); if (!(data is Shared.Models.Messages.GetChat)) { response.Data = 5; response.TypeData = "error"; return(response); } var info = (Shared.Models.Messages.GetChat)data; using (var db = new ServerData()) { var chat = db.UsersChats.SingleOrDefault(c => c.Owner == user.UserId && c.ChatId == info.ChatId); if (chat is null) { response.Data = 9; response.TypeData = "error"; return(response); } var chatMsgs = chat.Messages.Split(",").ToList(); var rsp = new GetChatResponse(); rsp.Messages = new List <Message>(); for (var i = info.Offset; i < info.Count; i++) { var msgId = chatMsgs[Convert.ToInt32(i)]; var msgDb = db.Messages.Single(m => m.MsgId == long.Parse(msgId)); var msg = new Shared.Models.Messages.Message(); msg.Text = msgDb.Text; msg.Time = msgDb.Time; msg.ChatId = msgDb.ChatId; msg.MsgId = msgDb.MsgId; msg.RecieverId = msgDb.RecieverId; msg.SenderId = msgDb.SenderId; msg.UsersReaded = msgDb.UsersReaded; rsp.Messages.Add(msg); } response.Data = rsp; } response.TypeData = "getChat"; return(response); }
/// <summary> /// try to parse a raw ServerData to friendly ChatMessage /// </summary> /// <param name="message">raw message</param> /// <param name="chatMsg">parsed chat message</param> /// <returns>success:true, else:false</returns> public static bool TryParse(ServerData message, out ChatMessage chatMsg) { try { chatMsg = MsgBuilder.Parse(message); return(true); } catch (Exception e) { chatMsg = null; return(false); } }
public void DatabasesTest() { ServerData target = new ServerData(); DatabaseList expected = new DatabaseList(); expected.Add(new DatabaseItem()); DatabaseList actual; target.Databases = expected; actual = target.Databases; Assert.AreEqual(expected, actual); Assert.AreEqual(1, actual.Count); }
public static bool SaveServerData(ServerData serverData) { try { SaveData(ConfigValues.ServerDataFile, serverData); return(true); } catch (Exception e) { Logger.LogError("Failed to save Server Data.", e); return(false); } }
public void Add(ServerData serverData) { var request = new RestRequest("api/serverdata", Method.POST); request.AddBody(serverData); var response = client.Execute <ServerData>(request); if (response.StatusCode != HttpStatusCode.Created) { throw new Exception(response.ErrorMessage); } }
public EventSubscription(string sid, DvService service, ICollection <string> callbackURLs, DateTime expiration, string httpVersion, bool subscriberSupportsUPnP11, EndpointConfiguration config, ServerData serverData) { _sid = sid; _service = service; _callbackURLs = callbackURLs; _expiration = expiration; _subscriberHTTPVersion = httpVersion; _subscriberSupportsUPnP11 = subscriberSupportsUPnP11; _config = config; _serverData = serverData; _notificationTimer = new Timer(OnNotificationTimerElapsed, null, Timeout.Infinite, Timeout.Infinite); }
public async Task <ServerData> Get() { ServerData Data = await GetBackupData(); if (Data == null) { Data = new ServerData(); Data.ClientMessage = ""; // client Data.ServerMessage = "Fail to Get Data from Passthrough Server"; Data.ActionMessage = "Passthrough Action"; } return(Data); }
public void ConvertMultiDbDataToTextConfigTest() { DbOverrideSequence sequenceA = new DbOverrideSequence(); sequenceA.Add("1", new DatabaseOverride("default1", "override1")); sequenceA.Add("2", new DatabaseOverride("default2", "override2")); sequenceA.Add("0", new DatabaseOverride("default0", "override0")); DatabaseOverride ovrX = new DatabaseOverride("defaultX", "overrideX"); DatabaseOverride ovrY = new DatabaseOverride("defaultY", "overrideY"); List <DatabaseOverride> lstOvr = new List <DatabaseOverride>(); lstOvr.Add(ovrX); lstOvr.Add(ovrY); sequenceA.Add("M", lstOvr); ServerData serverA = new ServerData(); serverA.OverrideSequence = sequenceA; serverA.ServerName = "ServerA"; DbOverrideSequence sequenceB = new DbOverrideSequence(); sequenceB.Add("6", new DatabaseOverride("default6", "override6")); sequenceB.Add("7", new DatabaseOverride("default7", "override7")); sequenceB.Add("5", new DatabaseOverride("default5", "override5")); ServerData serverB = new ServerData(); serverB.OverrideSequence = sequenceB; serverB.ServerName = "ServerB"; MultiDbData cfg = new MultiDbData(); cfg.Add(serverA); cfg.Add(serverB); string expected = @"ServerA:default1,override1 ServerA:default2,override2 ServerA:default0,override0 ServerA:defaultX,overrideX;defaultY,overrideY ServerB:default6,override6 ServerB:default7,override7 ServerB:default5,override5 "; string actual; actual = MultiDbHelper.ConvertMultiDbDataToTextConfig(cfg); Assert.AreEqual(expected, actual); }
internal override ReplyData HandleRequest(RequestData requestData, int requestNum) { Random random = new Random(); int delayValue = random.Next(minDelay, maxDelay); Thread.Sleep(delayValue); while (freezed || requestNum < currentReq) { Thread.Sleep(200); } Utils.Print("[*] SMRServer: Handle Request."); if (CheckOldMsg(requestData)) { return(new DiscardedMsgReply(requestData.RequestId)); } if (CheckOldView(requestData)) { return(new ViewProposal(viewManager.GetView(), ServerData)); } holdbackQueue.Add(requestData.RequestId, requestData); Utils.Print(" [*] SMR Server: Added to Holdback Queue.", verbose: Verbose); Utils.Print($" [*] SMR Server: Request ID: {requestData.RequestId}.", verbose: Verbose); View view = viewManager.GetView(); string leaderUId = view.ManagerUId; ServerData leaderData = view.Find(leaderUId); if (leaderData.Equals(ServerData)) // As the View Leader. { int requestId = requestData.RequestId; Utils.Print($" [*] SMR Server Sequencer: Request ID: {requestId}.", verbose: Verbose); //If the message received is not the following message of the previously received //from the same Client, the message is added to the hold back list, to ensure FIFO //ordering. int lastClientMessageId = mIdTable[requestData.ClientId]; Utils.Print($" [*] SMR Server Sequencer: Last Client Request ID: {lastClientMessageId}.", verbose: Verbose); if (requestId > lastClientMessageId + 1) { holdbackQueueSequencer.Add(requestId, requestData); return(null); } SendTotalOrder(requestData.ClientId, requestId); return(null); } CheckDeliveryQueue(); return(null); }
private async Task PermCheck(SocketGuildUser user) { int perm = 0; if (ServerData.HasPermissionLevel(user, ServerData.PermissionLevel.USER)) { perm++; if (ServerData.HasPermissionLevel(user, ServerData.PermissionLevel.TRUSTED)) { perm++; if (ServerData.HasPermissionLevel(user, ServerData.PermissionLevel.MODERATOR)) { perm++; if (ServerData.HasPermissionLevel(user, ServerData.PermissionLevel.ADMIN)) { perm++; } } } } BasicEmbed be; switch (perm) { case 1: be = new BasicEmbed($"Permission Level For User {BotUtils.GetFullUsername(user)}", "User", "Permission Level:", BotUtils.Kamtro, user.GetAvatarUrl()); break; case 2: be = new BasicEmbed($"Permission Level For User {BotUtils.GetFullUsername(user)}", "Trusted", "Permission Level:", BotUtils.Green, user.GetAvatarUrl()); break; case 3: be = new BasicEmbed($"Permission Level For User {BotUtils.GetFullUsername(user)}", "Moderator", "Permission Level:", BotUtils.Blue, user.GetAvatarUrl()); break; case 4: be = new BasicEmbed($"Permission Level For User {BotUtils.GetFullUsername(user)}", "Admin", "Permission Level:", BotUtils.Purple, user.GetAvatarUrl()); break; default: be = new BasicEmbed($"Permission Level For User {BotUtils.GetFullUsername(user)}", "Muted", "Permission Level:", BotUtils.Grey, user.GetAvatarUrl()); break; } await be.Display(Context.Channel); }
//public dynamic Post() //[FromBody]string userid, [FromBody]string password) //string userid, string password) public dynamic Getlogin(string userid, string pswd) { //_db.Configuration.LazyLoadingEnabled = false; // prevents getting 'include' var ret = _db.users.Where(q => q.fname == userid && q.fpassword == pswd && q.factive == "Y"); // active if (ret.Count() > 0) { var usr = ret.FirstOrDefault(); var retuser = new { usr.fname, // = usr.ffirst, // + ' ' + ret.FirstOrDefault().flast, usr.fuserid, //usr.fisadmin, //_db.companies.FirstOrDefault().freportserver }; // Return username, branch, branch name, fuid, fisadmin // Return Main Menu Structure var ret2 = from grp in _db.groups_access.Where(t => t.fgroupid == usr.fgroupid) from prog in _db.programs.Where(t => t.fprogid == grp.fprogid && t.fviewname != null) from cd in _db.code_detail.Where(t => t.fgroupid == "MM" && t.fid == prog.fgrouptype) orderby prog.fgrouptype, prog.fsequence select new { id = prog.fviewname, fwindow = prog.fwindow, groupname = cd.fdescription, text = prog.fname, seq = prog.fsequence }; return new { success = true, data = ret2, user = retuser }; } return new { success = false }; }
public bool Update(ServerData serverData) { using (var session = NHibernateHelper.OpenSession()) { using (var transaction = session.BeginTransaction()) { session.SaveOrUpdate(serverData); try { transaction.Commit(); } catch (Exception) { throw; } } return true; } }
public void DisconnectCleanUp(bool internetAccess = false) { // Hide the server (change the fields things like "closed" this.HideServerFromMasterServer(internetAccess); // Clear the ServerData this.ServerData = new ServerData(); // Then disconnect because we need to have the server running to `MasterServer.RegisterHost` when we hide Network.Disconnect(); // No longer registered this.ServerRegistered = false; }
public void HideServerFromMasterServer(bool internetAccess = false) { // This basically does UnregisterHost() since `MasterServer.UnregisterHost();` doesn't work if(Network.isServer && !this.ServerData.isLan) { if(internetAccess) { ServerData closedServerData = new ServerData(); closedServerData.status = ServerData.ServerStatusCode.Closed; closedServerData.serverName = "nojoin"; closedServerData.description = "closed"; closedServerData.playerLimit = -1; closedServerData.map = "nomap"; closedServerData.gameType = "nogametype"; MasterServer.RegisterHost(this.uniqueGameName, closedServerData.serverName, closedServerData.ToSepString()); // Then unregister the host, but this doesn't work... MasterServer.UnregisterHost(); } } }
/// <summary> /// Creates a new <see cref="GENAServerController"/>. /// </summary> /// <param name="serverData">Global UPnP server data structure.</param> public GENAServerController(ServerData serverData) { _serverData = serverData; _expirationTimer = new Timer(OnExpirationTimerElapsed, null, TIMER_INTERVAL, TIMER_INTERVAL); _notificationTimer = new Timer(OnNotificationTimerElapsed, null, Timeout.Infinite, Timeout.Infinite); }
public AliveMessageSender(ServerData serverData) { _serverData = serverData; }
void StartServer(bool isInternetAvailable, string serverName, bool isLan, string serverPassword, int serverMaxPlayers, string serverDescription, string serverMap, string serverGameType) { // `isInternetAvailable`: // Only useful if you are trying to make an online game // Whether we can use nat punchthrough // Whether we can register on the master server serverMaxPlayers = Mathf.Clamp(serverMaxPlayers, 1, 32); // We will use this later on when the game starts this.gameManager.SelectedLevel = serverMap; Network.InitializeSecurity(); Network.incomingPassword = serverPassword; Network.maxConnections = serverMaxPlayers; bool useNat = !isLan && !Network.HavePublicAddress() && isInternetAvailable; NetworkConnectionError? error = null; int portIndex = 0; int port = this.serverPorts[portIndex]; while((error == null || error != NetworkConnectionError.NoError) && portIndex < this.serverPorts.Length) { port = this.serverPorts[portIndex]; error = Network.InitializeServer(serverMaxPlayers-1, port, useNat); this.serverPort = port; portIndex++; } // Only register the server if we had no problem setting it up if(error == NetworkConnectionError.NoError) { Debug.Log("Running Server on Port: " + this.serverPort); ServerData sData = new ServerData(); sData.ip = Network.player.ipAddress; sData.port = this.serverPort; sData.useNat = useNat; sData.guid = Network.player.guid; sData.serverName = serverName; sData.description = serverDescription; sData.status = ServerData.ServerStatusCode.Open; sData.isLan = isLan; sData.pwProtected = serverPassword != ""; sData.connectedPlayers = 1 + Network.connections.Length; // Add 1 for ourselves sData.playerLimit = serverMaxPlayers; sData.map = serverMap; sData.gameType = serverGameType; this.ServerData = sData; if(!isLan) { if(isInternetAvailable) MasterServer.RegisterHost(this.uniqueGameName, WWW.EscapeURL(serverName), this.ServerData.ToSepString()); else { // You probably won't get here because you check for internet higher in the stack // TODO: Tell our host config dialog that you can't do that Debug.Log("Can't Register the server online: No access to the internet"); this.OnServerRegisterAttempt(ServerCreationEventCode.MSRegistrationFailedNoInternet); } } else { // We need to inform the others on LAN about our game this.lanManager.StartListening(); // We have essentially registered the server locally this.OnServerRegisterAttempt(ServerCreationEventCode.RegistrationSucceeded); // Fire Event } } }
private void AddAliveServer(ServerData server) { log.Append(String.Format("Showing {0}:{1}", server.name, server.id)); aliveServers.AddItem(server, server.id); serverListView1.Add(server); }
public ServerSelectedEventArgs(ServerData serverSelected) : base() { this.server = serverSelected; }
private void InvokedAdd(ServerData server) { if (serverDataList.ContainsKey(server.id.ToString())) { serverDataList[server.id.ToString()] = server; RefreshTree(); } else { serverDataList[serverToAdd.id.ToString()] = server; addServerNode(server); } }
private void FireOnServerSelected(ServerData server) { if (ServerSelected != null) { ServerSelected(this, new ServerSelectedEventArgs(server)); } }
private void addServerNode(ServerData server) { TreeNode newNode = new TreeNode(server.name); TreeNode connectNode = new TreeNode("Connect"); newNode.Nodes.Add(connectNode); nodesAndServerData[connectNode] = server; newNode.Nodes.Add(server.description); TreeNode sensorsNode = new TreeNode("Sensors"); foreach (SensorDefinition sensor in server.sensors) { if (sensor.Range != 255) { sensorsNode.Nodes.Add(sensor.Description); } } newNode.Nodes.Add(sensorsNode); this.Nodes.Add(newNode); }
public EventSubscription(string sid, DvService service, ICollection<string> callbackURLs, DateTime expiration, string httpVersion, bool subscriberSupportsUPnP11, EndpointConfiguration config, ServerData serverData) { _sid = sid; _service = service; _callbackURLs = callbackURLs; _expiration = expiration; _subscriberHTTPVersion = httpVersion; _subscriberSupportsUPnP11 = subscriberSupportsUPnP11; _config = config; _serverData = serverData; _notificationTimer = new Timer(OnNotificationTimerElapsed, null, Timeout.Infinite, Timeout.Infinite); }
public NetworkConnectionErrorResponse Connect(string guid, string pw) { Debug.Log("Trying to Connect"); // Not all errors are immediate as Network.Connect is async // Also check for errors in OnFailedToConnect() NetworkConnectionError connectError; this.ServerData = this.CombinedServerList[guid]; // Use nat punchthrough if(this.ServerData.useNat) connectError = Network.Connect(guid, pw); // Or just use IP, port else connectError = Network.Connect(this.ServerData.ip, this.ServerData.port, pw); // TODO: stuff with the message return this.GetResponseFromNetworkConnectionError(connectError); }
public void UpdateGUIServerList(ServerData[] serverList) { // Update the server browser with the new-found servers if(this.viewReady) this.m_View.View.TriggerEvent("updateServerList", serverList); Debug.Log("Updated serverlist UI: " + serverList.Length); this.NewServerBrowserMessage("Refreshed Server List"); }
public ByeByeMessageSender(ServerData serverData) { _serverData = serverData; }
public SearchResultMessageSender(ServerData serverData, EndpointConfiguration localEndpointConfiguration, IPEndPoint receiverEndPoint) { _serverData = serverData; _localEndpointConfiguration = localEndpointConfiguration; _receiverEndPoint = receiverEndPoint; }
private void ProcessDescriptionMessage(Guid sender_id, TypedMessage message) { log.Append("ProcessDescriptionMessage", String.Format("Description from {0}", sender_id.ToString())); DescriptionMessage description = new DescriptionMessage(message.data); if (aliveServers.GetItem(sender_id) == null) { bool alreadySaved = DatabaseHelper.GetServerSaved(database, sender_id); ServerData serverData = new ServerData(sender_id, description.Name, description.Location, description.Description, description.Sensors, description.PictureBytes); if (alreadySaved == false) { DatabaseHelper.SaveServerConfigData(database, serverData); } AddAliveServer(serverData); } log.Append("ProcessDescriptionMessage", String.Format("Description from {0} at {1}", description.Name, sender_id.ToString())); //MessageBox.Show(String.Format("Description from {0} at {1}", description.Name, sender.ToString())); }
/// <summary> /// Creates a new <see cref="SSDPServerController"/> for a <see cref="UPnPServer"/>. /// </summary> /// <param name="serverData">The UPnP server configuration data structure to use.</param> public SSDPServerController(ServerData serverData) { _serverData = serverData; }
public bool Equals(ServerData sData) { // Tried to put these in order of quickest to fail if differnt return sData != null && this.status == sData.status && this.guid == sData.guid && this.ip == sData.ip && this.port == sData.port && this.connectedPlayers == sData.connectedPlayers && this.useNat == sData.useNat && this.pwProtected == sData.pwProtected && this.serverName == sData.serverName && this.description == sData.description && this.playerLimit == sData.playerLimit && this.map == sData.map && this.gameType == sData.gameType && this.isLan == sData.isLan; }
public void Remove(ServerData server) { this.Remove(server.id); }
/// <summary> /// Creates the UPnP description document for this root device and all embedded devices. /// </summary> /// <param name="serverData">Current server data structure.</param> /// <param name="config">UPnP endpoint which will be used to create the endpoint specific information. The comment of /// <see cref="DeviceTreeURLGenerator"/> describes why URLs must be adapted for each UPnP endpoint.</param> /// <param name="culture">The culture to localize strings and URLs of the returned description document.</param> /// <returns>UPnP device description document for this root device and all embedded devices.</returns> public string BuildRootDeviceDescription(ServerData serverData, EndpointConfiguration config, CultureInfo culture) { StringBuilder result = new StringBuilder(10000); using (StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(result, UPnPConsts.UTF8_NO_BOM)) using (XmlWriter writer = XmlWriter.Create(stringWriter, UPnPConfiguration.DEFAULT_XML_WRITER_SETTINGS)) { GenerateDescriptionDlgt dgh = DescriptionGenerateHook; writer.WriteStartDocument(); writer.WriteStartElement(string.Empty, "root", UPnPConsts.NS_DEVICE_DESCRIPTION); if (dgh != null) dgh(writer, this, GenerationPosition.RootDeviceStart, config, culture); writer.WriteAttributeString("configId", config.ConfigId.ToString()); writer.WriteStartElement("specVersion"); writer.WriteElementString("major", UPnPConsts.UPNP_VERSION_MAJOR.ToString()); writer.WriteElementString("minor", UPnPConsts.UPNP_VERSION_MINOR.ToString()); writer.WriteEndElement(); // specVersion AddDeviceDescriptionsRecursive(writer, config, culture); if (dgh != null) dgh(writer, this, GenerationPosition.RootDeviceEnd, config, culture); writer.WriteEndElement(); // root writer.Close(); } return result.ToString(); }
public UpdateMessageSender(ServerData serverData, int lastBootId, int nextBootId) { _serverData = serverData; _lastBootId = lastBootId; _nextBootId = nextBootId; }
private void InvokedAdd(ServerData server) { if (serverDataList.ContainsKey(server.id.ToString())) { serverDataList[server.id.ToString()] = serverToAdd; RefreshList(); } else { serverDataList[server.id.ToString()] = serverToAdd; addServerItem(server); } }
/// <summary> /// Switch the functionality of the practiceActivity /// </summary> private void SwitchMode(ServerData.TaskType newMode) { if (newMode == currentMode) return; // Hide the current mode if needed if (currentMode != ServerData.TaskType.None) { RunOnUiThread(() => { modeLayouts[currentMode].Visibility = ViewStates.Gone; }); } currentMode = newMode; string modeName; modeNames.TryGetByFirst(newMode, out modeName); Title = modeName; switch (newMode) { case ServerData.TaskType.Pacing: ChangeBpm(0); metronBuffSize = AudioTrack.GetMinBufferSize(44100, ChannelOut.Mono, Encoding.Pcm16bit); metronAudioBuffer = new short[metronBuffSize]; break; case ServerData.TaskType.Loudness: break; } }
/// <summary> /// Creates the UPnP service description for this service. /// </summary> /// <param name="config">Endpoint configuration for that the SCPD document should be created.</param> /// <param name="serverData">Global server data structure.</param> /// <returns>UPnP service description document.</returns> public string BuildSCPDDocument(EndpointConfiguration config, ServerData serverData) { StringBuilder result = new StringBuilder(10000); using (StringWriterWithEncoding stringWriter = new StringWriterWithEncoding(result, UPnPConsts.UTF8_NO_BOM)) using (XmlWriter writer = XmlWriter.Create(stringWriter, UPnPConfiguration.DEFAULT_XML_WRITER_SETTINGS)) { writer.WriteStartDocument(); writer.WriteStartElement(string.Empty, "scpd", UPnPConsts.NS_SERVICE_DESCRIPTION); // Datatype schema namespaces uint ct = 0; HashSet<string> schemaURIs = new HashSet<string>(); foreach (DvStateVariable stateVariable in _stateVariables.Values) { DvDataType dataType = stateVariable.DataType; if (dataType is DvExtendedDataType) { string schemaURI = ((DvExtendedDataType) dataType).SchemaURI; if (schemaURIs.Contains(schemaURI)) continue; schemaURIs.Add(schemaURI); writer.WriteAttributeString("xmlns", "dt" + ct++, null, schemaURI); } } writer.WriteAttributeString("configId", config.ConfigId.ToString()); writer.WriteStartElement("specVersion"); writer.WriteElementString("major", UPnPConsts.UPNP_VERSION_MAJOR.ToString()); writer.WriteElementString("minor", UPnPConsts.UPNP_VERSION_MINOR.ToString()); writer.WriteEndElement(); // specVersion ICollection<DvAction> actions = _actions.Values; if (actions.Count > 0) { writer.WriteStartElement("actionList"); foreach (DvAction action in actions) action.AddSCPDDescriptionForAction(writer); writer.WriteEndElement(); // actionList } writer.WriteStartElement("serviceStateTable"); foreach (DvStateVariable stateVariable in _stateVariables.Values) stateVariable.AddSCPDDescriptionForStateVariable(writer); writer.WriteEndElement(); // serviceStateTable writer.WriteEndElement(); // scpd writer.WriteEndDocument(); writer.Close(); } return result.ToString(); }