示例#1
0
        public object CallLambda(object function, dynamic options, dynamic values)
        {
            if (!(function is string functionText))
            {
                throw new ApplicationException($"{nameof(CallLambda)}: {nameof(function)} must be a string");
            }

            LambdaRequestOptions lambdaOptions = ProcessLambdaRequestOptions(options);

            string data   = null;
            var    native = ConvertToNative(values);

            if (native != null)
            {
                data = JsonConvert.SerializeObject(native);
            }

            var response = lambdaService.Invoke(functionText, data);

            if (lambdaOptions.KeepResponseAsString)
            {
                return(response);
            }

            var result = JsonConvert.DeserializeObject <dynamic>(response);

            return(ScriptHelpers.ToScriptValue(result, ScriptContext));
        }
        private static Dictionary <string, object> TestConversion(string testJson, string code)
        {
            V8Runtime v8Runtime = new V8Runtime();

            using (var context = v8Runtime.CreateScriptEngine())
            {
                var result   = JsonConvert.DeserializeObject <dynamic>(testJson);
                var jsValues = ScriptHelpers.ToScriptValue(result, context);
                context.AddHostObject("s", jsValues);

                Assert.IsTrue((bool)context.Evaluate(code));

                return(ConvertJsToNative(jsValues));
            }
        }
示例#3
0
        public object MakeWebRequestEx(object apiUrl, object apiMethod, dynamic options, dynamic values)
        {
            if (!(apiUrl is string apiUrlText))
            {
                throw new ApplicationException($"{nameof(MakeWebRequestEx)}: {nameof(apiUrl)} must be a string");
            }
            if (!(apiMethod is string apiMethodText))
            {
                throw new ApplicationException($"{nameof(MakeWebRequestEx)}: {nameof(apiMethod)} must be a string");
            }

            int tries       = 0;
            int dnsAttempts = 1;
            WebRequestOptions webRequestOptions = ProcessWebRequestOptions(options);

            do
            {
                logger.InfoFormat("Script: Calling web url: {0}", apiUrlText);
                Uri uri = new Uri(apiUrlText);  // Makes sure the url is valid

                try
                {
                    // Using older WebClient class since it has non-async methods.
                    // We can't use Async calls here because we aren't passing the async/await context through javscript.
                    // That requires using the javascript callback method and makes the javascript more complex.
                    using (WebClientEx wc = new WebClientEx(webRequestOptions.Timeout))
                    {
                        // fix for possible performance issue with WebClient class
                        // https://stackoverflow.com/questions/4932541/c-sharp-webclient-acting-slow-the-first-time
                        wc.Proxy = null;

                        Stopwatch sw = new Stopwatch();
                        sw.Start();

                        if (DummyMode)
                        {
                            wc.Headers.Add("X-DummyMode", "True");
                        }

                        // Add headers
                        if (webRequestOptions.Headers != null)
                        {
                            foreach (var header in webRequestOptions.Headers)
                            {
                                wc.Headers.Add(header.Key, header.Value?.ToString());
                            }
                        }

                        string response;

                        if (apiMethodText.Equals("GET", StringComparison.OrdinalIgnoreCase))
                        {
                            response = wc.DownloadString(uri);
                        }
                        else
                        {
                            string data = null;
                            if (webRequestOptions.KeepRequestAsString)
                            {
                                data = values;
                            }
                            else
                            {
                                var native = ConvertToNative(values);
                                if (native != null)
                                {
                                    data = JsonConvert.SerializeObject(native);
                                }
                            }

                            logger.DebugFormat("Script: Request: {0}", data);
                            response = wc.UploadString(uri, apiMethodText, data);
                        }

                        logger.DebugFormat("Script: Response: {0}", response);

                        sw.Stop();
                        var elapsedTime = sw.Elapsed.TotalSeconds;
                        if ((ChatConfiguration.DefaultRestAPIWarnSendTime >= 0) && (elapsedTime > ChatConfiguration.DefaultRestAPIWarnSendTime))
                        {
                            logger.WarnFormat("Network: MakeWebRequestEx() took {0} seconds. Url: {1}", elapsedTime, uri);
                        }

                        if (webRequestOptions.KeepResponseAsString)
                        {
                            return(response);
                        }

                        var result = JsonConvert.DeserializeObject <dynamic>(response);
                        return(ScriptHelpers.ToScriptValue(result, ScriptContext));
                    }
                }
                catch (WebException ex)
                {
                    if (ex.Status == WebExceptionStatus.NameResolutionFailure)
                    {
                        // WebClient gets DNS failures sometimes, so we auto retry.
                        if (++dnsAttempts <= MaxDnsAttempts)
                        {
                            logger.WarnFormat("Script: Warning DNS failure. Retrying: {0}", apiUrl);

                            // dont count as regulare try
                            tries--;
                            continue;
                        }

                        logger.ErrorFormat("Script: Error calling url {0}. {1}, {2}", apiUrl, ex.Status, ex.ToString());
                        return(null);
                    }

                    logger.ErrorFormat("Script: Error calling url {0}. {1}, {2}", apiUrl, ex.Status, ex.ToString());

                    if (ex.Status == WebExceptionStatus.ProtocolError)
                    {
                        var webResponse = (HttpWebResponse)ex.Response;

                        var errorBody = new StreamReader(webResponse.GetResponseStream()).ReadToEnd();
                        logger.DebugFormat("Script: Error Response: {0}", errorBody);

                        if (((int)webResponse.StatusCode >= 400) && ((int)webResponse.StatusCode <= 499))
                        {
                            // log 400 error. not re-try-able);
                            break;
                        }
                    }
                }
            } while (tries++ < webRequestOptions.Retries);

            return(null);
        }