コード例 #1
0
 private void Room_PlayerRemoved(Player obj)
 {
     _players[obj.Id].Destroy();
     _players.Remove(obj.Id);
     _dialogs.RemoveClones(obj.Id);
     ServerLogger.LogServer(this, $" Player {obj.Id} removed");
 }
コード例 #2
0
ファイル: Command.cs プロジェクト: steveoh/SolarCalculator
        public void Run()
        {
            var commandName = ToString();

            try
            {
                Debug.Print("Executing\r\n{0}".With(commandName));
                Logger.LogMessage(ServerLogger.msgType.debug, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Executing\r\n{0}".With(commandName));

                Execute();
                Debug.Print("Done Executing\r\n{0}".With(commandName));

                Logger.LogMessage(ServerLogger.msgType.debug, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Done Executing");
            }
            catch (Exception ex)
            {
                Debug.Print("Error processing task: {0}".With(commandName), ex);
                Logger.LogMessage(ServerLogger.msgType.error, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Error running command");
            }
            finally
            {
                Logger = null;
            }
        }
コード例 #3
0
 public static async Task <Dictionary <int, DB_Loot> > SelectAllLootsAsync()
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT * FROM {tb_09};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     var result = new Dictionary <int, DB_Loot>();
                     if (reader.HasRows)
                     {
                         while (await reader.ReadAsyncEx())
                         {
                             var id = reader.GetInt32(0);
                             if (!result.TryGetValue(id, out var entry))
                             {
                                 result[id] = entry = new DB_Loot(id);
                             }
                             entry.Loot.Add((reader.GetInt32(1), reader.GetInt32(2), reader.GetInt32(3), reader.GetFloat(4), reader.GetInt32(5), reader.GetInt32(6)));
                         }
                     }
                     return(result);
                 }
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #4
0
 public static async Task <Character> SelectCharacterAsync(int id)
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT * FROM {tb_02} WHERE id = {id};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     if (reader.HasRows && await reader.ReadAsyncEx())
                     {
                         return(new Character(id, reader.GetInt32(1), reader.GetInt16(2), reader.GetInt32(3), reader.GetPony(4), reader.GetProtoBuf <CharData>(8)));
                     }
                 }
             }
         }
         return(null);
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #5
0
 public static async Task <Dictionary <int, (ushort, string)> > SelectAllMessagesAsync()
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT * FROM {tb_10};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     var result = new Dictionary <int, (ushort, string)>();
                     if (reader.HasRows)
                     {
                         while (await reader.ReadAsyncEx())
                         {
                             result[reader.GetInt32(0)] = (reader.GetUInt16(1), reader.GetString(2));
                         }
                     }
                     return(result);
                 }
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #6
0
 public static async Task <Dictionary <int, DB_Creature> > SelectAllCreaturesAsync()
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT * FROM {tb_07};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     var result = new Dictionary <int, DB_Creature>();
                     if (reader.HasRows)
                     {
                         while (await reader.ReadAsyncEx())
                         {
                             var id = reader.GetInt32(0);
                             result[id] = new DB_Creature(id, reader.GetInt32(1), reader.GetByte(2), reader.GetInt32(3), reader.GetFloat(4), reader.GetInt32(5),
                                                          reader.GetUInt16(6), reader.GetFloat(7), reader.GetFloat(8), reader.GetFloat(9), reader.GetFloat(10), reader.GetFloat(11),
                                                          reader.GetFloat(12), reader.GetFloat(13), reader.GetFloat(14), reader.GetFloat(15), reader.GetFloat(16), reader.GetFloat(17));
                         }
                     }
                     return(result);
                 }
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #7
0
 public static async Task <List <DB_WorldObject> > SelectAllMapObjectsAsync(int map)
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT * FROM {tb_03_01} WHERE map = {map};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     var result = new List <DB_WorldObject>();
                     if (reader.HasRows)
                     {
                         while (await reader.ReadAsyncEx())
                         {
                             result.Add(new DB_WorldObject(reader.GetInt32(0), reader.GetUInt16(1), reader.GetInt32(2), reader.GetByte(3), reader.GetByte(4),
                                                           reader.GetVector3(5), reader.GetVector3(8), reader.GetFloat(11), reader.GetInt32(12), reader.GetInt32(13), reader.GetInt32(14)));
                         }
                     }
                     return(result);
                 }
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #8
0
 public static async Task <bool> DeleteBanAsync(int id, IPAddress ip, BanType type)
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 if (ip != null)
                 {
                     command.CommandText = $"DELETE FROM {tb_13} WHERE (ban_user = {id} OR ban_ip = {ip.ToInt64()}) AND ban_type = {(byte)type}";
                 }
                 else
                 {
                     command.CommandText = $"DELETE FROM {tb_13} WHERE ban_user = {id} AND ban_type = {(byte)type}";
                 }
                 return(await command.ExecuteNonQueryAsyncEx() > 0);
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(false);
     }
 }
コード例 #9
0
        public void Init(IServerObjectHelper pSOH)
        {
            try
            {
                _soHelper      = pSOH;
                _serverLog     = new ServerLogger();
                _restSOIHelper = new RestSOIHelper(pSOH);

                try
                {
                    IPropertySet configProps = ServerUtilities.QueryConfigurationProperties(pSOH.ServerObject.ConfigurationName, pSOH.ServerObject.TypeName);
                    _outputDirectory = configProps.GetProperty("outputDir") as string;
                }
                catch (Exception ignore)
                {
                    _outputDirectory = string.Empty;
                }

                _outputDirectory = _outputDirectory.Trim();
                if (string.IsNullOrEmpty(_outputDirectory))
                {
                    _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".init()", 500, "OutputDirectory is empty or missing. Reset to default.");
                    _outputDirectory = "C:\\arcgisserver\\directories\\arcgisoutput";
                }

                _serverLog.LogMessage(ServerLogger.msgType.infoDetailed, _soiName + ".init()", 500, "OutputDirectory is " + _outputDirectory);
                _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".init()", 200, "Initialized " + _soiName + " SOI.");
            }
            catch (Exception e)
            {
                _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".HandleRESTRequest()", 500, "Exception " + e.GetType().Name + " " + e.Message + " " + e.StackTrace);
                throw;
            }
        }
コード例 #10
0
ファイル: Command.cs プロジェクト: steveoh/SolarCalculator
        public void Run()
        {
            var commandName = ToString();

            try
            {
                Debug.Print("Executing\r\n{0}".With(commandName));
                Logger.LogMessage(ServerLogger.msgType.debug, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Executing\r\n{0}".With(commandName));

                Execute();
                Debug.Print("Done Executing\r\n{0}".With(commandName));

                Logger.LogMessage(ServerLogger.msgType.debug, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Done Executing");
            }
            catch (Exception ex)
            {
                Debug.Print("Error processing task: {0}".With(commandName), ex);
                Logger.LogMessage(ServerLogger.msgType.error, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Error running command");
            }
            finally
            {
                Logger = null;
            }
        }
コード例 #11
0
        public override void HandlePacket(NetIncomingMessage msg)
        {
            if (!State.ConnectionLookup.TryGetValue(msg.SenderConnection, out var connection))
            {
                return;
            }

            if (connection.Character != null)
            {
                return;
            }

            var playerEntity = State.World.CreatePlayer(connection, "prt_fild08", Area.CreateAroundPoint(new Position(170, 367), 5));

            connection.Entity             = playerEntity;
            connection.LastKeepAlive      = Time.ElapsedTime;
            connection.Character          = playerEntity.Get <Character>();
            connection.Character.IsActive = false;
            var networkPlayer = playerEntity.Get <Player>();

            networkPlayer.Connection = connection;
            connection.Player        = networkPlayer;

            ServerLogger.Debug($"Player assigned entity {playerEntity}, creating entity at location {connection.Character.Position}.");

            CommandBuilder.InformEnterServer(connection.Character, networkPlayer);
        }
コード例 #12
0
 public static async Task <DB_User> SelectUserAsync(int id)
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT login, phash, access, session FROM {tb_01} WHERE id={id};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     if (reader.HasRows && await reader.ReadAsyncEx())
                     {
                         return(new DB_User(id, reader.GetString(0), reader.GetString(1), reader.GetByte(2), reader.GetNullString(3)));
                     }
                 }
             }
         }
         return(DB_User.Empty);
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(DB_User.Empty);
     }
 }
コード例 #13
0
 public void Stop()
 {
     if (_server == null || !_running)
     {
         return;
     }
     _running                  = false;
     _server.RoomAdded        -= MasterServer_RoomAdded;
     _server.RoomRemoved      -= MasterServer_RoomRemoved;
     _server.PlayerAdded      -= MasterServer_PlayerAdded;
     _server.VerifyPlayer     -= MasterServer_VerifyPlayer;
     _server.PlayerRemoved    -= MasterServer_PlayerRemoved;
     _server.ConstructNetData -= MasterServer_ConstructNetData;
     foreach (var item in GetPlayers())
     {
         item.Destroy();
     }
     m_players.Clear();
     m_users.Clear();
     _server.Shutdown();
     _cfg    = null;
     _server = null;
     Thread.Sleep(100);
     ServerLogger.LogServer(this, $"Stopped");
 }
コード例 #14
0
        /// <summary>
        /// Initializes the database or creates a new one if it does not exists already.
        /// </summary>
        internal bool Load()
        {
            try
            {
                using (AuraContext database = new AuraContext())
                {
                    bool cine = database.Database.CreateIfNotExists();

                    if (cine)
                    {
                        ServerLogger.Database("Creating database...");
                    }
                    else
                    {
                        ServerLogger.Database("Preparing database...");
                    }

                    return(true);
                }
            }
            catch (Exception)
            {
                ServerLogger.Error("Failed to load the database!");
                return(false);
            }
        }
コード例 #15
0
 public static async Task <Character> CreateCharacterAsync(int user, PonyData pony, short level = 1)
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 var data = CharsMgr.CreateCharacterData(pony, level);
                 command.CommandText = $"INSERT INTO {tb_02} (user, level, race, gender, name, vdata, gdata) VALUES (@user, {level}, @race, @gender, @name, @vdata, @gdata);";
                 command.Parameters.AddWithValue("user", user);
                 command.Parameters.AddWithValue("name", pony.Name);
                 command.Parameters.AddWithValue("race", pony.Race);
                 command.Parameters.AddWithValue("gender", pony.Gender);
                 command.Parameters.AddWithValue("vdata", pony.GetBytes());
                 command.Parameters.AddWithValue("gdata", data.GetBytes());
                 if (await command.ExecuteNonQueryAsyncEx() == 1)
                 {
                     return(new Character((int)command.LastInsertedId, user, level, 0, pony, data));
                 }
             }
         }
         return(null);
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #16
0
        /// <summary>
        /// Removes a <see cref="ConnectionCore"/> from the <see cref="Chatroom"/>.
        /// </summary>
        public void Leave(ConnectionCore connection)
        {
            BroadcastChatMessage(connection, BroadcastType.UserLeftChatRoom);

            if (ChatroomUsers.Contains(connection))
            {
                ChatroomUsers.Remove(connection);

                ServerLogger.Chatroom(string.Format("{1}({0}) has disconnected from a chatroom.", connection.ID, connection.ConnectionData.Username));
            }
            else
            {
                ServerLogger.Error(string.Format("{1}({0}) cannot disconnect from a chatroom.", connection.ID, connection.ConnectionData.Username));
            }

            if (Private)
            {
                connection.SendMessage(new RemovePrivateRoomComposer(ID));
            }

            if (ChatroomUsers.Count == 0)
            {
                ServerLogger.Warning(string.Format("Chatroom {0} is empty.", ID.ToString()));
                connection.ServerManager.ChatroomManager.RemoveChatroom(ID);
                ServerLogger.Chatroom(string.Format("Chatroom {0} has been deleted.", ID.ToString()));
            }
        }
コード例 #17
0
 public static async Task <Dictionary <int, DB_Map> > SelectAllMapsAsync()
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT * FROM {tb_03};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     var result = new Dictionary <int, DB_Map>();
                     if (reader.HasRows)
                     {
                         while (await reader.ReadAsyncEx())
                         {
                             var id = reader.GetInt32(0);
                             result[id] = new DB_Map(id, reader.GetString(1), reader.GetByte(2));
                         }
                     }
                     return(result);
                 }
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #18
0
        public override void HandlePacket(NetIncomingMessage msg)
        {
            if (!State.ConnectionLookup.TryGetValue(msg.SenderConnection, out var connection))
            {
                return;
            }

            if (connection.Character == null)
            {
                return;                 //we don't accept the keep-alive packet if they haven't entered the world yet
            }
            var player = connection.Entity.Get <Player>();

            if (player.InActionCooldown())
            {
                ServerLogger.Debug("Player click ignored due to cooldown.");
                return;
            }

            player.AddActionDelay(CooldownActionType.Click);

            player.Target = EcsEntity.Null;

            var x = msg.ReadInt16();
            var y = msg.ReadInt16();

            var target = new Position(x, y);

            if (connection.Character.TryMove(ref connection.Entity, target, 0))
            {
                player.ClearTarget();
            }
        }
コード例 #19
0
        public static string GetCookie(string CookieName)
        {
            string result = "0";

            try
            {
                if (System.Web.HttpContext.Current.Request.Cookies[CookieName] != null)
                {
                    System.Web.HttpCookie IMCookie = System.Web.HttpContext.Current.Request.Cookies[CookieName];
                    // IMCookie.Domain = "";
                    DateTime endDate = DateTime.Parse(EncrypManager.Decode(IMCookie["e"]));
                    // DateTime endDate = DateTime.Parse(IMCookie["e"]);
                    if (endDate > DateTime.Now)
                    {
                        RemoveCookie(CookieName);
                        System.Web.HttpCookie NewDiyCookie = new System.Web.HttpCookie(CookieName);
                        //  NewDiyCookie.Domain = "";
                        NewDiyCookie.Values.Add("obj", IMCookie["obj"]);
                        NewDiyCookie.Values.Add("e", EncrypManager.Encode(DateTime.Now.AddMinutes(LoginExpirationIntervalMinutes).ToString()));//存储到期时间
                        System.Web.HttpContext.Current.Response.AppendCookie(NewDiyCookie);
                        result = EncrypManager.Decode(IMCookie["obj"]);
                        //  result = IMCookie["obj"];
                    }
                }
            }
            catch (Exception ex)
            {
                ServerLogger.Error(ex.Message);
            }
            return(result);
        }
コード例 #20
0
        public static HttpResponseMessage BuildExceptionJsonResponse(HttpStatusCode code, Exception ex)
        {
            string error = ExceptionHelper.GetMessage(ex);

            ServerLogger.Error(error);
            return(BuildJsonResponse(code, null, MessageType.Error, ex.Message));
        }
コード例 #21
0
        public static HttpResponseMessage ErrortoJson(Object obj, string ErrorMessage)
        {
            HttpResponseMessage result = null;

            try
            {
                String str = "";
                if (obj != null)
                {
                    if (obj is String || obj is Char)
                    {
                        str = obj.ToString();
                    }
                    else
                    {
                        str = JsonConvert.SerializeObject(obj);
                    }
                }
                if (!string.IsNullOrEmpty(ErrorMessage))
                {
                    ServerLogger.Error(ErrorMessage);
                }
                result = new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError, Content = new StringContent(str, Encoding.GetEncoding("UTF-8"), "application/json")
                };
            }
            catch (Exception ex)
            {
                result = new HttpResponseMessage {
                    StatusCode = HttpStatusCode.InternalServerError
                };
                ServerLogger.Error(ex.Message);
            }
            return(result);
        }
コード例 #22
0
        public static void HandleMessage(NetIncomingMessage msg)
        {
            var type = (PacketType)msg.ReadByte();

#if DEBUG
            if (State.ConnectionLookup.TryGetValue(msg.SenderConnection, out var connection) && connection.Entity.IsAlive())
            {
                ServerLogger.Debug($"Received message of type: {System.Enum.GetName(typeof(PacketType), type)} from entity {connection.Entity}.");
            }
            else
            {
                ServerLogger.Debug($"Received message of type: {System.Enum.GetName(typeof(PacketType), type)} from entity-less connection.");
            }

            State.LastPacketType = type;
            State.PacketHandlers[(int)type](msg);
#endif
#if !DEBUG
            try
            {
                State.LastPacketType = type;
                State.PacketHandlers[(int)type](msg);
            }
            catch (Exception)
            {
                ServerLogger.LogError($"Error executing packet handler for packet type {type}");
                throw;
            }
#endif
        }
コード例 #23
0
 public void Shutdown()
 {
     _logger.LogMessage(ServerLogger.msgType.infoStandard, "Shutdown", 8000, "Custom message: Shutting down the SOE");
     _serverObjectHelper = null;
     _logger             = null;
     _mosaicCatalog      = null;
 }
コード例 #24
0
        public override void HandlePacket(NetIncomingMessage msg)
        {
            if (!State.ConnectionLookup.TryGetValue(msg.SenderConnection, out var connection))
            {
                return;
            }

            if (connection.Character == null)
            {
                return;
            }

            var player = connection.Entity.Get <Player>();

            if (player.InActionCooldown())
            {
                ServerLogger.Debug("Player sit/stand action ignored due to cooldown.");
                return;
            }
            player.AddActionDelay(CooldownActionType.SitStand);

            var isSitting = msg.ReadBoolean();

            connection.Character.SitStand(ref connection.Entity, isSitting);
        }
コード例 #25
0
ファイル: Command.cs プロジェクト: agrc/api.mapserv.utah.gov
        public void Run()
        {
            var commandName = ToString();
            if (Logger == null)
                Logger = new ServerLogger();

            try
            {
                Debug.Print("Executing\r\n{0}".With(commandName));
#if !DEBUG
                Logger.LogMessage(ServerLogger.msgType.debug, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Executing\r\n{0}".With(commandName));
#endif
                Execute();
                Debug.Print("Done Executing\r\n{0}".With(commandName));

#if !DEBUG
                Logger.LogMessage(ServerLogger.msgType.debug, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "Done Executing");
#endif
            }
            catch (Exception ex)
            {
                Debug.Print("Error processing task: {0}".With(commandName), ex);
#if !DEBUG
                Logger.LogMessage(ServerLogger.msgType.error, "{0}.{1}".With(commandName, "execute"), MessageCode,
                                  "error running command: {0}. Error: {1}".With(commandName, ex.Message));
#endif
                ErrorMessage = ex.Message;
            }
            finally
            {
                Logger = null;
            }
        }
コード例 #26
0
        private void RPC_001(NetMessage arg1, NetMessageInfo arg2)
        {
            MapPlayer player = _server[arg2.Sender.Id];

            if (player == null)
            {
                ServerLogger.LogWarn($"Switch from map {_data.Data01} on portal {_data.Guid} failed: player {arg2.Sender.Id} not found!");
                return;
            }
            if (Vector3.DistanceSquared(_data.Position, player.Object.Position) <= Constants.MaxInteractionDistanceSquared)
            {
                if (player.PrepareForMapSwitch())
                {
                    player.User.Spawn = (ushort)_data.Data02;
                    arg2.Sender.SynchNetData();
                    arg2.Sender.ChangeRoom(m_map.Name);
                    player = null;
                }
                else
                {
                    player.CreateSaveTimer();
                    ServerLogger.LogWarn($"Switch from map {_data.Data01} on portal {_data.Guid} failed: couldn't save player {arg2.Sender.Id} character!");
                    player.SystemMsg("Map switch failed: couldn't save character to database!");
                }
            }
            else
            {
                player.SystemMsg("You far away from the portal.");
            }
        }
コード例 #27
0
        [Rpc(15, false)]//Local Chat
        private void RPC_015(NetMessage arg1, NetMessageInfo arg2)
        {
            var      time    = DateTime.Now;
            var      icon    = ChatIcon.None;
            ChatType type    = (ChatType)arg1.ReadByte();
            string   message = arg1.ReadString();
            var      player  = _server[arg2.Sender.Id];

            if (player.User.Access == AccessLevel.Admin)
            {
                icon = ChatIcon.Admin;
            }
            if (player.User.Access == AccessLevel.Moderator)
            {
                icon = ChatIcon.Mod;
            }
            if (message == Constants.StuckCommand)
            {
                _server.Objects.Teleport(player.Object, player.User.Spawn);
            }
            else if (message.Sum(x => char.IsUpper(x) ? 1 : 0) > message.Length / 4 + 4 || time < player.LastMsg)
            {
                player.Player.SystemMsg(Constants.ChatWarning);
            }
            else
            {
                player.LastMsg = time.AddMilliseconds(SpamDelay);
                ServerLogger.LogLocalChat(player, message);
                _server.Room.PlayerRpc(15, ChatType.Local, player.Char.Pony.Name, player.User.Name, message, player.User.Char, (int)arg2.Sender.Id, icon, DateTime.Now);
            }
        }
コード例 #28
0
 public static async Task <List <Character> > SelectAllUserCharactersAsync(int user)
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT * FROM {tb_02} WHERE user = {user} LIMIT {s_maxChars};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     var result = new List <Character>();
                     if (reader.HasRows)
                     {
                         while (await reader.ReadAsyncEx())
                         {
                             result.Add(new Character(reader.GetInt32(0), reader.GetInt32(1), reader.GetInt16(2), reader.GetInt32(3),
                                                      reader.GetPony(4), reader.GetProtoBuf <CharData>(8)));
                         }
                     }
                     return(result);
                 }
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #29
0
        private void Room_PlayerAdded(Player obj)
        {
            var player = new CharPlayer(obj, this);

            _players[obj.Id] = player;
            ServerLogger.LogServer(this, $" Player {obj.Id} added");
        }
コード例 #30
0
        private static void Main(string[] args)
        {
            try
            {
                FriendManager friendManager = CreatePlugin <FriendManager>();
                friendManager.OnPluginLoaded("", "", "");
                friendManager.OnPluginEnable();
                friendManager.OnPluginDisable();


                RemoteManager remoteManager = CreatePlugin <RemoteManager>();
                remoteManager.OnPluginLoaded("", "", "");
                remoteManager.OnPluginEnable();
                remoteManager.OnPluginDisable();


                ServerLogger serverLogger = CreatePlugin <ServerLogger>();
                serverLogger.OnPluginLoaded("", "", "");
                serverLogger.OnPluginEnable();
                serverLogger.OnPluginDisable();
            }
            catch (Exception ex)
            {
                Trace.TraceError(ex.ToString());
            }
            Console.ReadLine();
        }
コード例 #31
0
 public static async Task <List <string> > SelectAllResourcesAsync()
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"SELECT path FROM {tb_06};";
                 using (var reader = await command.ExecuteReaderAsyncEx())
                 {
                     var result = new List <string>();
                     if (reader.HasRows)
                     {
                         while (await reader.ReadAsyncEx())
                         {
                             result.Add(reader.GetString(0));
                         }
                     }
                     return(result);
                 }
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(null);
     }
 }
コード例 #32
0
 public static async Task <bool> CreateObjectAtAsync(WorldObject entry, int map, ushort guid, int objectID, byte type, byte flags, float time, params int[] data)
 {
     try
     {
         using (var connection = await GetConnectionAsync())
         {
             using (var command = connection.CreateCommand())
             {
                 command.CommandText = $"INSERT INTO {tb_03_01} (map, guid, object, type, flags, pos_x, pos_y, pos_z, rot_x, rot_y, rot_z, time, data01, data02, data03) " +
                                       $"VALUES ({map}, {guid}, {objectID}, {type}, {flags}, @pos_x, @pos_y, @pos_z, @rot_x, @rot_y, @rot_z, @time, @data01, @data02, @data03);";
                 command.Parameters.AddWithValue("time", time);
                 var vector = entry.Position;
                 command.Parameters.AddWithValue("pos_x", vector.X);
                 command.Parameters.AddWithValue("pos_y", vector.Y);
                 command.Parameters.AddWithValue("pos_z", vector.Z);
                 vector = entry.Rotation.ToDegrees();
                 command.Parameters.AddWithValue("rot_x", vector.X);
                 command.Parameters.AddWithValue("rot_y", vector.Y);
                 command.Parameters.AddWithValue("rot_z", vector.Z);
                 command.Parameters.AddWithValue("data01", data?.Length >= 1 ? data[0] : -1);
                 command.Parameters.AddWithValue("data02", data?.Length >= 2 ? data[1] : -1);
                 command.Parameters.AddWithValue("data03", data?.Length >= 3 ? data[2] : -1);
                 return(await command.ExecuteNonQueryAsyncEx() == 1);
             }
         }
     }
     catch (Exception exp)
     {
         ServerLogger.LogException(exp);
         return(false);
     }
 }
コード例 #33
0
        public void Init(IServerObjectHelper pSOH)
        {
            _soHelper = pSOH;
            _serverLog = new ServerLogger();
            _restSOIHelper = new RestSOIHelper(pSOH);

            _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".init()", 200, "Initialized " + _soiName + " SOI.");
        }
コード例 #34
0
ファイル: ArcStache.cs プロジェクト: dtsagile/arcstache
 public VectorCache()
 {
     soe_name = "ArcStache";
     logger = new ServerLogger();
     RestResource rootResource = CreateRestSchema();
     SoeRestImpl restImpl = new SoeRestImpl("arcstache", rootResource);
     reqHandler = (IRESTRequestHandler)restImpl;
 }
コード例 #35
0
 public void Shutdown() 
 {
     serverLog.LogMessage(ServerLogger.msgType.infoStandard, this.soeName + ".init()", 200, "Shutting down " + this.soeName + " SOE.");
     this.soHelper = null;
     this.serverLog = null;
     this.mapServerDataAccess = null;
     this.layerInfos = null;
 }
        public void Init(IServerObjectHelper pSOH)
        {
            this.soHelper = pSOH;
            this.serverLog = new ServerLogger();
            this.mapServerDataAccess = (IMapServerDataAccess)this.soHelper.ServerObject;
            IMapServer3 ms = (IMapServer3)this.mapServerDataAccess;
            IMapServerInfo mapServerInfo = ms.GetServerInfo(ms.DefaultMapName);
            this.layerInfos = mapServerInfo.MapLayerInfos;

            serverLog.LogMessage(ServerLogger.msgType.infoStandard, this.soeName + ".init()", 200, "Initialized " + this.soeName + " SOE.");
        }
        public NetFindNearFeaturesSoapSOE()
        {
            SoapCapabilities soapCaps = new SoapCapabilities();
            soapCaps.AddMethod("GetLayerInfos", "getInfo");
            soapCaps.AddMethod("FindNearFeatures", "findFeatures");
            soapCaps.AddMethod("DemoCustomObjectInput", "DemoCustomObject");
            soapCaps.AddMethod("DemoArrayOfCustomObjectsInput", "DemoArrayOfCustomObjects");

            logger = new ServerLogger();

            SoeSoapImpl soapImpl = new SoeSoapImpl(Constants.SOEName, soapCaps, HandleSoapMessage);
            reqHandler = (IRequestHandler2)soapImpl;
        }
        public void Init ( IServerObjectHelper pSOH )
        {
            try
            {
                _soHelper = pSOH;
                _serverLog = new ServerLogger();

                _restSOIHelper = new RestSOIHelper(pSOH);

                try
                {
                    //interop problem?
                    var se4 = _restSOIHelper.ServerEnvironment as IServerEnvironmentEx;
                    var dirInfos = se4.GetServerDirectoryInfos();
                    dirInfos.Reset();
                    object dirInfo = dirInfos.Next();
                    while (dirInfo != null)
                    {
                        var dinfo2 = dirInfo as IServerDirectoryInfo2;
                        if (null != dinfo2 && dinfo2.Type == esriServerDirectoryType.esriSDTypeOutput)
                        {
                            _outputDirectory = dinfo2.Path;
                            break;
                        }
                        dirInfo = dirInfos.Next();
                    }
                }
                catch (Exception ignore)
                {
                    _outputDirectory = string.Empty;
                }

                _outputDirectory = _outputDirectory.Trim();
                if (string.IsNullOrEmpty(_outputDirectory))
                {
                    _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".init()", 500, "OutputDirectory is empty or missing. Reset to default.");
                    _outputDirectory = "C:\\arcgisserver\\directories\\arcgisoutput";
                }

                _serverLog.LogMessage(ServerLogger.msgType.infoDetailed, _soiName + ".init()", 500, "OutputDirectory is " + _outputDirectory);
                _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".init()", 200, "Initialized " + _soiName + " SOI.");
            }
            catch (Exception e)
            {
                _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".HandleRESTRequest()", 500, "Exception " + e.GetType().Name + " " + e.Message + " " + e.StackTrace);
                throw;
            }
        }
コード例 #39
0
        public static Assembly AssemblyResolveHandler(object sender, ResolveEventArgs args)
        {
            var logger = new ServerLogger();
            logger.Log(TraceEventType.Warning, "Resolving Assembly: " + args.Name);
            Assembly match = null;
            var argsParts = args.Name.Split(',');
            var targetToLower = (argsParts.Length > 0) ? argsParts[0].ToLower() : args.Name.ToLower();
            var basedir = AppDomain.CurrentDomain.BaseDirectory;
            var providersdir = Path.Combine(basedir, "Providers");
            var assemblypaths_all = Directory.GetFiles(providersdir)
                                .Where(q => q.ToLower().Contains(".dll"));

            var assemblypaths = assemblypaths_all
                .Where(q => q.ToLower().Contains(targetToLower)).ToList();

            var count = assemblypaths.Count;
            logger.Log(TraceEventType.Verbose, "Items found in Providers dir: {0}", count);

            foreach (var item in assemblypaths)
            {
                Assembly a1 = null;
                try { a1 = Assembly.LoadFile(item); }
                finally { }
                if (a1 != null)
                {
                    if (a1.FullName == args.Name)
                    {
                        match = a1;
                        break;
                    }

                    if (a1.FullName.StartsWith(args.Name))
                    {
                        match = a1;
                        break;
                    }
                }
            }

            if (match == null)
                logger.Log(TraceEventType.Warning, "NO Match found");
            else
                logger.Log(TraceEventType.Information, "Match found");

            logger = null;
            return match;
        }
コード例 #40
0
        /// <summary>
        ///   Gets the value as string.
        /// </summary>
        /// <param name="property"> The property. </param>
        /// <param name="key"> The key. </param>
        /// <param name="errorOnNull"> if set to <c>true</c> [error on null]. </param>
        /// <returns> </returns>
        /// <exception cref="System.NullReferenceException"></exception>
        public static string GetValueAsString(this IPropertySet property, string key, bool errorOnNull = false)
        {
            var value = property.GetProperty(key) as string;

            if (string.IsNullOrEmpty(key))
            {
                var msg = "{0} is null or empty. Please add this value to the properties " +
                          "in the SOE capabilies section of the server manager application.".With(key);

                var logger = new ServerLogger();
                logger.LogMessage(ServerLogger.msgType.warning, "GetPropertyValue", 2472,
                                  msg);
                logger = null;

                if (errorOnNull)
                    throw new NullReferenceException(msg);
            }

            return value ?? "";
        }
コード例 #41
0
 public SampleSOE()
 {
     soe_name = this.GetType().Name;
     logger = new ServerLogger();
     reqHandler = new SoeRestImpl(soe_name, CreateRestSchema()) as IRESTRequestHandler;
 }
コード例 #42
0
 public LayerMetadata()
 {
     _soe_name = this.GetType().Name;
     _logger = new ServerLogger();
     _reqHandler = new SoeRestImpl(_soe_name, CreateRestSchema()) as IRESTRequestHandler;
 }
コード例 #43
0
        internal static RasterExtractionResult SummariseRaster(IGeoDataset pClippingPolygon, ExtractionLayerConfig pExtractionLayerConfig)
        {
            // set the analysis extent to be that of the polygon
            ServerLogger logger = new ServerLogger();
            logger.LogMessage(ServerLogger.msgType.debug, "SummariseCategoricalRaster", 99, "Categorical raster clip beginning..");
            IEnvelope tAnalysisExtent = pClippingPolygon.Extent;

            bool pCategoricalSummary = pExtractionLayerConfig.ExtractionType==ExtractionTypes.CategoricalRaster;
            IGeoDataset pRasterToClip = pExtractionLayerConfig.LayerDataset;

            IRasterAnalysisEnvironment tRasterAnalysisEnvironment = new RasterAnalysisClass();
            object tAnalysisEnvelopeCastToObject = (System.Object)tAnalysisExtent;
               // object tAnotherBizarreMissingObject = Type.Missing;
            object tSnapObject = (System.Object)pRasterToClip;
            tRasterAnalysisEnvironment.SetExtent(esriRasterEnvSettingEnum.esriRasterEnvValue,
                ref tAnalysisEnvelopeCastToObject, ref tSnapObject);
            tRasterAnalysisEnvironment.SetAsNewDefaultEnvironment();
            // extract the subset of the raster
            IExtractionOp2 tExtractionOp = new RasterExtractionOpClass();
            // note we want to base the extraction on a raster (in an IGeoDataset) rather than an IPolygon.
            // That's because the catchment polygon may be multipart, and the operation doesn't work with multipart.
            // Also the polygon has a max of 1000 vertices.
            // And raster mask extraction is probably faster since the
            // polygon is converted internally to a grid anyway.
            IGeoDataset tClipped;
            if (pRasterToClip as IRaster != null)
            {
                logger.LogMessage(ServerLogger.msgType.debug, "SummariseRaster", 99,
                    "Input was in raster form, using directly to clip...");
                tClipped = tExtractionOp.Raster(pRasterToClip, pClippingPolygon);
            }
            else
            {
                // POLYGON VERSION: tExtractionOp.Polygon(pClipRaster,pPolygon,true)
                // sometimes we need to be able to pass in a polygon but rather than using the polygon
                // method we'll manually convert to a mask raster to avoid the issues above
                // It would save work to do this once for each request rather than repeat the conversion
                // for each layer - but we might want a different environment (snap extent etc) for each.
                logger.LogMessage(ServerLogger.msgType.debug, "SummariseCategoricalRaster", 99,
                    "Converting input polygon to mask raster for clip...");
                IRasterConvertHelper tConvertPolygonToRaster = new RasterConvertHelperClass();
                // convert it to a raster with the same cell size as the input
                IRasterProps tRst = pRasterToClip as IRasterProps;
                IPnt tRstCellSize = tRst.MeanCellSize();
                double x = tRstCellSize.X;
                double y = tRstCellSize.Y;
                double cellSize = Math.Round(Math.Min(x, y), 0);
                object tCellSizeAsObjectForNoGoodReason = (System.Object)cellSize;
                tRasterAnalysisEnvironment.SetCellSize(esriRasterEnvSettingEnum.esriRasterEnvValue,
                    ref tCellSizeAsObjectForNoGoodReason);
                IGeoDataset tPolyAsRast =
                    tConvertPolygonToRaster.ToRaster1(pRasterToClip, "GRID", tRasterAnalysisEnvironment)
                as IGeoDataset;
                logger.LogMessage(ServerLogger.msgType.debug, "SummariseCategoricalRaster", 99,
                    "...done, proceeding with clip");
                tClipped = tExtractionOp.Raster(pRasterToClip, tPolyAsRast);
            }
            // now we have the clipped raster we need to summarise it differently depending on whether
            // we want a summary by category/value (for categorical rasters) or by stats (for float rasters)
            Dictionary<string, double> tResults;
            if (pCategoricalSummary)
            {
                tResults = WatershedDetailExtraction.SummariseRasterCategorically(tClipped);
                if (tResults.Count > 100)
                {
                    // sanity check: don't sum up more than 100 different values
                    tResults = WatershedDetailExtraction.SummariseRasterStatistically(tClipped);
                    pCategoricalSummary = false;
                }
            }
            else
            {
                tResults = WatershedDetailExtraction.SummariseRasterStatistically(tClipped);
            }
            tRasterAnalysisEnvironment.RestoreToPreviousDefaultEnvironment();
            return new RasterExtractionResult(pExtractionLayerConfig.ParamName, pCategoricalSummary, tResults);
            //return tResults;
        }
コード例 #44
0
 public Image_Services_SOE()
 {
     _soename = this.GetType().Name;
     _logger = new ServerLogger();
     reqHandler = new SoeRestImpl(_soename, CreateRestSchema()) as IRESTRequestHandler;
 }
コード例 #45
0
 public ISSOERasterAccess()
 {
     _soename = this.GetType().Name;
     _logger = new ServerLogger();
     _reqHandler = new SoeRestImpl(_soename, CreateRestSchema()) as IRESTRequestHandler;            
 }
コード例 #46
0
 public void Shutdown()
 {
     _logger.LogMessage(ServerLogger.msgType.infoStandard, "Shutdown", 8000, "Custom message: Shutting down the SOE");
     _serverObjectHelper = null;
     _logger = null;
     _mosaicCatalog = null;
 }
 public InternationalWaterbirdCensusExtensions()
 {
     soe_name = this.GetType().Name;
     logger = new ServerLogger();
     reqHandler = new SoeRestImpl(soe_name, CreateRestSchema()) as IRESTRequestHandler;
 }
コード例 #48
0
 public void Shutdown()
 {
     logger.LogMessage(ServerLogger.msgType.infoStandard, "Shutdown", 8000, "Custom message: Shutting down the SOE");
     soe_name = null;
     m_fcToQuery = null;
     m_mapFieldToQuery = null;
     serverObjectHelper = null;
     logger = null;
 }
コード例 #49
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="pSOH"></param>
        public void Init ( IServerObjectHelper pSOH )
        {
            try
            {
                _soHelper = pSOH;
                _serverLog = new ServerLogger();
                _serverObject = pSOH.ServerObject;

                _restServiceSOI = new RestSOIHelper(_soHelper);
                _SoapSOIHelper = new SoapSOIHelper(_soHelper, _wsdlFilePath);

                if (File.Exists(_permissionFilePath))
                {
                    //TODO REMOVE
                    _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".init()", 200, "Reading permissions from " + _permissionFilePath);

                    _servicePermissionMap = ReadPermissionFile(_permissionFilePath);

                    //TODO REMOVE
                    _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".init()", 200, "Total permission entries: " + _servicePermissionMap.Count());
                }
                else
                {
                    _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".init()", 500, "Permission file does not exist at " + _permissionFilePath);
                }

                InitFiltering();

                _serverLog.LogMessage(ServerLogger.msgType.infoStandard, _soiName + ".init()", 200, "Initialized " + _soiName + " SOI.");
            }
            catch (Exception e)
            {
                _serverLog.LogMessage(ServerLogger.msgType.error, _soiName + ".init()", 500, "Exception: " + e.Message + " in " + e.StackTrace);
            }
        }
コード例 #50
0
ファイル: wri-soe.cs プロジェクト: agrc/wri-webapi
 public wri_soe()
 {
     _soeName = GetType().Name;
     _logger = new ServerLogger();
     _reqHandler = new SoeRestImpl(_soeName, CreateRestSchema());
 }
コード例 #51
0
 public WatershedSOE()
 {
     soe_name = "WatershedSOE";
     logger = new ServerLogger();
     logger.LogMessage(ServerLogger.msgType.infoStandard,"startup",8000,"soe_name is "+soe_name);
 }
コード例 #52
0
 internal static bool AddAField(IFeatureClass pFeatureClass, string pFieldName, esriFieldType pFieldType, int pLength)
 {
     IField tField = new FieldClass();
     IFieldEdit tFieldEdit = tField as IFieldEdit;
     tFieldEdit.Type_2 = pFieldType;
     tFieldEdit.Name_2 = pFieldName;
     if (pFieldType == esriFieldType.esriFieldTypeString)
     {
         tFieldEdit.Length_2 = pLength;
     }
     ISchemaLock tSchemaLock = (ISchemaLock)pFeatureClass;
     bool successful = false;
     try
     {
         tSchemaLock.ChangeSchemaLock(esriSchemaLock.esriExclusiveSchemaLock);
         pFeatureClass.AddField(tField);
         successful = true;
     }
     catch (Exception ex)
     {
         ServerLogger servLogger = new ServerLogger();
         servLogger.LogMessage(ServerLogger.msgType.debug, "add field to output", 8000,
                 "Couldn't get schema lock to add field " + pFieldName + " to output!" + ex.Message);
     }
     finally
     {
         tSchemaLock.ChangeSchemaLock(esriSchemaLock.esriSharedSchemaLock);
     }
     //logger.LogMessage(ServerLogger.msgType.debug, "AddAField", 99,
     //                                     "Added field: " + pFieldName+", success: "+successful.ToString());
     return successful;
 }
コード例 #53
0
 /// <summary>
 ///     Initializes a new instance of the <see cref="CreateLayerMapCommand" /> class.
 /// </summary>
 /// <param name="serverObjectHelper">The server object helper.</param>
 public CreateLayerMapCommand(IServerObjectHelper serverObjectHelper)
 {
     _serverObjectHelper = serverObjectHelper;
     _logger = new ServerLogger();
 }