public async Task <ReqResult> Forward()
        {
            _driver.Navigate().Forward();


            return(ReqResult.Success());
        }
Exemple #2
0
        public async Task <ReqResult[]> AddImages(int itemId, IFormFile[] images)
        {
            var    processResults = new ReqResult[images.Length];
            string itemFolder     = Path.Combine(this.itemPath, itemId.ToString());

            if (!Directory.Exists(itemFolder))
            {
                this.CreateDirectory(itemId);
            }
            foreach (var image in images)
            {
                string imagePath = Path.Combine(itemFolder, image.FileName);

                if (!File.Exists(imagePath))
                {
                    var fileStream = new FileStream(imagePath, FileMode.Create);
                    await image.CopyToAsync(fileStream);

                    fileStream.Close();
                    processResults.Append(ReqResult.Ok);
                }
                else
                {
                    processResults.Append(ReqResult.ImageExists);
                }
            }

            return(processResults);
        }
        protected async Task <ReqResult> BaseLogic(Task <HttpResponseMessage> request)
        {
            try
            {
                var result = await request;

                if (!result.IsSuccessStatusCode)
                {
                    return(ReqResult.Failed(await result.Content.ReadAsStringAsync()));
                }

                var netres = JsonConvert.DeserializeObject <ReqResult>(await result.Content.ReadAsStringAsync());

                if (netres == null)
                {
                    return(ReqResult.Failed());
                }
                else
                {
                    return(netres);
                }
            }
            catch (Exception)
            {
                return(ReqResult.Failed());
            }
        }
        public async Task <ReqResult> Nav(Nav urlOrWebsiteName)
        {
            var regex = new Regex(@"^http(s)?://([\w-]+.)+[\w-]+(/[\w- ./?%&=])?$");

            var s = _driver.FindElement();

            _driver.

            s.

            if (!regex.IsMatch(urlOrWebsiteName.urlOrName))
            {
                //handle malformed here
            }

            //Uri url = new Uri(urlOrWebsiteName.urlOrName);

            //Uri.CheckHostName("") == UriHostNameType.

            //UriBuilder build = new UriBuilder(urlOrWebsiteName.urlOrName);

            //if(build.Scheme == null)
            //build.Scheme = http;

            //todo url or name logic


            _driver.Url = $"?{urlOrWebsiteName.urlOrName}";

            return(ReqResult.Success());
        }
        public async Task <ReqResult> Back()
        {
            _driver.Navigate().Back();


            return(ReqResult.Success());
        }
        public async Task <ReqResult> CloseBrowser()
        {
            _driver.Close();

            DriverDispose();

            return(ReqResult.Success());
        }
Exemple #7
0
        private async Task HandleClientRequest(HttpContext context)
        {
            HttpRequest  request  = context.Request;
            HttpResponse response = context.Response;

            if (shutdown)
            {
                response.StatusCode = 400; // BAD Request
                return;
            }

            try {
                if (request.Path == "/Mediator/" && context.WebSockets.IsWebSocketRequest)
                {
                    WebSocket webSocket = await context.WebSockets.AcceptWebSocketAsync();
                    await HandleClientWebSocket(webSocket);

                    return;
                }

                if (request.Method != "POST" || !HandleClientRequests.IsValid(request.Path))
                {
                    logger.Warn("Invalid request " + request.Path.ToUriComponent());
                    response.StatusCode = 400; // BAD Request
                    return;
                }

                //logger.Info("Client request: " + request.Path);

                JObject obj = null;
                using (var body = request.Body) {
                    using (var reader = new StreamReader(body, Encoding.UTF8)) {
                        obj = await StdJson.JObjectFromReaderAsync(reader);

                        //logger.Info("ReqStr: " + StdJson.ObjectToString(obj, true));
                    }
                }

                using (ReqResult result = await reqHandler.Handle(request.Path, obj)) {
                    //logger.Info(result.AsString());

                    response.StatusCode    = result.StatusCode;
                    response.ContentLength = result.Bytes.Length;
                    response.ContentType   = "application/json";

                    try {
                        await result.Bytes.CopyToAsync(response.Body);
                    }
                    catch (Exception) {
                        response.StatusCode = 500;
                    }
                }
            }
            catch (Exception exp) {
                response.StatusCode = 500;
                logger.Warn(exp.GetBaseException(), "Error handling client request");
            }
        }
        public async Task <ReqResult> Search(Bot.Lib.DTOs.Search query)
        {
            //check if I'm on bing
            //if not nav to bing
            //check if the two search input fields are there
            //if not fail

            return(ReqResult.Success());
        }
Exemple #9
0
        public async Task <ReqResult> UiReq_ConfigWidgetSetWidth(string pageID, int row, int col, int widget, string newWidth)
        {
            CheckActivePage(pageID);
            activePage !.ConfigWidgetSetWidth(row, col, widget, newWidth);
            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK(activePage.Page));
        }
Exemple #10
0
        public async Task <ReqResult> UiReq_ConfigWidgetDelete(string pageID, string widgetID)
        {
            CheckActivePage(pageID);
            await     activePage !.ConfigWidgetDelete(widgetID);
            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK(activePage.Page));
        }
Exemple #11
0
        public async Task <ReqResult> UiReq_ConfigPageRename(string pageID, string title)
        {
            CheckActivePage(pageID);
            activePage !.Page.Name = title;
            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK());
        }
Exemple #12
0
        public async Task <ReqResult> UiReq_ConfigRemoveCol(string pageID, int row, int col)
        {
            CheckActivePage(pageID);
            activePage !.ConfigRemoveCol(row, col);
            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK(activePage.Page));
        }
Exemple #13
0
        public async Task <ReqResult> UiReq_ConfigInsertRow(string pageID, int row, bool below)
        {
            CheckActivePage(pageID);
            activePage !.ConfigInsertRow(row, below);
            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK(activePage.Page));
        }
Exemple #14
0
        public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters)
        {
            switch (command)
            {
            case "Load": {
                TimeRange?time = parameters.Object <TimeRange>();
                if (time == null)
                {
                    throw new Exception("TimeRange is null");
                }

                var alarms = await GetActiveAlarms();

                var events = await GetEvents(time, alarms);

                lastAlarms    = alarms;
                lastEvents    = events;
                lastTimeRange = time;

                return(ReqResult.OK(new {
                        Alarms = alarms,
                        Events = events
                    }));
            }

            case "AckReset": {
                AckResetParams?para = parameters.Object <AckResetParams>();
                if (para == null)
                {
                    throw new Exception("AckResetParams is null");
                }
                string method  = para.Ack ? "Ack" : "Reset";
                var    comment = new NamedValue("Comment", para.Comment);
                var    keys    = new NamedValue("Keys", string.Join(';', para.Timestamps.Select(x => x.ToString(CultureInfo.InvariantCulture))));
                await Connection.CallMethod(Module, method, comment, keys);

                var alarms = await GetActiveAlarms();

                var events = await GetEvents(para.TimeRange, alarms);

                lastAlarms    = alarms;
                lastEvents    = events;
                lastTimeRange = para.TimeRange;

                return(ReqResult.OK(new {
                        Alarms = alarms,
                        Events = events
                    }));
            }

            default:
                return(ReqResult.Bad("Unknown command: " + command));
            }
        }
Exemple #15
0
        public async Task <ReqResult> UiReq_ConfigPageDelete(string pageID)
        {
            CheckActivePage(pageID);
            await DeactivatePage();

            configuration.Pages = configuration.Pages.Where(p => p.ID != pageID).ToArray();

            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK());
        }
Exemple #16
0
        public JsonResult GetCategoryGmktResult(ReqData data)
        {
            CommonBiz biz = new CommonBiz();
            List<CategoryGmktInfoT> categories = biz.GetGmktCategory(data.Step, data.ParentCode);

            ReqResult result = new ReqResult();
            result.ReturnForm = data.ReturnForm;
            result.CategoryGmkt = new List<CategoryGmktInfoT>();
            result.CategoryGmkt = categories;

            return Json(result);
        }
Exemple #17
0
        public IActionResult CreateImageDirectory(int itemId)
        {
            ReqResult result = _item.CreateDirectory(itemId);

            if (result == ReqResult.Ok)
            {
                return(Ok());
            }
            else
            {
                return(StatusCode(500));
            }
        }
Exemple #18
0
        public async Task <ReqResult> UiReq_ReadVar()
        {
            if (configuration.Variable.HasValue)
            {
                VTQ vtq = await Connection.ReadVariable(configuration.Variable.Value);

                return(ReqResult.OK(vtq.V.JSON));
            }
            else
            {
                return(ReqResult.OK(""));
            }
        }
Exemple #19
0
        public async Task <ReqResult> UiReq_Init()
        {
            if (configuration.Pages.Length > 0)
            {
                await UiReq_SwitchToPage(configuration.Pages.First().ID);
            }

            var result = ReqResult.OK(new {
                configuration,
                widgetTypes = widgetTypes.Keys.OrderBy(s => s).ToArray()
            });

            return(result);
        }
Exemple #20
0
        public static async Task <ReqResult> GetItemsData(Connection connection, ObjectRef[] usedObjects)
        {
            var modules = (await connection.GetModules())
                          .Where(m => m.HasNumericVariables)
                          .Select(m => new ModuleInfo()
            {
                ID   = m.ID,
                Name = m.Name
            }).ToArray();

            var objectMap = new Dictionary <string, ObjInfo>();

            // ObjectRef[] objects = configuration.Items.Select(it => it.Variable.Object).Distinct().ToArray();

            ObjectInfos infos;

            try {
                infos = await connection.GetObjectsByID(usedObjects);
            }
            catch (Exception) {
                infos = new ObjectInfos(usedObjects.Length);
                for (int i = 0; i < usedObjects.Length; ++i)
                {
                    ObjectRef obj = usedObjects[i];
                    try {
                        infos.Add(await connection.GetObjectByID(obj));
                    }
                    catch (Exception) {
                        infos.Add(new ObjectInfo(obj, "???", "???"));
                    }
                }
            }

            foreach (ObjectInfo info in infos)
            {
                var numericVariables = info.Variables.Where(IsNumericOrBool).Select(v => v.Name).ToArray();
                objectMap[info.ID.ToEncodedString()] = new ObjInfo()
                {
                    Name      = info.Name,
                    Variables = numericVariables
                };
            }

            return(ReqResult.OK(new {
                ObjectMap = objectMap,
                Modules = modules,
            }));
        }
Exemple #21
0
        public async Task <ReqResult> UiReq_SavePlot(PlotConfig plot)
        {
            bool reloadData =
                configuration.PlotConfig.MaxDataPoints != plot.MaxDataPoints ||
                configuration.PlotConfig.FilterByQuality != plot.FilterByQuality ||
                configuration.PlotConfig.LeftAxisLimitY != plot.LeftAxisLimitY ||
                configuration.PlotConfig.RightAxisLimitY != plot.RightAxisLimitY;

            configuration.PlotConfig = plot;

            await Context.SaveWidgetConfiguration(configuration);

            return(ReqResult.OK(new {
                ReloadData = reloadData
            }));
        }
Exemple #22
0
        public async Task <ReqResult> UiReq_SwitchToPage(string pageID)
        {
            if (pageID != "" && !Pages.ContainsKey(pageID))
            {
                throw new Exception($"Unknown page id: {pageID}");
            }

            await DeactivatePage();

            if (pageID != "")
            {
                PageState page = Pages[pageID];
                await page.OnActivate();

                activePage = page;
            }

            return(ReqResult.OK());
        }
        public async Task <ReqResult> OpenBrowser()
        {
            try
            {
                if (_driver == null)
                {
                    Setup();
                }

                _driver.Manage().Window.Maximize();

                _driver.Url = bing;

                return(ReqResult.Success());
            }
            catch (Exception)
            {
                return(ReqResult.Failed());
            }
        }
Exemple #24
0
        public async Task <ReqResult> UiReq_ReadModuleObjects(string ModuleID)
        {
            ObjectInfos objects;

            try {
                objects = await Connection.GetAllObjects(ModuleID);
            }
            catch (Exception) {
                objects = new ObjectInfos();
            }

            return(ReqResult.OK(new {
                Items = objects.Where(o => o.Variables.Any(IsNumericOrBool)).Select(o => new {
                    Type = o.ClassName,
                    ID = o.ID.ToEncodedString(),
                    Name = o.Name,
                    Variables = o.Variables.Where(IsNumericOrBool).Select(v => v.Name).ToArray()
                }).ToArray()
            }));
        }
Exemple #25
0
        public async Task <ReqResult> UiReq_SaveItems(ItemConfig[] items)
        {
            VariableRef[] newVariables = items.Select(it => it.Variable).ToArray();
            bool          reloadData   = !Arrays.Equals(newVariables, Variables);

            Variables = newVariables;

            configuration.Items = items;

            await Context.SaveWidgetConfiguration(configuration);

            if (reloadData)
            {
                Task ignored = Connection.EnableVariableHistoryChangedEvents(Variables);
            }

            return(ReqResult.OK(new {
                ReloadData = reloadData
            }));
        }
Exemple #26
0
        public async Task <ReqResult> UiReq_SaveItems(VarItem[] items)
        {
            VariableRef[] newVariables = items.Select(it => it.Variable).ToArray();
            bool          reloadData   = !Arrays.Equals(newVariables, Variables);

            Variables = newVariables;

            configuration.Items = items;

            await Context.SaveWidgetConfiguration(configuration);

            if (reloadData)
            {
                Task ignored  = Connection.EnableVariableValueChangedEvents(SubOptions.AllUpdates(sendValueWithEvent: true), Variables);
                Task ignored2 = Connection.EnableVariableHistoryChangedEvents(Variables);
            }

            var values = await LoadData(updateTrend : reloadData);

            return(ReqResult.OK(values));
        }
Exemple #27
0
        public async Task <ReqResult> UiReq_ConfigPageMoveRight(string pageID)
        {
            CheckActivePage(pageID);

            int i = configuration.Pages.ToList().FindIndex(p => p.ID == pageID);

            if (i < 0 || i >= configuration.Pages.Length - 1)
            {
                throw new Exception("Can't move right");
            }

            var tmp = configuration.Pages[i];

            configuration.Pages[i]     = configuration.Pages[i + 1];
            configuration.Pages[i + 1] = tmp;

            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK());
        }
Exemple #28
0
        public async Task <ReqResult> UiReq_ConfigPageDuplicate(string pageID, string newPageID, string title)
        {
            CheckActivePage(pageID);

            string pageCopy = StdJson.ObjectToString(activePage !.Page);
            var    page     = StdJson.ObjectFromString <Page>(pageCopy) !;

            page.ID   = newPageID;
            page.Name = title;

            var pages = configuration.Pages.ToList();

            pages.Add(page);
            configuration.Pages = pages.ToArray();

            Pages[page.ID] = new PageState(page, Connection, widgetTypes, this);

            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK(configuration.Pages));
        }
Exemple #29
0
        public virtual async Task <ReqResult> OnUiRequestAsync(string command, JObject parameters)
        {
            if (mapUiReqMethods.ContainsKey(command))
            {
                UiReqMethod method = mapUiReqMethods[command];
                method.ResetValues();

                foreach (JProperty p in parameters.Properties())
                {
                    if (method.ParameterMap.ContainsKey(p.Name))
                    {
                        UiReqPara para = method.ParameterMap[p.Name];
                        para.Value = p.Value.ToObject(para.Type);
                    }
                }

                object?[] paramValues = method.Parameters.Select(p => p.Value).ToArray();
                return(await method.TheDelegate(paramValues));
            }

            return(ReqResult.Bad("Unknown command: " + command));
        }
Exemple #30
0
        public async Task <ReqResult> UiReq_ConfigPageAdd(string pageID, string title)
        {
            var page = new Page()
            {
                ID   = pageID,
                Name = title,
                Rows = new Row[] {
                    new Row()
                    {
                        Columns = new Column[] {
                            new Column(),
                            new Column(),
                        }
                    },
                    new Row()
                    {
                        Columns = new Column[] {
                            new Column(),
                            new Column(),
                        }
                    }
                }
            };

            var pages = configuration.Pages.ToList();

            pages.Add(page);
            configuration.Pages = pages.ToArray();

            Pages[page.ID] = new PageState(page, Connection, widgetTypes, this);

            DataValue newViewConfig = DataValue.FromObject(configuration, indented: true);
            await Context.SaveViewConfiguration(newViewConfig);

            return(ReqResult.OK(configuration.Pages));
        }
Exemple #31
0
        public override async Task <ReqResult> OnUiRequestAsync(string command, DataValue parameters)
        {
            bool hasModuleID = !string.IsNullOrEmpty(configuration.ModuleID);

            moduleID = hasModuleID ? configuration.ModuleID : "CALC";

            switch (command)
            {
            case "GetModel": {
                ObjectInfo root = await Connection.GetRootObject(moduleID);

                RootID = root.ID;

                await Connection.EnableVariableValueChangedEvents(SubOptions.AllUpdates(sendValueWithEvent: true), root.ID);

                return(await GetModelResult());
            }

            case "Save": {
                SaveParams saveParams = parameters.Object <SaveParams>() ?? throw new Exception("SaveParams is null");
                string     objID      = saveParams.ID;
                IDictionary <string, JToken?> dict = saveParams.Obj;
                MemberValue[] members = dict
                                        .Where(kv => kv.Key != "ID")
                                        .Select(entry => MakeMemberValue(objID, entry))
                                        .ToArray();
                await Connection.UpdateConfig(members);

                return(await GetModelResult());
            }

            case "Delete": {
                ObjectRef obj = ObjectRef.Make(moduleID, parameters.GetString() ?? "");
                await Connection.UpdateConfig(ObjectValue.Make(obj, DataValue.Empty));

                return(await GetModelResult());
            }

            case "AddObject": {
                AddObjectParams addParams = parameters.Object <AddObjectParams>() ?? throw new Exception("AddObjectParams is null");
                ObjectRef       objParent = ObjectRef.Make(moduleID, addParams.ParentObjID);
                DataValue       dataValue = DataValue.FromObject(new {
                        ID   = addParams.NewObjID,
                        Name = addParams.NewObjName
                    });
                var element = AddArrayElement.Make(objParent, addParams.ParentMember, dataValue);
                await Connection.UpdateConfig(element);

                return(await GetModelResult());
            }

            case "MoveObject": {
                var  move = parameters.Object <MoveObject_Params>() ?? throw new Exception("MoveObject_Params is null");
                bool up   = move.Up;

                ObjectRef  obj     = ObjectRef.Make(moduleID, move.ObjID);
                ObjectInfo objInfo = await Connection.GetObjectByID(obj);

                MemberRefIdx?parentMember = objInfo.Parent;

                if (parentMember.HasValue)
                {
                    MemberValue value = await Connection.GetMemberValue(parentMember.Value.ToMemberRef());

                    DataValue v = value.Value;
                    if (v.IsArray)
                    {
                        JArray array = (JArray)StdJson.JTokenFromString(v.JSON);
                        int    index = parentMember.Value.Index;
                        if (up && index > 0)
                        {
                            JToken tmp = array[index - 1];
                            array[index - 1] = array[index];
                            array[index]     = tmp;

                            MemberValue mv = MemberValue.Make(parentMember.Value.ToMemberRef(), DataValue.FromObject(array));
                            await Connection.UpdateConfig(mv);
                        }
                        else if (!up && index < array.Count - 1)
                        {
                            JToken tmp = array[index + 1];
                            array[index + 1] = array[index];
                            array[index]     = tmp;

                            MemberValue mv = MemberValue.Make(parentMember.Value.ToMemberRef(), DataValue.FromObject(array));
                            await Connection.UpdateConfig(mv);
                        }
                    }
                }

                return(await GetModelResult());
            }

            case "ReadModuleObjects": {
                var pars = parameters.Object <ReadModuleObjectsParams>() ?? throw new Exception("ReadModuleObjectsParams is null");

                ObjectInfos objects;

                try {
                    objects = await Connection.GetAllObjects(pars.ModuleID);
                }
                catch (Exception) {
                    objects = new ObjectInfos();
                }

                Func <Variable, bool> isMatch = GetMatchPredicate(pars.ForType);

                return(ReqResult.OK(new {
                        Items = objects.Where(o => o.Variables.Any(isMatch)).Select(o => new {
                            Type = o.ClassName,
                            ID = o.ID.ToEncodedString(),
                            Name = o.Name,
                            Variables = o.Variables.Where(isMatch).Select(v => v.Name).ToArray()
                        }).ToArray()
                    }));
            }

            default:
                return(ReqResult.Bad("Unknown command: " + command));
            }
        }