Esempio n. 1
0
        static string Sign(JObj jo, string exclude = null)
        {
            StringBuilder sb = new StringBuilder(1024);

            for (int i = 0; i < jo.Count; i++)
            {
                JMbr mbr = jo[i];

                // not include the sign field
                if (exclude != null && mbr.Name == exclude)
                {
                    continue;
                }

                if (sb.Length > 0)
                {
                    sb.Append('&');
                }
                sb.Append(mbr.Name).Append('=').Append((string)mbr);
            }

            sb.Append("&key=").Append(key);

            return(StrUtility.MD5(sb.ToString()));
        }
Esempio n. 2
0
 public void Put(string name, JObj v)
 {
     if (name != null)
     {
         Build(name);
     }
     else
     {
         throw new NotImplementedException();
     }
 }
Esempio n. 3
0
        public static async Task <User> GetUserInfoAsync(string access_token, string openid)
        {
            JObj jo = await WeiXin.GetAsync <JObj>(null, "/sns/userinfo?access_token=" + access_token + "&openid=" + openid + "&lang=zh_CN");

            string nickname = jo[nameof(nickname)];
            string city     = jo[nameof(city)];

            return(new User {
                wx = openid, name = nickname, city = city
            });
        }
Esempio n. 4
0
        /// <summary>
        /// Load the configuration and initialize.
        /// </summary>
        static Application()
        {
            // load app config
            var bytes  = File.ReadAllBytes(APP_JSON);
            var parser = new JsonParser(bytes, bytes.Length);

            app = (JObj)parser.Parse();

            // file-based logger
            int logging = app[nameof(logging)];
            var logfile = DateTime.Now.ToString("yyyyMM") + ".log";

            logger = new FileLogger(logfile)
            {
                Level = logging
            };

            // security
            //
            string crypto = app[nameof(crypto)];

            cryptoKey = CryptoUtility.HexToKey(crypto);

            // string fedkey = app[nameof(fedkey)]; // federal key
            // _fedkey = CryptoUtility.HexToKey(fedkey);

            string certpasswd = app[nameof(certpasswd)]; // X509 certificate

            if (certpasswd != null)
            {
                try
                {
                    cert = new X509Certificate2(File.ReadAllBytes(CERT_PFX), certpasswd);
                }
                catch (Exception e)
                {
                    War(e.Message);
                }
            }

            // nodal cfg
            JObj store = app[nameof(store)];

            if (store != null)
            {
                InitializeStore(store);
            }

            ext = app[nameof(ext)];
        }
Esempio n. 5
0
        static Host()
        {
            // setup logger
            string logfile = DateTime.Now.ToString("yyyyMM") + ".log";

            Logger = new Logger(logfile);
            if (!File.Exists(HOST_JSON))
            {
                Logger.Log(5, null, HOST_JSON + " not found");
                return;
            }

            // load the configuration file
            byte[]     bytes  = File.ReadAllBytes(HOST_JSON);
            JsonParser parser = new JsonParser(bytes, bytes.Length);
            JObj       jo     = (JObj)parser.Parse();

            Config = new HostConfig();
            Config.Read(jo, 0xff);

            if (Config.logging > 0)
            {
                Logger.Level = Config.logging;
            }

            // references
            var r = Config.@ref;

            if (r != null)
            {
                for (int i = 0; i < r.Count; i++)
                {
                    var e = r.EntryAt(i);
                    if (Ref == null)
                    {
                        Ref = new Map <string, WebClient>(16);
                    }
                    Ref.Add(new WebClient(e.Key, e.Value)
                    {
                        Clustered = true
                    });
                }
            }

            Sign = Encrypt(Config.cipher.ToString());
        }
Esempio n. 6
0
        public static IContent BuildPrepayContent(string prepay_id)
        {
            string package   = "prepay_id=" + prepay_id;
            string timeStamp = ((int)(DateTime.Now - EPOCH).TotalSeconds).ToString();

            JObj jo = new JObj
            {
                new JMbr("appId", appid),
                new JMbr("nonceStr", noncestr),
                new JMbr("package", package),
                new JMbr("signType", "MD5"),
                new JMbr("timeStamp", timeStamp),
            };

            jo.Add("paySign", Sign(jo, "paySign"));

            return(jo.Dump());
        }
Esempio n. 7
0
        public static async Task <Accessor> GetAccessorAsync(string code)
        {
            string url = "/sns/oauth2/access_token?appid=" + appid + "&secret=" + appsecret + "&code=" + code + "&grant_type=authorization_code";
            JObj   jo  = await WeiXin.GetAsync <JObj>(null, url);

            if (jo == null)
            {
                return(default(Accessor));
            }

            string access_token = jo[nameof(access_token)];

            if (access_token == null)
            {
                return(default(Accessor));
            }
            string openid = jo[nameof(openid)];

            return(new Accessor(access_token, openid));
        }
Esempio n. 8
0
        internal DbSource(JObj s)
        {
            s.Get(nameof(host), ref host);
            s.Get(nameof(port), ref port);
            s.Get(nameof(database), ref database);
            s.Get(nameof(username), ref username);
            s.Get(nameof(password), ref password);

            // initialize connection string
            //
            var sb = new StringBuilder();

            sb.Append("Host=").Append(host);
            sb.Append(";Port=").Append(port);
            sb.Append(";Database=").Append(database);
            sb.Append(";Username="******";Password="******";Read Buffer Size=").Append(1024 * 32);
            sb.Append(";Write Buffer Size=").Append(1024 * 32);
            sb.Append(";No Reset On Close=").Append(true);

            connstr = sb.ToString();
        }
Esempio n. 9
0
        internal static void InitializeStore(JObj storecfg)
        {
            // create db source
            dbSource = new DbSource(storecfg);

            // create self peer info
            self = new Peer(storecfg)
            {
            };

            // load  peer connectors
            //
            using var dc = NewDbContext();
            dc.Sql("SELECT ").collst(Peer.Empty).T(" FROM peers_ WHERE state > 0");
            var arr = dc.Query <Peer>();

            if (arr != null)
            {
                foreach (var peer in arr)
                {
                    var cli = new FedClient(peer);

                    okayed.TryAdd(cli.Key, cli);

                    // init current block id
                    // await o.PeekLastBlockAsync(dc);
                }
            }

            // start the puller thead
            puller = new Thread(Replicate)
            {
                Name = "Block Puller"
            };
            puller.Start();
        }
Esempio n. 10
0
        JObj ParseObj(ref int pos)
        {
            JObj jo = new JObj();
            int  p  = pos;

            for (;;)
            {
                for (;;)
                {
                    if (p >= length - 1)
                    {
                        throw ParseEx;
                    }
                    int b = this[++p];
                    if (b == ' ' || b == '\t' || b == '\n' || b == '\r')
                    {
                        continue;
                    }
                    if (b == '"')
                    {
                        break;    // meet first quote
                    }
                    if (b == '}') // close early empty
                    {
                        pos = p;
                        return(jo);
                    }
                    throw ParseEx;
                }

                str.Clear(); // parse name
                for (;;)
                {
                    if (p >= length - 1)
                    {
                        throw ParseEx;
                    }
                    int b = this[++p];
                    if (b == '"')
                    {
                        break;           // meet second quote
                    }
                    str.Add((char)b);
                }

                for (;;) // till a colon
                {
                    if (p >= length - 1)
                    {
                        throw ParseEx;
                    }
                    int b = this[++p];
                    if (b == ' ' || b == '\t' || b == '\n' || b == '\r')
                    {
                        continue;
                    }
                    if (b == ':')
                    {
                        break;
                    }
                    throw ParseEx;
                }
                string name = str.ToString();

                // parse the value part
                for (;;)
                {
                    if (p >= length - 1)
                    {
                        throw ParseEx;
                    }
                    int b = this[++p];
                    if (b == ' ' || b == '\t' || b == '\n' || b == '\r')
                    {
                        continue;                                                  // skip ws
                    }
                    if (b == '{')
                    {
                        JObj v = ParseObj(ref p);
                        jo.Add(name, v);
                    }
                    else if (b == '[')
                    {
                        JArr v = ParseArr(ref p);
                        jo.Add(name, v);
                    }
                    else if (b == '"')
                    {
                        string v = ParseString(ref p);
                        jo.Add(name, v);
                    }
                    else if (b == 'n')
                    {
                        if (ParseNull(ref p))
                        {
                            jo.AddNull(name);
                        }
                    }
                    else if (b == 't' || b == 'f')
                    {
                        bool v = ParseBool(ref p, b);
                        jo.Add(name, v);
                    }
                    else if (b == '-' || b >= '0' && b <= '9')
                    {
                        JNumber v = ParseNumber(ref p, b);
                        jo.Add(name, v);
                    }
                    else if (b == '&') // bytes extension
                    {
                        byte[] v = ParseBytes(p);
                        jo.Add(name, v);
                    }
                    else
                    {
                        throw ParseEx;
                    }
                    break;
                }

                // comma or end
                for (;;)
                {
                    if (p >= length - 1)
                    {
                        throw ParseEx;
                    }
                    int b = this[++p];
                    if (b == ' ' || b == '\t' || b == '\n' || b == '\r')
                    {
                        continue;
                    }
                    if (b == ',')
                    {
                        break;
                    }
                    if (b == '}') // close normal
                    {
                        pos = p;
                        return(jo);
                    }
                    throw ParseEx;
                }
            }
        }
Esempio n. 11
0
        JArr ParseArr(ref int pos)
        {
            JArr ja = new JArr();
            int  p  = pos;

            for (;;)
            {
                if (p >= length - 1)
                {
                    throw ParseEx;
                }
                int b = this[++p];
                if (b == ' ' || b == '\t' || b == '\n' || b == '\r')
                {
                    continue; // skip ws
                }
                if (b == ']') // close early empty
                {
                    pos = p;
                    return(ja);
                }
                if (b == '{')
                {
                    JObj v = ParseObj(ref p);
                    ja.Add(new JMbr(null, v));
                }
                else if (b == '[')
                {
                    JArr v = ParseArr(ref p);
                    ja.Add(new JMbr(null, v));
                }
                else if (b == '"')
                {
                    string v = ParseString(ref p);
                    ja.Add(new JMbr(null, v));
                }
                else if (b == 'n')
                {
                    if (ParseNull(ref p))
                    {
                        ja.Add(new JMbr());
                    }
                }
                else if (b == 't' || b == 'f')
                {
                    bool v = ParseBool(ref p, b);
                    ja.Add(new JMbr(null, v));
                }
                else if (b == '-' || b >= '0' && b <= '9')
                {
                    JNumber v = ParseNumber(ref p, b);
                    ja.Add(new JMbr(null, v));
                }
                else if (b == '&') // bytes extension
                {
                    byte[] v = ParseBytes(p);
                    ja.Add(new JMbr(null, v));
                }
                else
                {
                    throw ParseEx;
                }

                // comma or return
                for (;;)
                {
                    if (p >= length - 1)
                    {
                        throw ParseEx;
                    }
                    b = this[++p];
                    if (b == ' ' || b == '\t' || b == '\n' || b == '\r')
                    {
                        continue;                                                  // skip ws
                    }
                    if (b == ',')
                    {
                        break;
                    }
                    if (b == ']') // close normal
                    {
                        pos = p;
                        return(ja);
                    }
                    throw ParseEx;
                }
            }
        }
Esempio n. 12
0
        internal DbSource(JObj s)
        {
            s.Get(nameof(host), ref host);
            s.Get(nameof(port), ref port);
            s.Get(nameof(database), ref database);
            s.Get(nameof(username), ref username);
            s.Get(nameof(password), ref password);

            // initialize connection string
            //
            var sb = new StringBuilder();

            sb.Append("Host=").Append(host);
            sb.Append(";Port=").Append(port);
            sb.Append(";Database=").Append(database);
            sb.Append(";Username="******";Password="******";Read Buffer Size=").Append(1024 * 32);
            sb.Append(";Write Buffer Size=").Append(1024 * 32);
            sb.Append(";No Reset On Close=").Append(true);

            connstr = sb.ToString();

            // load public composite types
            //
            using (var dc = NewDbContext())
            {
                // composite types
                dc.QueryAll("SELECT t.oid, t.typname, t.typarray FROM pg_type t, pg_class c WHERE t.oid = c.reltype AND c.relkind = 'c'");
                while (dc.Next())
                {
                    dc.Let(out uint oid);
                    dc.Let(out string name);
                    dc.Let(out uint typarray);
                    composites.Add(new DbType(oid, name, typarray)
                    {
                        Converter = (n, src, snk) =>
                        {
                            JObj v = null;
                            src.Get(n, ref v);
                            snk.Put(n, v);
                        }
                    });
                }

                // add columns and the related array type
                int count = composites.Count;
                for (int i = 0; i < count; i++)
                {
                    var comp = composites[i].Value;
                    dc.QueryAll("SELECT attname AS name, atttypid AS typoid, atthasdef AS def, attnotnull AS notnull FROM pg_attribute WHERE attrelid = @1", p => p.Set(comp.Key));
                    while (dc.Next())
                    {
                        comp.AddColumn(new DbField(dc));
                    }

                    // the corresponding array type
                    dc.Query("SELECT oid, typname, typarray FROM pg_type WHERE oid = @1", p => p.Set(comp.arrayoid));
                    dc.Let(out uint oid);
                    dc.Let(out string name);
                    composites.Add(new DbType(oid, name)
                    {
                        ElementType = comp,
                        Converter   = (n, src, snk) =>
                        {
                            JArr v = null;
                            src.Get(n, ref v);
                            snk.Put(n, v);
                        }
                    });
                }
            }
        }
Esempio n. 13
0
        public override async Task OperateAsync(WebContext wc, string method, string[] vars, string subscript)
        {
            var sql = new StringBuilder();

            // set vars as session variables
            for (int i = 0; i < Vars?.Count; i++)
            {
                var v = Vars[i];
                sql.Append("SET ").Append(v.Name).Append(" = @").Append(vars[i]).Append(";");
            }

            if (method == "GET")
            {
                sql.Append("SELECT * FROM ").Append(Name);

                using (var dc = Source.NewDbContext())
                {
                    await dc.QueryAsync(sql.ToString());

                    var cnt = Dump(dc, false);
                    wc.Give(200, cnt);
                }
            }
            else if (method == "POST")
            {
                sql.Append("INSERT INTO ").Append(Name).Append(" (");
                for (int i = 0; i < columns.Count; i++)
                {
                    if (i > 0)
                    {
                        sql.Append(", ");
                    }

                    var col = columns[i].Value;
                    sql.Append(col.Name);
                }

                sql.Append(") VALUES (");
                for (int i = 0; i < columns.Count; i++)
                {
                    if (i > 0)
                    {
                        sql.Append(", ");
                    }

                    var col = columns[i].Value;
                    sql.Append("@").Append(col.Name);
                }

                sql.Append(");");


                JObj f = await wc.ReadAsync <JObj>();

                // execute with parameters
                //
                using (var dc = Source.NewDbContext())
                {
                    await dc.ExecuteAsync(p =>
                    {
                        for (int i = 0; i < columns.Count; i++)
                        {
                            var col = columns[i].Value;
                            col.Convert(f, dc);
                        }
                    });
                }
            }
            else if (method == "PUT")
            {
                sql.Append("UPDATE ").Append(Name).Append(" SET ");
            }
            else if (method == "DELETE")
            {
                var f     = wc.Query;
                var idcol = columns[0].value;

                sql.Append("DELETE FROM ").Append(Name).Append(" WHERE ");
                sql.Append(idcol.Name).Append(" = @").Append(idcol.Name);

                using (var dc = Source.NewDbContext())
                {
                    await dc.ExecuteAsync(p => { idcol.Convert(f, dc); });
                }
            }
        }
Esempio n. 14
0
        public object getJSONObject(string strJSON
                                    , Type objType = null)
        {
            JObject objJSON = JObject.Parse(strJSON);
            object  obj     = createObject(objJSON, objType);

            if (obj == null)
            {
                return(null);
            }

            ///////////////////////////////////////////////////////

            Type   memberType = null;
            object objMember  = null;

            foreach (var f in objJSON)
            {
                switch (f.Value.Type.ToString())
                {
                case "String":
                case "Float":
                case "Integer":
                case "Boolean":
                    setPropertyValue(obj, f.Key, f.Value.ToString());
                    break;

                case "Object":

                    memberType = getMemberDeclaringType(obj, f.Key);

                    if (memberType != null)
                    {
                        objMember = getJSONObject(f.Value.ToString(), memberType);
                        setPropertyValue(obj, f.Key, objMember);
                    }
                    break;

                case "Array":
                    memberType = getMemberDeclaringType(obj, f.Key);

                    if (memberType != null)
                    {
                        Type memberListType = getMemberDeclaringType(obj, f.Key).GetGenericArguments()[0];
                        objMember = Activator.CreateInstance(memberType);
                        setPropertyValue(obj, f.Key, objMember);

                        JArray arr          = f.Value as JArray;
                        object arrayElement = null;

                        foreach (var JObj in arr)
                        {
                            switch (JObj.Type.ToString())
                            {
                            case "String":
                                arrayElement = JObj.ToString();
                                objMember.GetType().GetMethod("Add").Invoke(objMember, new object[] { arrayElement });
                                break;

                            case "Object":
                                arrayElement = getJSONObject(JObj.ToString(), memberListType);
                                objMember.GetType().GetMethod("Add").Invoke(objMember, new object[] { arrayElement });
                                break;
                            }
                        }
                    }
                    break;
                }
            }

            return(obj);
        }