Exemple #1
0
        static void Main(string[] args)
        {
            //Builder Pattern karmaşık sınıfların nesne üretim sürecini Client'tan gizleyen bir pattern’dir.
            GenericExtensions.WriteToConsole("Merhaba Dünya!");
            GenericExtensions.WriteToConsole("Builder Pattern Örneği\n");

            // Client ilk olarak Director nesnesi alan
            // ve üretime geçen Builder nesnesini oluşturur.
            // Oluşturulan nesneler Builder nesnesinden üretilmiş olur.
            var director = new Director();
            var builder  = new ProductBuilder();

            director.Builder = builder;

            GenericExtensions.WriteToConsole("Temel ürün üretimi:");
            director.buildMinimalViableProduct();
            GenericExtensions.WriteToConsole(builder.GetProduct().ListParts());

            GenericExtensions.WriteToConsole("Full ürün üretimi:");
            director.buildFullFeaturedProduct();
            GenericExtensions.WriteToConsole(builder.GetProduct().ListParts());

            // Builder Pattern Director olmadan da kullanılabilir.
            GenericExtensions.WriteToConsole("Özel ürün üretimi:");
            builder.BuildPartA();
            builder.BuildPartC();
            GenericExtensions.WriteToConsole(builder.GetProduct().ListParts());

            "\nDevam etmek için enter e basınız".WriteToConsole();
            System.Console.ReadLine();
        }
Exemple #2
0
            public void ProcessChange(TextContentChangedEventArgs e)
            {
                foreach (var change in e.Changes)
                {
                    var lineNumber = e.Before.GetLineNumberFromPosition(change.OldPosition);
                    if (lineNumber < 0 || lineNumber >= _lineMap.Count)
                    {
                        GenericExtensions.Debug();
                        return;
                    }

                    _lineMap[lineNumber].IsModified = true;
                    if (change.LineCountDelta >= 0)
                    {
                        if (lineNumber + 1 > _lineMap.Count)
                        {
                            GenericExtensions.Debug();
                            return;
                        }
                        _lineMap.InsertRange(lineNumber + 1, Enumerable.Range(0, change.LineCountDelta).Select(p => new LineStatus(-1)));
                    }
                    else
                    {
                        if (lineNumber + 1 > _lineMap.Count || lineNumber + 1 - change.LineCountDelta > _lineMap.Count)
                        {
                            GenericExtensions.Debug();
                            return;
                        }
                        _lineMap.RemoveRange(lineNumber + 1, -change.LineCountDelta);
                    }
                }
            }
        /// <summary>
        /// Returns a copy of the given <see cref="IEnumerable{T}"/> that is shuffled using the Fisher-Yates algorithm.
        /// </summary>
        /// <typeparam name="T">The type of the items in the <see cref="IEnumerable{T}"/>.</typeparam>
        /// <param name="source">The <see cref="IEnumerable{T}"/> to copy.</param>
        /// <param name="rand">The <see cref="Random"/> to use for number generation. Uses <see cref="TSRandom"/> if <see langword="null"/>.</param>
        public static IEnumerable <T> Shuffle <T>(this IEnumerable <T> source, Random rand = null)
        {
            GenericExtensions.ThrowIfNull(source, nameof(source));

            rand ??= TSRandom.Instance; // Thread-safe random
            return(source.ShuffleIterator(rand));
        }
 public TestClassBuilder() : base(new TestClass())
 {
     DefaultValues = new Dictionary <string, Func <dynamic> >
     {
         { GenericExtensions.GetPropertyName <TestClass, TestClass>(tc => tc.MeToo), () => new TestClass() }
     };
 }
 public EnvironmentalWorldDataBuilder() : base(new EnvironmentalWorldData())
 {
     DefaultValues = new Dictionary <string, Func <dynamic> >
     {
         { GenericExtensions.GetPropertyName <EnvironmentalWorldData, EnvironmentalCellGrid>(wd => wd.Grid), () => new EnvironmentalCellGrid(0) },
         { GenericExtensions.GetPropertyName <EnvironmentalWorldData, SeasonalTime>(wd => wd.Season), () => SeasonalTime.Spring }
     };
 }
Exemple #6
0
        public void Given_Null_Value_When_ThrowIfNullOrDefault_Invoked_Then_It_Should_Throw_Exception()
        {
            var value = (object)null;

            Action action = () => GenericExtensions.ThrowIfNullOrDefault(value);

            action.Should().Throw <ArgumentNullException>();
        }
Exemple #7
0
        public void Given_Value_When_IsNullOrDefault_Invoked_Then_It_Should_Return_False()
        {
            var value = new object();

            var result = GenericExtensions.IsNullOrDefault(value);

            result.Should().BeFalse();
        }
Exemple #8
0
        public void Given_Null_Value_When_IsNullOrDefault_Invoked_Then_It_Should_Return_True()
        {
            var value = (object)null;

            var result = GenericExtensions.IsNullOrDefault(value);

            result.Should().BeTrue();
        }
        public void Given_Null_IsNullOrDefault_ShouldReturn_True()
        {
            var result = GenericExtensions.IsNullOrDefault((object)null);

            result.Should().BeTrue();

            result = GenericExtensions.IsNullOrDefault(default(object));
            result.Should().BeTrue();
        }
        public void Given_Null_ThrowIfNullOrDefault_ShouldThrow_Exception()
        {
            Action action = () => GenericExtensions.ThrowIfNullOrDefault((object)null);

            action.ShouldThrow <ArgumentNullException>();

            action = () => GenericExtensions.ThrowIfNullOrDefault(default(object));
            action.ShouldThrow <ArgumentNullException>();
        }
Exemple #11
0
        private static void Part2()
        {
            int wx = 10, wy = -1, x = 0, y = 0;

            foreach (var line in input)
            {
                char action = line[0];
                int  value  = int.Parse(line.Substring(1));

                switch (action)
                {
                case 'N': wy -= value; break;

                case 'S': wy += value; break;

                case 'E': wx += value; break;

                case 'W': wx -= value; break;

                case 'R':
                case 'L':
                    if ((action == 'R' && value == 90) || (action == 'L' && value == 270))
                    {
                        GenericExtensions.Swap(ref wx, ref wy);
                        wx *= -1;
                        break;
                    }

                    if ((action == 'R' && value == 270) || (action == 'L' && value == 90))
                    {
                        GenericExtensions.Swap(ref wx, ref wy);
                        wy *= -1;
                        break;
                    }

                    if (value == 180)
                    {
                        wx *= -1;
                        wy *= -1;
                        break;
                    }

                    break;

                case 'F':
                    // move to the waypoint the given number of times
                    x += (wx * value);
                    y += (wy * value);
                    break;

                default: break;
                }
            }

            Console.WriteLine($"\nPart 2: End at ({x},{y})");
            Console.WriteLine($"Manhattan Distance: {(x, y).ManhattanDistance((0, 0))}");
        }
Exemple #12
0
        public void Given_Default_Value_When_ThrowIfNullOrDefault_Invoked_Then_It_Should_Return_Result()
        {
            var value = new object();

            var result = GenericExtensions.ThrowIfNullOrDefault(value);

            result
            .Should().NotBeNull()
            .And.BeOfType <object>();
        }
Exemple #13
0
        public static void SkipIfContainsNestedProperties <T, TReturn>(this ModelStateDictionary modelState, Expression <Func <T, TReturn> > expression)
        {
            var propName = GenericExtensions.GetPropertyName(expression);

            modelState
            .Keys
            .Where(x => x.Contains(propName) && !x.Equals(propName))
            .ToList()
            .ForEach(key => modelState[key].Errors.Clear());
        }
Exemple #14
0
 public StandardWorldBuilder() : base(new StandardWorld())
 {
     DefaultValues = new Dictionary <string, Func <dynamic> >
     {
         { GenericExtensions.GetPropertyName <StandardWorld, StandardWorldData>(w => w.Data), () => new StandardWorldData() },
         { GenericExtensions.GetPropertyName <StandardWorld, IFindNeighbours <StandardCell, StandardCellGrid> >(w => w.NeighbourFinder), () => new OpenNeighbourFinder <StandardCell, StandardCellGrid>() },
         { GenericExtensions.GetPropertyName <StandardWorld, ICalculateCell <StandardCell, StandardCellGrid, StandardWorldData> >(w => w.CellCalculator), () => new StandardCellCalculator() },
         { GenericExtensions.GetPropertyName <StandardWorld, IGenerateWorld <StandardCell, StandardCellGrid, StandardWorldData, StandardWorld> >(w => w.WorldGenerator), () => new StandardWorldGenerator() }
     };
 }
        public void GetPropertyName_Field_IsName()
        {
            // arrange
            const string expected = nameof(TestClass.IAmMostDefinitelyNotAProperty);

            // act
            var result = GenericExtensions.GetPropertyName <TestClass, string>(tc => tc.IAmMostDefinitelyNotAProperty);

            // assert
            Assert.AreEqual(expected, result);
        }
 public EnvironmentalWorldBuilder() : base(new EnvironmentalWorld())
 {
     DefaultValues = new Dictionary <string, Func <dynamic> >
     {
         { GenericExtensions.GetPropertyName <EnvironmentalWorld, EnvironmentalWorldData>(w => w.Data), () => new StandardWorldData() },
         { GenericExtensions.GetPropertyName <EnvironmentalWorld, IFindNeighbours <EnvironmentalCell, EnvironmentalCellGrid> >(w => w.NeighbourFinder), () => new OpenNeighbourFinder <EnvironmentalCell, EnvironmentalCellGrid>() },
         { GenericExtensions.GetPropertyName <EnvironmentalWorld, ICalculateCell <EnvironmentalCell, EnvironmentalCellGrid, EnvironmentalWorldData> >(w => w.CellCalculator), () => new EnvironmentalCellCalculator(new Random()) },
         { GenericExtensions.GetPropertyName <EnvironmentalWorld, IGenerateWorld <EnvironmentalCell, EnvironmentalCellGrid, EnvironmentalWorldData, EnvironmentalWorld> >(w => w.WorldGenerator), () => new EnvironmentalWorldGenerator() },
         { GenericExtensions.GetPropertyName <EnvironmentalWorld, ICalculateSeason>(w => w.SeasonCalculator), () => new NoSeasonCalculator() }
     };
 }
        /// <summary>
        /// Returns the given array with the specified object added to the end.
        /// </summary>
        /// <typeparam name="T">The type of objects contained within the array.</typeparam>
        /// <param name="array">The array to add to.</param>
        /// <param name="item">The object to be added to the end of the array. The value can be null for reference types.</param>
        /// <returns></returns>
        public static T[] Add <T>(this T[] array, T item)
        {
            GenericExtensions.ThrowIfNull(array, nameof(array));

            int oldLen = array.Length;

            Array.Resize(ref array, oldLen + 1);
            array[oldLen] = item;

            return(array);
        }
        public void GetPropertyName_ComplexProperty_IsName()
        {
            // arrange
            const string expected = nameof(TestClass.MeToo);

            // act
            var result = GenericExtensions.GetPropertyName <TestClass, TestClass>(tc => tc.MeToo);

            // assert
            Assert.AreEqual(expected, result);
        }
        public void GetPropertyName_PrimitiveProperty_IsName()
        {
            // arrange
            const string expected = nameof(TestClass.IAmAProperty);

            // act
            var result = GenericExtensions.GetPropertyName <TestClass, int>(tc => tc.IAmAProperty);

            // assert
            Assert.AreEqual(expected, result);
        }
Exemple #20
0
        /// <summary>
        /// Indexes the simple properties.
        /// </summary>
        private void IndexSimpleProperties()
        {
            foreach (PropertyInfo propertyInfo in FetchSimpleProperties())
            {
                var csName       = GetPropertyName(propertyInfo.Name, propertyInfo);
                var ciName       = csName.ToUpper();
                var propertyType = PropertyType.SIMPLE;

                if (GenericExtensions.IsIndexedType(propertyInfo.PropertyType))
                {
                    propertyType |= PropertyType.INDEXED;
                }
                if (GenericExtensions.IsMappedType(propertyInfo.PropertyType))
                {
                    propertyType |= PropertyType.MAPPED;
                }

                var prop = new SimpleMagicPropertyInfo(
                    csName,
                    propertyInfo,
                    propertyInfo.GetGetMethod(),
                    propertyInfo.GetSetMethod(),
                    propertyType);

                AddOrUpdateProperty(csName, ciName, prop);
            }

            foreach (MethodInfo methodInfo in FetchSimpleAccessors())
            {
                var csName       = GetAccessorPropertyName(methodInfo);
                var ciName       = csName.ToUpper();
                var setter       = GetSimpleMutator(csName, methodInfo.ReturnType);
                var propertyType = PropertyType.SIMPLE;

                if (GenericExtensions.IsIndexedType(methodInfo.ReturnType))
                {
                    propertyType |= PropertyType.INDEXED;
                }
                if (GenericExtensions.IsMappedType(methodInfo.ReturnType))
                {
                    propertyType |= PropertyType.MAPPED;
                }

                var prop = new SimpleMagicPropertyInfo(
                    csName,
                    methodInfo,
                    methodInfo,
                    setter,
                    propertyType);

                AddOrUpdateProperty(csName, ciName, prop);
            }
        }
 public bool TryOpenCoverageReport(string reportPath)
 {
     try
     {
         _report = GenericExtensions.ParseXml <CoverageSession>(reportPath);
         CoverageUpdated?.Invoke(this, EventArgs.Empty);
         return(true);
     }
     catch
     {
         return(false);
     }
 }
Exemple #22
0
        public void Given_Default_Value_When_IsNullOrDefault_Invoked_Then_It_Should_Return_True()
        {
            var value1 = default(object);

            var result1 = GenericExtensions.IsNullOrDefault(value1);

            result1.Should().BeTrue();

            var value2 = default(int);

            var result2 = GenericExtensions.IsNullOrDefault(value2);

            result2.Should().BeTrue();
        }
Exemple #23
0
        public async Task <bool> UploadExceptionAsync(SerializableException exception, bool force = false)
        {
            if (IsTelemetryEnabled || force)
            {
                GenericExtensions.Debug();
                _editorContext.WriteToLog(Resources.ExceptionEncountered);
                _editorContext.WriteToLog(exception.GetDescription());

                return(await UploadExceptionAsync(exception));
            }
            else
            {
                return(false);
            }
        }
Exemple #24
0
 public Object GetBeanPropInternal(Object @object, String key)
 {
     try
     {
         var result = _fastMethod.Invoke(@object, null);
         return(GenericExtensions.FetchKeyedValue(result, key, null));
     }
     catch (InvalidCastException e)
     {
         throw PropertyUtility.GetMismatchException(_fastMethod.Target, @object, e);
     }
     catch (TargetInvocationException e)
     {
         throw PropertyUtility.GetInvocationTargetException(_fastMethod.Target, e);
     }
 }
        /// <summary>
        /// Returns the given array with the first occurence of the specified object removed.
        /// </summary>
        /// <typeparam name="T">The type of items contained within the array.</typeparam>
        /// <param name="array">The array to remove from.</param>
        /// <param name="item">The object to remove from the array. The value can be null for reference types.</param>
        /// <returns></returns>
        public static T[] Remove <T>(this T[] array, T item)
        {
            GenericExtensions.ThrowIfNull(array, nameof(array));

            int removeIdx = Array.IndexOf(array, item);

            if (removeIdx > array.GetLowerBound(0) - 1)
            {
                T[] newArray = new T[array.Length - 1];

                Array.Copy(array, 0, newArray, 0, removeIdx + 1);
                Array.Copy(array, removeIdx + 1, newArray, removeIdx + 1, array.Length - removeIdx);

                return(newArray);
            }

            return(array);
        }
        /// <summary>
        /// Returns a new, combined array from the given arrays.
        /// </summary>
        /// <typeparam name="T">The type of the array.</typeparam>
        /// <param name="array">The first array to concatenate.</param>
        /// <param name="arrays">The additional arrays to concatenate.</param>
        /// <returns></returns>
        public static T[] Concat <T>(this T[] array, params T[][] arrays)
        {
            GenericExtensions.ThrowIfNull(array, nameof(array));
            GenericExtensions.ThrowIfNull(arrays, nameof(arrays));

            int offset = array.Length;

            Array.Resize(ref array, array.Length + arrays.Sum(a => a.Length));

            foreach (T[] arr in arrays)
            {
                int len = arr.Length;
                Array.Copy(arr, 0, array, offset, len);
                offset += len;
            }

            return(array);
        }
Exemple #27
0
        /// <summary>
        ///     Create a fragment event type.
        /// </summary>
        /// <param name="propertyType">property return type</param>
        /// <param name="genericType">property generic type parameter, or null if none</param>
        /// <param name="beanEventTypeFactory">for event types</param>
        /// <param name="publicFields">indicator whether classes are public-field-property-accessible</param>
        /// <returns>fragment type</returns>
        public static FragmentEventType CreateNativeFragmentType(
            Type propertyType,
            Type genericType,
            BeanEventTypeFactory beanEventTypeFactory,
            bool publicFields)
        {
            var isIndexed = false;

            if (propertyType.IsArray) {
                isIndexed = true;
                propertyType = propertyType.GetElementType();
            }
            else if (propertyType.IsGenericDictionary()) {
                // Ignore this - technically enumerable
            }
            else if (propertyType.IsGenericEnumerable()) {
                propertyType = GenericExtensions
                    .FindGenericEnumerationInterface(propertyType)
                    .GetGenericArguments()[0];
                isIndexed = true;

#if false
                if (genericType == null) {
                    return null;
                }

                propertyType = genericType;
#endif
            }

            if (!propertyType.IsFragmentableType()) {
                return null;
            }

            EventType type = beanEventTypeFactory.GetCreateBeanType(propertyType, publicFields);
            return new FragmentEventType(type, isIndexed, true);
        }
 public void WhenSourceIsNull_ThenThrowException()
 {
     Assert.Throws <ArgumentNullException>(() => GenericExtensions.InvokeMethod(null as object, "PrivateMethodReturnVoid"));
 }
Exemple #29
0
        public static CodegenExpression CastSafeFromObjectType(
            Type targetType,
            CodegenExpression value)
        {
            if (targetType == null) {
                return ConstantNull();
            }

            if (targetType == typeof(object)) {
                return value;
            }

            if (value is CodegenExpressionConstantNull) {
                return value;
            }
            
            if ((value is CodegenExpressionConstant codegenExpressionConstant) &&
                       (codegenExpressionConstant.IsNull)) {
                return value;
            }

            if (targetType == typeof(void)) {
                throw new ArgumentException("Invalid void target type for cast");
            }

            if (targetType == typeof(int)) {
                return ExprDotMethod(value, "AsInt32");
            }
            else if (targetType == typeof(int?)) {
                return ExprDotMethod(value, "AsBoxedInt32");
            }
            else if (targetType == typeof(long)) {
                return ExprDotMethod(value, "AsInt64");
            }
            else if (targetType == typeof(long?)) {
                return ExprDotMethod(value, "AsBoxedInt64");
            }
            else if (targetType == typeof(short)) {
                return ExprDotMethod(value, "AsInt16");
            }
            else if (targetType == typeof(short?)) {
                return ExprDotMethod(value, "AsBoxedInt16");
            }
            else if (targetType == typeof(byte)) {
                return ExprDotMethod(value, "AsByte");
            }
            else if (targetType == typeof(byte?)) {
                return ExprDotMethod(value, "AsBoxedByte");
            }
            else if (targetType == typeof(decimal)) {
                return ExprDotMethod(value, "AsDecimal");
            }
            else if (targetType == typeof(decimal?)) {
                return ExprDotMethod(value, "AsBoxedDecimal");
            }
            else if (targetType == typeof(double)) {
                return ExprDotMethod(value, "AsDouble");
            }
            else if (targetType == typeof(double?)) {
                return ExprDotMethod(value, "AsBoxedDouble");
            }
            else if (targetType == typeof(float)) {
                return ExprDotMethod(value, "AsFloat");
            }
            else if (targetType == typeof(float?)) {
                return ExprDotMethod(value, "AsBoxedFloat");
            }
            else if (targetType == typeof(bool)) {
                return ExprDotMethod(value, "AsBoolean");
            }
            else if (targetType == typeof(bool?)) {
                return ExprDotMethod(value, "AsBoxedBoolean");
            }
            else if (targetType == typeof(DateTime)) {
                return ExprDotMethod(value, "AsDateTime");
            }
            else if (targetType == typeof(DateTime?)) {
                return ExprDotMethod(value, "AsBoxedDateTime");
            }
            else if (targetType == typeof(DateTimeOffset)) {
                return ExprDotMethod(value, "AsDateTimeOffset");
            }
            else if (targetType == typeof(DateTimeOffset?)) {
                return ExprDotMethod(value, "AsBoxedDateTimeOffset");
            }
            else if (targetType == typeof(FlexCollection)) {
                return StaticMethod(typeof(FlexCollection), "Of", value);
            }
            else if (targetType == typeof(IDictionary<string, object>)) {
                return StaticMethod(typeof(CompatExtensions), "AsStringDictionary", value);
            }
            else if (targetType == typeof(IDictionary<object, object>)) {
                return StaticMethod(typeof(CompatExtensions), "AsObjectDictionary", value);
            }
            else if (targetType.IsGenericDictionary()) {
                return Cast(targetType, value);
            }
            else if (targetType.IsArray()) {
                var elementType = targetType.GetElementType();
                return StaticMethod(typeof(CompatExtensions), "UnwrapIntoArray", new[] {elementType}, value);
            }
            else if (targetType.IsGenericList()) {
                var elementType = GenericExtensions.GetCollectionItemType(targetType);
                return StaticMethod(typeof(CompatExtensions), "UnwrapIntoList", new [] {elementType}, value);
            }
            else if (targetType.IsGenericSet()) {
                var elementType = GenericExtensions.GetCollectionItemType(targetType);
                return StaticMethod(typeof(CompatExtensions), "UnwrapIntoSet", new [] {elementType}, value);
            }
            else if (targetType == typeof(ICollection<object>)) {
                return StaticMethod(typeof(TypeHelper), "AsObjectCollection", value);
            }
            else if (targetType.IsGenericCollection()) {
                var elementType = GenericExtensions.GetCollectionItemType(targetType);
                return Unwrap(elementType, value);
            }

            return Cast(targetType, value);
        }
Exemple #30
0
        private JsonSerializationForgePair GetForgePair(
            Type type,
            IDictionary <Type, JsonApplicationClassSerializationDesc> classSerializationDescs)
        {
            type = type.GetBoxedType();

            // Search for a pre-built pair.  Please change this logic so that built-in types are
            // done in pairs.

            if (_forgePairs.TryGetValue(type, out var forgePair))
            {
                return(forgePair);
            }

            // The type was not found as a pre-built pair.  Examine the data type and attempt to create
            // the right pair of forges for this type.

            if (type.IsEnum)
            {
                return(new JsonSerializationForgePair(
                           JsonSerializerForgeStringWithToString.INSTANCE,
                           new JsonDeserializerForgeEnum(type)));
            }

            if (type.IsArray)
            {
                var componentType      = type.GetElementType();
                var componentForgePair = GetForgePair(componentType, classSerializationDescs);
                return(new JsonSerializationForgePair(
                           new JsonSerializerForgeArray(componentForgePair.SerializerForge, componentType),
                           new JsonDeserializerForgeArray(componentForgePair.DeserializerForge, componentType)));
            }

            if (type.IsGenericStringDictionary())
            {
                var valueType          = type.GetDictionaryValueType();
                var valueTypeForgePair = GetForgePair(valueType, classSerializationDescs);

                return(new JsonSerializationForgePair(
                           new JsonSerializerForgePropertyMap(
                               valueTypeForgePair.SerializerForge,
                               valueType),
                           new JsonDeserializerForgePropertyMap(
                               valueTypeForgePair.DeserializerForge,
                               valueType)));
            }

            if (type.IsGenericList() || type.IsGenericEnumerable())
            {
                var genericType = GenericExtensions.GetComponentType(type);
                if (genericType == null)
                {
                    return(null);
                }

                var genericForgePair = GetForgePair(genericType, classSerializationDescs);
                return(new JsonSerializationForgePair(
                           new JsonSerializerForgeArray(genericForgePair.SerializerForge, genericType),
                           new JsonDeserializerForgeArray(genericForgePair.DeserializerForge, genericType)));
            }

            if (classSerializationDescs.TryGetValue(type, out JsonApplicationClassSerializationDesc existingDesc))
            {
                return(new JsonSerializationForgePair(
                           new JsonSerializerForgeByClassName(existingDesc.SerializerClassName),
                           new JsonDeserializerForgeByClassName(existingDesc.DeserializerClassName)));
            }

            //throw new ArgumentException($"unable to determine forge pair for type {type.CleanName()}");

            return(null);
        }