Ejemplo n.º 1
0
        /// <summary>
        /// Puts the specified named attributes into JsonMap. If named attribute is not found it is written with null if keepAbsent=true or skipped.
        /// You can specify optional rename pattern like so "src->target" e.g. : node.ToMapOfAttrs("run-id->id","description->d");
        /// </summary>
        public static JsonDataMap ToMapOfAttrs(this IConfigSectionNode node, bool keepAbsent, params string[] attrNames)
        {
            var result = new JsonDataMap(false);

            if (node != null && attrNames != null)
            {
                attrNames.ForEach(a =>
                {
                    var target = a;
                    var source = a;
                    var i      = a.IndexOf("->");
                    if (i > 0 && i < a.Length - 2)
                    {
                        source = a.Substring(0, i);
                        target = a.Substring(i + 2);//len of ->
                    }
                    var attr = node.AttrByName(source);
                    if (attr.Exists || keepAbsent)
                    {
                        result[target] = attr.Value;
                    }
                });
            }

            return(result);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Override to map incoming request based on normalized <see cref="ISession.DataContextName"/> into a connect string.
        /// The default base implementation just allocates a connection using <see cref="ConnectString" /> property
        /// </summary>
        /// <param name="headers">Optional headers supplied with request (may be null)</param>
        /// <returns>New SqlConnection instance</returns>
        protected virtual SqlConnection GetSqlConnection(JsonDataMap headers)
        {
            var result = new SqlConnection(ConnectString);

            result.Open();
            return(result);
        }
Ejemplo n.º 3
0
        /// <summary>
        /// Continues a distributed call flow on this LOGICAL thread (asynchronous call chain) from the supplied state (JsonDataMap).
        /// If the current logical thread is already set with distributed flow then throws exception.
        /// Otherwise, sets the existing code flow step as the first step of the distributed one
        /// </summary>
        public static DistributedCallFlow Continue(IApplication app, JsonDataMap existing, Guid?guid = null, string directorName = null, string callerAgent = null, string callerPort = null)
        {
            app.NonNull(nameof(app));
            existing.IsTrue(v => v != null && v.Count > 0, nameof(existing));

            var current = ExecutionContext.CallFlow;

            var result = current as DistributedCallFlow;

            if (result == null)
            {
                result = new DistributedCallFlow();

                result.ReadAsJson(existing, false, null);

                if (current == null)
                {
                    callerAgent = callerAgent.Default(System.Reflection.Assembly.GetCallingAssembly().GetName().Name);
                    callerPort  = callerPort.Default(System.Reflection.Assembly.GetEntryAssembly()?.GetName().Name);
                    current     = new CodeCallFlow(guid ?? Guid.NewGuid(), directorName, callerAgent, callerPort);
                }
                result.m_List.Add(new Step(app, ExecutionContext.Session, current));
                ExecutionContext.__SetThreadLevelCallContext(result);
            }
            else
            {
                throw new AzosException("Distributed flow error: The context is already injected with DistributedCallFlow");
            }

            return(result);
        }
Ejemplo n.º 4
0
        private JsonDataMap getByNamespace(IInstrumentation instr)
        {
            var data = new JsonDataMap();

            IEnumerable <Type> typeKeys = instr.DataTypes.OrderBy(t => t.FullName);

            foreach (var tkey in typeKeys)
            {
                Datum datum      = null;
                var   sourceKeys = instr.GetDatumTypeSources(tkey, out datum).OrderBy(s => s);
                if (datum == null)
                {
                    continue;
                }

                var tData = new JsonDataMap();
                tData["data"] = sourceKeys;

                tData["descr"] = datum.Description;
                tData["unit"]  = datum.ValueUnitName;
                tData["error"] = datum is IErrorInstrument;
                tData["gauge"] = datum is Gauge;

                data.Add(tkey.FullName, tData);
            }

            return(data);
        }
Ejemplo n.º 5
0
 private void buildFromTemplateArgs(BSONDocument root, JsonDataMap template, TemplateArg[] args)
 {
     foreach (var kvp in template)
     {
         root.Set(jToB(kvp.Key, kvp.Value, args));
     }
 }
Ejemplo n.º 6
0
        /// <summary>
        /// Creates an instance of configuration initialized from JSON content passed as JsonDataMap
        /// </summary>
        public static JSONConfiguration CreateFromJson(JsonDataMap content)
        {
            var result = new JSONConfiguration();

            result.read(content);
            return(result);
        }
Ejemplo n.º 7
0
        public object LoadComponentTree(string group = null)
        {
            var res = new JsonDataMap();

            var all = App.AllComponents;

            var rootArr = new JsonDataArray();

            foreach (var cmp in all.Where(c => c.ComponentDirector == null))
            {
                rootArr.Add(getComponentTreeMap(all, cmp, 0, group));
            }

            res["root"] = rootArr;

            var otherArr = new JsonDataArray();

            foreach (var cmp in all.Where(c => c.ComponentDirector != null && !(c is ApplicationComponent)))
            {
                rootArr.Add(getComponentTreeMap(all, cmp, 0));
            }

            res["other"] = otherArr;

            return(new { OK = true, tree = res });
        }
Ejemplo n.º 8
0
        /// <summary>
        /// Returns true if JsonDataMap map is not null and it has a named key and its value matches the specified pattern using * and ? wild cards a la DOS
        /// </summary>
        public static bool MapValueMatches(this JsonDataMap map, string key, string pattern, bool senseCase = false)
        {
            if (map == null)
            {
                return(false);
            }
            if (key.IsNullOrWhiteSpace())
            {
                return(false);
            }

            if (!map.ContainsKey(key))
            {
                return(false);
            }

            var got = map[key].AsString(null);

            if (got == null && pattern == null)
            {
                return(true);
            }

            return(got.MatchPattern(pattern, senseCase: senseCase));
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Returns this object converted to JsonDataMap. Only shallow conversion is done, that is:
        /// any complex values are added as-is.
        /// This method is the backbone of DOC to JSON serialization
        /// </summary>
        public virtual JsonDataMap ToJsonDataMap(JsonWritingOptions options = null)
        {
            var map = new JsonDataMap();

            foreach (var fd in Schema)
            {
                string name;

                var val = FilterJsonSerializerField(fd, options, out name);
                if (name.IsNullOrWhiteSpace())
                {
                    continue;                   //field was excluded for Json serialization
                }
                AddJsonSerializerField(fd, options, map, name, val);
            }

            if (this is IAmorphousData amorph)
            {
                if (amorph.AmorphousDataEnabled)
                {
                    foreach (var kv in amorph.AmorphousData)
                    {
                        var key = kv.Key;
                        while (map.ContainsKey(key))
                        {
                            key += "_";
                        }
                        AddJsonSerializerField(null, options, map, key, kv.Value);
                    }
                }
            }

            return(map);
        }
Ejemplo n.º 10
0
        /// <summary>
        /// Builds a default map with base exception descriptor, searching its InnerException chain for IExternalStatusProvider.
        /// This method never returns null as the very root data map is always built
        /// </summary>
        public static JsonDataMap DefaultBuildErrorStatusProviderMap(this Exception error, bool includeDump, string ns, string type = null)
        {
            var result = new JsonDataMap
            {
                { CoreConsts.EXT_STATUS_KEY_NS, ns.NonBlank(nameof(ns)) },
                { CoreConsts.EXT_STATUS_KEY_TYPE, type.Default(error.GetType().Name) }
            };

            if (error is AzosException aze)
            {
                result[CoreConsts.EXT_STATUS_KEY_CODE] = aze.Code;
            }

            var inner = error.InnerException.SearchThisOrInnerExceptionOf <IExternalStatusProvider>();

            if (inner != null)
            {
                var innerData = inner.ProvideExternalStatus(includeDump);
                if (innerData != null)
                {
                    result[CoreConsts.EXT_STATUS_KEY_CAUSE] = innerData;
                }
            }

            return(result);
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Returns true if JsonDataMap map is not null and it has a named key and its value contains the specified substring doing case insensitive
        /// comparison by default. Used in unit tests doing partial data matches
        /// </summary>
        public static bool MapValueContains(this JsonDataMap map, string key, string substring, bool senseCase = false)
        {
            if (map == null)
            {
                return(false);
            }
            if (key.IsNullOrWhiteSpace())
            {
                return(false);
            }

            if (!map.ContainsKey(key))
            {
                return(false);
            }

            var got = map[key].AsString(null);

            if (got == null && substring == null)
            {
                return(true);
            }

            return(got.IndexOf(substring, senseCase ? StringComparison.Ordinal : StringComparison.OrdinalIgnoreCase) >= 0);
        }
Ejemplo n.º 12
0
        public Record(string init) : base()
        {
            if (init.IsNullOrWhiteSpace())
            {
                throw new WaveException(StringConsts.ARGUMENT_ERROR + "Record.ctor(init==null|empty)");
            }

            JsonDataMap initMap = null;

            try
            {
                initMap = JsonReader.DeserializeDataObject(init) as JsonDataMap;
            }
            catch (Exception error)
            {
                throw new WaveException(StringConsts.ARGUMENT_ERROR + "Record.ctor(init is bad): " + error.ToMessageWithType(), error);
            }

            if (initMap == null)
            {
                throw new WaveException(StringConsts.ARGUMENT_ERROR + "Record.ctor(init isnot map)");
            }

            ctor(initMap);
        }
Ejemplo n.º 13
0
        private JsonDataMap toTwilioEmail(Message msg)
        {
            var result = new JsonDataMap();

            result["a"] = 1;
            return(result);
        }
Ejemplo n.º 14
0
        private void jsonMapAndPrimitives(string actionName)
        {
            var initialMap = new JsonDataMap();

            initialMap["ID"]   = 100;
            initialMap["Name"] = "Initial Name";
            var str = initialMap.ToJson(JsonWritingOptions.CompactRowsAsMap);

            var values = new NameValueCollection();

            values.Add("n", "777");
            values.Add("s", "sss");

            using (var wc = CreateWebClient())
            {
                wc.QueryString = values;
                wc.Headers[HttpRequestHeader.ContentType] = Azos.Web.ContentType.JSON;
                var res = wc.UploadString(INTEGRATION_HTTP_ADDR + actionName, str);

                var gotMap = JsonReader.DeserializeDataObject(res) as JsonDataMap;

                Aver.AreObjectsEqual(gotMap["ID"], 777);
                Aver.AreObjectsEqual(gotMap["Name"], "sss");
            }
        }
Ejemplo n.º 15
0
        public void JSONDataMapFromURLEncoded_3()
        {
            var map = JsonDataMap.FromURLEncodedString("one=a%2Bb+%3E+123+%3D+true&two=Hello+%26+Welcome.%E4%B9%85%E6%9C%89%E5%BD%92%E5%A4%A9%E6%84%BF");

            Aver.AreObjectsEqual("a+b > 123 = true", map["one"]);
            Aver.AreObjectsEqual("Hello & Welcome.久有归天愿", map["two"]);
        }
Ejemplo n.º 16
0
        public void JWTHS256_Tamper()
        {
            var claims = new JsonDataMap {
                { "aud", "ZZZ" }, { "sub", "KKK" }
            };

            var jwt = m_App.SecurityManager.GetDefaultPublicJWT().ProtectJWTPayloadAsBuffer(claims);

            Encoding.UTF8.GetString(jwt).See("Encoded JWT:");

            var got = m_App.SecurityManager.GetDefaultPublicJWT().UnprotectJWTPayload(new ArraySegment <byte>(jwt));

            got.See("Deciphered from JWT:");

            Aver.IsNotNull(got);
            Aver.AreEqual(2, got.Count);
            Aver.AreEqual(claims["aud"].AsString(), got["aud"].AsString());
            Aver.AreEqual(claims["sub"].AsString(), got["sub"].AsString());

            var was = jwt[3];

            jwt[3] = was != (byte)'A' ? (byte)'A' : (byte)'B';

            Encoding.UTF8.GetString(jwt).See("Tampered JWT:");
            got = m_App.SecurityManager.GetDefaultPublicJWT().UnprotectJWTPayload(new ArraySegment <byte>(jwt));
            Aver.IsNull(got);//tampered
        }
Ejemplo n.º 17
0
        public void JSONDataMapFromURLEncoded_PlusAnd20Mix()
        {
            var map = JsonDataMap.FromURLEncodedString("a=I+Am%20John&b=He%20Is++Not");

            Aver.AreObjectsEqual("I Am John", map["a"]);
            Aver.AreObjectsEqual("He Is  Not", map["b"]);
        }
Ejemplo n.º 18
0
        protected override void DoEncodeResponse(MemoryStream ms, ResponseMsg msg, ISerializer serializer)
        {
            var data = new JsonDataMap();

            data["id"]       = msg.RequestID.ID;
            data["instance"] = msg.RemoteInstance?.ToString("D");

            if (msg.ReturnValue is string rstr)
            {
                data["return"] = rstr;
            }
            else if (msg.ReturnValue is Contracts.RemoteTerminalInfo rtrm)
            {
                data["return"] = rtrm;
            }
            else if (msg.ReturnValue is WrappedExceptionData wed)
            {
                data["return"] = new JsonDataMap {
                    { "error-content", wed.ToJson(JsonWritingOptions.CompactRowsAsMap) }
                }
            }
            ;
            else
            {
                throw new ProtocolException(StringConsts.GLUE_BINDING_RESPONSE_ERROR.Args(nameof(AppTermBinding), "unsupported ReturnValue `{0}`".Args(msg.ReturnValue)));
            }

            var json = data.ToJson(JsonWritingOptions.Compact);
            var utf8 = Encoding.UTF8.GetBytes(json);

            ms.Write(utf8, 0, utf8.Length);
        }
Ejemplo n.º 19
0
        /// <summary>
        /// Returns a string parsed into key values as:  val1: descr1,val2: desc2...
        /// </summary>
        public static JsonDataMap ParseValueListString(string valueList, bool caseSensitiveKeys = false)
        {
            var result = new JsonDataMap(caseSensitiveKeys);

            if (valueList.IsNullOrWhiteSpace())
            {
                return(result);
            }

            var segs = valueList.Split(',', '|', ';');

            foreach (var seg in segs)
            {
                var i = seg.LastIndexOf(':');
                if (i > 0 && i < seg.Length - 1)
                {
                    result[seg.Substring(0, i).Trim()] = seg.Substring(i + 1).Trim();
                }
                else
                {
                    result[seg] = seg;
                }
            }

            return(result);
        }
Ejemplo n.º 20
0
        public void MapValueMatches_Cases()
        {
            JsonDataMap map = new JsonDataMap {
                { "a", "Alex Macedonian" }, { "b", "Bobby Fisher" }, { "c", null }
            };

            Aver.IsTrue(map.MapValueMatches("a", "Alex*"));
            Aver.IsTrue(map.MapValueMatches("a", "ALEX*"));
            Aver.IsFalse(map.MapValueMatches("a", "ALEX*", senseCase: true));
            Aver.IsFalse(map.MapValueMatches("b", "ALEX*"));

            Aver.IsTrue(map.MapValueMatches("a", "Al*Mac*n?an"));
            Aver.IsFalse(map.MapValueMatches("a", "Al*Mac*nY?an"));

            Aver.IsTrue(map.MapValueMatches("b", "*"));
            Aver.IsTrue(map.MapValueMatches("b", "????? ??????"));
            Aver.IsFalse(map.MapValueMatches("b", "????  ??????"));

            Aver.IsTrue(map.MapValueMatches("b", "*Fi?her"));
            Aver.IsTrue(map.MapValueMatches("b", "Bobb*Fisher"));
            Aver.IsFalse(map.MapValueMatches("b", "BOB*", senseCase: true));
            Aver.IsTrue(map.MapValueMatches("b", "BOB*"));
            Aver.IsFalse(map.MapValueMatches("b", "*AFisher"));

            Aver.IsTrue(map.MapValueMatches("c", null));
        }
Ejemplo n.º 21
0
        private JsonDataMap getComponentTreeMap(IEnumerable <IApplicationComponent> all, IApplicationComponent cmp, int level, string group = null)
        {
            var cmpTreeMap = new JsonDataMap();

            if (level > 7)
            {
                return(cmpTreeMap);  //cyclical ref
            }
            cmpTreeMap = getComponentMap(cmp, group);

            var children = new JsonDataArray();

            foreach (var child in all.Where(c => object.ReferenceEquals(cmp, c.ComponentDirector)))
            {
                var childMap = getComponentTreeMap(all, child, level + 1, group);
                children.Add(childMap);
            }

            if (children.Count() > 0)
            {
                cmpTreeMap["children"] = children;
            }

            return(cmpTreeMap);
        }
Ejemplo n.º 22
0
        public void JSONDataMapFromURLEncoded_WOAmKey()
        {
            var dict = JsonDataMap.FromURLEncodedString("a");

            Aver.AreEqual(1, dict.Count);
            Aver.AreObjectsEqual(null, dict["a"]);
        }
Ejemplo n.º 23
0
        private JsonDataMap getTemplateJSONDataMap(string template, bool cache)
        {
            JsonDataMap result = null;

            if (cache)
            {
                if (!s_TemplateCache.TryGetValue(template, out result))
                {
                    lock (s_TemplateCacheLock)
                    {
                        if (!s_TemplateCache.TryGetValue(template, out result))
                        {
                            result = compileTemplate(template);
                            var ncache = new Dictionary <string, JsonDataMap>(s_TemplateCache, StringComparer.Ordinal);
                            ncache[template] = result;
                            System.Threading.Thread.MemoryBarrier();
                            s_TemplateCache = ncache;//atomic
                        }
                    }
                }
            }
            else
            {
                result = compileTemplate(template);
            }

            return(result);
        }
Ejemplo n.º 24
0
        public void JSONDataMapFromURLEncoded_DoubleEq()
        {
            var dict = JsonDataMap.FromURLEncodedString("a==1");

            Aver.AreEqual(1, dict.Count);
            Aver.AreObjectsEqual("=1", dict["a"]);
        }
Ejemplo n.º 25
0
        /// <summary>
        /// Converts BSON document to JSON data map by directly mapping
        ///  BSON types into corresponding CLR types. The sub-documents get mapped into JSONDataObjects,
        ///   and BSON arrays get mapped into CLR object[]
        /// </summary>
        public virtual JsonDataMap BSONDocumentToJSONMap(BSONDocument doc, Func <BSONDocument, BSONElement, bool> filter = null)
        {
            if (doc == null)
            {
                return(null);
            }

            var result = new JsonDataMap(true);

            foreach (var elm in doc)
            {
                if (filter != null)
                {
                    if (!filter(doc, elm))
                    {
                        continue;
                    }
                }

                var clrValue = DirectConvertBSONValue(elm, filter);
                result[elm.Name] = clrValue;
            }

            return(result);
        }
Ejemplo n.º 26
0
        public void JSONDataMapFromURLEncoded_1()
        {
            var map = JsonDataMap.FromURLEncodedString("name=Alex&title=Professor");

            Aver.AreObjectsEqual("Alex", map["name"]);
            Aver.AreObjectsEqual("Professor", map["title"]);
        }
Ejemplo n.º 27
0
            public void WriteAsJson(TextWriter wri, int nestingLevel, JsonWritingOptions options = null)
            {
                var map = new JsonDataMap
                {
                    { "utc", Utc.ToMillisecondsSinceUnixEpochStart() },
                    { "ssn", Session },
                    { "app", App },
                    { "ain", AppInstance.ToString("N") },
                    { "h", Host },
                    { "t", Type },
                    { "id", ID.ToString("N") },
                    { "dir", DirectorName },
                    { "cad", CallerAddress },
                    { "cag", CallerAgent },
                    { "cpr", CallerPort }
                };

                var items = m_Items;

                if (items != null)
                {
                    map["items"] = items;
                }

                JsonWriter.WriteMap(wri, map, nestingLevel + 1, options);
            }
Ejemplo n.º 28
0
        public void JSONDataMapFromURLEncoded_2()
        {
            var map = JsonDataMap.FromURLEncodedString("one=a%2Bb+%3E+123&two=Hello+%26+Welcome.");

            Aver.AreObjectsEqual("a+b > 123", map["one"]);
            Aver.AreObjectsEqual("Hello & Welcome.", map["two"]);
        }
Ejemplo n.º 29
0
        /// <summary>
        /// Protected the JWT payload (middle) segment with the default public algorithm
        /// </summary>
        /// <param name="secman">App chassis sec manager</param>
        /// <param name="payload">JWT payload (the middle) segment between '.'</param>
        /// <returns>JWT string like: `header.payload.hash` encoded with base 64 URI scheme</returns>
        public static string PublicProtectJWTPayload(this ISecurityManager secman, JsonDataMap payload)
        {
            var algo   = secman.GetDefaultPublicJWT();
            var result = ProtectJWTPayloadAsString(algo, payload);

            return(result);
        }
Ejemplo n.º 30
0
        public void Options_MapSkipNulls()
        {
            var map = new JsonDataMap();

            map["a"] = 23;
            map["b"] = true;
            map["c"] = null;
            map["d"] = (int?)11;
            map["e"] = "aaa";
            map["f"] = (int?)null;


            var json = JW.Write(map);

            Console.WriteLine(json);

            Aver.AreEqual(@"{""a"":23,""b"":true,""c"":null,""d"":11,""e"":""aaa"",""f"":null}", json);

            json = JW.Write(map, new JsonWritingOptions {
                MapSkipNulls = true
            });

            Console.WriteLine(json);

            Aver.AreEqual(@"{""a"":23,""b"":true,""d"":11,""e"":""aaa""}", json);
        }