Пример #1
0
      /// <summary>Parses the input JSON document into an output BPL object of the given expected type.</summary>
      public override bool Parse(String input, Type expectedType) {
         Clear();
         Input = input;
         if (input.IsEmpty()) {
            AddError("Input JSON string is empty.");
            return false;
         }
         var expectedClass = (expectedType != null ? BplClass.Get(expectedType) : null);
         if (expectedType != null && expectedClass == null) {
            AddError("Expected BPL class '{0}' is invalid.", expectedType);
            return false;
         }

         try {
            var inputJson = _tokenizeJson(input);
            var migrators = _customMigrators as IEnumerable<Func<Hashtable, bool>>;
            if (migrators == null && expectedClass != null) {
               migrators = expectedClass.JsonMigrationFunctions;
            }
            if (migrators != null) {
               foreach (var migrator in migrators) {
                  if (migrator(inputJson)) WasMigrated = true;
               }
            }
            return _parse(inputJson, expectedClass);
         } catch (Exception e) {
            AddException(e);
            return false;
         }

      }
Пример #2
0
        private IClientSession GetSessionInternal(String sessionId, bool createIfNotExists)
        {
            sessionId = sessionId.HasValue() ? sessionId
                : (HttpContext.Current == null ? (string)ContextData.Get(CLIENT_SESSION_KEY)
                    : HttpContext.Current.Session[CLIENT_SESSION_KEY].AsString());

            if (sessionId.IsEmpty())
                sessionId = Guid.NewGuid().ToString("N").ToLower();

            IClientSession result = null;
            if (!_sessions.TryGetValue(sessionId, out result) && createIfNotExists)
            {
                lock (__lockObject)
                {
                    result = new ClientSession(sessionId, this);
                    if (HttpContext.Current == null)
                        ContextData.Set(CLIENT_SESSION_KEY, sessionId);
                    else
                        HttpContext.Current.Session[CLIENT_SESSION_KEY] = sessionId;
                    _sessions[sessionId] = result;
                }
            }
            else if (!result.isAlive)
                return GetSessionInternal(Guid.NewGuid().ToString("N").ToLower(), true);
            return result;
        }
Пример #3
0
 public static String FirstUpper(String phrase)
 {
     if (!phrase.IsEmpty())
         return phrase.Substring(0, 1).ToUpper() + phrase.Substring(1);
     else
         return "";
 }
Пример #4
0
 private void About(SqlTwitchUser speaker, String additionalText)
 {
     if (!additionalText.IsEmpty() && additionalText.Equals("sober")) {
         room.SendChatMessage("//TODO get quote from sober"); //I NEED SOMEETHING FROM YOU SOBER ~1am
     }
     else {
         room.SendChatMessage("Hi, I am HardlyBot! I am a chatbot designed to host card games. I am currently open source and made by HardlySober @ http://bit.ly/1LUViNe ");
     }
 }
Пример #5
0
 private void TimeMeOut(SqlTwitchUser speaker, String time)
 {
     try {
         if (time.IsEmpty()) {
             room.SendChatMessage(".timeout " + speaker.userName + " " + Random.Uint.Between(1, 600));
         }
         else {
             room.SendChatMessage(".timeout " + speaker.userName + " " + Int32.Parse(time));
         }
     }
     catch (Exception) {
         //*do nothing ever i want this to be (somewhat)secret*//
     }
 }
Пример #6
0
      /// <summary>Parses an input XML document into an output BPL object.</summary>
      public override bool Parse(String input) {
         Clear();
         Input = input;
         if (input.IsEmpty()) {
            AddError("Input XML string is empty");
            return false;
         }

         try {
            XDocument inputXml = null;
            using (var reader = XmlReader.Create(new StringReader(input), _getReaderSettings())) {
               inputXml = XDocument.Load(reader, PreserveErrorsInfo ? LoadOptions.SetLineInfo : LoadOptions.None);
            }
            var migrators = _customMigrators ?? _classMigrators;
            if (migrators != null) {
               foreach (var migrator in migrators) {
                  if (migrator(inputXml.Root)) WasMigrated = true;
               }
            }
            _mapping = new XmlNamespaceMap(inputXml);
            _resolver = new BplReferenceResolver();
            _resolver.CustomResolver = CustomResolver;

            if (inputXml.Root != null) {
               Output = _deserializeObject(inputXml.Root);
            }
            if (!Success) return false;

            if (ResolutionStrategy != BplResolutionStrategy.Manual) {
               var success = _resolver.Resolve();
               if (success || ResolutionStrategy == BplResolutionStrategy.Tolerant) {
                  Output.CompleteInitialization();
               } else {
                  foreach (var R in _resolver.Pending) {
                     AddError("Failed to resolve reference from '{0}' to '{1}' ('{2}' association).", R.Source, R.TargetId, R.Property.Name);
                  }
               }
            }
            Pending = _resolver.Pending;
            return true;
         } catch (Exception e) {
            AddException(e);
            return false;
         }
      }
Пример #7
0
        public ActionResult Logon(String usr, String pwd, String token, String fwd)
        {
            if (!token.IsEmpty())
                DecodeToken(token, ref usr, ref pwd, ref fwd);
            else if (usr.IsEmpty())
                return RedirectToAction("LoginView", new { fwd = fwd });
            var tokenDic = new Dictionary<String, String>();
            tokenDic["usr"] = usr.AsString();
            tokenDic["pwd"] = pwd.AsString();
            tokenDic["fwd"] = fwd.AsString();
            token = tokenDic.GetToken();

            var authService = ServiceLocator.GetInstance<IAuthenticationService>();
            var msg = "";
            if (!authService.PerformLogin(usr, pwd, out msg))
                return RedirectToAction("LoginError", new { token = token, msg = msg });
            return RedirectToAction("LoginSuccess", new { token = token });
        }
Пример #8
0
      /// <summary>Parses an input XML document into an output BPL object.</summary>
      public override bool Parse(String input) {
         Clear();
         Input = input;
         if (input.IsEmpty()) {
            Errors.AddError("Input HEX string is empty");
            return false;
         }

         try {
            var buffer = _fromHexString(Input);
            var reader = new BplBinaryReader(buffer);
            Output = reader.Deserialize();
            return true;
         } catch (Exception e) {
            Errors.AddException(e);
            return false;
         }
      }
 public void ReturnFalseIfNotEmpty(String value)
 {
     Assert.False(value.IsEmpty());
 }
        public override int Delete (String table, String whereClause, params String[] whereArgs)
        {
            Debug.Assert(!table.IsEmpty());

            var command = GetDeleteCommand(table, whereClause, whereArgs);

            var resultCount = -1;
            try {
                resultCount = command.ExecuteNonQuery ();
            } catch (Exception ex) {
                Log.E(Tag, "Error deleting from table " + table, ex);
            } finally {
                command.Dispose();
            }
            return resultCount;
        }
        public override int Update (String table, ContentValues values, String whereClause, params String[] whereArgs)
        {
            Debug.Assert(!table.IsEmpty());
            Debug.Assert(values != null);

            var builder = new SqliteCommandBuilder();
            builder.SetAllValues = false;

            var command = GetUpdateCommand(table, values, whereClause, whereArgs);

            var resultCount = -1;
            try {
                resultCount = (Int32)command.ExecuteNonQuery ();
            } catch (Exception ex) {
                Log.E(Tag, "Error updating table " + table, ex);
            }
            return resultCount;
        }
Пример #12
0
 public void IsEmpty(String source, Boolean expected)
 {
     Assert.Equal(expected, source.IsEmpty());
     Assert.NotEqual(expected, source.IsNotEmpty());
 }
Пример #13
0
        protected CommandLineConfig(String[] s_args)
        {
            Log = Logger.Get(GetType());
            Log.MinLevel = Level.Info;

            if (s_args.Count() == 1 && s_args[0] == "/?")
            {
                Banners.About();
                throw new ConfigException(String.Empty);
            }
            else
            {
                if (s_args.LastOrDefault() == "/verbose")
                {
                    IsVerbose = true;
                    s_args = s_args.SkipLast().ToArray();

                    Info.WriteLine("Detected the \"/verbose\" switch, entering verbose mode.");
                    Log.MinLevel = Level.Debug;

                    Debug.EnsureBlankLine();
                    Debug.Write("Command line args are: ");
                    if (s_args.IsEmpty()) Debug.WriteLine("empty");
                    else Debug.WriteLine("({0} arg{1})", s_args.Count(), s_args.Count() == 1 ? "" : "s");
                    s_args.ForEach((arg, i) => Debug.WriteLine("{0}: {1}", i + 1, arg));
                }

                Debug.EnsureBlankLine();
                Debug.WriteLine("Pre-parsing arguments...");
                var named_args = new Dictionary<String, String>();
                var shortcut_args = new List<String>();
                foreach (var s_arg in s_args)
                {
                    var m = s_arg.Parse("^-(?<name>.*?):(?<value>.*)$");
                    var name = m != null ? m["name"] : null;
                    var value = m != null ? m["value"] : s_arg;
                    if (m != null) Debug.WriteLine("Parsed \"{0}\" as name/value pair: {1} => \"{2}\".", s_arg, name, value);
                    else Debug.WriteLine("Parsed \"{0}\" as raw value.", s_arg);

                    if (name == null)
                    {
                        if (named_args.IsNotEmpty()) throw new ConfigException("Fatal error: shortcut arguments must be specified before named arguments.");
                        else shortcut_args.Add(value);
                    }
                    else
                    {
                        if (named_args.ContainsKey(name)) throw new ConfigException("Fatal error: duplicate argument \"{0}\".", name);
                        else named_args.Add(name, value);
                    }
                }
                Debug.WriteLine("Pre-parse completed: found {0} named argument{1} and {2} shortcut argument{3}.",
                    named_args.Count(), named_args.Count() == 1 ? "" : "s",
                    shortcut_args.Count(), shortcut_args.Count() == 1 ? "" : "s");

                Debug.EnsureBlankLine();
                Debug.WriteLine("Parsing arguments...");

                var parsed_args = new Dictionary<PropertyInfo, Object>();
                if (named_args.IsNotEmpty())
                {
                    Debug.WriteLine("Parsing named arguments...");
                    parsed_args = ParseArgs(named_args);
                }

                if (shortcut_args.IsNotEmpty())
                {
                    Debug.WriteLine("Parsing shortcut arguments...");

                    Dictionary<PropertyInfo, Object> parsed_shortcut_args = null;
                    var shortcuts = GetType().Attrs<ShortcutAttribute>().OrderBy(shortcut => shortcut.Priority);
                    var bind_errors = new Dictionary<String, String>();
                    foreach (var shortcut in shortcuts)
                    {
                        Debug.WriteLine("Considering shortcut schema \"{0}\"...", shortcut.Schema);
                        var words = shortcut.Schema.SplitWords();
                        if (words.Count() != shortcut_args.Count())
                        {
                            var message = String.Format("argument count mismatch.");
                            bind_errors.Add(shortcut.Schema, message);
                            Debug.WriteLine("Schema \"{0}\" won't work: {1}", shortcut.Schema, message);
                            continue;
                        }

                        try { parsed_shortcut_args = ParseArgs(words.Zip(shortcut_args).ToDictionary(t => t.Item1, t => t.Item2)); }
                        catch (ConfigException cex)
                        {
                            bind_errors.Add(shortcut.Schema, cex.Message);
                            Debug.WriteLine(cex.Message);
                            Debug.WriteLine("Schema \"{0}\" won't work: failed to parse arguments.", shortcut.Schema);

                            continue;
                        }

                        var dupes = Set.Intersect(parsed_args.Keys, parsed_shortcut_args.Keys);
                        if (dupes.IsNotEmpty())
                        {
                            var a = dupes.AssertFirst().Attr<ParamAttribute>();
                            var name = named_args.Keys.Single(k => a.Aliases.Contains(k));
                            Debug.WriteLine("Schema \"{0}\" won't work: shortcut argument duplicates parsed argument \"{1}\".", shortcut.Schema, name);
                            parsed_shortcut_args = null;
                            continue;
                        }
                        else
                        {
                            Debug.WriteLine("Schema \"{0}\" works fine, skipping other schemas (if any).", shortcut.Schema);
                            break;
                        }
                    }

                    if (parsed_shortcut_args == null)
                    {
                        var message = "Fatal error: failed to match the shortcuts.";
                        var bind_summary = bind_errors.Select(kvp => String.Format("Failed to match \"{0}\": {1}", kvp.Key, kvp.Value.Replace("Fatal error: ", String.Empty))).StringJoin(Environment.NewLine);
                        if (!IsVerbose) message = message + Environment.NewLine + bind_summary;
                        throw new ConfigException(message);
                    }
                    else
                    {
                        parsed_args.AddElements(parsed_shortcut_args);
                    }
                }

                Debug.WriteLine("Parse completed.");
                Debug.EnsureBlankLine();
                Debug.WriteLine("Setting configuration parameters...");
                var props = this.GetType().GetProperties(BF.AllInstance).Where(p => p.HasAttr<ParamAttribute>()).OrderBy(p => p.Attr<ParamAttribute>().Priority);
                props.ForEach(p =>
                {
                    if (parsed_args.ContainsKey(p))
                    {
                        var value = parsed_args[p];
                        Debug.WriteLine("Resolved %{0} as {1}.", p.Name, value.ToLog());
                        p.SetValue(this, value, null);
                    }
                    else
                    {
                        var p_default = this.GetType().GetProperty("Default" + p.Name, BF.AllStatic);
                        if (p_default == null) throw new ConfigException("Fatal error: parameter \"{0}\" must be specified.");

                        var value = p_default.GetValue(null, null);
                        Debug.WriteLine("Defaulted %{0} to {1}.", p.Name, value.ToLog());
                        p.SetValue(this, value, null);
                    }
                });
                Debug.WriteLine("Configuration parameters successfully set.");
            }
        }
Пример #14
0
        protected void VerifyResult(String s_expected, String s_actual)
        {
            (s_expected != null && s_actual != null).AssertTrue();
            s_expected = PreprocessReference(s_expected);
            s_actual = PreprocessResult(s_actual);

            var success = false;
            String failMsg = null;
            if (s_expected.IsEmpty())
            {
                Log.EnsureBlankLine();
                Log.WriteLine(s_actual);

                Assert.Fail(String.Format(
                    "Reference result for unit test '{1}' is empty.{0}" +
                    "Please, verify the trace dumped above and put in into the resource file.",
                    Environment.NewLine, UnitTest.CurrentTest.GetCSharpRef(ToCSharpOptions.Informative)));
            }
            else
            {
                var expected = s_expected.SplitLines();
                var actual = s_actual.SplitLines();
                if (expected.Count() != actual.Count())
                {
                    success = false;
                    failMsg = String.Format(
                        "Number of lines doesn't match. Expected {0}, actually found {1}" + Environment.NewLine,
                        expected.Count(), actual.Count());
                }
                else
                {
                    success = expected.Zip(actual).SkipWhile((t, i) =>
                    {
                        if (t.Item1 != t.Item2)
                        {
                            var maxLines = Math.Max(actual.Count(), expected.Count());
                            var maxDigits = (int)Math.Floor(Math.Log10(maxLines)) + 1;
                            failMsg = String.Format(
                                "Line {1} (starting from 1) doesn't match.{0}{4}{2}{0}{5}{3}",
                                Environment.NewLine, i + 1,
                                t.Item1.Replace(" ", "·"), t.Item2.Replace(" ", "·"),
                                "E:".PadRight(maxDigits + 3), "A:".PadRight(maxDigits + 3));
                            return false;
                        }
                        else
                        {
                            return true;
                        }
                    }).IsEmpty();
                }

                if (!success)
                {
                    var maxLines = Math.Max(actual.Count(), expected.Count());
                    var maxDigits = (int)Math.Floor(Math.Log10(maxLines + 1)) + 1;
                    var maxActual = Math.Max(actual.MaxOrDefault(line => line.Length), "Actual".Length);
                    var maxExpected = Math.Max(expected.MaxOrDefault(line => line.Length), "Expected".Length);
                    var total = maxDigits + 3 + maxActual + 3 + maxExpected;

                    Log.EnsureBlankLine();
                    Log.WriteLine(String.Format("{0} | {1} | {2}",
                        "N".PadRight(maxDigits),
                        "Actual".PadRight(maxActual),
                        "Expected".PadRight(maxExpected)));
                    Log.WriteLine(total.Times("-"));

                    0.UpTo(maxLines - 1).ForEach(i =>
                    {
                        var l_actual = actual.ElementAtOrDefault(i, String.Empty);
                        var l_expected = expected.ElementAtOrDefault(i, String.Empty);
                        Log.WriteLine(String.Format("{0} | {1} | {2}",
                            (i + 1).ToString().PadLeft(maxDigits),
                            l_actual.PadRight(maxActual),
                            l_expected.PadRight(maxExpected)));
                    });

                    Log.EnsureBlankLine();
                    Log.WriteLine(failMsg);
                    Assert.Fail("Actual result doesn't match expected result.");
                }
            }
        }