Kill the heartbeat thread properly.

Kill the heartbeat thread properly.

--- OpenSim/Region/Framework/Scenes/Scene.cs
+++ OpenSim/Region/Framework/Scenes/Scene.cs
@@ -1,815 +1,816 @@
-/*
- * Copyright (c) Contributors, http://opensimulator.org/
- * See CONTRIBUTORS.TXT for a full list of copyright holders.
- *
- * Redistribution and use in source and binary forms, with or without
- * modification, are permitted provided that the following conditions are met:
- *     * Redistributions of source code must retain the above copyright
- *       notice, this list of conditions and the following disclaimer.
- *     * Redistributions in binary form must reproduce the above copyrightD
- *       notice, this list of conditions and the following disclaimer in the
- *       documentation and/or other materials provided with the distribution.
- *     * Neither the name of the OpenSimulator Project nor the
- *       names of its contributors may be used to endorse or promote products
- *       derived from this software without specific prior written permission.
- *
- * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
- * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
- * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
- * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
- * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
- * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
- * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
- * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
- * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
- * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
- */
-
-using System;
-using System.Collections.Generic;
-using System.Threading;
-using System.Reflection;
-using log4net;
-using Nini.Config;
-using Aurora.DataManager;
-using Aurora.Framework;
-using OpenMetaverse;
-using OpenMetaverse.StructuredData;
-using OpenSim.Framework;
-using OpenSim.Region.Framework.Interfaces;
-using OpenSim.Services.Interfaces;
-using GridRegion = OpenSim.Services.Interfaces.GridRegion;
-
-namespace OpenSim.Region.Framework.Scenes
-{
-    public class Scene : RegistryCore, IScene
-    {
-        #region Fields
-
-        private static readonly ILog m_log
-            = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
-
-        private List<ISceneEntity> m_PhysicsReturns = new List<ISceneEntity> ();
-        public List<ISceneEntity> PhysicsReturns
-        {
-            get { return m_PhysicsReturns; }
-        }
-
-        /// <value>
-        /// The scene graph for this scene
-        /// </value>
-        private SceneGraph m_sceneGraph;
-
-        protected readonly ClientManager m_clientManager = new ClientManager();
-
-        protected RegionInfo m_regInfo;
-        protected IClientNetworkServer m_clientServer;
-
-        protected ThreadMonitor monitor = new ThreadMonitor();
-
-        protected AuroraEventManager m_AuroraEventManager = null;
-        protected EventManager m_eventManager;
-        /// <value>
-        /// Manage events that occur in this scene (avatar movement, script rez, etc.).  Commonly used by region modules
-        /// to subscribe to scene events.
-        /// </value>
-        public EventManager EventManager
-        {
-            get { return m_eventManager; }
-        }
-        /// <summary>
-        /// Generic manager to send and recieve events. Used mainly by region modules
-        /// </summary>
-        public AuroraEventManager AuroraEventManager
-        {
-            get { return m_AuroraEventManager; }
-        }
-
-        private SceneManager m_sceneManager;
-
-        public SceneManager SceneManager
-        {
-            get { return m_sceneManager; }
-        }
-
-        protected ScenePermissions m_permissions;
-        /// <summary>
-        /// Controls permissions for the Scene
-        /// </summary>
-        public ScenePermissions Permissions
-        {
-            get { return m_permissions; }
-        }
-
-        protected IConfigSource m_config;
-
-        protected AgentCircuitManager m_authenticateHandler;
-
-        // Central Update Loop
-
-        protected uint m_frame;
-        /// <summary>
-        /// The current frame #
-        /// </summary>
-        public uint Frame
-        {
-            get { return m_frame; }
-        }
-
-        private float m_basesimfps = 45f;
-        private float m_basesimphysfps = 45f;
-
-        protected float m_updatetimespan = 0.022f;
-        protected float m_physicstimespan = 0.022f;
-        protected DateTime m_lastphysupdate = DateTime.UtcNow;
-
-        private int m_update_physics = 1; //Trigger the physics update
-        private int m_update_entities = 5; // Send prim updates for clients
-        private int m_update_events = 1; //Trigger the OnFrame event and tell any modules about the new frame
-        private int m_update_coarse_locations = 30; //Trigger the sending of coarse location updates (minimap updates)
-
-        private volatile bool shuttingdown = false;
-
-        public bool ShouldRunHeartbeat = true;
-
-        #endregion
-
-        #region Properties
-
-        public PhysicsScene PhysicsScene
-        {
-            get { return m_sceneGraph.PhysicsScene; }
-            set { m_sceneGraph.PhysicsScene = value; }
-        }
-
-        public float BaseSimFPS
-        {
-            get { return m_basesimfps; }
-        }
-
-        public float BaseSimPhysFPS
-        {
-            get { return m_basesimphysfps; }
-        }
-
-        public AgentCircuitManager AuthenticateHandler
-        {
-            get { return m_authenticateHandler; }
-        }
-
-        public ISimulationDataStore SimulationDataService
-        {
-            get { return m_sceneManager.SimulationDataService; }
-        }
-
-        public bool ShuttingDown
-        {
-            get { return shuttingdown; }
-        }
-
-        public ISceneGraph SceneGraph
-        {
-            get { return m_sceneGraph; }
-        }
-
-        public RegionInfo RegionInfo
-        {
-            get { return m_regInfo; }
-            set { m_regInfo = value; }
-        }
-
-        // This gets locked so things stay thread safe.
-        public object SyncRoot
-        {
-            get { return m_sceneGraph.m_syncRoot; }
-        }
-
-        public EntityManager Entities
-        {
-            get { return m_sceneGraph.Entities; }
-        }
-
-        public IConfigSource Config
-        {
-            get { return m_config; }
-            set { m_config = value; }
-        }
-
-        public float TimeDilation
-        {
-            get { return m_sceneGraph.PhysicsScene.TimeDilation; }
-            set { m_sceneGraph.PhysicsScene.TimeDilation = value; }
-        }
-
-        public override string ToString()
-        {
-            return "Name: " + m_regInfo.RegionName + ", Loc: " +
-                m_regInfo.RegionLocX / Constants.RegionSize + "," +
-                m_regInfo.RegionLocY / Constants.RegionSize + ", Size: " +
-                m_regInfo.RegionSizeX + "," +
-                m_regInfo.RegionSizeY +
-                ", Port: " + m_regInfo.InternalEndPoint.Port +
-            ", Internal address: " + m_regInfo.InternalEndPoint.Address +
-            ", External address: " + m_regInfo.ExternalHostName;
-        }
-
-        #region Services
-
-        public IAssetService AssetService
-        {
-            get
-            {
-                return RequestModuleInterface<IAssetService>();
-            }
-        }
-
-        public IAuthenticationService AuthenticationService
-        {
-            get
-            {
-                return RequestModuleInterface<IAuthenticationService>();
-            }
-        }
-
-        public IAvatarService AvatarService
-        {
-            get
-            {
-                return RequestModuleInterface<IAvatarService>();
-            }
-        }
-
-        public IGridService GridService
-        {
-            get
-            {
-                return RequestModuleInterface<IGridService>();
-            }
-        }
-
-        public IInventoryService InventoryService
-        {
-            get
-            {
-                return RequestModuleInterface<IInventoryService>();
-            }
-        }
-
-        public ISimulationService SimulationService
-        {
-            get
-            {
-                return RequestModuleInterface<ISimulationService>();
-            }
-        }
-
-        public IUserAccountService UserAccountService
-        {
-            get
-            {
-                return RequestModuleInterface<IUserAccountService>();
-            }
-        }
-
-        #endregion
-
-        #endregion
-
-        #region Constructors
-
-        public void Initialize (RegionInfo regionInfo)
-        {
-            m_regInfo = regionInfo;
-        }
-
-        public void Initialize (RegionInfo regionInfo, AgentCircuitManager authen, IClientNetworkServer clientServer)
-        {
-            Initialize (regionInfo);
-
-            //Set up the clientServer
-            m_clientServer = clientServer;
-            clientServer.AddScene (this);
-
-            m_sceneManager = RequestModuleInterface<SceneManager>();
-
-            m_config = m_sceneManager.ConfigSource;
-            m_authenticateHandler = authen;
-
-            m_AuroraEventManager = new AuroraEventManager();
-            m_eventManager = new EventManager();
-            m_permissions = new ScenePermissions(this);
-
-            // Load region settings
-            m_regInfo.RegionSettings = m_sceneManager.SimulationDataService.LoadRegionSettings(m_regInfo.RegionID);
-
-            m_sceneGraph = new SceneGraph(this, m_regInfo);
-
-            #region Region Config
-
-            IConfig aurorastartupConfig = m_config.Configs["AuroraStartup"];
-            if (aurorastartupConfig != null)
-            {
-                //Region specific is still honored here, the RegionInfo checks for it
-                RegionInfo.ObjectCapacity = aurorastartupConfig.GetInt("ObjectCapacity", 80000);
-            }
-
-            IConfig packetConfig = m_config.Configs["PacketPool"];
-            if (packetConfig != null)
-            {
-                PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
-                PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
-            }
-
-            #endregion Region Config
-
-            m_basesimfps = 45f;
-            m_basesimphysfps = 45f;
-
-            m_basesimphysfps = Config.Configs["Physics"].GetFloat("BasePhysicsFPS", 45f);
-            if (m_basesimphysfps > 45f)
-                m_basesimphysfps = 45f;
-
-            m_basesimfps = Config.Configs["Protection"].GetFloat("BaseRateFramesPerSecond", 45f);
-            if (m_basesimfps > 45f)
-                m_basesimfps = 45f;
-
-            if (m_basesimphysfps > m_basesimfps)
-                m_basesimphysfps = m_basesimfps;
-
-            m_updatetimespan = 1 / m_basesimfps;
-            m_physicstimespan = 1 / m_basesimphysfps;
-
-            #region Startup Complete config
-
-            EventManager.OnAddToStartupQueue += AddToStartupQueue;
-            EventManager.OnModuleFinishedStartup += FinishedStartup;
-            EventManager.OnStartupComplete += StartupComplete;
-
-            AddToStartupQueue("Startup");
-
-            #endregion
-        }
-
-        #endregion Constructors
-
-        #region Close
-
-        /// <summary>
-        /// This is the method that shuts down the scene.
-        /// </summary>
-        public void Close()
-        {
-            m_log.InfoFormat("[Scene]: Closing down the single simulator: {0}", RegionInfo.RegionName);
-
-            // Kick all ROOT agents with the message, 'The simulator is going down'
-            ForEachScenePresence (delegate (IScenePresence avatar)
-            {
-                if (!avatar.IsChildAgent)
-                    avatar.ControllingClient.Kick("The simulator is going down.");
-            });
-
-            IEntityTransferModule transferModule = RequestModuleInterface<IEntityTransferModule> ();
-            if (transferModule != null)
-            {
-                foreach (IScenePresence avatar in GetScenePresences ())
-                {
-                    transferModule.IncomingCloseAgent (this, avatar.UUID);
-                }
-            }
-            //Stop the heartbeat
-            monitor.Stop();
-
-            if (m_sceneGraph.PhysicsScene != null)
-                m_sceneGraph.PhysicsScene.Dispose ();
-
-            //Tell the neighbors that this region is now down
-            INeighborService service = RequestModuleInterface<INeighborService>();
-            if (service != null)
-                service.InformNeighborsThatRegionIsDown(RegionInfo);
-
-            // Stop updating the scene objects and agents.
-            shuttingdown = true;
-
-            m_sceneGraph.Close();
-        }
-
-        #endregion
-
-        #region Tracker
-
-        /// <summary>
-        /// Start the heartbeat which triggers regular scene updates
-        /// </summary>
-        public void StartHeartbeat()
-        {
-            if (!ShouldRunHeartbeat) //Allow for the heartbeat to not be used
-                return;
-
-            m_clientServer.Start ();
-
-            //Give it the heartbeat delegate with an infinite timeout
-            monitor.StartTrackingThread(0, Update);
-            //Then start the thread for it with an infinite loop time and no
-            //  sleep overall as the Update delete does it on it's own
-            monitor.StartMonitor(0, 0);
-        }
-
-        #endregion
-
-        #region Scene Heartbeat Methods
-
-        private bool Update()
-        {
-            ISimFrameMonitor simFrameMonitor = (ISimFrameMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "SimFrameStats");
-            ITotalFrameTimeMonitor totalFrameMonitor = (ITotalFrameTimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Total Frame Time");
-            ISetMonitor lastFrameMonitor = (ISetMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Last Completed Frame At");
-            ITimeMonitor otherFrameMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Other Frame Time");
-            ITimeMonitor sleepFrameMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Sleep Frame Time");
-            IPhysicsFrameMonitor physicsFrameMonitor = (IPhysicsFrameMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Total Physics Frame Time");
-            ITimeMonitor physicsSyncFrameMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Physics Sync Frame Time");
-            ITimeMonitor physicsFrameTimeMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Physics Update Frame Time");
-            IPhysicsMonitor monitor = RequestModuleInterface<IPhysicsMonitor>();
-            while (true)
-            {
-                if (!ShouldRunHeartbeat) //If we arn't supposed to be running, kill ourselves
-                    return false;
-
-                int maintc = Util.EnvironmentTickCount();
-                int BeginningFrameTime = maintc;
-                // Increment the frame counter
-                ++m_frame;
-
-                try
-                {
-                    int OtherFrameTime = Util.EnvironmentTickCount();
-                    if (PhysicsReturns.Count != 0)
-                    {
-                        lock (PhysicsReturns)
-                        {
-                            ILLClientInventory inventoryModule = RequestModuleInterface<ILLClientInventory>();
-                            if (inventoryModule != null)
-                                inventoryModule.ReturnObjects(PhysicsReturns.ToArray(), UUID.Zero);
-                            PhysicsReturns.Clear();
-                        }
-                    }
-                    if (m_frame % m_update_coarse_locations == 0)
-                    {
-                        List<Vector3> coarseLocations;
-                        List<UUID> avatarUUIDs;
-                        SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
-                        // Send coarse locations to clients
-                        foreach (IScenePresence presence in GetScenePresences())
-                        {
-                            presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
-                        }
-                    }
-
-                    if (m_frame % m_update_entities == 0)
-                        m_sceneGraph.UpdateEntities();
-
-                    if (m_frame % m_update_events == 0)
-                        m_eventManager.TriggerOnFrame();
-
-                    int PhysicsSyncTime = Util.EnvironmentTickCount();
-                    TimeSpan SinceLastFrame = DateTime.UtcNow - m_lastphysupdate;
-
-                    if ((m_frame % m_update_physics == 0) && !RegionInfo.RegionSettings.DisablePhysics)
-                        m_sceneGraph.UpdatePreparePhysics();
-
-                    int MonitorPhysicsSyncTime = Util.EnvironmentTickCountSubtract(PhysicsSyncTime);
-
-                    int PhysicsUpdateTime = Util.EnvironmentTickCount();
-
-                    if (m_frame % m_update_physics == 0)
-                    {
-                        if (!RegionInfo.RegionSettings.DisablePhysics && SinceLastFrame.TotalSeconds > m_physicstimespan)
-                        {
-                            m_sceneGraph.UpdatePhysics(SinceLastFrame.TotalSeconds);
-                            m_lastphysupdate = DateTime.UtcNow;
-                        }
-                    }
-
-                    int MonitorPhysicsUpdateTime = Util.EnvironmentTickCountSubtract(PhysicsUpdateTime) + MonitorPhysicsSyncTime;
-
-                    physicsFrameTimeMonitor.AddTime(MonitorPhysicsUpdateTime);
-                    physicsFrameMonitor.AddFPS(1);
-                    physicsSyncFrameMonitor.AddTime(MonitorPhysicsSyncTime);
-
-                    if (monitor != null)
-                        monitor.AddPhysicsStats(RegionInfo.RegionID, PhysicsScene);
-
-                    //Now fix the sim stats
-                    int MonitorOtherFrameTime = Util.EnvironmentTickCountSubtract(OtherFrameTime);
-                    int MonitorLastCompletedFrame = Util.EnvironmentTickCount();
-
-                    simFrameMonitor.AddFPS(1);
-                    lastFrameMonitor.SetValue(MonitorLastCompletedFrame);
-                    otherFrameMonitor.AddTime(MonitorOtherFrameTime);
-
-                    maintc = Util.EnvironmentTickCountSubtract(maintc);
-                    maintc = (int)(m_updatetimespan * 1000) - maintc;
-                }
-                catch (Exception e)
-                {
-                    m_log.Error("[REGION]: Failed with exception " + e.ToString() + " in region: " + RegionInfo.RegionName);
-                    return true;
-                }
-
-                int MonitorEndFrameTime = Util.EnvironmentTickCountSubtract(BeginningFrameTime) + maintc;
-
-                if (maintc > 0 && maintc < 100)
-                    Thread.Sleep(maintc);
-
-                sleepFrameMonitor.AddTime(maintc);
-
-                totalFrameMonitor.AddFrameTime(MonitorEndFrameTime);
-            }
-        }
-
-        #endregion
-
-        #region Add/Remove Avatar Methods
-
-        /// <summary>
-        /// Adding a New Client and Create a Presence for it.
-        /// Called by the LLClientView when the UseCircuitCode packet comes in
-        /// Used by NPCs to add themselves to the Scene
-        /// </summary>
-        /// <param name="client"></param>
-        public void AddNewClient(IClientAPI client)
-        {
-            try
-            {
-                System.Net.IPEndPoint ep = (System.Net.IPEndPoint)client.GetClientEP();
-                AgentCircuitData aCircuit = AuthenticateHandler.AuthenticateSession(client.SessionId, client.AgentId, client.CircuitCode, ep);
-
-                if (aCircuit == null) // no good, didn't pass NewUserConnection successfully
-                    return;
-
-                m_clientManager.Add (client);
-
-                //Create the scenepresence
-                IScenePresence sp = m_sceneGraph.CreateAndAddChildScenePresence (client);
-                sp.IsChildAgent = aCircuit.child;
-
-
-                //Trigger events
-                m_eventManager.TriggerOnNewPresence (sp);
-
-                //Make sure the appearanace is updated
-                if (aCircuit != null)
-                {
-                    IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule> ();
-                    if (appearance != null)
-                        appearance.Appearance = aCircuit.Appearance;
-                }
-
-                if (GetScenePresence(client.AgentId) != null)
-                {
-                    EventManager.TriggerOnNewClient(client);
-                    if ((aCircuit.teleportFlags & (uint)TeleportFlags.ViaLogin) != 0)
-                        EventManager.TriggerOnClientLogin(client);
-                }
-
-                //Add the client to login stats
-                ILoginMonitor monitor = (ILoginMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor("", "LoginMonitor");
-                if ((aCircuit.teleportFlags & (uint)TeleportFlags.ViaLogin) != 0 && monitor != null)
-                {
-                    monitor.AddSuccessfulLogin();
-                }
-            }
-            catch(Exception ex)
-            {
-                m_log.Warn("[Scene]: Error in AddNewClient: " + ex.ToString());
-            }
-        }
-
-        /// <summary>
-        /// Tell a single agent to disconnect from the region.
-        /// Does not send the DisableSimulator EQM or close child agents
-        /// </summary>
-        /// <param name="?"></param>
-        /// <returns></returns>
-        public bool RemoveAgent (IScenePresence presence)
-        {
-            presence.ControllingClient.Close ();
-            if (presence.ParentID != UUID.Zero)
-            {
-                presence.StandUp ();
-            }
-
-            EventManager.TriggerClientClosed (presence.UUID, this);
-            EventManager.TriggerOnClosingClient (presence.ControllingClient);
-            EventManager.TriggerOnRemovePresence (presence);
-
-            ForEachClient (
-                delegate (IClientAPI client)
-                {
-                    //We can safely ignore null reference exceptions.  It means the avatar is dead and cleaned up anyway
-                    try { client.SendKillObject (presence.Scene.RegionInfo.RegionHandle, new IEntity[] { presence }); }
-                    catch (NullReferenceException) { }
-                });
-
-            try
-            {
-                presence.Close ();
-            }
-            catch (Exception e)
-            {
-                m_log.Error ("[SCENE] Scene.cs:RemoveClient:Presence.Close exception: " + e.ToString ());
-            }
-
-            //Remove any interfaces it might have stored
-            presence.RemoveAllInterfaces ();
-
-            // Remove the avatar from the scene
-            m_sceneGraph.RemoveScenePresence (presence);
-            m_clientManager.Remove (presence.UUID);
-
-            AuthenticateHandler.RemoveCircuit (presence.ControllingClient.CircuitCode);
-            //m_log.InfoFormat("[SCENE] Memory pre  GC {0}", System.GC.GetTotalMemory(false));
-            //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
-            return true;
-        }
-
-        #endregion
-
-        #region SceneGraph wrapper methods
-
-        /// <summary>
-        /// Request a scene presence by UUID. Fast, indexed lookup.
-        /// </summary>
-        /// <param name="agentID"></param>
-        /// <returns>null if the presence was not found</returns>
-        public IScenePresence GetScenePresence (UUID agentID)
-        {
-            return m_sceneGraph.GetScenePresence (agentID);
-        }
-
-        public IScenePresence GetScenePresence (uint agentID)
-        {
-            return m_sceneGraph.GetScenePresence (agentID);
-        }
-
-        /// <summary>
-        /// Performs action on all scene presences.
-        /// </summary>
-        /// <param name="action"></param>
-        public void ForEachScenePresence (Action<IScenePresence> action)
-        {
-            if (m_sceneGraph != null)
-            {
-                m_sceneGraph.ForEachScenePresence(action);
-            }
-        }
-
-        public List<IScenePresence> GetScenePresences ()
-        {
-            return new List<IScenePresence> (m_sceneGraph.GetScenePresences ());
-        }
-
-        public int GetScenePresenceCount()
-        {
-            return Entities.GetPresenceCount();
-        }
-
-        /// <summary>
-        /// Get a prim via its local id
-        /// </summary>
-        /// <param name="localID"></param>
-        /// <returns></returns>
-        public ISceneChildEntity GetSceneObjectPart (uint localID)
-        {
-            ISceneChildEntity entity;
-            m_sceneGraph.TryGetPart(localID, out entity);
-            return entity;
-        }
-
-        /// <summary>
-        /// Get a prim via its UUID
-        /// </summary>
-        /// <param name="fullID"></param>
-        /// <returns></returns>
-        public ISceneChildEntity GetSceneObjectPart (UUID ObjectID)
-        {
-            ISceneChildEntity entity;
-            m_sceneGraph.TryGetPart(ObjectID, out entity);
-            return entity as SceneObjectPart;
-        }
-
-        public bool TryGetPart (UUID objectUUID, out ISceneChildEntity SensedObject)
-        {
-            return m_sceneGraph.TryGetPart (objectUUID, out SensedObject);
-        }
-
-        /// <summary>
-        /// Get a scene object group that contains the prim with the given local id
-        /// </summary>
-        /// <param name="localID"></param>
-        /// <returns>null if no scene object group containing that prim is found</returns>
-        public ISceneEntity GetGroupByPrim (uint localID)
-        {
-            ISceneChildEntity part = GetSceneObjectPart (localID);
-            if (part != null)
-                return part.ParentEntity;
-            return null;
-        }
-
-        public bool TryGetScenePresence (UUID avatarId, out IScenePresence avatar)
-        {
-            return m_sceneGraph.TryGetScenePresence(avatarId, out avatar);
-        }
-
-        public bool TryGetAvatarByName (string avatarName, out IScenePresence avatar)
-        {
-            return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
-        }
-
-        public void ForEachClient(Action<IClientAPI> action)
-        {
-            m_clientManager.ForEachSync(action);
-        }
-
-        public bool TryGetClient(UUID avatarID, out IClientAPI client)
-        {
-            return m_clientManager.TryGetValue(avatarID, out client);
-        }
-
-        public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
-        {
-            return m_clientManager.TryGetValue(remoteEndPoint, out client);
-        }
-
-        public void ForEachSOG(Action<SceneObjectGroup> action)
-        {
-            m_sceneGraph.ForEachSOG(action);
-        }
-
-        #endregion
-
-        #region Startup Complete
-
-        private List<string> StartupCallbacks = new List<string>();
-        private List<string> StartupData = new List<string>();
-
-        /// <summary>
-        /// Add a module to the startup queue
-        /// </summary>
-        /// <param name="name"></param>
-        public void AddToStartupQueue(string name)
-        {
-            IConfig startupConfig = m_config.Configs["Startup"];
-            if ((startupConfig != null &&
-                !startupConfig.GetBoolean("CompleteStartupAfterAllModulesLoad", true)) ||
-                name == "Startup") //We allow startup through to allow for normal starting up, even if all module loading is disabled
-            {
-                StartupCallbacks.Add(name);
-            }
-        }
-
-        /// <summary>
-        /// This module finished startup and is giving a list of data about its startup
-        /// </summary>
-        /// <param name="name"></param>
-        /// <param name="data"></param>
-        public void FinishedStartup(string name, List<string> data)
-        {
-            if (StartupCallbacks.Contains(name))
-            {
-                StartupCallbacks.Remove(name);
-                if (data.Count != 0)
-                {
-                    List<string> NewData = new List<string>(data.Count + 2); //Fixed size to reduce memory
-                    NewData.Add(name);
-                    NewData.Add(data.Count.ToString());
-                    NewData.AddRange(data);
-                    StartupData.AddRange(NewData);
-                }
-                if (StartupCallbacks.Count == 0)
-                {
-                    //All callbacks are done, trigger startup complete
-                    EventManager.TriggerStartupComplete(this, StartupData);
-                }
-            }
-        }
-
-        /// <summary>
-        /// Startup is complete, trigger the modules and allow logins
-        /// </summary>
-        /// <param name="data"></param>
-        public void StartupComplete(IScene scene, List<string> data)
-        {
-            // In 99.9% of cases it is a bad idea to manually force garbage collection. However,
-            // this is a rare case where we know we have just went through a long cycle of heap
-            // allocations, and there is no more work to be done until someone logs in
-            GC.Collect();
-
-            m_log.Info("[Region]: Startup Complete in region " + RegionInfo.RegionName);
-
-            //Tell the SceneManager about it
-            m_sceneManager.HandleStartupComplete(this, data);
-        }
-
-        #endregion
-    }
+/*
+ * Copyright (c) Contributors, http://opensimulator.org/
+ * See CONTRIBUTORS.TXT for a full list of copyright holders.
+ *
+ * Redistribution and use in source and binary forms, with or without
+ * modification, are permitted provided that the following conditions are met:
+ *     * Redistributions of source code must retain the above copyright
+ *       notice, this list of conditions and the following disclaimer.
+ *     * Redistributions in binary form must reproduce the above copyrightD
+ *       notice, this list of conditions and the following disclaimer in the
+ *       documentation and/or other materials provided with the distribution.
+ *     * Neither the name of the OpenSimulator Project nor the
+ *       names of its contributors may be used to endorse or promote products
+ *       derived from this software without specific prior written permission.
+ *
+ * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY
+ * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
+ * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
+ * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY
+ * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
+ * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
+ * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
+ * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
+ * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
+ * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
+ */
+
+using System;
+using System.Collections.Generic;
+using System.Threading;
+using System.Reflection;
+using log4net;
+using Nini.Config;
+using Aurora.DataManager;
+using Aurora.Framework;
+using OpenMetaverse;
+using OpenMetaverse.StructuredData;
+using OpenSim.Framework;
+using OpenSim.Region.Framework.Interfaces;
+using OpenSim.Services.Interfaces;
+using GridRegion = OpenSim.Services.Interfaces.GridRegion;
+
+namespace OpenSim.Region.Framework.Scenes
+{
+    public class Scene : RegistryCore, IScene
+    {
+        #region Fields
+
+        private static readonly ILog m_log
+            = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
+
+        private List<ISceneEntity> m_PhysicsReturns = new List<ISceneEntity> ();
+        public List<ISceneEntity> PhysicsReturns
+        {
+            get { return m_PhysicsReturns; }
+        }
+
+        /// <value>
+        /// The scene graph for this scene
+        /// </value>
+        private SceneGraph m_sceneGraph;
+
+        protected readonly ClientManager m_clientManager = new ClientManager();
+
+        protected RegionInfo m_regInfo;
+        protected IClientNetworkServer m_clientServer;
+
+        protected ThreadMonitor monitor = new ThreadMonitor();
+
+        protected AuroraEventManager m_AuroraEventManager = null;
+        protected EventManager m_eventManager;
+        /// <value>
+        /// Manage events that occur in this scene (avatar movement, script rez, etc.).  Commonly used by region modules
+        /// to subscribe to scene events.
+        /// </value>
+        public EventManager EventManager
+        {
+            get { return m_eventManager; }
+        }
+        /// <summary>
+        /// Generic manager to send and recieve events. Used mainly by region modules
+        /// </summary>
+        public AuroraEventManager AuroraEventManager
+        {
+            get { return m_AuroraEventManager; }
+        }
+
+        private SceneManager m_sceneManager;
+
+        public SceneManager SceneManager
+        {
+            get { return m_sceneManager; }
+        }
+
+        protected ScenePermissions m_permissions;
+        /// <summary>
+        /// Controls permissions for the Scene
+        /// </summary>
+        public ScenePermissions Permissions
+        {
+            get { return m_permissions; }
+        }
+
+        protected IConfigSource m_config;
+
+        protected AgentCircuitManager m_authenticateHandler;
+
+        // Central Update Loop
+
+        protected uint m_frame;
+        /// <summary>
+        /// The current frame #
+        /// </summary>
+        public uint Frame
+        {
+            get { return m_frame; }
+        }
+
+        private float m_basesimfps = 45f;
+        private float m_basesimphysfps = 45f;
+
+        protected float m_updatetimespan = 0.022f;
+        protected float m_physicstimespan = 0.022f;
+        protected DateTime m_lastphysupdate = DateTime.UtcNow;
+
+        private int m_update_physics = 1; //Trigger the physics update
+        private int m_update_entities = 5; // Send prim updates for clients
+        private int m_update_events = 1; //Trigger the OnFrame event and tell any modules about the new frame
+        private int m_update_coarse_locations = 30; //Trigger the sending of coarse location updates (minimap updates)
+
+        private volatile bool shuttingdown = false;
+
+        public bool ShouldRunHeartbeat = true;
+
+        #endregion
+
+        #region Properties
+
+        public PhysicsScene PhysicsScene
+        {
+            get { return m_sceneGraph.PhysicsScene; }
+            set { m_sceneGraph.PhysicsScene = value; }
+        }
+
+        public float BaseSimFPS
+        {
+            get { return m_basesimfps; }
+        }
+
+        public float BaseSimPhysFPS
+        {
+            get { return m_basesimphysfps; }
+        }
+
+        public AgentCircuitManager AuthenticateHandler
+        {
+            get { return m_authenticateHandler; }
+        }
+
+        public ISimulationDataStore SimulationDataService
+        {
+            get { return m_sceneManager.SimulationDataService; }
+        }
+
+        public bool ShuttingDown
+        {
+            get { return shuttingdown; }
+        }
+
+        public ISceneGraph SceneGraph
+        {
+            get { return m_sceneGraph; }
+        }
+
+        public RegionInfo RegionInfo
+        {
+            get { return m_regInfo; }
+            set { m_regInfo = value; }
+        }
+
+        // This gets locked so things stay thread safe.
+        public object SyncRoot
+        {
+            get { return m_sceneGraph.m_syncRoot; }
+        }
+
+        public EntityManager Entities
+        {
+            get { return m_sceneGraph.Entities; }
+        }
+
+        public IConfigSource Config
+        {
+            get { return m_config; }
+            set { m_config = value; }
+        }
+
+        public float TimeDilation
+        {
+            get { return m_sceneGraph.PhysicsScene.TimeDilation; }
+            set { m_sceneGraph.PhysicsScene.TimeDilation = value; }
+        }
+
+        public override string ToString()
+        {
+            return "Name: " + m_regInfo.RegionName + ", Loc: " +
+                m_regInfo.RegionLocX / Constants.RegionSize + "," +
+                m_regInfo.RegionLocY / Constants.RegionSize + ", Size: " +
+                m_regInfo.RegionSizeX + "," +
+                m_regInfo.RegionSizeY +
+                ", Port: " + m_regInfo.InternalEndPoint.Port +
+            ", Internal address: " + m_regInfo.InternalEndPoint.Address +
+            ", External address: " + m_regInfo.ExternalHostName;
+        }
+
+        #region Services
+
+        public IAssetService AssetService
+        {
+            get
+            {
+                return RequestModuleInterface<IAssetService>();
+            }
+        }
+
+        public IAuthenticationService AuthenticationService
+        {
+            get
+            {
+                return RequestModuleInterface<IAuthenticationService>();
+            }
+        }
+
+        public IAvatarService AvatarService
+        {
+            get
+            {
+                return RequestModuleInterface<IAvatarService>();
+            }
+        }
+
+        public IGridService GridService
+        {
+            get
+            {
+                return RequestModuleInterface<IGridService>();
+            }
+        }
+
+        public IInventoryService InventoryService
+        {
+            get
+            {
+                return RequestModuleInterface<IInventoryService>();
+            }
+        }
+
+        public ISimulationService SimulationService
+        {
+            get
+            {
+                return RequestModuleInterface<ISimulationService>();
+            }
+        }
+
+        public IUserAccountService UserAccountService
+        {
+            get
+            {
+                return RequestModuleInterface<IUserAccountService>();
+            }
+        }
+
+        #endregion
+
+        #endregion
+
+        #region Constructors
+
+        public void Initialize (RegionInfo regionInfo)
+        {
+            m_regInfo = regionInfo;
+        }
+
+        public void Initialize (RegionInfo regionInfo, AgentCircuitManager authen, IClientNetworkServer clientServer)
+        {
+            Initialize (regionInfo);
+
+            //Set up the clientServer
+            m_clientServer = clientServer;
+            clientServer.AddScene (this);
+
+            m_sceneManager = RequestModuleInterface<SceneManager>();
+
+            m_config = m_sceneManager.ConfigSource;
+            m_authenticateHandler = authen;
+
+            m_AuroraEventManager = new AuroraEventManager();
+            m_eventManager = new EventManager();
+            m_permissions = new ScenePermissions(this);
+
+            // Load region settings
+            m_regInfo.RegionSettings = m_sceneManager.SimulationDataService.LoadRegionSettings(m_regInfo.RegionID);
+
+            m_sceneGraph = new SceneGraph(this, m_regInfo);
+
+            #region Region Config
+
+            IConfig aurorastartupConfig = m_config.Configs["AuroraStartup"];
+            if (aurorastartupConfig != null)
+            {
+                //Region specific is still honored here, the RegionInfo checks for it
+                RegionInfo.ObjectCapacity = aurorastartupConfig.GetInt("ObjectCapacity", 80000);
+            }
+
+            IConfig packetConfig = m_config.Configs["PacketPool"];
+            if (packetConfig != null)
+            {
+                PacketPool.Instance.RecyclePackets = packetConfig.GetBoolean("RecyclePackets", true);
+                PacketPool.Instance.RecycleDataBlocks = packetConfig.GetBoolean("RecycleDataBlocks", true);
+            }
+
+            #endregion Region Config
+
+            m_basesimfps = 45f;
+            m_basesimphysfps = 45f;
+
+            m_basesimphysfps = Config.Configs["Physics"].GetFloat("BasePhysicsFPS", 45f);
+            if (m_basesimphysfps > 45f)
+                m_basesimphysfps = 45f;
+
+            m_basesimfps = Config.Configs["Protection"].GetFloat("BaseRateFramesPerSecond", 45f);
+            if (m_basesimfps > 45f)
+                m_basesimfps = 45f;
+
+            if (m_basesimphysfps > m_basesimfps)
+                m_basesimphysfps = m_basesimfps;
+
+            m_updatetimespan = 1 / m_basesimfps;
+            m_physicstimespan = 1 / m_basesimphysfps;
+
+            #region Startup Complete config
+
+            EventManager.OnAddToStartupQueue += AddToStartupQueue;
+            EventManager.OnModuleFinishedStartup += FinishedStartup;
+            EventManager.OnStartupComplete += StartupComplete;
+
+            AddToStartupQueue("Startup");
+
+            #endregion
+        }
+
+        #endregion Constructors
+
+        #region Close
+
+        /// <summary>
+        /// This is the method that shuts down the scene.
+        /// </summary>
+        public void Close()
+        {
+            m_log.InfoFormat("[Scene]: Closing down the single simulator: {0}", RegionInfo.RegionName);
+
+            // Kick all ROOT agents with the message, 'The simulator is going down'
+            ForEachScenePresence (delegate (IScenePresence avatar)
+            {
+                if (!avatar.IsChildAgent)
+                    avatar.ControllingClient.Kick("The simulator is going down.");
+            });
+
+            IEntityTransferModule transferModule = RequestModuleInterface<IEntityTransferModule> ();
+            if (transferModule != null)
+            {
+                foreach (IScenePresence avatar in GetScenePresences ())
+                {
+                    transferModule.IncomingCloseAgent (this, avatar.UUID);
+                }
+            }
+            ShouldRunHeartbeat = false; //Stop the heartbeat
+            //Now close the tracker
+            monitor.Stop();
+
+            if (m_sceneGraph.PhysicsScene != null)
+                m_sceneGraph.PhysicsScene.Dispose ();
+
+            //Tell the neighbors that this region is now down
+            INeighborService service = RequestModuleInterface<INeighborService>();
+            if (service != null)
+                service.InformNeighborsThatRegionIsDown(RegionInfo);
+
+            // Stop updating the scene objects and agents.
+            shuttingdown = true;
+
+            m_sceneGraph.Close();
+        }
+
+        #endregion
+
+        #region Tracker
+
+        /// <summary>
+        /// Start the heartbeat which triggers regular scene updates
+        /// </summary>
+        public void StartHeartbeat()
+        {
+            if (!ShouldRunHeartbeat) //Allow for the heartbeat to not be used
+                return;
+
+            m_clientServer.Start ();
+
+            //Give it the heartbeat delegate with an infinite timeout
+            monitor.StartTrackingThread(0, Update);
+            //Then start the thread for it with an infinite loop time and no
+            //  sleep overall as the Update delete does it on it's own
+            monitor.StartMonitor(0, 0);
+        }
+
+        #endregion
+
+        #region Scene Heartbeat Methods
+
+        private bool Update()
+        {
+            ISimFrameMonitor simFrameMonitor = (ISimFrameMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "SimFrameStats");
+            ITotalFrameTimeMonitor totalFrameMonitor = (ITotalFrameTimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Total Frame Time");
+            ISetMonitor lastFrameMonitor = (ISetMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Last Completed Frame At");
+            ITimeMonitor otherFrameMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Other Frame Time");
+            ITimeMonitor sleepFrameMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Sleep Frame Time");
+            IPhysicsFrameMonitor physicsFrameMonitor = (IPhysicsFrameMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Total Physics Frame Time");
+            ITimeMonitor physicsSyncFrameMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Physics Sync Frame Time");
+            ITimeMonitor physicsFrameTimeMonitor = (ITimeMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor(RegionInfo.RegionID.ToString(), "Physics Update Frame Time");
+            IPhysicsMonitor monitor = RequestModuleInterface<IPhysicsMonitor>();
+            while (true)
+            {
+                if (!ShouldRunHeartbeat) //If we arn't supposed to be running, kill ourselves
+                    return false;
+
+                int maintc = Util.EnvironmentTickCount();
+                int BeginningFrameTime = maintc;
+                // Increment the frame counter
+                ++m_frame;
+
+                try
+                {
+                    int OtherFrameTime = Util.EnvironmentTickCount();
+                    if (PhysicsReturns.Count != 0)
+                    {
+                        lock (PhysicsReturns)
+                        {
+                            ILLClientInventory inventoryModule = RequestModuleInterface<ILLClientInventory>();
+                            if (inventoryModule != null)
+                                inventoryModule.ReturnObjects(PhysicsReturns.ToArray(), UUID.Zero);
+                            PhysicsReturns.Clear();
+                        }
+                    }
+                    if (m_frame % m_update_coarse_locations == 0)
+                    {
+                        List<Vector3> coarseLocations;
+                        List<UUID> avatarUUIDs;
+                        SceneGraph.GetCoarseLocations(out coarseLocations, out avatarUUIDs, 60);
+                        // Send coarse locations to clients
+                        foreach (IScenePresence presence in GetScenePresences())
+                        {
+                            presence.SendCoarseLocations(coarseLocations, avatarUUIDs);
+                        }
+                    }
+
+                    if (m_frame % m_update_entities == 0)
+                        m_sceneGraph.UpdateEntities();
+
+                    if (m_frame % m_update_events == 0)
+                        m_eventManager.TriggerOnFrame();
+
+                    int PhysicsSyncTime = Util.EnvironmentTickCount();
+                    TimeSpan SinceLastFrame = DateTime.UtcNow - m_lastphysupdate;
+
+                    if ((m_frame % m_update_physics == 0) && !RegionInfo.RegionSettings.DisablePhysics)
+                        m_sceneGraph.UpdatePreparePhysics();
+
+                    int MonitorPhysicsSyncTime = Util.EnvironmentTickCountSubtract(PhysicsSyncTime);
+
+                    int PhysicsUpdateTime = Util.EnvironmentTickCount();
+
+                    if (m_frame % m_update_physics == 0)
+                    {
+                        if (!RegionInfo.RegionSettings.DisablePhysics && SinceLastFrame.TotalSeconds > m_physicstimespan)
+                        {
+                            m_sceneGraph.UpdatePhysics(SinceLastFrame.TotalSeconds);
+                            m_lastphysupdate = DateTime.UtcNow;
+                        }
+                    }
+
+                    int MonitorPhysicsUpdateTime = Util.EnvironmentTickCountSubtract(PhysicsUpdateTime) + MonitorPhysicsSyncTime;
+
+                    physicsFrameTimeMonitor.AddTime(MonitorPhysicsUpdateTime);
+                    physicsFrameMonitor.AddFPS(1);
+                    physicsSyncFrameMonitor.AddTime(MonitorPhysicsSyncTime);
+
+                    if (monitor != null)
+                        monitor.AddPhysicsStats(RegionInfo.RegionID, PhysicsScene);
+
+                    //Now fix the sim stats
+                    int MonitorOtherFrameTime = Util.EnvironmentTickCountSubtract(OtherFrameTime);
+                    int MonitorLastCompletedFrame = Util.EnvironmentTickCount();
+
+                    simFrameMonitor.AddFPS(1);
+                    lastFrameMonitor.SetValue(MonitorLastCompletedFrame);
+                    otherFrameMonitor.AddTime(MonitorOtherFrameTime);
+
+                    maintc = Util.EnvironmentTickCountSubtract(maintc);
+                    maintc = (int)(m_updatetimespan * 1000) - maintc;
+                }
+                catch (Exception e)
+                {
+                    m_log.Error("[REGION]: Failed with exception " + e.ToString() + " in region: " + RegionInfo.RegionName);
+                    return true;
+                }
+
+                int MonitorEndFrameTime = Util.EnvironmentTickCountSubtract(BeginningFrameTime) + maintc;
+
+                if (maintc > 0 && maintc < 100)
+                    Thread.Sleep(maintc);
+
+                sleepFrameMonitor.AddTime(maintc);
+
+                totalFrameMonitor.AddFrameTime(MonitorEndFrameTime);
+            }
+        }
+
+        #endregion
+
+        #region Add/Remove Avatar Methods
+
+        /// <summary>
+        /// Adding a New Client and Create a Presence for it.
+        /// Called by the LLClientView when the UseCircuitCode packet comes in
+        /// Used by NPCs to add themselves to the Scene
+        /// </summary>
+        /// <param name="client"></param>
+        public void AddNewClient(IClientAPI client)
+        {
+            try
+            {
+                System.Net.IPEndPoint ep = (System.Net.IPEndPoint)client.GetClientEP();
+                AgentCircuitData aCircuit = AuthenticateHandler.AuthenticateSession(client.SessionId, client.AgentId, client.CircuitCode, ep);
+
+                if (aCircuit == null) // no good, didn't pass NewUserConnection successfully
+                    return;
+
+                m_clientManager.Add (client);
+
+                //Create the scenepresence
+                IScenePresence sp = m_sceneGraph.CreateAndAddChildScenePresence (client);
+                sp.IsChildAgent = aCircuit.child;
+
+
+                //Trigger events
+                m_eventManager.TriggerOnNewPresence (sp);
+
+                //Make sure the appearanace is updated
+                if (aCircuit != null)
+                {
+                    IAvatarAppearanceModule appearance = sp.RequestModuleInterface<IAvatarAppearanceModule> ();
+                    if (appearance != null)
+                        appearance.Appearance = aCircuit.Appearance;
+                }
+
+                if (GetScenePresence(client.AgentId) != null)
+                {
+                    EventManager.TriggerOnNewClient(client);
+                    if ((aCircuit.teleportFlags & (uint)TeleportFlags.ViaLogin) != 0)
+                        EventManager.TriggerOnClientLogin(client);
+                }
+
+                //Add the client to login stats
+                ILoginMonitor monitor = (ILoginMonitor)RequestModuleInterface<IMonitorModule>().GetMonitor("", "LoginMonitor");
+                if ((aCircuit.teleportFlags & (uint)TeleportFlags.ViaLogin) != 0 && monitor != null)
+                {
+                    monitor.AddSuccessfulLogin();
+                }
+            }
+            catch(Exception ex)
+            {
+                m_log.Warn("[Scene]: Error in AddNewClient: " + ex.ToString());
+            }
+        }
+
+        /// <summary>
+        /// Tell a single agent to disconnect from the region.
+        /// Does not send the DisableSimulator EQM or close child agents
+        /// </summary>
+        /// <param name="?"></param>
+        /// <returns></returns>
+        public bool RemoveAgent (IScenePresence presence)
+        {
+            presence.ControllingClient.Close ();
+            if (presence.ParentID != UUID.Zero)
+            {
+                presence.StandUp ();
+            }
+
+            EventManager.TriggerClientClosed (presence.UUID, this);
+            EventManager.TriggerOnClosingClient (presence.ControllingClient);
+            EventManager.TriggerOnRemovePresence (presence);
+
+            ForEachClient (
+                delegate (IClientAPI client)
+                {
+                    //We can safely ignore null reference exceptions.  It means the avatar is dead and cleaned up anyway
+                    try { client.SendKillObject (presence.Scene.RegionInfo.RegionHandle, new IEntity[] { presence }); }
+                    catch (NullReferenceException) { }
+                });
+
+            try
+            {
+                presence.Close ();
+            }
+            catch (Exception e)
+            {
+                m_log.Error ("[SCENE] Scene.cs:RemoveClient:Presence.Close exception: " + e.ToString ());
+            }
+
+            //Remove any interfaces it might have stored
+            presence.RemoveAllInterfaces ();
+
+            // Remove the avatar from the scene
+            m_sceneGraph.RemoveScenePresence (presence);
+            m_clientManager.Remove (presence.UUID);
+
+            AuthenticateHandler.RemoveCircuit (presence.ControllingClient.CircuitCode);
+            //m_log.InfoFormat("[SCENE] Memory pre  GC {0}", System.GC.GetTotalMemory(false));
+            //m_log.InfoFormat("[SCENE] Memory post GC {0}", System.GC.GetTotalMemory(true));
+            return true;
+        }
+
+        #endregion
+
+        #region SceneGraph wrapper methods
+
+        /// <summary>
+        /// Request a scene presence by UUID. Fast, indexed lookup.
+        /// </summary>
+        /// <param name="agentID"></param>
+        /// <returns>null if the presence was not found</returns>
+        public IScenePresence GetScenePresence (UUID agentID)
+        {
+            return m_sceneGraph.GetScenePresence (agentID);
+        }
+
+        public IScenePresence GetScenePresence (uint agentID)
+        {
+            return m_sceneGraph.GetScenePresence (agentID);
+        }
+
+        /// <summary>
+        /// Performs action on all scene presences.
+        /// </summary>
+        /// <param name="action"></param>
+        public void ForEachScenePresence (Action<IScenePresence> action)
+        {
+            if (m_sceneGraph != null)
+            {
+                m_sceneGraph.ForEachScenePresence(action);
+            }
+        }
+
+        public List<IScenePresence> GetScenePresences ()
+        {
+            return new List<IScenePresence> (m_sceneGraph.GetScenePresences ());
+        }
+
+        public int GetScenePresenceCount()
+        {
+            return Entities.GetPresenceCount();
+        }
+
+        /// <summary>
+        /// Get a prim via its local id
+        /// </summary>
+        /// <param name="localID"></param>
+        /// <returns></returns>
+        public ISceneChildEntity GetSceneObjectPart (uint localID)
+        {
+            ISceneChildEntity entity;
+            m_sceneGraph.TryGetPart(localID, out entity);
+            return entity;
+        }
+
+        /// <summary>
+        /// Get a prim via its UUID
+        /// </summary>
+        /// <param name="fullID"></param>
+        /// <returns></returns>
+        public ISceneChildEntity GetSceneObjectPart (UUID ObjectID)
+        {
+            ISceneChildEntity entity;
+            m_sceneGraph.TryGetPart(ObjectID, out entity);
+            return entity as SceneObjectPart;
+        }
+
+        public bool TryGetPart (UUID objectUUID, out ISceneChildEntity SensedObject)
+        {
+            return m_sceneGraph.TryGetPart (objectUUID, out SensedObject);
+        }
+
+        /// <summary>
+        /// Get a scene object group that contains the prim with the given local id
+        /// </summary>
+        /// <param name="localID"></param>
+        /// <returns>null if no scene object group containing that prim is found</returns>
+        public ISceneEntity GetGroupByPrim (uint localID)
+        {
+            ISceneChildEntity part = GetSceneObjectPart (localID);
+            if (part != null)
+                return part.ParentEntity;
+            return null;
+        }
+
+        public bool TryGetScenePresence (UUID avatarId, out IScenePresence avatar)
+        {
+            return m_sceneGraph.TryGetScenePresence(avatarId, out avatar);
+        }
+
+        public bool TryGetAvatarByName (string avatarName, out IScenePresence avatar)
+        {
+            return m_sceneGraph.TryGetAvatarByName(avatarName, out avatar);
+        }
+
+        public void ForEachClient(Action<IClientAPI> action)
+        {
+            m_clientManager.ForEachSync(action);
+        }
+
+        public bool TryGetClient(UUID avatarID, out IClientAPI client)
+        {
+            return m_clientManager.TryGetValue(avatarID, out client);
+        }
+
+        public bool TryGetClient(System.Net.IPEndPoint remoteEndPoint, out IClientAPI client)
+        {
+            return m_clientManager.TryGetValue(remoteEndPoint, out client);
+        }
+
+        public void ForEachSOG(Action<SceneObjectGroup> action)
+        {
+            m_sceneGraph.ForEachSOG(action);
+        }
+
+        #endregion
+
+        #region Startup Complete
+
+        private List<string> StartupCallbacks = new List<string>();
+        private List<string> StartupData = new List<string>();
+
+        /// <summary>
+        /// Add a module to the startup queue
+        /// </summary>
+        /// <param name="name"></param>
+        public void AddToStartupQueue(string name)
+        {
+            IConfig startupConfig = m_config.Configs["Startup"];
+            if ((startupConfig != null &&
+                !startupConfig.GetBoolean("CompleteStartupAfterAllModulesLoad", true)) ||
+                name == "Startup") //We allow startup through to allow for normal starting up, even if all module loading is disabled
+            {
+                StartupCallbacks.Add(name);
+            }
+        }
+
+        /// <summary>
+        /// This module finished startup and is giving a list of data about its startup
+        /// </summary>
+        /// <param name="name"></param>
+        /// <param name="data"></param>
+        public void FinishedStartup(string name, List<string> data)
+        {
+            if (StartupCallbacks.Contains(name))
+            {
+                StartupCallbacks.Remove(name);
+                if (data.Count != 0)
+                {
+                    List<string> NewData = new List<string>(data.Count + 2); //Fixed size to reduce memory
+                    NewData.Add(name);
+                    NewData.Add(data.Count.ToString());
+                    NewData.AddRange(data);
+                    StartupData.AddRange(NewData);
+                }
+                if (StartupCallbacks.Count == 0)
+                {
+                    //All callbacks are done, trigger startup complete
+                    EventManager.TriggerStartupComplete(this, StartupData);
+                }
+            }
+        }
+
+        /// <summary>
+        /// Startup is complete, trigger the modules and allow logins
+        /// </summary>
+        /// <param name="data"></param>
+        public void StartupComplete(IScene scene, List<string> data)
+        {
+            // In 99.9% of cases it is a bad idea to manually force garbage collection. However,
+            // this is a rare case where we know we have just went through a long cycle of heap
+            // allocations, and there is no more work to be done until someone logs in
+            GC.Collect();
+
+            m_log.Info("[Region]: Startup Complete in region " + RegionInfo.RegionName);
+
+            //Tell the SceneManager about it
+            m_sceneManager.HandleStartupComplete(this, data);
+        }
+
+        #endregion
+    }
 }


fix crash on VoicebankLoader.ParseOto

fix crash on VoicebankLoader.ParseOto

[00:44:16 ERR] Failed to parse
"H:\Program Files (x86)\UTAU\voice\Blue Trey CVC\oto.ini"
at line 2:
"濵濵・wav=,,,,,"
System.ArgumentException: String cannot be of zero length. (Parameter 'oldValue')
   at System.String.Replace(String oldValue, String newValue)
   at OpenUtau.Classic.VoicebankLoader.ParseOto(String line) in H:\External\Github\HeidenBZR\OpenUtau\OpenUtau.Core\Classic\VoicebankLoader.cs:line 318
   at OpenUtau.Classic.VoicebankLoader.ParseOtoSet(Stream stream, String filePath, Encoding encoding) in H:\External\Github\HeidenBZR\OpenUtau\OpenUtau.Core\Classic\VoicebankLoader.cs:line 273

--- OpenUtau.Core/Classic/VoicebankLoader.cs
+++ OpenUtau.Core/Classic/VoicebankLoader.cs
@@ -315,7 +315,12 @@
             };
             if (string.IsNullOrEmpty(result.Alias)) {
                 var ext = Path.GetExtension(wav);
-                result.Alias = wav.Replace(ext, "");
+                if (!string.IsNullOrEmpty(ext)) {
+                    result.Alias = wav.Replace(ext, "");
+                }
+                else {
+                    result.Alias = wav;
+                }
             }
             result.Phonetic = result.Alias;
             if (!ParseDouble(parts.Length < 2 ? null : parts[1], out result.Offset)) {


fix SQL issue

fix SQL issue

--- RaLibrary.Data/Managers/BorrowManager.cs
+++ RaLibrary.Data/Managers/BorrowManager.cs
@@ -44,8 +44,9 @@
                 return List();
             }

-            IQueryable<Borrow> borrows = _db.Borrows
-                .Where(b => b.Borrower == borrower);
+            List<Borrow> borrows = _db.Borrows
+                .Where(b => b.Borrower == borrower)
+                .ToList();

             List<BorrowDto> result = new List<BorrowDto>();
             foreach (Borrow borrow in borrows)


V2 of out variables.

V2 of out variables.

--- SampleCSharp7/FirstConsoleApp/Program.cs
+++ SampleCSharp7/FirstConsoleApp/Program.cs
@@ -39,7 +39,7 @@
             personHelper.PrintDataWithIsKeyword(null);
             personHelper.PrintDataWithSwitchCase(professor);

-            //Out Variables Demo
+            //Out Variables V1 Demo
             string value = "500";
             if(int.TryParse(value, out int number))
             {
@@ -47,6 +47,14 @@
             }
             WriteLine($"{number} is a valid integer");

+            //Out Variables V2 Demo
+            string value1 = "1500";
+            if (int.TryParse(value1, out var number1))
+            {
+                WriteLine($"{number1} is a valid integer");
+            }
+            WriteLine($"{number1} is a valid integer");
+
             WriteLine("\n\nPress any key...");
             ReadKey();
         }


Update KpOpcUaView.cs

Update KpOpcUaView.cs

--- ScadaComm/OpenKPs/KpOpcUa/KpOpcUaView.cs
+++ ScadaComm/OpenKPs/KpOpcUa/KpOpcUaView.cs
@@ -29,6 +29,7 @@
         /// The driver version.
         /// </summary>
         internal const string KpVersion = "5.0.0.0";
+

         /// <summary>
         /// Initializes a new instance of the class. Designed for general configuring.


timer between delete calls

timer between delete calls

--- Scripts/UnitTests/TestRetrieveAndRank.cs
+++ Scripts/UnitTests/TestRetrieveAndRank.cs
@@ -144,6 +144,12 @@
                         }
                 }

+                //	Wait before deleting config
+                m_IsDoneWaiting = false;
+                Runnable.Run(WaitUp(5f));
+                while (!m_IsDoneWaiting)
+                    yield return null;
+
                 //  Delete config
                 Log.Debug("TestRetriveAndRank", "Attempting to delete extra configs!");
                 if (cluster.Configs != null && cluster.Configs.Length > 0)


add example for Papercut

add example for Papercut

--- SendEmails/MailKitDemo/SendDemoEMails.cs
+++ SendEmails/MailKitDemo/SendDemoEMails.cs
@@ -1,3 +1,7 @@
+using System;
+using System.IO;
+using System.Threading;
+
 using MailKit.Net.Smtp;

 using MimeKit;
@@ -19,7 +23,7 @@
         /// * Run smtp4dev: smtp4dev
         /// </summary>
         [Test]
-        public void SendEMail()
+        public void SendEMailToSmtp4dev()
         {
             var message = new MimeMessage();
             message.From.Add(new MailboxAddress("Joey Tribbiani", "joey@friends.com"));
@@ -46,5 +50,54 @@
                 client.Disconnect(true);
             }
         }
+
+        /// <summary>
+        /// Run demo for mailing and see what shows up in Papercut (https://github.com/ChangemakerStudios/Papercut-SMTP)
+        /// * Install Papercut via Installer : https://github.com/ChangemakerStudios/Papercut-SMTP/releases (use exe in current release)
+        /// * Run Papercut in System menu (make sure that no other SMTP Server runs)
+        /// </summary>
+        [Test]
+        public void SendEMailToPapercut()
+        {
+            var id = Guid.NewGuid();
+            var subject = $"Test #{id.ToString().Substring(0,6)}";
+
+            var message = new MimeMessage();
+            message.From.Add(new MailboxAddress("Joey Tribbiani", "joey@friends.com"));
+            message.To.Add(new MailboxAddress("Mrs. Chanandler Bong", "chandler@friends.com"));
+            message.Subject = subject;
+
+            message.Body = new TextPart("plain")
+                               {
+                                   Text = @"Hey Chandler,
+
+I just wanted to let you know that Monica and I were going to go play some paintball, you in?
+
+-- Joey"
+                               };
+
+            using (var client = new SmtpClient())
+            {
+                client.Connect("localhost", 25, false);
+
+                // Note: only needed if the SMTP server requires authentication
+                //client.Authenticate("joey", "password");
+
+                client.Send(message);
+                client.Disconnect(true);
+            }
+
+            var pathToStorage = @"C:\Users\jg\AppData\Roaming\Changemaker Studios\Papercut SMTP\";
+            var currentDate = DateTime.Now.ToString("yyyyMMddhhmm");
+
+            Thread.Sleep(2000);
+            DirectoryInfo emailDir = new DirectoryInfo(pathToStorage);
+            FileInfo[] taskFiles = emailDir.GetFiles($"*{subject}*.eml");
+
+            foreach (var file in taskFiles)
+            {
+                Console.WriteLine(file.FullName);
+            }
+        }
     }
 }


upading namespace

upading namespace

--- 201-logic-app-workflow-1/WF-1-CreateAsset-MonitorCopyBlob/run.csx
+++ 201-logic-app-workflow-1/WF-1-CreateAsset-MonitorCopyBlob/run.csx
@@ -2,6 +2,7 @@
 #r "Microsoft.WindowsAzure.Storage"

 #load "../Shared/copyBlobHelpers.csx"
+#load "../Shared/ingestAssetConfigHelpers.csx"

 using System;
 using System.Net;


Fix broken transactionManagerService tests

--- BudgetAnalyser.UnitTest/Services/TransactionManagerServiceTest.cs
+++ BudgetAnalyser.UnitTest/Services/TransactionManagerServiceTest.cs
@@ -296,7 +296,8 @@
         [TestInitialize]
         public void TestInit()
         {
-            PrivateAccessor.SetProperty(this.testAppDb, "StatementModelStorageKey", @"C:\Foo.csv");
+            PrivateAccessor.SetProperty(this.testAppDb, "StatementModelStorageKey", @"Foo.csv");
+            PrivateAccessor.SetProperty(this.testAppDb, "FileName", @"C:\AppDb.bax");
             this.testData = StatementModelTestData.TestData2();

             this.mockBudgetBucketRepo = new Mock<IBudgetBucketRepository>();


made LinkSessionConnected.Context a property

--- x2/Events/LinkSessionDisconnected.cs
+++ x2/Events/LinkSessionDisconnected.cs
@@ -9,7 +9,7 @@
     {
         new private static readonly Tag tag;

-        public object Context;
+        public object Context { get; set; }

         static LinkSessionDisconnected()
         {


Upping version number

Upping version number

--- xUnit.BDD/Properties/AssemblyInfo.cs
+++ xUnit.BDD/Properties/AssemblyInfo.cs
@@ -6,4 +6,4 @@
 [assembly: AssemblyDescription("Extends xUnit.Net with Behavior Driven Development style fixtures.")]

 [assembly: ComVisible(false)]
-[assembly: AssemblyVersion("1.9.1.1")]
+[assembly: AssemblyVersion("1.9.2.0")]


Turns lobby music down (#3634)

Turns lobby music down (#3634)

--- Content.Client/GameObjects/EntitySystems/BackgroundAudioSystem.cs
+++ Content.Client/GameObjects/EntitySystems/BackgroundAudioSystem.cs
@@ -31,7 +31,7 @@
         private SoundCollectionPrototype _ambientCollection = default!;

         private AudioParams _ambientParams = new(-10f, 1, "Master", 0, 0, AudioMixTarget.Stereo, true, 0f);
-        private AudioParams _lobbyParams = new(5f, 1, "Master", 0, 0, AudioMixTarget.Stereo, true, 0f);
+        private AudioParams _lobbyParams = new(-5f, 1, "Master", 0, 0, AudioMixTarget.Stereo, true, 0f);

         private IPlayingAudioStream? _ambientStream;
         private IPlayingAudioStream? _lobbyStream;


Fix bug (not detecting INamespaceAuthorizer)

--- Core/NakedObjects.Metamodel/Authorization/AuthorizationManager.cs
+++ Core/NakedObjects.Metamodel/Authorization/AuthorizationManager.cs
@@ -34,10 +34,11 @@
             object authorizer = GetAuthorizer(target, lifecycleManager);
             Type authType = authorizer.GetType();

-            if (authType.IsAssignableFrom(typeof (INamespaceAuthorizer))) {
+            if ((typeof (INamespaceAuthorizer)).IsAssignableFrom(authType)) {
                 var nameAuth = (INamespaceAuthorizer) authorizer;
                 return nameAuth.IsVisible(session.Principal, target.Object, identifier.MemberName);
             }
+            //Must be an ITypeAuthorizer, including default authorizer (ITypeAuthorizer<object>)
             return isVisibleDelegates[authType](authorizer, session.Principal, target.GetDomainObject(), identifier.MemberName);
         }


Fixed a bug with the hash lookup table, much faster now

--- Duplicati/Library/Main/ForestHash/Database/LocalBackupDatabase.cs
+++ Duplicati/Library/Main/ForestHash/Database/LocalBackupDatabase.cs
@@ -138,7 +138,7 @@
             m_fileHashLookup = new HashPrefixLookup(FILE_HASH_LOOKUP_SIZE);

             using (var cmd = m_connection.CreateCommand())
-            using (var rd = cmd.ExecuteReader(@"SELECT DISTINCT ""Block"".""Hash"" FROM ""Block"", ""RemoteVolume"" WHERE ""RemoteVolume"".""Name"" = ""Block"".""File"" AND ""State"" IN (?,?,?,?) ", RemoteVolumeState.Temporary, RemoteVolumeState.Uploading, RemoteVolumeState.Uploaded, RemoteVolumeState.Verified))
+            using (var rd = cmd.ExecuteReader(@"SELECT DISTINCT ""Block"".""Hash"" FROM ""Block"", ""RemoteVolume"" WHERE ""RemoteVolume"".""Name"" = ""Block"".""File"" AND ""RemoteVolume"".""State"" IN (?,?,?,?) ", RemoteVolumeState.Temporary.ToString(), RemoteVolumeState.Uploading.ToString(), RemoteVolumeState.Uploaded.ToString(), RemoteVolumeState.Verified.ToString()))
                 while (rd.Read())
                     m_blockHashLookup.AddHash(Convert.FromBase64String(rd.GetValue(0).ToString()));

@@ -148,7 +148,7 @@
                     m_fileHashLookup.AddHash(Convert.FromBase64String(rd.GetValue(0).ToString()));

             using (var cmd = m_connection.CreateCommand())
-                m_missingBlockHashes = Convert.ToInt64(cmd.ExecuteScalar(@"SELECT COUNT (*) FROM (SELECT DISTINCT ""Block"".""Hash"", ""Block"".""Size"" FROM ""Block"", ""RemoteVolume"" WHERE ""RemoteVolume"".""Name"" = ""Block"".""File"" AND ""State"" NOT IN (?,?,?,?))", RemoteVolumeState.Temporary, RemoteVolumeState.Uploading, RemoteVolumeState.Uploaded, RemoteVolumeState.Verified));
+                m_missingBlockHashes = Convert.ToInt64(cmd.ExecuteScalar(@"SELECT COUNT (*) FROM (SELECT DISTINCT ""Block"".""Hash"", ""Block"".""Size"" FROM ""Block"", ""RemoteVolume"" WHERE ""RemoteVolume"".""Name"" = ""Block"".""File"" AND ""RemoteVolume"".""State"" NOT IN (?,?,?,?))", RemoteVolumeState.Temporary.ToString(), RemoteVolumeState.Uploading.ToString(), RemoteVolumeState.Uploaded.ToString(), RemoteVolumeState.Verified.ToString()));

         }

@@ -387,8 +387,7 @@

         public long GetFileEntry(string path, out DateTime oldScanned)
         {
-            m_selectfileSimpleCommand.SetParameterValue(0, path);
-            using(var rd = m_selectfileSimpleCommand.ExecuteReader())
+            using(var rd = m_selectfileSimpleCommand.ExecuteReader(null, path))
                 if (rd.Read())
                 {
                     oldScanned =  Convert.ToDateTime(rd.GetValue(1));


Update ScanDisplayNodes.cs

Update ScanDisplayNodes.cs

--- EDDiscovery/UserControls/HelpersScanDisplayUC/ScanDisplayNodes.cs
+++ EDDiscovery/UserControls/HelpersScanDisplayUC/ScanDisplayNodes.cs
@@ -133,7 +133,7 @@

                     nodelabels[1] = nodelabels[1].AppendPrePad(appendlabeltext, Environment.NewLine);

-                    //  nodelabels[1] = nodelabels[1].AppendPrePad("" + sn.ScanData?.BodyID, Environment.NewLine);
+//  nodelabels[1] = nodelabels[1].AppendPrePad("" + sn.ScanData?.BodyID, Environment.NewLine);

                     var ev = sc.GetEstimatedValues();
                     var PotValue = sc.EstimatedValue;


Lock wird nun auch freigegeben wenn man die Bearbeitung abbricht.

--- ILK-Protokoll/Areas/Session/Controllers/Lists/ParentController.cs
+++ ILK-Protokoll/Areas/Session/Controllers/Lists/ParentController.cs
@@ -38,7 +38,14 @@

 		public virtual PartialViewResult _FetchRow(int id)
 		{
-			return PartialView("_Row", Entities.Single(m => m.ID == id));
+			var row = Entities.Single(m => m.ID == id);
+			if (row.LockSessionID == GetSession().ID)
+			{
+				row.LockSessionID = null;
+				db.SaveChanges();
+			}
+
+			return PartialView("_Row", row);
 		}

 		[HttpPost]


WebM1 fixed linked file download

WebM1 fixed linked file download

--- MailRuCloud/MailRuCloudApi/Base/Requests/Repo/WebM1RequestRepo.cs
+++ MailRuCloud/MailRuCloudApi/Base/Requests/Repo/WebM1RequestRepo.cs
@@ -80,11 +80,11 @@
         {
             var url = new Uri($"{shard.Url}?token={Authent.AccessToken}");

-            var request = (HttpWebRequest)WebRequest.Create(url); //.OriginalString);
+            var request = (HttpWebRequest)WebRequest.Create(url);
             request.Proxy = Proxy;
             request.CookieContainer = Authent.Cookies;
             request.Method = "PUT";
-            request.ContentLength = file.OriginalSize; // + boundary.Start.LongLength + boundary.End.LongLength;
+            request.ContentLength = file.OriginalSize;
             request.Accept = "*/*";
             request.UserAgent = ConstSettings.UserAgent;
             request.AllowWriteStreamBuffering = false;
@@ -95,14 +95,10 @@
         {
             string url = shard.Type == ShardType.Get
                 ? $"{_downloadServer.Value.Url}{Uri.EscapeDataString(file.FullPath)}?token={Authent.AccessToken}"
-                : $"{shard.Url}{new Uri(ConstSettings.PublishFileLink + file.PublicLink).PathAndQuery.Remove(0, "/public".Length)}?token={Authent.AccessToken}";
-                //: $"{_weblinkGetServer.Value.Url}{new Uri(ConstSettings.PublishFileLink + file.PublicLink).PathAndQuery.Remove(0, "/public".Length)}?token={Authent.AccessToken}";
-                //: $"{_weblinkGetServer.Value.Url}{new Uri(ConstSettings.PublishFileLink + file.PublicLink).PathAndQuery.Remove(0, "/public/".Length)}?token={Authent.AccessToken}";
-
-
-
-            var request = (HttpWebRequest)WebRequest.Create(url);
-
+                : $"{shard.Url}/{file.PublicLink}?token={Authent.AccessToken}";
+            var uri = new Uri(url);
+
+            var request = (HttpWebRequest)WebRequest.Create(uri);
             request.Headers.Add("Accept-Ranges", "bytes");
             request.AddRange(instart, inend);
             request.Proxy = Proxy;
@@ -111,7 +107,10 @@
             request.ContentType = MediaTypeNames.Application.Octet;
             request.Accept = "*/*";
             request.UserAgent = ConstSettings.UserAgent;
-            request.AllowReadStreamBuffering = false;
+            request.Referer = $"{ConstSettings.CloudDomain}/home/{Uri.EscapeDataString(file.Path)}";
+            request.Headers.Add("Origin", ConstSettings.CloudDomain);
+            request.Host = uri.Host;
+            request.AllowWriteStreamBuffering = false;

             request.Timeout = 15 * 1000;


Adds better title for seeded articles

Adds better title for seeded articles

--- MvcEssentials/Data/MvcEssentials.Data/Migrations/Configuration.cs
+++ MvcEssentials/Data/MvcEssentials.Data/Migrations/Configuration.cs
@@ -75,9 +75,9 @@
             {
                 var categoriesList = new List<Models.NewsCategory>()
                 {
-                    new Models.NewsCategory() { Name = "Spors" },
-                    new Models.NewsCategory() { Name = "Crime" },
-                    new Models.NewsCategory() { Name = "Entertainment" }
+                    new NewsCategory() { Name = "Spors" },
+                    new NewsCategory() { Name = "Crime" },
+                    new NewsCategory() { Name = "Entertainment" }
                 };

                 foreach (var category in categoriesList)
@@ -112,7 +112,7 @@
                     var path = HostingEnvironment.MapPath(@"~/App_Data/Resources/Images/");
                     string adminUserName = ConfigurationManager.AppSettings["AdminUserName"];
                     var articlesToBeSeeded = new NewsArticle[5];
-                    var sampleTitle = "Title";
+                    var sampleTitle = "Article Title";
                     var sampleContent = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.";
                     var subTitle = "Lorem Ipsum is simply dummy text of the printing and typesetting industry.";
                     var categoriesCount = context.Categories.Count();
@@ -122,7 +122,7 @@
                     for (int i = 0; i < articlesToBeSeeded.Length; i++)
                     {
                         articlesToBeSeeded[i] = new NewsArticle();
-                        articlesToBeSeeded[i].Title = sampleTitle + " " + i;
+                        articlesToBeSeeded[i].Title = sampleTitle;
                         articlesToBeSeeded[i].Content = sampleContent;
                         articlesToBeSeeded[i].SampleContent = subTitle;
                         articlesToBeSeeded[i].ApplicationUserId = adminId;


Fix a bunch of assorted bugs with group IMs.

--- OpenSim/Region/CoreModules/Avatar/Groups/GroupsMessagingModule.cs
+++ OpenSim/Region/CoreModules/Avatar/Groups/GroupsMessagingModule.cs
@@ -308,7 +308,7 @@
         {
             if (m_debugEnabled) m_log.DebugFormat("[GROUPS-MESSAGING]: Session message from {0} going to agent {1}", msg.fromAgentName, msg.toAgentID);

-            UUID AgentID = msg.fromAgentID;
+            UUID AgentID = msg.toAgentID;
             UUID GroupID = msg.imSessionID;

             switch (msg.dialog)
@@ -421,7 +421,7 @@
                             //Tell 'other' agents about the new agent ('us')
                             IClientAPI otherAgent = GetActiveClient(member.AvatarKey);
                             if(otherAgent != null)//Local, so we can send it directly
-                                eq.ChatterBoxSessionAgentListUpdates(session.SessionID, Us.ToArray(), member.AvatarKey, "ENTER", SP.Scene.RegionInfo.RegionHandle);
+                                eq.ChatterBoxSessionAgentListUpdates(session.SessionID, Us.ToArray(), member.AvatarKey, "ENTER", otherAgent.Scene.RegionInfo.RegionHandle);
                             else
                             {
                                 IAsyncMessagePostService amps = m_sceneList[0].RequestModuleInterface<IAsyncMessagePostService>();
@@ -480,7 +480,7 @@
             // Send an update to the affected user
             IClientAPI affectedUser = GetActiveClient(thismember.AvatarKey);
             if(affectedUser != null)
-                eq.ChatterBoxSessionAgentListUpdates(sessionid, new OpenMetaverse.Messages.Linden.ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock[] { block }, AgentID, "", affectedUser.Scene.RegionInfo.RegionHandle);
+                eq.ChatterBoxSessionAgentListUpdates(sessionid, new OpenMetaverse.Messages.Linden.ChatterBoxSessionAgentListUpdatesMessage.AgentUpdatesBlock[] { block }, AgentID, "ENTER", affectedUser.Scene.RegionInfo.RegionHandle);
             else if(forward)
                 SendMutedUserIM(thismember, sessionid);
         }
@@ -638,7 +638,7 @@
                                 //Tell 'other' agents about the new agent ('us')
                                 IClientAPI otherAgent = GetActiveClient(member.AvatarKey);
                                 if(otherAgent != null)//Local, so we can send it directly
-                                    queue.ChatterBoxSessionAgentListUpdates(GroupID, Us.ToArray(), member.AvatarKey, "ENTER", remoteClient.Scene.RegionInfo.RegionHandle);
+                                    queue.ChatterBoxSessionAgentListUpdates(GroupID, Us.ToArray(), member.AvatarKey, "ENTER", otherAgent.Scene.RegionInfo.RegionHandle);
                                 else
                                 {
                                     IAsyncMessagePostService amps = m_sceneList[0].RequestModuleInterface<IAsyncMessagePostService>();


fix a bug in CanCopyObjectInventory; add CanDoObjectInvToObjectInv ( not wired)

--- OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
+++ OpenSim/Region/CoreModules/World/Permissions/PermissionsModule.cs
@@ -258,56 +258,65 @@
             m_scene.Permissions.OnBypassPermissions += BypassPermissions;
             m_scene.Permissions.OnSetBypassPermissions += SetBypassPermissions;
             m_scene.Permissions.OnPropagatePermissions += PropagatePermissions;
+
+            m_scene.Permissions.OnIsGridGod += IsGridAdministrator;
+            m_scene.Permissions.OnIsAdministrator += IsAdministrator;
+            m_scene.Permissions.OnIsEstateManager += IsEstateManager;
+
             m_scene.Permissions.OnGenerateClientFlags += GenerateClientFlags;
+
+            m_scene.Permissions.OnIssueEstateCommand += CanIssueEstateCommand;
+            m_scene.Permissions.OnRunConsoleCommand += CanRunConsoleCommand;
+
+            m_scene.Permissions.OnTeleport += CanTeleport;
+
+            m_scene.Permissions.OnInstantMessage += CanInstantMessage;
+
             m_scene.Permissions.OnAbandonParcel += CanAbandonParcel;
             m_scene.Permissions.OnReclaimParcel += CanReclaimParcel;
             m_scene.Permissions.OnDeedParcel += CanDeedParcel;
-            m_scene.Permissions.OnDeedObject += CanDeedObject;
-            m_scene.Permissions.OnIsGridGod += IsGridAdministrator;
-            m_scene.Permissions.OnIsAdministrator += IsAdministrator;
-            m_scene.Permissions.OnIsEstateManager += IsEstateManager;
+            m_scene.Permissions.OnSellParcel += CanSellParcel;
+            m_scene.Permissions.OnEditParcelProperties += CanEditParcelProperties;
+            m_scene.Permissions.OnTerraformLand += CanTerraformLand;
+            m_scene.Permissions.OnBuyLand += CanBuyLand;
+
+            m_scene.Permissions.OnRezObject += CanRezObject;
+            m_scene.Permissions.OnObjectEntry += CanObjectEntry;
+            m_scene.Permissions.OnReturnObjects += CanReturnObjects;
+
             m_scene.Permissions.OnDuplicateObject += CanDuplicateObject;
             m_scene.Permissions.OnDeleteObjectByIDs += CanDeleteObjectByIDs;
             m_scene.Permissions.OnDeleteObject += CanDeleteObject;
             m_scene.Permissions.OnEditObjectByIDs += CanEditObjectByIDs;
             m_scene.Permissions.OnEditObject += CanEditObject;
-            m_scene.Permissions.OnEditParcelProperties += CanEditParcelProperties;
-            m_scene.Permissions.OnInstantMessage += CanInstantMessage;
             m_scene.Permissions.OnInventoryTransfer += CanInventoryTransfer;
-            m_scene.Permissions.OnIssueEstateCommand += CanIssueEstateCommand;
             m_scene.Permissions.OnMoveObject += CanMoveObject;
-            m_scene.Permissions.OnObjectEntry += CanObjectEntry;
-            m_scene.Permissions.OnReturnObjects += CanReturnObjects;
-            m_scene.Permissions.OnRezObject += CanRezObject;
-            m_scene.Permissions.OnRunConsoleCommand += CanRunConsoleCommand;
-            m_scene.Permissions.OnRunScript += CanRunScript;
-            m_scene.Permissions.OnCompileScript += CanCompileScript;
-            m_scene.Permissions.OnSellParcel += CanSellParcel;
             m_scene.Permissions.OnTakeObject += CanTakeObject;
-            m_scene.Permissions.OnSellGroupObject += CanSellGroupObject;
             m_scene.Permissions.OnTakeCopyObject += CanTakeCopyObject;
-            m_scene.Permissions.OnTerraformLand += CanTerraformLand;
             m_scene.Permissions.OnLinkObject += CanLinkObject;
             m_scene.Permissions.OnDelinkObject += CanDelinkObject;
-            m_scene.Permissions.OnBuyLand += CanBuyLand;
+            m_scene.Permissions.OnDeedObject += CanDeedObject;
+            m_scene.Permissions.OnSellGroupObject += CanSellGroupObject;
+
+
+            m_scene.Permissions.OnCreateObjectInventory += CanCreateObjectInventory;
+            m_scene.Permissions.OnEditObjectInventory += CanEditObjectInventory;
+            m_scene.Permissions.OnCopyObjectInventory += CanCopyObjectInventory;
+            m_scene.Permissions.OnDeleteObjectInventory += CanDeleteObjectInventory;

             m_scene.Permissions.OnViewNotecard += CanViewNotecard;
             m_scene.Permissions.OnViewScript += CanViewScript;
             m_scene.Permissions.OnEditNotecard += CanEditNotecard;
             m_scene.Permissions.OnEditScript += CanEditScript;
-
-            m_scene.Permissions.OnCreateObjectInventory += CanCreateObjectInventory;
-            m_scene.Permissions.OnEditObjectInventory += CanEditObjectInventory;
-            m_scene.Permissions.OnCopyObjectInventory += CanCopyObjectInventory;
-            m_scene.Permissions.OnDeleteObjectInventory += CanDeleteObjectInventory;
             m_scene.Permissions.OnResetScript += CanResetScript;
+            m_scene.Permissions.OnRunScript += CanRunScript;
+            m_scene.Permissions.OnCompileScript += CanCompileScript;

             m_scene.Permissions.OnCreateUserInventory += CanCreateUserInventory;
             m_scene.Permissions.OnCopyUserInventory += CanCopyUserInventory;
             m_scene.Permissions.OnEditUserInventory += CanEditUserInventory;
             m_scene.Permissions.OnDeleteUserInventory += CanDeleteUserInventory;

-            m_scene.Permissions.OnTeleport += CanTeleport;

             m_scene.Permissions.OnControlPrimMedia += CanControlPrimMedia;
             m_scene.Permissions.OnInteractWithPrimMedia += CanInteractWithPrimMedia;
@@ -2061,7 +2070,7 @@
             if (sog == null)
                 return false;

-            uint perms = GetObjectPermissions(objectID, sog, true);
+            uint perms = GetObjectPermissions(userID, sog, true);
             if((perms & (uint)PermissionMask.Modify) == 0)
                 return false;

@@ -2076,6 +2085,56 @@

             if(sog.OwnerID != userID && (itperms & (uint)PermissionMask.Transfer) == 0)
                 return false;
+
+            return true;
+        }
+
+        // object inventory to object inventory item drag and drop
+        private bool CanDoObjectInvToObjectInv(TaskInventoryItem item, SceneObjectPart sourcePart, SceneObjectPart destPart)
+        {
+            DebugPermissionInformation(MethodInfo.GetCurrentMethod().Name);
+            if (m_bypassPermissions) return m_bypassPermissionsValue;
+
+            if (sourcePart == null || destPart == null || item == null)
+                return false;
+
+            SceneObjectGroup srcsog = sourcePart.ParentGroup;
+            SceneObjectGroup destsog = destPart.ParentGroup;
+            if (srcsog == null || destsog == null)
+                return false;
+
+            // dest is locked
+            if((destsog.EffectiveOwnerPerms & (uint)PermissionMask.Move) == 0)
+                return false;
+
+            uint itperms = item.CurrentPermissions;
+
+            // if item is no copy the source is modifed
+            if((itperms & (uint)PermissionMask.Copy) == 0 && (srcsog.EffectiveOwnerPerms & (uint)PermissionMask.Modify) == 0)
+                return false;
+
+            UUID srcOwner = srcsog.OwnerID;
+            UUID destOwner = destsog.OwnerID;
+            bool notSameOwner = srcOwner != destOwner;
+
+            if(notSameOwner)
+            {
+                if((itperms & (uint)PermissionMask.Transfer) == 0)
+                    return false;
+
+                // scripts can't be droped
+                if(item.InvType == (int)InventoryType.LSL)
+                    return false;
+
+                if((destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0)
+                    return false;
+            }
+            else
+            {
+                if((destPart.GetEffectiveObjectFlags() & (uint)PrimFlags.AllowInventoryDrop) == 0 &&
+                            (destsog.EffectiveOwnerPerms & (uint)PermissionMask.Modify) == 0)
+                    return false;
+            }

             return true;
         }


Make all NPCs owned by default

Make all NPCs owned by default

--- OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
+++ OpenSim/Region/ScriptEngine/Shared/Api/Implementation/OSSL_Api.cs
@@ -2242,7 +2242,7 @@
             CheckThreatLevel(ThreatLevel.High, "osNpcCreate");
             m_host.AddScriptLPS(1);

-            return NpcCreate(firstname, lastname, position, notecard, false, false);
+            return NpcCreate(firstname, lastname, position, notecard, true, false);
         }

         public LSL_Key osNpcCreate(string firstname, string lastname, LSL_Vector position, string notecard, int options)


add a failing unit test

add a failing unit test

--- tests/Avalonia.Controls.UnitTests/WindowTests.cs
+++ tests/Avalonia.Controls.UnitTests/WindowTests.cs
@@ -540,6 +540,51 @@
                 Assert.Equal(window.Position, expectedPosition);
             }
         }
+
+        [Fact]
+        public void Window_Should_Be_Centered_When_WindowStartupLocation_Is_CenterScreen_1080_175()
+        {
+            var screen1 = new Mock<Screen>(1.75, new PixelRect(new PixelSize(1920, 1080)), new PixelRect(new PixelSize(1920, 966)), true);
+
+            var screens = new Mock<IScreenImpl>();
+            screens.Setup(x => x.AllScreens).Returns(new Screen[] { screen1.Object });
+            screens.Setup(x => x.ScreenFromPoint(It.IsAny<PixelPoint>())).Returns(screen1.Object);
+
+
+            var windowImpl = MockWindowingPlatform.CreateWindowMock();
+            windowImpl.Setup(x => x.DesktopScaling).Returns(1.75);
+            windowImpl.Setup(x => x.RenderScaling).Returns(1.75);
+            windowImpl.Setup(x => x.Screen).Returns(screens.Object);
+
+            var clientSize = new Size(801.142, 366);
+
+            windowImpl.Setup(x => x.ClientSize).Returns(() => clientSize);
+
+            windowImpl.Setup(x => x.Resize(It.IsAny<Size>(), It.IsAny<PlatformResizeReason>()))
+                .Callback<Size, PlatformResizeReason>((x, y) =>
+                {
+                    clientSize = x;//.Constrain(screen1.Object.Bounds.Size.ToSize(1.75));
+                    windowImpl.Object.Resized?.Invoke(clientSize, y);
+                });
+
+            windowImpl.Setup(x => x.FrameSize).Returns(() => clientSize.Inflate(new Thickness(5, 25, 5, 5)));
+
+            using (UnitTestApplication.Start(TestServices.StyledWindow))
+            {
+                var window = new Window(windowImpl.Object);
+                window.WindowStartupLocation = WindowStartupLocation.CenterScreen;
+                window.MinWidth = 720;
+                window.MinHeight = 480;
+                //window.Width = 720;
+                //window.Height = 480;
+
+                window.Show();
+
+                var expectedPosition = new PixelPoint(321, 36);
+
+                Assert.Equal(window.Position, expectedPosition);
+            }
+        }

         [Fact]
         public void Window_Should_Be_Centered_Relative_To_Owner_When_WindowStartupLocation_Is_CenterOwner()


Small fix after merge with presence branch

--- QMunicateWin8/QMunicate.Shared/Services/CachingQuickbloxClient.cs
+++ QMunicateWin8/QMunicate.Shared/Services/CachingQuickbloxClient.cs
@@ -32,7 +32,7 @@
         public CachingQuickbloxClient(IQuickbloxClient quickbloxClient)
         {
             this.quickbloxClient = quickbloxClient;
-            quickbloxClient.ChatXmppClient.OnPresenceReceived += ChatXmppClientOnOnPresenceReceived;
+            quickbloxClient.ChatXmppClient.PresenceReceived += ChatXmppClientOnOnPresenceReceived;
         }

         #endregion


contact page fix text

contact page fix text

--- RestaurantOrganizationalManager/ROM.Web/Views/Home/Contact.cshtml
+++ RestaurantOrganizationalManager/ROM.Web/Views/Home/Contact.cshtml
@@ -19,7 +19,7 @@

 <address>

Bulgaria,

-
Sofia 1324,

+
Sofia 1322,

Phone number: +359 99 46 16 12

Marketing: Marian.Nikolov.NET.com


Add [Serializable] attribute

Add [Serializable] attribute

Enables other frameworks to report exceptions across application domains using the default binary serializer.
Add missing using statement.

--- Source/NSubstitute/Exceptions/NullSubstituteReferenceException.cs
+++ Source/NSubstitute/Exceptions/NullSubstituteReferenceException.cs
@@ -1,3 +1,4 @@
+using System;
 using System.Runtime.Serialization;

 namespace NSubstitute.Exceptions


Delete main cached files with no headers file.

--- Sources/Silphid.Loadzup/Sources/Loaders/Http/Caching/HttpCache.cs
+++ Sources/Silphid.Loadzup/Sources/Loaders/Http/Caching/HttpCache.cs
@@ -39,13 +39,22 @@

             Directory
                 .GetFiles(GetCacheDir())
-                .Where(file => file.EndsWith(HeadersExtension))
-                .ForEach(headersFile =>
+                .Where(file => !file.EndsWith(HeadersExtension))
+                .ForEach(mainFile =>
                 {
-                    var mainFile = headersFile.RemoveSuffix(HeadersExtension);
+                    // Find corresponding header
+                    var headersFile = mainFile + HeadersExtension;
+                    if (!File.Exists(headersFile))
+                    {
+                        // Main file without headers file is useless: delete it
+                        File.Delete(mainFile);
+                        deletedCount++;
+                        return;
+                    }
+
+                    // Load headers and check if expired
                     var fileDate = File.GetLastWriteTimeUtc(mainFile);
                     var headers = LoadHeaders(headersFile);
-
                     if (IsExpired(headers, utcNow, fileDate))
                     {
                         File.Delete(mainFile);