//-------------------------------------------------------------------------------------------- // 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); }
/// <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); } } ; })); }
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)); } }
public bool initShell() { if (!ShellSessionReady) { this.UpdateStatus(Status.Starting("Aquiring shell session")); shellSession = Board.GetShellSession(); if (shellSession != null) { this.UpdateStatus(Status.Starting("Connecting to shell session. This may take a while...")); Why conected = shellSession.Connect(); if (conected) { this.UpdateStatus(Status.Done("Shell session banner: " + shellSession.ConnectionBanner.ShortenTextWithEllipsis(60))); this.UpdateStatus(Status.Done("Shell session : " + shellSession)); return(true); } else { this.UpdateStatus(Status.Error(string.Format("Error [{0}] Could not connect to [{1}] ", conected.Reason, shellSession))); State = TaskState.abortedError; return(false); } } else { this.UpdateStatus(Status.Error("Could not get shell sesion for: " + Board)); return(false); } } else { return(true); } }
public IActionResult Put(Why why) { UserProfile user = GetCurrentUserProfile(); _whyRepository.Update(why, user.Id); return(NoContent()); }
public Why Save(BinaryWriter s) { return(Why.FromTry(delegate() { s.Write(Dots); s.Write(MesuredDistance.Metres); })); }
/// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; // Suitable nullity checks etc, of course :) if (Class != null) { hashCode = hashCode * 59 + Class.GetHashCode(); } if (Actions != null) { hashCode = hashCode * 59 + Actions.GetHashCode(); } if (Blocked != null) { hashCode = hashCode * 59 + Blocked.GetHashCode(); } if (Buildable != null) { hashCode = hashCode * 59 + Buildable.GetHashCode(); } if (Id != null) { hashCode = hashCode * 59 + Id.GetHashCode(); } if (InQueueSince != null) { hashCode = hashCode * 59 + InQueueSince.GetHashCode(); } if (Params != null) { hashCode = hashCode * 59 + Params.GetHashCode(); } if (Stuck != null) { hashCode = hashCode * 59 + Stuck.GetHashCode(); } if (Task != null) { hashCode = hashCode * 59 + Task.GetHashCode(); } if (Url != null) { hashCode = hashCode * 59 + Url.GetHashCode(); } if (Why != null) { hashCode = hashCode * 59 + Why.GetHashCode(); } if (BuildableStartMilliseconds != null) { hashCode = hashCode * 59 + BuildableStartMilliseconds.GetHashCode(); } return(hashCode); } }
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 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); }
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); }
/// <summary> /// If True, Logs the reason via WDAppLog /// </summary> public static void LogIfTrue(this Why why, ErrorLevel priority = ErrorLevel.Error, [CallerLineNumber] int line = 0, [CallerFilePath] string file = "", [CallerMemberName] string member = "") { if (why) { WDAppLog.logError(priority, why.Reason ?? "(no reason given)", "", line, file, member); } }
//--------------------------------------------------------------------------------------------------------------- // 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 Check(double value, Action <string> onError = null, params NumericRule[] rules) { foreach (NumericRule rule in rules) { Why r = Check(value, rule, onError); if (!r) { return(r); } } return(true); }
private void validateToolStripMenuItem_Click(object sender, EventArgs e) { if (puzzle != null) { Why valid = puzzle.Valid(); MessageBox.Show(valid ? "Crossword is valid" : ("Crossword not valid\r\n" + valid.Reason)); } if (dictionary != null) { } }
public static ProformaClass FromNameAndAge(string name, int age) { ProformaClass p = new ProformaClass(name, age); Why valid = p.Valid(); if (valid) { return(p); } else { WDAppLog.logError(ErrorLevel.Error, "Invalid data: " + valid.Reason); return(null); } }
public static Why CheckCustom(double value, Dictionary <string, Predicate <double> > checks, Action <string> onError = null) { foreach (var check in checks) { Why r = CheckCustom(value, check.Key, check.Value, onError); if (!r) { return(r); } } 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 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 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 void Add(Why why) { using (var conn = Connection) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"INSERT INTO Why (Description, DreamId) OUTPUT INSERTED.ID VALUES (@Description, @DreamId)"; cmd.Parameters.AddWithValue("@Description", why.Description); cmd.Parameters.AddWithValue("@DreamId", why.DreamId); why.Id = (int)cmd.ExecuteScalar(); } } }
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()); }
public Why GetRandomWhy(int dreamId, int userProfileId) { using (var conn = Connection) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"SELECT TOP 1 w.Id AS WhyId, w.Description, w.DreamId, d.Name, d.IsDeactivated, d.UserProfileId FROM Why w JOIN Dream d ON w.DreamId = d.Id WHERE d.Id = @dreamId AND d.UserProfileId = @userProfileId ORDER BY NEWID();"; cmd.Parameters.AddWithValue("@dreamId", dreamId); cmd.Parameters.AddWithValue("@userProfileId", userProfileId); var reader = cmd.ExecuteReader(); if (reader.Read()) { Why why = new Why() { Id = DbUtils.GetInt(reader, "WhyId"), Description = DbUtils.GetString(reader, "Description"), DreamId = DbUtils.GetInt(reader, "DreamId"), Dream = new Dream() { Id = DbUtils.GetInt(reader, "DreamId"), Name = DbUtils.GetString(reader, "Name"), IsDeactivated = DbUtils.GetInt(reader, "IsDeactivated"), UserProfileId = DbUtils.GetInt(reader, "UserProfileId"), } }; reader.Close(); return(why); } else { reader.Close(); return(null); } } } }
//----------------------------------------------------------------------------------------------- // 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); }
public static bool TestConection(INetworkCom connection, string pingCmd, Predicate <string> pingCorrect, IStatusProvider status = null) { //NOTE: status.UpdateStatus is a null safe extension method bool successful = false; //TelnetCom tc = new SimpleTelnetCom(Board.IpAdress, TelnetPort); Why telnetConected = connection.Connect(); if (telnetConected) { Task.Delay(500); status.UpdateStatus(Status.Done("Coms available: " + connection)); status.UpdateStatus(Status.Done("Banner data: " + connection.InputBuffer.ToString())); successful = true; if (!string.IsNullOrEmpty(pingCmd)) { string telnetResponce = connection.ExecuteCommand(pingCmd); if (pingCorrect != null) { successful = pingCorrect(telnetResponce); status.UpdateStatus(successful ? Status.Done("Telnet test passed: " + telnetResponce) : Status.Error("Telnet test failed: " + telnetResponce)); } else { successful = !string.IsNullOrWhiteSpace(telnetResponce); status.UpdateStatus(successful ? Status.Done("Telnet responded to ping command: " + telnetResponce) : Status.Error("Telnet didn't respond to ping command: " + telnetResponce)); } } } else { status.UpdateStatus(Status.Error("Telnet un-available: " + telnetConected.Reason ?? "(no information)")); } return(successful); }
public static Why Save(Bitmap b, BinaryWriter 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); } } ; })); }
public void Update(Why why, int userProfileId) { using (var conn = Connection) { conn.Open(); using (var cmd = conn.CreateCommand()) { cmd.CommandText = @"UPDATE Why SET Why.Description = @Description FROM Why JOIN Dream ON Why.DreamId = Dream.Id JOIN UserProfile ON Dream.UserProfileId = UserProfile.Id WHERE Why.Id = @WhyId AND UserProfileId = @UserProfileId"; cmd.Parameters.AddWithValue("@Description", why.Description); cmd.Parameters.AddWithValue("@WhyId", why.Id); cmd.Parameters.AddWithValue("@UserProfileId", userProfileId); cmd.ExecuteNonQuery(); } } }
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>")); }