Exemple #1
0
        public Record(JSONDataMap init)
            : base()
        {
            if (init==null) throw new WaveException(StringConsts.ARGUMENT_ERROR+"Record.ctor(init(map)==null)");

              ctor(init);
        }
Exemple #2
0
 protected override void DoAfterWork(WorkContext work, JSONDataMap matched)
 {
   var txt = matched[VAR_ERROR].AsString();
   if (txt.IsNotNullOrWhiteSpace())
       throw new WaveException(txt);
   else
    work.Aborted = true;
 }
 public DropBoxContentObjectMetadata(JSONDataMap dataMap) : base(dataMap)
 {
     if (dataMap != null)
     {
         _photoMetadata = dataMap["photo_info"] as JSONDataMap;
         _metadata = dataMap;   
     }
 }
Exemple #4
0
        public Record(JSONDataMap init) : base()
        {
            if (init == null)
            {
                throw new WaveException(StringConsts.ARGUMENT_ERROR + "Record.ctor(init(map)==null)");
            }

            ctor(init);
        }
Exemple #5
0
        /// <summary>
        /// If non null or empty parses JSON content and sets the RoundtripBag
        /// </summary>
        public void SetRoundtripBagFromJSONString(string content)
        {
            if (content.IsNullOrWhiteSpace())
            {
                return;
            }

            m_RoundtripBag = content.JSONToDataObject() as JSONDataMap;
        }
Exemple #6
0
 protected override void DoBeforeWork(WorkContext work, JSONDataMap matched)
 {
     work.Log(
        matched[VAR_TYPE].AsEnum<MessageType>(MessageType.Info),
        matched[VAR_TEXT].AsString(work.About),
        matched[VAR_FROM].AsString("{0}.Before".Args(GetType().FullName)),
        pars: matched.ToJSON(JSONWritingOptions.CompactASCII)
        );
 }
 public object EchoJson(JSONDataMap data)
 {
     return new
     {
       ServerMessage = "Echo response",
       ServerDateTime = DateTime.Now,
       RequestedData = data
     };
 }
Exemple #8
0
        public void JSONDataMapFromURLEncoded_KeyEmptyEqNormal()
        {
            var dict = JSONDataMap.FromURLEncodedString("a=&b&&=&=14&c=3459");

            Assert.AreEqual(3, dict.Count);
            Assert.AreEqual(string.Empty, dict["a"]);
            Assert.AreEqual(null, dict["b"]);
            Assert.AreEqual("3459", dict["c"]);
        }
Exemple #9
0
        public static Schema FromJSON(JSONDataMap map, bool readOnly = false)
        {
            if (map == null || map.Count == 0)
            {
                throw new DataException(StringConsts.ARGUMENT_ERROR + "Schema.FromJSON(map==null|empty)");
            }

            var name = map["Name"].AsString();

            if (name.IsNullOrWhiteSpace())
            {
                throw new DataException(StringConsts.ARGUMENT_ERROR + "Schema.FromJSON(map.Name=null|empty)");
            }

            var adefs = map["FieldDefs"] as JSONDataArray;

            if (adefs == null || adefs.Count == 0)
            {
                throw new DataException(StringConsts.ARGUMENT_ERROR + "Schema.FromJSON(map.FieldDefs=null|empty)");
            }

            var defs = new List <Schema.FieldDef>();

            foreach (var mdef in adefs.Cast <JSONDataMap>())
            {
                var fname = mdef["Name"].AsString();
                if (fname.IsNullOrWhiteSpace())
                {
                    throw new DataException(StringConsts.ARGUMENT_ERROR + "Schema.FromJSON(map.FierldDefs[name=null|empty])");
                }

                var req      = mdef["IsRequired"].AsBool();
                var key      = mdef["IsKey"].AsBool();
                var vis      = mdef["Visible"].AsBool();
                var desc     = mdef["Description"].AsString();
                var minLen   = mdef["MinLen"].AsInt();
                var maxLen   = mdef["MaxLen"].AsInt();
                var valList  = mdef["ValueList"].AsString();
                var strKind  = mdef["Kind"].AsString();
                var dataKind = strKind == null ? DataKind.Text : (DataKind)Enum.Parse(typeof(DataKind), strKind);
                var strCase  = mdef["CharCase"].AsString();
                var chrCase  = strCase == null ? CharCase.AsIs : (CharCase)Enum.Parse(typeof(CharCase), strCase);

                var tp  = mdef["Type"].AsString(string.Empty).ToLowerInvariant().Trim();
                var tpn = mdef["Nullable"].AsBool();

                var type = JSONMappings.MapJSONTypeToCLR(tp, tpn);

                var atr = new FieldAttribute(required: req, key: key, visible: vis, description: desc,
                                             minLength: minLen, maxLength: maxLen,
                                             valueList: valList, kind: dataKind, charCase: chrCase);
                var def = new Schema.FieldDef(fname, type, atr);
                defs.Add(def);
            }

            return(new Schema(name, readOnly, defs));
        }
Exemple #10
0
        public void MakeURI_T1_noprefix()
        {
            var pattern = new URIPattern("/news/{year}/{month}/{title}");
            var map = new JSONDataMap { { "year", "1981" }, { "month", 12 }, { "title", "some_title" } };

            var uri = pattern.MakeURI(map);

            Assert.AreEqual(new Uri("/news/1981/12/some_title", UriKind.RelativeOrAbsolute), uri);
        }
Exemple #11
0
 public object Echo(JSONDataMap data)
 {
     return(new
     {
         ServerMessage = "You have supplied content and here is my response",
         ServerDateTime = DateTime.Now,
         RequestedData = data
     });
 }
Exemple #12
0
 public static Task <JSONDataMap> GetValueMapAsync(Uri uri, RequestParams request)
 {
     return(GetStringAsync(uri, request)
            .ContinueWith((antecedent) =>
     {
         var response = antecedent.Result;
         return response.IsNotNullOrWhiteSpace() ? JSONDataMap.FromURLEncodedString(response) : null;
     }));
 }
Exemple #13
0
 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)
         );
 }
Exemple #14
0
        public void MakeURI_T2_params()
        {
            var pattern = new URIPattern("{year}/values?{p1}={v1}&par2={v2}");
            var map = new JSONDataMap { { "year", "1980" }, { "p1", "par1" }, { "v1", 10 }, { "v2", "val2" } };

            var uri = pattern.MakeURI(map);

            Assert.AreEqual(new Uri("1980/values?par1%3D10%26par2%3Dval2", UriKind.RelativeOrAbsolute), uri);
        }
Exemple #15
0
 public RemoteTerminalInfo(JSONDataMap map)
 {
     TerminalName    = map["TerminalName"].AsString();
     WelcomeMsg      = map["WelcomeMsg"].AsString();
     Host            = map["Host"].AsString();
     AppName         = map["AppName"].AsString();
     ServerLocalTime = map["ServerLocalTime"].AsDateTime();
     ServerUTCTime   = map["ServerUTCTime"].AsDateTime();
 }
Exemple #16
0
        private Address doValidateAddress(ShippoSession session, IShippingContext context, Address address, Guid logID, out ValidateShippingAddressException error)
        {
            error = null;
            var cred = (ShippoCredentials)session.User.Credentials;
            var body = getAddressBody(address);

            body["validate"] = true;

            // validate address request
            var request = new WebClient.RequestParams(this)
            {
                Method      = HTTPRequestMethod.POST,
                ContentType = ContentType.JSON,
                Headers     = new Dictionary <string, string>
                {
                    { HDR_AUTHORIZATION, HDR_AUTHORIZATION_TOKEN.Args(cred.PrivateToken) }
                },
                Body = body.ToJSON(JSONWritingOptions.Compact)
            };

            var response = WebClient.GetJson(new Uri(URI_API_BASE + URI_ADDRESS), request);

            Log(MessageType.Info, "doValidateAddress()", response.ToJSON(), relatedMessageID: logID);

            // check for validation errors:
            // Shippo API can return STATUS_INVALID or (!!!) STATUS_VALID but with 'code'="Invalid"
            var         state    = response["object_state"].AsString(STATUS_INVALID);
            var         messages = response["messages"] as JSONDataArray;
            JSONDataMap message  = null;
            var         code     = string.Empty;
            var         text     = string.Empty;

            if (messages != null)
            {
                message = messages.FirstOrDefault() as JSONDataMap;
            }
            if (message != null)
            {
                code = message["code"].AsString(string.Empty);
                text = message["text"].AsString(string.Empty);
            }

            // error found
            if (!state.EqualsIgnoreCase(STATUS_VALID) || code.EqualsIgnoreCase(CODE_INVALID))
            {
                var errMess = StringConsts.SHIPPO_VALIDATE_ADDRESS_INVALID_ERROR.Args(text);
                Log(MessageType.Error, "doValidateAddress()", errMess, relatedMessageID: logID);
                error = new ValidateShippingAddressException(errMess, text);
                return(null);
            }

            // no errors
            var corrAddress = getAddressFromJSON(response);

            return(corrAddress);
        }
Exemple #17
0
 public GoogleDriveHandle(JSONDataMap info)
 {
     Id           = info[Metadata.ID].AsString();
     Name         = info[Metadata.TITLE].AsString();
     IsFolder     = info[Metadata.MIME_TYPE].Equals(GoogleDriveMimeType.FOLDER);
     Size         = info[Metadata.FILE_SIZE].AsULong();
     CreatedDate  = info[Metadata.CREATED_DATE].AsDateTime();
     ModifiedDate = info[Metadata.MODIFIED_DATE].AsDateTime();
     IsReadOnly   = !info[Metadata.EDITABLE].AsBool();
 }
Exemple #18
0
 public PayPalOAuthToken(JSONDataMap response, int expirationMargin)
 {
     m_ObtainTime = App.TimeSource.Now;
     m_ExpirationMargin = expirationMargin;
     m_ApplicationID = response[APP_ID].AsString();
     m_ExpiresInSeconds = response[EXPIRES_IN].AsInt();
     m_AccessToken = response[ACCESS_TOKEN].AsString();
     m_Scope = response[SCOPE].AsString();
     m_Nonce = response[NONCE].AsString();
 }
Exemple #19
0
 public GoogleDriveHandle(JSONDataMap info)
 {
     Id            = info[Metadata.ID].AsString();
     Name          = info[Metadata.TITLE].AsString();
     IsFolder      = info[Metadata.MIME_TYPE].Equals(GoogleDriveMimeType.FOLDER);
     Size          = info[Metadata.FILE_SIZE].AsULong();
     CreatedDate   = info[Metadata.CREATED_DATE].AsDateTime();
     ModifiedDate  = info[Metadata.MODIFIED_DATE].AsDateTime();
     IsReadOnly    = !info[Metadata.EDITABLE].AsBool();
 }
Exemple #20
0
 /// <summary>
 /// DEVELOPERS do not use!
 /// A hack method needed in some VERY RARE cases, like serving an error page form the filter which is out of portal scope.
 /// </summary>
 public void ___InternalInjectPortal(Portal portal           = null,
                                     Theme theme             = null,
                                     WorkMatch match         = null,
                                     JSONDataMap matchedVars = null)
 {
     m_Portal            = portal;
     m_PortalTheme       = theme;
     m_PortalMatch       = match;
     m_PortalMatchedVars = matchedVars;
 }
Exemple #21
0
        public void MakeURI_T1_prefix()
        {
            var pattern = new URIPattern("{year}/{month}/{title}");
            var prefix = new Uri("http://test.com");
            var map = new JSONDataMap { { "year", "1981" }, { "month", 12 }, { "title", "some_title" } };

            var uri = pattern.MakeURI(map, prefix);

            Assert.AreEqual(new Uri(prefix, "http://test.com/1981/12/some_title"), uri);
        }
Exemple #22
0
 public PayPalOAuthToken(JSONDataMap response, int expirationMargin)
 {
     m_ObtainTime       = App.TimeSource.Now;
     m_ExpirationMargin = expirationMargin;
     m_ApplicationID    = response[APP_ID].AsString();
     m_ExpiresInSeconds = response[EXPIRES_IN].AsInt();
     m_AccessToken      = response[ACCESS_TOKEN].AsString();
     m_Scope            = response[SCOPE].AsString();
     m_Nonce            = response[NONCE].AsString();
 }
Exemple #23
0
        public void MakeURI_T2_params()
        {
            var pattern = new URIPattern("{year}/values?{p1}={v1}&par2={v2}");
            var map     = new JSONDataMap {
                { "year", "1980" }, { "p1", "par1" }, { "v1", 10 }, { "v2", "val2" }
            };

            var uri = pattern.MakeURI(map);

            Aver.AreObjectsEqual(new Uri("1980/values?par1%3D10%26par2%3Dval2", UriKind.RelativeOrAbsolute), uri);
        }
Exemple #24
0
        public void MultipartMap(JSONDataMap map)
        {
            var fld    = Encoding.UTF8.GetBytes(map["field"].AsString());
            var txt    = Encoding.UTF8.GetBytes(map["text"].AsString());
            var bin    = map["bin"] as byte[];
            var output = WorkContext.Response.GetDirectOutputStreamForWriting();

            output.Write(fld, 0, fld.Length);
            output.Write(txt, 0, txt.Length);
            output.Write(bin, 0, bin.Length);
        }
Exemple #25
0
        private static Amount?parseAmount(JSONDataMap map)
        {
            if (map == null)
            {
                return(null);
            }
            var currencyISO = map["currency"].AsString();
            var value       = map["value"].AsDecimal();

            return(new Amount(currencyISO, value));
        }
Exemple #26
0
        public static JSONDataMap GetValueMap(Uri uri, IWebClientCaller caller,
                                              HTTPRequestMethod method = HTTPRequestMethod.GET,
                                              IDictionary <string, string> queryParameters = null,
                                              IDictionary <string, string> bodyParameters  = null,
                                              IDictionary <string, string> headers         = null)
        {
            string responseStr = GetString(uri, caller, method, queryParameters: queryParameters, bodyParameters: bodyParameters, headers: headers);
            var    dict        = JSONDataMap.FromURLEncodedString(responseStr);

            return(dict);
        }
Exemple #27
0
        public void MakeURI_T1_noprefix()
        {
            var pattern = new URIPattern("/news/{year}/{month}/{title}");
            var map     = new JSONDataMap {
                { "year", "1981" }, { "month", 12 }, { "title", "some_title" }
            };

            var uri = pattern.MakeURI(map);

            Aver.AreObjectsEqual(new Uri("/news/1981/12/some_title", UriKind.RelativeOrAbsolute), uri);
        }
Exemple #28
0
        /// <summary>
        /// Used for injection of pre-parsed value list
        /// </summary>
        public FieldAttribute(
            JSONDataMap valueList,
            string targetName    = ANY_TARGET,
            StoreFlag storeFlag  = StoreFlag.LoadAndStore,
            bool key             = false,
            DataKind kind        = DataKind.Text,
            bool required        = false,
            bool visible         = true,
            object dflt          = null,
            object min           = null,
            object max           = null,
            int minLength        = 0,
            int maxLength        = 0,
            CharCase charCase    = CharCase.AsIs,
            string backendName   = null,
            string backendType   = null,
            string description   = null,
            string metadata      = null,
            bool nonUI           = false,
            string formatRegExp  = null,
            string formatDescr   = null,
            string displayFormat = null
            ) : base(targetName, metadata)
        {
            if (valueList == null)
            {
                throw new DataException("FieldAttribute(JSONDataMap valueList==null)");
            }

            StoreFlag         = storeFlag;
            BackendName       = backendName;
            BackendType       = backendType;
            Key               = key;
            Kind              = kind;
            Required          = required;
            Visible           = visible;
            Min               = min;
            Max               = max;
            Default           = dflt;
            MinLength         = minLength;
            MaxLength         = maxLength;
            CharCase          = charCase;
            Description       = description;
            NonUI             = nonUI;
            FormatRegExp      = formatRegExp;
            FormatDescription = formatDescr;
            DisplayFormat     = displayFormat;

            m_CacheValueListPresetInCtor = true;
            m_CacheValueList_Insensitive = valueList;
            m_CacheValueList_Sensitive   = valueList;
            ValueList = null;
        }
Exemple #29
0
        ////////private void drawSet(Graphics gr, float startX, int dataWidth, int height, CPUUsage[] cpuData, RAMUsage[] ramData)
        ////////{
        ////////  //======= CPU
        ////////  using (var br = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, dataWidth, height),
        ////////                                                                    Color.FromArgb(0xFF, 0x40, 0x00),
        ////////                                                                    Color.FromArgb(0x20, 0xFF, 0x00),
        ////////                                                                    90f))
        ////////  {
        ////////    using (var lp = new Pen(br, 1f))
        ////////    {
        ////////      float x = startX;
        ////////      for (int i = 0; i < cpuData.Length - 1; i++)
        ////////      {
        ////////        var datum = cpuData[i];
        ////////        gr.DrawLine(lp, x, height, x, (int)(height - (height * (datum.Value / 100f))));

        ////////        x += 1f;
        ////////      }
        ////////    }
        ////////  }

        ////////  //========= RAM
        ////////  using (var br = new System.Drawing.Drawing2D.LinearGradientBrush(new Rectangle(0, 0, dataWidth, height),
        ////////                                                                    Color.FromArgb(0xA0, 0xff, 0xc0, 0xff),
        ////////                                                                    Color.FromArgb(0x50, 0xc0, 0xc0, 0xff),
        ////////                                                                    90f))
        ////////  {
        ////////    using (var lp = new Pen(br, 1f))
        ////////    {
        ////////      float x = startX;
        ////////      for (int i = 0; i < ramData.Length - 1; i++)
        ////////      {
        ////////        var datum = ramData[i];
        ////////        gr.DrawLine(lp, x, height, x, (int)(height - (height * (datum.Value / 100f))));

        ////////        x += 1f;
        ////////      }
        ////////    }
        ////////  }
        ////////}

        private void addError(JSONDataMap datum, string type, Message msg, DateTime?lastErrorSample)
        {
            if (msg == null)
            {
                return;
            }
            if (!lastErrorSample.HasValue || (msg.UTCTimeStamp - lastErrorSample.Value).TotalSeconds > 1)
            {
                datum[type] = msg.UTCTimeStamp.ToString("dd HH:mm:ss");
                datum["LastErrorSample"] = msg.UTCTimeStamp;
            }
        }
Exemple #30
0
        public void MakeURI_T1_prefix()
        {
            var pattern = new URIPattern("{year}/{month}/{title}");
            var prefix  = new Uri("http://test.com");
            var map     = new JSONDataMap {
                { "year", "1981" }, { "month", 12 }, { "title", "some_title" }
            };

            var uri = pattern.MakeURI(map, prefix);

            Aver.AreObjectsEqual(new Uri(prefix, "http://test.com/1981/12/some_title"), uri);
        }
Exemple #31
0
        public void MakeURI_T2_params_prefix()
        {
            var pattern = new URIPattern("{year}/values?{p1}={v1}&par2={v2}");
            var map     = new JSONDataMap {
                { "year", "1980" }, { "p1", "par1" }, { "v1", 10 }, { "v2", "val2" }
            };
            var prefix = new Uri("http://test.org/");

            var uri = pattern.MakeURI(map, prefix);

            Assert.AreEqual(new Uri("http://test.org/1980/values?par1%3D10%26par2%3Dval2", UriKind.RelativeOrAbsolute), uri);
        }
Exemple #32
0
        protected override void DoAfterWork(WorkContext work, JSONDataMap matched)
        {
            var txt = matched[VAR_ERROR].AsString();

            if (txt.IsNotNullOrWhiteSpace())
            {
                throw new WaveException(txt);
            }
            else
            {
                work.Aborted = true;
            }
        }
Exemple #33
0
        private string extractVerifier(JSONDataMap inboundParams)
        {
            var oauthToken    = inboundParams[OAUTH_TOKEN_PARAMNAME].AsString();
            var oauthVerifier = inboundParams[OAUTH_VERIFIER_PARAMNAME].AsString();

            if (oauthToken.IsNullOrWhiteSpace() || oauthVerifier.IsNullOrWhiteSpace())
            {
                throw new NFXException(StringConsts.ARGUMENT_ERROR + GetType().Name
                                       + ".ExtractVerifier(inboundParams.Contains({0}&{1}))".Args(OAUTH_TOKEN_PARAMNAME, OAUTH_VERIFIER_PARAMNAME));
            }

            return(oauthVerifier);
        }
Exemple #34
0
        public override JSONDataMap Make(WorkContext work, object context = null)
        {
            var result = base.Make(work, context);

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

            foreach (var match in m_ANDMatches.OrderedValues)
            {
                var capture = match.Make(work, context);
                if (capture == null)
                {
                    return(null);
                }

                if (CaptureMatches && match.CompositeCapture)
                {
                    result.Append(capture, true);
                }
            }


            var         any              = false;
            JSONDataMap orCapture        = null;
            var         compositeCapture = false;

            foreach (var match in m_ORMatches.OrderedValues)
            {
                any       = true;
                orCapture = match.Make(work, context);
                if (orCapture != null)
                {
                    compositeCapture = match.CompositeCapture;
                    break;
                }
            }

            if (any && orCapture == null)
            {
                return(null);
            }

            if (CaptureMatches && compositeCapture && orCapture != null)
            {
                result.Append(orCapture);
            }

            return(result);
        }
Exemple #35
0
        /// <summary>
        /// Decides whether the specified WorkContext makes the match per this instance and if it does, returns the match variables.
        /// Returns null if match was not made
        /// </summary>
        public virtual JSONDataMap Make(WorkContext work, object context = null)
        {
            if (
                !Check_Methods(work) ||
                !Check_AcceptTypes(work) ||
                !Check_ContentTypes(work) ||
                !Check_IsLocal(work) ||
                !Check_Hosts(work) ||
                !Check_Ports(work) ||
                !Check_Schemes(work) ||
                !Check_UserAgents(work) ||
                !Check_UserHosts(work) ||
                !Check_Permissions(work) ||
                !Check_Cookies(work) ||
                !Check_AbsentCookies(work) ||
                !Check_IsSocialNetBot(work) ||
                !Check_IsSearchCrawler(work) ||
                !Check_Headers(work) ||
                !Check_AbsentHeaders(work) ||
                !Check_ApiVersions(work)
                )
            {
                return(null);
            }

            JSONDataMap result = null;

            if (m_PathPattern != null)
            {
                result = m_PathPattern.MatchURIPath(work.Request.Url);
                if (result == null)
                {
                    return(null);
                }
            }

            if (m_NotPathPattern != null)
            {
                if (m_NotPathPattern.MatchURIPath(work.Request.Url) != null)
                {
                    return(null);
                }
            }

            if (!Check_VariablesAndGetValues(work, ref result))
            {
                return(null);
            }

            return(result ?? new JSONDataMap(false));
        }
Exemple #36
0
#pragma warning disable 1570
        /// <summary>
        /// Parses query string (e.g. "id=457&name=zelemhan") into dictionary (e.g. {{"id", "457"}, {"name", "zelemhan"}})
        /// </summary>
#pragma warning restore 1570
        public static JSONDataMap ParseQueryString(string query)
        {
            if (query.IsNullOrWhiteSpace())
            {
                return(new JSONDataMap());
            }

            var dict     = new JSONDataMap();
            int queryLen = query.Length;

            int startIdx = 0;

            while (startIdx < queryLen)
            {
                int ampIdx = query.IndexOf('&', startIdx);
                int kvLen  = (ampIdx != -1) ? ampIdx - startIdx : queryLen - startIdx;

                if (kvLen < 1)
                {
                    startIdx = ampIdx + 1;
                    continue;
                }

                int eqIdx = query.IndexOf('=', startIdx, kvLen);
                if (eqIdx == -1)
                {
                    var key = Uri.UnescapeDataString(query.Substring(startIdx, kvLen));
                    dict.Add(key, null);
                }
                else
                {
                    int keyLen = eqIdx - startIdx;
                    if (keyLen > 0)
                    {
                        string key    = Uri.UnescapeDataString(query.Substring(startIdx, keyLen));
                        string val    = null;
                        int    valLen = kvLen - (eqIdx - startIdx) - 1;
                        if (valLen > 0)
                        {
                            val = Uri.UnescapeDataString(query.Substring(eqIdx + 1, kvLen - (eqIdx - startIdx) - 1));
                        }
                        dict.Add(key, val);
                    }
                }

                startIdx += kvLen + 1;
            }

            return(dict);
        }
Exemple #37
0
        protected override void DoAfterWork(WorkContext work, JSONDataMap matched)
        {
            var code  = matched[VAR_CODE].AsInt();
            var error = matched[VAR_ERROR].AsString();

            if (code > 0)
            {
                throw new HTTPStatusException(code, error);
            }
            else
            {
                work.Aborted = true;
            }
        }
Exemple #38
0
            public payoutBatch(JSONDataMap map)
            {
                if (map.ContainsKey("batch_header"))
                {
                    BatchHeader = new payoutBatchHeader(map["batch_header"] as JSONDataMap);
                }
                else
                {
                    throw new PaymentException(GetType().Name + ".ctor(batch_header is null)");
                }
                var items = (map["items"] as JSONDataArray) ?? Enumerable.Empty <object>();

                Items = new List <payoutItemDetails>(items.Select(item => new payoutItemDetails(item as JSONDataMap)));
            }
Exemple #39
0
        public void JSONDataMapFromURLEncoded_Esc()
        {
            string[] strs = { " ", "!", "=", "&", "\"zele/m\\h()an\"" };

            foreach (var str in strs)
            {
                var query = "a=" + Uri.EscapeDataString(str);

                var dict = JSONDataMap.FromURLEncodedString(query);

                Aver.AreEqual(1, dict.Count);
                Aver.AreObjectsEqual(str, dict["a"]);
            }
        }
Exemple #40
0
        private JSONDataMap doObject()
        {
            fetchPrimary();    // skip {

            var obj = new JSONDataMap();

            if (token.Type != JSONTokenType.tBraceClose) //empty object  {}
            {
                while (true)
                {
                    if (token.Type != JSONTokenType.tIdentifier && token.Type != JSONTokenType.tStringLiteral)
                    {
                        errorAndAbort(JSONMsgCode.eObjectKeyExpected);
                    }

                    var key = token.Text;

                    if (obj.ContainsKey(key))
                    {
                        errorAndAbort(JSONMsgCode.eDuplicateObjectKey);
                    }

                    fetchPrimary();
                    if (token.Type != JSONTokenType.tColon)
                    {
                        errorAndAbort(JSONMsgCode.eColonOperatorExpected);
                    }

                    fetchPrimary();

                    var value = doAny();

                    obj[key] = value;

                    fetchPrimary();
                    if (token.Type != JSONTokenType.tComma)
                    {
                        break;
                    }
                    fetchPrimary();
                }

                if (token.Type != JSONTokenType.tBraceClose)
                {
                    errorAndAbort(JSONMsgCode.eUnterminatedObject);
                }
            }
            return(obj);
        }
      /// <summary>
      /// Generates JSON object suitable for passing into WV.RecordModel.Record(...) constructor on the client.
      /// Pass target to select attributes targeted to ANY target or to the specified one, for example
      ///  may get attributes for client data entry screen that sees field metadata differently, in which case target will reflect the name
      ///   of the screen
      /// </summary>
      public static JSONDataMap RowToRecordInitJSON(Row row, Exception validationError, string recID = null, string target = null, string isoLang = null)
      {
        var result = new JSONDataMap();
        if (row==null) return result;
        if (recID.IsNullOrWhiteSpace()) recID = Guid.NewGuid().ToString();

        result["OK"] = true;
        result["ID"] = recID;
        if (isoLang.IsNotNullOrWhiteSpace())
          result["ISOLang"] = isoLang;

        //20140914 DKh
        if (row is FormModel)
        {
          result[FormModel.JSON_MODE_PROPERTY] = ((FormModel)row).FormMode;
          result[FormModel.JSON_CSRF_PROPERTY] = ((FormModel)row).CSRFToken;
        }
        
        var fields = new JSONDataArray();
        result["fields"] = fields;

        var schemaName = row.Schema.Name;
        if (row.Schema.TypedRowType!=null) schemaName = row.Schema.TypedRowType.FullName;

        foreach(var fdef in row.Schema.FieldDefs.Where(fd=>!fd.NonUI))
        {
          var fld = new JSONDataMap();
          fields.Add(fld);
          fld["def"] = fieldDefToJSON(schemaName, fdef, target);
          fld["val"] = row.GetFieldValue(fdef);
          var ferr = validationError as CRUDFieldValidationException;
          //field level exception
          if (ferr!= null && ferr.FieldName==fdef.Name)
          {
            fld["error"] = ferr.ToMessageWithType();
            fld["errorText"] = localizeString(schemaName, "errorText", ferr.ClientMessage);
          }
        }

        //record level
        if (validationError!=null && !(validationError is CRUDFieldValidationException))
        {
          result["error"] = validationError.ToMessageWithType();
          result["errorText"] = localizeString(schemaName, "errorText", validationError.Message);
        }

        return result;
      }   
Exemple #42
0
#pragma warning disable 1570
    /// <summary>
    /// Parses query string (e.g. "id=457&name=zelemhan") into dictionary (e.g. {{"id", "457"}, {"name", "zelemhan"}})
    /// </summary>
#pragma warning restore 1570
    public static JSONDataMap ParseQueryString(string query)
    {
      if (query.IsNullOrWhiteSpace()) return new JSONDataMap();

      var dict = new JSONDataMap();
      int queryLen = query.Length;

      int startIdx = 0;
      while (startIdx < queryLen)
      {
        int ampIdx = query.IndexOf('&', startIdx);
        int kvLen = (ampIdx != -1) ? ampIdx - startIdx : queryLen - startIdx;

        if (kvLen < 1)
        {
          startIdx = ampIdx + 1;
          continue;
        }

        int eqIdx = query.IndexOf('=', startIdx, kvLen);
        if (eqIdx == -1)
        {
          var key = Uri.UnescapeDataString(query.Substring(startIdx, kvLen));
          dict.Add(key, null);
        }
        else
        {
          int keyLen = eqIdx - startIdx;
          if (keyLen > 0)
          {
            string key = Uri.UnescapeDataString(query.Substring(startIdx, keyLen));
            string val = null;
            int valLen = kvLen - (eqIdx - startIdx) - 1;
            if (valLen > 0)
              val = Uri.UnescapeDataString(query.Substring(eqIdx + 1, kvLen - (eqIdx - startIdx) - 1));
            dict.Add(key, val);
          }
        }

        startIdx += kvLen + 1;
      }

      return dict;
    }
Exemple #43
0
        /// <summary>
        /// Converts request body and MatchedVars into a single JSONDataMap. Users should call WholeRequestAsJSONDataMap.get() as it caches the result
        /// </summary>
        protected virtual JSONDataMap GetWholeRequestAsJSONDataMap()
        {
            var body = this.RequestBodyAsJSONDataMap;

            if (body==null) return MatchedVars;

            var result = new JSONDataMap(false);
            result.Append(MatchedVars)
              .Append(body);
            return result;
        }
Exemple #44
0
          private Transaction createPayoutTransaction(PaySession session, ITransactionContext context, JSONDataMap response, Account to, Amount amount, string description = null)
          {                                                             
              var batchID = response.GetNodeByPath(RESPONSE_BATCH_HEADER, RESPONSE_BATCH_ID);
              object itemID = null;
              var items = response.GetNodeByPath(RESPONSE_ITEMS) as JSONDataArray;
              if (items != null && items.Count > 0)
              {
                  // for the moment there is only one possible payment in a batch
                  itemID = ((JSONDataMap)items[0]).GetNodeByPath(RESPONSE_ITEMS_ITEMID);
              }

              var processorToken = new { batchID = batchID.AsString(), itemID = itemID.AsString() };
              var transactionDate = response.GetNodeByPath(RESPONSE_BATCH_HEADER, RESPONSE_TIME_COMPLETED)
                                            .AsDateTime(App.TimeSource.UTCNow);

              var transactionID = PaySystemHost.GenerateTransactionID(session, context, TransactionType.Transfer);
              
              return new Transaction(transactionID, 
                                     TransactionType.Transfer, 
                                     this.Name, processorToken, 
                                     Account.EmptyInstance, 
                                     to, 
                                     amount, 
                                     transactionDate, 
                                     description);
          }
Exemple #45
0
        /// <summary>
        /// Converts BSON document to JSON data map by directly mapping 
        ///  BSON types into corresponding CLR types. The sub-documents get mapped into JSONDataObjects,
        ///   and BSON arrays get mapped into CLR object[]
        /// </summary>
        public virtual JSONDataMap BSONDocumentToJSONMap(BSONDocument doc, Func<BSONDocument, BSONElement, bool> filter = null)
        {
          if (doc==null) return null;

          var result = new JSONDataMap(true);
          foreach(var elm in doc)
          {
             if (filter!=null)
              if (!filter(doc, elm)) continue;

             var clrValue = DirectConvertBSONValue(elm, filter);
             result[elm.Name] = clrValue;
          }

          return result;
        }
Exemple #46
0
      protected virtual JSONDataMap FieldDefToJSON(string schema, Schema.FieldDef fdef, string target, string isoLang = null)
      {
        var result = new JSONDataMap();

        result["Name"] = fdef.Name;
        result["Type"] = MapCLRTypeToJS(fdef.NonNullableType);
        var key = fdef.AnyTargetKey;
        if (key) result["Key"] = key; 
                               

        if (fdef.NonNullableType.IsEnum)
        { //Generate default lookupdict for enum
          var names = Enum.GetNames(fdef.NonNullableType);
          var values = new JSONDataMap(true);
          foreach(var name in names)
            values[name] = name;

          result["LookupDict"] = values;
        }

        var attr = fdef[target];
        if (attr!=null)
        {
            if (attr.Description!=null) result["Description"] = OnLocalizeString(schema, "Description", attr.Description, isoLang);
            var str =  attr.StoreFlag==StoreFlag.OnlyStore || attr.StoreFlag==StoreFlag.LoadAndStore;
            if (!str) result["Stored"] = str;
            if (attr.Required) result["Required"] = attr.Required;
            if (!attr.Visible) result["Visible"] = attr.Visible;
            if (attr.Min!=null) result["MinValue"] = attr.Min;
            if (attr.Max!=null) result["MaxValue"] = attr.Max;
            if (attr.MinLength>0) result["MinSize"] = attr.MinLength;
            if (attr.MaxLength>0) result["Size"]    = attr.MaxLength;        
            if (attr.Default!=null) result["DefaultValue"] = attr.Default;
            if (attr.ValueList.IsNotNullOrWhiteSpace())
            {
              var vl = OnLocalizeString(schema, "LookupDict", attr.ValueList, isoLang);
              result["LookupDict"] = FieldAttribute.ParseValueListString(vl);
            }
            if (attr.Kind!=DataKind.Text) result["Kind"] = MapCLRKindToJS(attr.Kind);
        }

        if (attr.Metadata!=null)
        {
            foreach(var fn in METADATA_FIELDS)
            { 
              var mv = attr.Metadata.AttrByName(fn).Value; 
              if (mv.IsNullOrWhiteSpace()) continue;
                
              if (fn=="Description"||fn=="Placeholder"||fn=="LookupDict"||fn=="Hint")
                mv = OnLocalizeString(schema, fn, mv, isoLang);

              result[fn] = mv;
            }
        }


        return result;
      }
Exemple #47
0
      public void T_14_RowCycle_TransitiveCycle_3()
      {
          var root = new JSONDataMap();

          root["a"] = 1;
          root["b"] = true;
          root["array"] = new JSONDataArray(){1,2,3,true,true,root};  //TRANSITIVE(via another instance) CYCLE!!!!
            
          var rc = new RowConverter(); 
      
          var doc = rc.ConvertCLRtoBSON(null, root, "A");//exception
      }
Exemple #48
0
 public object InboundJSONMapEcho(JSONDataMap data)
 {
     return data;
 }
Exemple #49
0
 public object JSONMapAndPrimitive_JSONFirst(JSONDataMap map, int n, string s)
 {
     map["ID"] = n;
       map["Name"] = s;
       return map; // or you could write: new JSONResult(map, JSONWritingOptions.CompactRowsAsMap);
 }
Exemple #50
0
        public void Templatization_Recursive()
        {
            var map1 = new JSONDataMap { { "a", 1 } };
              var map2 = new JSONDataMap { { "b", 2 }, { "c", map1 } };
              map1.Add("d", map2);

              var qry = new BSONDocument("{ rec: '$$value' }", true, new TemplateArg("value", map1));
        }
Exemple #51
0
        protected virtual Schema.FieldDef GetFieldDefFromJSON(JSONDataMap def)
        {
            var name = def["Name"].AsString();
              var type = MapJSToCLRType(def["Type"].AsString());
              var key = def["Key"].AsBool(false);
              var description = def["Description"].AsString(null);
              var required = def["Required"].AsBool(false);
              var visible = def["Visible"].AsBool(true);
              var minValue = def["MinValue"];
              var maxValue = def["MaxValue"];
              var minLength = def["MinSize"].AsInt(0);
              var maxLength = def["Size"].AsInt(0);
              var defaultValue = def["DefaultValue"];
              var kind = MapJSToCLRKind(def["Kind"].AsString());
              var charCase = MapJSToCLRCharCase(def["Case"].AsString());

              var stored = def["Stored"].AsNullableBool();
              var storeFlag = (stored == false) ? StoreFlag.OnlyLoad : StoreFlag.LoadAndStore;

              var lookupValues = def["LookupDict"] as JSONDataMap;

              var metadata = Configuration.NewEmptyRoot();
              foreach (var kvp in def)
              {
            if (kvp.Value == null) continue;
            metadata.AddAttributeNode(kvp.Key, kvp.Value);
              }
              var mcontent = metadata.ToLaconicString(LaconfigWritingOptions.Compact);

              var attr = lookupValues == null ?
                 new FieldAttribute(
                   targetName: TargetedAttribute.ANY_TARGET,
                   storeFlag: storeFlag,
                   key: key,
                   kind: kind,
                   required: required,
                   visible: visible,
                   dflt: defaultValue,
                   min: minValue,
                   max: maxValue,
                   minLength: minLength,
                   maxLength: maxLength,
                   charCase: charCase,
                   description: description,
                   metadata: mcontent
                   // nonUI = false,
                   // formatRegExp = null,
                   // formatDescr  = null,
                   // displayFormat = null
                   ) :
                   new FieldAttribute(
                   valueList: lookupValues,
                   targetName: TargetedAttribute.ANY_TARGET,
                   storeFlag: storeFlag,
                   key: key,
                   kind: kind,
                   required: required,
                   visible: visible,
                   dflt: defaultValue,
                   min: minValue,
                   max: maxValue,
                   minLength: minLength,
                   maxLength: maxLength,
                   charCase: charCase,
                   description: description,
                   metadata: mcontent
                   // nonUI = false,
                   // formatRegExp = null,
                   // formatDescr  = null,
                   // displayFormat = null
                   );

              var fdef = new Schema.FieldDef(name, type, attr);

              return fdef;
        }
Exemple #52
0
        /// <summary>
        /// Tries to match the pattern against the URI path section and returns a JSONDataMap match object filled with pattern match or NULL if pattern could not be matched.
        /// JSONDataMap may be easily converted to dynamic by calling new JSONDynamicObject(map)
        /// </summary>
        public JSONDataMap MatchURIPath(Uri uri, bool senseCase = false)
        {
            JSONDataMap result = null;
              if (m_MatchChunks.Count==0) return new JSONDataMap(false);

              var segs = uri.LocalPath.Split('/');

              var ichunk = -1;
              chunk chunk = null;
              var wildCard = false;
              foreach(var seg in segs)
              {
               if (seg.Length==0) continue;//skip empty ////

               if (!wildCard)
               {
            ichunk++;
            if (ichunk>=m_MatchChunks.Count) return null;
            chunk = m_MatchChunks[ichunk];
               }

               if (chunk.Portion!=chunkPortion.Path) return null;

               if (chunk.IsWildcard)
               {
             wildCard = true;
             if (result==null) result = new JSONDataMap(false);
             if (!result.ContainsKey(chunk.Name))
                result[chunk.Name] = seg;
             else
                result[chunk.Name] = (string)result[chunk.Name] + '/' + seg;
               }
               else
               if (chunk.IsVar)
               {
              if (result==null) result = new JSONDataMap(false);
              result[chunk.Name] = seg;
               }
               else
               if (!chunk.Name.Equals(seg, senseCase ? StringComparison.InvariantCulture : StringComparison.InvariantCultureIgnoreCase)) return null;
              }//foreach

              ichunk++;
              while(ichunk<m_MatchChunks.Count)
              {
            chunk=m_MatchChunks[ichunk];
            if (!chunk.IsVar) return null;//some trailing elements that are not vars and  do not match
            if (result==null)
              result = new JSONDataMap(false);
            if (!result.ContainsKey(chunk.Name))
              result[chunk.Name] = chunk.DefaultValue;
            ichunk++;
              }

              return result ?? new JSONDataMap(false);
        }
Exemple #53
0
 private void ctor(JSONDataMap init)
 {
     m_Init = init;
       var schema = MapInitToSchema();
       __ctor(schema);
       LoadData();
 }
Exemple #54
0
 /// <summary>
 /// Internal method. Developers do not call
 /// </summary>
 internal void ___SetWorkMatch(WorkMatch match, JSONDataMap vars){m_Match = match; m_MatchedVars = vars;} 
        public DropBoxPhotoObjectMetadata(JSONDataMap dataMap)
        {
            if (dataMap == null) throw new ArgumentNullException("dataMap");

            _dataMap = dataMap;
        }
Exemple #56
0
 public object JSONMapAndPrimitive_JSONMiddle(int n, JSONDataMap map, string s)
 {
     map["ID"] = n;
       map["Name"] = s;
       return map;//new JSONResult(map, JSONWritingOptions.CompactRowsAsMap);
 }
Exemple #57
0
        protected override void DoObtainTokens(SocialUserInfo userInfo, JSONDataMap request, string returnPageURL)
        {
          var code = request[ACCESSTOKEN_CODE_PARAMNAME].AsString();

          if (code.IsNullOrWhiteSpace())
            throw new NFXException( StringConsts.ARGUMENT_ERROR + GetType().Name + ".GetUserInfo(request should contain code)");

          FacebookSocialUserInfo fbUserInfo = userInfo as FacebookSocialUserInfo;

          string returnURL = PrepareReturnURLParameter(returnPageURL);

          fbUserInfo.AccessToken = getAccessToken( code, returnURL);
        }
Exemple #58
0
        /// <summary>
        /// Returns a string parsed into key values as:  val1: descr1,val2: desc2...
        /// </summary>
        public static JSONDataMap ParseValueListString(string valueList, bool caseSensitiveKeys = false)
        {
            var result = new JSONDataMap(caseSensitiveKeys);
            if (valueList.IsNullOrWhiteSpace()) return result;

            var segs = valueList.Split(',','|',';');
            foreach(var seg in segs)
            {
              var i = seg.LastIndexOf(':');
              if (i>0&&i<seg.Length-1) result[seg.Substring(0,i).Trim()] = seg.Substring(i+1).Trim();
              else
                result[seg] = seg;
            }

            return result;
        }
Exemple #59
0
 private static void checkPayoutStatus(JSONDataMap response)
 {
     var batchStatus = response.GetNodeByPath(RESPONSE_BATCH_HEADER, RESPONSE_BATCH_STATUS);
     if (batchStatus.AsString() != RESPONSE_SUCCESS)
     {
         var errorName = response.GetNodeByPath(RESPONSE_ERRORS, RESPONSE_ERRORS_NAME);
         var errorMessage = response.GetNodeByPath(RESPONSE_ERRORS, RESPONSE_ERRORS_MESSAGE);
         var errorDescription = response.GetNodeByPath(RESPONSE_ERRORS, RESPONSE_ERRORS_DETAILS);
         var message = StringConsts.PAYPAL_PAYOUT_DENIED_MESSAGE.Args(errorName ?? EMPTY, 
                                                                      errorMessage ?? EMPTY, 
                                                                      errorDescription ?? EMPTY);
     
         throw new PayPalPaymentException(message);      
     }
 }
Exemple #60
0
        private void checkPayoutStatus(JSONDataMap response, PayPalSession payPalSession)
        {
            var batchStatus = response.GetNodeByPath(RESPONSE_BATCH_HEADER, RESPONSE_BATCH_STATUS).AsString();
              if (!batchStatus.EqualsIgnoreCase(RESPONSE_SUCCESS))
              {
                throwPaymentException(response.GetNodeByPath(RESPONSE_ERRORS, RESPONSE_ERRORS_NAME).AsString(),
                                      response.GetNodeByPath(RESPONSE_ERRORS, RESPONSE_ERRORS_MESSAGE).AsString(),
                                      response.GetNodeByPath(RESPONSE_ERRORS, RESPONSE_ERRORS_DETAILS).AsString());
              }

              var items = response[RESPONSE_ITEMS] as JSONDataArray;
              if (items == null || items.Count<=0) return;

              // for the moment there is only one possible payment in a batch
              var item = (JSONDataMap)items[0];
              var status = item[RESPONSE_ITEM_TRAN_STATUS].AsString();

              //todo: cancel unclaimed transaction?
              if (status.EqualsIgnoreCase(RESPONSE_ITEM_UNCLAIMED))
              {
                var itemID = item[RESPONSE_ITEMS_ITEMID].AsString();
                cancelUnclaimedPayout(itemID, payPalSession);

                throwPaymentException(item.GetNodeByPath(RESPONSE_ITEM_ERRORS, RESPONSE_ITEM_ERRORS_NAME).AsString(),
                                      item.GetNodeByPath(RESPONSE_ITEM_ERRORS, RESPONSE_ITEM_ERRORS_MESSAGE).AsString(),
                                      EMPTY);
              }

              //todo: other statuses https://developer.paypal.com/docs/api/payments.payouts-batch#payouts_get
              if (!status.EqualsIgnoreCase(RESPONSE_ITEM_SUCCESS))
              {
                throwPaymentException(item.GetNodeByPath(RESPONSE_ITEM_ERRORS, RESPONSE_ITEM_ERRORS_NAME).AsString(),
                                      item.GetNodeByPath(RESPONSE_ITEM_ERRORS, RESPONSE_ITEM_ERRORS_MESSAGE).AsString(),
                                      status);
              }
        }