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] = NFX.Web.ContentType.JSON; var res = wc.UploadString(INTEGRATION_HTTP_ADDR + actionName, str); var gotMap = JSONReader.DeserializeDataObject(res) as JSONDataMap; Assert.AreEqual(gotMap["ID"], 777); Assert.AreEqual(gotMap["Name"], "sss"); } }
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.ToBase64() } } } ; 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); }
public void WriteAsJSON(TextWriter wri, int nestingLevel, JSONWritingOptions options = null) { JSONDataMap map = new JSONDataMap { { "unit", UnitName }, { "value", Value } }; map.ToJSON(wri, options); }
protected override void DoAfterWork(WorkContext work, JSONDataMap matched) { work.Log( matched[VAR_TYPE].AsEnum<MessageType>(MessageType.Info), matched[VAR_TEXT].AsString(work.About), matched[VAR_FROM].AsString("{0}.After".Args(GetType().FullName)), pars: matched.ToJSON(JSONWritingOptions.CompactASCII) ); }
protected override void DoAfterWork(WorkContext work, JSONDataMap matched) { work.Log( matched[VAR_TYPE].AsEnum <MessageType>(MessageType.Info), matched[VAR_TEXT].AsString(work.About), matched[VAR_FROM].AsString("{0}.After".Args(GetType().FullName)), pars: matched.ToJSON(JSONWritingOptions.CompactASCII) ); }
public override string MapGaugeDimensions(string tEntity, IEnumerable <KeyValuePair <string, string> > dimensions) { var map = new JSONDataMap(); var allDims = DIMENSIONS[tEntity]; foreach (var dim in dimensions) { if (!allDims.Contains(dim.Key)) { continue; // ERROR } map[dim.Key] = dim.Value; } return(map.ToJSON()); }
private string getCreateLabelRequestBody(ShippoSession session, Shipment shipment, object labelID) { shipment.CarrierID = session.ConnectionParams.CarrierID; // use USPS for the moment shipment.ServiceID = USPS_PRIORITY_SERVICE; var isReturn = labelID != null; var body = new JSONDataMap(); body["carrier_account"] = shipment.CarrierID; body["servicelevel_token"] = shipment.ServiceID; body["label_file_type"] = FORMATS[shipment.LabelFormat]; body["async"] = false; var shpm = new JSONDataMap(); shpm["object_purpose"] = PURCHASE_LABEL_PURPOSE; shpm["address_from"] = getAddressBody(shipment.FromAddress); shpm["address_to"] = getAddressBody(shipment.ToAddress); if (!isReturn && shipment.ReturnAddress.HasValue) { shpm["address_return"] = getAddressBody(shipment.ReturnAddress.Value); } body["shipment"] = shpm; var parcel = new JSONDataMap(); if (shipment.Template.HasValue) { parcel["template"] = PARCEL_TEMPLATES[shipment.Template.Value]; } parcel["length"] = shipment.Length.ToString(CultureInfo.InvariantCulture); parcel["width"] = shipment.Width.ToString(CultureInfo.InvariantCulture); parcel["height"] = shipment.Height.ToString(CultureInfo.InvariantCulture); parcel["distance_unit"] = DIST_UNITS[shipment.DistanceUnit]; parcel["weight"] = shipment.Weight.ToString(CultureInfo.InvariantCulture); parcel["mass_unit"] = MASS_UNITS[shipment.MassUnit]; shpm["parcel"] = parcel; if (isReturn) { shpm["return_of"] = labelID; } return(body.ToJSON(JSONWritingOptions.Compact)); }
/// <summary> /// Handles the exception by responding appropriately with error page with conditional level of details and logging /// </summary> public static void HandleException(WorkContext work, Exception error, OrderedRegistry <WorkMatch> showDumpMatches, OrderedRegistry <WorkMatch> logMatches, string securityRedirectURL = null, Type customPageType = null ) { if (work == null || error == null) { return; } var showDump = showDumpMatches != null? showDumpMatches.OrderedValues.Any(m => m.Make(work) != null) : false; if (work.Response.Buffered) { work.Response.CancelBuffered(); } var json = false; if (work.Request != null && work.Request.AcceptTypes != null)//if needed for some edge HttpListener cases when Request or Request.AcceptTypes are null { json = work.Request.AcceptTypes.Any(at => at.EqualsIgnoreCase(ContentType.JSON)); } var actual = error; if (actual is FilterPipelineException) { actual = ((FilterPipelineException)actual).RootException; } if (actual is MVCActionException) { actual = ((MVCActionException)actual).InnerException; } var securityError = actual is NFX.Security.AuthorizationException || actual.InnerException is NFX.Security.AuthorizationException; if (actual is HTTPStatusException) { var se = (HTTPStatusException)actual; work.Response.StatusCode = se.StatusCode; work.Response.StatusDescription = se.StatusDescription; } else { if (securityError) { work.Response.StatusCode = WebConsts.STATUS_403; work.Response.StatusDescription = WebConsts.STATUS_403_DESCRIPTION; } else { work.Response.StatusCode = WebConsts.STATUS_500; work.Response.StatusDescription = WebConsts.STATUS_500_DESCRIPTION; } } if (json) { work.Response.ContentType = ContentType.JSON; work.Response.WriteJSON(error.ToClientResponseJSONMap(showDump)); } else { if (securityRedirectURL.IsNotNullOrWhiteSpace() && securityError) { work.Response.RedirectAndAbort(securityRedirectURL); } else { WaveTemplate errorPage = null; if (customPageType != null) { try { errorPage = Activator.CreateInstance(customPageType) as WaveTemplate; if (errorPage == null) { throw new WaveException("not WaveTemplate"); } } catch (Exception actErr) { work.Log(Log.MessageType.Error, StringConsts.ERROR_PAGE_TEMPLATE_TYPE_ERROR.Args(customPageType.FullName, actErr.ToMessageWithType()), typeof(ErrorFilter).FullName + ".ctor(customPageType)", actErr); } } if (errorPage == null) { errorPage = new ErrorPage(work, error, showDump); errorPage.Render(work, error); } else { errorPage.Render(work, actual); } } } if (logMatches != null && logMatches.Count > 0) { JSONDataMap matched = null; foreach (var match in logMatches.OrderedValues) { matched = match.Make(work); if (matched != null) { break; } } if (matched != null) { work.Log(Log.MessageType.Error, error.ToMessageWithType(), typeof(ErrorFilter).FullName, pars: matched.ToJSON(JSONWritingOptions.CompactASCII)); } } }
public override string ToString() { return(m_Content.ToJSON()); }
public string JSONMapAndPrimitive_JSONMiddle(int n, JSONDataMap map, string s) { map["ID"] = n; map["Name"] = s; return(map.ToJSON(JSONWritingOptions.CompactRowsAsMap)); }
/// <summary> /// Handles the exception by responding appropriately with error page with conditional level of details and logging /// </summary> public static void HandleException(WorkContext work, Exception error, OrderedRegistry<WorkMatch> showDumpMatches, OrderedRegistry<WorkMatch> logMatches, string securityRedirectURL = null, string securityRedirectTarget = null, OrderedRegistry<WorkMatch> securityRedirectMatches = null, Type customPageType = null ) { if (work==null || error==null) return; var showDump = showDumpMatches != null ? showDumpMatches.OrderedValues.Any(m => m.Make(work)!=null) : false; if (work.Response.Buffered) work.Response.CancelBuffered(); var json = false; if (work.Request!=null && work.Request.AcceptTypes!=null)//if needed for some edge HttpListener cases when Request or Request.AcceptTypes are null json = work.Request.AcceptTypes.Any(at=>at.EqualsIgnoreCase(ContentType.JSON)); var actual = error; if (actual is FilterPipelineException) actual = ((FilterPipelineException)actual).RootException; if (actual is MVCException) actual = ((MVCException)actual).InnerException; var securityError = NFX.Security.AuthorizationException.IsDenotedBy(actual); if (actual is HTTPStatusException) { var se = (HTTPStatusException)actual; work.Response.StatusCode = se.StatusCode; work.Response.StatusDescription = se.StatusDescription; } else { if (securityError) { work.Response.StatusCode = WebConsts.STATUS_403; work.Response.StatusDescription = WebConsts.STATUS_403_DESCRIPTION; } else { work.Response.StatusCode = WebConsts.STATUS_500; work.Response.StatusDescription = WebConsts.STATUS_500_DESCRIPTION; } } if (json) { work.Response.ContentType = ContentType.JSON; work.Response.WriteJSON(error.ToClientResponseJSONMap(showDump)); } else { if (securityRedirectMatches != null && securityRedirectMatches.Count > 0) { JSONDataMap matched = null; foreach(var match in securityRedirectMatches.OrderedValues) { matched = match.Make(work, actual); if (matched!=null) break; } if (matched!=null) { var url = matched[VAR_SECURITY_REDIRECT_URL].AsString(); var target = matched[VAR_SECURITY_REDIRECT_TARGET].AsString(); if (url.IsNotNullOrWhiteSpace()) securityRedirectURL = url; if (target.IsNotNullOrWhiteSpace()) securityRedirectTarget = target; } } if (securityRedirectURL.IsNotNullOrWhiteSpace() && securityError && !work.IsAuthenticated) { var url = securityRedirectURL; var target = securityRedirectTarget; if (target.IsNotNullOrWhiteSpace()) { var partsA = url.Split('#'); var parts = partsA[0].Split('?'); var query = parts.Length > 1 ? parts[0] + "&" : string.Empty; url = "{0}?{1}{2}={3}{4}".Args(parts[0], query, target, Uri.EscapeDataString(work.Request.Url.PathAndQuery), partsA.Length > 1 ? "#" + partsA[1] : string.Empty); } work.Response.RedirectAndAbort(url); } else { WaveTemplate errorPage = null; if (customPageType!=null) try { errorPage = Activator.CreateInstance(customPageType) as WaveTemplate; if (errorPage==null) throw new WaveException("not WaveTemplate"); } catch(Exception actErr) { work.Log(Log.MessageType.Error, StringConsts.ERROR_PAGE_TEMPLATE_TYPE_ERROR.Args(customPageType.FullName, actErr.ToMessageWithType()), typeof(ErrorFilter).FullName+".ctor(customPageType)", actErr); } if (errorPage==null) errorPage = new ErrorPage(work, error, showDump); errorPage.Render(work, error); } } if (logMatches!=null && logMatches.Count>0) { JSONDataMap matched = null; foreach(var match in logMatches.OrderedValues) { matched = match.Make(work, error); if (matched!=null) break; } if (matched!=null) work.Log(Log.MessageType.Error, error.ToMessageWithType(), typeof(ErrorFilter).FullName, pars: matched.ToJSON(JSONWritingOptions.CompactASCII)); } }
public string JSONMapAndPrimitive_JSONMiddle(int n, JSONDataMap map, string s) { map["ID"] = n; map["Name"] = s; return map.ToJSON(JSONWritingOptions.CompactRowsAsMap); }
private ConfigSectionNode buildSection(string name, JSONDataMap sectData, ConfigSectionNode parent) { var value = sectData[SECTION_VALUE_ATTR].AsString(); ConfigSectionNode result = parent==null ? new ConfigSectionNode(this, null, name, value) : parent.AddChildNode(name, value); foreach(var kvp in sectData) { if (kvp.Value is JSONDataMap) buildSection(kvp.Key, (JSONDataMap)kvp.Value, result); else if (kvp.Value is JSONDataArray) { var lst = (JSONDataArray)kvp.Value; foreach(var lnode in lst) { var lmap = lnode as JSONDataMap; if (lmap==null) throw new ConfigException(StringConsts.CONFIG_JSON_STRUCTURE_ERROR, new ConfigException("Bad structure: "+sectData.ToJSON())); buildSection(kvp.Key, lmap, result); } } else result.AddAttributeNode(kvp.Key, kvp.Value); } return result; }
private ConfigSectionNode buildSection(string name, JSONDataMap sectData, ConfigSectionNode parent) { var value = sectData[SECTION_VALUE_ATTR].AsString(); ConfigSectionNode result = parent == null ? new ConfigSectionNode(this, null, name, value) : parent.AddChildNode(name, value); foreach (var kvp in sectData) { if (kvp.Value is JSONDataMap) { buildSection(kvp.Key, (JSONDataMap)kvp.Value, result); } else if (kvp.Value is JSONDataArray) { var lst = (JSONDataArray)kvp.Value; foreach (var lnode in lst) { var lmap = lnode as JSONDataMap; if (lmap == null) { throw new ConfigException(StringConsts.CONFIG_JSON_STRUCTURE_ERROR, new ConfigException("Bad structure: " + sectData.ToJSON())); } buildSection(kvp.Key, lmap, result); } } else { if (!kvp.Key.EqualsIgnoreCase(SECTION_VALUE_ATTR))//20181201 DKh { result.AddAttributeNode(kvp.Key, kvp.Value); } } } return(result); }
protected override void DoEncodeRequest(MemoryStream ms, RequestMsg msg) { if (msg.Contract != typeof(Contracts.IRemoteTerminal)) { throw new ProtocolException(StringConsts.GLUE_BINDING_UNSUPPORTED_FUNCTION_ERROR.Args(nameof(AppTermBinding), nameof(Contracts.IRemoteTerminal), msg.Contract.FullName)); } var request = msg as RequestAnyMsg; if (request == null) { throw new ProtocolException(StringConsts.GLUE_BINDING_UNSUPPORTED_FUNCTION_ERROR.Args(nameof(AppTermBinding), nameof(RequestAnyMsg), msg.GetType().FullName)); } var data = new JSONDataMap(); data["id"] = request.RequestID.ID; data["instance"] = request.RemoteInstance?.ToString("D"); data["method"] = request.MethodName; data["one-way"] = false;//reserved for future use if (request.Arguments != null && request.Arguments.Length > 0) { data["command"] = request.Arguments[0]; } else { data["command"] = null; } //Handle headers, this binding allows ONLY for AuthenticationHeader with supported tokens/credentials if (request.HasHeaders) { if (request.Headers.Count > 1) { throw new ProtocolException(StringConsts.GLUE_BINDING_UNSUPPORTED_FUNCTION_ERROR.Args(nameof(AppTermBinding), "1 AuthenticationHeader", request.Headers.Count)); } var ahdr = request.Headers[0] as AuthenticationHeader; if (ahdr == null) { throw new ProtocolException(StringConsts.GLUE_BINDING_UNSUPPORTED_FUNCTION_ERROR.Args(nameof(AppTermBinding), "1 AuthenticationHeader", request.Headers[0].GetType().FullName)); } if (ahdr.Token.Assigned) { data["auth-token"] = Security.SkyAuthenticationTokenSerializer.Serialize(ahdr.Token); } if (ahdr.Credentials != null) { var src = ahdr.Credentials as Azos.Security.IStringRepresentableCredentials; if (src == null) { throw new ProtocolException(StringConsts.GLUE_BINDING_UNSUPPORTED_FUNCTION_ERROR.Args(nameof(AppTermBinding), "IStringRepresentableCredentials", ahdr.Credentials.GetType().FullName)); } data["auth-cred"] = src.RepresentAsString(); } } var json = data.ToJSON(JSONWritingOptions.Compact); var utf8 = Encoding.UTF8.GetBytes(json); ms.Write(utf8, 0, utf8.Length); }
private string getCreateLabelRequestBody(ShippoSession session, Shipment shipment, object labelID) { shipment.CarrierID = session.ConnectionParams.CarrierID; // use USPS for the moment shipment.ServiceID = USPS_PRIORITY_SERVICE; var isReturn = labelID != null; var body = new JSONDataMap(); body["carrier_account"] = shipment.CarrierID; body["servicelevel_token"] = shipment.ServiceID; body["label_file_type"] = FORMATS[shipment.LabelFormat]; body["async"] = false; var shpm = new JSONDataMap(); shpm["object_purpose"] = PURCHASE_LABEL_PURPOSE; shpm["address_from"] = getAddressBody(shipment.FromAddress); shpm["address_to"] = getAddressBody(shipment.ToAddress); if (!isReturn && shipment.ReturnAddress.HasValue) shpm["address_return"] = getAddressBody(shipment.ReturnAddress.Value); body["shipment"] = shpm; var parcel = new JSONDataMap(); if (shipment.Template.HasValue) parcel["template"] = PARCEL_TEMPLATES[shipment.Template.Value]; parcel["length"] = shipment.Length.ToString(CultureInfo.InvariantCulture); parcel["width"] = shipment.Width.ToString(CultureInfo.InvariantCulture); parcel["height"] = shipment.Height.ToString(CultureInfo.InvariantCulture); parcel["distance_unit"] = DIST_UNITS[shipment.DistanceUnit]; parcel["weight"] = shipment.Weight.ToString(CultureInfo.InvariantCulture); parcel["mass_unit"] = MASS_UNITS[shipment.MassUnit]; shpm["parcel"] = parcel; if (isReturn) shpm["return_of"] = labelID; return body.ToJSON(JSONWritingOptions.Compact); }