Map() public method

public Map ( Fun x ) : List
x Fun
return List
Ejemplo n.º 1
0
        /// <summary>
        /// Returns chunk with duplicate point positions removed.
        /// </summary>
        public Chunk ImmutableDeduplicate()
        {
            if (!HasPositions)
            {
                return(this);
            }

            var dedup = new HashSet <V3d>();
            var ia    = new List <int>();

            for (var i = 0; i < Count; i++)
            {
                if (dedup.Add(Positions[i]))
                {
                    ia.Add(i);
                }
            }
            var hasDuplicates = ia.Count < Count;

            if (hasDuplicates)
            {
                var self = this;
                var ps   = HasPositions ? ia.Map(i => self.Positions[i]) : null;
                var cs   = HasColors ? ia.Map(i => self.Colors[i]) : null;
                var ns   = HasNormals ? ia.Map(i => self.Normals[i]) : null;
                var js   = HasIntensities ? ia.Map(i => self.Intensities[i]) : null;
                return(new Chunk(ps, cs, ns, js));
            }
            else
            {
                return(this);
            }
        }
        private void RunInsertAndRead()
        {
            Customer c = new Customer()
            {
                Username = "******", DeletedTime = DateTime.MaxValue, MyTimeSpan = new TimeSpan(1, 30, 0)
            };

            c.ContactDetails = new ContactDetails();
            c.ContactDetails.ContactItemList = new List <ContactItem>();
            c.ContactDetails.ContactItemList.Add(new AlfaOnline("a", "b", "C"));
            c._SetCustomProperty("MyBoolProp", true);
            c._SetCustomProperty("MyDateTime", DateTime.Now);
            c._SetCustomProperty("Settings", new CustomerSettings()
            {
                CustomerConnect_NotifCancelled = true, NotifFinished = true
            });
            c._SetCustomProperty("MyList", new List <uint> {
                1, 2, 3, 4
            });

            CoreObject co = c;
            long       id;

            using (IDbConnection db = _dbFactory.Open())
            {
                var typedApi = db.CreateTypedApi(co.GetType());
                id = typedApi.Insert(co, selectIdentity: true);

                Console.WriteLine($"  Insert - Untyped: {id}");

                string tableName = co.GetType().GetModelMetadata().ModelName;
                List <Dictionary <string, object> > results = db.Select <Dictionary <string, object> >($"SELECT * FROM {tableName} where id={id}");
                List <CoreObject> coreObjects = results.Map(x => (CoreObject)x.FromObjectDictionary(co.GetType()));
                Console.WriteLine($"  Read - Untyped + FromObjectDict: {id}");
                RunAssert(coreObjects[0]);

                Console.WriteLine($"  Read - Typed: {id}");
                coreObjects = db.Select <CoreObject>($"SELECT * FROM {tableName} where id={id}");
                Customer cDes = db.SingleById <Customer>(id);
                RunAssert(cDes);
                Console.WriteLine();

                id = db.Insert <Customer>(c, selectIdentity: true);
                Console.WriteLine($"  Insert - Typed: {id}");

                Console.WriteLine($"  Read - Untyped + FromObjectDict: {id}");
                results     = db.Select <Dictionary <string, object> >($"SELECT * FROM {tableName} where id={id}");
                coreObjects = results.Map(x => (CoreObject)x.FromObjectDictionary(co.GetType()));
                RunAssert(coreObjects[0]);

                Console.WriteLine($"  Read - Typed: {id}");
                cDes = db.SingleById <Customer>(id);
                RunAssert(cDes);
            };
        }
Ejemplo n.º 3
0
        public void GetMembers_ByHierarchy_ReturnListMembersWithCorrectLevelNumber()
        {
            //Buiding object used during test
            var mae   = new MembersAdomdEngine();
            var disco = new DiscoveryRequestFactory().Build(
                ConnectionStringReader.GetAdomd(),
                string.Empty,
                "Adventure Works",
                "Geography",
                "Geography",
                null
                );

            //Call the method to test
            var actual = mae.GetMembers(disco);

            ////Assertion
            Assert.That(actual, Has.Count.GreaterThan(0));
            //0 = All
            Assert.That(List.Map(actual).Property("LevelNumber"), Has.Some.EqualTo(0));
            //1 = Country
            Assert.That(List.Map(actual).Property("LevelNumber"), Has.Some.EqualTo(1));
            //2 = State/Province
            Assert.That(List.Map(actual).Property("LevelNumber"), Has.Some.EqualTo(2));
            //3 = Town
            Assert.That(List.Map(actual).Property("LevelNumber"), Has.Some.EqualTo(3));
            //4 = Zip code
            Assert.That(List.Map(actual).Property("LevelNumber"), Has.Some.EqualTo(4));
            //Nothing else
            Assert.That(List.Map(actual).Property("LevelNumber"), Has.All.LessThanOrEqualTo(4));
        }
Ejemplo n.º 4
0
        public void ListMapperTest()
        {
            var strings = new [] { "a", "ab", "abc" };
            var lengths = new [] { 1, 2, 3 };

            Assert.That(List.Map(strings).Property("Length"), Is.EqualTo(lengths), "Map property Length from string array to array list");
        }
Ejemplo n.º 5
0
    void RemoveGroup(int group, List <List <Card> > groups)
    {
        if (group < 0 || group >= groups.Count)
        {
            return;
        }
        //print("remove "+ group + groups[group].Map(card => card.name).StringJoin(","));
        List <GameObject> coll = new List <GameObject>();

        foreach (var trans in ScrollView.transform)
        {
            if (trans is Transform transform)
            {
                CardSetting cardSetting = transform.GetComponent <CardSetting>();
                if (cardSetting == null)
                {
                    continue;
                }
                if (groups[group].Contains(cardSetting.setedCard))
                {
                    coll.Add(cardSetting.gameObject);
                }
            }
        }
        coll.Map(go => RemoveCardSetting(go));
    }
Ejemplo n.º 6
0
        public void ListObjectTestWithAutoMapping()
        {
            MapFactory.ResetAllMaps();
            var target = new List <InnType>
            {
                new InnType {
                    DateTimeValue = DateTime.Now, DesimalValue = (decimal)100.212, StringValue = "test"
                },
                new InnType {
                    DateTimeValue = DateTime.Now, DesimalValue = (decimal)100.212, StringValue = "test"
                },
                new InnType {
                    DateTimeValue = DateTime.Now, DesimalValue = (decimal)100.212, StringValue = "test", MyInts = new List <int> {
                        1, 2, 3, 4
                    }
                }
            };

            var result = target.Map().To <OutType2>();

            Assert.IsNotNull(result);
            Assert.AreEqual(3, result.Count());
            Assert.AreEqual(target.First().DateTimeValue, result.First().DateTimeValue);
            Assert.AreNotEqual(target.First().DesimalValue, result.First().DesimalValue1);
        }
Ejemplo n.º 7
0
    public void ShowTreasureCollection()
    {
        if (showCC == 1)
        {
            return;
        }
        showCC = 1;
        ClearScrollView();
        DescriptionWindowSingle.Close();
        MoveScrollView = null;
        List <Card> cards = GameController.GetAllTreasureCard();
        Vector3     LT    = CardL0T0.transform.position;
        Vector3     L1T0  = CardL1T0.transform.position;
        Vector3     L0T1  = CardL0T1.transform.position;
        Vector3     dx    = L1T0 - LT;
        Vector3     dy    = L0T1 - LT;

        List <CardSetting> settings = cards.Map(GetCardSetting);

        settings.Map((setting, index) => {
            int fx = index % 3;
            int fy = index / 3;
            setting.HideStar();
            setting.transform.localPosition = LT + fx * dx + fy * dy;
            if (!setting.setedCard.Lock)
            {
                setting.EnableTap(true, () => {
                    DescriptionWindowSingle.Show(setting.setedCard, tween => { });
                });
            }
        });

        ScrollTop = -(LT + dy * (cards.Count / 3 - 1)).y;
        HookAllScrollViewObjects();
    }
Ejemplo n.º 8
0
        public static void BuildConvexPolygon(this Mesh mesh, Vector3[] vertices, Vector3 normal)
        {
            var v3s = new List <Vector3>(vertices);

            v3s.Add(v3s.GetCentroid());

            List <int> triangles = new List <int>();

            vertices.ToList().ForEach((v, i) => {
                triangles.Add(i);
                triangles.Add((i + 1) % vertices.Length);
                triangles.Add(v3s.Count - 1);
            });

            var normals = new Vector3[v3s.Count];

            normals.Fill(() => normal);

            var uv = v3s.Map(v => v.ToVector2()).ToArray();

            mesh.vertices  = v3s.ToArray();
            mesh.triangles = triangles.ToArray();
            mesh.normals   = normals;
            mesh.uv        = uv;
        }
Ejemplo n.º 9
0
 public void YeaJurMapperSameTypeTest()
 {
     var list = new List <Order> {
         GetOrder(), GetOrder(), GetOrder()
     };
     var model = list.Map();
 }
        public static async Task MapTFunc_Maps(List <string> collection, Func <string, int> mapper)
        {
            var expected = collection.Map(mapper);
            var actual   = await Task.FromResult <IEnumerable <string> >(collection).MapT(mapper).ConfigureAwait(false);

            Assert.Equal(expected, actual);
        }
Ejemplo n.º 11
0
        private SwaggerApi FormatMethodDescription(RestPath restPath, Dictionary <string, SwaggerModel> models)
        {
            var verbs   = new List <string>();
            var summary = restPath.Summary ?? restPath.RequestType.GetDescription();
            var notes   = restPath.Notes;

            verbs.AddRange(restPath.AllowsAllVerbs
                ? new[] { "GET", "POST", "PUT", "DELETE" }
                : restPath.AllowedVerbs.Split(new[] { ',', ' ' }, StringSplitOptions.RemoveEmptyEntries));

            var routePath   = restPath.Path.Replace("*", "");
            var requestType = restPath.RequestType;

            var md = new SwaggerApi
            {
                Path        = routePath,
                Description = summary,
                Operations  = verbs.Map(verb => new SwaggerOperation
                {
                    Method         = verb,
                    Nickname       = requestType.Name,
                    Summary        = summary,
                    Notes          = notes,
                    Parameters     = ParseParameters(verb, requestType, models, routePath),
                    ResponseClass  = GetResponseClass(restPath, models),
                    ErrorResponses = GetMethodResponseCodes(requestType)
                })
            };

            return(md);
        }
Ejemplo n.º 12
0
        static void Main()
        {
            //If DB classes reside in other namespace, assembly etc.
            //Mapper.Assembly = nameof(MyAlternativeDbContext);

            //For more complex types, e.g nested custom objects which AutoMapper cannot determine automatically
            //As an alternative, you can also use Attribute Mapping: https://docs.automapper.org/en/latest/Attribute-mapping.html
            //Mapper.CustomMappings.Add(typeof(MyCustomSubclass), typeof(MyCustomSubclassViewModel)); //or:
            //Mapper.CustomMappings.Add<MyCustomSubclass, MyCustomSubclassViewModel>();

            //Optional advanced configuration; see below
            Mapper.OnConfiguring += AdvancedConf;

            var list1 = new List <MyClass1>
            {
                new MyClass1(),
                new MyClass1(),
                new MyClass1()
            };

            var dto  = list1.Map <List <MyClass2> >();
            var dto2 = Mapper.Map <List <MyClass2> >(list1);
            var dto3 = Mapper.Map <MyClass2[]>(list1);

            var dto4 = list1.MapL <MyClass2>(); //for convenience
            var dto5 = Mapper.MapL <MyClass2>(list1);

            var dto6 = list1.AsQueryable().ProjectTo <List <MyClass2> >(); //for DB queries
            var dto7 = Mapper.ProjectTo <List <MyClass2> >(list1.AsQueryable());
        }
Ejemplo n.º 13
0
        public string GenerateTypeScript(NativeTypesBase request, MetadataTypesConfig typesConfig)
        {
            //Include SS types by removing ServiceStack namespaces
            if (typesConfig.AddServiceStackTypes)
            {
                typesConfig.IgnoreTypesInNamespaces = new List <string>();
            }

            var metadataTypes = NativeTypesMetadata.GetMetadataTypes(Request, typesConfig);

            metadataTypes.Types.RemoveAll(x => x.Name == "Service");

            if (typesConfig.AddServiceStackTypes)
            {
                //IReturn markers are metadata properties that are not included as normal interfaces
                var generator          = ((NativeTypesMetadata)NativeTypesMetadata).GetMetadataTypesGenerator(typesConfig);
                var registerInterfaces = new List <Type>
                {
                    typeof(IReturn <>),
                    typeof(IReturnVoid),
                };
                var builtinInterfaces = new[]
                {
                    typeof(IGet),
                    typeof(IPost),
                    typeof(IPut),
                    typeof(IDelete),
                    typeof(IPatch),
                    typeof(IOptions),
                    typeof(IMeta),
                    typeof(IHasSessionId),
                    typeof(IHasVersion),
                };

                foreach (var op in metadataTypes.Operations)
                {
                    foreach (var typeName in op.Request.Implements.Safe())
                    {
                        var iface = builtinInterfaces.FirstOrDefault(x => x.Name == typeName.Name);
                        if (iface != null)
                        {
                            registerInterfaces.AddIfNotExists(iface);
                        }
                    }
                }

                metadataTypes.Types.InsertRange(0, registerInterfaces.Map(x => generator.ToType(x)));
            }

            ExportMissingSystemTypes(typesConfig);

            typesConfig.ExportTypes.Add(typeof(Tuple <>));
            typesConfig.ExportTypes.Add(typeof(Tuple <,>));
            typesConfig.ExportTypes.Add(typeof(Tuple <, ,>));
            typesConfig.ExportTypes.Add(typeof(Tuple <, , ,>));

            var typeScript = new TypeScriptGenerator(typesConfig).GetCode(metadataTypes, base.Request, NativeTypesMetadata);

            return(typeScript);
        }
Ejemplo n.º 14
0
 public void GetMethodsWithAttribute()
 {
     MethodInfo[] methods = Reflect.GetMethodsWithAttribute(myType, "Colors.BlueAttribute", false);
     Assert.That(
         List.Map(methods).Property("Name"),
         Is.EqualTo(new string[] { "BaseBlueMethod", "BlueMethod" }));
 }
Ejemplo n.º 15
0
        public async Task <List <Password> > GetAllPasswords()
        {
            List <PasswordOrm> allPasswordOrms = dbHelper.GetAllPasswords();
            List <Password>    result          = allPasswordOrms.Map <List <PasswordOrm>, List <Password> >();

            return(await Task.FromResult(result));
        }
Ejemplo n.º 16
0
        public void MapPrivateFields()
        {
            List <SimpleClass1> list = new List <SimpleClass1>
            {
                new SimpleClass1(10,
                                 new Dictionary <int, string>()
                {
                    { 10, "a" }
                },
                                 new Dictionary <string, InnerClass>()
                {
                    { "hello", new InnerClass()
                      {
                          InnerString = "Test"
                      } }
                })
            };
            var mappedList = list.Map <SimpleClass2>();

            Assert.Collection(mappedList, (item) =>
            {
                Assert.Equal(10, item.Val1);
                Assert.Collection(item.Dic, val =>
                {
                    Assert.Equal("a", val.Value);
                });
                Assert.Collection(item.ComplexDic, val =>
                {
                    Assert.Equal("hello", val.Key);
                    Assert.Equal("Test", val.Value.InnerString);
                });
            });
        }
Ejemplo n.º 17
0
        public void ListObjectTestType2()
        {
            MapFactory.ResetAllMaps();
            var target = new List <InnType>
            {
                new InnType {
                    DateTimeValue = DateTime.Now, DesimalValue = (decimal)100.212, StringValue = "test"
                },
                new InnType {
                    DateTimeValue = DateTime.Now, DesimalValue = (decimal)100.212, StringValue = "test"
                },
                new InnType {
                    DateTimeValue = DateTime.Now, DesimalValue = (decimal)100.212, StringValue = "test"
                }
            };
            var map = MapFactory.CreateEmptyMapRule <InnType, OutType2>();

            map.AddMap <InnType, OutType2>(new Dictionary <string, string>
            {
                { "DateTimeValue", "DateTimeValue" },
                { "DesimalValue", "DesimalValue1" },
                { "StringValue", "StringValue" }
            });
            var result = target.Map().To <OutType2>(map);

            Assert.IsNotNull(result);
            Assert.AreEqual(3, result.Count());
        }
Ejemplo n.º 18
0
        public void MapEmptyList()
        {
            List <SimpleClass1> emptyList = new List <SimpleClass1>();
            var mappedList = emptyList.Map <SimpleClass2>();

            Assert.Equal(emptyList.Count, mappedList.Count());
        }
Ejemplo n.º 19
0
        public void MapList()
        {
            List <SimpleClass1> list = new List <SimpleClass1>
            {
                new SimpleClass1()
                {
                    Var1 = "Hello", Var2 = 1, List = new List <InnerClass>()
                    {
                        new InnerClass()
                        {
                            InnerString = "Inner"
                        }
                    }
                }
            };
            var mappedList = list.Map <SimpleClass2>();

            Assert.Collection(mappedList, (item) =>
            {
                Assert.Equal("Hello", item.Var1);
                Assert.Equal(1, item.Var2Test);
                Assert.Collection(item.ListTest, (innerItem) =>
                {
                    Assert.Equal("Inner", innerItem.TestName);
                });
            });
        }
        public void ShouldReturnMapStringResultsUsingIntList()
        {
            List <int> list = new List <int>()
            {
                1, 2, 3, 4
            };
            List <string> expected = new List <string>()
            {
                "AA", "BB", "CC", "DD"
            };

            Func <int, string> Translate = (a) =>
            {
                Dictionary <int, string> translations = new Dictionary <int, string>
                {
                    { 1, "AA" },
                    { 2, "BB" },
                    { 3, "CC" },
                    { 4, "DD" },
                    { 5, "EE" }
                };
                return(translations[a]);
            };

            Assert.Equal(expected, list.Map(Translate));
        }
Ejemplo n.º 21
0
        protected override void Start()
        {
            base.Start();

            var assembliesToTest = anyTypeInTargetAssembly.Map(typeString => {
                try { return(Type.GetType(typeString).Assembly); }
                catch (Exception) {
                    Log.e("Could not find type for string '" + typeString + "'");
                    return(null);
                }
            });

            // On the parent canvas level collect all links:
            var links         = GetComponentInParent <Canvas>().gameObject.GetLinkMap();
            var autoRunToggle = links.Get <Toggle>("AutoRunToggle");

            autoRunToggle.isOn = autoRunAllTests;
            autoRunToggle.SetOnValueChangedAction(isChecked => {
                autoRunAllTests = isChecked;
                return(true);
            });
            links.Get <Button>("StartButton").SetOnClickAction((_) => {
                CollectTests(assembliesToTest, links);
            });
            links.Get <InputField>("SearchInput").SetOnValueChangedActionThrottled((newSearchText) => {
                newSearchText = newSearchText.ToLower();
                CellData      = allTests.Filter(t => t.name.ToLower().Contains(newSearchText)).ToList();
            }, 200);
        }
Ejemplo n.º 22
0
        protected void ValidateProperty <T>(string propertyName, T value)
        {
            var context = new ValidationContext(this)
            {
                MemberName = propertyName,
            };
            var results = new List <ValidationResult>();

            Validator.TryValidateProperty(value, context, results);
            var oldErrors = _errors.TryGetValue(propertyName);
            var newErrors = results
                            .Map(result => result.ErrorMessage)
                            .ToImmutableArray();

            if (newErrors.Any())
            {
                _errors[propertyName] = newErrors;
            }
            else
            {
                _errors.Remove(propertyName);
            }

            var isErrorsChanged = oldErrors
                                  .Some(oldErrorsValue => !oldErrorsValue.SequenceEqual(newErrors))
                                  .None(() => true);

            if (isErrorsChanged)
            {
                ErrorsChanged?.Invoke(this, new(propertyName));
            }
        }
Ejemplo n.º 23
0
    public void Episodes_Should_Not_Duplicate_When_Reshuffling()
    {
        List <MediaItem> contents = Episodes(10);

        // normally returns 10 5 7 4 3 6 2 8 9 1 1 (note duplicate 1 at end)
        var state = new CollectionEnumeratorState {
            Seed = 8
        };

        var groupedMediaItems = contents.Map(mi => new GroupedMediaItem(mi, null)).ToList();
        var shuffledContent   = new ShuffledMediaCollectionEnumerator(groupedMediaItems, state);

        var list = new List <int>();

        for (var i = 1; i <= 1000; i++)
        {
            shuffledContent.Current.IsSome.Should().BeTrue();
            shuffledContent.Current.Do(x => list.Add(x.Id));
            shuffledContent.MoveNext();
        }

        for (var i = 0; i < list.Count - 1; i++)
        {
            if (list[i] == list[i + 1])
            {
                Assert.Fail("List contains duplicate items");
            }
        }
    }
Ejemplo n.º 24
0
        public async Task <List <Group> > GetAllGroups()
        {
            List <GroupOrm> allGroupOrms = dbHelper.GetAllGroups();
            List <Group>    result       = allGroupOrms.Map <List <GroupOrm>, List <Group> >();

            return(await Task.FromResult(result));
        }
Ejemplo n.º 25
0
        private static PropertyInfo FindProperty(Type type, string propertyName, Expression[] arguments, BindingFlags flags)
        {
            var props   = type.GetProperties(flags).Where(x => x.Name.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase));
            var members = new List <PropertyInfo>(props).ToArray();

            if (members == null || members.Length == 0)
            {
                return(null);
            }

            PropertyInfo pi;
            var          propertyInfos = members.Map(t => t);
            var          count         = FindBestProperty(propertyInfos, arguments, out pi);

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

            if (count > 1)
            {
                throw Error.PropertyWithMoreThanOneMatch(propertyName, type);
            }

            return(pi);
        }
Ejemplo n.º 26
0
    public void SelectTreasure(List <Card> list)
    {
        Title.SetSelectTreasure();
        Buttons.Show();
        ClearScrollView();
        StartSence.gameObject.SetActive(false);

        Vector3 first     = First.transform.position;
        Vector3 second    = Second.transform.position;
        Vector3 dPosition = second - first;

        Vector3[] positions = new Vector3[] { first, second, second + dPosition };

        List <TrasureSelectCommponentSetting> settings = list.Map(card => GetTrasureSelectCommponentSetting());

        for (int i = 0; i < list.Count; i++)
        {
            var  setting = settings[i];
            Card card    = list[i];
            //Debug.Log(card.name);
            setting.SetByCard(card);
            setting.transform.position = positions[i];
            setting.Glow(false);
            setting.EnableTap(true, () => {
                OnSelectTreasure(card);
                settings.Map(st => st.Glow(false));
                setting.Glow(true);
            });
        }
        OnSelectTreasure(null);
    }
Ejemplo n.º 27
0
        protected override void Start()
        {
            base.Start();

            var assembliesToTest = anyTypeInTargetAssembly.Map(typeString => {
                try { return(Type.GetType(typeString).Assembly); }
                catch (Exception) {
                    Log.e("Could not find type for string '" + typeString + "'");
                    return(null);
                }
            });

            // On the parent canvas level collect all links:
            var links         = GetComponentInParent <Canvas>().gameObject.GetLinkMap();
            var autoRunToggle = links.Get <Toggle>("AutoRunToggle");

            autoRunToggle.isOn = autoRunAllTests;
            autoRunToggle.SetOnValueChangedAction(isChecked => {
                autoRunAllTests = isChecked;
                return(true);
            });
            links.Get <Button>("StartButton").SetOnClickAction((_) => {
                CollectTests(assembliesToTest, links);
            });
        }
 public bool AddLineStatus(List <LineStatusDTO> data)
 {
     using (var uow = new UnitOfWork())
     {
         try
         {
             var isAdded = uow.LineStatus.AddLineStatus(data.Map());
             if (isAdded == true)
             {
                 return(true);
             }
             else
             {
                 return(false);
             }
         }
         catch (Exception ex)
         {
             ex.Data.Add("AddDataUsage", "An error occurred while trying to Add Data Usage Record - BLL");
             uow.Rollback();
             Tracer.Error(ex);
             return(false);
         }
     }
 }
Ejemplo n.º 29
0
        public void should_get_the_newest_articles_from_entire_day()
        {
            var articles = new List <Article>
            {
                new ArticleBuilder().WithDate(new DateTime(2021, 03, 12)).Build(),
                new ArticleBuilder().WithDate(new DateTime(2022, 04, 22)).Build(),
                new ArticleBuilder().WithDate(new DateTime(2022, 04, 23, 10, 20, 02)).Build(),
                new ArticleBuilder().WithDate(new DateTime(2022, 04, 23, 10, 20, 21)).Build(),
                new ArticleBuilder().WithDate(new DateTime(2022, 04, 23, 12, 00, 00)).Build(),
                new ArticleBuilder().WithDate(new DateTime(2022, 04, 23, 15, 40, 00)).Build(),
                new ArticleBuilder().WithDate(new DateTime(2022, 04, 23, 23, 00, 41)).Build(),
            };
            var articlesFromDb = articles.Map().OrderByDescending(n => n.DateScrapped).ToList();

            var expectedResult = articles
                                 .Where(a => a.DateScrapped.ToShortDateString() == new DateTime(2022, 04, 23).ToShortDateString())
                                 .OrderByDescending(a => a.DateScrapped)
                                 .ToList();

            List <ArticleDb> mappedArticles = null;

            void MapArticles(object list)
            {
                mappedArticles = list as List <ArticleDb>;
            }

            _articlesRepository.Setup(n => n.Get(null, It.IsAny <Func <IQueryable <ArticleDb>, IOrderedQueryable <ArticleDb> > >(), ""))
            .Returns(articlesFromDb);
            _mapper.Setup(n => n.Map <List <Article> >(It.IsAny <List <ArticleDb> >())).Callback((Action <object>)MapArticles);

            _sut.GetNew();

            mappedArticles.Should().BeEquivalentTo(expectedResult);
        }
Ejemplo n.º 30
0
        private SwaggerApi FormatMethodDescription(RestPath restPath, Dictionary <string, SwaggerModel> models)
        {
            var verbs   = new List <string>();
            var summary = restPath.Summary ?? restPath.RequestType.GetDescription();
            var notes   = restPath.Notes;

            verbs.AddRange(restPath.AllowsAllVerbs
                ? AnyRouteVerbs
                : restPath.Verbs);

            var routePath   = restPath.Path.Replace("*", "");
            var requestType = restPath.RequestType;

            var md = new SwaggerApi
            {
                Path        = routePath,
                Description = summary,
                Operations  = verbs.Map(verb => new SwaggerOperation
                {
                    Method         = verb,
                    Nickname       = requestType.Name,
                    Summary        = summary,
                    Notes          = notes,
                    Parameters     = ParseParameters(verb, requestType, models, routePath),
                    ResponseClass  = GetResponseClass(restPath, models),
                    ErrorResponses = GetMethodResponseCodes(requestType),
                    Deprecated     = requestType.HasAttribute <ObsoleteAttribute>() ? "true" : null
                })
            };

            return(md);
        }
Ejemplo n.º 31
0
        public static List<string> TrimArgs(List<string> from)
        {
            if (from == null)
                return null;

            var to = from.Map(x => x == null ? x : x.Trim());
            return to;
        }
Ejemplo n.º 32
0
 public static void Main(string[] args)
 {
     var test = new TestMapExtensions();
     var input = new List<int>();
     input.AddRange(Enumerable.Range(1, 10));
     var output = (List<int>)input.Map(test.square);
     for (int i = 0; i < output.Count(); i++)
     {
         Contract.Ensures(output[i] == input[i] * input[i]);
     }
 }
Ejemplo n.º 33
0
        public override RegionMeta Select(
            int index,
            int date,
            List<RegionMeta> regionHistory,
            Dictionary<RegionType, int> regionCountMap,
            Dictionary<RegionType, int> regionLastIndex,
            Dictionary<RegionType, int> regionLastDate) {

            CurrentDate = date;
            RegionHistory = regionHistory;
            RegionCountMap = regionCountMap;
            RegionLastIndex = regionLastIndex;
            RegionLastDate = regionLastDate;

            var mustSelect = new List<RegionType>();
            var weightList = new List<Pair<RegionType, float>>();
            foreach (var pair in m_calculators) {
                var regionType = pair.Key;
                var calculator = pair.Value;

                int passIndexSinceLast = regionLastIndex.ContainsKey(regionType) ? index - regionLastIndex[regionType] : index + 1;
                int passTimeSinceLast = regionLastDate.ContainsKey(regionType) ? date - regionLastDate[regionType] : date + 1;
                var regionSelectInfo = regionArgs.ContainsKey(regionType) ? regionArgs[regionType] : _defaultRegionSelectInfo;

                float weight = calculator(regionSelectInfo, passIndexSinceLast, passTimeSinceLast);
                if (weight == float.MaxValue) {
                    mustSelect.Add(regionType);
                }
                else {
                    weightList.Add(Pair.Of(regionType, weight));
                }
            }

            RegionType selectedType;
            if (mustSelect.Count > 0) {
                selectedType = Randoms.Default.Range(mustSelect);
            }
            else {
                selectedType = Randoms.Default.RangeWithWeight(weightList, weightList.Map(pair => pair.Second)).First;
            }
            var regionMeta = new RegionMeta() {
                date = date,
                type = selectedType
            };
            if (m_postProcesses.ContainsKey(selectedType)) {
                m_postProcesses[selectedType](
                    regionArgs.ContainsKey(selectedType) ? regionArgs[selectedType] : null,
                    regionMeta);
            }
            return regionMeta;
        }
Ejemplo n.º 34
0
        public async Task WaitForTablesToBeReadyAsync(IEnumerable<string> tableNames, CancellationToken token = default(CancellationToken))
        {
            var pendingTables = new List<string>(tableNames);

            if (pendingTables.Count == 0)
                return;

            do
            {
                try
                {
                    var responses = await Task.WhenAll(pendingTables.Map(x =>
                            ExecAsync(() => DynamoDb.DescribeTableAsync(x, token))
                        ).ToArray());

                    foreach (var response in responses)
                    {
                        if (response.Table.TableStatus == DynamoStatus.Active)
                            pendingTables.Remove(response.Table.TableName);
                    }

                    if (Log.IsDebugEnabled)
                        Log.Debug("Tables Pending: {0}".Fmt(pendingTables.ToJsv()));

                    if (pendingTables.Count == 0)
                        return;

                    if (token.IsCancellationRequested)
                        return;

                    Thread.Sleep(PollTableStatus);
                }
                catch (ResourceNotFoundException)
                {
                    // DescribeTable is eventually consistent. So you might
                    // get resource not found. So we handle the potential exception.
                }
            } while (true);
        }
Ejemplo n.º 35
0
		internal static void SetEnabledNotations(IEnumerable<NotationConstructor> notationConstructors)
		{
			Contract.Requires(notationConstructors != null);
			Contract.LazilyAssertMinimumCount(ref notationConstructors, 1);
			if (!notationConstructors.Select(OrderRequirementAttribute.ToComparableToken).IsSorted())
			{
				//whenever a special array of ConstructorNotations is specified, I don't want to have to manually sort it. This just does that for me. 
				//however, the most frequently specified enumerable, AllLinearNotations, should simply be already sorted
				notationConstructors = notationConstructors.OrderBy(OrderRequirementAttribute.ToComparableToken);
			}

			List<INotation<TestDomain>> allNotations = new List<INotation<TestDomain>>();
			foreach (NotationConstructor notationConstructor in notationConstructors)
			{
				allNotations.AddRange(notationConstructor(allNotations));
			}

			allNotations.Sort(Notation<TestDomain>.ComparerByForm);//perhaps it is important that this happens after adding all elements. Artificial notations that are to be replaced, can they be replaced with normal notations that exist 
																   //before that artificial notation was created notation-precedence wise, or added-wise?

			Contract.Assert(allNotations.Select(notation => notation.Form).AreUnique());//checks that no artificial notation forms are returned that could have been replaced by normal notation forms
			EnabledNotations = new SortedReadOnlyList<ICompositeNotationForm<TestDomain>>(allNotations.Map(notation => (ICompositeNotationForm<TestDomain>)notation.Form));
		}
Ejemplo n.º 36
0
 //implementar aquí métodos de ejercicios 1, 2 y 3
 public void ej1(int formato)
 {
     List<int> duraciones = new List<int>(canciones.Filter(x => x.FormatoID == formato).Select(x => x.Duracion));
     int media = duraciones.Reduce((x,y) => x + y) / canciones.Filter(x => x.FormatoID == formato).Count();
     Console.WriteLine(duraciones.Map(x => (x-media)*(x-media)).Sum());
 }
Ejemplo n.º 37
0
        public string GetCode(MetadataTypes metadata, IRequest request)
        {
            var defaultNamespaces = Config.DefaultSwiftNamespaces;

            var typeNamespaces = new HashSet<string>();
            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            Func<string, string> defaultValue = k =>
                request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sb = new StringBuilderWrapper(new StringBuilder());
            var sbExt = new StringBuilderWrapper(new StringBuilder());
            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("Version: {0}".Fmt(metadata.Version));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();

            //sb.AppendLine("{0}MakePropertiesOptional: {1}".Fmt(defaultValue("MakePropertiesOptional"), Config.MakePropertiesOptional));
            //sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddModelExtensions: {1}".Fmt(defaultValue("AddModelExtensions"), Config.AddModelExtensions));
            sb.AppendLine("{0}InitializeCollections: {1}".Fmt(defaultValue("InitializeCollections"), Config.InitializeCollections));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}DefaultNamespaces: {1}".Fmt(defaultValue("DefaultNamespaces"), defaultNamespaces.ToArray().Join(", ")));

            sb.AppendLine("*/");
            sb.AppendLine();

            string lastNS = null;

            var existingTypes = new HashSet<string>();

            var requestTypes = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes = metadata.Operations
                .Where(x => x.Response != null)
                .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            var allTypes = new List<MetadataType>();
            allTypes.AddRange(types);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(requestTypes);

            //Swift doesn't support reusing same type name with different generic airity
            var conflictPartialNames = allTypes.Map(x => x.Name).Distinct()
                .GroupBy(g => g.SplitOnFirst('`')[0])
                .Where(g => g.Count() > 1)
                .Select(g => g.Key)
                .ToList();

            this.conflictTypeNames = allTypes
                .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                .Map(x => x.Name);

            defaultNamespaces.Each(x => sb.AppendLine("import {0}".Fmt(x)));

            //ServiceStack core interfaces
            foreach (var type in allTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                            new CreateTypeOptions
                            {
                                ImplementsFn = () =>
                                {
                                    if (!Config.AddReturnMarker
                                        && !type.ReturnVoidMarker
                                        && type.ReturnMarkerTypeName == null)
                                        return null;

                                    if (type.ReturnVoidMarker)
                                        return "IReturnVoid";
                                    if (type.ReturnMarkerTypeName != null)
                                        return Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) });
                                    return response != null
                                        ? Type("IReturn`1", new[] { Type(type.Name, type.GenericArgs) })
                                        : null;
                                },
                                IsRequest = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName)
                        && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                            new CreateTypeOptions
                            {
                                IsResponse = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                        new CreateTypeOptions { IsType = true });

                    existingTypes.Add(fullTypeName);
                }
            }

            if (Config.AddModelExtensions)
            {
                sb.AppendLine();
                sb.AppendLine(sbExt.ToString());
            }

            return sb.ToString();
        }
Ejemplo n.º 38
0
        public string GetCode(MetadataTypes metadata, IRequest request)
        {
            var typeNamespaces = new HashSet<string>();
            RemoveIgnoredTypes(metadata);
            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            var defaultImports = !Config.DefaultImports.IsEmpty()
                ? Config.DefaultImports
                : DefaultImports;

            Func<string, string> defaultValue = k =>
                request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sbInner = StringBuilderCache.Allocate();
            var sb = new StringBuilderWrapper(sbInner);
            var sbExt = new StringBuilderWrapper(new StringBuilder());
            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("SwiftVersion: 3.0");
            sb.AppendLine("Version: {0}".Fmt(Env.ServiceStackVersion));
            sb.AppendLine("Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("//")));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();

            sb.AppendLine("{0}BaseClass: {1}".Fmt(defaultValue("BaseClass"), Config.BaseClass));
            sb.AppendLine("{0}AddModelExtensions: {1}".Fmt(defaultValue("AddModelExtensions"), Config.AddModelExtensions));
            sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeGenericBaseTypes: {1}".Fmt(defaultValue("ExcludeGenericBaseTypes"), Config.ExcludeGenericBaseTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}InitializeCollections: {1}".Fmt(defaultValue("InitializeCollections"), Config.InitializeCollections));
            sb.AppendLine("{0}TreatTypesAsStrings: {1}".Fmt(defaultValue("TreatTypesAsStrings"), Config.TreatTypesAsStrings.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}DefaultImports: {1}".Fmt(defaultValue("DefaultImports"), defaultImports.Join(",")));

            sb.AppendLine("*/");
            sb.AppendLine();

            foreach (var typeName in Config.TreatTypesAsStrings.Safe())
            {
                TypeAliases[typeName] = "String";
            }

            string lastNS = null;

            var existingTypes = new HashSet<string>();

            var requestTypes = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes = metadata.Operations
                .Where(x => x.Response != null)
                .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            allTypes = new List<MetadataType>();
            allTypes.AddRange(requestTypes);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(types);

            allTypes = FilterTypes(allTypes);

            //Swift doesn't support reusing same type name with different generic airity
            var conflictPartialNames = allTypes.Map(x => x.Name).Distinct()
                .GroupBy(g => g.LeftPart('`'))
                .Where(g => g.Count() > 1)
                .Select(g => g.Key)
                .ToList();

            this.conflictTypeNames = allTypes
                .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                .Map(x => x.Name);

            defaultImports.Each(x => sb.AppendLine("import {0};".Fmt(x)));

            //ServiceStack core interfaces
            foreach (var type in allTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                            new CreateTypeOptions
                            {
                                ImplementsFn = () =>
                                {
                                    if (!Config.AddReturnMarker
                                        && !type.ReturnVoidMarker
                                        && type.ReturnMarkerTypeName == null)
                                        return null;

                                    if (type.ReturnVoidMarker)
                                        return "IReturnVoid";
                                    if (type.ReturnMarkerTypeName != null)
                                        return ReturnType("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) });
                                    return response != null
                                        ? ReturnType("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                        : null;
                                },
                                IsRequest = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName)
                        && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                            new CreateTypeOptions
                            {
                                IsResponse = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, ref sbExt, type, lastNS,
                        new CreateTypeOptions { IsType = true });

                    existingTypes.Add(fullTypeName);
                }
            }

            if (Config.AddModelExtensions)
            {
                sb.AppendLine();
                sb.AppendLine(sbExt.ToString());
            }

            return StringBuilderCache.ReturnAndFree(sbInner);
        }
 public IEnumerable<int> GetSquares(List<int> numbers)
 {
     return numbers.Map(n => n*n);
 }
Ejemplo n.º 40
0
 private void manageWeaponButton_Click(object sender, EventArgs e)
 {
     var x = new ListEditor<Weapon, WeaponEditor>("Weapon", wpl);
     if (x.ShowDialog() == DialogResult.OK)
     {
         wpl = new List<Weapon>(x.Items);
         weaponBox.Items.Clear();
         weaponBox.Items.AddRange(wpl.Map(a => a.Name).ToArray());
         UpdateDamage();
     }
 }
        public string GetCode(MetadataTypes metadata, IRequest request, INativeTypesMetadata nativeTypes)
        {
            var typeNamespaces = new HashSet<string>();
            metadata.RemoveIgnoredTypes(Config);
            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            var defaultImports = !Config.DefaultImports.IsEmpty()
                ? Config.DefaultImports
                : DefaultImports;

            // Look first for shortest Namespace ending with `ServiceModel` convention, else shortest ns
            var globalNamespace = Config.GlobalNamespace
                ?? typeNamespaces.Where(x => x.EndsWith("ServiceModel"))
                    .OrderBy(x => x).FirstOrDefault()
                ?? typeNamespaces.OrderBy(x => x).First();

            Func<string, string> defaultValue = k =>
                request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sb = new StringBuilderWrapper(new StringBuilder());
            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("Version: {0}".Fmt(Env.ServiceStackVersion));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(defaultValue("GlobalNamespace"), Config.GlobalNamespace));
            sb.AppendLine("{0}MakePropertiesOptional: {1}".Fmt(defaultValue("MakePropertiesOptional"), Config.MakePropertiesOptional));
            sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}DefaultImports: {1}".Fmt(defaultValue("DefaultImports"), defaultImports.Join(",")));

            sb.AppendLine("*/");
            sb.AppendLine();

            string lastNS = null;

            var existingTypes = new HashSet<string>();

            var requestTypes = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes = metadata.Operations
                .Where(x => x.Response != null)
                .Select(x => x.Response).ToHashSet();
            var types = metadata.Types.ToHashSet();

            var allTypes = new List<MetadataType>();
            allTypes.AddRange(types);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(requestTypes);
            allTypes.RemoveAll(x => x.IgnoreType(Config));

            //TypeScript doesn't support reusing same type name with different generic airity
            var conflictPartialNames = allTypes.Map(x => x.Name).Distinct()
                .GroupBy(g => g.SplitOnFirst('`')[0])
                .Where(g => g.Count() > 1)
                .Select(g => g.Key)
                .ToList();

            this.conflictTypeNames = allTypes
                .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                .Map(x => x.Name);

            defaultImports.Each(x => sb.AppendLine("import {0};".Fmt(x)));
            sb.AppendLine();

            sb.AppendLine("declare module {0}".Fmt(globalNamespace.SafeToken()));
            sb.AppendLine("{");

            //ServiceStack core interfaces
            foreach (var type in allTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS,
                            new CreateTypeOptions
                            {
                                ImplementsFn = () =>
                                {
                                    if (!Config.AddReturnMarker
                                        && !type.ReturnVoidMarker
                                        && type.ReturnMarkerTypeName == null)
                                        return null;

                                    if (type.ReturnVoidMarker)
                                        return "IReturnVoid";
                                    if (type.ReturnMarkerTypeName != null)
                                        return Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName) });
                                    return response != null
                                        ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs) })
                                        : null;
                                },
                                IsRequest = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName)
                        && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS,
                            new CreateTypeOptions
                            {
                                IsResponse = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS,
                        new CreateTypeOptions { IsType = true });

                    existingTypes.Add(fullTypeName);
                }
            }

            sb.AppendLine();
            sb.AppendLine("}");

            return sb.ToString();
        }
Ejemplo n.º 42
0
        private static PropertyInfo FindProperty(Type type, string propertyName, Expression[] arguments, BindingFlags flags)
        {
            var props = type.GetProperties(flags).Where(x => x.Name.Equals(propertyName, StringComparison.CurrentCultureIgnoreCase)); ;
            PropertyInfo[] members = new List<PropertyInfo>(props).ToArray();
            if (members == null || members.Length == 0)
                return null;

            PropertyInfo pi;
            var propertyInfos = members.Map(t => (PropertyInfo)t);
            int count = FindBestProperty(propertyInfos, arguments, out pi);

            if (count == 0)
                return null;
            if (count > 1)
                throw Error.PropertyWithMoreThanOneMatch(propertyName, type);
            return pi;
        }
        public string GetCode(MetadataTypes metadata, IRequest request, INativeTypesMetadata nativeTypes)
        {
            var typeNamespaces = new HashSet<string>();
            metadata.RemoveIgnoredTypes(Config);
            metadata.Types.Each(x => typeNamespaces.Add(x.Namespace));
            metadata.Operations.Each(x => typeNamespaces.Add(x.Request.Namespace));

            var defaultImports = !Config.DefaultImports.IsEmpty()
                ? Config.DefaultImports
                : DefaultImports;

            var globalNamespace = Config.GlobalNamespace;

            Func<string, string> defaultValue = k =>
                request.QueryString[k].IsNullOrEmpty() ? "//" : "";

            var sbInner = StringBuilderCache.Allocate();
            var sb = new StringBuilderWrapper(sbInner);
            sb.AppendLine("/* Options:");
            sb.AppendLine("Date: {0}".Fmt(DateTime.Now.ToString("s").Replace("T", " ")));
            sb.AppendLine("Version: {0}".Fmt(Env.ServiceStackVersion));
            sb.AppendLine("Tip: {0}".Fmt(HelpMessages.NativeTypesDtoOptionsTip.Fmt("//")));
            sb.AppendLine("BaseUrl: {0}".Fmt(Config.BaseUrl));
            sb.AppendLine();
            sb.AppendLine("{0}GlobalNamespace: {1}".Fmt(defaultValue("GlobalNamespace"), Config.GlobalNamespace));
            //sb.AppendLine("{0}ExportAsTypes: {1}".Fmt(defaultValue("ExportAsTypes"), Config.ExportAsTypes));
            sb.AppendLine("{0}MakePropertiesOptional: {1}".Fmt(defaultValue("MakePropertiesOptional"), Config.MakePropertiesOptional));
            sb.AppendLine("{0}AddServiceStackTypes: {1}".Fmt(defaultValue("AddServiceStackTypes"), Config.AddServiceStackTypes));
            sb.AppendLine("{0}AddResponseStatus: {1}".Fmt(defaultValue("AddResponseStatus"), Config.AddResponseStatus));
            sb.AppendLine("{0}AddImplicitVersion: {1}".Fmt(defaultValue("AddImplicitVersion"), Config.AddImplicitVersion));
            sb.AppendLine("{0}AddDescriptionAsComments: {1}".Fmt(defaultValue("AddDescriptionAsComments"), Config.AddDescriptionAsComments));
            sb.AppendLine("{0}IncludeTypes: {1}".Fmt(defaultValue("IncludeTypes"), Config.IncludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}ExcludeTypes: {1}".Fmt(defaultValue("ExcludeTypes"), Config.ExcludeTypes.Safe().ToArray().Join(",")));
            sb.AppendLine("{0}DefaultImports: {1}".Fmt(defaultValue("DefaultImports"), defaultImports.Join(",")));

            sb.AppendLine("*/");
            sb.AppendLine();

            string lastNS = null;

            var existingTypes = new HashSet<string>();

            var requestTypes = metadata.Operations.Select(x => x.Request).ToHashSet();
            var requestTypesMap = metadata.Operations.ToSafeDictionary(x => x.Request);
            var responseTypes = metadata.Operations
                .Where(x => x.Response != null)
                .Select(x => x.Response).ToHashSet();

            // Base Types need to be written first
            var types = CreateSortedTypeList(metadata.Types);

            allTypes = new List<MetadataType>();
            allTypes.AddRange(types);
            allTypes.AddRange(responseTypes);
            allTypes.AddRange(requestTypes);
            allTypes.RemoveAll(x => x.IgnoreType(Config));

            allTypes = FilterTypes(allTypes);

            //TypeScript doesn't support reusing same type name with different generic airity
            var conflictPartialNames = allTypes.Map(x => x.Name).Distinct()
                .GroupBy(g => g.LeftPart('`'))
                .Where(g => g.Count() > 1)
                .Select(g => g.Key)
                .ToList();

            this.conflictTypeNames = allTypes
                .Where(x => conflictPartialNames.Any(name => x.Name.StartsWith(name)))
                .Map(x => x.Name);

            defaultImports.Each(x => sb.AppendLine("import {0};".Fmt(x)));

            if (!string.IsNullOrEmpty(globalNamespace))
            {
                var moduleDef = Config.ExportAsTypes ? "" : "declare ";
                sb.AppendLine();
                sb.AppendLine("{0}module {1}".Fmt(moduleDef, globalNamespace.SafeToken()));
                sb.AppendLine("{");

                sb = sb.Indent();
            }

            //ServiceStack core interfaces
            foreach (var type in allTypes)
            {
                var fullTypeName = type.GetFullName();
                if (requestTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName))
                    {
                        MetadataType response = null;
                        MetadataOperationType operation;
                        if (requestTypesMap.TryGetValue(type, out operation))
                        {
                            response = operation.Response;
                        }

                        lastNS = AppendType(ref sb, type, lastNS,
                            new CreateTypeOptions
                            {
                                ImplementsFn = () =>
                                {
                                    if (!Config.AddReturnMarker
                                        && !type.ReturnVoidMarker
                                        && type.ReturnMarkerTypeName == null)
                                        return null;

                                    if (type.ReturnVoidMarker)
                                        return "IReturnVoid";
                                    if (type.ReturnMarkerTypeName != null)
                                        return Type("IReturn`1", new[] { Type(type.ReturnMarkerTypeName).InDeclarationType() });
                                    return response != null
                                        ? Type("IReturn`1", new[] { Type(response.Name, response.GenericArgs).InDeclarationType() })
                                        : null;
                                },
                                IsRequest = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (responseTypes.Contains(type))
                {
                    if (!existingTypes.Contains(fullTypeName)
                        && !Config.IgnoreTypesInNamespaces.Contains(type.Namespace))
                    {
                        lastNS = AppendType(ref sb, type, lastNS,
                            new CreateTypeOptions
                            {
                                IsResponse = true,
                            });

                        existingTypes.Add(fullTypeName);
                    }
                }
                else if (types.Contains(type) && !existingTypes.Contains(fullTypeName))
                {
                    lastNS = AppendType(ref sb, type, lastNS,
                        new CreateTypeOptions { IsType = true });

                    existingTypes.Add(fullTypeName);
                }
            }

            if (!string.IsNullOrEmpty(globalNamespace))
            {
                sb = sb.UnIndent();
                sb.AppendLine();
                sb.AppendLine("}");
            }

            return StringBuilderCache.ReturnAndFree(sbInner);
        }