Пример #1
0
        void OnMessageReceive(Communication.JSON.Message msg)
        {
            //Messages which can be received at any time:
            if(msg is Communication.JSON.MiscellaneousMessage) {
                Log.WriteGame(Log.Verbosity.Important, "Received miscellaneousMessage: " + (msg as Communication.JSON.MiscellaneousMessage).Text);
                return;
            }

            lock ("UnsafeWaitHandlerState") {
                var oldhandler = CurrentWaitHandler;
                try {
                    var res = CurrentWaitHandler.Invoke(msg);
                    if (res == null)
                        throw new BOSClientException("Received an message invalid in the current state of the protocol" +
                            "HandlerType: " + oldhandler.Method.Name +
                            "MessageType:" + msg.GetType().ToString()
                    );
                    CurrentWaitHandler = res.Item1;
                    if(res.Item2 != null)
                        communicator.SendMessage(res.Item2);
                    return;
                } catch (Exception ex) {
                    CurrentWaitHandler = oldhandler;
                    Log.WriteError(Log.Verbosity.Normal, "There was an error processing an received message: " + ex.ToString());
                }
            }
        }
Пример #2
0
    static void Main(string[] args)
    {
        Communication Client = new Communication();

            // Send Client Alive via the UDP Protocol to a determined port UDPport
            Thread UdpThread = new Thread(new ThreadStart(Client.UDPClientAlive));
            UdpThread.Start();
            Client.ClientAliveThreadID = UdpThread.ManagedThreadId;

            // Listen for a Sever Response over TCP
            Thread tcpListen = new Thread(new ThreadStart(Client.TCPListen));
            tcpListen.Start();
            tcpListen.Join();

            // Kill the Client Alive Thread Once TCP Communication is detected

            // First Message from Kinect: Establish Connection
            Client.TcpRecieveAndSendAck(Client.tcp);

            // Second Message from Kinect: Receive Initial Kinect Data
            Client.TcpRecieveAndSendAck(Client.tcp);

            while (true)
            {

            }
    }
        public BasemeterComThread(string ipAddress, string tcpPort, CommunicationPort port)
        {
            this.endpoint = new IPEndPoint(IPAddress.Parse(ipAddress), int.Parse(tcpPort));
            this.port = port;
            this.logger = LogManager.GetLogger($"{port.ComPortName}");

            // initialize bus communication
            this.communication = new Communication(new NLogLogger());
            this.communication.DeviceDiscovered += OnDeviceDiscovered;
            this.communication.DeviceDisappeared += OnDeviceDisappeared;
        }
Пример #4
0
    private DataOperator() {
		waitSend.Reset ();
		comInstance = Communication.GetInstance ();

        comInstance.Initial(Statics.netType, Statics.ServerIpAddress, Statics.ServerPort);

		comInstance.AddNetworkListeners (comInstance_OnNetworkConnected, 
		                                 comInstance_OnDataSent,
		                                 comInstance_OnDataReceived,
		                                 comInstance_OnNetworkError);
        comInstance.Connect();
    }
Пример #5
0
        public void CanUseMediator()
        {
            var helloWorld = "Hello world";
            var left = new User("Robert");
            var right = new User("Luc");

            var com = new Communication(left, right);
            com.Say(helloWorld);

            Assert.AreEqual(string.Format("{0} says {1} to {2}", com.Left.Name, helloWorld, right.Name)
                , left.Message);
        }
        public BasemeterComThread(string portName, CommunicationPort port, int baudRate = 921600)
        {
            this.portName = portName;
            this.baudRate = baudRate;
            this.port = port;
            this.logger = LogManager.GetLogger(this.portName);

            // initialize bus communication
            this.communication = new Communication(new NLogLogger());
            this.communication.DeviceDiscovered += OnDeviceDiscovered;
            this.communication.DeviceDisappeared += OnDeviceDisappeared;
        }
Пример #7
0
        //static bool _continue;
        //static SerialPort _serialPort;
        //static bool _replyreceived;

        static void Main(string[] args)
        {
            if (args.Length == 0)
            {
                Console.WriteLine("usage: PlotterCoppy filename [COMx]");
                return;
            }

            string com = "COM6";

            if (args.Length < 2)
                com = args[1];

            Communication communication = new Communication();
            communication.CommandSend += new Communication.CommandEventHandler(CommandSend);
            communication.CommandError += new Communication.CommandEventHandler(CommandError);
            communication.SendFile(args[0],com);
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (words.Length != 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp( ));
                return(false);
            }
            bool small;
            bool large;

            switch (words[0].ToLower( ))
            {
            case "small":
                small = true;
                large = false;
                break;

            case "large":
                small = false;
                large = true;
                break;

            case "all":
                small = true;
                large = true;
                break;

            default:
                Communication.SendPrivateInformation(userId, GetHelp( ));
                return(false);
            }

            var ents  = MyEntities.GetEntities( ).ToArray( );
            int count = 0;

            foreach (var ent in ents)
            {
                var grid = ent as MyCubeGrid;
                if (grid == null)
                {
                    continue;
                }

                if (grid.Physics == null || grid.IsStatic)
                {
                    continue;
                }

                if ((grid.GridSizeEnum == MyCubeSize.Large && large) || (grid.GridSizeEnum == MyCubeSize.Small && small))
                {
                    Wrapper.BeginGameAction(() =>
                    {
                        grid.Physics.ClearSpeed( );
                        grid.RequestConversionToStation( );
                    });
                    Essentials.Log.Info($"Converted {grid.DisplayName} to static");
                    count++;
                }
            }
            Communication.SendPrivateInformation(userId, $"Converted {count} grids to static");
            return(true);
        }
        private void CheckPlayerInDockingZone(IMyPlayer player)
        {
            if (player.Controller == null || player.Controller.ControlledEntity == null || player.Controller.ControlledEntity.Entity == null)
            {
                return;
            }

            IMyEntity entity   = player.Controller.ControlledEntity.Entity;
            long      playerId = player.PlayerID;
            IMyEntity parent   = entity.GetTopMostParent();

            // Not a ship?  let's not process
            if (!(parent is IMyCubeGrid))
            {
                if (m_playersInside.Contains(playerId))
                {
                    m_playersInside.Remove(playerId);
                    ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId);
                    Communication.Notification(steamId, MyFontEnum.DarkBlue, 7, "You have exited a ship in a docking zone");
                }

                return;
            }

            // Get All ships with 500m
            BoundingSphereD  sphere         = new BoundingSphereD(parent.GetPosition(), 500);
            List <IMyEntity> nearByEntities = null;

            // Live dangerously (no wrapper for speed!)
            try
            {
                nearByEntities = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);
            }
            catch (Exception ex)
            {
                Logging.WriteLineAndConsole(string.Format("CheckPlayerInDockingZone(): {0}", ex.ToString()));
                return;
            }

            if (nearByEntities == null)
            {
                return;
            }

            List <IMyEntity> nearByGrids = nearByEntities.FindAll(x => x is IMyCubeGrid);

            // See if player's ship is inside a docking zone
            foreach (IMyEntity nearByEntity in nearByGrids)
            {
                // Sanity Check
                if (!(nearByEntity is IMyCubeGrid))
                {
                    return;
                }

                IMyCubeGrid cubeGrid = (IMyCubeGrid)nearByEntity;
                // Does this grid contain a docking zone?
                if (m_zoneCache.Contains(cubeGrid))
                {
                    Dictionary <String, List <IMyCubeBlock> > zoneList = DockingZone.GetZonesInGrid(cubeGrid);
                    if (zoneList == null)
                    {
                        continue;
                    }

                    // Get zones
                    foreach (KeyValuePair <String, List <IMyCubeBlock> > p in zoneList)
                    {
                        // Check if we're inside
                        if (DockingZone.IsGridInside((IMyCubeGrid)parent, p.Value))
                        {
                            if (!m_playersInside.Contains(playerId))
                            {
                                m_playersInside.Add(playerId);
                                ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId);
                                Communication.Notification(steamId, MyFontEnum.Green, 7, string.Format("You are inside a valid docking zone: {0}", p.Key));
                            }

                            return;
                        }
                    }
                }
            }

            // We've left
            if (m_playersInside.Contains(playerId))
            {
                m_playersInside.Remove(playerId);
                ulong steamId = PlayerMap.Instance.GetSteamIdFromPlayerId(playerId);
                Communication.Notification(steamId, MyFontEnum.Red, 7, "You have left a docking zone");
            }
        }
Пример #10
0
        private static DeepBlue.Models.Entity.UnderlyingFund GetUnderlyingFundFromBlue(C7_10tblGPPaymentInstructions blueUFund, out Address fundRegisteredOffice)
        {
            DeepBlue.Models.Entity.UnderlyingFund uf = new DeepBlue.Models.Entity.UnderlyingFund();
            uf.EntityID = Globals.DefaultEntityID;
            // ToDO: IssuerID
            uf.FundName = blueUFund.Fund;
            uf.FundTypeID = GetFundType(blueUFund.FundType);
            uf.IsFeesIncluded = blueUFund.FeesInside.HasValue ? blueUFund.FeesInside.Value : false;
            uf.VintageYear = blueUFund.VintageYear.HasValue ? (short?)blueUFund.VintageYear : null;
            // TODO: Convert FundSize to money in DB and re-gen the model
            try {
                uf.TotalSize = Convert.ToInt32(blueUFund.FundSize);
            } catch {
                uf.TotalSize = Int32.MaxValue;
            }
            if (blueUFund.TerminationDate.HasValue) {
                uf.TerminationYear = Convert.ToInt16(blueUFund.TerminationDate.Value.Year);
            }

            // WARNING: these fields are present in blue but absent in deepblue
            // What are these fields used for in blue?
            //blueUFund.Website;
            uf.GeographyID = Globals.Geograpies.First().GeographyID;
            // WARNING: We dont use the InvestmentTypeID. Do we really need this?
            // uf.InvestmentTypeID
            // ShareClass type can be added via the admin screen. However, we dont ask for it when creating a new UF. Should we not ask for it?
            // uf.ShareClassType
            // We dont use this field,a s there is no UI element for it.
            // uf.FundStructureID
            uf.WebUserName = blueUFund.WebLogin;
            uf.WebPassword = blueUFund.WebPassword;

            uf.IndustryID = GetIndustryFocus(blueUFund.Industry_Focus);
            uf.ReportingFrequencyID = GetReportingFrequency(blueUFund.Reporting);
            uf.ReportingTypeID = GetReportingType(blueUFund.ReportingType);
            uf.Description = Globals.DefaultString + blueUFund.Comments ?? string.Empty;
            // description cannot be over 100 characters
            if (uf.Description.Length > 100) {
                uf.Description = uf.Description.Substring(0, 100);
            }

            Contact contact = new Contact();
            contact.ContactName = blueUFund.ContactName;
            if (!string.IsNullOrEmpty(blueUFund.Phone)) {
                Communication comm = new Communication() { CommunicationTypeID = (int)DeepBlue.Models.Admin.Enums.CommunicationType.WorkPhone, CommunicationValue = blueUFund.Phone };
                contact.ContactCommunications.Add(new ContactCommunication() { Communication = comm });
            }
            if (!string.IsNullOrEmpty(blueUFund.Email_address)) {
                Communication comm = new Communication() { CommunicationTypeID = (int)DeepBlue.Models.Admin.Enums.CommunicationType.Email, CommunicationValue = blueUFund.Email_address };
                contact.ContactCommunications.Add(new ContactCommunication() { Communication = comm });
            }
            if (!string.IsNullOrEmpty(contact.ContactName)) {
                uf.UnderlyingFundContacts.Add(new UnderlyingFundContact() { Contact = contact });
            }

            //uf.FundRegisteredOfficeID
            // TODO: use uf.FundRegisteredOfficeID to store the address
            // This is the Fund's registered office address, and not the contact's address
            Address address = null;
            if (!string.IsNullOrEmpty(blueUFund.MailingAddress1) || !string.IsNullOrEmpty(blueUFund.MailingAddress2)) {
                address = new Address();
                if (!string.IsNullOrEmpty(blueUFund.MailingAddress1)) {
                    address.Address1 = blueUFund.MailingAddress1;
                } else {
                    address.Address1 = Globals.DefaultStringValue;
                }

                // Address 1 has to be less than or equal to 40 characters
                if (address.Address1.Length > 40) {
                    address.Address1 = address.Address1.Substring(0, 40);
                }

                address.Address2 = blueUFund.MailingAddress2;
                // Address 2 has to be less than or equal to 40 characters
                if (!string.IsNullOrEmpty(address.Address2) && address.Address2.Length > 40) {
                    address.Address2 = address.Address2.Substring(0, 40);
                }
                //string[] parts = new string[3];
                //if (Util.ParseAddress(address.Address2, out parts)) {
                //    address.City = parts[0];
                //    address.State = Globals.States.Where(x => x.Abbr == parts[1].ToUpper().Trim()).First().StateID;
                //    address.PostalCode = parts[2];
                //}
                Util.SetAddress(address.Address2, address);

                address.AddressTypeID = (int)DeepBlue.Models.Admin.Enums.AddressType.Work;
                address.Country = Globals.DefaultCountryID;
            } else {
                // We have to have the address.. The UI enforces us to have an address
                address = new Address();
                address.Address1 = Globals.DefaultAddress1;
                address.AddressTypeID = (int)DeepBlue.Models.Admin.Enums.AddressType.Work;
                address.City = Globals.DefaultCity;
                address.State = Globals.DefaultStateID;
                address.PostalCode = Globals.DefaultZip;
                address.Country = Globals.DefaultCountryID;
                messageLog.AppendLine("WARNING: " + uf.FundName + " doesnt have an address, so using default address");
            }

            fundRegisteredOffice = address;
            // You have to have an account# for a successful account to be created
            if (!string.IsNullOrEmpty(blueUFund.AccountNumber)) {
                Account account = new Account();
                account.BankName = blueUFund.Bank;
                try {
                    account.Routing = Convert.ToInt32(blueUFund.ABANumber.Replace("-", string.Empty).Replace(" ", string.Empty));
                } catch {
                    account.Routing = 111000025;
                }
                account.AccountOf = blueUFund.Accountof;
                if (!string.IsNullOrEmpty(blueUFund.AccountNumber)) {
                    account.Account1 = blueUFund.AccountNumber;
                } else {
                    account.Account1 = "dummy_account";
                }
                account.Attention = blueUFund.Attn;
                account.Reference = blueUFund.Reference;
                uf.Account = account;
            }

            // WARNING: the following fields are present in DeepBlue, but are not present in Blue
            //uf.LegalFundName
            uf.LegalFundName = uf.FundName;
            //uf.FiscalYearEnd
            //uf.IsDomestic
            //uf.FundStructureId
            //uf.Taxable
            //uf.Exempt
            //uf.AddressID
            //uf.managementfee
            //uf.incentivefee
            //uf.taxrate
            //uf.auditorname
            //uf.managercontactid
            //uf.shareclasstypeid
            //uf.investmenttypeid
            //account.Phone;
            //account.Fax;
            //account.IBAN;
            //account.FFC;
            //account.FFCNumber;
            //account.SWIFT;
            //account.AccountNumberCash
            return uf;
        }
Пример #11
0
        private void AddRecepients(Communication communication, bool sendParents)
        {
            //List to keep from sending multiple messages
            List <int> addedIds = new List <int>();

            if (!string.IsNullOrWhiteSpace(hfCommunication.Value))
            {
                //For adding a single person from the roster
                var member = memberData.Where(m => m.Id == hfCommunication.Value.AsIntegerOrNull()).FirstOrDefault();
                if (member != null)
                {
                    if (member.IsParent || !sendParents)
                    {
                        if (!addedIds.Contains(member.Id))
                        {
                            //Add person to Communication
                            var communicationRecipient = new CommunicationRecipient();
                            communicationRecipient.PersonAliasId = member.PersonAliasId;
                            communication.Recipients.Add(communicationRecipient);
                            addedIds.Add(member.Id);
                        }
                    }
                    else
                    {
                        //Add parents to communication
                        foreach (Person parent in member.Parents)
                        {
                            if (!addedIds.Contains(parent.Id))
                            {
                                var communicationRecipient = new CommunicationRecipient();
                                communicationRecipient.PersonAliasId = parent.PrimaryAliasId ?? parent.Id;
                                communication.Recipients.Add(communicationRecipient);
                                addedIds.Add(parent.Id);
                            }
                        }
                    }
                }
                //clear the value we are done
                hfCommunication.Value = "";
            }
            else
            {
                var keys = gMembers.SelectedKeys;

                List <MemberData> members = new List <MemberData>();

                foreach (int key in keys)
                {
                    members.Add(memberData.Where(md => md.Id == key).FirstOrDefault());
                }

                if (!members.Any())
                {
                    FilterData();
                    members = memberData;
                }
                //For adding the communication recepients from the membership list
                foreach (var member in members)
                {
                    member.LoadParents();
                    if (member.IsParent || !sendParents)
                    {
                        if (!addedIds.Contains(member.Id))
                        {
                            //Add person to Communication
                            var communicationRecipient = new CommunicationRecipient();
                            communicationRecipient.PersonAliasId = member.PersonAliasId;
                            communication.Recipients.Add(communicationRecipient);
                            addedIds.Add(member.Id);
                        }
                    }
                    else
                    {
                        //Add parents to communication
                        foreach (Person parent in member.Parents)
                        {
                            if (!addedIds.Contains(parent.Id))
                            {
                                var communicationRecipient = new CommunicationRecipient();
                                communicationRecipient.PersonAliasId = parent.PrimaryAliasId ?? parent.Id;
                                communication.Recipients.Add(communicationRecipient);
                                addedIds.Add(parent.Id);
                            }
                        }
                    }
                }
            }
        }
Пример #12
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            bool showConcealed = true;

            if (words.Length > 0 && words[0].ToLower() == "revealed")
            {
                showConcealed = false;
            }

            if (showConcealed)
            {
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
                //Wrapper.GameAction(() =>
                //{
                MyAPIGateway.Entities.GetEntities(entities);
                //});

                Communication.SendPrivateInformation(userId, "==== Concealed Entities ===");
                int count = 0;
                foreach (IMyEntity entity in entities)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entity.InScene)
                    {
                        continue;
                    }

                    IMyCubeGrid grid      = (IMyCubeGrid)entity;
                    long        ownerId   = 0;
                    string      ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId   = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition())));
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total concealed entities: {0}", count));
            }
            else
            {
                HashSet <IMyEntity> entities = new HashSet <IMyEntity>();
                Wrapper.GameAction(() =>
                {
                    MyAPIGateway.Entities.GetEntities(entities);
                });

                Communication.SendPrivateInformation(userId, "==== Revealed Entities ===");
                Communication.SendPrivateInformation(userId, "==== Unconnected Entities ===");
                HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>();
                CubeGrids.GetGridsUnconnected(entitiesFound, entities);
                int count = 0;
                List <IMySlimBlock> slimBlocks = new List <IMySlimBlock>();
                foreach (IMyEntity entity in entitiesFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    IMyCubeGrid grid      = (IMyCubeGrid)entity;
                    long        ownerId   = 0;
                    string      ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId   = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total unconnected revealed entities: {0}", count));

                Communication.SendPrivateInformation(userId, "==== Connected Entities ===");
                HashSet <IMyEntity> connectedFound = new HashSet <IMyEntity>();
                CubeGrids.GetConnectedGrids(connectedFound);
                Console.WriteLine("Here: {0} : {1} {2}", connectedFound.Intersect(entitiesFound).Count(), entitiesFound.Count, connectedFound.Count);
                count = 0;
                slimBlocks.Clear();
                foreach (IMyEntity entity in connectedFound)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    if (entitiesFound.Contains(entity))
                    {
                        continue;
                    }

                    if (!entity.InScene)
                    {
                        continue;
                    }

                    if (CubeGrids.GetRecursiveGridList((IMyCubeGrid)entity).Count < 2)
                    {
                        continue;
                    }

                    IMyCubeGrid grid      = (IMyCubeGrid)entity;
                    long        ownerId   = 0;
                    string      ownerName = "";
                    if (grid.BigOwners.Count > 0)
                    {
                        ownerId   = grid.BigOwners.First();
                        ownerName = PlayerMap.Instance.GetPlayerItemFromPlayerId(ownerId).Name;
                    }

                    if (ownerName == "")
                    {
                        ownerName = "No one";
                    }

                    grid.GetBlocks(slimBlocks, null);
                    Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count, CubeGrids.GetRecursiveGridList(grid).Count));
                    //Communication.SendPrivateInformation(userId, string.Format("Id: {0} Display: {1} OwnerId: {2} OwnerName: {3} Position: {4} BlockCount: {5} Connections: {6}", entity.EntityId, entity.DisplayName, ownerId, ownerName, General.Vector3DToString(entity.GetPosition()), slimBlocks.Count));
                    slimBlocks.Clear();
                    count++;
                }

                Communication.SendPrivateInformation(userId, string.Format("Total connected revealed entities: {0}", count));
            }

            return(true);
        }
Пример #13
0
        public PacketHandlers()
        {
            setPacketSizes();
            PacketHandler temp;

            temp = new ActionButton();
            handlers.Add(PacketId.CLOSE, temp); //Close
            handlers.Add(PacketId.ACTIONBUTTON, temp); //Actionbutton #1
            handlers.Add(PacketId.ACTIONBUTTON2, temp); //Actionbutton #2
            handlers.Add(PacketId.ACTIONBUTTON3, temp); //Actionbutton #3

            temp = new ClientAction();
            handlers.Add(PacketId.IDLE, temp); //Idle
            handlers.Add(PacketId.MOVE_CAMERA, temp); //Move camera
            handlers.Add(PacketId.PING, temp); //Ping
            handlers.Add(PacketId.FOCUS, temp); //Window focus
            handlers.Add(PacketId.CLICK_MOUSE, temp); //Mouse
            handlers.Add(PacketId.WINDOW_TYPE, temp); //Window type
            handlers.Add(PacketId.SOUND_SETTINGS, temp); //Toggle sound (sounds)

            temp = new Command();
            handlers.Add(PacketId.COMMAND, temp); //Commands

            temp = new Communication();
            handlers.Add(PacketId.ADD_FRIEND, temp); //Add friend
            handlers.Add(PacketId.DELETE_FRIEND, temp); //Delete friend
            handlers.Add(PacketId.ADD_IGNORE, temp); //Add ignore
            handlers.Add(PacketId.DELETE_IGNORE, temp); //Delete ignore
            handlers.Add(PacketId.SEND_PM, temp); //Send PM
            handlers.Add(PacketId.CLAN_RANKS, temp); //Set clan ranks
            handlers.Add(PacketId.CLAN_CHAT, temp); //Join clan chat
            handlers.Add(PacketId.PUBLIC, temp); //Public chat
            handlers.Add(PacketId.CLAN_KICK, temp); //Clan chat kick
            handlers.Add(PacketId.PRIVACY_SETTINGS, temp); //public/private/trade chat settings

            temp = new Walk();
            handlers.Add(PacketId.WALK_1, temp); //Walk
            handlers.Add(PacketId.WALK_2, temp); //Walk
            handlers.Add(PacketId.WALK_3, temp); //Walk

            temp = new PlayerInteract();
            handlers.Add(PacketId.ATTACK_PLAYER, temp); //Attack
            handlers.Add(PacketId.FOLLOW, temp); //Follow
            handlers.Add(PacketId.TRADE, temp); //Trade
            handlers.Add(PacketId.MAGIC_ON_PLAYER, temp); //Magic on player

            temp = new NPCInteract();
            handlers.Add(PacketId.NPC_FIRST_CLICK, temp); //Attack
            handlers.Add(PacketId.NPC_SECOND_CLICK, temp); //Second click
            handlers.Add(PacketId.NPC_THIRD_CLICK, temp); //Third click
            handlers.Add(PacketId.NPC_FOURTH_CLICK, temp); //Fourth click
            handlers.Add(PacketId.NPC_FIFTH_CLICK, temp); //Fifth click
            handlers.Add(PacketId.NPC_EXAMINE, temp); //Examine Npc
            handlers.Add(PacketId.MAGIC_ON_NPC, temp); //Magic on NPC
            handlers.Add(PacketId.ITEM_ON_NPC, temp); //Item on NPC

            temp = new ObjectInteract();
            handlers.Add(PacketId.OBJECT_FIRST_CLICK, temp); //First click
            handlers.Add(PacketId.OBJECT_SECOND_CLICK, temp); //Second click
            handlers.Add(PacketId.OBJECT_THIRD_CLICK, temp); //Third click
            handlers.Add(PacketId.OBJECT_FOURTH_CLICK, temp); //Fourth click
            handlers.Add(PacketId.OBJECT_EXAMINE, temp); //object examine

            temp = new ItemInteract();
            handlers.Add(PacketId.EQUIP, temp); //Equip item
            handlers.Add(PacketId.ITEM_ON_ITEM, temp); //Item used on item
            handlers.Add(PacketId.INV_CLICK, temp); //Inventory click item
            handlers.Add(PacketId.ITEM_ON_OBJECT, temp); //Item used on object
            handlers.Add(PacketId.ITEM_ON_GROUND_ITEM, temp); //Item used on ground item.
            handlers.Add(PacketId.INV_OPERATE, temp); //Operate option
            handlers.Add(PacketId.INV_DROP, temp); //Drop item
            handlers.Add(PacketId.PICKUP, temp); //Pick up item
            handlers.Add(PacketId.INV_SWAP_SLOT, temp); //Swap item slot 1
            handlers.Add(PacketId.INV_SWAP_SLOT2, temp); //Swap item slot 2
            handlers.Add(PacketId.INV_RIGHT_CLICK_OPTION1, temp); //Right click option 1
            handlers.Add(PacketId.INV_RIGHT_CLICK_OPTION2, temp); //Right click option 2
            handlers.Add(PacketId.INV_EXAMINE_ITEM, temp); //Inventory item examine

            temp = new InterfaceOptions();
            handlers.Add(PacketId.ENTER_AMOUNT, temp); //Enter amount
            handlers.Add(PacketId.ENTER_TEXT, temp); // Enter text
            handlers.Add(PacketId.INTERFACE_CLICK_1, temp); //Option 1
            handlers.Add(PacketId.INTERFACE_CLICK_2, temp); //Option 2
            handlers.Add(PacketId.INTERFACE_CLICK_3, temp); //Option 3
            handlers.Add(PacketId.INTERFACE_CLICK_4, temp); //Option 4
            handlers.Add(PacketId.INTERFACE_CLICK_5, temp); //Option 5
            handlers.Add(PacketId.INTERFACE_CLICK_6, temp); //Option 6
            handlers.Add(PacketId.INTERFACE_CLICK_7, temp); //Option 7
            handlers.Add(PacketId.INTERFACE_CLICK_8, temp); //Option 8
            handlers.Add(PacketId.INTERFACE_CLICK_9, temp); //Option 9
            handlers.Add(PacketId.INTERFACE_CLICK_10, temp); //Option 9
            handlers.Add(PacketId.GE_SEARCH, temp); //Grand exchange search

            temp = new Unused();
            handlers.Add(PacketId.REIGON_LOADING, temp); //Region loading, varied size
            handlers.Add(PacketId.PACKET_COUNT, temp); //Sent after any click which increases 'count' in getPackets
            handlers.Add(PacketId.CLIENT_VARIABLE_30, temp); //Sent if a client variable is 30..unknown
            handlers.Add(PacketId.DODGY_PACKET, temp); //Caused by a dodgy packet

            Console.WriteLine("Binded packetHandlers");
        }
Пример #14
0
 //Modifier communication Entreprise
 static public bool modifierCommunicationEntrepriseUtilisateur(Communication communication)
 {
     return(RequeteCommunication.modifierCommunicationEntrepriseUtilisateur(communication));
 }
Пример #15
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitPlaygroundResponseState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.PlaygroundResponseMessage) {
                var pr_msg = msg as Communication.JSON.PlaygroundResponseMessage;
                Log.WriteInfo(Log.Verbosity.Normal, "Playground was received.");
                Log.WriteGame(Log.Verbosity.Normal, "Enemy Playground: " + pr_msg.PlayGround.GetShort());

                //Set playground
                Algorithm.SetEnemyPlayground(pr_msg.PlayGround);

                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitGoodbyeResponseState,
                    new Communication.JSON.GoodbyeRequestMessage());
            } else
                return null;
        }
Пример #16
0
 //Ajouter communication Etudiant
 static public void ajouterCommunicationEtudiantUtilisateur(Communication communication)
 {
     RequeteCommunication.ajouterCommunicationEtudiantUtilisateur(communication);
 }
Пример #17
0
 //Modifier communication Etudiant
 static public bool modifierCommunicationEtudiantUtilisateur(Communication communication)
 {
     return(RequeteCommunication.modifierCommunicationEtudiantUtilisateur(communication));
 }
Пример #18
0
 //Ajouter communication entreprise
 static public void ajouterCommunicationEntrepriseUtilisateur(Communication communication)
 {
     RequeteCommunication.ajouterCommunicationEntrepriseUtilisateur(communication);
 }
Пример #19
0
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.WaypointsEnabled)
            {
                return(false);
            }

            Communication.SendPrivateInformation(userId, "Personal / Faction Waypoints:");
            int personalCount = 0;
            int factionCount  = 0;

            List <WaypointItem> items = Waypoints.Instance.Get(userId);
            string waypoints          = "";

            foreach (WaypointItem item in items.OrderBy(x => x.Group))
            {
                if (waypoints != "")
                {
                    waypoints += "\r\n";
                }

                if (item.Group != null && item.Group != "")
                {
                    waypoints += string.Format("Group {3} - {0}: '{1}' : {2}", item.Name, item.Text, General.Vector3DToString(item.Position), item.Group);
                }
                else
                {
                    waypoints += string.Format("{0}: '{1}' : {2}", item.Name, item.Text, General.Vector3DToString(item.Position));
                }
            }
            personalCount = items.Count;

            long       playerId = PlayerMap.Instance.GetFastPlayerIdFromSteamId(userId);
            IMyFaction faction  = MyAPIGateway.Session.Factions.TryGetPlayerFaction(playerId);

            if (faction != null)
            {
                items = Waypoints.Instance.Get((ulong)faction.FactionId);
                if (waypoints != "" && items.Count > 0)
                {
                    waypoints += "\r\n";
                }

                foreach (WaypointItem item in items.OrderBy(x => x.Group))
                {
                    if (waypoints != "")
                    {
                        waypoints += "\r\n";
                    }

                    if (item.Group != null && item.Group != "")
                    {
                        waypoints += string.Format("F: Group {3} - {0}: '{1}' : {2}", item.Name, item.Text, General.Vector3DToString(item.Position), item.Group);
                    }
                    else
                    {
                        waypoints += string.Format("F: {0}: '{1}' : {2}", item.Name, item.Text, General.Vector3DToString(item.Position));
                    }
                }

                factionCount = items.Count;
            }

            if (waypoints != "")
            {
                waypoints += "\r\n";
            }

            Communication.DisplayDialog(userId, "Waypoints", string.Format("Your defined waypoints: {0} personal, {1} faction", personalCount, factionCount), waypoints);

            waypoints += string.Format("Your defined waypoints: {0} personal, {1} faction", personalCount, factionCount);
            Communication.SendPrivateInformation(userId, waypoints);


            return(true);
        }
        private static bool copyOutgoingDatabase(Application inFromApplication,
                                                 Application inToApplication,
                                                 string directionType,
                                                 string communicationType)
        {
            try
            {
                int toApplicationIdentity   = inFromApplication.id;
                int fromApplicationIdentity = inToApplication.id;
                // get all applications
                List <Configuration> applicationList = ConfigurationDAO.GetApplications(new Application()
                {
                    id = fromApplicationIdentity
                });

                // get all communuication and direction Types
                Configuration masterConfigration = ConfigurationDAO.GetAllConfigurations();

                // get the specific application direction and comm you want
                Configuration fromApplication = applicationList.Find(a => a.communicationType.name == communicationType &&
                                                                     a.directionType.name == directionType);


                // communication translation identities
                int toDirectionTypeId =
                    masterConfigration.directionTypes.Find(d => d.name == fromApplication.directionType.name).id;
                int toCommunicationTypeId =
                    masterConfigration.communicationTypes.Find(c => c.name == fromApplication.communicationType.name).id;

                // create a new application object with your current application identity
                Application toApplication = new Application()
                {
                    id = toApplicationIdentity
                };

                // insert a new communication with your exsisting application
                Communication toCommunication =
                    CommunicationDAO.PostUpdate(new Communication()
                {
                    applicationId       = toApplication.id,
                    communicationTypeId = toCommunicationTypeId,
                    directionTypeId     = toDirectionTypeId
                });


                // get the database_instance information (credential id, name, server, ip) of the communication identity.
                DatabaseInstance fromDatabaseInstance =
                    masterConfigration.databaseInstances.Find(i => i.communicationId == fromApplication.communication.id);

                // get database_instance id of the copy from insert into new database_instance with info prior step
                DatabaseInstance toDatabaseInstance = new DatabaseInstance();

                // copy individual values as not top copy the reference (we need it later)
                toDatabaseInstance = fromDatabaseInstance.ShallowCopy();

                // override the communication id w/ the "to" communication id
                toDatabaseInstance.id = 0;
                toDatabaseInstance.communicationId = toCommunication.id;
                // insert new database instance - get the id from this request
                toDatabaseInstance = DatabaseInstanceDAO.PostUpdate(toDatabaseInstance);

                // get all database tables from the fromDatabaseInstance
                List <Configuration> fromDatabaseTables = ConfigurationDAO.GetDatabaseTables(fromDatabaseInstance);

                // get the database table relations
                List <DatabaseTableRelation> databaseTableRelations = masterConfigration.databaseTableRelations;

                // create a new database relation object
                DatabaseTableRelation databaseTableRelation = new DatabaseTableRelation()
                {
                    id = 0,
                    requiresIdentity      = true,
                    sourceDatabaseTableId = -1,
                    targetDatabaseTableId = -1
                };

                // foreach table that belongs to the from database_instance, get the from database_table information
                fromDatabaseTables.ForEach(delegate(Configuration configurationTable)
                {
                    // extract the database table from the configuration
                    DatabaseTable fromDatabaseTable = new DatabaseTable()
                    {
                        id = configurationTable.databaseTable.id,
                        databaseInstanceId = fromDatabaseInstance.id,
                        name = configurationTable.databaseTable.name
                    };

                    // create new database table
                    DatabaseTable toDatabaseTable = new DatabaseTable()
                    {
                        databaseInstanceId = toDatabaseInstance.id,
                        name = fromDatabaseTable.name
                    };

                    // insert new table into database_table with fromDatabaseTable information but use toDatabaseInstanceId
                    toDatabaseTable = DatabaseTableDAO.PostUpdate(toDatabaseTable);

                    // check for prior source relation
                    if (ConfigurationUtility.IsDatabaseTableRelation(configurationTable.databaseTable, databaseTableRelations))
                    {
                        databaseTableRelation.sourceDatabaseTableId = toDatabaseTable.id;
                    }

                    // check for prior target relation
                    if (ConfigurationUtility.IsDatabaseTableRelation(configurationTable.databaseTable, databaseTableRelations, true))
                    {
                        databaseTableRelation.targetDatabaseTableId = toDatabaseTable.id;
                    }

                    // based on the fromDatabaseTable get all column sets
                    List <Configuration> fromColumnSets = ConfigurationDAO.GetDatabaseColumns(fromDatabaseTable);

                    // foreach columnset that belongs to fromDatabaseColumn copy all information (except for the fromDatabaseTableId)
                    fromColumnSets.ForEach(delegate(Configuration configurationColumnSet)
                    {
                        // define the column set
                        ColumnSet fromColumnSet = new ColumnSet();
                        ColumnSet toColumnSet   = new ColumnSet();

                        // get the column set from the configuration list
                        fromColumnSet = configurationColumnSet.columnSet;
                        fromColumnSet.databaseTableId = configurationColumnSet.databaseTable.id;

                        // do a shallow copy of its properties and override the ones you need
                        toColumnSet    = fromColumnSet.ShallowCopy();
                        toColumnSet.id = 0;
                        toColumnSet.databaseTableId = toDatabaseTable.id;

                        // insert new toColumnSet using new toDAtabaseTable.id
                        toColumnSet = ColumnSetDAO.PostUpdate(toColumnSet);
                    });
                });

                // if relation source or target is not negative one - insert new relation
                if (databaseTableRelation.sourceDatabaseTableId != -1 &&
                    databaseTableRelation.targetDatabaseTableId != -1)
                {
                    databaseTableRelation = DatabaseTableRelationDAO.PostUpdate(databaseTableRelation);
                }
            }
            catch (Exception ex)
            {
                string fromApplicationId = inFromApplication.id.ToString();
                string toApplicationId   = inToApplication.id.ToString();
                ErrorLogger.LogError(ex,
                                     "CopyConfigurationUtility.CopyOutgoingDatabase(fromApplication, toApplication, directionType,communicationType)",
                                     fromApplicationId + "|" +
                                     toApplicationId + "|" +
                                     directionType + "|" +
                                     communicationType);

                return(false);
            }

            return(true);
        }
Пример #21
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitHandshakeResponseState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.HandshakeResponseMessage) {
                var hsr_msg = msg as Communication.JSON.HandshakeResponseMessage;
                Log.WriteInfo(Log.Verbosity.Normal, "Handshake Response received from ");
                Log.WriteInfo(Log.Verbosity.Important, hsr_msg.ClientName);
                Log.WriteInfo(Log.Verbosity.Important, "Algorithm: " + hsr_msg.Algorithm);
                Log.WriteInfo(Log.Verbosity.Normal, "Greeting: " + hsr_msg.Greeting);

                Algorithm.SetEnemyAlgorithmName(hsr_msg.Algorithm);

                Log.WriteInfo(Log.Verbosity.Normal, "Sending GameConfigRequest.");
                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitGameConfigResponseState,
                    new Communication.JSON.GameConfigMessageRequest(Algorithm.GetPreferredRuleSet()));
            } else
                return null;
        }
Пример #22
0
 //Supprimer communication etudiant
 static public void supprimerCommunicationEtudiantUtilisateur(Communication communication)
 {
     RequeteCommunication.supprimerCommunicationEtudiantUtilisateur(communication);
 }
Пример #23
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitHashedPlaygroundResponseState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.HashedPlaygroundResponseMessage) {
                var hpr_msg = msg as Communication.JSON.HashedPlaygroundResponseMessage;
                Log.WriteInfo(Log.Verbosity.Normal, "Hashed Playground was received: " + hpr_msg.HashCode);

                //Set enemy playground-hash
                Algorithm.SetEnemyPlaygroundHash(hpr_msg.HashCode);

                var shoots = Algorithm.GetShoots();

                if (shoots.Any())
                    return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                        WaitHitListState,
                        new Communication.JSON.ShootListMessage(shoots));
                else {
                    Log.WriteInfo(Log.Verbosity.Important, "Giving up.");
                    return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                        m => null,
                        new Communication.JSON.DefeatMessage(Algorithm.GetDefeatReason(), Algorithm.GetDefeatWhining())
                        );
                }
            } else
                return null;
        }
Пример #24
0
 //Supprimer communication entreprise
 static public void supprimerCommunicationEntrepriseUtilisateur(Communication communication)
 {
     RequeteCommunication.supprimerCommunicationEntrepriseUtilisateur(communication);
 }
Пример #25
0
        protected override Response GetLoopData()
        {
            try
            {
                _config = Communication.GetResponse("/management/index.php?sub=requestClientInfo&configure");
                var promptTime = SandBoxParse(_config, "promptTime", MIN_PROMPT, MAX_PROMPT, MIN_PROMPT);
                Settings.Set("PromptTime", promptTime.ToString());

                Settings.Set("Company", _config.GetField("company"));
                Settings.Set("Color", _config.GetField("color"));
                var idealHash = _config.GetField("bannerHash").ToUpper();
                Settings.Set("BannerHash", idealHash);

                var bannerURL  = _config.GetField("bannerURL");
                var bannerFile = Path.Combine(Settings.Location, "banner.png");
                if (!string.IsNullOrEmpty(bannerURL))
                {
                    // Check the hash to see if we need to re-download it
                    if (!File.Exists(bannerFile) || !Hash.SHA512(bannerFile).Equals(idealHash, StringComparison.OrdinalIgnoreCase))
                    {
                        Communication.DownloadFile(bannerURL, bannerFile);
                    }
                }
                else
                {
                    File.Delete(bannerFile);
                }
            }
            catch (Exception ex) when(ex is IOException || ex is UnauthorizedAccessException)
            {
                Log.Error(Name, "Failed modify banner image");
                Log.Error(Name, ex);
            }
            catch (Exception ex)
            {
                Log.Error(Name, "Unable to get config data");
                Log.Error(Name, ex);
                _config = null;
            }
            try
            {
                var response = Communication.GetResponse("/management/index.php?sub=requestClientInfo", true);
                // Construct the clientupdater data regardless of encryption
                var srvClientVersion = Communication.GetRawResponse("/service/getversion.php?clientver");
                var srvVersion       = Communication.GetRawResponse("/service/getversion.php");

                var clientUpdaterData = new JObject {
                    ["version"] = srvClientVersion
                };
                response.Data["clientupdater"] = clientUpdaterData;

                Log.NewLine();
                Log.Entry(Name, "Creating user agent cache");
                try
                {
                    Settings.Set("ServerVersion", srvVersion);

                    var alo = response.GetSubResponse("autologout");
                    Settings.Set("ALOTime", (alo == null) ? "0" : alo.GetField("time"));

                    var pDefault = response.GetSubResponse("printermanager");
                    Settings.Set("DefaultPrinter", (pDefault == null) ? "" : pDefault.GetField("default"));

                    var display = response.GetSubResponse("displaymanager");
                    Settings.Set("DisplayX", (display == null || display.Error) ? "" : display.GetField("x"));
                    Settings.Set("DisplayY", (display == null || display.Error) ? "" : display.GetField("y"));
                    Settings.Set("DisplayR", (display == null || display.Error) ? "" : display.GetField("r"));
                }
                catch (Exception ex)
                {
                    Log.Error(Name, "Unable to set user agent cache");
                    Log.Error(Name, ex);
                }

                return(response);
            }
            catch (Exception ex)
            {
                Log.Error(Name, "Unable to get cycle data");
                Log.Error(Name, ex);
            }

            return(new Response());
        }
Пример #26
0
        protected override void DoWork()
        {
            while (true)
            {
                //Get task info
                var taskResponse = Communication.GetResponse("/service/snapins.checkin.php", true);

                //Download the snapin file if there was a response and run it
                if (taskResponse.Error)
                {
                    return;
                }

                Log.Entry(Name, "Snapin Found:");
                Log.Entry(Name, string.Format("    ID: {0}", taskResponse.GetField("JOBTASKID")));
                Log.Entry(Name, string.Format("    RunWith: {0}", taskResponse.GetField("SNAPINRUNWITH")));
                Log.Entry(Name, string.Format("    RunWithArgs: {0}", taskResponse.GetField("SNAPINRUNWITHARGS")));
                Log.Entry(Name, string.Format("    Name: {0}", taskResponse.GetField("SNAPINNAME")));
                Log.Entry(Name, string.Format("    File: {0}", taskResponse.GetField("SNAPINFILENAME")));
                Log.Entry(Name, string.Format("    Created: {0}", taskResponse.GetField("JOBCREATION")));
                Log.Entry(Name, string.Format("    Args: {0}", taskResponse.GetField("SNAPINARGS")));
                Log.Entry(Name, string.Format("    Reboot: {0}", taskResponse.GetField("SNAPINBOUNCE")));

                var snapinFilePath = string.Format("{0}tmp\\{1}", AppDomain.CurrentDomain.BaseDirectory, taskResponse.GetField("SNAPINFILENAME"));

                var downloaded = Communication.DownloadFile(string.Format("/service/snapins.file.php?mac={0}&taskid={1}",
                                                                          Configuration.MACAddresses(), taskResponse.GetField("JOBTASKID")), snapinFilePath);

                var exitCode = "-1";

                //If the file downloaded successfully then run the snapin and report to FOG what the exit code was
                if (downloaded)
                {
                    exitCode = StartSnapin(taskResponse, snapinFilePath);
                    if (File.Exists(snapinFilePath))
                    {
                        File.Delete(snapinFilePath);
                    }

                    Communication.Contact(string.Format("/service/snapins.checkin.php?taskid={0}&exitcode={1}",
                                                        taskResponse.GetField("JOBTASKID"), exitCode), true);

                    if (!taskResponse.GetField("SNAPINBOUNCE").Equals("1"))
                    {
                        if (!Power.ShuttingDown)
                        {
                            //Rerun this method to check for the next snapin
                            continue;
                        }
                    }
                    else
                    {
                        Power.Restart("Snapin requested shutdown", Power.FormOption.Delay,
                                      "This computer needs to reboot to apply new software.");
                    }
                }
                else
                {
                    Communication.Contact(string.Format("/service/snapins.checkin.php?taskid={0}&exitcode={1}",
                                                        taskResponse.GetField("JOBTASKID"), exitCode), true);
                }
                break;
            }
        }
Пример #27
0
        private static DeepBlue.Models.Entity.UnderlyingFund GetUnderlyingFundFromBlue(C7_10tblGPPaymentInstructions blueUFund)
        {
            DeepBlue.Models.Entity.UnderlyingFund uf = new DeepBlue.Models.Entity.UnderlyingFund();
            uf.EntityID = Globals.DefaultEntityID;
            // ToDO: IssuerID
            uf.FundName = blueUFund.Fund;
            uf.FundTypeID = GetFundType(blueUFund.FundType);
            uf.IsFeesIncluded = blueUFund.FeesInside.HasValue ? blueUFund.FeesInside.Value : false;
            uf.VintageYear = blueUFund.VintageYear.HasValue ? (short?)blueUFund.VintageYear : null;
            // TODO: Convert FundSize to money in DB and re-gen the model
            uf.TotalSize = Convert.ToInt32(blueUFund.FundSize);
            if (blueUFund.TerminationDate.HasValue) {
                uf.TerminationYear = Convert.ToInt16(blueUFund.TerminationDate.Value.Year);
            }

            // WARNING: these fields are present in blue but absent in deepblue
            // What are these fields used for in blue?
            //blueUFund.Website;
            //blueUFund.WebLogin;
            //blueUFund.WebPassword;

            uf.IndustryID = GetIndustryFocus(blueUFund.Industry_Focus);
            uf.GeographyID = Globals.Geograpies.First().GeographyID;
            uf.ReportingFrequencyID = GetReportingFrequency(blueUFund.Reporting);
            uf.ReportingTypeID = GetReportingType(blueUFund.ReportingType);
            uf.Description = Globals.DefaultString;

            Contact contact = new Contact();
            contact.ContactName = blueUFund.ContactName;
            if (!string.IsNullOrEmpty(blueUFund.Phone)) {
                Communication comm = new Communication() { CommunicationTypeID = (int)DeepBlue.Models.Admin.Enums.CommunicationType.WorkPhone, CommunicationValue = blueUFund.Phone };
                contact.ContactCommunications.Add(new ContactCommunication() { Communication = comm });
            }

            if (!string.IsNullOrEmpty(blueUFund.Email_address)) {
                Communication comm = new Communication() { CommunicationTypeID = (int)DeepBlue.Models.Admin.Enums.CommunicationType.Email, CommunicationValue = blueUFund.Email_address };
                contact.ContactCommunications.Add(new ContactCommunication() { Communication = comm });
            }

            //uf.FundRegisteredOfficeID
            // TODO: use uf.FundRegisteredOfficeID to store the address
            Address address = new Address();
            address.Address1 = blueUFund.MailingAddress1;
            address.Address2 = blueUFund.MailingAddress2;
            string[] parts = new string[3];
            if (Util.ParseAddress(address.Address2, out parts)) {
                address.City = parts[0];
                address.State = Globals.States.Where(x => x.Abbr == parts[1].ToUpper().Trim()).First().StateID;
                address.PostalCode = parts[2];
            }

            address.AddressTypeID = (int)DeepBlue.Models.Admin.Enums.AddressType.Work;
            address.Country = Globals.DefaultCountryID;
            //ContactAddress contactAddress = new ContactAddress();
            //     contactAddress.Address = address;
            // contact.ContactAddresses.Add(contactAddress);

            Account account = new Account();
            account.BankName = blueUFund.Bank;
            account.Routing = Convert.ToInt32(blueUFund.ABANumber.Replace("-", string.Empty).Replace(" ", string.Empty));
            account.AccountOf = blueUFund.Accountof;
            account.Account1 = blueUFund.AccountNumber;

            account.Attention = blueUFund.Attn;
            account.Reference = blueUFund.Reference;
            // WARNING: the following fields are present in DeepBlue, but are not present in Blue
            //uf.LegalFundName
            //uf.FiscalYearEnd
            //uf.IsDomestic
            //uf.FundStructureId
            //uf.Taxable
            //uf.Exempt
            //uf.AddressID
            //uf.managementfee
            //uf.incentivefee
            //uf.taxrate
            //uf.auditorname
            //uf.managercontactid
            //uf.shareclasstypeid
            //uf.investmenttypeid
            //account.Phone;
            //account.Fax;
            //account.IBAN;
            //account.FFC;
            //account.FFCNumber;
            //account.SWIFT;
            //account.AccountNumberCash

            return uf;
        }
        // /admin movefrom x y z x y z radius
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (words.Count() != 4 && words.Count() != 0)
            {
                return(false);
            }

            if (words.Count() != 4)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            // Test Input
            float test = 0;

            for (int r = 1; r < 4; r++)
            {
                if (!float.TryParse(words[r], out test))
                {
                    Communication.SendPrivateInformation(userId, string.Format("The value at position {0} - '{1}' is invalid.  Please try the command again.", r + 1, words[r]));
                    return(true);
                }
            }

            string   userName      = words[0];
            Vector3D startPosition = new Vector3D(double.Parse(words[1]), double.Parse(words[2]), double.Parse(words[3]));

            if (!Player.Move(userName, startPosition))
            {
                Communication.SendPrivateInformation(userId, string.Format("Unable to move player: {0}", userName));
            }

            /*
             * CharacterEntity charEntity = SectorObjectManager.Instance.GetTypedInternalData<CharacterEntity>().Where(x => x.DisplayName.ToLower() == userName.ToLower() && x.Health > 0).First();
             * CubeGridEntity gridEntity = new CubeGridEntity(new FileInfo(Essentials.PluginPath + "MovePlayer.sbc"));
             * gridEntity.EntityId = BaseEntity.GenerateEntityId();
             * foreach (MyObjectBuilder_CubeBlock block in gridEntity.BaseCubeBlocks)
             * {
             *      // set ownership
             *      if(block is MyObjectBuilder_Cockpit)
             *      {
             *              MyObjectBuilder_Cockpit cockpit = (MyObjectBuilder_Cockpit)block;
             *              cockpit.Pilot = (MyObjectBuilder_Character)charEntity.Export();
             *      }
             * }
             *
             * gridEntity.PositionAndOrientation = new MyPositionAndOrientation(startPosition, Vector3.Forward, Vector3.Up);
             *
             * Wrapper.GameAction(() =>
             * {
             *      MyObjectBuilder_EntityBase baseEntity = gridEntity.Export();
             *      IMyEntity entity = MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(baseEntity);
             *      Type someManager = SandboxGameAssemblyWrapper.Instance.GetAssemblyType(SectorObjectManager.EntityBaseNetManagerNamespace, SectorObjectManager.EntityBaseNetManagerClass);
             *      Wrapper.InvokeStaticMethod(someManager, SectorObjectManager.EntityBaseNetManagerSendEntity, new object[] { entity.GetObjectBuilder() });
             *      gridEntity = new CubeGridEntity((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder(), entity);
             * });
             *
             *
             * int count = 0;
             * while (gridEntity.IsLoading)
             * {
             *      Thread.Sleep(100);
             *      count++;
             *      if (count > 10)
             *              break;
             * }
             *
             * if (gridEntity.IsLoading)
             *      return true;
             *
             * foreach (CubeBlockEntity block in gridEntity.CubeBlocks)
             * {
             *      if(block is CockpitEntity)
             *      {
             *              block.IntegrityPercent = 0.1f;
             *              Log.Info("Removing User From Cockpit");
             *      }
             * }
             *
             * gridEntity.Dispose();
             */

            return(true);
        }
 void temp()
 {
     Communication c = new Communication();
     Thread threadStart = new Thread(new ThreadStart(c.startTread(this)));
 }
Пример #30
0
        private async Task<List<State>> GetRemediationWorkflow()
        {
            var remediationWorkflow = new State(100, "Remediation Workflow", StateType.Root);

            var communication = new Communication()
            {
                Id = 200,
                Name = "Communication"
            };

            var letterSent = new LetterSent()
            {
                Id = 210,
                Name = "Letter Sent"
            };

            var responseReceived = new ResponseReceived()
            {
                Id = 220,
                Name = "Response Received"
            };

            var collateData = new CollateData()
            {
                Id = 300,
                Name = "Collate Data"
            };

            var adjustmentDecision = new AdjustmentDecision()
            {
                Id = 400,
                Name = "Adjustment Decision",
                Type = StateType.Auto
            };

            var adjustment = new Adjustment()
            {
                Id = 500,
                Name = "Adjustment"
            };

            var autoTransitionToRedressReview = new AutoTransitionToRedressReview()
            {
                Id = 600,
                Name = "Auto Transition Redress Review",
                Type = StateType.Auto
            };

            var redressReview = new RedressReview()
            {
                Id = 700,
                Name = "Redress Review"
            };

            var payment = new Payment()
            {
                Id = 800,
                Name = "Payment"
            };

            redressReview
                .AddTransition(payment, true)
                .AddTransition(collateData)
                .AddDependency(communication, true)
                .AddDependency(autoTransitionToRedressReview, true);

            autoTransitionToRedressReview
                .AddDependant(redressReview)
                .AddTransition(redressReview, true);

            adjustment
                .AddTransition(autoTransitionToRedressReview, true);

            adjustmentDecision
                .AddTransition(adjustment)
                .AddTransition(autoTransitionToRedressReview);

            collateData
                .AddTransition(adjustmentDecision, true);

            letterSent
                .AddTransition(responseReceived, true);

            communication
                .AddSubState(letterSent, true)
                .AddSubState(responseReceived)
                .AddDependant(redressReview)
                .AddTransition(redressReview, true);

            remediationWorkflow
                .AddSubState(communication, true)
                .AddSubState(collateData, true)
                .AddSubState(adjustmentDecision)
                .AddSubState(adjustment, completionRequired: false)
                .AddSubState(autoTransitionToRedressReview)
                .AddSubState(redressReview)
                .AddSubState(payment);

            await remediationWorkflow.ExecuteAsync(StateExecutionType.Initialise);

            return remediationWorkflow.Flatten();
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            lock (Docking.Instance)
            {
                foreach (DockingItem dockingItem in Docking.Instance.DockingItems)
                {
                    string dockedShipFileName = Essentials.PluginPath + String.Format("\\Docking\\docked_{0}_{1}_{2}.sbc", dockingItem.PlayerId, dockingItem.TargetEntityId, dockingItem.DockedEntityId);

                    IMyEntity entity = MyAPIGateway.Entities.GetEntity(x => x.EntityId == dockingItem.TargetEntityId && x is IMyCubeGrid);
                    if (entity == null)
                    {
                        //Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        Logging.WriteLineAndConsole(string.Format("Unable to find parent '{0}' for '{1}' - '{2}'", dockingItem.TargetEntityId, dockingItem.DockedEntityId, dockingItem.DockedName));
                        //continue;
                    }

                    if (!File.Exists(dockedShipFileName))
                    {
                        Logging.WriteLineAndConsole(string.Format("Unable to find ship file: {0}", dockedShipFileName));
                        continue;
                    }

//					FileInfo fileInfo = new FileInfo(dockedShipFileName);
                    MyObjectBuilder_CubeGrid cubeGrid = BaseObjectManager.ReadSpaceEngineersFile <MyObjectBuilder_CubeGrid, MyObjectBuilder_CubeGridSerializer>(dockedShipFileName);

                    if (entity != null)
                    {
                        // Rotate our ship relative to our saved rotation and the new carrier rotation
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(Matrix.CreateFromQuaternion(Quaternion.CreateFromRotationMatrix(entity.Physics.GetWorldMatrix().GetOrientation()) * dockingItem.SaveQuat).GetOrientation());
                        // Move our ship relative to the new carrier position and orientation
                        Quaternion newQuat    = Quaternion.CreateFromRotationMatrix(entity.Physics.GetWorldMatrix().GetOrientation());
                        Vector3D   rotatedPos = Vector3D.Transform(dockingItem.SavePos, newQuat);
                        //cubeGrid.Position = rotatedPos + parent.GetPosition();
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(MathUtility.RandomPositionFromPoint(entity.GetPosition(), 250f), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);
                    }
                    else
                    {
                        cubeGrid.PositionAndOrientation = new MyPositionAndOrientation(MathUtility.RandomPositionFromPoint(cubeGrid.PositionAndOrientation.Value.Position, 500f), cubeGrid.PositionAndOrientation.Value.Forward, cubeGrid.PositionAndOrientation.Value.Up);
                    }

                    // Add object to world
                    cubeGrid.EntityId        = BaseEntity.GenerateEntityId();
                    cubeGrid.LinearVelocity  = Vector3.Zero;
                    cubeGrid.AngularVelocity = Vector3.Zero;

                    bool undock = false;
                    Wrapper.GameAction(() =>
                    {
                        try
                        {
                            MyAPIGateway.Entities.CreateFromObjectBuilderAndAdd(cubeGrid);

                            List <MyObjectBuilder_EntityBase> addList = new List <MyObjectBuilder_EntityBase>();
                            addList.Add(cubeGrid);
                            MyAPIGateway.Multiplayer.SendEntitiesCreated(addList);
                            undock = true;
                        }
                        catch (Exception ex)
                        {
                            Logging.WriteLineAndConsole(string.Format("Error undocking ship: {0}", ex.ToString()));
                            Communication.SendPrivateInformation(userId, string.Format("Unable to undock ship due to error."));
                        }
                    });

                    if (!undock)
                    {
                        return(true);
                    }

                    File.Delete(dockedShipFileName);
                    Communication.SendPrivateInformation(userId, string.Format("The ship '{0}' has been undocked from docking zone", dockingItem.DockedName));
                }

                Docking.Instance.DockingItems.Clear();
                Docking.Instance.Save();
            }

            return(true);
        }
Пример #32
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitGameConfigRequestState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.GameConfigMessageRequest) {
                var gcr_msg = msg as Communication.JSON.GameConfigMessageRequest;
                Log.WriteInfo(Log.Verbosity.Normal, "Game-Configuration received.");

                Log.WriteInfo(Log.Verbosity.Normal, "Sending GameConfigConfirmation.");

                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitHashedPlaygroundRequestState,
                    new Communication.JSON.GameConfigConfirmationMessage(gcr_msg.Rules, Algorithm.SetRuleSet(gcr_msg.Rules)));
            } else
                return null;
        }
        public async Task <List <Communication> > GetCommunicationsAsync(string subscription, DateTime startTime, DateTime endTime, string impactedService = "appservice")
        {
            if (string.IsNullOrWhiteSpace(subscription))
            {
                throw new ArgumentNullException("subscription");
            }

            if (string.IsNullOrWhiteSpace(impactedService))
            {
                throw new ArgumentNullException("impactedService");
            }

            DateTime currentTimeUTC = DateTime.UtcNow;

            string startTimeStr = DateTimeHelper.GetDateTimeInUtcFormat(startTime).ToString("yyyy-MM-dd HH:mm:ss");
            string endTimeStr   = DateTimeHelper.GetDateTimeInUtcFormat(endTime).ToString("yyyy-MM-dd HH:mm:ss");

            string kustoQuery = _commsQuery
                                .Replace("{START_TIME}", startTimeStr)
                                .Replace("{END_TIME}", endTimeStr)
                                .Replace("{IMPACTED_SERVICE}", impactedService)
                                .Replace("{SUBSCRIPTION}", subscription);

            DataTable dt = await this._kustoQueryService.ExecuteQueryAsync("Icmcluster", "ACM.Backend", kustoQuery);

            List <Communication> commsList = new List <Communication>();

            if (dt == null || dt.Rows == null || dt.Rows.Count == 0)
            {
                return(commsList);
            }

            foreach (DataRow row in dt.Rows)
            {
                Communication comm = new Communication
                {
                    CommunicationId = row["CommunicationId"].ToString(),
                    PublishedTime   = DateTimeHelper.GetDateTimeInUtcFormat(DateTime.Parse(row["PublishedTime"].ToString())),
                    Title           = row["Title"].ToString(),
                    RichTextMessage = row["RichTextMessage"].ToString(),
                    Status          = row["Status"].ToString().Equals("Active", StringComparison.OrdinalIgnoreCase) ? CommunicationStatus.Active : CommunicationStatus.Resolved,
                    IncidentId      = row["IncidentId"].ToString()
                };

                comm.ImpactedServices = GetImpactedRegions(row["ImpactedServices"].ToString());
                commsList.Add(comm);
            }

            commsList = commsList.OrderByDescending(p => p.PublishedTime).ToList();

            Communication impactedServiceComm           = null;
            Communication mostRecentImpactedServiceComm = commsList.FirstOrDefault(p => p.ImpactedServices.Exists(q => q.Name.ToLower().Contains(impactedService.ToLower())));

            if (mostRecentImpactedServiceComm != null)
            {
                if (mostRecentImpactedServiceComm.Status == CommunicationStatus.Active)
                {
                    mostRecentImpactedServiceComm.IsAlert    = true;
                    mostRecentImpactedServiceComm.IsExpanded = true;
                    impactedServiceComm = mostRecentImpactedServiceComm;
                }
                else if (mostRecentImpactedServiceComm.Status == CommunicationStatus.Resolved)
                {
                    Communication rca = commsList.FirstOrDefault(p => (
                                                                     p.IncidentId == mostRecentImpactedServiceComm.IncidentId &&
                                                                     p.PublishedTime > mostRecentImpactedServiceComm.PublishedTime &&
                                                                     p.CommunicationId != mostRecentImpactedServiceComm.CommunicationId &&
                                                                     p.Title.ToUpper().Contains("RCA")));

                    if (rca != null && ((currentTimeUTC - rca.PublishedTime) <= _commAlertWindow))
                    {
                        rca.IsAlert    = true;
                        rca.IsExpanded = false;
                        // NOTE:- For now, resolved incidents will be collapsed by Default.
                        // Uncommenting below line would make resolved incidents expanded by default for certain timespan.
                        //rca.IsExpanded = ((currentTimeUTC - rca.PublishedTime) <= _commExpandedWindow);
                        impactedServiceComm = rca;
                    }
                    else if ((currentTimeUTC - mostRecentImpactedServiceComm.PublishedTime) <= _commAlertWindow)
                    {
                        mostRecentImpactedServiceComm.IsAlert    = true;
                        mostRecentImpactedServiceComm.IsExpanded = false;
                        // NOTE:- For now, resolved incidents will be collapsed by Default.
                        // Uncommenting below line would make resolved incidents expanded by default for certain timespan.
                        //mostRecentImpactedServiceComm.IsExpanded = ((currentTimeUTC - mostRecentImpactedServiceComm.PublishedTime) <= _commExpandedWindow);
                        impactedServiceComm = mostRecentImpactedServiceComm;
                    }
                }
            }

            return(commsList);
        }
Пример #34
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitGoodbyeResponseState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.GoodbyeResponseMessage) {
                var pr_msg = msg as Communication.JSON.GoodbyeResponseMessage;
                Log.WriteInfo(Log.Verbosity.Important, "Goodbye-Response was received.");

                Shutdown();

                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    m => null,
                    null);
            } else
                return null;
        }
Пример #35
0
 // Use this for initialization
 void Start()
 {
     comms = GameObject.FindGameObjectWithTag("GameController").GetComponent <Communication>();
 }
Пример #36
0
        public static void Process(bool reload = false)
        {
            Dictionary <long, long> ownership = ProcessAsteroidOwnership();
            long owner = 0;
            int  count = 0;

            foreach (KeyValuePair <long, long> p in ownership)
            {
                if (!Instance.Leaderboard.ContainsKey(p.Key))
                {
                    if (owner == 0)
                    {
                        owner = p.Value;
                    }

                    count++;
                }
                else if (Instance.Leaderboard[p.Key] != ownership[p.Key])
                {
                    if (owner == 0)
                    {
                        owner = p.Value;
                    }

                    count++;
                }
            }

            if (count == 1)
            {
                MyObjectBuilder_Checkpoint.PlayerItem item = PlayerMap.Instance.GetPlayerItemFromPlayerId(owner);
                string name = "";
                if (item.Name != null)
                {
                    name = item.Name;
                }

                if (!reload)
                {
                    Communication.SendPublicInformation(string.Format("[CONQUEST]: {0} has conquered an asteroid.", name));
                }
            }
            else if (count > 1)
            {
                if (!reload)
                {
                    Communication.SendPublicInformation(string.Format("[CONQUEST]: Multiple asteroids have been conquered.  {0} asteroids have been claimed or changed ownership.", count));
                }
            }

            bool change = false;

            foreach (KeyValuePair <long, long> p in ownership)
            {
                if (!Instance.Leaderboard.ContainsKey(p.Key))
                {
                    Instance.Leaderboard.Add(p.Key, p.Value);
                    change = true;
                }
                else if (Instance.Leaderboard.ContainsKey(p.Key) && Instance.Leaderboard[p.Key] != p.Value)
                {
                    Instance.Leaderboard[p.Key] = p.Value;
                    change = true;
                }
            }

            if (change)
            {
                Save();
            }
        }
Пример #37
0
        private static void SerializePatient()
        {
            Patient patient = new Patient();

            PersonData cd = new PersonData();
            cd.ID = Guid.NewGuid();
            cd.Surname = "Androulidakis";
            cd.Name = "Aggelos";

            List<Communication> communications = new List<Communication>();

            Communication commun1 = new Communication();
            commun1.IsPrimary = true;
            commun1.Type = CommunicationType.Phone;
            commun1.Value = "+302107722453";
            communications.Add(commun1);

            Communication commun2 = new Communication();
            commun2.IsPrimary = false;
            commun2.Value = "*****@*****.**";
            commun2.Type = CommunicationType.Email;
            communications.Add(commun2);

            cd.CommunicationList = new List<Communication>(communications);

            List<Address> addresses = new List<Address>();
            Address address = new Address();
            address.Street = "Patission";
            address.StreetNo = "42";
            address.City = "Athens";
            address.Country = "GR";
            address.Notes = "3rd floor";
            address.IsPrimary = true;
            address.ZipCode = "123-45";
            address.County = "Attica";
            addresses.Add(address);
            addresses.Add(address);

            List<Identifier> ids = new List<Identifier>();
            Identifier id = new Identifier();
            id.Type = IdentifierType.PassportID;
            id.Number = "AB202825";
            id.IssueDate = "17/02/2003";
            id.IssueAuthority = "ABC";
            ids.Add(id);
            ids.Add(id);

            cd.IdentifierList = ids;

            cd.AddressList = new List<Address>(addresses);

            patient.PersonData = cd;

            SocioDemographicData sd = new SocioDemographicData();
            sd.Age = 82;
            SystemParameter maritalStatus = new SystemParameter();
            maritalStatus.Code = 1;
            maritalStatus.Description = "widow";
            sd.MaritalStatus = maritalStatus;

            sd.Children = 2;
            SystemParameter sex = new SystemParameter();
            sex.Code = 1;
            sex.Description = "Male";

            sd.Gender = sex;

            SystemParameter livingWith = new SystemParameter();
            livingWith.Code = 1;
            livingWith.Description = "with son/daughter";

            sd.LivingWith = livingWith;

            patient.SD_Data = sd;

            Carer c1 = new Carer();
            c1.PersonData = patient.PersonData;
            c1.SD_Data = patient.SD_Data;

            PatientCaregiver pc1 = new PatientCaregiver();
            pc1.Caregiver = c1;
            pc1.IsPrimary = true;

            PatientCaregiver pc2 = new PatientCaregiver();
            pc2.Caregiver = c1;
            pc2.IsPrimary = false;

            patient.PatientCaregiverList.ListOfCaregivers.Add(pc1);
            patient.PatientCaregiverList.ListOfCaregivers.Add(pc2);

            Clinician respClinician = new Clinician();
            respClinician.PersonData = patient.PersonData;

            patient.ResponsibleClinician = respClinician;

            //PatientAssessment assessment = new PatientAssessment();
            //assessment.MMSE = 22;
            //assessment.DateOfAssessment = System.DateTime.Now;

            //patient.Assessments.ListOfAssessments.Add(assessment);

            SerializeMe(patient, "Patient.xml");
        }
Пример #38
0
        protected override void DoWork(Response data, UpdateMessage msg)
        {
            var localVersion  = Settings.Get("Version");
            var serverVersion = msg.Version;

            if (string.IsNullOrWhiteSpace(serverVersion))
            {
                Log.Error(Name, "No version provided by server");
                return;
            }

            try
            {
                var updaterPath = Path.Combine(Settings.Location, "tmp", "SmartInstaller.exe");

                if (File.Exists(updaterPath))
                {
                    File.Delete(updaterPath);
                }

                var server      = serverVersion.Split('.');
                var local       = localVersion.Split('.');
                var needUpgrade = false;

                for (var i = 0; i < server.Length; i++)
                {
                    var serverSection = int.Parse(server[i]);
                    var localSection  = int.Parse(local[i]);

                    if (localSection > serverSection)
                    {
                        return;
                    }

                    if (serverSection > localSection)
                    {
                        needUpgrade = true;
                        break;
                    }
                }

                if (!needUpgrade)
                {
                    return;
                }

                // Ensure the update is authentic
                Communication.DownloadFile("/client/" + "SmartInstaller.exe", updaterPath);
                if (!IsAuthenticate(updaterPath))
                {
                    return;
                }

                PrepareUpdateHelpers();
                Power.Updating = true;
            }
            catch (Exception ex)
            {
                Log.Error(Name, "Unable to parse versions");
                Log.Error(Name, ex);
            }
        }
Пример #39
0
        void com_SerialDataEvent(object sender, Communication.SerialDataEventArgs e)
        {
            foreach (char c in e.Data)
            {
                if (!_isReceivingLine)
                {
                    if (c == 4)
                    {
                        //Block done (= EOT).
                        if (replyTimerRunning)
                        {
                            _replyStopwatch.Stop();
                            replyTimerRunning = false;
                            _lastPing =(long)Math.Round((_lastPing*2.0+(double)_replyStopwatch.ElapsedMilliseconds)/3);
                            Data.db.UpdateProperty("LastPing");
                        }

                        processReply(_receivingBuffer.ToString());
                    }
                    else if (c != '\n')
                    {
                        _isReceivingLine = true;
                        _receivingBuffer.Append(c);
                    }
                    else
                    {
                        //TODO handle this (received just \n)
                    }
                }
                else
                {
                    if (c != '\n')
                    {
                        _isReceivingLine = true;
                        _receivingBuffer.Append(c);
                    }
                    else
                    {
                        _isReceivingLine = false;
                        processReply(_receivingBuffer.ToString());
                        _receivingBuffer.Clear();
                        _linesReceived++;
                    }
                }
            }
        }
 public void Add(Communication communication)
 {
     _communications.Add(communication);
 }
Пример #41
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitGameConfigResponseState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.GameConfigConfirmationMessage) {
                var gcr_msg = msg as Communication.JSON.GameConfigConfirmationMessage;
                Log.WriteInfo(Log.Verbosity.Normal, "Game-Configuration " + (gcr_msg.Accept ? "was accepted!" : "was rejected!"));

                Algorithm.SetRuleSet(gcr_msg.Rules);

                //Generate Playground-Hash
                var hash = Algorithm.GetPlayground().GetHash();

                //Send hashed playground
                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitHashedPlaygroundResponseState,
                    new Communication.JSON.HashedPlaygroundRequestMessage(hash));
            } else
                return null;
        }
Пример #42
0
 /// <summary>
 /// Function to send Error email to system support team
 /// </summary>
 /// <param name="subject">Email Subject</param>
 /// <param name="ex">Exception</param>
 public static void SendErrorEmail(string strEmailSubject, Exception ex)
 {
     Communication.SendEmail(strEmailSender, strEmailSupport, strEmailSubject, ex.ToString());
 }
Пример #43
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitHandshakeRequestState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.HandshakeRequestMessage) {
                var hsr_msg = msg as Communication.JSON.HandshakeRequestMessage;
                Log.WriteInfo(Log.Verbosity.Normal, "Handshake Request received from ");
                Log.WriteInfo(Log.Verbosity.Important, hsr_msg.ClientName);
                Log.WriteInfo(Log.Verbosity.Important, "Algorithm: " + hsr_msg.Algorithm);
                Log.WriteInfo(Log.Verbosity.Normal, "Greeting: " + hsr_msg.Greeting);

                Algorithm.SetEnemyAlgorithmName(hsr_msg.Algorithm);

                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitGameConfigRequestState,
                    new Communication.JSON.HandshakeResponseMessage("Fabs Superior C# Client", "If u can read this", Algorithm.GetAlgorithmName(), "0.1"));
            } else
                return null;
        }
Пример #44
0
 /// <summary>
 /// Function to send Support email to system support team
 /// </summary>
 /// <param name="subject">Email Subject</param>
 /// <param name="message">Email body message</param>
 public static void SendSupportEmail(string strEmailSubject, string strEmailBody)
 {
     Communication.SendEmail(strFromSystemEmail, strEmailSupport, strEmailSubject, strEmailBody);
 }
Пример #45
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitHashedPlaygroundRequestState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.HashedPlaygroundRequestMessage) {
                var hpr_msg = msg as Communication.JSON.HashedPlaygroundRequestMessage;
                Log.WriteInfo(Log.Verbosity.Normal, "Hashed Playground was received: " + hpr_msg.HashCode);

                //Generate playground-hash
                var hash = Algorithm.GetPlayground().GetHash();

                //Set enemy playground-hash
                Algorithm.SetEnemyPlaygroundHash(hpr_msg.HashCode);

                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitShootListState,
                    new Communication.JSON.HashedPlaygroundResponseMessage(hash));
            } else
                return null;
        }
Пример #46
0
 /// <summary>
 /// General function for sending email
 /// </summary>
 /// <param name="to">Receiver email address</param>
 /// <param name="strEmailBody">Email body content</param>
 /// <param name="strSubject">Email Subject</param>
 public static void SendEmail(string strEmailReceiver, string strEmailBody, string strEmailSubject)
 {
     Communication.SendEmail(strEmailSender, strEmailReceiver, null, null, strEmailSubject, strEmailBody);
 }
Пример #47
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitHitListState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.HitListMessage) {
                var hl_msg = msg as Communication.JSON.HitListMessage;
                Log.WriteInfo(Log.Verbosity.Normal, "Hit list was received. Amount: " + hl_msg.Hits.Length);
                Log.WriteGame(Log.Verbosity.Normal, "Hits: " + string.Join(",", hl_msg.Hits.Select(h => h.ToString())));

                //Set hits
                Algorithm.SetShootResults(hl_msg.Hits);

                Tuple<StateWaitHandler, Communication.JSON.Message> result;
                if (Algorithm.GetAcceptedRuleSet().RepeatWhenHit && hl_msg.Hits.Any(h => h.Hitted))
                    result = new Tuple<StateWaitHandler, Communication.JSON.Message>(
                        WaitHitListState,
                        new Communication.JSON.ShootListMessage(Algorithm.GetShoots()));
                else
                    result = new Tuple<StateWaitHandler, Communication.JSON.Message>(
                        WaitShootListState,
                        new Communication.JSON.EndOfTurnMessage(Algorithm.GetEndOfTurnSmack())
                        );

                return result;
            } else
                return null;
        }
Пример #48
0
        // admin scan x y z radius
        public override bool HandleCommand(ulong userId, string command)
        {
            string[] words = command.Split(' ');
            if (words.Count( ) != 8 && words.Count( ) != 0)
            {
                return(false);
            }

            if (words.Count() != 8)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            // Test Input
            float test = 0;

            for (int r = 0; r < 8; r++)
            {
                if (!float.TryParse(words[r], out test))
                {
                    Communication.SendPrivateInformation(userId, string.Format("The value at position {0} - '{1}' is invalid.  Please try the command again.", r + 1, words[r]));
                    return(true);
                }
            }

            Vector3D startPosition  = new Vector3D(float.Parse(words[0]), float.Parse(words[1]), float.Parse(words[2]));
            Vector3D targetPosition = new Vector3D(float.Parse(words[3]), float.Parse(words[4]), float.Parse(words[5]));
            float    distance       = float.Parse(words[6]);
            float    radius         = float.Parse(words[7]);

            Vector3D targetMovement = targetPosition - startPosition;

            targetMovement.Normalize();
            Vector3D finalPosition = targetMovement * distance;

            finalPosition += startPosition;

            List <MyObjectBuilder_CubeGrid> gridsToMove = new List <MyObjectBuilder_CubeGrid>();
            BoundingSphereD  sphere   = new BoundingSphereD(finalPosition, radius);
            List <IMyEntity> entities = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);
            int count = 0;

            Communication.SendPrivateInformation(userId, string.Format("Scanning {0} meters around {1}", radius, General.Vector3DToString(finalPosition)));
            Wrapper.GameAction(() =>
            {
                foreach (IMyEntity entity in entities)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    Communication.SendPrivateInformation(userId, string.Format("Found ship {0} at {1}", entity.DisplayName, General.Vector3DToString(entity.GetPosition())));
                    count++;
                }
            });

            Communication.SendPrivateInformation(userId, string.Format("Total ships found: {0}", count));
            return(true);
        }
Пример #49
0
        Tuple<StateWaitHandler, Communication.JSON.Message> WaitShootListState(Communication.JSON.Message msg)
        {
            if (msg is Communication.JSON.ShootListMessage) {
                var sl_msg = msg as Communication.JSON.ShootListMessage;
                Log.WriteInfo(Log.Verbosity.Important, "Shoot list was received. Amount: " + sl_msg.Shoots.Length);
                Log.WriteGame(Log.Verbosity.Normal, "Shoots: " + string.Join(",", sl_msg.Shoots.Select(s => s.ToString())));
                //Set shoots
                var results = Algorithm.SetShoots(sl_msg.Shoots);

                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitShootListState,
                    new Communication.JSON.HitListMessage(results));
            } else if (msg is Communication.JSON.EndOfTurnMessage) {
                var sl_msg = msg as Communication.JSON.EndOfTurnMessage;
                Log.WriteGame(Log.Verbosity.Normal, "End of turn received.");

                Algorithm.PutEndOfTurnSmack(sl_msg.SmackTalk);

                var shoots = Algorithm.GetShoots();

                if (shoots.Any())
                    return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                        WaitHitListState,
                        new Communication.JSON.ShootListMessage(shoots));
                else {
                    Log.WriteGame(Log.Verbosity.Important, "Giving up.");
                    return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                        WaitPlaygroundRequestState,
                        new Communication.JSON.DefeatMessage(Algorithm.GetDefeatReason(), Algorithm.GetDefeatWhining())
                        );
                }
            } else if (msg is Communication.JSON.DefeatMessage) {
                var d_msg = msg as Communication.JSON.DefeatMessage;
                Log.WriteGame(Log.Verbosity.Important, "Defeat received.");

                Algorithm.PutDefeat(d_msg.Reason, d_msg.Whining);

                this.Won = true;

                var playground = Algorithm.GetPlayground();

                Log.WriteGame(Log.Verbosity.Normal, "Own Playground: " + playground.GetShort());
                Log.WriteInfo(Log.Verbosity.Normal, "Send own playground.");
                return new Tuple<StateWaitHandler, Communication.JSON.Message>(
                    WaitPlaygroundResponseState,
                    new Communication.JSON.PlaygroundRequestMessage(playground));
            } else
                return null;
        }
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (!PluginSettings.Instance.WaypointsEnabled)
            {
                return(false);
            }

            if (words.Length != 6 && words.Length != 7 && words.Length != 1)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            string     playerName = PlayerMap.Instance.GetPlayerNameFromSteamId(userId);
            long       playerId   = PlayerMap.Instance.GetFastPlayerIdFromSteamId(userId);
            IMyFaction faction    = MyAPIGateway.Session.Factions.TryGetPlayerFaction(playerId);

            if (faction == null)
            {
                Communication.SendPrivateInformation(userId, string.Format("Unable to find your faction information.  You must be in a faction to use this."));
                return(true);
            }

            List <WaypointItem> items = Waypoints.Instance.Get((ulong)faction.FactionId);

            if (PluginSettings.Instance.WaypointsMaxPerFaction > 0 && items.Count >= PluginSettings.Instance.WaypointsMaxPerFaction)
            {
                Communication.SendPrivateInformation(userId, string.Format("Waypoint limit has been reached.  You may only have {0} faction waypoints at a time on this server.  Please remove some waypoints in order to add new ones.", PluginSettings.Instance.WaypointsMaxPerPlayer));
                return(true);
            }

            if (words.Length == 1)
            {
                IMyEntity playerEntity = Player.FindControlledEntity(playerId);
                if (playerEntity == null)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Can't find your position"));
                    return(true);
                }

                Vector3D pos  = playerEntity.GetPosition();
                string   name = words[0];

                foreach (ulong steamId in PlayerManager.Instance.ConnectedPlayers)
                {
                    if (Player.CheckPlayerSameFaction(userId, steamId))
                    {
                        Communication.SendClientMessage(steamId, string.Format("/waypoint add '{0}' '{0}' Neutral {1} {2} {3}", name, Math.Floor(pos.X), Math.Floor(pos.Y), Math.Floor(pos.Z)));
                    }
                }

                WaypointItem item = new WaypointItem
                {
                    SteamId      = (ulong)faction.FactionId,
                    Name         = name,
                    Text         = name,
                    Position     = pos,
                    WaypointType = WaypointTypes.Neutral,
                    Leader       = faction.IsLeader(playerId)
                };
                Waypoints.Instance.Add(item);

                Communication.SendFactionClientMessage(userId, string.Format("/message Server {2} has added the waypoint: '{0}' at {1} by '{2}'", item.Name, General.Vector3DToString(item.Position), playerName));
            }
            else
            {
                for (int r = 3; r < 6; r++)
                {
                    double test;
                    if (!double.TryParse(words[r], out test))
                    {
                        Communication.SendPrivateInformation(userId, string.Format("Invalid position information: {0} is invalid", words[r]));
                        return(true);
                    }
                }

                string add = string.Join(" ", words.Select(s => s.ToLowerInvariant()));

                foreach (ulong steamId in PlayerManager.Instance.ConnectedPlayers)
                {
                    if (Player.CheckPlayerSameFaction(userId, steamId))
                    {
                        Communication.SendClientMessage(steamId, string.Format("/waypoint add {0}", add));
                    }
                }

                string group = "";
                if (words.Length == 7)
                {
                    group = words[7];
                }

                WaypointItem item = new WaypointItem
                {
                    SteamId = (ulong)faction.FactionId,
                    Name    = words[0],
                    Text    = words[1]
                };
                WaypointTypes type;
                Enum.TryParse(words[2], true, out type);
                item.WaypointType = type;
                item.Position     = new Vector3D(double.Parse(words[3]), double.Parse(words[4]), double.Parse(words[5]));
                item.Group        = group;
                item.Leader       = faction.IsLeader(playerId);
                Waypoints.Instance.Add(item);

                Communication.SendFactionClientMessage(userId, string.Format("/message Server {2} has added the waypoint: '{0}' at {1} by '{2}'", item.Name, General.Vector3DToString(item.Position), playerName));
            }
            return(true);
        }
Пример #51
0
 private static void AddCommunication(DeepBlue.Models.Entity.Contact contact, DeepBlue.Models.Admin.Enums.CommunicationType communicationType, string value)
 {
     if (!string.IsNullOrEmpty(value)) {
         ContactCommunication contactComm = new ContactCommunication();
         Communication comm = new Communication();
         comm.CommunicationTypeID = (int)communicationType;
         comm.CommunicationValue = value;
         contactComm.Communication = comm;
         contact.ContactCommunications.Add(contactComm);
     }
 }
Пример #52
0
        // /admin movefrom x y z x y z radius
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (words.Count() != 8 && words.Count() != 0)
            {
                return(false);
            }

            if (words.Count() != 8)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            // Test Input
            float test = 0;

            for (int r = 0; r < 7; r++)
            {
                if (!float.TryParse(words[r], out test))
                {
                    Communication.SendPrivateInformation(userId, string.Format("The value at position {0} - '{1}' is invalid.  Please try the command again.", r + 1, words[r]));
                    return(true);
                }
            }

            Vector3D startPosition  = new Vector3(float.Parse(words[0]), float.Parse(words[1]), float.Parse(words[2]));
            Vector3D targetPosition = new Vector3(float.Parse(words[3]), float.Parse(words[4]), float.Parse(words[5]));
            float    distance       = float.Parse(words[6]);
            float    radius         = float.Parse(words[7]);

            Vector3D movementPosition = targetPosition - startPosition;

            movementPosition.Normalize();
            Vector3D finalPosition = movementPosition * distance;
            //finalPosition += startPosition;

            List <MyObjectBuilder_CubeGrid> gridsToMove = new List <MyObjectBuilder_CubeGrid>();
            BoundingSphereD  sphere         = new BoundingSphereD(startPosition, radius);
            List <IMyEntity> entitiesToMove = MyAPIGateway.Entities.GetEntitiesInSphere(ref sphere);

            Communication.SendPrivateInformation(userId, string.Format("Moving all grids in a radius of {0} near {1} towards {2} by {3} meters", radius, General.Vector3DToString(startPosition), General.Vector3DToString(targetPosition), distance));

            Wrapper.GameAction(() =>
            {
                foreach (IMyEntity entity in entitiesToMove)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    Communication.SendPrivateInformation(userId, string.Format("Moving '{0}' from {1} to {2}", entity.DisplayName, General.Vector3DToString(entity.GetPosition()), General.Vector3DToString(entity.GetPosition() + finalPosition)));

                    gridsToMove.Add((MyObjectBuilder_CubeGrid)entity.GetObjectBuilder());
                    MyAPIGateway.Entities.RemoveEntity(entity);
                }
            });

            Thread.Sleep(5000);

            Wrapper.GameAction(() =>
            {
                foreach (IMyEntity entity in entitiesToMove)
                {
                    if (!(entity is IMyCubeGrid))
                    {
                        continue;
                    }

                    Logging.WriteLineAndConsole(string.Format("Removing '{0}' for move", entity.DisplayName));
                    MyAPIGateway.Entities.RemoveFromClosedEntities(entity);
                }
            });

            Thread.Sleep(10000);

            Wrapper.GameAction(() =>
            {
                foreach (MyObjectBuilder_CubeGrid grid in gridsToMove)
                {
                    grid.PositionAndOrientation = new MyPositionAndOrientation(grid.PositionAndOrientation.Value.Position + finalPosition, grid.PositionAndOrientation.Value.Forward, grid.PositionAndOrientation.Value.Up);
                    Communication.SendPrivateInformation(userId, string.Format("Adding '{0}' for move", grid.DisplayName));
                    SectorObjectManager.Instance.AddEntity(new CubeGridEntity(grid));
                }
            });

            Communication.SendPrivateInformation(userId, string.Format("Finished moving {0} grids", gridsToMove.Count));

            return(true);
        }
Пример #53
0
	public static Communication GetInstance() {
		if (_instance == null) {
			_instance = new Communication();
		}
		return _instance;
	}
Пример #54
0
        /// <summary>
        /// 控制柜子公共类
        /// </summary>
        /// <param name="task_info">任务对象</param>
        /// <param name="gun_number">枪位号集合</param>
        /// <param name="magazine_number">弹仓号集合</param>
        /// <returns></returns>
        public static bool control(Model.task_info task_info, byte[] gun_number, byte[] magazine_number)
        {
            Communication comm = CommunicationInstance.getInstance().getCommunication();

            //WebService接口调用工具
            WebService.gunServices webService = SingleWebService.getWebService();
            if (gun_number.Length > 0 || task_info.task_BigType == 14)
            {
                //标识发完开门指令后多少秒还未开门
                int count = 0;
                //开枪柜门(枪支封存解封不开柜门)
                if (task_info.task_BigType != 4 && task_info.task_BigType != 10)
                {
                    comm.send_message(Port.Get_ComGun(), Communication.open);
                }
                //枪支封存
                if (task_info.task_BigType == 4)
                {
                    PlaySound.paly(Properties.Resources._29);
                    return(true);
                }
                //枪支解封
                if (task_info.task_BigType == 10)
                {
                    PlaySound.paly(Properties.Resources._30);
                    return(true);
                }
                //语音提示
                PlaySound.paly(Properties.Resources._9);
                //如果柜门已经打开,再发解锁枪位指令
                while (PubFlag.gunark_control_isAile)
                {
                    //将此循环设置为1秒执行一次,判断25秒之后还未将门打开,此时柜门已重新锁上

                    //查询枪柜门状态
                    bool gunDoorStatus = SearchDoorStatus.searchGunStatus();
                    System.Threading.Thread.Sleep(1000);
                    count++;
                    if (count > 20)
                    {
                        return(false);
                    }
                    //判断枪柜门是否已经打开
                    if (gunDoorStatus)
                    {
                        GunarkDoorStatus gds = new GunarkDoorStatus(task_info, gun_number, magazine_number);
                        gds.pictureBox1.Image = Properties.Resources.gun_open;
                        gds.pictureBox2.Image = Properties.Resources.openDoor;
                        gds.Flag = 1;
                        //gds.openBackgroundWorker();
                        gds.ShowDialog();
                        break;
                    }
                }
                ////判断是否已经关闭枪柜门,检测关闭枪柜门之后再开启弹柜门
                //while (PubFlag.gunark_control_isAile)
                //{
                //    //查询枪柜门状态
                //    bool doorStatus = SearchDoorStatus.searchGunStatus();
                //    System.Threading.Thread.Sleep(1000);
                //    //////假设已经关闭枪柜门,测试用,以后要删除下边这行代码
                //    ////doorStatus = false;
                //    //if (!doorStatus)
                //    if (true)
                //    {
                //        GunarkDoorStatus gds = new GunarkDoorStatus(task_info, gun_number, magazine_number);
                //        gds.pictureBox1.Image = Properties.Resources.gun_close;
                //        gds.pictureBox2.Image = Properties.Resources.closeDoor;
                //        gds.Flag = 2;
                //        gds.openBackgroundWorker();
                //        gds.ShowDialog();
                //        break;
                //    }
                //}
            }
            //结束取枪后,判断是否有子弹,若有在进行下面对弹柜的操作
            if (magazine_number.Length > 0)
            {
                //开弹柜门
                //comm.send_message(Port.Get_ComBullet(), Communication.open);
                //语音提示
                PlaySound.paly(Properties.Resources._10);
                //如果弹柜门已打开,再发弹开弹仓指令
                while (PubFlag.gunark_control_isAile)
                {
                    //查询弹柜门状态
                    //bool bulletDoorStatus = SearchDoorStatus.searchBulletStatus();
                    System.Threading.Thread.Sleep(1000);
                    //判断弹柜门是否已经打开(假设已经打开)
                    //if (bulletDoorStatus)
                    if (true)
                    {
                        GunarkDoorStatus gds = new GunarkDoorStatus(task_info, gun_number, magazine_number);
                        gds.pictureBox1.Image = Properties.Resources.bullet_open;
                        gds.pictureBox2.Image = Properties.Resources.openDoor;
                        gds.Flag = 3;
                        //gds.openBackgroundWorker();
                        gds.ShowDialog();
                        break;
                    }
                }
                /////判断弹柜门是否已经关闭
                //while (PubFlag.gunark_control_isAile)
                //{
                //    //查询弹柜门状态
                //    //bool doorStatus = SearchDoorStatus.searchBulletStatus();
                //    System.Threading.Thread.Sleep(1000);

                //    ////假设应经关闭
                //    //if (!doorStatus)
                //    if(true)
                //    {
                //        GunarkDoorStatus gds = new GunarkDoorStatus(task_info, gun_number, magazine_number);
                //        gds.pictureBox1.Image = Properties.Resources.bullet_close;
                //        gds.pictureBox2.Image = Properties.Resources.closeDoor;
                //        gds.Flag = 4;
                //        gds.openBackgroundWorker();
                //        gds.ShowDialog();
                //        break;
                //    }
                //}
            }
            return(true);
        }
Пример #55
0
        /// <summary>
        /// This event handles incoming messages from communication channel.
        /// </summary>
        /// <param name="sender">Communication channel that received message</param>
        /// <param name="e">Event arguments</param>
        private void CommunicationChannel_MessageReceived(ICommunicationChannel sender, Communication.Channels.MessageReceivedEventArgs e)
        {
            //Update last incoming message time
            LastIncomingMessageTime = DateTime.Now;

            //Check for duplicate messages.
            if (e.Message.MessageTypeId == NGRIDMessageFactory.MessageTypeIdNGRIDDataTransferMessage)
            {
                var dataMessage = e.Message as NGRIDDataTransferMessage;
                if (dataMessage != null)
                {
                    if (dataMessage.MessageId == LastAcknowledgedMessageId)
                    {
                        try
                        {
                            SendMessageInternal(new NGRIDOperationResultMessage
                            {
                                RepliedMessageId = dataMessage.MessageId,
                                Success = true,
                                ResultText = "Duplicate message."
                            });
                        }
                        catch (Exception ex)
                        {
                            Logger.Warn(ex.Message, ex);
                        }

                        return;
                    }
                }
            }

            //Check if there is a waiting thread for this message (in SendAndWaitForReply method)
            if (!string.IsNullOrEmpty(e.Message.RepliedMessageId))
            {
                WaitingMessage waitingMessage = null;
                lock (_waitingMessages)
                {
                    if (_waitingMessages.ContainsKey(e.Message.RepliedMessageId))
                    {
                        waitingMessage = _waitingMessages[e.Message.RepliedMessageId];
                    }
                }

                if (waitingMessage != null)
                {
                    if (waitingMessage.WaitingResponseType == e.Message.MessageTypeId)
                    {
                        waitingMessage.ResponseMessage = e.Message;
                        waitingMessage.State = WaitingMessageStates.ResponseReceived;
                        waitingMessage.WaitEvent.Set();
                        return;
                    }
                    
                    if(e.Message.MessageTypeId == NGRIDMessageFactory.MessageTypeIdNGRIDOperationResultMessage)
                    {
                        var resultMessage = e.Message as NGRIDOperationResultMessage;
                        if ((resultMessage != null) && (!resultMessage.Success))
                        {
                            waitingMessage.State = WaitingMessageStates.MessageRejected;
                            waitingMessage.WaitEvent.Set();
                            return;
                        }
                    }
                }
            }

            //If this message is not a response, then add it to message process queue
            _incomingMessageQueue.Add(e.Message);
        }
Пример #56
0
 public static void AddCommenication(Communication communication)
 {
     commu.AddCommenication(communication);
 }
Пример #57
0
 public static void UpdateCommun(Communication communica)
 {
     commu.UpdateCommun(communica);
 }
        // admin nobeacon scan
        public override bool HandleCommand(ulong userId, string[] words)
        {
            if (words.Count() > 3)
            {
                return(false);
            }

            if (words.Count() == 0)
            {
                Communication.SendPrivateInformation(userId, GetHelp());
                return(true);
            }

            int days = -1;

            if (!int.TryParse(words[0], out days) || days < 0)
            {
                Communication.SendPrivateInformation(userId, string.Format("Invalid argument.  Days argument must be an integer that is 0 or greater."));
                return(true);
            }

            // Just assume that anything after the days is going to "ignorenologin"
            bool removeNoLoginInformation = true;
            bool removeOwnerless          = true;

            if (words.Count() > 1)
            {
                foreach (string word in words)
                {
                    if (word.ToLower() == "ignorenologin")
                    {
                        removeNoLoginInformation = false;
                    }
                    if (word.ToLower() == "ignoreownerless")
                    {
                        removeOwnerless = false;
                    }
                }
            }

            Communication.SendPrivateInformation(userId, string.Format("Scanning for grids with owners that haven't logged in {0} days.  (Must Have Login Info={1})", days, removeNoLoginInformation));

            HashSet <IMyEntity> entities = new HashSet <IMyEntity>();

            Wrapper.GameAction(() =>
            {
                MyAPIGateway.Entities.GetEntities(entities, x => x is IMyCubeGrid);
            });

            HashSet <IMyEntity> entitiesFound = new HashSet <IMyEntity>();

            foreach (IMyEntity entity in entities)
            {
                if (!(entity is IMyCubeGrid))
                {
                    continue;
                }

                IMyCubeGrid              grid        = (IMyCubeGrid)entity;
                CubeGridEntity           gridEntity  = (CubeGridEntity)GameEntityManager.GetEntity(grid.EntityId);
                MyObjectBuilder_CubeGrid gridBuilder = CubeGrids.SafeGetObjectBuilder(grid);
                if (gridBuilder == null)
                {
                    continue;
                }

                // This entity is protected by whitelist
                if (PluginSettings.Instance.LoginEntityWhitelist.Length > 0 && PluginSettings.Instance.LoginEntityWhitelist.Contains(grid.EntityId.ToString()))
                {
                    continue;
                }

                if (CubeGrids.GetAllOwners(gridBuilder).Count < 1 && removeOwnerless)
                {
                    Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) not owned by anyone.", gridEntity.Name, entity.EntityId));
                    entitiesFound.Add(entity);
                    continue;
                }

                foreach (long player in CubeGrids.GetBigOwners(gridBuilder))
                {
                    // This playerId is protected by whitelist
                    if (PluginSettings.Instance.LoginPlayerIdWhitelist.Length > 0 && PluginSettings.Instance.LoginPlayerIdWhitelist.Contains(player.ToString()))
                    {
                        continue;
                    }

                    MyObjectBuilder_Checkpoint.PlayerItem checkItem = PlayerMap.Instance.GetPlayerItemFromPlayerId(player);
                    if (checkItem.IsDead || checkItem.Name == "")
                    {
                        Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by dead player - ID: {2}", gridEntity.Name, entity.EntityId, player));
                        entitiesFound.Add(entity);
                        continue;
                    }

                    PlayerItem item = Players.Instance.GetPlayerById(player);
                    if (item == null)
                    {
                        if (removeNoLoginInformation)
                        {
                            Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by a player with no login info: {2}", gridEntity.Name, entity.EntityId, checkItem.Name));
                            entitiesFound.Add(entity);
                        }
                    }
                    else if (item.LastLogin < DateTime.Now.AddDays(days * -1))
                    {
                        Communication.SendPrivateInformation(userId, string.Format("Found entity '{0}' ({1}) owned by inactive player: {2}", gridEntity.Name, entity.EntityId, PlayerMap.Instance.GetPlayerItemFromPlayerId(player).Name));
                        entitiesFound.Add(entity);
                    }
                }
            }

            Communication.SendPrivateInformation(userId, string.Format("Found {0} grids owned by inactive users", entitiesFound.Count));
            return(true);
        }
Пример #59
0
 public override void updateProgress(Communication.Progress.ProgressUpdatedEventArgs e)
 {
     if(e.message!=null)
         this.progressBox.Header = e.message;
     applyProgress(this.progressBar1,e);
 }
Пример #60
0
 public DelegateMethod( Communication communication)
 {
     _communication = communication;
     _sender = _communication.SendMessageWithEmail;
     _sender += _communication.SendMessageWithSms;
 }