private JObject GetGxObject(JArray array, String CmpContext, bool IsMasterPage) { try { JObject obj; for (int i = 0; i < array.Count; i++) { obj = array.GetObject(i); if (obj["CmpContext"].ToString().Equals(CmpContext) && obj["IsMasterPage"].ToString().Equals(IsMasterPage.ToString())) { return(obj); } } obj = new JObject(); obj.Put("CmpContext", CmpContext); obj.Put("IsMasterPage", IsMasterPage.ToString()); array.Add(obj); return(obj); } catch (Exception ex) { GXLogging.Error(log, "GetGxObject error", ex); } return(null); }
public void ajax_rsp_assign_sdt_attri(String CmpContext, bool IsMasterPage, String AttName, Object SdtObj) { if (isJsOutputEnabled) { if (!context.isSpaRequest() || (context.isSpaRequest() && String.IsNullOrEmpty(CmpContext))) { try { JObject obj = GetGxObject(AttValues, CmpContext, IsMasterPage); if (obj != null) { IGxJSONAble SdtObjJson = SdtObj as IGxJSONAble; if (SdtObjJson != null) { obj.Put(AttName, SdtObjJson.GetJSONObject()); } else { Array array = SdtObj as Array; if (array != null) { JArray jArray = new JArray(array); obj.Put(AttName, jArray); } } } } catch (Exception ex) { GXLogging.Error(log, "ajax_rsp_assign_sdt_attri error", ex); } } } }
internal string GetJson() { var json = new JObject(); if (!string.IsNullOrEmpty(this.CollapseKey)) { json.Put("collapse_key", this.CollapseKey); } if (this.TimeToLive.HasValue) { json.Put("time_to_live", this.TimeToLive.Value); } json.Put("registration_ids", new JArray(this.RegistrationIds.ToArray())); if (this.DelayWhileIdle.HasValue) { json.Put("delay_while_idle", this.DelayWhileIdle.Value); } if (!string.IsNullOrEmpty(this.JsonData)) { var jsonData = Utils.FromJSonString(this.JsonData); if (jsonData != null) { json.Put("data", jsonData); } } return(json.ToString()); }
private void OnCommandAccountsView(string[] args) { string name = args[0]; if (!wallets.TryGetValue(name, out Account account)) { BConsole.WriteLine("account (", name, ") not found"); return; } string key = account.Key; if (string.IsNullOrEmpty(key)) { key = "Locked"; } var o = new JObject(); o.Put <string>("name", name); o.Put <string>("address", account.Address); o.Put <string>("secretKey", key); o.Put <JObject>("keystore", account.KeyStore); BConsole.WriteLine(o); }
public IActionResult MutiPost(string value1, string value2 = "100") { var res = new JObject(); res.Put("value1", value1); res.Put("value2", value2); return(ApiResult.Ok(res)); }
static string GetRawAction(WindowsNotification notif) { JObject js = new JObject(); js.Put("action", notif.Action); js.Put("executionTime", notif.ExecutionTime); js.Put("params", notif.Parameters.ToJObject()); return(js.ToString()); }
public void setExternalObjectProperty(String cmpContext, bool isMasterPage, String objectName, String propertyName, object value) { var obj = new JObject(); obj.Put("CmpContext", cmpContext); obj.Put("IsMasterPage", isMasterPage); obj.Put("ObjectName", objectName); obj.Put("PropertyName", propertyName); obj.Put("Value", value); commands.AppendCommand(new GXAjaxCommand("exoprop", obj)); }
public static JObject FromException(Exception e, bool includeStackTrace) { if (e == null) throw new ArgumentNullException("e"); JObject error = new JObject(); error.Put("message", e.GetBaseException().Message); if (includeStackTrace) error.Put("stackTrace", e.StackTrace); return error; }
public void PrintReportAtClient(string reportFile, string printerRule) { JObject obj = new JObject(); try { obj.Put("reportFile", reportFile); obj.Put("printerRule", printerRule); } catch (JsonException) { } commands.AppendCommand(new GXAjaxCommand("print", obj)); }
public void PrintReportAtClient(string reportFile, string printerRule) { JObject obj = new JObject(); try { obj.Put("reportFile", reportFile); obj.Put("printerRule", printerRule); } catch (Exception ex) { GXLogging.Error(log, "PrintReportAtClient error", ex); } commands.AppendCommand(new GXAjaxCommand("print", obj)); }
public virtual void CallWebObject(string url) { string target = GetCallTargetFromUrl(url); if (String.IsNullOrEmpty(target)) { context.wjLoc = url; } else { JObject cmdParms = new JObject(); cmdParms.Put("url", url); cmdParms.Put("target", target); context.httpAjaxContext.appendAjaxCommand("calltarget", cmdParms); } }
internal void WcfExecute(Stream istream, string contentType) { string savedFileName, ext, fName; ext = context.ExtensionForContentType(contentType); savedFileName = FileUtil.getTempFileName(Preferences.getTMP_MEDIA_PATH(), "BLOB", string.IsNullOrEmpty(ext) ? "tmp" : ext); GxFile file = new GxFile(Preferences.getTMP_MEDIA_PATH(), savedFileName); file.Create(istream); JObject obj = new JObject(); fName = file.GetURI(); string fileGuid = GxUploadHelper.GetUploadFileGuid(); string fileToken = GxUploadHelper.GetUploadFileId(fileGuid); obj.Put("object_id", fileToken); localHttpContext.Response.AddHeader("GeneXus-Object-Id", fileGuid); localHttpContext.Response.ContentType = MediaTypesNames.ApplicationJson; HttpHelper.SetResponseStatus(localHttpContext, ((int)HttpStatusCode.Created).ToString(), string.Empty); localHttpContext.Response.Write(obj.ToString()); GxUploadHelper.CacheUploadFile(fileGuid, savedFileName, fName, ext, file, localHttpContext); }
private void OnCommandUserView(string[] args) { string uid = args[0]; var user = GameDB.Users.Select(uid); if (ReferenceEquals(user, null)) { return; } Task.Run(async() => { try { // 사용자 정보 JObject info = JObject.FromObject(user); info.Put <string>("passhash", user.PassHash); // 사용자 계좌 잔고 조회 string address = GameKey.CKD(uid).Address; ulong balance = (await web4b.GetBalanceAsync(address)).balance.Value; ulong nonce = (await web4b.GetNonceAsync(address)).nonce.Value; info.Put <string>("address", address); info.Put <decimal>("balance", Coin.ToCoin(balance)); info.Put <ulong>("nonce", nonce); // 사용자 인벤토리 JArray inven = new JArray(); foreach (var itemcode in GameDB.Inventories.Select(uid)) { var item = GameDB.Items.Select(itemcode); if (null != item) { inven.Add(JObject.FromObject(item)); } } info.Put <JArray>("inventory", inven); BConsole.WriteLine(uid, "=", info); } catch (Exception ex) { BConsole.WriteLine("exception! ex=", ex); } }); }
internal JObject ToJObject() { JObject ar = new JObject(); foreach (KeyValuePair <string, string> p in m_data) { ar.Put(p.Key, p.Value); } return(ar); }
private void OnCommandAccounts(string[] args) { Task.Run(async() => { foreach (var entry in wallets) { var o = new JObject(); string name = entry.Key; string address = entry.Value.Address; (ulong?balance, string error) = await web4b.GetBalanceAsync(address, Be4Helper.LATEST); o.Put <string>("name", name); o.Put <string>("address", address); o.Put <string>("balance", Coin.ToCoin(balance ?? 0).ToString("N")); BConsole.WriteLine(o); } }); }
public override void OnMessage(string message) { string key = GetClientKey(this); Type objType = GeneXus.Metadata.ClassLoader.FindType("GeneXus", GX_NOTIFICATIONINFO_NAME, null); GxUserType nInfo = (GxUserType)Activator.CreateInstance(objType); JObject jObj = new JObject(); jObj.Put("Message", message); nInfo.FromJSONObject(jObj); ExecuteHandler(HandlerType.ReceivedMessage, new Object[] { key, nInfo }); OnNewMessage?.Invoke(key, message); }
public override Task OnMessage(string connectionGUID, System.Net.WebSockets.WebSocket socket, WebSocketReceiveResult result, byte[] buffer) { string key = connectionGUID; string message = Encoding.UTF8.GetString(buffer); Type objType = GeneXus.Metadata.ClassLoader.FindType("GeneXus", GX_NOTIFICATIONINFO_NAME, null); GxUserType nInfo = (GxUserType)Activator.CreateInstance(objType); JObject jObj = new JObject(); jObj.Put("Message", message); nInfo.FromJSONObject(jObj); ExecuteHandler(HandlerType.ReceivedMessage, new Object[] { key, nInfo }); OnNewMessage?.Invoke(key, message); return(Task.CompletedTask); }
public void executeExternalObjectMethod(String cmpContext, bool isMasterPage, String objectName, String methodName, object[] parms, bool isEvent) { var obj = new JObject(); obj.Put("CmpContext", cmpContext); obj.Put("IsMasterPage", isMasterPage); obj.Put("ObjectName", objectName); obj.Put("Method", methodName); obj.Put("Parms", HttpAjaxContext.GetParmsJArray(parms)); obj.Put("IsEvent", isEvent); commands.AppendCommand(new GXAjaxCommand("exomethod", obj)); }
private JObject GetControlProps(JObject obj, String Control) { JObject ctrlProps = null; try { ctrlProps = obj[Control] as JObject; if (ctrlProps == null) { ctrlProps = new JObject(); obj.Put(Control, ctrlProps); } } catch (JsonException) { } return(ctrlProps); }
protected JObject GetNetTime() { var time = new JObject(); time.Put <bool>("synchronized", NetTime.Synchronized); time.Put <string>("provider", NetTime.ActiveTimeServer); time.Put <DateTime>("utc", NetTime.UtcNow); time.Put <DateTime>("now", DateTime.Now); time.Put <int>("unixtime", NetTime.UnixTime); time.Put <TimeSpan>("timediff", NetTime.TimeDiff); return(time); }
private void OnMessageInfoReq(TcpSession session, GameMessage message) { string scode = message.Get <string>("session"); string uid = GetUidBySession(scode); if (string.IsNullOrEmpty(uid) || scode != session.ID) { session.Write(new GameMessage("error").With("message", "unknown session key")); return; } // select user var user = gamedb.Users.Select(uid); if (ReferenceEquals(user, null)) { session.Write(new GameMessage("error").With("message", "user data not found")); return; } // user information JObject info = new JObject(); info.Put <string>("uid", uid); info.Put <string>("rdate", user.RegisterDate); // user balance & nonce string address = web4b.GetUserAddress(uid); ulong balance = web4b.GetBalanceAsync(address).Result.balance ?? 0; ulong nonce = web4b.GetNonceAsync(address).Result.nonce ?? 0; info.Put <string>("address", address); info.Put <decimal>("balance", Coin.ToCoin(balance)); info.Put <ulong>("nonce", nonce); // user inventory JArray inven = new JArray(); foreach (var code in gamedb.Inventories.Select(uid)) { var item = gamedb.Items.Select(code); inven.Add(JObject.Parse(item.ToString())); } info.Put <JArray>("inventory", inven); session.Write( new GameMessage("info.res") .With("info", info) ); }
private JObject GetControlProps(JObject obj, String Control) { JObject ctrlProps = null; try { ctrlProps = obj[Control] as JObject; if (ctrlProps == null) { ctrlProps = new JObject(); obj.Put(Control, ctrlProps); } } catch (Exception ex) { GXLogging.Error(log, "GetControlProps error", ex); } return(ctrlProps); }
public void ajax_rsp_assign_attri(String CmpContext, bool IsMasterPage, String AttName, Object AttValue) { if (isJsOutputEnabled) { if (!context.isSpaRequest() || (context.isSpaRequest() && String.IsNullOrEmpty(CmpContext))) { try { JObject obj = GetGxObject(AttValues, CmpContext, IsMasterPage); if (obj != null) { obj.Put(AttName, AttValue); } } catch (JsonException) { } } } }
public void ajax_rsp_assign_prop(String CmpContext, bool IsMasterPage, String Control, String Property, String Value, bool SendAjax = true) { if (SendAjax && ShouldLogAjaxControlProperty(Property)) { if (!context.isSpaRequest() || (context.isSpaRequest() && String.IsNullOrEmpty(CmpContext))) { try { // Avoid sending to the client side tmp media directory paths if (Property == "URL" && (Value.StartsWith(Preferences.getTMP_MEDIA_PATH()) || Value.StartsWith(context.PathToRelativeUrl(Preferences.getTMP_MEDIA_PATH())))) { return; } if (Control == "FORM" && Property == "Caption") { FormCaption = Value; } JObject obj = GetGxObject(PropValues, CmpContext, IsMasterPage); if (obj != null) { JObject ctrlProps = GetControlProps(obj, Control); if (ctrlProps != null) { ctrlProps.Put(Property, Value); } } if (!context.isAjaxRequest()) { ajax_rsp_assign_hidden(Control + "_" + Property.Substring(0, 1) + Property.Substring(1).ToLower(), Value); } } catch (Exception ex) { GXLogging.Error(log, "ajax_rsp_assign_prop error", ex); } } } }
private JObject BuildCallTemplatesObject() { JObject info = new JObject(); StringBuilder sb = new StringBuilder(); foreach (JsonRpcMethod method in ServiceClass.GetMethods()) { sb.Length = 0; sb.Append("[ "); JsonRpcParameter[] parameters = method.GetParameters(); if (parameters.Length == 0) { sb.Append("/* void */"); } else { foreach (JsonRpcParameter parameter in parameters) { if (parameter.Position > 0) sb.Append(", "); sb.Append("/* ").Append(parameter.Name).Append(" = */ ?"); } } sb.Append(" ]"); info.Put(method.Name, sb.ToString()); } return info; }
private StorePurchase ValidatePurchase(string purchaseToken, PurchaseResult purchaseResult, PurchaseEnvironment env) { StorePurchase p = null; string responseString; string url = (env == PurchaseEnvironment.Production) ? APPLE_STORE_VALIDATION_URL_PROD : APPLE_STORE_VALIDATION_URL_SANDBOX; JObject inputObj = new JObject(); inputObj.Put("receipt-data", purchaseResult.TransactionData.Trim()); inputObj.Put("password", _iTunesStorePassword); string key = Util.GetHashString(inputObj.ToString()); if (!dataCache.TryGetValue(key, out responseString)) { HttpStatusCode code = DoPost(inputObj.ToString(), url, out responseString); switch (code) { case HttpStatusCode.OK: break; default: throw new StoreInvalidPurchaseException(""); } dataCache.TryAdd(key, responseString); } JObject jResponse = Util.FromJSonString(responseString); if (jResponse.Contains("status")) { int statusCode = (int)jResponse["status"]; switch (statusCode) { case 21000: throw new StoreResponsePurchaseException("The App Store could not read the JSON object you provided."); case 21002: throw new StoreResponsePurchaseException("The data in the receipt-data property was malformed or missing."); case 21003: throw new StoreResponsePurchaseException("The receipt could not be authenticated."); case 21004: throw new StoreResponsePurchaseException("The shared secret you provided does not match the shared secret on file for your account."); case 21005: throw new StoreResponsePurchaseException("The receipt server is not currently available."); case 21006: throw new StoreResponsePurchaseException("Could not handle 21006 status response"); case 21007: string value; dataCache.TryRemove(key, out value); throw new StoreResponseEnvironmentException("This receipt is from the test environment, but it was sent to the production environment for verification. Send it to the test environment instead."); case 21008: break; case 0: break; default: throw new StoreResponsePurchaseException($"Could not handle '{statusCode}' status response"); } bool found = false; if (jResponse.Contains("receipt")) { JObject receipt = (JObject)jResponse["receipt"]; if (receipt.Contains("in_app")) { JArray purchases = (JArray)receipt["in_app"]; foreach (JObject purchase in purchases) { if (purchase.Contains("transaction_id") && (string)purchase["transaction_id"] == purchaseToken) { found = true; p = ParsePurchase(purchase); String ATT_ORIG_TRN_ID = "original_transaction_id"; if (p.PurchaseStatus == PurchaseStatus.Expired && p.ProductType == (int)ProductType.Subscription && purchase.Contains(ATT_ORIG_TRN_ID) && jResponse.Contains("latest_receipt_info")) { String originalTransactionId = (string)purchase[ATT_ORIG_TRN_ID]; JArray latestInfo = (JArray)jResponse["latest_receipt_info"]; List <StorePurchase> list = new List <StorePurchase>(); foreach (JObject latestPurchase in latestInfo) { if (latestPurchase.Contains(ATT_ORIG_TRN_ID) && (string)latestPurchase[ATT_ORIG_TRN_ID] == originalTransactionId) { p = ParsePurchase(latestPurchase); list.Add(p); if (p.PurchaseStatus == PurchaseStatus.Valid) { break; } } } if (p.PurchaseStatus != PurchaseStatus.Valid && list.Count > 0) { list = list.OrderByDescending(sp => sp.Subscription.Expiration).ToList(); p = list.First(); } } else { break; } } } } } if (!found) { throw new StorePurchaseNotFoundException("Purchase Id not found inside Apple Receipt"); } } else { throw new StoreResponsePurchaseException("Aplle Store validation servers seems to be unavailable."); } if (p.ProductType == (int)ProductType.Subscription) { p.Custom.OriginalPurchase = purchaseResult; } return(p); }
public void AddObjectProperty(string name, object prop) { _Properties.Put(name, prop); }
protected virtual object OnError(Exception e) { if (JsonRpcTrace.Switch.TraceError) JsonRpcTrace.Error(e); JObject error = new JObject(); error.Put("message", e.GetBaseException().Message); if (_localExecution) error.Put("stackTrace", e.StackTrace); return error; }
protected virtual object ParseRequest(TextReader input) { if (input == null) throw new ArgumentNullException("input"); JsonReader reader = (JsonReader) _serviceProvider.GetService(typeof(JsonReader)); if (reader == null) reader = new JsonTextReader(input); JObject request = new JObject(); JsonRpcMethod method = null; reader.ReadToken(JsonTokenClass.Object); while (reader.TokenClass != JsonTokenClass.EndObject) { string memberName = reader.ReadMember(); switch (memberName) { case "id" : { request["id"] = reader.DeserializeNext(); break; } case "method" : { string methodName = reader.ReadString(); request["method"] = methodName; method = _service.GetClass().GetMethodByName(methodName); break; } case "params" : { object args; if (method == null) { args = reader.DeserializeNext(); } else { JsonRpcParameter[] parameters = method.GetParameters(); if (reader.TokenClass == JsonTokenClass.Array) { reader.Read(); ArrayList argList = new ArrayList(parameters.Length); // TODO: This loop could bomb when more args are supplied that parameters available. for (int i = 0; reader.TokenClass != JsonTokenClass.EndArray; i++) argList.Add(reader.Get(parameters[i].ParameterType)); reader.Read(); args = argList.ToArray(); } else if (reader.TokenClass == JsonTokenClass.Object) { reader.Read(); JObject argByName = new JObject(); while (reader.TokenClass != JsonTokenClass.EndObject) { // TODO: Imporve this lookup. JsonRpcParameter matchedParameter = null; foreach (JsonRpcParameter parameter in parameters) { if (parameter.Name.Equals(reader.Text)) { matchedParameter = parameter; break; } } reader.Read(); // TODO: This could bomb when if no matching parameter is found. argByName.Put(matchedParameter.Name, reader.Get(matchedParameter.ParameterType)); } reader.Read(); args = argByName; } else { args = reader.DeserializeNext(); } request["params"] = args; } break; } } } reader.Read(); return request; }
protected virtual object ParseRequest(TextReader input) { if (input == null) throw new ArgumentNullException("input"); JsonReader reader = (JsonReader) _serviceProvider.GetService(typeof(JsonReader)); if (reader == null) reader = new JsonTextReader(input); JObject request = new JObject(); IRpcMethodDescriptor method = null; reader.ReadToken(JsonToken.Object); while (reader.ReadToken() != JsonToken.EndObject) { switch (reader.Text) { case "id" : { reader.Read(); request["id"] = reader.DeserializeNext(); break; } case "method" : { string methodName = reader.ReadString(); request["method"] = methodName; method = _service.GetDescriptor().GetMethodByName(methodName); break; } case "params" : { object args; if (method == null) { reader.Read(); args = reader.DeserializeNext(); } else { reader.Read(); IRpcParameterDescriptor[] parameters = method.GetParameters(); if (reader.Token == JsonToken.Array) { reader.Read(); ArrayList argList = new ArrayList(parameters.Length); for (int i = 0; reader.Token != JsonToken.EndArray; i++) argList.Add(reader.Get(parameters[i].ParameterType)); args = argList.ToArray(); } else if (reader.Token == JsonToken.Object) { reader.Read(); JObject argByName = new JObject(); while (reader.Token != JsonToken.EndObject) { IRpcParameterDescriptor matchedParameter = null; foreach (IRpcParameterDescriptor parameter in parameters) { if (parameter.Name.Equals(reader.Text)) { matchedParameter = parameter; break; } } reader.Read(); argByName.Put(matchedParameter.Name, reader.Get(matchedParameter.ParameterType)); } args = argByName; } else { args = reader.DeserializeNext(); } request["params"] = args; } break; } } } return request; }
public override void webExecute() { bool isRefreshToken = false; bool isDevice = false; bool isExternalSDAuth = false; String clientId = cgiGet("client_id"); String clientSecret = cgiGet("client_secret"); String grantType = cgiGet("grant_type"); String nativeToken = cgiGet("native_token"); String nativeVerifier = cgiGet("native_verifier"); String avoid_redirect = cgiGet("avoid_redirect"); String additional_parameters = cgiGet("additional_parameters"); String refreshToken = ""; String userName = string.Empty; String userPassword = string.Empty; String scope = string.Empty; string URL = string.Empty; bool flag = false; try { DataStoreUtil.LoadDataStores(context); if (grantType.Equals("refresh_token", StringComparison.OrdinalIgnoreCase)) { refreshToken = cgiGet("refresh_token"); isRefreshToken = true; } else if (grantType.Equals("device", StringComparison.OrdinalIgnoreCase)) { isDevice = true; } else if (!string.IsNullOrEmpty(nativeToken)) { isExternalSDAuth = true; } else { userName = cgiGet("username"); userPassword = cgiGet("password"); scope = cgiGet("scope"); } OutData gamout; GxResult result; if (isRefreshToken) { result = GxSecurityProvider.Provider.refreshtoken(context, clientId, clientSecret, refreshToken, out gamout, out flag); } else if (isDevice) { result = GxSecurityProvider.Provider.logindevice(context, clientId, clientSecret, out gamout, out flag); } else if (isExternalSDAuth) { result = GxSecurityProvider.Provider.externalauthenticationfromsdusingtoken(context, grantType, nativeToken, nativeVerifier, clientId, clientSecret, ref scope, additional_parameters, out gamout, out flag); } else if (String.IsNullOrEmpty(additional_parameters)) { result = GxSecurityProvider.Provider.oauthauthentication(context, grantType, userName, userPassword, clientId, clientSecret, scope, out gamout, out URL, out flag); } else { result = GxSecurityProvider.Provider.oauthauthentication(context, grantType, userName, userPassword, clientId, clientSecret, scope, additional_parameters, out gamout, out URL, out flag); } localHttpContext.Response.ContentType = MediaTypesNames.ApplicationJson; if (!flag) { localHttpContext.Response.StatusCode = 401; if (result != null) { string messagePermission = result.Description; HttpHelper.SetResponseStatusAndJsonError(context.HttpContext, result.Code, messagePermission); if (GXUtil.ContainsNoAsciiCharacter(messagePermission)) { messagePermission = string.Format("{0}{1}", GxRestPrefix.ENCODED_PREFIX, Uri.EscapeDataString(messagePermission)); } localHttpContext.Response.AddHeader(HttpHeader.AUTHENTICATE_HEADER, HttpHelper.OatuhUnauthorizedHeader(context.GetServerName(), result.Code, messagePermission)); } } else { if (!isDevice && !isRefreshToken && (gamout == null || String.IsNullOrEmpty((string)gamout["gxTpr_Access_token"]))) { if (string.IsNullOrEmpty(avoid_redirect)) { localHttpContext.Response.StatusCode = 303; } else { localHttpContext.Response.StatusCode = 200; } localHttpContext.Response.AddHeader("location", URL); JObject jObj = new JObject(); jObj.Put("Location", URL); localHttpContext.Response.Write(jObj.ToString()); } else { localHttpContext.Response.StatusCode = 200; localHttpContext.Response.Write(gamout.JsonString); } } context.CloseConnections(); } catch (Exception e) { localHttpContext.Response.StatusCode = 404; localHttpContext.Response.Write(e.Message); GXLogging.Error(log, string.Format("Error in access_token service clientId:{0} clientSecret:{1} grantType:{2} userName:{3} scope:{4}", clientId, clientSecret, grantType, userName, scope), e); } }
public void AddObjectProperty(string name, object prop) { wrapper.Put(name, prop); }
protected override void ProcessRequest() { if (!Modified()) { Response.StatusCode = 304; return; } // // Generate the SMD object graph. // IRpcServiceDescriptor service = TargetService.GetDescriptor(); JObject smd = new JObject(); smd.Put("SMDVersion", ".1"); smd.Put("objectName", JsonRpcServices.GetServiceName(TargetService)); smd.Put("serviceType", "JSON-RPC"); smd.Put("serviceURL", Request.FilePath); // TODO: Check whether this should be an absolute path from the protocol root. IRpcMethodDescriptor[] methods = service.GetMethods(); if (methods.Length > 0) // TODO: Check if methods entry can be skipped if there are none. { JArray smdMethods = new JArray(); foreach (IRpcMethodDescriptor method in methods) { JObject smdMethod = new JObject(); smdMethod.Put("name", method.Name); IRpcParameterDescriptor[] parameters = method.GetParameters(); if (parameters.Length > 0) // TODO: Check if parameters entry can be skipped if there are none. { JArray smdParameters = new JArray(); foreach (IRpcParameterDescriptor parameter in parameters) { JObject smdParameter = new JObject(); smdParameter.Put("name", parameter.Name); smdParameters.Add(smdParameter); } smdMethod.Put("parameters", smdParameters); } smdMethods.Add(smdMethod); } smd.Put("methods", smdMethods); } // // Generate the response. // if (HasLastModifiedTime) { Response.Cache.SetCacheability(HttpCacheability.Public); Response.Cache.SetLastModified(LastModifiedTime); } Response.ContentType = "text/plain"; Response.AppendHeader("Content-Disposition", "attachment; filename=" + service.Name + ".smd"); JsonTextWriter writer = new JsonTextWriter(Response.Output); writer.WriteValue(smd); }
public void TestRemoteConflictResolution() { // Create a document with two conflicting edits. var doc = database.CreateDocument(); var rev1 = doc.CreateRevision().Save(); var rev2a = CreateRevisionWithRandomProps(rev1, false); var rev2b = CreateRevisionWithRandomProps(rev1, true); // make sure we can query the db to get the conflict var allDocsQuery = database.CreateAllDocumentsQuery(); allDocsQuery.AllDocsMode = allDocsQuery.AllDocsMode = AllDocsMode.OnlyConflicts; var rows = allDocsQuery.Run(); Assert.AreEqual(1, rows.Count); Assert.IsTrue(rows.Aggregate(false, (found, row) => found |= row.Document.Id.Equals(doc.Id))); // Push the conflicts to the remote DB. var pusher = database.CreatePushReplication(GetReplicationURL()); RunReplication(pusher); Assert.IsNull(pusher.LastError); var rev3aBody = new JObject(); rev3aBody.Put("_id", doc.Id); rev3aBody.Put("_rev", rev2a.Id); // Then, delete rev 2b. var rev3bBody = new JObject(); rev3bBody.Put("_id", doc.Id); rev3bBody.Put("_rev", rev2b.Id); rev3bBody.Put("_deleted", true); // Combine into one _bulk_docs request. var requestBody = new JObject(); var docs = new JArray { rev3aBody, rev3bBody }; requestBody.Put("docs", docs); // Make the _bulk_docs request. var client = new HttpClient(); var bulkDocsUrl = GetReplicationURL() + "/_bulk_docs"; var request = new HttpRequestMessage(HttpMethod.Post, bulkDocsUrl); //request.Headers.Add("Accept", "*/*"); request.Content = new StringContent(requestBody.ToString(), Encoding.UTF8, "application/json"); var response = client.SendAsync(request).Result; // Check the response to make sure everything worked as it should. Assert.AreEqual(HttpStatusCode.Created, response.StatusCode); var rawResponse = response.Content.ReadAsStringAsync().Result; var resultArray = Manager.GetObjectMapper().ReadValue <JArray>(rawResponse); Assert.AreEqual(2, resultArray.Count); foreach (var value in resultArray.Values <JObject>()) { var err = (string)value["error"]; Assert.IsNull(err); } WorkaroundSyncGatewayRaceCondition(); // Pull the remote changes. var puller = database.CreatePullReplication(GetReplicationURL()); RunReplication(puller); Assert.IsNull(puller.LastError); // Make sure the conflict was resolved locally. Assert.AreEqual(1, doc.ConflictingRevisions.Count()); }
public string ToJson() { JObject json = new JObject(); JObject aps = new JObject(); if (!this.Alert.IsEmpty) { if (!string.IsNullOrEmpty(this.Alert.Body) && string.IsNullOrEmpty(this.Alert.LocalizedKey) && string.IsNullOrEmpty(this.Alert.ActionLocalizedKey) && (this.Alert.LocalizedArgs == null || this.Alert.LocalizedArgs.Count <= 0) && !this.HideActionButton) { aps.Put("alert", this.Alert.Body); } else { JObject jsonAlert = new JObject(); if (!string.IsNullOrEmpty(this.Alert.LocalizedKey)) { jsonAlert.Put("loc-key", this.Alert.LocalizedKey); } if (this.Alert.LocalizedArgs != null && this.Alert.LocalizedArgs.Count > 0) { jsonAlert.Put("loc-args", new JArray(this.Alert.LocalizedArgs.ToArray())); } if (!string.IsNullOrEmpty(this.Alert.Body)) { jsonAlert.Put("body", this.Alert.Body); } if (this.HideActionButton) { jsonAlert.Put("action-loc-key", (string)null); } else if (!string.IsNullOrEmpty(this.Alert.ActionLocalizedKey)) { jsonAlert.Put("action-loc-key", this.Alert.ActionLocalizedKey); } aps["alert"] = jsonAlert; } } if (this.Badge.HasValue) { aps.Put("badge", this.Badge.Value); } if (!string.IsNullOrEmpty(this.Sound)) { aps.Put("sound", this.Sound); } if (this.ContentAvailable.HasValue) { aps.Put("content-available", this.ContentAvailable.Value); } if (aps.Count > 0) { json["aps"] = aps; } foreach (string key in this.CustomItems.Keys) { if (this.CustomItems[key].Length == 1) { json.Put(key, this.CustomItems[key][0]); } else if (this.CustomItems[key].Length > 1) { json[key] = new JArray(this.CustomItems[key]); } } string rawString = json.ToString(); StringBuilder encodedString = new StringBuilder(); foreach (char c in rawString) { if ((int)c < 32 || (int)c > 127) { encodedString.Append("\\u" + String.Format("{0:x4}", Convert.ToUInt32(c))); } else { encodedString.Append(c); } } return(rawString); // encodedString.ToString(); }
public JObject ToJObject() { var json = new JObject(); json.Put <string>("hash", Txid); json.Put <string>("chain", Hex.ToString(Chain, true)); json.Put <string>("version", Hex.ToString(Version, true)); json.Put <string>("from", From); json.Put <string>("to", To); json.Put <string>("value", Hex.ToString(Value, true)); json.Put <string>("gas", Hex.ToString(Gas, true)); json.Put <string>("nonce", Hex.ToString(Nonce, true)); json.Put <string>("input", Hex.ToString(Data)); json.Put <string>("extra", Hex.ToString(Extra)); json.Put <string>("metadata", Hex.ToString(Metadata)); json.Put <string>("v", Hex.ToString(V)); json.Put <string>("r", Hex.ToString(R)); json.Put <string>("s", Hex.ToString(S)); json.Put <string>("size", Hex.ToString(Rlp.Length, true)); return(json); }