Ejemplo n.º 1
0
        /// <summary>
        /// Closes the connection if open, a query is in progress and the query
        /// has exceeded its timeout period.
        /// </summary>
        /// <param name="now">The current time (SYS).</param>
        /// <returns><c>true</c> if the connection was closed due to a timeout.</returns>
        public bool CloseIfTimeout(DateTime now)
        {
            using (TimedLock.Lock(this))
            {
                if (queryPending && this.TTD <= now)
                {
                    Close();

                    queryPending = false;
                    timedOut     = true;

                    return(true);
                }

                return(false);
            }
        }
Ejemplo n.º 2
0
        public ServerMessage method_6()
        {
            ServerMessage Message = new ServerMessage(460u);

            Message.AppendInt32(this.Int32_0);
            using (TimedLock.Lock(this.list_0))
            {
                foreach (AvatarEffect current in this.list_0)
                {
                    Message.AppendInt32(current.int_0);
                    Message.AppendInt32(current.int_1);
                    Message.AppendBoolean(!current.bool_0);
                    Message.AppendInt32(current.Int32_0);
                }
            }
            return(Message);
        }
Ejemplo n.º 3
0
        private void CreateRectangularBedGridImage(int linesInX, int linesInY)
        {
            using (TimedLock.Lock(lastCreatedBedImage, "CreateRectangularBedGridImage"))
            {
                if (linesInX == lastLinesCount.x && linesInY == lastLinesCount.y)
                {
                    BedImage = lastCreatedBedImage;
                    return;
                }
                Vector2 bedImageCentimeters = new Vector2(linesInX, linesInY);

                BedImage = new ImageBuffer(1024, 1024, 32, new BlenderBGRA());
                Graphics2D graphics2D = BedImage.NewGraphics2D();
                graphics2D.Clear(bedBaseColor);
                {
                    double lineDist = BedImage.Width / (double)linesInX;

                    int count     = 1;
                    int pointSize = 20;
                    graphics2D.DrawString(count.ToString(), 4, 4, pointSize, color: bedMarkingsColor);
                    for (double linePos = lineDist; linePos < BedImage.Width; linePos += lineDist)
                    {
                        count++;
                        int linePosInt = (int)linePos;
                        graphics2D.Line(linePosInt, 0, linePosInt, BedImage.Height, bedMarkingsColor);
                        graphics2D.DrawString(count.ToString(), linePos + 4, 4, pointSize, color: bedMarkingsColor);
                    }
                }
                {
                    double lineDist = BedImage.Height / (double)linesInY;

                    int count     = 1;
                    int pointSize = 16;
                    for (double linePos = lineDist; linePos < BedImage.Height; linePos += lineDist)
                    {
                        count++;
                        int linePosInt = (int)linePos;
                        graphics2D.Line(0, linePosInt, BedImage.Height, linePosInt, bedMarkingsColor);
                        graphics2D.DrawString(count.ToString(), 4, linePos + 4, pointSize, color: bedMarkingsColor);
                    }
                }

                lastCreatedBedImage = BedImage;
                lastLinesCount      = new Point2D(linesInX, linesInY);
            }
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Returns the endpoint to be used for cluster requests taking the parameter passed
        /// into account.
        /// </summary>
        /// <param name="key">The optional topology implementation specific key (or <c>null</c>).</param>
        /// <returns>The endpoint of the cluster service instance where the request is to be directed.</returns>
        private MsgEP GetRequestEP(object key)
        {
            int hash;

            using (TimedLock.Lock(this))
            {
                if (instances.Length == 0)
                {
                    return(broadcastEP);     // We don't know of any specific endpoints
                }
                // yet so send this to any possible service instance.

                hash = key == null?Helper.Rand() : key.GetHashCode();

                return(instances[hash % instances.Length]);
            }
        }
Ejemplo n.º 5
0
        /// <summary>
        /// Initiates a nested transaction.
        /// </summary>
        /// <returns>The nested <see cref="Transaction" />.</returns>
        /// <exception cref="TransactionException">Thrown if the transaction is not open.</exception>
        /// <exception cref="TransactionException">Thrown if the transaction is not on the top of the stack.</exception>
        public Transaction BeginTransaction()
        {
            using (TimedLock.Lock(syncLock))
            {
                if (!isOpen)
                {
                    throw new TransactionException(NotOpenMsg);
                }

                if (transBase.Count == 0 || !object.ReferenceEquals(this, transBase.Peek()))
                {
                    throw new TransactionException("This transaction is not on the top of the stack.");
                }

                return(transBase.BeginTransaction());
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Establishes a session with the authentication extension.
        /// </summary>
        /// <param name="args">The extension specific arguments (see the remarks).</param>
        /// <param name="query">Ignored for this extension.</param>
        /// <param name="perfCounters">The application's performance counter set (or <c>null</c>).</param>
        /// <param name="perfPrefix">The string to prefix any performance counter names (or <c>null</c>).</param>
        /// <remarks>
        /// <para>
        /// This extension recognises the following arguments:
        /// </para>
        /// <list type="table">
        ///     <item>
        ///         <term>Key</term>
        ///         <description>
        ///         The fully qualified name of the configuration key array with the credentials.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>MaxCacheTime</term>
        ///         <description>
        ///         Specifies the maximum time clients should retain authentication information.
        ///         This is expressed in the same format as timespans parsed by <see cref="Config.Parse(string,TimeSpan)" />.
        ///         This argument defaults to "5m".
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutCount</term>
        ///         <description>
        ///         Specifies the limiting failed authentication count.  Accounts
        ///         will be locked when the fail count reaches this number.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutThreshold</term>
        ///         <description>
        ///         The period of time that can elapse between failed authentication
        ///         attempts where the failed attempts will <b>not</b> be counted against the
        ///         <b>LockoutCount</b>.  Set this to <see cref="TimeSpan.Zero" />
        ///         to disable account lockout for the realm.
        ///         </description>
        ///     </item>
        ///     <item>
        ///         <term>LockoutTime</term>
        ///         <description>
        ///         The period of time an account will remain locked after being locked
        ///         out due to too many failed authentication attempts.
        ///         </description>
        ///     </item>
        /// </list>
        /// <para>
        /// The credentials are loaded from a configuration array holding a list
        /// of accounts, one array element, with the account fields separated by semicolons.
        /// The required fields are <b>Realm</b>, <b>Account</b>, and <b>Password</b>
        /// in that order.  Here's an example:
        /// </para>
        /// <code language="none">
        ///     Accounts[0] = lilltek.com;jeff.lill;foobar
        ///     Accounts[1] = lilltek.com;joe.blow;little.debbie
        ///     Accounts[2] = lilltek.com;jane.doe;fancy.pants
        ///     Accounts[3] = amex.com;[email protected];password.123
        /// </code>
        /// <note>
        /// All calls to <see cref="Open" /> must be matched with a call
        /// to <see cref="Close" /> or <see cref="Dispose" />.
        /// </note>
        /// </remarks>
        public void Open(ArgCollection args, string query, PerfCounterSet perfCounters, string perfPrefix)
        {
            using (TimedLock.Lock(this))
            {
                string   key;
                string[] accounts;
                string[] fields;

                if (IsOpen)
                {
                    throw new AuthenticationException("Authentication extension is already open.");
                }

                perf         = new Perf(perfCounters, perfPrefix);
                maxCacheTime = args.Get("MaxCacheTime", TimeSpan.FromMinutes(5));

                key = args.Get("Key", (string)null);
                if (key == null)
                {
                    throw new AuthenticationException("Authentication extension argument [{0}] not found.");
                }

                accounts = Config.Global.GetArray(key);
                if (accounts == null)
                {
                    accounts = new string[0];
                }

                credentials = new Dictionary <string, string>(StringComparer.OrdinalIgnoreCase);

                for (int i = 0; i < accounts.Length; i++)
                {
                    fields = accounts[i].Split(new char[] { ';' }, StringSplitOptions.None);
                    if (fields.Length != 3)
                    {
                        throw new AuthenticationException("Invalid account credentials in setting [{0}[{1}]].", key, i);
                    }

                    key = fields[0].Trim() + ":" + fields[1].Trim();
                    if (!credentials.ContainsKey(key))
                    {
                        credentials.Add(key, fields[2].Trim());
                    }
                }
            }
        }
Ejemplo n.º 7
0
        private void HandleNetwork(object sender, InterServerEventArgs <NetworkMsg> e)
        {
            using (TimedLock.Lock(_dicLock))
            {
                switch (e.Content.Code)
                {
                case NetworkCode.Join:
                    if (AddServer(e.InstanceId, e.Content.Info))
                    {
                        Log.InfoFormat("{0} ({1}, {2}) joined the network.",
                                       e.Content.Info.name, e.Content.Info.type, e.InstanceId);

                        // make new server aware of this server
                        Publish(Channel.Network, new NetworkMsg()
                        {
                            Code = NetworkCode.Join,
                            Info = _settings.serverInfo
                        });

                        NewServer?.Invoke(this, e);
                    }
                    else
                    {
                        UpdateServer(e.InstanceId, e.Content.Info);
                    }
                    break;

                case NetworkCode.Ping:
                    if (!_servers.ContainsKey(e.InstanceId))
                    {
                        Log.InfoFormat("{0} ({1}, {2}) re-joined the network.",
                                       e.Content.Info.name, e.Content.Info.type, e.InstanceId);
                    }
                    UpdateServer(e.InstanceId, e.Content.Info);
                    ServerPing?.Invoke(this, e);
                    break;

                case NetworkCode.Quit:
                    Log.InfoFormat("{0} ({1}, {2}) left the network.",
                                   e.Content.Info.name, e.Content.Info.type, e.InstanceId);
                    RemoveServer(e.InstanceId);
                    ServerQuit?.Invoke(this, e);
                    break;
                }
            }
        }
Ejemplo n.º 8
0
        public ServerMessage method_6(GameClient Session)
        {
            ServerMessage Message = new ServerMessage(451u);

            Message.AppendInt32(0);
            Message.AppendInt32(6);
            Message.AppendStringWithBreak("");
            Message.AppendInt32(Session.GetHabbo().list_1.Count);
            using (TimedLock.Lock(Session.GetHabbo().list_1))
            {
                foreach (uint current in Session.GetHabbo().list_1)
                {
                    GoldTree.GetGame().GetRoomManager().method_11(current).method_3(Message, false, false);
                }
            }
            return(Message);
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Initiates an asynchronous operation to authenticate user credentials.
        /// </summary>
        /// <param name="realm">Specifies the authentication scope.</param>
        /// <param name="account">The account.</param>
        /// <param name="password">The password.</param>
        /// <param name="callback">The delegate to be called when the operation completes (or <c>null</c>).</param>
        /// <param name="state">Application defined state (or <c>null</c>).</param>
        /// <returns>The <see cref="IAsyncResult" /> instance to be used to track the operation.</returns>
        /// <remarks>
        /// <note>
        /// All successful calls to <see cref="BeginAuthenticate" /> must eventually be
        /// matched by a call to <see cref="EndAuthenticate" />.
        /// </note>
        /// </remarks>
        public IAsyncResult BeginAuthenticate(string realm, string account, string password, AsyncCallback callback, object state)
        {
            RadiusClientPort port;

            using (TimedLock.Lock(this))
            {
                if (!IsOpen)
                {
                    throw new RadiusException(NotOpen);
                }

                port     = ports[nextPort];
                nextPort = (++nextPort) % ports.Length;

                return(port.BeginAuthenticate(realm, account, password, null, port));
            }
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Returns the set of logical routes that map to the logical endpoint passed.
        /// </summary>
        /// <param name="logicalEP">The </param>
        /// <returns>The set of logical routes that match the endpoint passed.</returns>
        public List <LogicalRoute> GetRoutes(MsgEP logicalEP)
        {
            var matches = new List <LogicalRoute>();

            using (TimedLock.Lock(router.SyncRoot))
            {
                for (int i = 0; i < routes.Count; i++)
                {
                    if (routes[i].LogicalEP.LogicalMatch(logicalEP))
                    {
                        matches.Add(routes[i]);
                    }
                }
            }

            return(matches);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Initialises the client and starts listening for messages from the server
        /// </summary>
        public void StartListening()
        {
#if DEBUG
            EventLog.Debug("MessageClient.cs " + System.Reflection.MethodBase.GetCurrentMethod().Name);
#endif
            try
            {
                _timeout = false;

                using (TimedLock.Lock(_messageLockObject))
                {
                    string threadName = String.Format("Client Listening Thread {0}", _server);

                    if (ThreadManager.Exists(threadName))
                    {
                        return;
                    }

                    _tcpClient                = new TcpClient(_server, _port);
                    _tcpClient.SendTimeout    = 30000;
                    _tcpClient.ReceiveTimeout = 30000;
                    MessageClientListeningThread newListeningThread = new MessageClientListeningThread(this);
                    newListeningThread.MessageReceived += newListeningThread_MessageReceived;
                    ThreadManager.ThreadStart(newListeningThread, threadName, ThreadPriority.Lowest);
                }

                RaiseConnected();
            }
            catch (Exception err)
            {
#if DEBUG
                EventLog.Debug(err);
                EventLog.Debug("MessageClient.cs " + System.Reflection.MethodBase.GetCurrentMethod().Name);
#endif
                if (err.Message.Contains("A connection attempt failed because the connected party did not properly respond") ||
                    err.Message.Contains("No connection could be made because the target machine actively refused it"))
                {
                    RaiseConnectionRefused();
                }
                else if (!HandleClientException(err))
                {
                    EventLog.Add(err, String.Format("Server: {0}; Port: {1}", _server, _port));
                    throw;
                }
            }
        }
Ejemplo n.º 12
0
        public static bool Execute(params InventoryTransaction[] transactions)
        {
            using (TimedLock.Lock(TrySaveLock))
            {
                if (transactions.Any(tranaction => !tranaction.Validate()))
                {
                    return(false);
                }

                foreach (var transcation in transactions)
                {
                    transcation.Execute();
                }

                return(true);
            }
        }
Ejemplo n.º 13
0
 internal void CancelCurrentSlicing()
 {
     if (slicerProcess != null)
     {
         using (TimedLock.Lock(slicerProcess, "SlicingProcess"))
         {
             if (slicerProcess != null && !slicerProcess.HasExited)
             {
                 slicerProcess.Kill();
             }
         }
     }
     else
     {
         MatterHackers.MatterSlice.MatterSlice.Stop();
     }
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Truncates the log to the position passed.
        /// </summary>
        /// <param name="position">The <see cref="ILogPosition" /> defining where the truncation should occur.</param>
        /// <remarks>
        /// <note>
        /// This property can only be called if the operation log is in <see cref="OperationLogMode.Undo" />
        /// mode.
        /// </note>
        /// <para>
        /// This method is used in combination with the <see cref="Position" /> property to roll
        /// back operations within a base transaction.
        /// </para>
        /// </remarks>
        /// <exception cref="TransactionException">Thrown if the log isn't open or if the mode isn't <see cref="OperationLogMode.Undo" />.</exception>
        public void Truncate(ILogPosition position)
        {
            using (TimedLock.Lock(this))
            {
                if (file == null)
                {
                    throw new TransactionException(ClosedMsg);
                }

                if (mode != OperationLogMode.Undo)
                {
                    throw new TransactionException("Write is available only when the log is in UNDO mode.");
                }

                file.SetLength(((FileLogPosition)position).Position);
            }
        }
Ejemplo n.º 15
0
        /// <summary>
        /// Releases and resources associated with the ServiceControl
        /// infrastructure.
        /// </summary>
        /// <remarks>
        /// This must be called when the derived class is stopped.
        /// </remarks>
        public void Close()
        {
            using (TimedLock.Lock(this))
            {
                if (inbox != null)
                {
                    inbox.Close();
                    inbox = null;
                }

                if (outbox != null)
                {
                    outbox.Close();
                    outbox = null;
                }
            }
        }
Ejemplo n.º 16
0
        private void DefBlockThread()
        {
            lockException = null;
            lockFailTime  = DateTime.MaxValue;

            try
            {
                using (TimedLock.Lock(this))
                {
                }
            }
            catch (Exception e)
            {
                lockException = e;
                lockFailTime  = SysTime.Now;
            }
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Completes an asynchronous request receive operation initiated by one of the <b>BeginReceiveRequest()</b> overrides.
        /// </summary>
        /// <param name="result">The <see cref="IAsyncResult" /> returned by <b>BeginReceiveRequest()</b>.</param>
        /// <returns>The <see cref="RequestContext" /> received.</returns>
        public RequestContext EndReceiveRequest(IAsyncResult result)
        {
            AsyncResult <RequestInfo, ReplyChannel> arReceive;
            RequestInfo requestInfo;

            arReceive = result as AsyncResult <RequestInfo, ReplyChannel>;
            if (arReceive != null)
            {
                // Operation completed in BeginReceiveRequest() above.

                arReceive.Wait();
                try
                {
                    if (arReceive.Exception != null)
                    {
                        throw arReceive.Exception;
                    }

                    requestInfo = arReceive.Result;
                    if (requestInfo == null)
                    {
                        return(null);
                    }

                    using (TimedLock.Lock(this))
                        pendingRequests.Add(requestInfo.Context.SessionID, requestInfo.Context);

                    return(new LillTekRequestContext(requestInfo.Context, requestInfo.Message, this));
                }
                finally
                {
                    arReceive.Dispose();
                }
            }

            requestInfo = listener.EndReceiveRequest(result);
            if (requestInfo == null)
            {
                return(null);
            }

            using (TimedLock.Lock(this))
                pendingRequests.Add(requestInfo.Context.SessionID, requestInfo.Context);

            return(new LillTekRequestContext(requestInfo.Context, requestInfo.Message, this));
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Queries the realm map provider for the current set of realm mappings.
        /// </summary>
        /// <returns>The list of realm mappings.</returns>
        /// <exception cref="AuthenticationException">Thrown if there's an error getting the map.</exception>
        public List <RealmMapping> GetMap()
        {
            OdbcConnection      dbCon  = null;
            OdbcDataReader      reader = null;
            List <RealmMapping> map    = new List <RealmMapping>();
            OdbcCommand         cmd;

            using (TimedLock.Lock(this))
            {
                if (!IsOpen)
                {
                    throw new AuthenticationException("Provider is closed.");
                }

                dbCon = new OdbcConnection(conString);
                dbCon.Open();

                try
                {
                    cmd             = dbCon.CreateCommand();
                    cmd.CommandText = query;
                    cmd.CommandType = CommandType.Text;

                    reader = cmd.ExecuteReader();
                    while (reader.Read())
                    {
                        map.Add(new RealmMapping(engineSettings,
                                                 SqlHelper.AsString(reader["Realm"]),
                                                 Config.Parse(SqlHelper.AsString(reader["ProviderType"]), (System.Type)null),
                                                 ArgCollection.Parse(EnvironmentVars.Expand(SqlHelper.AsString(reader["Args"]))),
                                                 SqlHelper.AsString(reader["Query"])));
                    }
                }
                finally
                {
                    if (reader != null)
                    {
                        reader.Close();
                    }

                    dbCon.Close();
                }

                return(map);
            }
        }
Ejemplo n.º 19
0
        public void UpdateWorldInstance(int worldId, World world)
        {
            if (_world == null)
            {
                return;
            }

            using (TimedLock.Lock(_worldLock))
            {
                if (!_portals.ContainsKey(worldId))
                {
                    return;
                }

                _portals[worldId].WorldInstance = world;
            }
        }
Ejemplo n.º 20
0
        public RoomBot method_3(uint uint_0)
        {
            RoomBot result;

            using (TimedLock.Lock(this.list_0))
            {
                foreach (RoomBot current in this.list_0)
                {
                    if (current.Id == uint_0)
                    {
                        result = current;
                        return(result);
                    }
                }
            }
            return(null);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Generates LogicalAdvertiseMsgs for the logical endpoints handled
        /// by this router and sends them to the router endpoint passed.
        /// </summary>
        /// <param name="routerEP">The endpoint.</param>
        private void SendLogicalAdvertiseMsgs(MsgEP routerEP)
        {
            LogicalAdvertiseMsg[] adMsgs;

            using (TimedLock.Lock(this.SyncRoot))
            {
                adMsgs = GenLogicalAdvertiseMsgs(null, true);
                if (adMsgs.Length == 0)
                {
                    return;     // There is nothing to advertise
                }
                for (int i = 0; i < adMsgs.Length; i++)
                {
                    SendTo(routerEP, adMsgs[i]);
                }
            }
        }
Ejemplo n.º 22
0
        public bool PortalIsOpen(int worldId)
        {
            if (_world == null)
            {
                return(false);
            }

            using (TimedLock.Lock(_worldLock))
            {
                if (!_portals.ContainsKey(worldId))
                {
                    return(false);
                }

                return(_portals[worldId].Usable && !_portals[worldId].Locked);
            }
        }
Ejemplo n.º 23
0
        /// <summary>
        /// Adds text to the log file
        /// </summary>
        /// <param name="text">text to add to log file</param>
        public static void DebugText(string text)
        {
            if (String.IsNullOrEmpty(text))
            {
                return;
            }

            try
            {
                using (TimedLock.Lock(_lockObject))
                {
                    string LogPath = Path.Replace("\\Logs\\", "\\Debug\\");

                    if (!Directory.Exists(LogPath))
                    {
                        Directory.CreateDirectory(LogPath);
                    }

                    string fileName = GetLogFileName(LogPath);

                    if (!CanLogData(fileName))
                    {
                        return;
                    }

                    StreamWriter w = File.AppendText(fileName);
                    try
                    {
                        w.WriteLine("{0} {1} - {2}", DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss"),
                                    System.Diagnostics.Process.GetCurrentProcess().Id, text.Replace("\r\n", " "));
                    }
                    finally
                    {
                        // Update the underlying file.
                        w.Flush();
                        w.Close();
                        w.Dispose();
                        w = null;
                    }
                }
            }
            catch
            {
                //ignore, I suppose :-\
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Removes a message from the backing store if the message is present.
        /// </summary>
        /// <param name="persistID">The provider specific ID of the message being removed.</param>
        public void Remove(object persistID)
        {
            using (TimedLock.Lock(this))
            {
                if (messages == null)
                {
                    throw new ObjectDisposedException(this.GetType().Name);
                }

                Guid msgID = (Guid)persistID;

                if (messages.ContainsKey(msgID))
                {
                    messages.Remove(msgID);
                }
            }
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Releases all resources associated with the instance.
        /// </summary>
        /// <remarks>
        /// <note>
        /// All files in the transit folder will be deleted.
        /// </note>
        /// </remarks>
        public void Dispose()
        {
            FileSystemWatcher watcher = null;

            using (TimedLock.Lock(syncLock))
            {
                isDisposed = true;

                if (fileWatcher != null)
                {
                    watcher     = fileWatcher;
                    fileWatcher = null;
                }

                Helper.DeleteFile(transitFolder + "*.*");
            }
        }
Ejemplo n.º 26
0
        /// <summary>
        /// Writes an <see cref="IOperation" /> to the log.
        /// </summary>
        /// <param name="resource">The parent <see cref="ITransactedResource" /> responsible for serializing the operation.</param>
        /// <param name="operation">The operation to be written.</param>
        /// <remarks>
        /// <note>
        /// This property can only be called if the operation log is in <see cref="OperationLogMode.Undo" />
        /// mode.
        /// </note>
        /// </remarks>
        /// <exception cref="TransactionException">Thrown if the log isn't open or if the mode isn't <see cref="OperationLogMode.Undo" />.</exception>
        public void Write(ITransactedResource resource, IOperation operation)
        {
            using (TimedLock.Lock(syncLock))
            {
                if (!isOpen)
                {
                    throw new TransactionException(NotOpenMsg);
                }

                if (mode != OperationLogMode.Undo)
                {
                    throw new TransactionException("Write is available only when the log is in UNDO mode.");
                }

                operations.Add(operation);
            }
        }
Ejemplo n.º 27
0
        //---------------------------------------------------------------------
        // ILillTekChannelManager implementation

        /// <summary>
        /// Called by LillTek channels accepted by this listener when the
        /// channel is closed or aborted to terminate any pending operations.
        /// </summary>
        /// <param name="channel">The closed or aborted channel.</param>
        /// <param name="e">The exception to be used to terminate the operation.</param>
        public virtual void OnChannelCloseOrAbort(LillTekChannelBase channel, Exception e)
        {
            using (TimedLock.Lock(this))
            {
                string channelID = channel.ID;

                if (channels == null)
                {
                    return;
                }

                if (channels.ContainsKey(channelID))
                {
                    channels.Remove(channelID);
                }
            }
        }
Ejemplo n.º 28
0
        private void HandlePortal(Player player, Portal portal)
        {
            if (portal == null || !portal.Usable)
            {
                return;
            }

            using (TimedLock.Lock(portal.CreateWorldLock))
            {
                var world = portal.WorldInstance;

                // special portal case lookup
                if (world == null && _realmPortals.Contains(portal.ObjectType))
                {
                    world = player.Manager.GetRandomGameWorld();
                    if (world == null)
                    {
                        return;
                    }
                }

                if (world is Realm && !player.Manager.Resources.GameData.ObjectTypeToId[portal.ObjectDesc.ObjectType].Contains("Cowardice"))
                {
                    player.FameCounter.CompleteDungeon(player.Owner.Name);
                }

                if (world != null)
                {
                    player.Reconnect(world);
                    return;
                }

                // dynamic case lookup
                if (portal.CreateWorldTask == null || portal.CreateWorldTask.IsCompleted)
                {
                    portal.CreateWorldTask = Task.Factory
                                             .StartNew(() => portal.CreateWorld(player))
                                             .ContinueWith(e =>
                                                           Log.Error(e.Exception.InnerException.ToString()),
                                                           TaskContinuationOptions.OnlyOnFaulted);
                }

                portal.WorldInstanceSet += player.Reconnect;
            }
        }
Ejemplo n.º 29
0
        public async Task Invoke(HttpContext context)
        {
            try
            {
                if (_disabled)
                {
                    return;
                }

                using (StopWatchTimer stopwatchTimer = StopWatchTimer.Initialise(_timings))
                {
                    string routeLowered = RouteLowered(context);

                    using (TimedLock lck = TimedLock.Lock(_lockObject))
                    {
                        if (_ignoredRoutes.Contains(routeLowered))
                        {
                            return;
                        }
                    }

                    if (!context.Response.Headers.ContainsKey("Cache-Control"))
                    {
                        foreach (KeyValuePair <string, CacheControlRoute> keyValuePair in _routePaths)
                        {
                            if (routeLowered.StartsWith(keyValuePair.Key))
                            {
                                context.Response.Headers.Add("Cache-Control", $"max-age={keyValuePair.Value.CacheValue}");
                                return;
                            }
                        }
                    }

                    using (TimedLock lck = TimedLock.Lock(_lockObject))
                    {
                        _ignoredRoutes.Add(routeLowered);
                    }
                }
            }

            finally
            {
                await _next(context);
            }
        }
Ejemplo n.º 30
0
        protected override bool Run(object parameters)
        {
            // if the thread has been cancelled then exit
            if (HasCancelled())
            {
                return(false);
            }

            List <Message> messages = new List <Message>();

            try
            {
                using (TimedLock.Lock(_lockObject))
                {
                    // copy all messages to the local list and clear it out,
                    // the service item can then process them as it see's fit
                    foreach (Message message in _serviceMessages)
                    {
                        messages.Add(message);
                    }

                    _serviceMessages.Clear();
                }

                if (!_serverManagerService.ServiceExecute(messages))
                {
                    return(false);
                }

                return(!HasCancelled());
            }
            catch (Exception error)
            {
                _logging.AddToLog(error, ToString());

                // add all message back to the list

                foreach (Message message in messages)
                {
                    AddMessage(message);
                }
            }

            return(!HasCancelled());
        }