public StackerBlockViewModel(BlockBase block, Random rand)
        {
            Id    = rand.Next();
            Block = block;
            OnPropertyChanged("Label");
            OnPropertyChanged("Color");

            // Define mapping scheme
            var ts = new TypeSwitch()
                     .Case((BlockParse x) => Page          = new PageBlockParse(x))
                     .Case((BlockKeycheck x) => Page       = new PageBlockKeycheck(x))
                     .Case((BlockRequest x) => Page        = new PageBlockRequest(x))
                     .Case((BlockRecaptcha x) => Page      = new PageBlockRecaptcha(x))
                     .Case((BlockFunction x) => Page       = new PageBlockFunction(x))
                     .Case((BlockImageCaptcha x) => Page   = new PageBlockCaptcha(x))
                     .Case((BlockBypassCF x) => Page       = new PageBlockBypassCF(x))
                     .Case((BlockUtility x) => Page        = new PageBlockUtility(x))
                     .Case((BlockLSCode x) => Page         = new PageBlockLSCode(x))
                     .Case((BlockTCP x) => Page            = new PageBlockTCP(x))
                     .Case((SBlockNavigate x) => Page      = new PageSBlockNavigate(x))
                     .Case((SBlockBrowserAction x) => Page = new PageSBlockBrowserAction(x))
                     .Case((SBlockElementAction x) => Page = new PageSBlockElementAction(x))
                     .Case((SBlockExecuteJS x) => Page     = new PageSBlockExecuteJS(x));

            ts.Switch(Block);
        }
Пример #2
0
        /// <summary>
        /// Updates the UI display by authority.
        /// </summary>
        private void UpdateUIDisplayByAuthority()
        {
            BindingFlags flag = BindingFlags.Instance | BindingFlags.NonPublic;

            MemberInfo[] memberInfos = typeof(BCMainForm).GetMembers(flag);

            var typeSwitch = new TypeSwitch()
                             .Case((System.Windows.Forms.ToolStripMenuItem tsm, bool tf) => { tsm.Enabled = tf; })
                             .Case((System.Windows.Forms.ComboBox cb, bool tf) => { cb.Enabled = tf; });

            foreach (MemberInfo memberInfo in memberInfos)
            {
                Attribute AuthorityCheck = memberInfo.GetCustomAttribute(typeof(AuthorityCheck));
                if (AuthorityCheck != null)
                {
                    string    attribute_FUNName = ((AuthorityCheck)AuthorityCheck).FUNCode;
                    FieldInfo info = (FieldInfo)memberInfo;
                    if (bcApp.SCApplication.UserBLL.checkUserAuthority(bcApp.LoginUserID, attribute_FUNName))
                    {
                        typeSwitch.Switch(info.GetValue(this), true);
                    }
                    else
                    {
                        typeSwitch.Switch(info.GetValue(this), false);
                    }
                }
            }
        }
Пример #3
0
        private double typeChangeAddition(TaikoHitObjectDifficulty previousHitObject)
        {
            // If we don't have the same hit type, trigger a type change!
            if (previousHitObject.isRim != isRim)
            {
                lastTypeSwitchEven = previousHitObject.sameTypeSince % 2 == 0 ? TypeSwitch.Even : TypeSwitch.Odd;

                // We only want a bonus if the parity of the type switch changes!
                switch (previousHitObject.lastTypeSwitchEven)
                {
                case TypeSwitch.Even:
                    if (lastTypeSwitchEven == TypeSwitch.Odd)
                    {
                        return(type_change_bonus);
                    }
                    break;

                case TypeSwitch.Odd:
                    if (lastTypeSwitchEven == TypeSwitch.Even)
                    {
                        return(type_change_bonus);
                    }
                    break;
                }
            }
            // No type change? Increment counter and keep track of last type switch
            else
            {
                lastTypeSwitchEven = previousHitObject.lastTypeSwitchEven;
                sameTypeSince      = previousHitObject.sameTypeSince + 1;
            }

            return(0);
        }
        public static void Write(this MenuSuiteNode node, CSideWriter writer)
        {
            writer.Write("{ ");
            writer.Write(node.NodeTypeAsString());
            writer.Write(";");
            writer.Write("[{0}] ", node.ID.ToString("B").ToUpper());
            writer.Write(";");

            writer.Indent(writer.Column);

            IEnumerable <Property> properties = null;

            TypeSwitch.Do(
                node,
                TypeSwitch.Case <RootNode>(n => properties  = n.Properties),
                TypeSwitch.Case <MenuNode>(n => properties  = n.Properties),
                TypeSwitch.Case <GroupNode>(n => properties = n.Properties),
                TypeSwitch.Case <ItemNode>(n => properties  = n.Properties),
                TypeSwitch.Case <DeltaNode>(n => properties = n.Properties)
                );

            var relevantProperties = properties.Where(p => p.HasValue);

            relevantProperties.Write(PropertiesStyle.Field, writer);

            writer.Unindent();
            writer.WriteLine("}");
        }
        public virtual ExceptionModel Convert(Exception exception)
        {
            ExceptionModel model = null;

            TypeSwitch.On(exception)
            .Case <HttpStatusException>(ex =>
            {
                exception = ex.InnerException;
                model     = Convert(exception);
            })
            .Case <ArgumentException>(ex => model = new ArgumentExceptionModel
            {
                ParamName = ex.ParamName,
            })
            .Case <NotSupportedException>(ex => model     = new NotSupportedExceptionModel())
            .Case <InvalidOperationException>(ex => model = new InvalidOperationExceptionModel())
            .Default(() => model = new ExceptionModel
            {
                Message = string.Format("[No exception serializer found for {0}].{1}", exception.GetType(), Environment.NewLine)
            });

            model.Message    = exception.Message;
            model.StackTrace = exception.StackTrace;
            return(model);
        }
        public Color GetBlockColor()
        {
            Color color = Colors.Black;

            // Define mapping scheme
            var ts = new TypeSwitch()
                     .Case((BlockParse x) => color          = Colors.Gold)
                     .Case((BlockKeycheck x) => color       = Colors.DodgerBlue)
                     .Case((BlockRequest x) => color        = Colors.LimeGreen)
                     .Case((BlockRecaptcha x) => color      = Colors.Turquoise)
                     .Case((BlockFunction x) => color       = Colors.YellowGreen)
                     .Case((BlockImageCaptcha x) => color   = Colors.DarkOrange)
                     .Case((BlockBypassCF x) => color       = Colors.DarkSalmon)
                     .Case((BlockUtility x) => color        = Colors.Wheat)
                     .Case((BlockLSCode x) => color         = Colors.White)
                     .Case((BlockTCP x) => color            = Colors.MediumPurple)
                     .Case((SBlockNavigate x) => color      = Colors.RoyalBlue)
                     .Case((SBlockBrowserAction x) => color = Colors.Green)
                     .Case((SBlockElementAction x) => color = Colors.Firebrick)
                     .Case((SBlockExecuteJS x) => color     = Colors.Indigo);

            // Execute type check to set color data
            ts.Switch(Block);

            return(color);
        }
Пример #7
0
        public Message Write(NetOutgoingMessage message, bool isInherited = false)
        {
            if (!isInherited)
            {
                message.Write(this.Type.ToString());
            }

            foreach (var key in this.keys)
            {
                var nv = this.Fields[key];

                var ts = new TypeSwitch()
                         .Case((int x) => message.Write(x))
                         .Case((float x) => message.Write(x))
                         .Case((byte x) => message.Write(x))
                         .Case((string x) => message.Write(x));

                ts.Switch(nv.Value);
            }

            foreach (var inherited in this.inheritedMessages)
            {
                inherited.Write(message, true);
            }

            return(this);
        }
Пример #8
0
        private static void Traverse(IGenericObject genericObject, IApp app)
        {
            if (genericObject == null)
            {
                return;
            }

            // Check if the object is an extensions of a master object.
            if (genericObject.Properties.ExtendsObject != null)
            {
                var masterObject = (IMasterObject)genericObject.Properties.ExtendsObject;
                TextHelper.WriteLine(4, "MasterObject version " + masterObject.Properties.MasterVersion);
            }

            // The information to print for each object depends on the type of the object. The TypeSwitch class can be used
            // for this purpose. For extensions of master objects, property values will automatically be retrieved from the
            // master object.
            TypeSwitch.Do(genericObject,
                          TypeSwitch.Case <Table>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Barchart>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Linechart>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Piechart>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Scatterplot>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Treemap>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Gauge>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Combochart>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <TextImage>(o => TextHelper.Print(o.GetType().Name, o.Properties.HyperCubeDef, o.Title, app)),
                          TypeSwitch.Case <Listbox>(o => TextHelper.Print(o.GetType().Name, o.Title)),
                          TypeSwitch.Case <Filterpane>(o => TextHelper.Print(o.GetType().Name, o.Title)),
                          TypeSwitch.Case <Kpi>(o => TextHelper.Print(o.GetType().Name, o.Title)),
                          TypeSwitch.Case <Pivottable>(o => TextHelper.Print(o.GetType().Name, o.Title)),
                          TypeSwitch.Case <Map>(o => TextHelper.Print(o.GetType().Name, o.Title)),
                          TypeSwitch.Default(() => TextHelper.WriteLine(4, "Unknown type: " + genericObject.GetType().FullName))
                          );
        }
Пример #9
0
        public override string ConvertTypeToSQLType(Type type, bool preferUnicode = true, string maxLen = "4000")
        {
            string retval = null;

            TypeSwitch.ForType(type,
                               TypeSwitch.Case <char>(() => retval     = preferUnicode ? "CHAR(1) CHARACTER SET ISO8859_1" : "CHAR(1) CHARACTER SET ASCII"),
                               TypeSwitch.Case <string>(() => retval   = (preferUnicode ? "VARCHAR({0}) CHARACTER SET ISO8859_1" : "VARCHAR({0}) CHARACTER SET ASCII").FormatWith(maxLen)),
                               TypeSwitch.Case <byte>(() => retval     = "SMALLINT"),
                               TypeSwitch.Case <bool>(() => retval     = "CHAR(1)"),
                               TypeSwitch.Case <Guid>(() => retval     = "CHAR(16) CHARACTER SET OCTETS"),
                               TypeSwitch.Case <short>(() => retval    = "SMALLINT"),
                               TypeSwitch.Case <int>(() => retval      = "INTEGER"),
                               TypeSwitch.Case <long>(() => retval     = "BIGINT"),
                               TypeSwitch.Case <decimal>(() => retval  = "DECIMAL(18,4)"),
                               TypeSwitch.Case <float>(() => retval    = "FLOAT"),
                               TypeSwitch.Case <double>(() => retval   = "DOUBLE"),
                               TypeSwitch.Case <DateTime>(() => retval = "TIMESTAMP"),
                               TypeSwitch.Case <Byte[]>(() => retval   = "BLOB")
                               );


            if (retval == null)
            {
                throw new SoftwareException("Unable to convert type '{0}' to sql type.", type);
            }

            return(retval);
        }
Пример #10
0
        public Message Read(NetIncomingMessage message)
        {
            // why in the name of actual f**k do I need to reset the
            // position of an incoming message stream manually.....?
            //message.Position = 0;
            this.SenderInfo = new SenderInfo
            {
                Connection = message.SenderConnection
            };

            foreach (var key in this.keys)
            {
                var nv = this.Fields[key];

                var ts = new TypeSwitch()
                         .Case((int x) => this.SetField(key, message.ReadInt32()))
                         .Case((float x) => this.SetField(key, message.ReadSingle()))
                         .Case((byte x) => this.SetField(key, message.ReadByte()))
                         .Case((string x) => this.SetField(key, message.ReadString()));

                ts.Switch(nv.Type);
            }

            foreach (var inherited in this.inheritedMessages)
            {
                inherited.Read(message);
            }

            return(this);
        }
Пример #11
0
 public override ISQLBuilder Literal(object value)
 {
     if (value != null)
     {
         TypeSwitch.Do(
             value,
             TypeSwitch.Case <byte[]>(x => Emit("X'").Emit(x.ToHexString(true)).Emit("'")),
             TypeSwitch.Case <Guid>(x => this.Literal(x.ToByteArray())),
             TypeSwitch.Case <Guid?>(x => {
             if (x.HasValue)
             {
                 this.Literal(x.Value.ToByteArray());
             }
             else
             {
                 base.Literal(null);
             }
         }),
             TypeSwitch.Default(() => base.Literal(value))
             );
     }
     else
     {
         base.Literal(null);
     }
     return(this);
 }
Пример #12
0
        public virtual string ConvertTypeToSQLType(Type type, bool preferUnicode = true, string maxLen = "4000")
        {
            string retval = null;

            TypeSwitch.ForType(type,
                               TypeSwitch.Case <Char>(() => retval     = preferUnicode ? "NCHAR" : "CHAR"),
                               TypeSwitch.Case <String>(() => retval   = preferUnicode ? "NVARCHAR(MAX)" : "VARCHAR(MAX)"),
                               TypeSwitch.Case <Byte>(() => retval     = "TINYINT"),
                               TypeSwitch.Case <Boolean>(() => retval  = "BIT"),
                               TypeSwitch.Case <Guid>(() => retval     = "UNIQUEIDENTIFIER"),
                               TypeSwitch.Case <Int16>(() => retval    = "SMALLINT"),
                               TypeSwitch.Case <Int32>(() => retval    = "INT"),
                               TypeSwitch.Case <Int64>(() => retval    = "BIGINT"),
                               TypeSwitch.Case <Decimal>(() => retval  = "MONEY"),
                               TypeSwitch.Case <Single>(() => retval   = "REAL"),
                               TypeSwitch.Case <Double>(() => retval   = "FLOAT"),
                               TypeSwitch.Case <DateTime>(() => retval = "DATETIME")
                               );


            if (retval == null)
            {
                throw new SoftwareException("Unable to convert type '{0}' to sql type.", type);
            }

            return(retval);
        }
Пример #13
0
        private void RegisterMultipleComponentsRegistration(ComponentRegistryDefinition componentRegistryDefinition, ComponentRegistryDefinition.ComponentSetRegistrationDefinition componentSetRegistrationDefinition)
        {
            if (componentSetRegistrationDefinition.RegistrationsDefinition == null)
            {
                return;
            }

            foreach (var registration in componentSetRegistrationDefinition.RegistrationsDefinition)
            {
                TypeSwitch.Do(registration,
                              TypeSwitch.Case <ComponentRegistryDefinition.ComponentRegistrationDefinition>(componentRegistration => {
                    componentRegistration.Interface = componentSetRegistrationDefinition.Interface;
                    RegisterMutipleComponentComponentRegistration(
                        componentRegistryDefinition,
                        componentRegistration
                        );
                }),
                              TypeSwitch.Case <ComponentRegistryDefinition.ProxyInterfaceRegistrationDefinition>(proxyRegistration => {
                    proxyRegistration.Interface = componentSetRegistrationDefinition.Interface;
                    RegisterMultipleComponentProxyRegistration(
                        componentRegistryDefinition,
                        proxyRegistration
                        );
                }),
                              TypeSwitch.Default(() => { throw new NotSupportedException(registration.GetType().FullName); })
                              );
            }
        }
Пример #14
0
        public void TypeSwitch_Do_WhenCaseActionNull_ExpectCallAction_Success()
        {
            Action action = null;
            var    case1  = TypeSwitch.Case <object>(action);

            case1.Action.Invoke(null);
        }
Пример #15
0
        public override string ConvertTypeToSQLType(Type type, bool preferUnicode = true, string maxLen = "MAX")
        {
            string retval = null;

            TypeSwitch.ForType(type,
                               TypeSwitch.Case <char>(() => retval           = preferUnicode ? "NCHAR" : "CHAR"),
                               TypeSwitch.Case <string>(() => retval         = (preferUnicode ? "NVARCHAR({0})" : "VARCHAR({0})").FormatWith(maxLen)),
                               TypeSwitch.Case <byte>(() => retval           = "TINYINT"),
                               TypeSwitch.Case <bool>(() => retval           = "BIT"),
                               TypeSwitch.Case <Guid>(() => retval           = "UNIQUEIDENTIFIER"),
                               TypeSwitch.Case <short>(() => retval          = "SMALLINT"),
                               TypeSwitch.Case <int>(() => retval            = "INT"),
                               TypeSwitch.Case <long>(() => retval           = "BIGINT"),
                               TypeSwitch.Case <decimal>(() => retval        = "MONEY"),
                               TypeSwitch.Case <float>(() => retval          = "REAL"),
                               TypeSwitch.Case <double>(() => retval         = "FLOAT"),
                               TypeSwitch.Case <DateTime>(() => retval       = "DATETIME"),
                               TypeSwitch.Case <DateTimeOffset>(() => retval = "DATETIMEOFFSET"),
                               TypeSwitch.Case <Byte[]>(() => retval         = "VARBINARY(" + (maxLen ?? "MAX") + ")")
                               );


            if (retval == null)
            {
                throw new SoftwareException("Unable to convert type '{0}' to sql type.", type);
            }

            return(retval);
        }
Пример #16
0
        public static string Beautify(object obj)
        {
            var val = string.Empty;

            if (obj != null)
            {
                TypeSwitch.Do(obj,
                              TypeSwitch.Case <string>(s => val     = s),
                              TypeSwitch.Case <DateTime?>(dt => val = string.Format("{0:yyyy-MM-dd HH:mm:ss}", dt)),
                              TypeSwitch.Case <DateTime>(dt => val  = string.Format("{0:yyyy-MM-dd HH:mm:ss}", dt)),
                              //TypeSwitch.Case<byte[]>(b => val =  BitcoinProtocolHelper.BytesToString(b)),
                              TypeSwitch.Case <decimal?>(d => val = string.Format("{0:0.#############################}", d)),
                              TypeSwitch.Case <decimal>(d => val  = string.Format("{0:0.#############################}", d)),
                              TypeSwitch.Case <double?>(d => val  = string.Format("{0:0.#############################}", d)),
                              TypeSwitch.Case <double>(d => val   = string.Format("{0:0.#############################}", d)),
                              TypeSwitch.Case <float?>(d => val   = string.Format("{0:0.#############################}", d)),
                              TypeSwitch.Case <float>(d => val    = string.Format("{0:0.#############################}", d)),
                              TypeSwitch.Default(() => val        = obj.ToString())
                              );
            }
            else
            {
                val = string.Empty;
            }
            return(val);
        }
Пример #17
0
        /// <summary>
        /// Sets the uniform value.
        /// </summary>
        /// <param name="uniformId">Uniform identifier.</param>
        /// <param name="value">Value.</param>
        void SetUniformValue(int uniformId, object value)
        {
            // Check if another program is loaded
            if (CurrentProgramId != 0 && CurrentProgramId != programId)
            {
                // Throw an exception
                const string message = "Cannot set uniform {0} on program {1} because the current program is {2}.";
                this.Throw(message, uniformId, programId, CurrentProgramId);
            }

            // Set the uniform
            using (UseProgram()) {
                TypeSwitch.On(value)
                .Case((int x) => GL.Uniform1(uniformId, x))
                .Case((uint x) => GL.Uniform1(uniformId, x))
                .Case((float x) => GL.Uniform1(uniformId, x))
                .Case((Vector2 x) => GL.Uniform2(uniformId, x))
                .Case((Vector3 x) => GL.Uniform3(uniformId, x))
                .Case((Vector4 x) => GL.Uniform4(uniformId, x))
                .Case((Quaternion x) => GL.Uniform4(uniformId, x))
                .Case((Color4 x) => GL.Uniform4(uniformId, x))
                .Case((int[] x) => GL.Uniform1(uniformId, x.Length, x))
                .Case((uint[] x) => GL.Uniform1(uniformId, x.Length, x))
                .Case((float[] x) => GL.Uniform1(uniformId, x.Length, x))
                .Case((Matrix4 x) => GL.UniformMatrix4(uniformId, false, ref x))
                .Case((Color x) => GL.Uniform4(uniformId, x.R, x.G, x.B, x.A))
                .Default(x => this.Throw("GlUniform type {0} is not (yet?) implemented.", value.GetType().FullName));
            }
        }
Пример #18
0
        public void SetUniformValue(int uniformId, object value)
        {
            if (CurrentProgramId != 0 && CurrentProgramId != ProgramId)
            {
                throw new System.Exception("An other program is already loaded!");
            }

            using (UseProgram())
            {
                TypeSwitch.On(value)
                .Case((int x) => GL.Uniform1(uniformId, x))
                .Case((uint x) => GL.Uniform1(uniformId, x))
                .Case((float x) => GL.Uniform1(uniformId, x))
                .Case((Vector2 x) => GL.Uniform2(uniformId, x))
                .Case((Vector3 x) => GL.Uniform3(uniformId, x))
                .Case((Vector4 x) => GL.Uniform4(uniformId, x))
                .Case((Quaternion x) => GL.Uniform4(uniformId, x))
                .Case((Color4 x) => GL.Uniform4(uniformId, x))
                .Case((int[] x) => GL.Uniform1(uniformId, x.Length, x))
                .Case((uint[] x) => GL.Uniform1(uniformId, x.Length, x))
                .Case((float[] x) => GL.Uniform1(uniformId, x.Length, x))
                .Case((Matrix4 x) => GL.UniformMatrix4(uniformId, false, ref x))
                .Case((Color x) => GL.Uniform4(uniformId, x.R, x.G, x.B, x.A))
                .Default(x => Throw("GLUniform type {0} is not is not implemented.", value.GetType()));
            }
        }
Пример #19
0
 private void ValidateRequestSettings(IRequestSettings <T> config, IContactRequest typeRequest)
 {
     TypeSwitch.Do(
         config.mailingProvider,
         TypeSwitch.Case <IIContactRequest>(() => { IContactValidateRequestSettings(config, typeRequest); }),
         TypeSwitch.Default(() => { }));
 }
Пример #20
0
        public void TypeSwitch_Default_ActionNull_Success()
        {
            var result = TypeSwitch.Default(null);

            result.Action.Invoke(null);
            Assert.AreEqual(null, result.Target);
            Assert.IsTrue(result.IsDefault);
        }
Пример #21
0
 public void SomeDlsMethod()
 {
     TypeSwitch.Do(someDslObject,
                   TypeSwitch.Case <DslObjectA>(someDslObjectA => ...),
                   TypeSwitch.Case <DslObjectB>(someDslObjectB => ...),
                   TypeSwitch.Default(() => ...)
                   );
 }
Пример #22
0
        public void TypeSwitch_Case_Generic_ActionIsNotNull_Success()
        {
            var result = TypeSwitch.Case(delegate(object o) { });

            result.Action.Invoke(null);
            Assert.AreEqual(typeof(object), result.Target);
            Assert.IsFalse(result.IsDefault);
        }
Пример #23
0
        public void TypeSwitch_Do_WhenNullCases_ExpectException()
        {
            var case1 = new TypeSwitch.CaseInfo {
                IsDefault = false, Action = null, Target = typeof(object)
            };

            TypeSwitch.Do(null, case1);
        }
        /// <summary>
        ///     Az adott "Target Object"-en végrehajt egy állapot visszaállítást. Tehát az objektum
        ///     új értéke, az előzőleg megadott érték lesz.
        ///     (Például: CurrentValue = 20; OldValue = 15; -> Undo -> CurrentValue = 15; OldValue = )
        /// </summary>
        /// <param name="eventType">
        ///     Az az esemény típus amely meghatározza, hogy a TargetObject-en milyen típusú végrehajtott
        ///     eseményeket kell kiválasztani, majd meghatározza, hogy melyik esemény "Parancsot" kell
        ///     visszavonni.
        /// </param>
        public void UndoLast(object eventType)
        {
            List <object> currentEventTypeList = _personEventBrokerHelpers.FillCurrentEventTypeList(eventType.GetType(), this.AllEvents);

            TypeSwitch.Do(eventType,
                          TypeSwitch.Case <AgeChangedEvent>(() => _personUndoMethods.UndoLastAgeChanged(currentEventTypeList, AllEvents, this)),
                          TypeSwitch.Case <NameChangedEvent>(() => _personUndoMethods.UndoLastNameChanged(currentEventTypeList, AllEvents, this)));
        }
        protected override void OnReceive(AbstractMessage message)
        {
            TypeSwitch.On(message)
            .Case((ClearMessage clearMessage) =>
            {
                // Reset partition and send sync message
                clear();
                clearMessage.Sender.SendMe(new EstimateRefinedMessage(this));
            })
            .Case((RefineMessage refineMessage) =>
            {
                // Perform local refine step
                refine();
                refineMessage.Sender.SendMe(new EstimateRefinedMessage(this));
            })
            .Case((CountMessage countMessage) =>
            {
                var blocks = new HashSet <int>();
                foreach (var node in ownerInverted[this])
                {
                    if (!blocks.Contains(partition[node]))
                    {
                        blocks.Add(partition[node]);
                    }
                }

                countMessage.Sender.SendMe(new CountedMessage(this, blocks));
            })
            .Case((ShareMessage shareMessage) =>
            {
                // Share changes
                foreach (var worker in ownerInverted.Keys)
                {
                    if (worker != this)
                    {
                        var changedNodesOfInterest = partition.Where(kvp => interestedIn[worker].Contains(kvp.Key) && changed[kvp.Key]);

                        if (changedNodesOfInterest.Any())
                        {
                            worker.SendMe(new UpdatePartitionMessage <TNode>(this, changedNodesOfInterest));
                        }
                    }
                }

                shareMessage.Sender.SendMe(new SharedMessage(this));
            })
            .Case((UpdatePartitionMessage <TNode> updatePartitionMessage) =>
            {
                foreach (var change in updatePartitionMessage.Changes)
                {
                    partition[change.Key] = change.Value;
                }
            })
            .Case((SegmentRequestMessage segmentRequestMessage) =>
            {
                segmentRequestMessage.Sender.SendMe(new SegmentResponseMessage <TNode>(this, partition.Where(kvp => owner[kvp.Key] == this)));
            });
        }
Пример #26
0
        public void ExecutesFallbackActionAssignedInConstructorWhenExecutedTypeNotFoundOrNull()
        {
            var swithWithFallback = new TypeSwitch<int>( () => 0 );
            swithWithFallback.Set( typeof(int), () => 1 );

            var result = swithWithFallback.Execute( typeof(bool) );

            Assert.AreEqual( 0, result );
        }
Пример #27
0
        public void TypeSwitch_Do_WhenCaseGeneric_ExpectNotDefaultAndTargetEqualsObject()
        {
            //------------Execute Test---------------------------
            var result = TypeSwitch.Case <object>(delegate(object o) { });

            //------------Assert Results-------------------------
            Assert.AreEqual(typeof(object), result.Target);
            Assert.IsFalse(result.IsDefault);
        }
Пример #28
0
        public void TypeSwitch_Do_WhenDefault_ExpectDefaultAndTargetNull()
        {
            //------------Execute Test---------------------------
            var result = TypeSwitch.Default(delegate() { });

            //------------Assert Results-------------------------
            Assert.AreEqual(null, result.Target);
            Assert.IsTrue(result.IsDefault);
        }
Пример #29
0
        public static IDev2TOFn CreateNewDTO(IDev2TOFn dto, int index = 0, bool inserted = false, string initializeWith = "")
        {
            IDev2TOFn toReturn = null;

            TypeSwitch.Do(dto,
                          // ReSharper disable ImplicitlyCapturedClosure
                          TypeSwitch.Case <ActivityDTO>(x => toReturn = new ActivityDTO(initializeWith, "", index, inserted)),
                          // ReSharper restore ImplicitlyCapturedClosure
                          TypeSwitch.Case <DataSplitDTO>(x =>
            {
                var dataSplitDto = dto as DataSplitDTO;
                if (dataSplitDto != null)
                {
                    toReturn = new DataSplitDTO(initializeWith, dataSplitDto.SplitType, dataSplitDto.At, index, false, inserted);
                }
            }),
                          TypeSwitch.Case <DataMergeDTO>(x =>
            {
                var dataMergeDto = dto as DataMergeDTO;
                if (dataMergeDto != null)
                {
                    toReturn = new DataMergeDTO(initializeWith, dataMergeDto.MergeType, dataMergeDto.At, index, dataMergeDto.Padding, dataMergeDto.Alignment, inserted);
                }
            }),
                          TypeSwitch.Case <CaseConvertTO>(x =>
            {
                var caseConvertTO = dto as CaseConvertTO;
                if (caseConvertTO != null)
                {
                    toReturn = CaseConverterFactory.CreateCaseConverterTO(initializeWith, caseConvertTO.ConvertType, caseConvertTO.Result, index);
                }
            }),
                          TypeSwitch.Case <BaseConvertTO>(x =>
            {
                var baseConvertTO = dto as BaseConvertTO;
                if (baseConvertTO != null)
                {
                    toReturn = new BaseConvertTO(initializeWith, baseConvertTO.FromType, baseConvertTO.ToType, baseConvertTO.ToExpression, index, inserted);
                }
            }),
                          // ReSharper disable ImplicitlyCapturedClosure
                          TypeSwitch.Case <GatherSystemInformationTO>(x => toReturn =
                                                                          // ReSharper restore ImplicitlyCapturedClosure
                                                                          new GatherSystemInformationTO(enTypeOfSystemInformationToGather.FullDateTime,
                                                                                                        initializeWith, index, inserted)),
                          // ReSharper disable ImplicitlyCapturedClosure
                          TypeSwitch.Case <XPathDTO>(x => toReturn = new XPathDTO(initializeWith, "", index, inserted)),
                          // ReSharper restore ImplicitlyCapturedClosure
                          // ReSharper disable ImplicitlyCapturedClosure
                          TypeSwitch.Case <FindRecordsTO>(() => toReturn = new FindRecordsTO("", "", index, inserted)),
                          // ReSharper restore ImplicitlyCapturedClosure
                          // ReSharper disable ImplicitlyCapturedClosure
                          TypeSwitch.Default(() => toReturn = null));
            // ReSharper restore ImplicitlyCapturedClosure

            return(toReturn);
        }
Пример #30
0
 public void DoDoesNothingIfTypesDoNotMatchAndNoDefaultCaseExists()
 {
     TypeSwitch.Do <object>(
         TypeSwitch.Case <string>(() => Assert.That(false, "Expected default case, got string")),
         TypeSwitch.Case <bool>(() => Assert.That(false, "Expected default case, got bool")),
         TypeSwitch.Case <int>(() => Assert.That(false, "Expected default case, got int")),
         TypeSwitch.Case <float>(() => Assert.That(false, "Expected default case, got float"))
         );
 }
Пример #31
0
 public void DoSelectsCorrectCase()
 {
     TypeSwitch.Do <int>(
         TypeSwitch.Case <string>(() => Assert.That(false, "Expected int, got string")),
         TypeSwitch.Case <bool>(() => Assert.That(false, "Expected int, got bool")),
         TypeSwitch.Case <int>(() => {}),
         TypeSwitch.Case <float>(() => Assert.That(false, "Expected int, got float"))
         );
 }
Пример #32
0
        public ViewSelector()
        {
            _switch = new TypeSwitch<DataTemplate>( () => base.SelectTemplate( null, null ) );

            _switch.Set( typeof(ComponentManagementViewModel), () => ComponentView );
            _switch.Set( typeof(LocationManagementViewModel), () => LocationsView );
            _switch.Set( typeof(PalletManagementViewModel), () => PalletView );
            _switch.Set( typeof(PalletSummaryViewModel), () => PalletSummaryView );
            _switch.Set( typeof(NavigationViewModel), () => NavigationView );
            _switch.Set( typeof( SettingsViewModel ), () => SettingsView );
        }
Пример #33
0
 public void Setup()
 {
     _switch = new TypeSwitch<int>();
 }