Example #1
0
    public void ReGenerate()
    {
        m_Queue.Clear();

        for (uint i = 1; i <= m_nIDMaxCount; ++i)
        {
            T obj = m_factory.CreateObject(i);
            m_Queue.Enqueue(obj);
        }

        m_list.Clear();
    }
 public object InvokeDefaultConstruction(Type type)
 {
     if (FactoryType == ObjectFactoryType.Class)
     {
         return(_objectFactory.CreateObject(type));
     }
     if (FactoryType == ObjectFactoryType.Delegate)
     {
         return(_default(type));
     }
     return(null);
 }
Example #3
0
 void ExpandCache(int count)
 {
     for (int i = 0; i < count; ++i)
     {
         objects_.Add(objectFactoryMethod_.CreateObject());
     }
 }
Example #4
0
        private object CreateCompatibleValue(PaperContext context, object sourceValue, Type targetType)
        {
            if (sourceValue is PropertyMap map)
            {
                var instance = objectFactory.CreateObject(targetType);

                foreach (var key in map.Keys)
                {
                    var property = targetType.GetProperties().FirstOrDefault(x => x.Name.EqualsIgnoreCase(key));
                    if (property == null)
                    {
                        continue;
                    }

                    var value           = map[key];
                    var compatibleValue = CreateCompatibleValue(context, value, property.PropertyType);
                    property.SetValue(instance, compatibleValue);
                }

                return(instance);
            }
            else
            {
                return(Change.To(sourceValue, targetType));
            }
        }
Example #5
0
        private object ReadDocument()
        {
            // validate data length:
            var length = _input.ReadUInt32();

            if (length == 0)
            {
                return(null);
            }

            // decode data:
            var          resultObject = new Dictionary <string, object>();
            BSonItemType type;
            string       key;
            object       value;
            int          prevOffset;

            while ((type = (BSonItemType)_input.ReadByte()) != BSonItemType.EndOfDocument)
            {
                prevOffset = _input.Offset;
                value      = ReadItem(type, out key);

                if (string.IsNullOrEmpty(key))
                {
                    throw new FormatException("Missing key, when parsing BSON document at " + prevOffset);
                }

                resultObject[key] = value;
            }

            return(_factory.CreateObject(resultObject));
        }
        public virtual T Take()
        {
            T obj;

            if (_pools.Count == 0)
            {
                obj = _factory.CreateObject(true);
            }
            else
            {
                obj = _pools[0];
                _factory.ActivateObject(obj);
                _pools.RemoveAt(0);
            }
            _activeCount++;
            return(obj);
        }
        public static object Create(this PaperDescriptor paper, IObjectFactory factory, Type type)
        {
            var creator  = paper.Factories.FirstOrDefault(x => type.IsAssignableFrom(x.ReturnType));
            var instance = creator?.Invoke(paper.Paper, null)
                           ?? factory.CreateObject(type);

            return(instance);
        }
Example #8
0
        public T Take()
        {
            T t;

            if (pools.Count == 0)
            {
                t = factory.CreateObject(true);
            }
            else
            {
                t = pools[0];
                factory.ActivateObject(t);
                pools.RemoveAt(0);
            }

            activeNum++;
            return(t);
        }
Example #9
0
        async Task GetPaper(string paper)
        {
            var descriptor = paperCatalog.FindPaperDescriptor(defaultCatalog, paper);

            if (descriptor == null)
            {
                var ret = Ret.Fail(HttpStatusCode.NotFound, $"O objeto não existe: {defaultCatalog}/{paper}");
                await Res.SendEntityStatusAsync(ret);

                return;
            }

            object output;

            var instance = objectFactory.CreateObject(descriptor.PaperType);

            if (instance._HasMethod("Render"))
            {
                output = objectFactory.Call(instance, "Render", null);
            }
            else
            {
                throw new HttpException($"Não há um algoritmo de renderização conhecido para objeto do tipo ${descriptor.PaperType.FullName}.");
            }

            if (output is Stream stream)
            {
                await stream.CopyToAsync(Res.Body);

                await Res.Body.FlushAsync();
            }
            else if (output is StreamReader reader)
            {
                var encoding = Encoding.UTF8;
                var writer   = new StreamWriter(Res.Body, encoding);
                await reader.CopyToAsync(writer);

                await writer.FlushAsync();

                await Res.Body.FlushAsync();
            }
            else if (output is Entity entity)
            {
                var encoding   = Encoding.UTF8;
                var mimeType   = "json";
                var serializer = new MediaSerializer(mimeType);
                serializer.Serialize(entity, Res.Body, encoding);
                await Res.Body.FlushAsync();
            }
            else
            {
                throw new HttpException($"Não há suporte para renderização de dados do tipo {output.GetType().FullName}");
            }
        }
Example #10
0
        private void AddExposedCollections <TContract>(IObjectFactory factory, Func <TContract, T> converter)
            where TContract : class
        {
            var types = ExposedTypes.GetTypes <ICatalogCollection <TContract> >();

            foreach (var type in types)
            {
                try
                {
                    var collection = (ICatalogCollection <TContract>)factory.CreateObject(type);
                    var items      = collection.Items.Select(converter);
                    AddCollection(collection.Name, items);
                }
                catch (Exception ex)
                {
                    ex.Trace();
                }
            }
        }
Example #11
0
        private void AddExposedItems <TContract>(IObjectFactory factory, Func <TContract, T> converter)
            where TContract : class
        {
            var types = ExposedTypes.GetTypes <TContract>();

            foreach (var type in types)
            {
                try
                {
                    var contract       = (TContract)factory.CreateObject(type);
                    var collection     = contract._GetAttribute <CatalogAttribute>();
                    var collectionName = collection?.CollectionName ?? type.Assembly.FullName.Split(',').First();
                    var item           = converter.Invoke(contract);
                    AddCollection(collectionName, item);
                }
                catch (Exception ex)
                {
                    ex.Trace();
                    Console.WriteLine(ex.GetStackTrace());
                }
            }
        }
Example #12
0
        public IPipeline CreatePipeline(IObjectFactory objectFactory)
        {
            var pipeline = (IPipeline)objectFactory.CreateObject(Type);

            return(pipeline);
        }
Example #13
0
        /// <summary>
        /// Reads a dictonary from an input stream.
        /// </summary>
        private object ReadObject()
        {
            Dictionary <string, object> result = new Dictionary <string, object>();
            JSonReaderTokenInfo         currentToken;
            string name      = null;
            bool   colonSpot = false;
            bool   commaSpot = false;
            int    commas    = 0;

            while ((currentToken = ReadNextToken(true)).Type != JSonReaderTokenType.EndOfText)
            {
                if (currentToken.Type == JSonReaderTokenType.ObjectEnd)
                {
                    PopTopToken();

                    // if number of commas is greater than number of added elements,
                    // then value was not passed between:
                    if (commas > 0 && commas >= result.Count)
                    {
                        throw new JSonReaderException("Too many commas at closing object token, expected none", currentToken);
                    }
                    break;
                }

                switch (currentToken.Type)
                {
                case JSonReaderTokenType.ArrayStart:

                    // read embedded array:
                    AddValue(result, ref name, ReadArray(), ref colonSpot, ref commaSpot, currentToken);
                    break;

                case JSonReaderTokenType.ObjectStart:

                    // read embedded object:
                    AddValue(result, ref name, ReadObject(), ref colonSpot, ref commaSpot, currentToken);
                    break;

                case JSonReaderTokenType.Keyword:

                    if (name == null)
                    {
                        throw new JSonReaderException("Keyword can not be an object element's name", currentToken);
                    }

                    // add embedded value of reserved keyword:
                    AddValue(result, ref name, ReadKeyword(), ref colonSpot, ref commaSpot, currentToken);
                    break;

                case JSonReaderTokenType.Number:

                    // add embedded numeric value:
                    AddValue(result, ref name, ReadNumber(), ref colonSpot, ref commaSpot, currentToken);
                    break;

                case JSonReaderTokenType.String:

                    if (!commaSpot && result.Count > 0)
                    {
                        throw new JSonReaderException("Missing comma before name and value definition", currentToken);
                    }

                    if (name == null)
                    {
                        name = ReadString().ToString();

                        if (result.ContainsKey(name))
                        {
                            throw new JSonReaderException("Duplicated name in object", currentToken);
                        }

                        break;
                    }

                    // add embedded string:
                    AddValue(result, ref name, ReadString(), ref colonSpot, ref commaSpot, currentToken);
                    break;

                case JSonReaderTokenType.Colon:
                    PopTopToken();

                    if (colonSpot)
                    {
                        throw new JSonReaderException("Duplicated colon found in object", currentToken);
                    }

                    if (name == null)
                    {
                        throw new JSonReaderException("Unexpected colon, when name not given", currentToken);
                    }

                    colonSpot = true;
                    break;

                case JSonReaderTokenType.Comma:

                    // go to next array element:
                    currentToken = PopTopToken();

                    if (commaSpot)
                    {
                        throw new JSonReaderException("Two commans in a row", currentToken);
                    }

                    commas++;
                    commaSpot = true;

                    // if number of commas is greater than number of added elements,
                    // then value was not passed between:
                    if (commas > result.Count)
                    {
                        throw new JSonReaderException("Missing value for object element", currentToken);
                    }
                    break;

                default:
                    throw new JSonReaderException("Invalid token", currentToken);
                }
            }

            JSonReaderTokenInfo topToken = PopTopToken();

            if (topToken.Type != JSonReaderTokenType.ObjectStart || currentToken.Type == JSonReaderTokenType.EndOfText)
            {
                throw new JSonReaderException("Missing close object token", topToken);
            }

            return(_factory.CreateObject(result));
        }
 public static T CreateObject <T>(this IObjectFactory factory, params object[] extraArgs)
 {
     return((T)factory.CreateObject(typeof(T), extraArgs));
 }
Example #15
0
        public async Task RenderAsync(Request req, Response res, NextAsync next)
        {
            var path = req.Path.Substring(Route.Length);

            // Destacando a ação de uma URI, como em /My/Path/-MyAction
            var tokens      = path.Split("/-");
            var paperPath   = tokens.First();
            var paperAction = tokens.Skip(1).FirstOrDefault() ?? "Index";

            var paper = paperCatalog.FindExact(paperPath).FirstOrDefault();

            if (paper == null)
            {
                await next.Invoke();

                return;
            }

            var hasAction = paper.GetMethod(paperAction) != null;

            if (!hasAction)
            {
                await next.Invoke();

                return;
            }

            var args = new Args();

            args.AddMany(req.QueryArgs);
            args.AddMany(Args.ParsePathArgs(path, paper.PathTemplate));

            var context = new PaperContext();

            context.Paper    = paper;
            context.Path     = paperPath;
            context.Action   = paperAction;
            context.Args     = args;
            context.Request  = req;
            context.Response = res;

            var caller   = objectFactory.CreateObject <PaperCaller>();
            var renderer = objectFactory.CreateObject <PaperRenderer>();

            Ret <Result> result = await caller.CallAsync(context);

            if (result.Status.CodeClass != HttpStatusClass.Success)
            {
                var entity = HttpEntity.CreateFromRet(req.RequestUri, result);
                await SendAsync(res, result, entity);

                return;
            }

            Ret <Entity> media = await renderer.RenderAsync(context, result);

            if (!media.Ok)
            {
                var entity = HttpEntity.CreateFromRet(req.RequestUri, result);
                await SendAsync(res, media, entity);

                return;
            }

            await SendAsync(res, media, media.Value);
        }