Esempio n. 1
0
        public void TestSessionReq()
        {
            // formatLogin: {a: "login", logid: logId, pswd: tokenB64, iv: ivB64};
            AnsonMsg reqv11 = AnSessionReq.formatLogin(uid, tk64, iv64);

            MemoryStream stream = new MemoryStream();

            reqv11.ToBlock(stream);
            string json = Utils.ToString(stream);

            // json:
            // {type: io.odysz.anson.jprotocol.AnsonMsg,
            //  code: null, opts: null,
            //  port: "session",
            //  header: null, vestion: "1.0",
            //  body: [{type: io.odysz.anson.jprotocol.AnSessionReq,
            //          uid: "test-id",
            //          parent: "io.odysz.anson.jprotocol.AnsonMsg",
            //          a: "login", conn: null,
            //          iv: "iv: I'm base64", mds: null,
            //          token: "tk: I'm base64"}], seq: 909}
            AnsonMsg msg = (AnsonMsg)Anson.FromJson(json);

            Assert.AreEqual(reqv11.code, msg.code);
            Assert.AreEqual(reqv11.port.name, msg.port.name);
            Assert.AreEqual(((AnSessionReq)reqv11.Body(0)).iv, ((AnSessionReq)msg.Body(0)).iv);
            Assert.AreEqual(((AnSessionReq)reqv11.Body(0)).token, ((AnSessionReq)msg.Body(0)).token);
        }
Esempio n. 2
0
        public async Task Commit_async(AnsonMsg req, OnOk onOk, OnError onErr = null)
        {
            HttpServClient httpClient = new HttpServClient();
            AnsonMsg       msg        = await httpClient.Post(AnClient.ServUrl((Port)req.port), req);

            MsgCode code = msg.code;

            if (AnClient.console)
            {
                System.Console.Out.WriteLine(msg.ToString());
            }

            if (MsgCode.ok == code.code)
            {
                onOk.ok((AnsonResp)msg.Body(0));
            }
            else
            {
                if (onErr != null)
                {
                    onErr.err(code, ((AnsonResp)msg.Body(0)).Msg());
                }
                else
                {
                    System.Console.Error.WriteLine("code: {0}\nerror: {1}",
                                                   code, msg.ToString());
                }
            }
        }
Esempio n. 3
0
        /// <summary>
        /// Submit transaction requist to jserv. This method is synchronized - not returned until callbacks been called.
        /// </summary>
        /// <param name="req"></param>
        /// <param name="onOk"></param>
        /// <param name="onErr"></param>
        public void CommitAsync(AnsonMsg req, OnOk onOk, OnError onErr = null, CancellationTokenSource waker = null)
        {
            Task t = Task.Run(async delegate
            {
                try
                {
                    HttpServClient httpClient = new HttpServClient();
                    AnsonMsg msg = await httpClient.Post(AnClient.ServUrl((Port)req.port), req);
                    MsgCode code = msg.code;

                    if (MsgCode.ok == code.code)
                    {
                        onOk.ok((AnsonResp)msg.Body(0));
                    }
                    else
                    {
                        if (onErr != null)
                        {
                            onErr.err(code, ((AnsonResp)msg.Body(0)).Msg());
                        }
                        else
                        {
                            Debug.WriteLine("Error: code: {0}\nerror: {1}",
                                            code, msg.ToString());
                        }
                    }
                }
                catch (Exception _) { }
                finally { if (waker != null)
                          {
                              waker.Cancel();
                          }
                }
            });
        }
Esempio n. 4
0
        /// <summary>
        /// Login and return a client instance (with session managed by jserv).
        /// </summary>
        /// <param name="uid"></param>
        /// <paramref name="pswdPlain">password in plain</param>
        /// <param name="device"></param>
        /// <param name="onlogin"></param>
        /// <param name="err"></param>
        /// <throws>SQLException the request makes server generate wrong SQL.</throws>
        /// <throws>SemanticException Request can not parsed correctly</throws>
        /// <throws>GeneralSecurityException  other error</throws>
        /// <throws>Exception, most likely the network failed</throws>
        /// <return>null if failed, a SessionClient instance if login succeed.</return>
        public static async Task <SessionClient> Login(string uid, string pswdPlain, string device,
                                                       OnLogin onlogin, OnError err = null)
        {
            byte[] iv   = AESHelper.getRandom();
            string iv64 = AESHelper.Encode64(iv);

            if (uid == null || pswdPlain == null)
            {
                throw new SemanticException("user id and password can not be null.");
            }

            // string tk64 = AESHelper.Encrypt("-----------" + uid, pswdPlain, iv);
            string tk64 = AESHelper.Encrypt(uid, pswdPlain, iv);

            // formatLogin: {a: "login", logid: logId, pswd: tokenB64, iv: ivB64};
            // AnsonMsg<? extends AnsonBody> reqv11 = new AnsonMsg<AnQueryReq>(Port.session);;
            AnsonMsg reqv11 = AnSessionReq.formatLogin(uid, tk64, iv64, device);

            string         url        = ServUrl(new Port(Port.session));
            HttpServClient httpClient = new HttpServClient();

            SessionClient[] inst = new SessionClient[1];
            AnsonMsg        msg  = await httpClient.Post(url, reqv11).ConfigureAwait(false);

            MsgCode code = msg.code;

            if (code != null && MsgCode.ok == code.code)
            {
                // create a logged in client
                inst[0] = new SessionClient(((AnSessionResp)msg.Body()[0]).ssInf);
                if (onlogin != null)
                {
                    // onlogin.ok(new SessionClient(((AnSessionResp)msg.Body()[0]).ssInf));
                    onlogin.ok(inst[0]);
                }

                if (AnClient.console)
                {
                    Console.WriteLine(msg.ToString());
                }
            }
            else if (err != null)
            {
                err.err(new MsgCode(code.code), ((AnsonResp)msg.Body(0)).Msg());
            }
            else
            {
                throw new SemanticException(
                          "loging failed\ncode: {0}\nerror: {1}",
                          code, ((AnsonResp)msg.Body()[0]).Msg());
            }
            return(inst[0]);
        }
Esempio n. 5
0
        /// <summary>
        /// Upload files to "a_attaches" table. Before files been saved, all files attached to
        /// the recid will been deleted. (This is supported by the semantic-DA samantics configuration)
        /// <p><b>FIXME:</b></p>
        /// this method used 2 round of memory copy, should implemented in stream style
        /// </summary>
        /// <param name="files"></param>
        /// <param name="busiTbl">business table to which file is attached, e.g. "a_users"</param>
        /// <param name="recid">business record Id to which file is owned, e.g. "admin"</param>
        public void AttachFiles(List <string> files, string busiTbl, string recid,
                                Action <MsgCode, AnsonResp> onOk = null, Action <MsgCode, AnsonResp> onErr = null)
        {
            AnsonMsg    jmsg = Delete(null, "a_attaches");
            AnUpdateReq del  = (AnUpdateReq)jmsg.Body(0);

            del.WhereEq("busiTbl", busiTbl)
            .WhereEq("busiId", recid);

            foreach (string file in files)
            {
                byte[] f   = File.ReadAllBytes(file);
                string fn  = Path.GetFileName(file);
                string b64 = AESHelper.Encode64(f);
                del.Post(AnInsertReq
                         .formatInsertReq(null, null, "a_attaches")
                         .Cols("attName", "busiId", "busiTbl", "uri")
                         .Nv("attName", fn)
                         .Nv("busiId", recid)
                         .Nv("busiTbl", busiTbl)
                         .Nv("uri", b64));
            }

            jmsg.Header(Header());

            Console(jmsg);

            Commit(jmsg,
                   (code, data) => {
                if (MsgCode.ok == code.code)
                {
                    if (onOk != null)
                    {
                        onOk(code, (AnsonResp)data.Body(0));
                    }
                    else
                    {
                        Utils.Logi(code.ToString());
                    }
                }
                else if (onErr != null)
                {
                    onErr(code, (AnsonResp)data.Body(0));
                }
                else
                {
                    Utils.Warn(data.ToString());
                }
            },
                   onErr: (c, err) => {
                if (onErr != null)
                {
                    onErr(c, err);
                }
                else
                {
                    Utils.Warn(string.Format(@"code: {0}, error: {1}", c, err.Msg()));
                }
            });
        }
Esempio n. 6
0
        /// <summary>Format login request message.</summary>
        /// <param name="uid"/>
        /// <param name="tk64"/>
        /// <param name="iv64"/>
        /// <returns>login request message</returns>
        public static AnsonMsg formatLogin(string uid, string tk64, string iv64)
        {
            // AnSessionReq : AnsonBody
            AnsonMsg     jmsg = new AnsonMsg(new Port(Port.session), null);
            AnSessionReq itm  = new AnSessionReq(jmsg);

            itm.setup(uid, tk64, iv64);
            itm.A("login");

            jmsg.Body((AnsonBody)itm);
            return(jmsg);
        }
Esempio n. 7
0
        public AnsonResp Commit(AnsonMsg req, ErrorCtx err = null)
        {
            HttpServClient  httpClient = new HttpServClient();
            Task <AnsonMsg> tmsg       = httpClient.Post(AnClient.ServUrl((Port)req.port), req);

            tmsg.Wait();
            AnsonMsg msg  = tmsg.Result;
            MsgCode  code = msg.code;

            if (MsgCode.ok != code.code)
            {
                if (err != null)
                {
                    err.onError(code, ((AnsonResp)msg.Body(0)).Msg());
                }
                else
                {
                    Debug.WriteLine("Error: code: {0}\nerror: {1}",
                                    code, msg.ToString());
                }
            }

            return((AnsonResp)msg.Body(0));
        }
Esempio n. 8
0
        public AnsonMsg UserReq(string uri, IPort port, string[] act, AnsonBody req)
        {
            if (ssInf == null)
            {
                throw new SemanticException("SessionClient can not visit jserv without session information.");
            }

            AnsonMsg jmsg = new AnsonMsg(port, null);

            if (act != null)
            {
                Header().act(act);
            }
            jmsg.Header(header);
            jmsg.Body(req, uri);

            return(jmsg);
        }
Esempio n. 9
0
        static void UploadTransaction(CancellationTokenSource waker, AnsonClient client, string p)
        {
            // string p = Path.get(filename);
            byte[] f   = File.ReadAllBytes(p);
            string b64 = AESHelper.Encode64(f);

            AnsonMsg    jmsg = client.Update(null, "a_users");
            AnUpdateReq upd  = (AnUpdateReq)jmsg.Body(0);

            upd.Nv("nationId", "CN")
            .WhereEq("userId", "admin")
            // .post(((UpdateReq) new UpdateReq(null, "a_attach")
            .Post(AnUpdateReq.formatDelReq(null, null, "a_attaches")
                  .WhereEq("busiTbl", "a_users")
                  .WhereEq("busiId", "admin")
                  .Post((AnInsertReq.formatInsertReq(null, null, "a_attaches")
                         .Cols("attName", "busiId", "busiTbl", "uri")
                         .Nv("attName", "-Anclient.cs Test")
                         // The parent pk can't be resulved, we must provide the value.
                         // See https://odys-z.github.io/notes/semantics/best-practices.html#fk-ins-cate
                         .Nv("busiId", "admin")
                         .Nv("busiTbl", "a_users")
                         .Nv("uri", b64))));

            jmsg.Header(client.Header());

            client.Console(jmsg);

            client.Commit(jmsg,
                          (code, data) => {
                if (MsgCode.ok == code.code)
                {
                    Utils.Logi(code.ToString());
                }
                else
                {
                    Utils.Warn(data.ToString());
                }
            },
                          onErr: (c, err) => {
                Assert.Fail(string.Format(@"code: {0}, error: {1}", c, err.Msg()));
            },
                          waker);
        }
Esempio n. 10
0
        /// <summary>Format a query request object, including all information for
        /// construct a "select" statement.</summary>
        /// <param name="uri"></param>
        /// <param name="tbl"></param>
        /// <param name="alias">main table alias</param>
        /// <param name="page">page, -1 for no paging at server side.</param>
        /// <param name="size"></param>
        /// <param name="funcId">current function ID</param>
        /// <returns>formatted query object</returns>
        public AnsonMsg query(string uri, string tbl, string alias,
                              int page, int size, string funcId = null)
        {
            AnsonMsg msg = new AnsonMsg((IPort) new Port(Port.query), null);

            AnsonHeader header = new AnsonHeader(ssInf.ssid, ssInf.uid);

            if (funcId != null && funcId.Length > 0)
            {
                header.UsrAct(funcId, "query", "R", "test");
            }

            msg.Header(header);

            AnQueryReq itm = AnQueryReq.formatReq(uri, msg, tbl, alias);

            msg.Body(itm, uri);
            itm.Page(page, size);

            return(msg);
        }
Esempio n. 11
0
        public void TestAnsonResp()
        {
            AnsonMsg respmsg = (AnsonMsg)Anson.FromJson(respjson);

            Assert.AreEqual("ok", respmsg.code.Name());
            Assert.AreEqual(Port.update, respmsg.port.port());

            AnsonResp resp = (AnsonResp)respmsg.Body(0);

            Assert.IsNotNull(resp);
            Assert.IsNotNull(resp.map);
            SemanticObject resulved = (SemanticObject)resp.map["resulved"];

            Assert.IsNotNull(resulved);

            IDictionary    props  = resulved.props;
            SemanticObject attach = (SemanticObject)props["a_attaches"];

            Assert.IsNotNull(attach.props);
            Assert.AreEqual("00000D", attach.props["attId"]);
        }
Esempio n. 12
0
        public string streamdown(string url, AnsonMsg jreq, string localpath)
        {
            HttpWebRequest  req = (HttpWebRequest)WebRequest.Create(url);
            HttpWebResponse con = (HttpWebResponse)req.GetResponse();

            //add reuqest header
            req.Method    = "POST";
            req.UserAgent = USER_AGENT;
            // req.setRequestProperty("Accept-Language", "en-US,en;q=0.5");
            req.Headers.Add("Accept-Language", "fr,fr-FR;q=0.8,en-US;q=0.5,en;q=0.3");
            // con.setRequestProperty("Content-Type", "text/plain");
            req.ContentType = "text/plain";
            // con.setRequestProperty("charset", "utf-8");
            req.TransferEncoding = "utf-8";

            // Send post request
            // con.setDoOutput(true);
            using (Stream stream = req.GetResponse().GetResponseStream())
            {
                jreq.ToBlock(stream);
            }

            if (AnClient.verbose)
            {
                Utils.Logi(url);
            }

            Stream     ins = con.GetResponseStream();
            FileStream ofs = new FileStream(localpath, FileMode.OpenOrCreate);

            ins.CopyTo(ofs);
            ofs.Close();

            AnsonMsg s    = null;
            string   type = null;

            try {
                // FileInputStream ifs = new FileInputStream(localpath);
                // type = detector.detect(ifs);
                // ifs.close();
                if (localpath.EndsWith(".json"))
                {
                    type = "json";
                }
            }
            catch (Exception e) {
                return(localpath);
            }

            if (type != null && type.StartsWith("json"))
            {
                FileStream ifs = new FileStream(localpath, FileMode.OpenOrCreate);
                try
                {
                    s = (AnsonMsg)Anson.FromJson(ifs);
                }
                catch (Exception e)
                {
                    return(localpath);
                }
                finally { ifs.Close(); }
                throw new SemanticException("Code: %s\nmsg: %s", s.code, ((AnsonResp)s.Body(0)).Msg());
            }

            return(localpath);
        }