/**Get a photo record (this synchronous file base64 content) * @param docId * @param onErr * @return response */ public AlbumResp selectPhotoRec(string docId, ErrorCtx err = null) { ErrorCtx errHandler = err == null ? errCtx : err; AnsonHeader header = client.Header().act("album.c#", "synch", "c/photo", "multi synch"); AlbumReq req = new AlbumReq().selectPhoto(docId); AlbumResp resp = null; try { AnsonMsg q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req) .Header(header); resp = (AlbumResp)client.Commit(q, errCtx); } catch (Exception e) { if (e is AnsonException || e is SemanticException) { errHandler.onError(new MsgCode(MsgCode.exSemantic), e.Message + " " + e.Source == null ? "" : e.Source.GetType().Name); } else { errHandler.onError(new MsgCode(MsgCode.exIo), e.Message + " " + e.Source == null ? "" : e.Source.GetType().Name); } } return(resp); }
/// <summary> /// Asynchronously query synchronizing records. /// </summary> /// <param name="files"></param> /// <param name="page"></param> /// <param name="onOk"></param> /// <param name="onErr"></param> /// <returns>this</returns> public AlbumClientier asyncQuerySyncs(IList <IFileDescriptor> files, SyncingPage page, OnOk onOk, OnError onErr) { Task.Run(() => { DocsResp resp = null; try { AnsonHeader header = client.Header().act("album.c#", "query", "r/states", "query sync"); List <DocsResp> reslts = new List <DocsResp>(files.Count); AlbumReq req = (AlbumReq) new AlbumReq().Syncing(page).A(A.selectSyncs); for (int i = page.start; i < page.end & i < files.Count; i++) { IFileDescriptor p = files[i]; req.querySync(p); } AnsonMsg q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req) .Header(header); resp = (DocsResp)client.Commit(q, errCtx); reslts.Add(resp); onOk.ok(resp); } catch (Exception e) { onErr.err(new MsgCode(MsgCode.exIo), uri, new string[] { e.GetType().Name, e.Message }); } }); return(this); }
/// <summary> /// Asynchronously synchronize photos /// </summary> /// <param name="photos"></param> /// <param name="user"></param> /// <param name="onOk"></param> /// <param name="onErr"></param> /// <exception cref="SemanticException"></exception> /// <exception cref="SemanticException"></exception> /// <exception cref="IOException"></exception> /// <exception cref="AnsonException"></exception> public void asyncPhotos(List <IFileDescriptor> photos, SessionInf user, OnOk onOk, OnError onErr) { DocsResp resp = null; try { AnsonHeader header = client.Header().act("album.c#", "synch", "c/photo", "multi synch"); List <DocsResp> reslts = new List <DocsResp>(photos.Count); foreach (IFileDescriptor p in photos) { AlbumReq req = new AlbumReq() .createPhoto(p, user); AnsonMsg q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req) .Header(header); Task <AnsonResp> tresp = (Task <AnsonResp>)client.Commit_async(q, null, onErr); tresp.Wait(); reslts.Add((DocsResp)tresp.Result); } onOk.ok(resp); } catch (Exception e) { onErr.err(new MsgCode(MsgCode.exIo), string.Format("%s, %s", e.GetType().Name, e.Message)); } }
/// <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(); } } }); }
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()); } } }
/// <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())); } }); }
public DocsResp del(string device, string clientpath) { AlbumReq req = new AlbumReq().del(device, clientpath); DocsResp resp = null; try { AnsonHeader header = client.Header().act("album.c#", "del", "d/photo", ""); AnsonMsg q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req) .Header(header); resp = (DocsResp)client.Commit(q, errCtx); } catch (Exception e) { if (e is AnsonException || e is SemanticException) { errCtx.onError(new MsgCode(MsgCode.exSemantic), e.Message + " " + e.Source == null ? "" : e.Source.GetType().Name); } else { errCtx.onError(new MsgCode(MsgCode.exIo), e.Message + " " + e.Source == null ? "" : e.Source.GetType().Name); } } return(resp); }
/// <summary> /// Js equivalent: Ajax. /// We use HttpClient, see https://stackoverflow.com/a/4015346/7362888 /// </summary> /// <param name="url"></param> /// <param name="req"></param> /// <param name="onResp"></param> internal async Task <AnsonMsg> Post(string url, AnsonMsg req) { using (var client = new HttpClient()) { try { // what about http stream? MemoryStream s = new MemoryStream(); req.ToBlock(s); StringContent payload = new StringContent(anson.Utils.ToString(s), Encoding.UTF8, "application/json"); HttpResponseMessage jresponse = await client.PostAsync(url, payload).ConfigureAwait(false); AnsonMsg resp = (AnsonMsg)Anson.FromJson(await jresponse.Content.ReadAsStringAsync()); // onResp(resp.code, resp); return(resp); } catch (Exception ex) { Debug.WriteLine(ex.StackTrace); // throw new IOException(ex.Message); return(new AnsonMsg(req.port, new MsgCode(MsgCode.exIo)) .Body(new AnsonResp(null, ex.Message), null)); } } }
/// <summary>Format an insert request.</summary> /// <param name="conn"/> /// <param name="parent"/> /// <param name="tabl"/> /// <param name="cmd"> /// /// <see cref="JProtocol.CRUD"/> /// .C R U D /// </param> /// <returns>a new update request</returns> public static AnInsertReq formatInsertReq(string conn, AnsonMsg parent, string tabl) { AnInsertReq bdItem = (AnInsertReq) new AnInsertReq(parent, conn).A(JProtocol.CRUD.C); bdItem.mtabl = tabl; return(bdItem); }
/* * public virtual AnQueryReq j(string with, string @as, string on) * { * return j("j", with, @as, on); * } * * public virtual AnQueryReq l(string with, string @as, string on) * { * return j("l", with, @as, on); * } * * public virtual AnQueryReq r(string with, string @as, string on) * { * return j("R", with, @as, on); * } * * public virtual AnQueryReq j(List <string[]> joins) * { * if (joins != null) * { * foreach (string[] join in joins) * { * j(join); * } * } * return this; * } * * public virtual AnQueryReq j(string t, string with, string @as, string on) * { * if (joins == null) * { * joins = new List<string[]>(); * } * string[] joining = new string[Query.Ix.joinSize]; * joining[Query.Ix.joinTabl] = with; * joining[Query.Ix.joinAlias] = @as; * joining[Query.Ix.joinType] = t; * joining[Query.Ix.joinOnCond] = on; * return j(joining); * } * * private AnQueryReq j(string[] join) * { * joins.Add(join); * return this; * } * * public virtual AnQueryReq expr(string expr, string alias, params string[] tabl) * { * if (exprs == null) * { * exprs = new List<string[]>(); * } * string[] exp = new string[Query.Ix.exprSize]; * exp[Query.Ix.exprExpr] = expr; * exp[Query.Ix.exprAlais] = alias; * exp[Query.Ix.exprTabl] = tabl == null || tabl.Length == 0 ? * null : tabl[0]; * exprs.Add(exp); * return this; * } * * public virtual AnQueryReq Where(string oper, string lop, string rop) * { * if (where == null) * { * where = new List<string[]>(); * } * string[] predicate = new string[Query.Ix.predicateSize]; * predicate[Query.Ix.predicateOper] = oper; * predicate[Query.Ix.predicateL] = lop; * predicate[Query.Ix.predicateR] = rop; * where.Add(predicate); * return this; * } * * public virtual AnQueryReq orderby(string col, params bool[] asc) * { * if (orders == null) * { * orders = new List<string[]>(); * } * orders.Add(new string[] { col, asc == null || asc.Length == 0 ? "asc" : asc[0] ? "asc" : "desc" }); * return this; * } */ /// <summary> /// <p>Create a qeury request body item, for joining etc.</p> /// <p>This is a client side helper, don't confused with /// <see cref="Query">Query</see> /// .</p> /// </summary> /// <param name="conn"/> /// <param name="parent"/> /// <param name="from"></param> /// <param name="as"></param> /// <returns>query request</returns> public static AnQueryReq formatReq(string conn, AnsonMsg parent, string from, params string[] @as) { AnQueryReq bdItem = new AnQueryReq (parent, conn, from, @as == null || @as.Length == 0 ? null : @as[0]); return(bdItem); }
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); }
/// <summary>Format an insert request.</summary> /// <param name="parent"/> /// <param name="tabl"/> /// <param name="uri"/> /// /// <see cref="JProtocol.CRUD"/> /// .C R U D /// </param> /// <returns>a new update request</returns> public static AnInsertReq formatInsertReq(AnsonMsg parent, string tabl, string uri) { AnInsertReq bdItem = (AnInsertReq) new AnInsertReq(uri, parent).A(JProtocol.CRUD.C); bdItem.mtabl = tabl; return(bdItem); }
// public virtual string sk() { return sk; } public static AnDatasetReq formatReq(string conn, AnsonMsg parent, string sk) { AnDatasetReq bdItem = new AnDatasetReq(parent, conn); bdItem.sk = sk; return(bdItem); }
public static AnDatasetReq formatReq(string uri, AnsonMsg parent, string sk) { AnDatasetReq bdItem = new AnDatasetReq(uri, parent); bdItem.sk = sk; return(bdItem); }
/// <summary> /// <p>Create a qeury request body item, for joining etc.</p> /// <p>This is a client side helper, don't confused with /// <see cref="Query">Query</see> /// .</p> /// </summary> /// <param name="uri"/> /// <param name="parent"/> /// <param name="from"></param> /// <param name="asTabl"></param> /// <returns>query request</returns> public static AnQueryReq formatReq(string uri, AnsonMsg parent, string from, params string[] asTabl) { AnQueryReq bdItem = new AnQueryReq(uri, parent, from, asTabl == null || asTabl.Length == 0 ? null : asTabl[0]); return(bdItem); }
public string download(string uri, IPort port, DocsReq body, string localpath, string[] act = null) { if (port == null) { throw new AnsonException("AnsonMsg<DocsReq> needs port explicitly specified."); } // let header = Protocol.formatHeader(this.ssInf); body.Uri(uri); if (act != null && act.Length > 0) { header.act(act); } AnsonMsg msg = new AnsonMsg(port.name) .Header(header) .Body(body, uri); if (AnClient.verbose) { Utils.Logi(msg.ToString()); } HttpServClient httpClient = new HttpServClient(); return(httpClient.streamdown(AnClient.ServUrl(port), msg, localpath)); }
public AlbumClientier getSettings(OnOk onOk, OnError onErr) { Task.Run(() => { try { AnsonHeader header = client .Header() .UsrAct("album.c#", "profile", "r/settings", "load profile"); AlbumReq req = new AlbumReq(uri); req.A(A.getPrefs); AnsonMsg q = client .UserReq(uri, new AlbumPort(AlbumPort.album), null, req) .Header(header); client.CommitAsync(q, onOk, onErr); } catch (Exception e) { onErr.err(new MsgCode(MsgCode.exIo), string.Format("%s\n%s", e.GetType().Name, e.Message)); } }); return(this); }
/// <summary>Format a delete request.</summary> /// <param name="uri"/> /// <param name="parent"/> /// <param name="tabl"/> /// <returns>a new deleting request</returns> public static AnUpdateReq formatDelReq(string uri, AnsonMsg parent, string tabl) { AnUpdateReq bdItem = ((AnUpdateReq) new AnUpdateReq(uri, parent) .A(JProtocol.CRUD.D)) .Mtabl(tabl); return(bdItem); }
public AnQueryReq(AnsonMsg parent, string conn, string fromTbl, params string[] alias) : base(parent, conn) { a = JProtocol.CRUD.R; mtabl = fromTbl; mAlias = alias == null || alias.Length == 0 ? null : alias[0]; Page(-1, 0); }
public AnSessionResp(AnsonMsg parent, SessionInf ssInf) : base(parent) { // TODO built-in role? // if (roleId != null && roleId.length > 0) // ssInf.roleId = roleId[0]; this.ssInf = ssInf; }
public AnSessionResp(AnsonMsg parent, string ssid, string uid, params string[] roleId) : base(parent) { ssInf = new SessionInf(ssid, uid, roleId == null || roleId .Length == 0 ? null : roleId[0]); //ssInf.ssid = ssid; //ssInf.uid = uid; }
/// <exception cref="AnsonException"/> /// <exception cref="System.IO.IOException"/> //public override Anson toBlock(java.io.OutputStream stream, params // io.odysz.anson.JsonOpt[] opts) //{ // if (jprotocol.JProtocol.CRUD.C.Equals(a) && (cols == null || cols // .Length == 0)) // { // io.odysz.common.Utils.warn("WARN - UpdateReq.toJson():\nFound inserting request but cols are null, this is wrong for no insert statement can be generated.\n" // + "Suggestion: call the InsertReq.col(col-name) before serialize this to json for table: %s\n" // + "Another common error leads to this is using UpdateReq for inserting with java client." // , mtabl); // } // return base.toBlock(stream, opts); //} /// <summary>Format an update request.</summary> /// <param name="conn"/> /// <param name="parent"/> /// <param name="tabl"/> /// <param name="cmd"> /// <see cref="JProtocol.CRUD"/>.C R U D /// </param> /// <returns>a new update request</returns> public static AnUpdateReq FormatUpdateReq(string conn, AnsonMsg parent, string tabl) { AnUpdateReq bdItem = ((AnUpdateReq) new AnUpdateReq(parent, conn) .A(JProtocol.CRUD.U)) .Mtabl(tabl); return(bdItem); }
public AlbumResp getCollect(string collectId) { AlbumReq req = new AlbumReq(uri).CollectId("c-001"); req.A(A.collect); AnsonMsg q = client.UserReq(uri, new AlbumPort(AlbumPort.album), null, req); return((AlbumResp)client.Commit(q, errCtx)); }
/// <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]); }
/// <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); }
/**Print Json Request (no request sent to server) * @param req * @return this object * @throws SQLException */ public SessionClient Console(AnsonMsg req) { if (AnClient.console) { try { Debug.WriteLine(req.ToString()); } catch (Exception ex) { Debug.WriteLine(ex.ToString()); } } return(this); }
public AnsonMsg Delete(string uri, string tbl, string[] act = null) { AnUpdateReq itm = AnUpdateReq.formatDelReq(uri, null, tbl); AnsonMsg jmsg = UserReq(uri, new Port(Port.update), act, itm); AnsonHeader header = new AnsonHeader(ssInf.ssid, ssInf.uid); if (act != null && act.Length > 0) { header.act(act); } return(jmsg.Header(header)); }
public AlbumResp insertPhoto(string collId, string fullpath, string clientname) { AlbumReq req = new AlbumReq(uri) .createPhoto(collId, fullpath) .photoName(clientname); req.A(A.insertPhoto); AnsonHeader header = client.Header().act("album.c#", "create", "c/photo", "create photo"); AnsonMsg q = client.UserReq(uri, new AlbumPort(AlbumPort.album), req) .Header(header); return((AlbumResp)client.Commit(q, errCtx)); }
public AnsonMsg Update(string conn, string tbl, string[] act = null) { AnUpdateReq itm = AnUpdateReq.FormatUpdateReq(conn, null, tbl); AnsonMsg jmsg = UserReq(new Port(Port.update), act, itm); AnsonHeader header = new AnsonHeader(ssInf.ssid, ssInf.uid); if (act != null && act.Length > 0) { header.act(act); } return(jmsg.Header(header) ); //.Body(itm); }
public AnsonMsg Insert(string uri, string tbl, string[] act = null) { AnInsertReq itm = AnInsertReq.formatInsertReq(null, tbl, uri); AnsonMsg jmsg = UserReq(uri, new Port(Port.insert), act, itm); AnsonHeader header = new AnsonHeader(ssInf.ssid, ssInf.uid); if (act != null && act.Length > 0) { header.act(act); } return(jmsg.Header(header) .Body(itm, uri)); }