public static void CollectInput(Farm farm, IDuck animal) { Console.Clear(); for (int i = 0; i < farm.DuckHouses.Count; i++) { Console.WriteLine($"{i + 1}. Duck House has ({farm.DuckHouses[i].animalCount}/{farm.DuckHouses[i].Capacity})"); System.Console.WriteLine(); farm.DuckHouses[i].GroupedAnimals(); System.Console.WriteLine(); } Console.WriteLine(); // How can I output the type of animal chosen here? Console.WriteLine($"Place the {animal.Type}(s) where?"); Console.Write("> "); int choice = Int32.Parse(Console.ReadLine()) - 1; farm.DuckHouses[choice].AddResource(animal); /* * Couldn't get this to work. Can you? * Stretch goal. Only if the app is fully functional. */ // farm.PurchaseResource<IGrazing>(animal, choice); }
public void NullReferenceException_When_Invoking() { Duck source = null; IDuck target = source.As <IDuck>(); Assert.NotNull(target); Assert.Throws <NullReferenceException>(() => target.Quack()); }
private static void Tester(IDuck duck) { duck.Fly(); duck.Quack(); }
public async Task Override_Virtual_Method() { ExecitedDuck source = new ExecitedDuck(); IDuck target = source.As <IDuck>(); Assert.Equal(await source.WalkAsync(), await target.WalkAsync()); Assert.Same(source, target.GetSource <ExecitedDuck>()); }
public void Null_Can_Be_Goosed() { Duck source = null; IDuck target = source.As <IDuck>(); Assert.NotNull(target); Assert.Null(target.GetSource <Duck>()); }
private static string TestDuck(IDuck duck) { StringBuilder sb = new StringBuilder(); sb.AppendLine(duck.Quack()); sb.AppendLine(duck.Fly()); return(sb.ToString()); }
public void Hide_Base_Using_New() { ExecitedDuck source = new ExecitedDuck(); IDuck target = source.As <IDuck>(); Assert.Equal(source.Quack(), target.Quack()); Assert.Same(source, target.GetSource <Duck>()); Assert.Same(source, target.GetSource <ExecitedDuck>()); }
public async void Polymorphism_For_Override_Method() { Duck duck = new ExecitedDuck(); IDuck target = duck.As <IDuck>(); Assert.Equal(await duck.WalkAsync(), await target.WalkAsync()); Assert.Same(duck, target.GetSource <Duck>()); Assert.Same(duck, target.GetSource <ExecitedDuck>()); }
public void Should_Use_Original_Object() { Duck source = new Duck(); IDuck target = source.As <IDuck>(); Assert.Same(source, target); Assert.Same(source, target.GetSource <Duck>()); Assert.Throws <ArgumentException>(() => target.GetSource <ExecitedDuck>()); }
public void Primitive_Type_As_Unrelated_Interface() { int source = 1; IDuck target = source.As <IDuck>(); Assert.NotNull(target); Assert.Equal(source, target.GetSource <int>()); Assert.Throws <InvalidCastException>(() => target.GetSource <long>()); }
private static void DuckStory(Flock flock, IDuck rubberDuck, IDuck sicklyDuck, BehaviorFactory duckBehaviorFactory) { Console.WriteLine("The flock notices a potential threat! Time to fly away!" + "\r\n"); flock.ChangeState(DuckStates.TakingOff); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("We're in the air now! Hold on to your butts!" + "\r\n"); flock.ChangeState(DuckStates.Flying); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("With the danger far off, it's time to give the wings a break, and find a snack!" + "\r\n"); flock.ChangeState(DuckStates.Landing); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("Now on the other side of the lake, the water seems like the safest place to be right now." + "\r\n"); flock.ChangeState(DuckStates.OnWater); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("The rubber duck, having been picked up by the tide, floats back to the flock." + "\r\n"); flock.Attach(rubberDuck); flock.ChangeState(DuckStates.OnWater); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("Suddenly, a large splash hits the water!" + "\r\n"); Duck crazyDuck = new CrazyDuck(flock, duckBehaviorFactory); flock.Attach(crazyDuck); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("The flock wants nothing to do with this duck, and makes way for land." + "\r\n"); flock.ChangeState(DuckStates.OnGround); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("Unable to get away from this Crazy Duck, the flock takes flight." + "\r\n"); flock.ChangeState(DuckStates.TakingOff); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); Console.WriteLine("The Crazy Duck is still following, but there is another duck flying in to join! It's the sickly Duck!" + "\r\n"); flock.Attach(sicklyDuck); flock.ChangeState(DuckStates.Flying); Console.WriteLine("\r\n" + "-----------------------------------------------------------------------" + "\r\n"); }
static void MakeDuckSwim(IDuck duck) { // Violation : Open Close Principal // We manually turned on the switch to make it working if (duck is ElectricDuck) { ((ElectricDuck)duck).IsTurnedOn = true; } duck.Swim(); Console.WriteLine(duck.IsSwimming); }
public static void CollectInput(Farm farm, IDuck duck) { Console.Clear(); if (farm.DuckHouses.Count == 0) { Console.WriteLine("No duck houses available. Buy a duck house! Press any key to continue"); Console.Write("> "); Console.ReadLine(); } else { for (int i = 0; i < farm.DuckHouses.Count; i++) { Console.WriteLine($"{i + 1}. Duck House (contains {farm.DuckHouses[i].AnimalCount()} ducks). The capacity is 12"); } Console.WriteLine(); Console.WriteLine($"Place the Duck where?"); Console.Write("> "); var choice = 0; while (!int.TryParse(Console.ReadLine(), out choice)) { Console.WriteLine("That was invalid. Enter a valid selection."); } // int choice = Int32.Parse(Console.ReadLine()) - 1; if (choice > farm.DuckHouses.Count) { Console.WriteLine("Incorrect Selection. Press any key to continue"); Console.Write("> "); Console.ReadLine(); } else { if (farm.DuckHouses[choice - 1].Capacity == farm.DuckHouses[choice - 1].AnimalCount()) { Console.WriteLine("Too many animals. Press any key to continue"); Console.Write("> "); Console.ReadLine(); } else { farm.DuckHouses[choice - 1].AddResource(duck); Console.WriteLine($"Your Duck was placed in the Duck House ! Press any key to continue"); Console.ReadLine(); } } } }
public MainViewModel() { Duck = new Duck(); int i = 0; dog = this.WhenAnyValue(x => x.Duck.Chicken) .Select(x => $"{i++} => {Guid.NewGuid()}") .ToProperty(this, x => x.Dog, "dog"); this.WhenAnyValue(x => x.Duck.Chicken) .Subscribe(_ => Hit()); this.WhenAnyValue(x => x.Dog).Subscribe(_ => Hit()); }
private static void TestDuck(IDuck duck) { duck.Quack(); duck.Fly(); try { duck.CatchFish(); } catch (InvalidOperationException ex) { Console.ForegroundColor = ConsoleColor.Red; Console.WriteLine("Error! " + ex.Message); Console.ResetColor(); } }
public static void CollectInput(Farm farm, IDuck animal) { Console.Clear(); List <DuckFarm> CapacityList = farm.DuckFarms.Where(thing => thing.GetCount < thing.Capacity).ToList(); if (CapacityList.Count == 0) { Console.WriteLine(" All Fields are at Capacity"); Console.WriteLine("Press return key to return to Main Menu"); Console.ReadLine(); return; } else { for (int i = 0; i < CapacityList.Count; i++) { if (CapacityList[i].GetCount < farm.DuckFarms[i].Capacity) { Console.WriteLine($"Duck Farm {i + 1}:"); } Console.WriteLine($"Duck Farm ({CapacityList[i].Animals.Count} Total Ducks - {CapacityList[i].Duck()} duck)"); } } Console.WriteLine(); // How can I output the type of animal chosen here? Console.WriteLine($"Place the animal where?"); Console.Write("> "); int choice = Int32.Parse(Console.ReadLine()); CapacityList[choice - 1].AddResource(animal); /* * Couldn't get this to work. Can you? * Stretch goal. Only if the app is fully functional. */ // farm.PurchaseResource<IGrazing>(animal, choice); }
public static void CollectInput(Farm farm, IDuck duck) { Utils.Clear(); for (int i = 0; i < farm.DuckHouses.Count; i++) { if (farm.DuckHouses[i].duckCount != farm.DuckHouses[i].Capacity) { Console.WriteLine($"{i + 1}. {farm.DuckHouses[i].ToString()} Max Capacity: {farm.DuckHouses[i].Capacity}"); } } // Console.WriteLine(); // How can I output the type of Duck chosen here? Console.WriteLine($"Place the Duck where?"); Console.Write("> "); int choice = Int32.Parse(Console.ReadLine()) - 1; if (choice < farm.DuckHouses.Count) { farm.DuckHouses[choice].AddResource(duck); } else { Console.WriteLine("Not a valid facility. You may need to create one!"); Console.ReadLine(); } /* * Couldn't get this to work. Can you? * Stretch goal. Only if the app is fully functional. */ // farm.PurchaseResource<IGrazing>(Duck, choice); }
public static void CollectInput(Farm farm, IDuck animal) { Utils.Clear(); List <DuckHouse> maxDuckHouseList = farm.DuckHouses.Where(house => house.Capacity < house.MaxCapacity).ToList(); for (int i = 0; i < maxDuckHouseList.Count; i++) { Console.WriteLine($"{i + 1}. Duck House {maxDuckHouseList[i].Capacity}"); } Console.WriteLine(); // How can I output the type of animal chosen here? Console.WriteLine($"Place the animal where?"); Console.WriteLine(); Console.Write("> "); int choice = Int32.Parse(Console.ReadLine()); choice--; ChosenFacility(choice, animal, maxDuckHouseList); }
static void testDuck(IDuck duck) { duck.Quack(); duck.Fly(); }
public void Detach(IDuck duck) { DucksInFlock.Remove(duck); }
static private void TestDuck(IDuck duck) { duck.Quack(); duck.Fly(); }
private void LetTheDuckSwim(IDuck duck) { duck.Swim(); }
public void Attach(IDuck duck) { DucksInFlock.Add(duck); }
public static void ChosenFacility(int option, IDuck animal, List <DuckHouse> availableDuckHouseList) { availableDuckHouseList[option].AddResource(animal); }
public DuckAdapter(IDuck d) { duck = d; }
public void MakeDuckSwim(IDuck duck) { duck.Swim(); }
//Constructor public DuckDetails(IDuck duck) { this.duck = duck; }
static void TestDuck(IDuck duck) { duck.Quack(); duck.Fly(); }
/// <summary> /// Sets the value of a complex reference (something like $foo.bar) /// Currently used by ASTSetReference() /// </summary> /// <seealso cref=" ASTSetDirective"/> /// <param name="context">context object containing this reference</param> /// <param name="value">Object to set as value</param> /// <returns>true if successful, false otherwise</returns> public bool SetValue(IInternalContextAdapter context, Object value) { // The rootOfIntrospection is the object we will // retrieve from the Context. This is the base // object we will apply reflection to. Object result = GetVariableValue(context, rootString); if (result == null) { runtimeServices.Error( new ReferenceException(string.Format("reference set : template = {0}", context.CurrentTemplateName), this)); return(false); } // How many child nodes do we have? for (int i = 0; i < numChildren - 1; i++) { result = GetChild(i).Execute(result, context); if (result == null) { runtimeServices.Error( new ReferenceException(string.Format("reference set : template = {0}", context.CurrentTemplateName), this)); return(false); } } // We support two ways of setting the value in a #set($ref.foo = $value ) : // 1) ref.setFoo( value ) // 2) ref,put("foo", value ) to parallel the get() map introspection try { IDuck duck = result as IDuck; if (duck == null) { // first, we introspect for the set<identifier> setter method Type c = result.GetType(); PropertyInfo p; try { p = runtimeServices.Introspector.GetProperty(c, identifier); if (p == null) { throw new MethodAccessException(); } } catch (MethodAccessException) { StringBuilder sb = new StringBuilder(); sb.Append(identifier); if (Char.IsLower(sb[0])) { sb[0] = Char.ToUpper(sb[0]); } else { sb[0] = Char.ToLower(sb[0]); } p = runtimeServices.Introspector.GetProperty(c, sb.ToString()); if (p == null) { throw; } } // and if we get here, getMethod() didn't chuck an exception... Object[] args = new Object[] {}; p.SetValue(result, value, args); } else { duck.SetInvoke(identifier, value); } } catch (MethodAccessException) { // right now, we only support the IDictionary interface if (result is IDictionary) { try { IDictionary d = (IDictionary)result; d[identifier] = value; } catch (Exception ex) { runtimeServices.Error( string.Format("ASTReference Map.put : exception : {0} template = {1} [{2},{3}]", ex, context.CurrentTemplateName, Line, Column)); return(false); } } else { runtimeServices.Error( string.Format("ASTReference : cannot find {0} as settable property or key to Map in template = {1} [{2},{3}]", identifier, context.CurrentTemplateName, Line, Column)); return(false); } } catch (TargetInvocationException targetInvocationException) { // this is possible throw new MethodInvocationException( string.Format("ASTReference : Invocation of method '{0}' in {1} threw exception {2}", identifier, result.GetType(), targetInvocationException.GetBaseException().GetType()), targetInvocationException, identifier); } catch (Exception e) { // maybe a security exception? runtimeServices.Error( string.Format("ASTReference setValue() : exception : {0} template = {1} [{2},{3}]", e, context.CurrentTemplateName, Line, Column)); return(false); } return(true); }
public void CookDuck(IDuck duck) { Console.WriteLine("Im cooking this duck: " + duck.Flavor()); }
public DuckAdapter(IDuck duck) { _duck = duck; }
public DuckQuackDecorator(IDuck duck) : base(duck) { }
/// <summary> /// invokes the method. Returns null if a problem, the /// actual return if the method returns something, or /// an empty string "" if the method returns void /// </summary> public override Object Execute(Object o, IInternalContextAdapter context) { IDuck duck = o as IDuck; object[] parameters = new object[paramCount]; if (duck != null) { EvalParameters(parameters, context); return(duck.Invoke(methodName, parameters)); } /* * new strategy (strategy!) for introspection. Since we want * to be thread- as well as context-safe, we *must* do it now, * at execution time. There can be no in-node caching, * but if we are careful, we can do it in the context. */ MethodInfo method = null; PropertyInfo property = null; bool preparedAlready = false; object[] methodArguments = new object[paramCount]; try { /* * check the cache */ IntrospectionCacheData introspectionCacheData = context.ICacheGet(this); Type c = o.GetType(); /* * like ASTIdentifier, if we have cache information, and the * Class of Object o is the same as that in the cache, we are * safe. */ EvalParameters(parameters, context); if (introspectionCacheData != null && introspectionCacheData.ContextData == c) { preparedAlready = true; /* * and get the method from the cache */ if (introspectionCacheData.Thingy is MethodInfo) { method = (MethodInfo)introspectionCacheData.Thingy; methodArguments = BuildMethodArgs(method, parameters, paramArrayIndex); } if (introspectionCacheData.Thingy is PropertyInfo) { property = (PropertyInfo)introspectionCacheData.Thingy; } } else { /* * otherwise, do the introspection, and then * cache it */ Object obj = PerformIntrospection(context, c, parameters); if (obj is MethodInfo) { method = (MethodInfo)obj; } if (obj is PropertyInfo) { property = (PropertyInfo)obj; } if (obj != null) { introspectionCacheData = new IntrospectionCacheData(); introspectionCacheData.ContextData = c; introspectionCacheData.Thingy = obj; context.ICachePut(this, introspectionCacheData); } } /* * if we still haven't gotten the method, either we are calling * a method that doesn't exist (which is fine...) or I screwed * it up. */ if (method == null && property == null) { return(null); } } catch (Exception ex) { runtimeServices.Error(string.Format("ASTMethod.execute() : exception from introspection : {0}", ex)); throw new RuntimeException( String.Format( "Error during object introspection. Check inner exception for details. Node literal {0} Line {1} Column {2}", base.Literal, Line, Column), ex); } try { /* * get the returned object. It may be null, and that is * valid for something declared with a void return type. * Since the caller is expecting something to be returned, * as long as things are peachy, we can return an empty * String so ASTReference() correctly figures out that * all is well. */ Object obj; if (method == null) { obj = property.GetValue(o, null); } else { if (!preparedAlready) { methodArguments = BuildMethodArgs(method, parameters); } obj = method.Invoke(o, methodArguments); if (obj == null && method.ReturnType == typeof(void)) { obj = String.Empty; } } return(obj); } catch (TargetInvocationException targetInvocationException) { /* * In the event that the invocation of the method * itself throws an exception, we want to catch that * wrap it, and throw. We don't log here as we want to figure * out which reference threw the exception, so do that * above */ EventCartridge eventCartridge = context.EventCartridge; /* * if we have an event cartridge, see if it wants to veto * also, let non-Exception Throwables go... */ if (eventCartridge == null) { /* * no event cartridge to override. Just throw */ throw new MethodInvocationException( string.Format("Invocation of method '{0}' in {1} threw exception {2} : {3}", methodName, o.GetType(), targetInvocationException.GetBaseException().GetType(), targetInvocationException.GetBaseException().Message), targetInvocationException, methodName); } else { try { return(eventCartridge.HandleMethodException(o.GetType(), methodName, targetInvocationException)); } catch (Exception e) { throw new MethodInvocationException( string.Format("Invocation of method '{0}' in {1} threw exception {2} : {3}", methodName, o.GetType(), e.GetType(), e.Message), e, methodName); } } } catch (Exception e) { runtimeServices.Error( string.Format("ASTMethod.execute() : exception invoking method '{0}' in {1} : {2}", methodName, o.GetType(), e)); throw; } }
public static void GetInfo(IDuck duck) { duck.Quack(); duck.Name(); duck.Fly(); }
public void AddDuck(IDuck duck) { _ducks.Add(duck); }
private static void DuckClient(IDuck duck) { Console.WriteLine(duck.Quack()); Console.WriteLine(duck.Fly()); }
public DuckSqueakDecorator(IDuck duck) : base(duck) { }
public DuckAdapter(IDuck duck) { this.duck = duck; }