Ejemplo n.º 1
0
 public NodeEnumerator(Node node)
 {
     _node              = _root = node;
     _first             = true;
     _nodeEnumerators   = new ArrayRig <Teple <IEnumerator <Node>, bool> >();
     _currentEnumerator = new ArrayRig <Node>(1).GetEnumerator();
 }
Ejemplo n.º 2
0
        /// <summary>
        /// Manually submit all unsubmitted changes to rows.
        /// </summary>
        public void SubmitChanges()
        {
            // ensure initialization
            if (_initialize)
            {
                Initialize();
            }

            // if no updated collections - skip
            if (_currentCollections.Count == 0)
            {
                return;
            }

            _lock.Take();

            // copy the updated collections
            ArrayRig <RowCollection> collections = _currentCollections;

            _currentCollections = new ArrayRig <RowCollection>(collections.Count);

            _lock.Release();

            // iterate all updated collections
            foreach (RowCollection collection in collections)
            {
                // run an update for the collection
                Update(collection, true);
            }

            collections.Dispose();
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Initialize a new ThreadHandle that will start a new Thread.
        /// If memory parameter is 0 this handle will manage the thread that called the constructor.
        /// </summary>
        public ThreadHandle(long memory)
        {
            // initialize the required parameters
            Needles = new ArrayRig <Needle>();

            Handles.Take();
            if (memory == 0)
            {
                Thread            = Thread.CurrentThread;
                Thread.Priority   = ThreadPriority.AboveNormal;
                ThreadHandle.Main = this;
                Thread.Name       = "Main";
            }
            else
            {
                Thread      = new Thread(new ThreadStart(Run), (int)memory);
                Thread.Name = (Handles.Item.Count + 1).ToString();
            }

            Id = Thread.ManagedThreadId;
            Handles.Item.Add(this);
            _handleMap.TakeItem()[Id] = this;

            _handleMap.Release();
            Handles.Release();

            _iteration = -1;
            _index     = -1;
        }
Ejemplo n.º 4
0
        /// <summary>
        /// Validate the form with the specified post parameters. Returns
        /// an empty array if validation succeeded or an array with user
        /// friendly error messages if the validation failed.
        /// </summary>
        public virtual ArrayRig <string> Validate(HttpPostParams parameters, ArrayRig <string> errors = null)
        {
            if (_update)
            {
                Update();
            }
            // create a collection of potential errors
            if (errors == null)
            {
                errors = new ArrayRig <string>(1);
            }
            if (parameters == null)
            {
                errors.Add("Malformed or missing request parameters.");
                return(errors);
            }

            // iterate and validate the child forms
            foreach (var form in _forms)
            {
                form.Validate(parameters, errors);
            }

            // iterate and validate the input elements
            foreach (var input in _input)
            {
                IHttpPostParam parameter = parameters[input.Key];
                input.Value.Validate(parameter, errors);
            }

            // return the collection of error messages
            return(errors);
        }
Ejemplo n.º 5
0
        //----------------------------------//

        //----------------------------------//

        internal JsMethod(JsClass jsClass, MethodInfo method)
        {
            Parameters = new Dictionary <string, Js>();
            Commands   = new ArrayRig <JsCommand>();

            // does the method return a string?
            if (method.ReturnType != typeof(string))
            {
                throw new InvalidOperationException("JsMethod '" + method.Name + "' doesn't return a string.");
            }

            // iterate the parameters
            foreach (var parameter in method.GetParameters())
            {
                // ensure each parameter is a Js type
                if (!Js.IsAncestor(parameter.ParameterType))
                {
                    throw new InvalidOperationException("Parameter '" + parameter.Name + "' of method '" + method.Name + "' in class '" +
                                                        method.DeclaringType.Name + "' doesn't inherit from Js.");
                }

                // add the parameter
                Parameters.Add(parameter.Name, parameter.HasDefaultValue ? (Js)parameter.DefaultValue : null);
            }

            // add the string returned from the method as the javascript command
            Commands.Add(new JsCommandString((string)method.Invoke(jsClass, new object[Parameters.Count])));
        }
Ejemplo n.º 6
0
        //-------------------------------------------//

        /// <summary>
        /// Initialize an element rule with a tag to parse and parameters to return.
        /// </summary>
        public ExtractUrl(IAction <string> onUrl = null, ArrayRig <Protocol> protocols = null)
        {
            if (onUrl != null)
            {
                OnUrl    = new Shared <IAction <string> >(onUrl);
                OnUrlSet = true;
            }

            // initialize the tree search instance
            ProtocolSearch = new TreeSearch <char, char[]>();

            // were the protocols specified?
            if (protocols == null)
            {
                // no, set default
                protocols = new ArrayRig <Protocol>(new [] { Protocol.Http, Protocol.Https });
            }

            // iterate the protocols
            foreach (var protocol in protocols)
            {
                char[] chars = Protocols.Get(protocol).ToCharArray();
                ProtocolSearch.Add(chars, new ArrayRig <char>(chars));
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Add an enumerable collection as keys.
        /// </summary>
        public void Add(TValue value, System.Collections.Generic.IEnumerable <TKey> keys)
        {
            ArrayRig <TKey> rig = new ArrayRig <TKey>();

            rig.AddCollection(keys);
            Add(value, rig);
        }
Ejemplo n.º 8
0
        //-------------------------------------------//

        /// <summary>
        /// Initialize an element rule with a tag to parse and parameters to return.
        /// </summary>
        public ParseLine(ExtractLine extract)
        {
            _extract = extract;
            _line    = new char[_extract.CharBuffer];

            _reqParsersSet = extract.ReqExtracts != null;
            if (_reqParsersSet)
            {
                _reqParsers = new ArrayRig <Parse>();
                foreach (Extract req in extract.ReqExtracts)
                {
                    _reqParsers.Add(req.GetParser());
                }
            }

            _subParsersSet = extract.SubExtracts != null;
            if (_subParsersSet)
            {
                _subParsers = new ArrayRig <Parse>();
                foreach (Extract sub in extract.SubExtracts)
                {
                    _subParsers.Add(sub.GetParser());
                }
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Create a new udp connection to handle communication to a single endpoint from the specified socket.
        /// </summary>
        public UdpConnection(UdpServer server, Socket socket, IPEndPoint remoteEndpoint)
        {
            // persist the server
            Server         = server;
            RemoteEndPoint = remoteEndpoint;

            _timeoutTimer = new Timer(_timeoutMilliseconds, ActionSet.New(ProcessError, new TimeoutException("UdpConnection timeout.")));

            _header             = new UdpHeader();
            _header.Compression = _defaultCompression = DecompressionMethods.None;

            // create the encoder
            _encoder = Encoding.UTF8.GetEncoder();
            _lock    = new Lock();
            _message = new UdpMessage(this);

            _messages  = new ArrayRig <UdpMessage>();
            _onMessage = new ActionPop <UdpMessage>();

            _errors  = new ArrayRig <Exception>();
            _onError = new ActionPop <Exception>();

            // create an async socket to manage the socket
            AsyncSocket = new AsyncUdpSocket(socket, (IPEndPoint)socket.LocalEndPoint, OnReceived, ProcessError);
            AsyncSocket.TargetEndPoint = RemoteEndPoint;
        }
Ejemplo n.º 10
0
        //-------------------------------------------//

        /// <summary>
        /// Derive a collection of one type from another, optionally with a predicate.
        /// </summary>
        public static ArrayRig <B> Derive <A, B>(this IEnumerable <A> collection, Func <A, B> mapper, Func <A, bool> predicate = null)
        {
            ArrayRig <B> rig = new ArrayRig <B>();

            // was the predicate supplied?
            if (predicate == null)
            {
                // no, perform the mapping without
                foreach (A item in collection)
                {
                    rig.Add(mapper(item));
                }
            }
            else
            {
                // yes, perform the mapping with the predicate
                foreach (A item in collection)
                {
                    if (predicate(item))
                    {
                        rig.Add(mapper(item));
                    }
                }
            }

            return(rig);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Dispose of the data cluster and all related resources.
        /// </summary>
        public void Dispose()
        {
            ArrayRig <Keyspace> keyspaces = new ArrayRig <Keyspace>();

            // iterate and dispose of Keyspaces
            foreach (var keyspace in Keyspaces)
            {
                keyspaces.Add(keyspace.Value);
            }
            foreach (var keyspace in keyspaces)
            {
                keyspace.Dispose();
            }

            _lock.Take();

            Keyspaces.Clear();
            Keyspaces = null;

            _lock.Release();

            // remove the cluster from the manager
            ManagerCql.RemoveCluster(this);

            // dispose of the cassandra cluster
            Cluster.Shutdown();
            Cluster.Dispose();
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Create a new incoming udp connection to handle communication to a single endpoint.
        /// </summary>
        public UdpConnection(UdpServer server, IPEndPoint remoteEndpoint, IPEndPoint localEndpoint, byte[] buffer, int count)
        {
            // persist the server
            Server         = server;
            RemoteEndPoint = remoteEndpoint;

            _timeoutTimer = new Timer(_timeoutMilliseconds, ActionSet.New(ProcessError, new TimeoutException("UdpConnection timeout.")));

            _header             = new UdpHeader();
            _header.Compression = _defaultCompression = DecompressionMethods.None;

            // create the encoder
            _encoder = Encoding.UTF8.GetEncoder();
            _lock    = new Lock();
            _message = new UdpMessage(this);

            _messages  = new ArrayRig <UdpMessage>();
            _onMessage = new ActionPop <UdpMessage>();

            _errors  = new ArrayRig <Exception>();
            _onError = new ActionPop <Exception>();

            // call on received for the first buffer
            OnReceived(RemoteEndPoint, buffer, count);

            // create a socket instance for the udp connection
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);

            // create an async socket to manage the socket
            AsyncSocket = new AsyncUdpSocket(socket, localEndpoint, OnReceived, ProcessError);
            AsyncSocket.TargetEndPoint = RemoteEndPoint;
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources.
        /// </summary>
        public virtual void Dispose()
        {
            if (_stopped)
            {
                return;
            }
            _stopped = true;

            try {
                // get a collection of the current connections
                var connections = new ArrayRig <UdpConnection>();
                foreach (var entry in _connections.TakeItem())
                {
                    connections.Add(entry.Value);
                }
                _connections.Release();

                // dispose of each connection
                foreach (var connection in connections)
                {
                    connection.Dispose();
                }

                // dispose of the listenning socket
                AsyncSocket.Dispose();
                _socket.Dispose();
            } catch (Exception ex) {
                Log.Error("Exception disposing of UDP server connections.", ex);
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Add a root path and callback for the sub path.
        /// </summary>
        public void Add(string path, HttpMethod methods, IAction <string, HttpRequest> callback)
        {
            if (string.IsNullOrEmpty(path))
            {
                throw new InvalidOperationException("Null or empty paths aren't allowed. Use the DefaultCallback field.");
            }

            path = path.ToLowercase();
            if (path[0] == Chars.ForwardSlash)
            {
                path = path.Substring(1);
            }

            _lock.Take();
            ArrayRig <Route> routes;

            if (_routes.TryGetValue(path, out routes))
            {
                foreach (var route in routes)
                {
                    if (route.Methods.Is(methods))
                    {
                        throw new Exception("Route methods cannot be defined twice.");
                    }
                }
                routes.Add(new Route(methods, callback));
            }
            else
            {
                routes = new ArrayRig <Route>();
                routes.Add(new Route(methods, callback));
                _routes.Add(path, routes);
            }
            _lock.Release();
        }
Ejemplo n.º 15
0
        private static void Add(IConnection connection, bool tryLock)
        {
            // get the lock
            if (tryLock && !(tryLock = _lock.TryTake))
            {
                _lock.TryLock(new Act <IConnection, bool>(Add, connection, false));
                return;
            }

            // get the list of connections of that type
            Type sourceType = connection.GetType();
            ArrayRig <IConnection> connections;

            if (!_sources.TryGetValue(sourceType, out connections))
            {
                _sources[sourceType] = connections = new ArrayRig <IConnection>();
            }

            // add the connection
            _sources[sourceType].Add(connection);

            // if manually locked, unlock
            if (tryLock)
            {
                _lock.Release();
            }
        }
Ejemplo n.º 16
0
        /// <summary>
        /// Dispose of the blob stream.
        /// </summary>
        protected override void Dispose(bool disposing)
        {
            if (!disposing)
            {
                return;
            }

            _lock.Take();
            FlushInternal();

            if (_sections != null)
            {
                // dispose of the sections collection
                for (int i = _sections.Count - 1; i >= 0; --i)
                {
                    if (_sections[i] == null)
                    {
                        continue;
                    }
                    _sections[i].Bytes = null;
                }
                _sections.Dispose();
                _sections = null;
            }

            _lock.Release();
        }
Ejemplo n.º 17
0
        /// <summary>
        /// Add or Get a connection synchronously to the connections known by the Api Manager.
        /// This doesn't open the connection.
        /// </summary>
        public static C Get <C>(string path) where C : Connection <C>, new()
        {
            // get the lock
            _lock.Take();

            Type sourceType = typeof(C);
            ArrayRig <IConnection> connections;

            if (!_sources.TryGetValue(sourceType, out connections))
            {
                _sources[sourceType] = connections = new ArrayRig <IConnection>();
            }

            // try get the connection
            C connection = connections.GetSingle(c => c.Path == path) as C;

            if (connection == null)
            {
                // connection doesn't exist, create it
                connection      = new C();
                connection.Path = path;
                _sources[sourceType].Add(connection);
            }

            // if manually locked, unlock
            _lock.Release();

            return(connection);
        }
Ejemplo n.º 18
0
        /// <summary>
        /// Get a supported class from the connection. Resource is unlocked after the action called is ended.
        /// </summary>
        public static void Get <T, C>(string path, out Teple <LockShared, T> resource) where C : Connection <C>, IGetValue <T>, new()
        {
            _lock.Take();

            // get the type of connection
            Type sourceType = typeof(C);
            ArrayRig <IConnection> source;

            // check if there are currently any types of connections like this
            if (!_sources.TryGetValue(sourceType, out source))
            {
                // create the dictionary
                source = new ArrayRig <IConnection>();
                _sources[sourceType] = source;
            }

            // try get the connection
            C connection = source.GetSingle(c => c.Path == path) as C;

            // if the connection doesn't exist
            if (connection == null)
            {
                // create a new connection
                connection      = new C();
                connection.Path = path;
                // add to the source
                source.Add(connection);
            }

            // unlock the sources lock
            _lock.Release();

            // get the resource
            connection.Get(out resource);
        }
Ejemplo n.º 19
0
        private static void Get <T, C>(C connection, Act <T> onResource, bool tryLock) where C : Connection <C>, IGetValue <T>, new()
        {
            // get the lock
            if (tryLock && !(tryLock = _lock.TryTake))
            {
                _lock.TryLock(new Act <C, Act <T>, bool>(Get <T, C>, connection, onResource, false));
                return;
            }

            Type sourceType = typeof(C);
            ArrayRig <IConnection> source;

            // check if there are currently any types of connections like this
            if (!_sources.TryGetValue(sourceType, out source))
            {
                // create the source dictionary and add it
                _sources[sourceType] = source = new ArrayRig <IConnection>();
            }
            // does the connection exist in source?
            if (!source.Contains(connection))
            {
                // add to the connections
                source.Add(connection);
            }

            // if manually locked, unlock
            if (tryLock)
            {
                _lock.Release();
            }

            // get the resource
            connection.Get(onResource);
        }
Ejemplo n.º 20
0
        //----------------------------------//

        /// <summary>
        /// Initialize a wav file reader.
        /// </summary>
        public WavInterpret()
        {
            BufferCount(24);

            Left  = new ArrayRig <double>(1000);
            Right = new ArrayRig <double>(1000);
        }
Ejemplo n.º 21
0
        /// <summary>
        /// Initialize a new set of headers.
        /// </summary>
        public HttpResponseHeaders(bool includeDefault)
        {
            // initialize the collection
            _definedHeaders = new ArrayRig <Teple <HttpResponseHeader, Teple <string, int> > >(12);
            _definedSingles = new Dictionary <HttpResponseHeader, string>();
            _customHeaders  = new ArrayRig <Teple <string, Teple <string, int> > >();
            _customSingles  = new Dictionary <string, string>();
            _builder        = new StringBuilder();

            // should the default headers be added?
            if (includeDefault)
            {
                // set the default header prefix
                Version    = "Http/1.1";
                StatusCode = 200;

                Set(HttpResponseHeader.Server, "Efz");
                Set(HttpResponseHeader.AcceptRanges, "bytes");
                Set(HttpResponseHeader.Vary, "Accept-Encoding");
                Set(HttpResponseHeader.Connection, "keep-alive");
                Set(HttpResponseHeader.ContentEncoding, "gzip");
                Set(HttpResponseHeader.ContentType, "text/html; charset=UTF-8");
            }
            else
            {
                _statusCode = 0;
                _version    = _statusDescription = string.Empty;
            }
        }
Ejemplo n.º 22
0
 /// <summary>
 /// Add a child style.
 /// </summary>
 public void Add(Style child)
 {
     if (_children == null)
     {
         _children = new ArrayRig <Style>();
     }
     _children.Add(child);
 }
Ejemplo n.º 23
0
        //-------------------------------------------//

        /// <summary>
        /// Initialize with the functions necessary to perform calculations on a generic type.
        /// </summary>
        public Average(int _batchSize, int _batchNumber, double _batchWeight = 1.0)
        {
            batchSize   = _batchSize;
            batchCount  = _batchNumber;
            BatchWeight = _batchWeight;
            batch       = new ArrayRig <double>(batchSize);
            batches     = new ArrayRig <double>(batchCount);
        }
Ejemplo n.º 24
0
 /// <summary>
 /// Add a sub extract that must exist within this section for it to be
 /// parsed successfully.
 /// </summary>
 public void AddRequirement(Extract extract)
 {
     if (ReqExtracts == null)
     {
         ReqExtracts = new ArrayRig <Extract>();
     }
     ReqExtracts.Add(extract);
 }
Ejemplo n.º 25
0
 /// <summary>
 /// Add a sub extract to act on the body of the element if it exists.
 /// </summary>
 public void AddBodyExtract(Extract extract)
 {
     if (BodyExtracts == null)
     {
         BodyExtracts = new ArrayRig <Extract>();
     }
     BodyExtracts.Add(extract);
 }
Ejemplo n.º 26
0
 /// <summary>
 /// Add a sub extract that will be parsed on a successful
 /// section.
 /// </summary>
 public void AddSubExtract(Extract extract)
 {
     if (SubExtracts == null)
     {
         SubExtracts = new ArrayRig <Extract>();
     }
     SubExtracts.Add(extract);
 }
Ejemplo n.º 27
0
 /// <summary>
 /// Add a sub extract to act on the body of the element if it exists.
 /// </summary>
 public void AddSubExtract(Extract extract)
 {
     if (!SubExtractSet)
     {
         SubExtractSet = true;
         SubExtract    = new ArrayRig <Extract>();
     }
     SubExtract.Add(extract);
 }
Ejemplo n.º 28
0
        /// <summary>
        /// Add or Set a search node to the current search branches.
        /// </summary>
        public void Add(TValue value, params Struct <TKey[], bool>[] keySets)
        {
            var sets = new ArrayRig <Struct <ArrayRig <TKey>, bool> >(keySets.Length);

            foreach (var s in keySets)
            {
                sets.Add(new Struct <ArrayRig <TKey>, bool>(new ArrayRig <TKey>(s.ArgA), s.ArgB));
            }
            Add(value, sets);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Add or Set a search node to the current search branches.
        /// </summary>
        public void Add(TValue value, ArrayRig <Struct <TKey[], bool> > keySets)
        {
            var sets = new ArrayRig <Struct <ArrayRig <TKey>, bool> >(keySets.Count);

            foreach (var s in keySets)
            {
                sets.Add(new Struct <ArrayRig <TKey>, bool>(new ArrayRig <TKey>(s.ArgA), s.ArgB));
            }
            Add(value, sets);
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Add a node to this nodes array collection.
 /// </summary>
 public void Add(Node node)
 {
     if (!_arraySet)
     {
         Array     = new ArrayRig <Node>();
         _arraySet = true;
     }
     node._parent = this;
     _array.Add(node);
 }