public static Why Load(BinaryReader r, out Bitmap b) { try { bool notNull = r.ReadBoolean(); if (notNull) { int len = r.ReadInt32(); byte[] data = r.ReadBytes(len); using (MemoryStream ms = new MemoryStream(data)) { b = new Bitmap(ms); return(true); } } else { b = null; return(true); } } catch (Exception ex) { b = null; return(Why.FalseBecause(ex)); } }
/// <summary> /// Bitmap save routine, bridges Bitmap saving to BinaryWriter /// </summary> public static Why Save(Bitmap b, BinaryWriter s) { // validate inputs if (s == null) { return(Why.FalseBecause("Save(Bitmap b, BinaryWriter s), BinaryWriter was null", true)); } // Save b into s return(Why.FromTry(delegate() { bool notNull = b != null; s.Write(notNull); if (notNull) { using (MemoryStream ms = new MemoryStream()) { b.Save(ms, ImageFormat.Bmp); byte[] data = ms.ToArray(); s.Write(data.Length); s.Write(data); } } ; })); }
//-------------------------------------------------------------------------------------------- // IValidatable //-------------------------------------------------------------------------------------------- public Why Valid() { for (int x = 0; x < Width; x++) { for (int y = 0; y < Height; y++) { //is there a character at the grid which matches our text char?_c = grid[x, y]; if (_c != null) { foreach (WordVector wv in words) { if (wv.Intersects(x, y)) { char?letter = wv[x, y]; if (letter == null) { return(Why.FalseBecause("Code error: WordVector.Intersects(x, y) is not meshing properly with WordVector[x, y]")); } if (letter.Value != _c.Value) { return(Why.FalseBecause("word / grid letter mismatch. ({0}, {1}) is {2}, but intersects a {3} in '{4}'", x, y, _c.Value, letter.Value, wv.Word.PrimarySpelling)); } } } } } } return(true); }
public virtual Why DoAction(object sender, EventArgs args) { if (Action != null) { return(Action(sender, args)); } return(Why.FalseBecause("No action method supplied")); }
public static Why CheckCustom(double value, string error, Predicate <double> check, Action <string> onError = null) { if (!check(value)) { string reason = string.Format("{1} [got: {0}]", value, error); doAction(onError, reason); return(Why.FalseBecause(reason)); } return(true); }
public static Why CheckIsKey <K, V>(K key, IDictionary <K, V> dictionary, Action <string> onError = null) { if (dictionary.ContainsKey(key)) { string reason = string.Format("Key not found: {0}", key); doAction(onError, reason); return(Why.FalseBecause(reason)); } return(true); }
//--------------------------------------------------------------------------------------------------------------- // Parsing //--------------------------------------------------------------------------------------------------------------- public Why paseFile(string path) { precomplieTag = Math.Abs(Path.GetFileName(path).GetHashCode()); Why r = parseText(File.ReadAllText(path)); if (!r) { return(Why.FalseBecause("Error loading {0}: {1}", Path.GetFileName(path), r.Reason)); } return(r); }
public static Why CheckIndex <T>(int index, IList <T> array, Action <string> onError = null) { if (index < 0) { string reason = string.Format("Index can not be negative, got: {0}", index); doAction(onError, reason); return(Why.FalseBecause(reason)); } if (index >= array.Count) { string reason = string.Format("Index out of bounts 0 <= index < {1}, got: {0}", index, array.Count); doAction(onError, reason); return(Why.FalseBecause(reason)); } return(true); }
public static Why Load(BinaryReader s, out Resolution res) { try { double dots = s.ReadDouble(); double meters = s.ReadDouble(); res = Resolution.fromMesurement(dots, meters); } catch (Exception ex) { res = null; return(Why.FalseBecause(ex)); } return(true); }
public override Why Connect() { if (State == DeviceState.Ready) { return(true); //already connected } try { State = DeviceState.Init; endPoint = new IPEndPoint(IpAdress, Port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.BeginConnect(endPoint, OnConnect, socket); Candle respondTime = Candle.StartNewFromSeconds(5); while (State == DeviceState.Init) { Thread.Sleep(10); if (!respondTime) { socket.Close(); State = DeviceState.Error; return(FalseBecauseTimedOut); } } if (socket.Connected) { State = DeviceState.Ready; return(true); } else { State = DeviceState.Error; return(FalseBecauseConectionFailed); } } catch (Exception ex) { State = DeviceState.Error; return(Why.FalseBecause(ex)); } return(true); }
public override Why Connect() { try { State = DeviceState.Init; client.Connect(); //sshShellStream = client.CreateShellStream("xterm", 120, 24, 800, 600, 1024 * 10); sshShellStream = client.CreateShellStream("xterm", 2048, 24, 800, 600, 1024 * 10); sshShellStream.ErrorOccurred += sshShell_ErrorOccurred; sshShellStream.DataReceived += sshShellStream_DataReceived; swInput = new StreamWriter(sshShellStream); srOutput = new StreamReader(sshShellStream); swInput.AutoFlush = true; State = DeviceState.Ready; Thread.Sleep(1000); /* * StringBuilder sb = new StringBuilder(); * while (sshShellStream.DataAvailable) * { * sb.Append(sshShellStream.Read()); * } * this.ConnectionBanner = sb.ToString();*/ //this.ConnectionBanner = srOutput.ReadToEnd(); //srOutput. //swInput.WriteLine("ls --help"); this.ConnectionBanner = srOutput.ReadToEnd(); } catch (SshAuthenticationException ex) { AuthenticationFailed = true; State = DeviceState.Error; return(Why.FalseBecause(ex.Message)); } catch (Exception ex) { State = DeviceState.Error; return(Why.FalseBecause(ex.Message)); } return(true); }
public Why parseText(string text) { FileHash = Math.Abs(text.GetHashCode()); string[] lines = text.GetLines(StringExtension.PruneOptions.NoPrune).ToArray(); for (int i = 0; i < lines.Length; i++) { string line = lines[i]; if (isComment(line) || isBlank(line)) { //skip line continue; } else if (isDef(line)) { Why r = parseDef(line); if (!r) { return(Why.FalseBecause("#def at line {0} was not parsable ({2}): {1}", i + 1, line, r.Reason)); } } else if (isPragma(line)) { Why r = parsePragma(line); if (!r) { return(Why.FalseBecause("#pragma at line {0} was not parsable ({2}): {1}", i + 1, line, r.Reason)); } } else { line = preProcess(line); Why r = parseLine(line); if (!r) { return(Why.FalseBecause("line {0} was not parsable ({2}): {1}", i + 1, line, r.Reason)); } } } //signal end of file return(parseEndOfFile()); }
//----------------------------------------------------------------------------------------------- // IValidatable //----------------------------------------------------------------------------------------------- public Why Valid() { Why valid = true; if (Age > MaxAge) { valid &= Why.FalseBecause("Age can not be greater than {0}.", MaxAge); } if (Age < 0) { valid &= Why.FalseBecause("Age can not be negative."); } if (Name == null) { valid &= Why.FalseBecause("Name can not be null."); } return(valid); }
public static Why CheckRangeInclusive(double value, double minInclusive, double maxInclusive, Action <string> onError = null) { if (value < minInclusive) { string reason = string.Format("Value can not be < {1}, got: {0}", value, minInclusive); doAction(onError, reason); return(Why.FalseBecause(reason)); } if (value > maxInclusive) { string reason = string.Format("Value can not be < {1}, got: {0}", value, maxInclusive); doAction(onError, reason); return(Why.FalseBecause(reason)); } return(true); }
public override Why Connect() { try { State = DeviceState.Init; endPoint = new IPEndPoint(IpAdress, Port); socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); socket.Connect(endPoint); pollTimer = new Timer(pollForInput, null, 0, 10); State = DeviceState.Ready; } catch (Exception ex) { socket.Close(); State = DeviceState.Error; return(Why.FalseBecause(ex.Message)); } return(true); }
private bool parseDef(string line) { string[] parts = line.Split("=".ToCharArray(), 2); if (parts.Length == 2) { string def = parts[0]; string insertText = parts[1]; if (def.Length > 5) { def = parts[0].Substring(5).Trim(); insertText = insertText.Trim(); insertText = preProcess(insertText); Defs.Add(new Tuple <string, string>(def, insertText)); return(true); } else { return(Why.FalseBecause("mising def before =")); } } return(Why.FalseBecause("expeting #def<name> = <something>")); }
public override Why parseLine(string line) { if (string.IsNullOrWhiteSpace(line)) { return(true); // blank line = do nothing } else if (Value == null) { return(Why.FalseBecause("Not expecting regular line (aka a spritesheet) before sprite is defined.")); } else if (layerFrames.Length == 0) { return(Why.FalseBecause("Not expecting (another?) spritesheet.")); } else if (layerParsedImagePaths.Count < layerFrames.Length) { string filePath = ResolveAbsoluteFileName(line.Trim()); if (!File.Exists(filePath)) { return(Why.FalseBecause("File not found ({0}).", line.Trim())); } layerParsedImagePaths.Add(filePath); } //no else if (layerParsedImagePaths.Count == layerFrames.Length) { CreateLayerFromImageSet(); //LayeredSpriteLayer layer = new LayeredSpriteLayer(name, ); //reset spritesheets layerParsedImagePaths = new List <string>(); layerFrames = new string[0]; } return(true); }
public override Why parsePragma(string pragma, string args) { List <KeyValuePair <string, string> > options = parseArgs(args); if (options == null) //error (empty list if no args) { return(Why.FalseBecause("Could not parse option set (eg op1=x; opt2=y), got:", args)); } if (pragma.EqualsIgnoreCaseTrimmed("sprite")) { int width, height; string name = getOption(options, "name") ?? "un-named"; //frameSize = 32, 32; frameRate=FRAME_RATE int[] nums = getOption(options, "framesize").ParseAllIntegers(); if (nums.Length != 2) { return(Why.FalseBecause("#frameSize expects two numbers, got {0}.", nums.Length)); } width = nums[0]; height = nums[1]; double defaultFps = int.Parse(getOption(options, "defaultfps") ?? "10"); Value = new LayeredSprite(width, height, defaultFps); Value.Name = name; } else if (pragma.EqualsIgnoreCaseTrimmed("readmode")) { string mode = getOption(options, "mode") ?? "list_of_simple_sheets"; readMode = (ReadMode)Enum.Parse(typeof(ReadMode), mode); } else if (pragma.EqualsIgnoreCaseTrimmed("anim")) { if (Value == null) { return(Why.FalseBecause("Not expecting anim definition before sprite is defined.")); } //parse args int stancePos = int.Parse(getOption(options, "stancePos") ?? "-1"); bool repeat = Misc.DoesStringMeanTrue(getOption(options, "repeat")); bool ping = Misc.DoesStringMeanTrue(getOption(options, "ping")); bool interuptable = Misc.DoesStringMeanTrue(getOption(options, "interuptable")); bool returnToFirstFrame = Misc.DoesStringMeanTrue(getOption(options, "returnToFirstFrame")); int frameRate = int.Parse(getOption(options, "frameRate") ?? "30"); string name = getOption(options, "name") ?? "un-named"; string sheet = getOption(options, "default") ?? "un-named"; string set = getOption(options, "set") ?? "sprite"; int[] frames = (getOption(options, "frames") ?? "0").ParseAllIntegers(); int xMove = int.Parse(getOption(options, "x") ?? "0"); int yMove = int.Parse(getOption(options, "y") ?? "0"); //create sprite double frameMs = 1000.0 / (double)frameRate; SpriteAnimation anim = new SpriteAnimation(frames, frameMs, new Point2D(xMove, yMove)); Value.Animations.Add(name, anim); } else if (pragma.EqualsIgnoreCaseTrimmed("layer")) { if (Value == null) { return(Why.FalseBecause("Not expecting layer definition before sprite is defined.")); } if (layerParsedImagePaths.Count > 0) { return(Why.FalseBecause("New layer defined before all sheets in previous layer were defined.")); } //parse layer //name, sheets, preCompile layerName = getOption(options, "name") ?? "un-named"; layerFrames = (getOption(options, "sheets") ?? "un-named").Split(",".ToCharArray()).Select(S => S.Trim()).ToArray(); layerPreCompile = Misc.DoesStringMeanTrue(getOption(options, "preCompile") ?? "false"); //Bitmap b = Com //LayeredSpriteLayer layer = new LayeredSpriteLayer(name, //Value. } else { return(Why.FalseBecause("unknown pragma ({0})", pragma ?? "NULL")); } return(true); }
public static Why Check(double value, NumericRule rule, Action <string> onError = null) { string reason = ""; //handle -0 double negativeZero = -1.0 * 0; if (BitConverter.DoubleToInt64Bits(0) == BitConverter.DoubleToInt64Bits(negativeZero)) { value = 0; } //if ok, return true switch (rule) { case NumericRule.IsZero: if (value == 0.0) { return(true); } reason = string.Format("expecting zero, got: {0}", value); break; case NumericRule.IsNotZero: if (value != 0.0) //nb -0 == 0 in c# { return(true); } reason = string.Format("value can not be zero"); break; case NumericRule.IsGreaterThanOrEqualZero: if (value >= 0.0) { return(true); } reason = string.Format("expecting >= zero, got: {0}", value); break; case NumericRule.IsGreaterThanZero: if (value > 0.0) { return(true); } reason = string.Format("expecting > zero, got: {0}", value); break; case NumericRule.IsLessThanOrEqualZero: if (value <= 0.0) { return(true); } reason = string.Format("expecting <= zero, got: {0}", value); break; case NumericRule.IsLesThanZero: if (value < 0.0) { return(true); } reason = string.Format("expecting < zero, got: {0}", value); break; case NumericRule.IsOdd: if (isWholeNumber(value)) { if (isOdd((int)value)) { return(true); } reason = string.Format("expecting an odd number, got: {0}", value); } else { reason = string.Format("expecting odd number, but did not get a whole number {0}", value); } break; case NumericRule.IsEven: if (isWholeNumber(value)) { if (isEven((int)value)) { return(true); } reason = string.Format("expecting an even number, got: {0}", value); } else { reason = string.Format("expecting even number, but did not get a whole number {0}", value); } break; case NumericRule.IsUnsignedByte: return(CheckRangeInclusive(value, byte.MinValue, byte.MaxValue, onError)); case NumericRule.IsSignedByte: return(CheckRangeInclusive(value, sbyte.MinValue, sbyte.MaxValue, onError)); case NumericRule.IsUnsignedInt32: return(CheckRangeInclusive(value, uint.MinValue, uint.MaxValue, onError)); case NumericRule.IsSignedInt32: return(CheckRangeInclusive(value, int.MinValue, int.MaxValue, onError)); case NumericRule.IsPow2: if (isWholeNumber(value)) { if (IsPowerOfTwo((ulong)value)) { return(true); } reason = string.Format("expecting a power of 2, got: {0}", value); } else { reason = string.Format("expecting a power of 2, but did not get a whole number {0}", value); } break; default: reason = string.Format("INVALID CHECK ({0})", rule); break; } //here because the test failed doAction(onError, reason); return(Why.FalseBecause(reason)); }