Example #1
0
        async void StartHttp()
        {
            // NOTE: For an `async void` function, we have to wrap all its code
            // inside try-catch-block, so that exception does NOT leak into unknown world.
            try
            {
                string url = edtURL.Text;
                int    timeout_millisec = int.Parse(edtTimeoutMs.Text);

                AsyncHttp.HeaderDict headers = new AsyncHttp.HeaderDict()
                {
                    {
                        HttpRequestHeader.UserAgent,
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; Trident/7.0; rv:11.0) like Gecko"
                    },
                };

                string postbody = "MyPostText";
                postbody = null;

                AsyncHttp ahttp = new AsyncHttp(url, headers, postbody);

                _cts = new CancellationTokenSource();

                logtid($"HTTP starts. \r\n" +
                       $"  URL:     {url}\r\n" +
                       $"  Timeout: {timeout_millisec} millisec"
                       ); // note: "\n" only does not cause line break

                _tskHttp = ahttp.StartAsText(_cts.Token, timeout_millisec);
                string body = await _tskHttp;

                logtid(
                    $"HTTP success. Body bytes: {ahttp._respbody_bytes.Length}, body chars: {ahttp._respbody_text.Length}");
            }
            catch (Exception e)
            {
                UIPromptException(e);
            }
            finally
            {
                if (_tskHttp != null)
                {
                    _tskHttp.Dispose();
                }

                _tskHttp = null;
            } // try-block end
        }     // async function end
Example #2
0
        }     // async function end

        async Task StartStress()
        {
            try
            {
                string url              = edtURL.Text;
                int    cycles           = int.Parse(edtStressCycles.Text);
                int    timeout_millisec = int.Parse(edtTimeoutMs.Text);

                bool is_eager_report = ckbEagerReport.Checked;

                Stopwatch sw = new Stopwatch();
                sw.Restart();
                long msec_prev = 0;
                long msec_now  = 0;

                var dict_bytes2count = new Dictionary <int, int>(); // map http response-body bytes to count

                AsyncHttp.HeaderDict headers = new AsyncHttp.HeaderDict()
                {
                    {
                        HttpRequestHeader.UserAgent,
                        "Mozilla/5.0 (Windows NT 10.0; Win64; x64; Trident/7.0; rv:11.0) like Gecko"
                    },
                };

                string postbody = "MyPostText";
                postbody = null;

                for (int i = 0; i < cycles; i++)
                {
                    AsyncHttp ahttp = new AsyncHttp(url, headers, postbody);

                    _cts = new CancellationTokenSource();

                    if (is_eager_report)
                    {
                        logtid($"HTTP starts. {url}");
                    }

                    _tskHttp = ahttp.StartAsText(_cts.Token, timeout_millisec);
                    string body = await _tskHttp;

                    int nrbyte = ahttp._respbody_bytes.Length;
                    int nrchar = ahttp._respbody_text.Length;
                    if (dict_bytes2count.ContainsKey(nrbyte))
                    {
                        dict_bytes2count[nrbyte]++;
                    }
                    else
                    {
                        dict_bytes2count[nrbyte] = 1;
                    }

                    if (is_eager_report)
                    {
                        logtid(
                            $"[{i}]HTTP success. Body bytes: {nrbyte}, body chars: {nrchar}");
                    }
                    else // not eager report, report every 1 second
                    {
                        msec_now = sw.ElapsedMilliseconds;
                        if (msec_now - msec_prev >= 1000)
                        {
                            logtid($"{i+1} success");
                            msec_prev = msec_now;
                        }
                    }
                }

                // print summary

                string info = "HTTP response summary:\r\n";
                foreach (int nrbyte in dict_bytes2count.Keys.OrderBy(key => key))
                {
                    string oneline = $"    [{nrbyte} bytes] {dict_bytes2count[nrbyte]} occurrence.";
                    info += oneline + "\r\n";
                }
                logtid(info);

                logtid($"Total milliseconds cost: {sw.ElapsedMilliseconds}");
            }
            catch (Exception e)
            {
                UIPromptException(e);
            }
            finally
            {
//                _tskHttp.Dispose();
                _tskHttp = null;
            } // try-block end
        }
        public Response DesignerApiProcessing(ref AsyncHttp.Server.RequestContext ctx)
        {
            AsyncHttp.Server.Response response = null;
            try
            {
                NameValueCollection pars = new NameValueCollection();
                pars.Add(ctx.Request.HttpParams.QueryString);

                Stream fileStream = null;
                if (ctx.Request.HttpMethod.Equals("POST", StringComparison.InvariantCultureIgnoreCase) && ctx.Request.HttpParams.FormParams != null)
                {
                    pars.Add(ctx.Request.HttpParams.FormParams);
                    fileStream = ctx.Request.HttpParams.FirstFileStream;
                }

                var res = DesignerApi(pars, fileStream);
                if (pars.AllKeys.Contains("operation") && pars["operation"] == "downloadscheme")
                {
                    response = new StringResponse(res, "file/xml", new Dictionary<string, string>() {
                        {"Content-Disposition", "attachment; filename=schema.xml"}
                    });
                }
                else
                {
                    response = new StringResponse(res);
                }
            }
            catch (Exception ex)
            {
                if (this.Parameters.Log != null)
                    this.Parameters.Log(ex.ToString());
                response = new EmptyResponse(404);
            }
            return response;
        }
        public Response WorkflowApiProcessing(ref AsyncHttp.Server.RequestContext ctx)
        {
            object data = string.Empty;
            string error = string.Empty;

            try
            {
                string operation = ctx.Request.HttpParams.QueryString["operation"];
                if (string.IsNullOrWhiteSpace(operation))
                {
                    throw new Exception("Parameter 'operation' is required!");
                }

                Guid processid;
                if (!Guid.TryParse(ctx.Request.HttpParams.QueryString["processid"], out processid))
                {
                    throw new Exception("Parameter 'processid' is required and must be is GUID!");
                }
                var identityid = ctx.Request.HttpParams.QueryString["identityid"];
                var impersonatedIdentityId = ctx.Request.HttpParams.QueryString["impersonatedIdentityId"];
                Dictionary<string, object> parameters = JsonSerializer.DeserializeFromString<Dictionary<string, object>>(ctx.Request.HttpParams.QueryString["parameters"]);
                CultureInfo culture = CultureInfo.CurrentUICulture;
                if (!string.IsNullOrWhiteSpace(ctx.Request.HttpParams.QueryString["culture"]))
                {
                    culture = new CultureInfo(ctx.Request.HttpParams.QueryString["culture"]);
                }

                switch (operation.ToLower())
                {
                    case "createinstance":
                        var schemacode = ctx.Request.HttpParams.QueryString["schemacode"];
                        if (string.IsNullOrWhiteSpace(schemacode))
                        {
                            throw new Exception("Parameter 'schemacode' is required!");
                        }

                        if (parameters == null)
                            parameters = new Dictionary<string, object>();

                        _runtime.CreateInstance(schemacode, processid, identityid, impersonatedIdentityId, parameters);
                        break;

                    case "getavailablecommands":
                        data = JsonSerializer.SerializeToString(_runtime.GetAvailableCommands(processid, new List<string>() { identityid }, null, impersonatedIdentityId));
                        break;

                    case "executecommand":
                        var command = ctx.Request.HttpParams.QueryString["command"];
                        var wfcommand = _runtime.GetAvailableCommands(processid, new List<string>() { identityid }, command, impersonatedIdentityId).FirstOrDefault();
                        _runtime.ExecuteCommand(processid, identityid, impersonatedIdentityId, wfcommand);
                        break;

                    case "getavailablestatetoset":
                        data = JsonSerializer.SerializeToString(_runtime.GetAvailableStateToSet(processid, culture));
                        break;

                    case "setstate":
                        var state = ctx.Request.HttpParams.QueryString["state"];

                        if (parameters == null)
                            parameters = new Dictionary<string, object>();

                        _runtime.SetState(processid, identityid, impersonatedIdentityId, state, parameters);
                        break;

                    case "isexistprocess":
                        data = JsonSerializer.SerializeToString(_runtime.IsProcessExists(processid));
                        break;
                    default:
                        throw new Exception(string.Format("operation={0} is not suported!", operation));
                }
            }
            catch (Exception ex)
            {
                error = string.Format("{0}{1}",
                    ex.Message, ex.InnerException == null ? string.Empty :
                            string.Format(". InnerException: {0}", ex.InnerException.Message));
            }

            var res = JsonSerializer.SerializeToString(new
            {
                data = data,
                success = error.Length == 0,
                error = error
            });
            return new StringResponse(res);
        }