Esempio n. 1
0
        public static HttpWebRequest UploadDataAsync(Uri address, X509Certificate2 clientCert, string contentType, byte[] data,
                                                     int millisecondsTimeout, OpenWriteEventHandler openWriteCallback, DownloadProgressEventHandler downloadProgressCallback,
                                                     RequestCompletedEventHandler completedCallback)
        {
            // Create the request
            HttpWebRequest request = SetupRequest(address, clientCert);

            request.ContentLength = data.Length;
            if (!String.IsNullOrEmpty(contentType))
            {
                request.ContentType = contentType;
            }
            request.Method = "POST";

            // Create an object to hold all of the state for this request
            RequestState state = new RequestState(request, data, millisecondsTimeout, openWriteCallback,
                                                  downloadProgressCallback, completedCallback);

            // Start the request for a stream to upload to
            IAsyncResult result = request.BeginGetRequestStream(OpenWrite, state);

            // Register a timeout for the request
            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);

            return(request);
        }
Esempio n. 2
0
        static void OpenWrite(IAsyncResult ar)
        {
            RequestState state = (RequestState)ar.AsyncState;

            try
            {
                // Get the stream to write our upload to
                using (Stream uploadStream = state.Request.EndGetRequestStream(ar))
                {
                    // Fire the callback for successfully opening the stream
                    if (state.OpenWriteCallback != null)
                    {
                        state.OpenWriteCallback(state.Request);
                    }

                    // Write our data to the upload stream
                    uploadStream.Write(state.UploadData, 0, state.UploadData.Length);
                }

                // Start the request for the remote server response
                IAsyncResult result = state.Request.BeginGetResponse(GetResponse, state);
                // Register a timeout for the request
                ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state,
                                                       state.MillisecondsTimeout, true);
            }
            catch (Exception ex)
            {
                //Logger.Log.Debug("CapsBase.OpenWrite(): " + ex.Message);
                if (state.CompletedCallback != null)
                {
                    state.CompletedCallback(state.Request, null, null, ex);
                }
            }
        }
Esempio n. 3
0
 internal SystemHttpServer(ScriptExecutorGetter bc, int port, string robotName)
 {
     clientManager = bc;
     PortNum       = port;
     RobotName     = robotName;
     ThreadPool.QueueUserWorkItem(Init);
 }
Esempio n. 4
0
        void Friends_FriendOnline(object sender, FriendInfoEventArgs e)
        {
            if (!instance.GlobalSettings["show_friends_online_notifications"])
            {
                return;
            }

            ThreadPool.QueueUserWorkItem(sync =>
            {
                string name           = instance.Names.Get(e.Friend.UUID, true);
                MethodInvoker display = () =>
                {
                    DisplayNotification(e.Friend.UUID, name + " is online");
                    RefreshFriendsList();
                };

                if (InvokeRequired)
                {
                    BeginInvoke(display);
                }
                else
                {
                    display();
                }
            });
        }
        public void DoTeleport()
        {
            if (!Active)
            {
                return;
            }

            if (instance.MonoRuntime)
            {
                map?.Navigate(Path.GetDirectoryName(Application.ExecutablePath) + @"/worldmap.html");
            }

            lblStatus.Text    = "Teleporting to " + txtRegion.Text;
            prgTeleport.Style = ProgressBarStyle.Marquee;

            ThreadPool.QueueUserWorkItem(state =>
            {
                if (!client.Self.Teleport(txtRegion.Text, new Vector3((int)nudX.Value, (int)nudY.Value, (int)nudZ.Value)))
                {
                    Self_TeleportProgress(this, new TeleportEventArgs(string.Empty, TeleportStatus.Failed, TeleportFlags.Default));
                }
                InTeleport = false;
            }
                                         );
        }
        void map_DocumentCompleted(object sender, WebBrowserDocumentCompletedEventArgs e)
        {
            map.DocumentCompleted         -= new WebBrowserDocumentCompletedEventHandler(map_DocumentCompleted);
            map.AllowWebBrowserDrop        = false;
            map.WebBrowserShortcutsEnabled = false;
            map.ScriptErrorsSuppressed     = true;
            map.ObjectForScripting         = this;
            map.AllowNavigation            = false;

            if (instance.MonoRuntime)
            {
                map.Navigating += new WebBrowserNavigatingEventHandler(map_Navigating);
            }

            ThreadPool.QueueUserWorkItem(sync =>
            {
                Thread.Sleep(1000);
                if (InvokeRequired && (!instance.MonoRuntime || IsHandleCreated))
                {
                    BeginInvoke(new MethodInvoker(() =>
                    {
                        if (savedRegion != null)
                        {
                            gotoRegion(savedRegion, savedX, savedY);
                        }
                        else if (Active)
                        {
                            gotoRegion(client.Network.CurrentSim.Name, 128, 128);
                        }
                    }
                                                  ));
                }
            }
                                         );
        }
Esempio n. 7
0
        static void RunMETAbolt(string[] args)
        {
            // Increase the number of IOCP threads available. Mono defaults to a tragically low number
            int workerThreads, iocpThreads;

            ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);

            if (workerThreads < 500 || iocpThreads < 1000)
            {
                if (workerThreads < 500)
                {
                    workerThreads = 500;
                }
                if (iocpThreads < 1000)
                {
                    iocpThreads = 1000;
                }
                ThreadPool.SetMaxThreads(workerThreads, iocpThreads);
            }

            // Read command line options
            CommandLine = new CommandLine();
            CommandLineParser parser = new CommandLineParser(new CommandLineParserSettings(Console.Error));

            if (!parser.ParseArguments(args, CommandLine))
            {
                Environment.Exit(1);
            }

            // Change current working directory to METAbolt install dir
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // See if we only wanted to display list of grids
            if (CommandLine.ListGrids)
            {
                Console.WriteLine(CommandLine.GetHeader());
                Console.WriteLine();
                GridManager grids = new GridManager();
                Console.WriteLine("Use Grid ID as the parameter for --grid");
                Console.WriteLine("{0,-25} - {1}", "Grid ID", "Grid Name");
                Console.WriteLine("========================================================");

                for (int i = 0; i < grids.Count; i++)
                {
                    Console.WriteLine("{0,-25} - {1}", grids[i].ID, grids[i].Name);
                }

                Environment.Exit(0);
            }

            // Create main METAbolt instance
            METAboltInstance instance = METAboltInstance.GlobalInstance;

            Application.Run(instance.MainForm);
            OpenMetaverse.WorkPool.Shutdown();
        }
        void gotoRegion(string regionName, int simX, int simY)
        {
            savedRegion = regionName;
            savedX      = simX;
            savedY      = simY;

            if (!Visible)
            {
                return;
            }

            if (mmap != null)
            {
                if (!regionHandles.ContainsKey(regionName))
                {
                    ThreadPool.QueueUserWorkItem(sync =>
                    {
                        ManualResetEvent done = new ManualResetEvent(false);
                        EventHandler <GridRegionEventArgs> handler = (sender, e) =>
                        {
                            regionHandles[e.Region.Name] = Utils.UIntsToLong((uint)e.Region.X, (uint)e.Region.Y);
                            if (e.Region.Name == regionName)
                            {
                                done.Set();
                            }
                        };
                        client.Grid.GridRegion += handler;
                        client.Grid.RequestMapRegion(regionName, GridLayerType.Objects);
                        if (done.WaitOne(30 * 1000, false))
                        {
                            if (!instance.MonoRuntime || IsHandleCreated)
                            {
                                BeginInvoke(new MethodInvoker(() => gotoRegion(regionName, simX, simY)));
                            }
                        }
                        client.Grid.GridRegion -= handler;
                    }
                                                 );
                    return;
                }
                mmap.CenterMap(regionHandles[regionName], (uint)simX, (uint)simY, true);
                return;
            }

            if (map == null || map.Document == null)
            {
                return;
            }

            if (instance.MonoRuntime)
            {
                map.Document.InvokeScript(string.Format("gReg = \"{0}\"; gSimX = {1}; gSimY = {2}; monosucks", regionName, simX, simY));
            }
            else
            {
                map.Document.InvokeScript("gotoRegion", new object[] { regionName, simX, simY });
            }
        }
Esempio n. 9
0
        /// <summary>Raises the EachSimEvent event</summary>
        /// <param name="e">An EachSimEventEventArgs object containing the
        /// data returned from the data server</param>
        protected virtual void OnEachSimEvent(CogbotEvent e)
        {
            if (e.Verb == "On-Log-Message")
            {
                return;
            }
            if (ExpectConnected == false)
            {
                return;
            }
            EventHandler <EventArgs> handler = m_EachSimEvent;

            if (handler == null)
            {
                return;
            }
            List <Delegate> todo = new List <Delegate>();

            lock (m_EachSimEventLock)
            {
                handler = m_EachSimEvent;
                if (handler == null)
                {
                    return;
                }
                AddTodo(handler.GetInvocationList(), todo);
            }

            object sender = e.Sender ?? this;
            bool   async  = todo.Count > 3;

            foreach (var d in todo)
            {
                var         del  = (EventHandler <EventArgs>)d;
                ThreadStart task = () =>
                {
                    try
                    {
                        del(sender, (EventArgs)e);
                    }
                    catch (Exception ex)
                    {
                        LogException("OnEachSimEvent Worker", ex);
                    }
                };
                if (async)
                {
                    ThreadPool.QueueUserWorkItem(sync => task());
                }
                else
                {
                    task();
                }
            }
        }
Esempio n. 10
0
        private void btnIM_Click(object sender, EventArgs e)
        {
            if (listFriends.SelectedItems.Count == 1)
            {
                selectedFriend = (FriendInfo)listFriends.SelectedItems[0];
                instance.TabConsole.ShowIMTab(selectedFriend.UUID, selectedFriend.Name, true);
            }
            else if (listFriends.SelectedItems.Count > 1)
            {
                List <UUID> participants = new List <UUID>();
                foreach (var item in listFriends.SelectedItems)
                {
                    participants.Add(((FriendInfo)item).UUID);
                }
                UUID tmpID = UUID.Random();
                lblFriendName.Text = "Startings friends conference...";
                instance.TabConsole.DisplayNotificationInChat(lblFriendName.Text, ChatBufferTextStyle.Invisible);
                btnIM.Enabled = false;

                ThreadPool.QueueUserWorkItem(sync =>
                {
                    using (ManualResetEvent started = new ManualResetEvent(false))
                    {
                        UUID sessionID     = UUID.Zero;
                        string sessionName = string.Empty;

                        EventHandler <GroupChatJoinedEventArgs> handler = (isender, ie) =>
                        {
                            if (ie.TmpSessionID == tmpID)
                            {
                                sessionID   = ie.SessionID;
                                sessionName = ie.SessionName;
                                started.Set();
                            }
                        };

                        client.Self.GroupChatJoined += handler;
                        client.Self.StartIMConference(participants, tmpID);
                        if (started.WaitOne(30 * 1000, false))
                        {
                            instance.TabConsole.BeginInvoke(new MethodInvoker(() =>
                            {
                                instance.TabConsole.AddConferenceIMTab(sessionID, sessionName);
                                instance.TabConsole.SelectTab(sessionID.ToString());
                            }
                                                                              ));
                        }
                        client.Self.GroupChatJoined -= handler;
                        BeginInvoke(new MethodInvoker(() => RefreshFriendsList()));
                    }
                }
                                             );
            }
        }
Esempio n. 11
0
        static void RunRadegast(CommandLineOptions args)
        {
            s_CommandLineOpts = args;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // Increase the number of IOCP threads available. Mono defaults to a tragically low number
            int workerThreads, iocpThreads;

            ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);

            if (workerThreads < 500 || iocpThreads < 1000)
            {
                if (workerThreads < 500)
                {
                    workerThreads = 500;
                }
                if (iocpThreads < 1000)
                {
                    iocpThreads = 1000;
                }
                ThreadPool.SetMaxThreads(workerThreads, iocpThreads);
            }

            // Change current working directory to Radegast install dir
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
                                          ?? throw new InvalidOperationException());

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);

            // See if we only wanted to display list of grids
            if (s_CommandLineOpts.ListGrids)
            {
                Console.WriteLine(s_CommandLineOpts.GetHeader());
                Console.WriteLine();
                GridManager grids = new GridManager();
                Console.WriteLine("Use Grid ID as the parameter for --grid");
                Console.WriteLine("{0,-25} - {1}", "Grid ID", "Grid Name");
                Console.WriteLine(@"========================================================");

                for (int i = 0; i < grids.Count; i++)
                {
                    Console.WriteLine(@"{0,-25} - {1}", grids[i].ID, grids[i].Name);
                }

                Environment.Exit(0);
            }

            // Create main Radegast instance
            RadegastInstance instance = RadegastInstance.GlobalInstance;

            Application.Run(instance.MainForm);
        }
Esempio n. 12
0
        /// <summary>Process an incoming packet and raise the appropriate events</summary>
        /// <param name="sender">The sender</param>
        /// <param name="e">The EventArgs object containing the packet data</param>
        protected void CoarseLocationHandler(object sender, PacketReceivedEventArgs e)
        {
            CoarseLocationUpdatePacket coarse = (CoarseLocationUpdatePacket)e.Packet;

            // populate a dictionary from the packet, for local use
            Dictionary <UUID, Vector3> coarseEntries = new Dictionary <UUID, Vector3>();

            for (int i = 0; i < coarse.AgentData.Length; i++)
            {
                if (coarse.Location.Length > 0)
                {
                    coarseEntries[coarse.AgentData[i].AgentID] = new Vector3((int)coarse.Location[i].X, (int)coarse.Location[i].Y, (int)coarse.Location[i].Z * 4);
                }

                // the friend we are tracking on radar
                if (i == coarse.Index.Prey)
                {
                    e.Simulator.preyID = coarse.AgentData[i].AgentID;
                }
            }

            // find stale entries (people who left the sim)
            List <UUID> removedEntries = e.Simulator.avatarPositions.FindAll(delegate(UUID findID) { return(!coarseEntries.ContainsKey(findID)); });

            // anyone who was not listed in the previous update
            List <UUID> newEntries = new List <UUID>();

            lock (e.Simulator.avatarPositions.Dictionary)
            {
                // remove stale entries
                foreach (UUID trackedID in removedEntries)
                {
                    e.Simulator.avatarPositions.Dictionary.Remove(trackedID);
                }

                // add or update tracked info, and record who is new
                foreach (KeyValuePair <UUID, Vector3> entry in coarseEntries)
                {
                    if (!e.Simulator.avatarPositions.Dictionary.ContainsKey(entry.Key))
                    {
                        newEntries.Add(entry.Key);
                    }

                    e.Simulator.avatarPositions.Dictionary[entry.Key] = entry.Value;
                }
            }

            if (m_CoarseLocationUpdate != null)
            {
                ThreadPool.QueueUserWorkItem(delegate(object o)
                                             { OnCoarseLocationUpdate(new CoarseLocationUpdateEventArgs(e.Simulator, newEntries, removedEntries)); });
            }
        }
Esempio n. 13
0
        /// <summary>
        /// Fire the events registered for this packet type
        /// </summary>
        /// <param name="packetType">Incoming packet type</param>
        /// <param name="packet">Incoming packet</param>
        /// <param name="simulator">Simulator this packet was received from</param>
        internal void RaiseEvent(PacketType packetType, Packet packet, Simulator simulator)
        {
            PacketCallback callback;

            // Default handler first, if one exists
            if (_EventTable.TryGetValue(PacketType.Default, out callback) && callback.Callback != null)
            {
                if (callback.IsAsync)
                {
                    PacketCallbackWrapper wrapper;
                    wrapper.Callback  = callback.Callback;
                    wrapper.Packet    = packet;
                    wrapper.Simulator = simulator;
                    ThreadPool.QueueUserWorkItem(ThreadPoolDelegate, wrapper);
                }
                else
                {
                    try { callback.Callback(this, new PacketReceivedEventArgs(packet, simulator)); }
                    catch (Exception ex)
                    {
                        Logger.Log("Default packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client);
                    }
                }
            }

            if (_EventTable.TryGetValue(packetType, out callback) && callback.Callback != null)
            {
                if (callback.IsAsync)
                {
                    PacketCallbackWrapper wrapper;
                    wrapper.Callback  = callback.Callback;
                    wrapper.Packet    = packet;
                    wrapper.Simulator = simulator;
                    ThreadPool.QueueUserWorkItem(ThreadPoolDelegate, wrapper);
                }
                else
                {
                    try { callback.Callback(this, new PacketReceivedEventArgs(packet, simulator)); }
                    catch (Exception ex)
                    {
                        Logger.Log("Packet event handler: " + ex.ToString(), Helpers.LogLevel.Error, Client);
                    }
                }

                return;
            }

            if (packetType != PacketType.Default && packetType != PacketType.PacketAck)
            {
                Logger.DebugLog("No handler registered for packet event " + packetType, Client);
            }
        }
Esempio n. 14
0
        public static void DownloadDataAsync(HttpWebRequest request, int millisecondsTimeout,
                                             DownloadProgressEventHandler downloadProgressCallback, RequestCompletedEventHandler completedCallback)
        {
            // Create an object to hold all of the state for this request
            RequestState state = new RequestState(request, null, millisecondsTimeout, null, downloadProgressCallback,
                                                  completedCallback);

            // Start the request for the remote server response
            IAsyncResult result = request.BeginGetResponse(GetResponse, state);

            // Register a timeout for the request
            ThreadPool.RegisterWaitForSingleObject(result.AsyncWaitHandle, TimeoutCallback, state, millisecondsTimeout, true);
        }
        public void StartCheck()
        {
            if (client == null)
            {
                client = new WebClient();
                client.DownloadStringCompleted += OnDownloadStringCompleted;
            }

            ThreadPool.QueueUserWorkItem(state =>
            {
                client.DownloadStringAsync(new Uri(Properties.Resources.UpdateCheckUri));
            }
                                         );
        }
Esempio n. 16
0
 public void StartServer()
 {
     if (myServer != null)
     {
         return;
     }
     Console.WriteLine("starting testRDFServer");
     myServer = new PFEndpoint();
     //StringParser.Parse(prologEngine.rdfGraph, "<http://example.org/a1> <http://example.org/b1> <http://example.org/c1> .");
     prologEngine.connectMT("spindleMT", "rdfMT");
     prologEngine.connectMT("rdfMT", "baseKB");
     prologEngine.appendKB("triple(this,can,work).\n", "rdfMT");
     ThreadPool.QueueUserWorkItem((o) => myServer.beginService(prologEngine));
     prologEngine.EndpointCreated(myServer);
 }
Esempio n. 17
0
        private void frmPrimWorkshop_Shown(object sender, EventArgs e)
        {
            SetupGLControl();

            ThreadPool.QueueUserWorkItem(sync =>
            {
                if (Client.Network.CurrentSim.ObjectsPrimitives.ContainsKey(RootPrimLocalID))
                {
                    UpdatePrimBlocking(Client.Network.CurrentSim.ObjectsPrimitives[RootPrimLocalID]);
                    var children = Client.Network.CurrentSim.ObjectsPrimitives.FindAll(p => p.ParentID == RootPrimLocalID);
                    children.ForEach(UpdatePrimBlocking);
                }
            }
                                         );
        }
Esempio n. 18
0
        public override CmdResult ExecuteRequest(CmdRequest args)
        {
            if (args.Length < 1)
            {
                return(ShowUsage());
            }
            string cmd = args.GetString("command");

            //return ClientManager.DoCommandAll()
            // Make an immutable copy of the Clients dictionary to safely iterate over
            int[] completed   = { 0 };
            var   BotClients  = ClientManager.BotClients;
            int   count       = BotClients.Count;
            var   fromAgentID = args.CallerAgent;

            if (count == 0)
            {
                return(ClientManager.ExecuteSystemCommand(cmd, fromAgentID, WriteLine, args.CmdFlags));
            }
            CmdResult[] results   = new CmdResult[count];
            int[]       clientNum = { 0 };
            foreach (BotClient client in BotClients)
            {
                clientNum[0]++;
                ThreadPool.QueueUserWorkItem(
                    (WaitCallback)
                    delegate(object state)
                {
                    BotClient testClient  = (BotClient)state;
                    results[clientNum[0]] = testClient.ExecuteCommand(cmd, fromAgentID, WriteLine, args.CmdFlags);
                    ++completed[0];
                },
                    client);
            }
            while (completed[0] < count)
            {
                Thread.Sleep(50);
            }
            foreach (var r in results)
            {
                if (r != null)
                {
                    return(r);
                }
            }
            return(results[0]);
        }
 protected void FireNotificationCallback(NotificationEventArgs e)
 {
     if (OnNotificationDisplayed == null)
     {
         return;
     }
     try
     {
         e.Type = Type;
         ThreadPool.QueueUserWorkItem(o => Notificaton_Displayed(this, e));
     }
     catch (Exception ex)
     {
         Console.WriteLine("" + ex);
         Logger.Log("Error executing notification callback", Helpers.LogLevel.Warning, ex);
     }
 }
Esempio n. 20
0
 public void Start()
 {
     lock (StartupLock)
     {
         if (IsStarted)
         {
             return;
         }
         IsStarted = true;
         try
         {
             LogInfo("Starting " + clientManager.GetType() + " on HTTPD port " + PortNum);
             if (!httpListener.IsListening)
             {
                 if (httpListener.Prefixes.Count == 0)
                 {
                     PrefixAdd("http://*:" + PortNum + "/");
                     PrefixAdd("http://*:" + PortNum + "/hanson_robotics/");
                     if (RobotName != null)
                     {
                         PrefixAdd("http://*:" + PortNum + "/" + RobotName + "/");
                     }
                 }
                 httpListener.Start();
                 if (!SynchronouslyHandle)
                 {
                     // Starts up the http listener to process requests asynchronously.
                     // Move our listening loop off to a worker thread so that the GUI doesn't lock up.
                     ThreadPool.QueueUserWorkItem(Listen);
                     return;
                 }
                 else
                 {
                     // Also moves our listening loop off to a worker thread so that the GUI doesn't lock up.
                     ThreadPool.QueueUserWorkItem(HandleSynchronously);
                 }
             }
         }
         catch (Exception)
         {
             IsStarted = false;
         }
     }
 }
Esempio n. 21
0
        // Increase the number of IOCP threads available. Mono defaults to a tragically low number
        private static void ResizeThreadPools()
        {
            int workerThreads, iocpThreads;

            ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);

            if (workerThreads < 500 || iocpThreads < 1000)
            {
                if (workerThreads < 500)
                {
                    workerThreads = 500;
                }
                if (iocpThreads < 1000)
                {
                    iocpThreads = 1000;
                }
                ThreadPool.SetMaxThreads(workerThreads, iocpThreads);
            }
        }
Esempio n. 22
0
        void Friends_FriendshipTerminated(object sender, FriendshipTerminatedEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(sync =>
            {
                string name           = instance.Names.Get(e.AgentID, true);
                MethodInvoker display = () =>
                {
                    DisplayNotification(e.AgentID, name + " is no longer on your friend list");
                    RefreshFriendsList();
                };

                if (InvokeRequired)
                {
                    BeginInvoke(display);
                }
                else
                {
                    display();
                }
            });
        }
Esempio n. 23
0
        private void btnNewPick_Click(object sender, EventArgs e)
        {
            ThreadPool.QueueUserWorkItem(sync =>
            {
                UUID parcelID = client.Parcels.RequestRemoteParcelID(client.Self.SimPosition, client.Network.CurrentSim.Handle, client.Network.CurrentSim.ID);
                newPickID     = UUID.Random();

                client.Self.PickInfoUpdate(
                    newPickID,
                    false,
                    parcelID,
                    Instance.State.Parcel.Name,
                    client.Self.GlobalPosition,
                    Instance.State.Parcel.SnapshotID,
                    Instance.State.Parcel.Desc
                    );

                Invoke(new MethodInvoker(() => ClearPicks()));
                client.Avatars.RequestAvatarPicks(AgentID);
            });
        }
Esempio n. 24
0
        /// <summary>
        /// Fire the events registered for this event type asynchronously
        /// </summary>
        /// <param name="capsEvent">Capability name</param>
        /// <param name="message">Decoded event body</param>
        /// <param name="simulator">Reference to the simulator that
        /// generated this event</param>
        internal void BeginRaiseEvent(string capsEvent, IMessage message, Simulator simulator)
        {
            bool specialHandler = false;

            Caps.EventQueueCallback callback;

            // Default handler first, if one exists
            if (_EventTable.TryGetValue(String.Empty, out callback))
            {
                if (callback != null)
                {
                    CapsCallbackWrapper wrapper;
                    wrapper.Callback  = callback;
                    wrapper.CapsEvent = capsEvent;
                    wrapper.Message   = message;
                    wrapper.Simulator = simulator;
                    ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);
                }
            }

            // Explicit handler next
            if (_EventTable.TryGetValue(capsEvent, out callback) && callback != null)
            {
                CapsCallbackWrapper wrapper;
                wrapper.Callback  = callback;
                wrapper.CapsEvent = capsEvent;
                wrapper.Message   = message;
                wrapper.Simulator = simulator;
                ThreadPool.QueueUserWorkItem(_ThreadPoolCallback, wrapper);

                specialHandler = true;
            }

            if (!specialHandler)
            {
                Logger.Log("Unhandled CAPS event " + capsEvent, Helpers.LogLevel.Warning, Client);
            }
        }
 private void StartDisplayNameChage(string name)
 {
     ThreadPool.QueueUserWorkItem(sync =>
     {
         Client.Avatars.GetDisplayNames(new List <UUID>()
         {
             Client.Self.AgentID
         },
                                        (success, names, badIDs) =>
         {
             if (!success || names.Length < 1)
             {
                 UpdateStatus("Failed to get curret name");
             }
             else
             {
                 Client.Self.SetDisplayName(names[0].DisplayName, name);
             }
         }
                                        );
     }
                                  );
 }
Esempio n. 26
0
        /// <summary>
        /// Handle Instant Messages
        /// </summary>
        /// <param name="im"></param>
        /// <param name="simulator"></param>
        void OnInstantMessage(object sender, InstantMessageEventArgs e)
        {
            ThreadPool.QueueUserWorkItem(sync =>
            {
                Thread.Sleep(100);     // Give tab a chance to show up
                IMSession sess = null;
                string groupName;

                // All sorts of things come in as a instant messages. For actual messages
                // we need to match them up with an existing Conversation.  IM Conversations
                // are keyed by the name of the group or individual involved.
                switch (e.IM.Dialog)
                {
                case InstantMessageDialog.MessageFromAgent:
                    if (control.instance.Groups.ContainsKey(e.IM.IMSessionID))
                    {
                        // Message from a group member
                        groupName = control.instance.Groups[e.IM.IMSessionID].Name;
                        sess      = (IMSession)control.converse.GetConversation(groupName);
                        if (sess != null)
                        {
                            sess.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                        }
                        else
                        {
                            Talker.Say(e.IM.FromAgentName + ", " + e.IM.Message);
                        }
                    }
                    else if (e.IM.BinaryBucket.Length >= 2)
                    {
                        // Ad-hoc friend conference
                        sess = (IMSession)control.converse.GetConversation(Utils.BytesToString(e.IM.BinaryBucket));
                        if (sess != null)
                        {
                            sess.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                        }
                        else
                        {
                            Talker.Say(e.IM.FromAgentName + ", " + e.IM.Message);
                        }
                    }
                    else if (e.IM.FromAgentName == "Second Life")
                    {
                        Talker.Say("Second Life says " + e.IM.Message);
                    }
                    else
                    {
                        // Message from an individual
                        sess = (IMSession)control.converse.GetConversation(e.IM.FromAgentName);
                        if (sess != null)
                        {
                            sess.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                        }
                        else
                        {
                            Talker.Say(e.IM.FromAgentName + ", " + e.IM.Message);
                        }
                    }
                    break;

                case InstantMessageDialog.SessionSend:
                    if (control.instance.Groups.ContainsKey(e.IM.IMSessionID))
                    {
                        // Message from a group member
                        groupName = control.instance.Groups[e.IM.IMSessionID].Name;
                        sess      = (IMSession)control.converse.GetConversation(groupName);
                    }
                    else if (e.IM.BinaryBucket.Length >= 2)         // ad hoc friends conference
                    {
                        sess = (IMSession)control.converse.GetConversation(Utils.BytesToString(e.IM.BinaryBucket));
                    }

                    sess?.OnMessage(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.Message);
                    break;

                case InstantMessageDialog.FriendshipOffered:
                    Talker.Say(e.IM.FromAgentName + " is offering friendship.");
                    break;

                default:
                    break;
                }
            }
                                         );
        }
Esempio n. 27
0
        static void RunRadegast(CommandLineOptions args)
        {
            newOut.WriteEvent     += consoleWriter_WriteEvent;
            newOut.WriteLineEvent += consoleWriter_WriteLineEvent;
            Console.SetOut(newOut);

            //Console.SetOut(TextWriter.Null);

            // **

            Console.WriteLine("Running Radegast...");
            s_CommandLineOpts = args;
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // Increase the number of IOCP threads available. Mono defaults to a tragically low number
            int workerThreads, iocpThreads;

            ThreadPool.GetMaxThreads(out workerThreads, out iocpThreads);

            if (workerThreads < 500 || iocpThreads < 1000)
            {
                if (workerThreads < 500)
                {
                    workerThreads = 500;
                }
                if (iocpThreads < 1000)
                {
                    iocpThreads = 1000;
                }
                ThreadPool.SetMaxThreads(workerThreads, iocpThreads);
            }

            // Change current working directory to Radegast install dir
            Directory.SetCurrentDirectory(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
                                          ?? throw new InvalidOperationException());

            //Application.EnableVisualStyles();
            //Application.SetCompatibleTextRenderingDefault(false);

            // See if we only wanted to display list of grids
            if (s_CommandLineOpts.ListGrids)
            {
                Console.WriteLine(s_CommandLineOpts.GetHeader());
                Console.WriteLine();
                GridManager grids = new GridManager();
                Console.WriteLine("Use Grid ID as the parameter for --grid");
                Console.WriteLine("{0,-25} - {1}", "Grid ID", "Grid Name");
                Console.WriteLine(@"========================================================");

                for (int i = 0; i < grids.Count; i++)
                {
                    Console.WriteLine(@"{0,-25} - {1}", grids[i].ID, grids[i].Name);
                }

                Environment.Exit(0);
            }

            // Create main Radegast instance
            Console.WriteLine("Creating Radegast Instance...");
            RadegastInstance instance = RadegastInstance.GlobalInstance;

            if (s_CommandLineOpts.DisableLookAt)
            {
                Console.WriteLine("Disabling LookAt...");
                instance.GlobalSettings["disable_look_at"] = true; // Disable LookAt
            }
            if (s_CommandLineOpts.AutoReConnect)
            {
                Console.WriteLine("Enabling Auto Reconnect...");
                instance.GlobalSettings["auto_reconnect"] = true; // Enable Auto Reconnect
            }

            // Load Email Configuration
            EmailSender._smtpServer  = s_CommandLineOpts.EmailServer;
            EmailSender._smtpPort    = s_CommandLineOpts.EmailPort;
            EmailSender._smtpSsl     = s_CommandLineOpts.EmailSsl;
            EmailSender._user        = s_CommandLineOpts.EmailUsername;
            EmailSender._pass        = s_CommandLineOpts.EmailPassword;
            EmailSender._fromAddress = s_CommandLineOpts.EmailFrom;
            EmailSender._toAddress   = s_CommandLineOpts.EmailTo;

            Console.WriteLine("Running MainForm...");
            while (true)
            {
                Thread.Sleep(2000);
            }
            //Application.Run(instance.MainForm);
            //instance.MainForm = new frmMain(instance);
            //frmMain mf = instance.MainForm;
        }