Inheritance: MonoBehaviour
Exemplo n.º 1
0
        //Checks the given point against every node in this nav mesh until it finds one which node the point is inside
        //Based on answers found in this question https://gamedev.stackexchange.com/questions/28781/easy-way-to-project-point-onto-triangle-or-plane/152476#152476
        public NavMeshNode FindNodeContainingPoint(Vector3 Point)
        {
            foreach (NavMeshNode Node in MeshNodes)
            {
                //Define the 3 corner points of the triangle
                Vector3 P1 = Node.VertexLocations[0];
                Vector3 P2 = Node.VertexLocations[1];
                Vector3 P3 = Node.VertexLocations[2];
                //Project the polnt onto the plane of the triangle
                Vector3 U = P2 - P1;
                Vector3 V = P3 - P1;
                Vector3 N = Vector3.Cross(U, V);
                Vector3 W = Point - P1;
                //Using the barycentric coordinates to find the point projected onto the plane
                //g = [(UxW).N]/N.N
                Vector3 UxW = Vector3.Cross(U, W);
                float   g   = Vector3.Dot(UxW, N) / Vector3.Dot(N, N);
                //b = [(WxV).N]/N.N
                Vector3 WxV = Vector3.Cross(W, V);
                float   b   = Vector3.Dot(WxV, N) / Vector3.Dot(N, N);
                float   a   = 1 - g - b;
                //Check if the projected point lies within the triangle
                bool ContainsPoint = ((0 <= a) && (a <= 1) &&
                                      (0 <= b) && (b <= 1) &&
                                      (0 <= g) && (g <= 1));
                //Return this mesh node if this is where the point was found to be inside
                if (ContainsPoint)
                {
                    return(Node);
                }
            }

            MessageLog.Print("Pathfinding.NavMesh this point lies completely outside of the navmesh");
            return(null);
        }
Exemplo n.º 2
0
        // Event handler for RLNET's Render event
        private static void OnRootConsoleRender(object sender, UpdateEventArgs e)
        {
            //don't redraw consoles if nothing changes
            if (_renderRequired)
            {
                _mapConsole.Clear();
                _statConsole.Clear();
                _messageConsole.Clear();
                _inventoryConsole.Clear();
                DungeonMap.Draw(_mapConsole, _statConsole);
                //draw the player
                Player.Draw(_mapConsole, DungeonMap);
                //draw the status console
                Player.DrawStats(_statConsole);
                //draw the MessageLog
                MessageLog.Draw(_messageConsole);

                //Blit the sub consoles to the root console in the correct locations
                RLConsole.Blit(_mapConsole, 0, 0, _mapWidth, _mapHeight, _rootConsole, 0, _inventoryHeight);
                RLConsole.Blit(_statConsole, 0, 0, _statWidth, _statHeight, _rootConsole, _mapWidth, 0);
                RLConsole.Blit(_messageConsole, 0, 0, _messageWidth, _messageHeight, _rootConsole, 0, _screenHeight - _messageHeight);
                RLConsole.Blit(_inventoryConsole, 0, 0, _inventoryWidth, _inventoryHeight, _rootConsole, 0, 0);

                //tell RLNet to draw the console
                _rootConsole.Draw();

                _renderRequired = false;
            }
        }
Exemplo n.º 3
0
        //Uses a data reader to read out a quaternion value from the database
        public static Quaternion ReadQuaternionValue(string CommandQuery, string Context = "Unknown error using reader to get quaternion value")
        {
            //Create a variable we will fill with the quaternion values when they are read from the databse
            Quaternion QuaternionValue = Quaternion.Identity;

            //Open a new connection with the base, then a datareader to get information from it
            MySqlConnection Connection = OpenConnection();
            MySqlCommand    Command    = CreateCommand(CommandQuery, Connection, Context);
            MySqlDataReader Reader     = CreateReader(Command);

            //Try using the reader to get the quaternion values that were looking for
            try
            {
                QuaternionValue.X = Convert.ToSingle(Reader["XRotation"]);
                QuaternionValue.Y = Convert.ToSingle(Reader["YRotation"]);
                QuaternionValue.Z = Convert.ToSingle(Reader["ZRotation"]);
                QuaternionValue.W = Convert.ToSingle(Reader["WRotation"]);
            }
            catch (MySqlException Exception) { MessageLog.Error(Exception, Context); }

            //Close the data reader, database connection then return the final quaternion values
            Reader.Close();
            Connection.Close();
            return(QuaternionValue);
        }
Exemplo n.º 4
0
        public static void Main()
        {
            string fontFileName = "terminal8x8.png";
            string consoleTitle = "RougeSharp RLNet Tutorial - Level 1";
            int    seed         = (int)DateTime.UtcNow.Ticks;

            Random = new DotNetRandom(seed);

            MessageLog = new MessageLog();
            MessageLog.Add("The rogue arrives on level 1");
            MessageLog.Add($"Level created with seed '{seed}'");

            Player           = new Player();
            SchedulingSystem = new SchedulingSystem();

            MapGenerator mapGenerator = new MapGenerator(_mapWidth, _mapHeight, 20, 13, 7, _mapLevel);

            DungeonMap = mapGenerator.CreateMap();

            //_rootConsole = new RLRootConsole( fontFileName, _screenWidth, _screenHeight, 8, 8, 1f, consoleTitle );
            //_mapConsole = new RLConsole( _mapWidth, _mapHeight );
            //_messageConsole = new RLConsole( _messageWidth, _messageHeight );
            //_statConsole = new RLConsole( _statWidth, _statHeight );
            //_inventoryConsole = new RLConsole( _inventoryWidth, _inventoryHeight );

            CommandSystem   = new CommandSystem();
            TargetingSystem = new TargetingSystem();

            Player.Item1 = new RevealMapScroll();
            Player.Item2 = new RevealMapScroll();

            //_rootConsole.Update += OnRootConsoleUpdate;
            //_rootConsole.Render += OnRootConsoleRender;
            //_rootConsole.Run();
        }
Exemplo n.º 5
0
        /// <summary>
        /// Handles a client players updated camera values to be stored in their ClientConnection, until
        /// they either leave or the server is being shutdown, to then be backed up into the database
        /// </summary>
        /// <param name="ClientID">NetworkID of the target client</param>
        /// <param name="Packet">Packet containing the information were after</param>
        public static void HandlePlayerCameraUpdate(int ClientID, ref NetworkPacket Packet)
        {
            //Log what we are doing here
            CommunicationLog.LogIn(ClientID + " Player Camera Update");

            //Extract all the values from the packet data
            float Zoom      = Packet.ReadFloat();
            float XRotation = Packet.ReadFloat();
            float YRotation = Packet.ReadFloat();

            //Try getting the ClientConnection object who sent this packet to us
            ClientConnection Client = ConnectionManager.GetClient(ClientID);

            //Display an error and exit from the function if they couldnt be found
            if (Client == null)
            {
                MessageLog.Print("ERROR: " + ClientID + " ClientConnection object couldnt be found, Player Camera Update could not be performed.");
                return;
            }

            //Store them in the ClientConnection object
            Client.Character.CameraZoom      = Zoom;
            Client.Character.CameraXRotation = XRotation;
            Client.Character.CameraYRotation = YRotation;
        }
Exemplo n.º 6
0
    void Init()
    {
        int seed = (int)DateTime.UtcNow.Ticks;

        Random = new DotNetRandom(seed);

        PlayerStat     = GameObject.Find("playerStat");
        EquipmentItems = GameObject.Find("equipmentItems");
        AbilitiesItems = GameObject.Find("abilitiesItems");
        ItemItems      = GameObject.Find("itemItems");
        MonsterStat    = GameObject.Find("monsterStat");
        MonsterItem    = Resources.Load <GameObject>("Prefabs/monsterItem");

        text       = GameObject.Find("massageText").GetComponent <Text>();
        text.color = Color.white;

        MessageLog       = new MessageLog();
        SchedulingSystem = new SchedulingSystem();
        MessageLog.Add("The rogue arrives on level 1");
        MessageLog.Add(string.Format("Level created with seed '{0}'", seed));

        groundTiles = new GameObject[_width, _height];
        ItemsTiles  = new Entry[_width, _height];

        boardHolder   = new GameObject("boardHolder").transform;
        itemsHolder   = new GameObject("itemsHolder").transform;
        effectsHolder = new GameObject("effectsHolder").transform;

        CommandSystem   = new CommandSystem();
        TargetingSystem = new TargetingSystem();
    }
Exemplo n.º 7
0
        public override CommandResult Execute(Entity entity)
        {
            if (Target == null || !entity.HasComponent <FighterComponent>() || !Target.HasComponent <FighterComponent>())
            {
                return(CommandResult.Failure);
            }

            int damage  = 0;
            int power   = entity.GetComponent <FighterComponent>().Power.Value;
            int defense = Target.GetComponent <FighterComponent>().Defense.Value;

            if (Program.Game.Random.NextDouble() < CriticalHitChance)
            {
                damage = power;
            }
            else
            {
                damage = power - defense;
            }

            if (damage > 0)
            {
                Target.GetComponent <FighterComponent>().Damage(damage, entity, ElementType.Physical);
            }
            else
            {
                MessageLog.Add($"{entity.Name} attacks {Target.Name} but it has no effect!");
            }

            return(CommandResult.Success);
        }
Exemplo n.º 8
0
    public void OnRunEvent()
    {
        switch (Random.Range(0, 4))
        {
        case 0:
            MessageLog.PushMessage("You appear on a local TV spot");
            Stats.singleton.audience += 1500f;
            break;

        case 1:
            MessageLog.PushMessage("You host a charity dinner at $100 per plate");
            Stats.singleton.money += 3000f;
            break;

        case 2:
            MessageLog.PushMessage("You represent yourself well in a debate");
            Stats.singleton.literacy += 1500f;
            break;

        case 3:
            MessageLog.PushMessage("You kiss some babies");
            Stats.singleton.audiencePerSecond += 2f;
            break;
        }
        Stats.singleton.influence += 1000f;
    }
Exemplo n.º 9
0
        public void AfterReceiveReply(ref System.ServiceModel.Channels.Message reply, object correlationState)
        {
            string ModuleName = "AUBMessageInspector";
            string MethodName = "AfterReceiveReply";

            string replyString = reply.ToString();
            string sessionID   = (string)correlationState;

            NCR.EAI.Log.MessageLogger msgLogger = new NCR.EAI.Log.MessageLogger();
            MessageLog _messageLog = new MessageLog();

            _messageLog.IN_OUT     = MessageLog.INOUT.OUT_RES.GetHashCode();
            _messageLog.SESSION_ID = sessionID;
            _messageLog.NETWORK_ID = ConfigurationManager.AppSettings["AUB_OIS_NETWORK_ID"].ToString();

            msgLogger.updateSoapResponseMsgLog(ref reply, ref _messageLog);

            //throw new NotImplementedException();
            //System.Windows.Forms.MessageBox.Show(reply.WriteMessage()
            if (Convert.ToBoolean(ConfigurationManager.AppSettings["LOG_AUB_MESSAGE"].ToString()))
            {
                string pattern  = @"\b(?:(4|5)([0-9]{1})([0-9]{4})([0-9]{6})([0-9]{4}))\b";
                string MASKCARD = "$1$2$3******$5";
                string DebugMsg = Regex.Replace(replyString, pattern, MASKCARD);

                Logger.logDebug(ModuleName, MethodName, "Reply Message: " + DebugMsg, Logger.LOGLEVEL.INFO);
            }
            try
            {
                Logger.logDebug(ModuleName, MethodName, "Is Fault: " + reply.IsFault.ToString(), Logger.LOGLEVEL.INFO);
            }
            catch
            {
            }
        }
Exemplo n.º 10
0
        private static void OnRootConsoleRender(object sender, UpdateEventArgs e)
        {
            if (_renderRequired)
            {
                _mapConsole.Clear();
                _statConsole.Clear();
                _messageConsole.Clear();

                DungeonMap.Draw(_mapConsole, _statConsole);
                Player.Draw(_mapConsole, DungeonMap);
                MessageLog.Draw(_messageConsole);

                Player.DrawStats(_statConsole);

                RLConsole.Blit(_mapConsole, 0, 0, _mapWidth, _mapHeight, _rootConsole, 0, _inventoryHeight);

                RLConsole.Blit(_statConsole, 0, 0, _statWidth, _statHeight, _rootConsole, _mapWidth, 0);

                RLConsole.Blit(_messageConsole, 0, 0, _messageWidth, _messageHeight, _rootConsole, 0, _screenHeight - _messageHeight);

                RLConsole.Blit(_inventoryConsole, 0, 0, _inventoryWidth, _inventoryHeight, _rootConsole, 0, 0);

                _rootConsole.Draw();

                _renderRequired = false;
            }
        }
Exemplo n.º 11
0
        private IActionResult BuildSolutionModel(Puzzle puzzle, MessageLog log = null)
        {
            var model = new PageModel(log);

            model.InitialState = puzzle.Copy();
            model.Puzzle       = puzzle;
            model.PageTitle    = "Sudoku brain";

            var solver = new PuzzleSolver(model.Log);

            int previousNumberFilledIn = puzzle.CountFilledInCells;

            while (solver.ApplyAllStrats(puzzle))
            {
                int currentNumberFilledIn = puzzle.CountFilledInCells;
                if (currentNumberFilledIn > previousNumberFilledIn)
                {
                    puzzle.WriteGridAsText(model.Log);
                }
                if (currentNumberFilledIn == 81)
                {
                    break;
                }
                previousNumberFilledIn = currentNumberFilledIn;
            }
            solver.EndSolutionStats(puzzle);

            return(View("Index", model));
        }
        //methods

        public void GenerateArrayCode(MessageLog pMessageLog)
        {
            _messageLog = pMessageLog;

            try
            {
                _messageLog.Clear();

                WriteMessageToLog(_declareClassBegin);

                GenerateSyntaxArrayCode("SentenceSyntaxDefs", _sentenceSyntaxList, 5);
                GenerateSyntaxArrayCode("SubordinateClauseDefs", _subordinateClauseList, 5);
                GenerateSyntaxArrayCode("NounPhraseSyntaxDefs", _nounPhraseSyntaxList, 5);
                GenerateSyntaxArrayCode("SubjectSyntaxDefs", _subjectSyntaxList, 5);
                GenerateSyntaxArrayCode("VerbPhraseSyntaxDefs", _verbPhraseSyntaxList, 5);
                GenerateSyntaxArrayCode("ObjectSyntaxDefs", _objectSyntaxList, 5);
                GenerateSyntaxArrayCode("SentenceTerminatorDefs", _sentenceTerminatorList, 5);
                GenerateHelperArrays();

                WriteMessageToLog(_declareClassEnd);
            }
            catch (System.Exception ex)
            {
                _msg.Length = 0;
                _msg.Append(AppGlobals.AppMessages.FormatErrorMessage(ex));
                WriteMessageToLog(_msg.ToString());
                AppMessages.DisplayErrorMessage(_msg.ToString(), _saveErrorMessagesToAppLog);
            }
            finally
            {
                ;
            }
        }
Exemplo n.º 13
0
        public string ThirdCharacterName  = ""; //Name of the third character

        /// <summary>
        /// Returns a new CharacterData object containing all of that characters data
        /// </summary>
        /// <param name="CharacterNumber">The character slot to get data from (1,2 or 3)</param>
        /// <returns></returns>
        public CharacterData GetCharactersData(int CharacterNumber)
        {
            //Make sure the character who's data is being requested exists
            if (CharacterNumber == 1 && FirstCharacterName == "")
            {
                MessageLog.Print("ERROR: This account doesnt have a 1st character, so its data cannot be provded.");
                return(null);
            }
            if (CharacterNumber == 2 && SecondCharacterName == "")
            {
                MessageLog.Print("ERROR: This account doesnt have a 2nd character, so its data cannot be provided.");
                return(null);
            }
            if (CharacterNumber == 3 && ThirdCharacterName == "")
            {
                MessageLog.Print("ERROR: This account doesnt have a 3rd character, so its data cannot be provided.");
                return(null);
            }

            //Fetch the characters data and return it
            return(CharactersDatabase.GetCharacterData(
                       CharacterNumber == 1 ? FirstCharacterName :
                       CharacterNumber == 2 ? SecondCharacterName :
                       ThirdCharacterName));
        }
Exemplo n.º 14
0
        public static void SendMessage(MessageLog log)
        {
            var factory = new ConnectionFactory()
            {
                HostName = "localhost"
            };

            using (IConnection connection = factory.CreateConnection())
                using (IModel channel = connection.CreateModel())
                {
                    channel.QueueDeclare(queue: "MessageLog",
                                         durable: false,
                                         exclusive: false,
                                         autoDelete: false,
                                         arguments: null);

                    string _messageLog = JsonConvert.SerializeObject(log);
                    var    body        = Encoding.UTF8.GetBytes(_messageLog);

                    channel.BasicPublish(exchange: "",
                                         routingKey: "MessageLog",
                                         basicProperties: null,
                                         body: body);
                    Console.WriteLine($" From: {log.Nick} [{log.Text}]");
                }
        }
Exemplo n.º 15
0
        public MessengerCommandHandler(ITcpPeerMessenger messenger, MessageLog messageLog)
        {
            _messenger  = messenger;
            _messageLog = messageLog;

            _messenger.ClientAccepted += (s, endPoint) => { _lastConnectedEndPoint = endPoint; };
        }
Exemplo n.º 16
0
 public ClassValidationVisitor(MessageLog log, SymbolTable symbols, ValidationPass pass)
 {
     Log     = log ?? new MessageLog();
     Symbols = symbols;
     Success = true;
     Pass    = pass;
 }
Exemplo n.º 17
0
 static void CreateDependencies()
 {
     messageLog                 = new MessageLog();
     fTextView                  = new TextView(infoList);
     drawingView                = new DrawingView(infoList);
     editingController          = new EditingController(infoList.List);
     editingController.Changed += fTextView.UpdateInfo;
     fEditor = new FEditor(editingController.ObservableCollection)
     {
         Header = infoList.Header
     };
     fListSelector = new FListSelector(editingController.ObservableCollection)
     {
         Header = infoList.Header
     };
     fRadioSelector = new FRadioSelector(editingController.ObservableCollection)
     {
         Header = infoList.Header
     };
     //fManaging = new FManager(fTextView, fEditor, fListSelector) {
     fManaging = new FManager(drawingView, fEditor, fRadioSelector, messageLog)
     {
         Title  = "RusRulers",
         Header = infoList.Header
     };
 }
Exemplo n.º 18
0
 public static int ExecuteScalar(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
 {
     try
     {
         SqlCommand cmd = new SqlCommand();
         using (SqlConnection connection = new SqlConnection(connectionString))
         {
             PrepareCommand(cmd, connection, cmdType, cmdText, commandParameters);
             object obj = cmd.ExecuteScalar();
             cmd.Parameters.Clear();
             return(ObjectToInt32(obj));
         }
     }
     catch (Exception ex)
     {
         MessageLog.WriteLog(new LogParameterModel()
         {
             ClassName  = "DAL.DbHelperSql",
             MethodName = "ExecuteScalar",
             LogLevel   = ELogLevel.Warn,
             Message    = ex.Message
         });
         return(-1);
     }
 }
Exemplo n.º 19
0
        public static void HandleClientChatMessage(int ClientID, ref NetworkPacket Packet)
        {
            CommunicationLog.LogIn(ClientID + " chat message");

            //Fetch this ClientConnection and make sure they were able to be found
            ClientConnection Client = ConnectionManager.GetClient(ClientID);

            if (Client == null)
            {
                MessageLog.Print("ERROR: Client not found, unable to handle chat message.");
                return;
            }

            //Extract the message content from the network packet
            string ChatMessage = Packet.ReadString();

            //Get the list of all the other game clients who are already ingame
            List <ClientConnection> OtherClients = ClientSubsetFinder.GetInGameClientsExceptFor(ClientID);

            //Pass this chat message on to all the other clients that are ingame
            foreach (ClientConnection OtherClient in OtherClients)
            {
                PlayerCommunicationPacketSender.SendChatMessage(OtherClient.ClientID, Client.Character.Name, ChatMessage);
            }
        }
Exemplo n.º 20
0
        private void applyJobFactors(PlaceState place, JobOffer offer)
        {
            if (offer.TrustFactor < 1.0f)
            {
                foreach (var dock in place.Docks)
                {
                    var schedule = dock.Schedule;
                    for (int i = 0; i < schedule.Jobs.Count; i++)
                    {
                        var item = schedule.Jobs[i];
                        if (item.Job.Id == offer.Id)
                        {
                            MessageLog.AddError(string.Format("{0} has cancelled your contract to ship {1} from {2} to {3}",
                                                              item.Job.Company,
                                                              item.Job.Item.Name,
                                                              item.Job.From.Name,
                                                              item.Job.To.Name));

                            schedule.Jobs.RemoveAt(i);
                            i--;
                        }
                    }
                }
            }
        }
Exemplo n.º 21
0
 private static int ExecuteNonQuery(string connectionString, CommandType cmdType, string cmdText, params SqlParameter[] commandParameters)
 {
     try
     {
         SqlCommand cmd = new SqlCommand();
         cmd.CommandTimeout = 60;
         using (SqlConnection connection = new SqlConnection(connectionString))
         {
             PrepareCommand(cmd, connection, cmdType, cmdText, commandParameters);
             int num = cmd.ExecuteNonQuery();
             cmd.Parameters.Clear();
             return(num);
         }
     }
     catch (Exception ex)
     {
         MessageLog.WriteLog(new LogParameterModel()
         {
             ClassName  = "DAL.DbHelperSql",
             MethodName = "ExecuteNonQuery",
             LogLevel   = ELogLevel.Warn,
             Message    = ex.Message
         });
         return(-1);
     }
 }
Exemplo n.º 22
0
        /// <summary>
        /// Загружает файл из телеграмм чата
        /// </summary>
        /// <param name="f">атрибуты полученного файла</param>
        public async void DownLoad(MyFile f)
        {
            string botReply = "Спасибо. ";

            try
            {
                if (!Directory.Exists($@"{Catalog.PathToUserFiles}\{f.FileType}"))
                {
                    Directory.CreateDirectory($@"{Catalog.PathToUserFiles}\{f.FileType}");
                }
                var file = await bot.GetFileAsync(f.FileId);

                FileStream fs = new FileStream(f.FilePath, FileMode.Create);

                await bot.DownloadFileAsync(file.FilePath, fs);

                fs.Close();

                fs.Dispose();
                f.IsDownloaded = true; // отметка о том, что файл был успешно загружен
            }
            catch (Exception ex)
            {
                botReply += "Возможно, мне неизвестен тип этого файла или произошла ошибка при загрузке.";
                Debug.WriteLine("Ошибка загрузки файла: " + ex.Message);
            }
            finally
            {
                Catalog.Add(f);
                await bot.SendTextMessageAsync(f.ChatId, botReply);

                MessageLog.Add(new MessageRec(DateTime.Now.ToLongTimeString(), 0, "Bot", botReply, "Text"));
            }
        }
Exemplo n.º 23
0
    public void OnRead()
    {
        string key = Talk.ChooseRandom(outcomes.Keys.ToArray());

        Stats.singleton.literacy += outcomes[key] + Mathf.Round(Stats.singleton.literacy * 0.1f);
        MessageLog.PushMessage(key);
    }
Exemplo n.º 24
0
        public void SendGameData(UserDataInfo player, MsgType messageType, bool messageState, GameDataType gameDataType, string gameDataObject = "")
        {
            var log = new MessageLog
            {
                Type           = messageType,
                State          = messageState,
                GameDataType   = gameDataType,
                GameDataObject = gameDataObject
            };

            player.Logs.Push(log);
            //Log.Debug($"Server sent {log} to {player.AccountName}");

            try
            {
                player.ResponseStream.WriteAsync(new GameServerStream()
                {
                    MessageType  = messageType,
                    MessageState = messageState,
                    Message      = JsonConvert.SerializeObject(new GameData()
                    {
                        GameId         = GameId,
                        PlayerId       = player.PlayerId,
                        GameDataType   = gameDataType,
                        GameDataObject = gameDataObject
                    })
                }).Wait();
            }
            catch
            {
                ;
            }
        }
Exemplo n.º 25
0
        /// <summary>
        /// Получает сообщения в фоновом режиме
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        public void MessageListener(object sender, Telegram.Bot.Args.MessageEventArgs e)
        {
            this.w.Dispatcher.Invoke(() =>
            {
                MessageRec message = new MessageRec(DateTime.Now.ToLongTimeString(), e.Message.Chat.Id, e.Message.Chat.FirstName, e.Message.Text, e.Message.Type.ToString());
                MessageLog.Add(message);

                BotContact botContact = new BotContact(e.Message.Chat.FirstName, e.Message.Chat.Id);

                if (!ContactList.Contains(botContact))
                {
                    ContactList.Add(botContact);
                }

                if (e.Message.Type.ToString() == "Text")
                {
                    string messageText = e.Message.Text.ToLower();
                    ReplyOnText(messageText, e.Message.Chat.Id);
                }
                else
                {
                    DownLoad(IdentifiedFile(e));
                }
            });
        }
Exemplo n.º 26
0
        public Task UserAddToGroupAsync(string userId, string groupName, TimeSpan ttl, CancellationToken cancellationToken = default)
        {
            if (string.IsNullOrEmpty(userId))
            {
                throw new ArgumentException(NullOrEmptyStringErrorMessage, nameof(userId));
            }

            if (string.IsNullOrEmpty(groupName))
            {
                throw new ArgumentException(NullOrEmptyStringErrorMessage, nameof(groupName));
            }

            if (ttl < TimeSpan.Zero)
            {
                throw new ArgumentOutOfRangeException(nameof(ttl), TtlOutOfRangeErrorMessage);
            }
            var message = AppendMessageTracingId(new UserJoinGroupMessage(userId, groupName)
            {
                Ttl = (int)ttl.TotalSeconds
            });

            if (message.TracingId != null)
            {
                MessageLog.StartToAddUserToGroup(Logger, message);
            }
            return(WriteAsync(message));
        }
Exemplo n.º 27
0
        //Loads a mesh into memory, then returns a key you can use to access that mesh from the dictionary
        public static int LoadMesh(string ContentName, Vector3 Scale)
        {
            //Make sure the manager has been initialized first
            if (MeshArchive == null || MemoryPool == null)
            {
                MessageLog.Print("ERROR: MeshManager has not been initialized yet, initialize it first before trying to load meshes into memory.");
                return(-1);
            }

            //Make sure there isnt already a mesh loaded with this name
            if (LoadedMeshNames.Contains(ContentName))
            {
                MessageLog.Print("Theres already a mesh loaded by the name of " + ContentName + ".");
                return(-1);
            }

            //Load the meshes content from the archive and build a new Mesh object with its information
            var MeshContent = MeshArchive.Load <MeshContent>(ContentName);

            MemoryPool.Take <Triangle>(MeshContent.Triangles.Length, out var Triangles);
            for (int i = 0; i < MeshContent.Triangles.Length; i++)
            {
                Triangles[i] = new Triangle(MeshContent.Triangles[i].A, MeshContent.Triangles[i].B, MeshContent.Triangles[i].C);
            }
            Mesh MeshObject = new Mesh(Triangles, Scale, MemoryPool);

            //Store the new mesh object into the dictionary with the others
            int MeshKey = ++NextMeshKey;

            LoadedMeshes.Add(MeshKey, MeshObject);
            return(MeshKey);
        }
Exemplo n.º 28
0
    private void AddNewCitizens()
    {
        if (GameObject.FindGameObjectWithTag("Enemy"))
        {
            return;
        }

        int   allCurrentCitizens = allCitizens.Count + currentEmployedAmount;
        float bedsLeft           = currentBedsAmount - allCurrentCitizens;

        if (bedsLeft <= 0)
        {
            MessageLog.AddNewMessage("Some people tried to join your town but there were no beds available, perhaps we should build more houses");  return;
        }

        //How many citizens are added depends on the happiness of the people
        int citizensToAdd = Mathf.RoundToInt(bedsLeft / 100 * currentHappinessAmount);

        for (int i = 0; i < citizensToAdd; i++)
        {
            SpawnNewCitizen();
        }
        if (currentHappinessAmount >= 100)
        {
            MessageLog.AddNewMessage("Its a new day and " + citizensToAdd.ToString() + " decided to join your town!");
        }
        else
        {
            float citizensLeft = bedsLeft - citizensToAdd;
            MessageLog.AddNewMessage("Its a new day and " + citizensToAdd.ToString() + " decided to join your town but " + citizensLeft.ToString() + " refused");
        }
        citizensText.text = (currentEmployedAmount + allCitizens.Count).ToString();
    }
Exemplo n.º 29
0
        static void Main()
        {
            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);
            //Application.Run(new CMainForm());


            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            CAppGlobalErrorHandler.WriteToAppLog   = true;
            CAppGlobalErrorHandler.WriteToEventLog = false;
            CAppGlobalErrorHandler.CancelApplicationOnGlobalError = false;

            Application.ThreadException += new ThreadExceptionEventHandler(CAppGlobalErrorHandler.GlobalErrorHandler);

            _messageLog              = new MessageLog();
            _messageLog.Caption      = "Test Progam (TestprogOdbc)";
            _messageLog.ShowDatetime = false;
            _messageLog.Font         = "Lucida Console";
            _messageLog.FontSize     = (float)10.0;
            _messageLog.ShowWindow();

            //MessageBox.Show(Environment.MachineName);

            _mainForm = new MainForm();

            Application.Run(_mainForm);
        }
Exemplo n.º 30
0
        // Event handler for RLNET's Render event
        private static void OnRootConsoleRender(object sender, UpdateEventArgs e)
        {
            if (_renderRequired)
            {
                _mapConsole.Clear();
                _statConsole.Clear();
                _messageConsole.Clear();

                DungeonMap.Draw(_mapConsole, _statConsole);
                Player.Draw(_mapConsole, DungeonMap);
                Player.DrawStats(_statConsole);
                MessageLog.Draw(_messageConsole);

                // Blit the sub consoles to the root console in the correct locations
                RLConsole.Blit(_mapConsole, 0, 0, _mapWidth, _mapHeight,
                               _rootConsole, 0, _inventoryHeight);
                RLConsole.Blit(_statConsole, 0, 0, _statWidth, _statHeight,
                               _rootConsole, _mapWidth, 0);
                RLConsole.Blit(_messageConsole, 0, 0, _messageWidth, _messageHeight,
                               _rootConsole, 0, _screenHeight - _messageHeight);
                RLConsole.Blit(_inventoryConsole, 0, 0, _inventoryWidth, _inventoryHeight,
                               _rootConsole, 0, 0);
                // Tell RLNET to draw the console that we set

                _rootConsole.Draw();

                _renderRequired = false;
            }
            _renderRequired = true;
        }
Exemplo n.º 31
0
 public int save(MessageLog m)
 {
     return DB.Save(m);
 }
Exemplo n.º 32
0
    public void Awake()
    {
        DontDestroyOnLoad(this);
        Instance = this;
        MessageLog = new MessageLog();
        MessageLog.Skin = BaseSkin;

        //uLink.Network.natFacilitatorIP = "107.170.78.82";

        ExternalServerList = new ExternalServerList();
        ExternalServerList.OnMasterServerListChanged += ReceiveMasterListChanged;
        ExternalServerList.OnMasterServerListFetchError += ReceiveMasterListFetchError;

        BoxSpacer = new GUIStyle(BaseSkin.box) {fixedWidth = 1};

        OptionsMenu = new OptionsMenu(BaseSkin);

        OptionsMenu.OnOptionsMenuWantsClosed += () =>
        { ShowOptions = false; };
        OptionsMenu.OnOptionsMenuWantsQuitGame += Application.Quit;
        OptionsMenu.OnOptionsMenuWantsGoToTitle += uLink.Network.Disconnect;

        // We want 60fps send rate, but Unity seems retarded and won't actually
		// send at the rate you give it. So we'll just specify it higher and
		// hope to meet the minimum of 60 ticks per second.
        uLink.Network.sendRate = 80;

        // Set up thing that requests to get our WAN IP from some server.
        AddressFinder = new ExternalAddressFinder();
    }
Exemplo n.º 33
0
 /**
  * FUNCTION TO WRITE TO THE MESSAGELOG TABLE
  *
  *
  * */
 private void write_to_message_log(MessageLog m)
 {
     IMessageLogRepository messageLog = new MessageLogRepository();
     messageLog.save(m);
 }
        /// <summary>
        /// This is the entry point for your add in.
        /// </summary>
        /// <param name="provider">This gives you access to the SSMS integrations provided by SIPFramework. If there's something missing let me know!</param>
        public void OnLoad(ISsmsExtendedFunctionalityProvider provider)
        {
            m_Provider = (ISsmsFunctionalityProvider6)provider;    //Caste to the latest version of the interface

            m_MessageLog = new MessageLog();
            var messagesView = new MessagesView { DataContext = m_MessageLog };
            m_MessageLogWindow = m_Provider.ToolWindow.Create(messagesView, "Sample Add-in", new Guid(c_MessageWindowGuid));
            m_MessageLogWindow.Window.Dock();
            DisplayMessages();

            AddMenuBarMenu();
            AddObjectExplorerContextMenu();
            AddToolbarButton();
        }
Exemplo n.º 35
0
        public void Update(int Id,string Title,string Body,string SentTo,DateTime SentAt,bool Deleted)
        {
            MessageLog item = new MessageLog();
            item.MarkOld();
            item.IsLoaded = true;

            item.Id = Id;

            item.Title = Title;

            item.Body = Body;

            item.SentTo = SentTo;

            item.SentAt = SentAt;

            item.Deleted = Deleted;

            item.Save(UserName);
        }
Exemplo n.º 36
0
        /**
         * This function should construct and send the email finally
         *
         * NOT FINISHED!!!
         */
        private void build_send_and_log_message(SigtradeUser user, MessageTemplate template, ParagraphActionCollection paras)
        {
            //create the mail message
            MailMessage mail = new MailMessage();

            //set the addresses
            mail.From = new MailAddress("*****@*****.**");

            //Finding user through membership Api

            MembershipUser my_user = Membership.GetUser(new Guid(user.userid));
            mail.To.Add(my_user.Email);
            //mail.To.Add(user); //MUST USE MEMBERSHIP API TO FIND USER AND PROFILE SETTINGS (INCL EMAIL) NOT WORKING

            //set the content
            mail.Subject = template.Title;
            StringBuilder emailBody = new StringBuilder();

            var userProfile = Profile.GetProfile(my_user.UserName);

            mail.Body = template.Body;
            emailBody.AppendLine("Dear " + userProfile.first_name + ' ' + userProfile.last_name);
            emailBody.AppendLine(template.Body);

            //Need to get the paragraph details
            IReviewRepository reviews = new ReviewRepository();
            ITaxonRepository taxon = new TaxonRepository();

            foreach (ParagraphAction para in paras)
            {
                var review = reviews.getSingleReview(para.ReviewID);
                var paragraph = reviews.getSinglePALib(para.PALibID);
                review.TaxonName = taxon.getReviewTaxonName(review.ID, review.Taxontype, review.Kingdom);
                //mail.Body = mail.Body.Concat(para.DeadlineDate.ToString()); //SOME SORT OF WARNING HERE!
                var review_type = review.TaxonName + " [" + review.CtyShort + "]";
                emailBody.AppendLine("Review:" + review_type);
                emailBody.AppendLine("Paragraph details: " + paragraph.Action + " (" + ((DateTime)para.DeadlineDate).ToShortDateString() + ')');
                emailBody.AppendLine();
                //mail.Body = mail.Body;
            }
            emailBody.AppendLine();
            emailBody.AppendLine(Resources.SigTrade.emailFooter);
            mail.Body = emailBody.ToString();

            //send the message
            SmtpClient smtp = new SmtpClient(UpdateUtils.SMTP_RELAY_SERVER,25);
            try
            {
                smtp.Send(mail);
            }
            catch(SmtpException e)
            {

            }

            //HERE WE SHOULD WRITE TO THE LOG TABLE.
            //Prepare the MessageLog object
            MessageLog log = new MessageLog();
            log.SentTo = my_user.Email;
            log.SentAt = DateTime.Today;
            log.Title = template.Title;
            log.Body = emailBody.ToString();
            write_to_message_log(log);
        }
 private void MessageLog_Click(object sender, RoutedEventArgs e)
 {
     // only check for loging right now but should also check for user keys next
     MessageLog logViewer = new MessageLog(UserContext.IsLoginSuccessful && UserContext.UserHasKey("MAG SYSTEM"));
     logViewer.ShowDialog();
 }
Exemplo n.º 38
0
 public void Awake()
 {
     singleton = this;
 }
Exemplo n.º 39
0
    void LogCallback(string message, string stackTrace, LogType type)
    {
        MessageLog entry = new MessageLog(message, stackTrace, type);
        messageLog.Add(entry);

        bodyScrollPosition.y += messageLog.Count * 10;
    }
Exemplo n.º 40
0
        public void Insert(string Title,string Body,string SentTo,DateTime SentAt,bool Deleted)
        {
            MessageLog item = new MessageLog();

            item.Title = Title;

            item.Body = Body;

            item.SentTo = SentTo;

            item.SentAt = SentAt;

            item.Deleted = Deleted;

            item.Save(UserName);
        }
Exemplo n.º 41
0
 public void delete(MessageLog m)
 {
     DB.Delete(m);
 }