Example #1
0
        public static HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context)
        {
            var state = _state.As<MonitorState>() ?? new MonitorState();

            state = Execute(jsons, state);

            var result = ImmutableGenerator.Generate(System.IO.File.ReadAllText(context.HttpContext.Server.MapPath("~/Examples/Main.cs")));
            var originalResult = System.IO.File.ReadAllText(context.HttpContext.Server.MapPath("~/Examples/Main.g.cs"));

            var page = h.Html(
              h.Head
              (
              ),
              h.Body
              (
                  result == originalResult,
                  h.Div(DateTime.UtcNow)
              )
            );
            return new HtmlResult<HElement>
            {
                Html = page,
                State = state,
            };

        }
Example #2
0
    public static NitroBolt.Wui.HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context)
    {
      var state = _state.As<MainState>() ?? new MainState();

      foreach (var json in jsons.OrEmpty())
      {

        switch (json.JPath("data", "command")?.ToString())
        {
          case "text":
            state = state.With(text: json.JPath("value")?.ToString());
            System.Threading.Thread.Sleep(new Random().Next(0, 500));
            break;
          default:            
            break;
        }
      }
     

      var page = Page(state);
      return new NitroBolt.Wui.HtmlResult<HElement>
      {
        Html = page,
        State = state,
      };
    }
    public string ProcessRequest(Dictionary<string, string> parameters, JsonData json)
    {

      var uri = parameters.Find("SCRIPT_NAME") + parameters.Find("PATH_INFO");
      var queryString = parameters.Find("QUERY_STRING");

      Console.WriteLine("{0} {1}, {2}", uri, queryString, Handlers.Select(pair => pair.Key).FirstOrDefault());

      var handlerPair = Handlers.FirstOrDefault(pair => uri?.StartsWith(pair.Key) ?? false);
      if (handlerPair.Value == null)
      {

        return "<html><body>invalid page</body></html>";
      }
      var handler = handlerPair.Value;
      var pageName = handlerPair.Key;

      if (uri.EndsWith(".js"))
      {
        var query = queryString.OrEmpty().Split('&').Select(pair => pair.Split('='))
          .ToDictionary(ss => ss.FirstOrDefault(), ss => ss.ElementAtOrDefault(1));
        var prevCycle = int.Parse(query.Find("cycle"));
        var prevUpdate = Updates.FirstOrDefault(_update => _update.Cycle == prevCycle);
        var prevPage = prevUpdate != null ? prevUpdate.Page : null;

        var update = PushUpdate(null);

        var result = handler(pageName, update.Cycle, json);
        //lock (locker)
        //{
        //  update.Page = result.Html;

        //}
        var page = result.Html;


        var commands = HtmlJavaScriptDiffer.JsSync(new HElementProvider(), prevPage == null ? null : prevPage.Element("body"), page.Element("body")).ToArray();
        var jupdate = new Dictionary<string, object>() { { "cycle", update.Cycle }, { "prev_cycle", prevCycle }, { "commands", commands } };

        var jsSerializer = new System.Web.Script.Serialization.JavaScriptSerializer();
        return jsSerializer.Serialize(jupdate);
      }
      else
      {
        var update = PushUpdate(null);

        var result = handler(pageName, update.Cycle, json);
        var page = result.Html;
        if (!uri.EndsWith(".raw.html"))
          page = h.Html(new HRaw(page.Element("head")?.ToString()), h.Body());

        //lock (locker)
        //{
        //  update.Page = page;
        //}
        return page.ToString();
      }
    }
Example #4
0
 public static List<int> GetSelectedLetterIds(JsonData json, TableLink letterTable)
 {
   List<int> selectedLetterIds = new List<int>();
   foreach (RowLink letter in letterTable.AllRows)
   {
     int letterId = letter.Get(LetterType.Id);
     if (json.GetText(string.Format("check_{0}", letterId)) == "True")
       selectedLetterIds.Add(letterId);
   }
   return selectedLetterIds;
 }
Example #5
0
        private static MonitorState Execute(JsonData[] jsons, MonitorState state)
        {

            foreach (var json in jsons.OrEmpty())
            {
                switch (json.JPath("data", "command")?.ToString())
                {

                }
            }
            return state;
        }
Example #6
0
    public static hevent FindEvent(this HElement page, JsonData json, bool isStrongBinding)
    {
      foreach (HElement element in RoundPage(page))
      {
        HEventElement eventElement = element as HEventElement;
        if (eventElement == null || eventElement.handler == null)
          continue;

        if (IsEventElement(json, eventElement.handler, isStrongBinding))
          return eventElement.handler;
      }
      return null;
    }
Example #7
0
        //
        //  см. также Global.Application_AuthenticateRequest
        //
        public static NitroBolt.Wui.HtmlResult<HElement> HView(object _state, JsonData[] jsons, HttpRequestMessage request)
        {
            Action<HttpResponseMessage> cookieSetter = null;
            var logins = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase) { { "Demo", "demodemo" }, { "Test", "test" } };

            foreach (var json in jsons.OrEmpty())
            {

                switch (json.JPath("data", "command")?.ToString())
                {
                    case "login":
                        {
                            var login = json.JPath("data", "login")?.ToString();
                            var password = json.JPath("data", "password")?.ToString();
                            if (logins.Find(login) == password)
                                cookieSetter = request.SetUserAndGetCookieSetter(login);
                            else
                            {
                                //display error
                            }
                        }
                        break;
                    case "logout":
                        cookieSetter = request.SetUserAndGetCookieSetter(null);
                        break;
                    default:
                        break;
                }

                if (request.UserName() != null)
                {
                    switch (json.JPath("data", "command")?.ToString())
                    {
                        default:
                            break;
                    }

                }
            }
            var account = request.UserName();


            var page = Page(logins, account, request);
            return new HtmlResult
            {
                Html = page,
                State = null,
                ResponseProcessor = cookieSetter,
            };
        }
Example #8
0
    public object Execute(JsonData jsonData)
    {
      object[] ids = ArrayHlp.Convert(this.ToArray(),
        delegate(HObject attr)
        { 
          return ((HAttribute)attr).Value; 
        }
      );
      return eventHandler(ids, jsonData);

      //object[] ids =  attributes.ConvertAll(delegate(HObject attr)
      //{ return ((HAttribute)attr).Value; }).ToArray();
      //return eventHandler(ids, jsonData);
    }
Example #9
0
        public static NitroBolt.Wui.HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context)
        {
            var state = _state.As<MainState>() ?? new MainState();

            foreach (var json in jsons.OrEmpty())
            {
                switch (json.JPath("data", "command")?.ToString())
                {
                    case "mouse-event":
                        {
                            var x = ConvertHlp.ToInt(json.JPath("data", "x"));
                            var y = ConvertHlp.ToInt(json.JPath("data", "y"));
                            if (x != null && y != null)
                            {
                                using (var client = new MouseClient(Zuma.VmIp))
                                {
                                    client.MoveTo(x.Value, y.Value, 800, 600);
                                }
                            }
                        }
                        break;
                    case "reset":
                        {
                            using (var client = new MouseClient(Zuma.VmIp))
                            {
                                client.Reset();
                            }
                        }
                        break;
                    case "screenshot":
                        {
                            new VmClient().Screenshot().Save(context.HttpContext.Server.MapPath($"~/App_Data/{DateTime.UtcNow.Ticks}.png"));
                        }
                        break;
                    default:
                        break;
                }
            }

            var page = Page(state);
            return new NitroBolt.Wui.HtmlResult<HElement>
            {
                Html = page,
                State = state,
            };
        }
Example #10
0
    public static bool IsEventElement(JsonData json, hevent handler, bool isStrongBinding)
    {
      foreach (HAttribute id in handler)
      {
        object jsonId = json.JPath(id.Name.LocalName.Split(new char[] { '-' }, StringSplitOptions.RemoveEmptyEntries));

        //Logger.AddMessage("IsEventElement: {0}, {1}", id, jsonId);
        if (jsonId == null)
          return false;

        if (isStrongBinding)
        {
          if (StringHlp.ToString(id.Value) != StringHlp.ToString(jsonId))
            return false;
        }
      }
      return true;
    }
Example #11
0
    public static HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context)
    {
      MailState state = _state.As<MailState>();
      if (state == null)
      {
        state = new MailState();
        Logger.AddMessage("Пересоздан state");
      }

      //Logger.AddMessage("Mail.Execute: {0}, {1}, {2}", 
      //  context.HttpContext.User.Identity.Name, context.HttpContext.Request.QueryString, jsons.Length);
 
      foreach (JsonData json in jsons)
      {
        try
        {
          Logger.AddMessage("Json: {0}", json);
          state.lastJson = json;
          HElement cachePage = Page(state, context.HttpContext);

          hevent eventh = cachePage.FindEvent(json, true);
          Logger.AddMessage("Event.Find: {0}", eventh != null);
          if (eventh != null)
          {
            eventh.Execute(json);
          }
        }
        catch (Exception ex)
        {
          Logger.WriteException(ex);
        }

      }

      var page = Page(state, context.HttpContext);
      return new HtmlResult<HElement>
      {
        Html = page,
        State = state,
        RefreshPeriod = TimeSpan.FromHours(1)
      };
    }
Example #12
0
     public static HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context)
    {
      var state = _state.As<SecondState>() ?? new SecondState();

      foreach (JsonData json in jsons)
      {
        switch (json.JPath("data", "command").ToString_Fair())
        {
          default:
            break;
        }
      }

      var page = Page();
      return new HtmlResult<HElement>
      {
        Html = page,
        State = state,
      };
    }
Example #13
0
        public static HtmlResult HView(object _state, JsonData[] jsons, HttpRequestMessage request)
        {
            var state = _state.As<MainState>() ?? new MainState();

            foreach (var json in jsons.OrEmpty())
            {

                switch (json.JPath("data", "command")?.ToString())
                {
                    case "text":
                        state = state.With(text: json.JPath("value")?.ToString());
                        System.Threading.Thread.Sleep(new Random().Next(0, 500));
                        break;
                    case "link":
                        state = state.With(text: "self:" + new Random().Next(1000));
                        break;
                    case "error":
                        throw new Exception("ошибка");
                    case "x":
                        state = state.With(text: json.JPath("value")?.ToString());
                        break;
                    case "x-container":
                        state = state.With(text: json.JPath("data", "x")?.ToString());
                        break;
                    case "array-name":
                        state = state.With(arrayNameResult: json.JPath("data", "x")?.ToString());
                        break;
                    default:
                        break;
                }
            }


            var page = Page(state);
            return new HtmlResult
            {
                Html = page,
                State = state,
            };
        }
Example #14
0
        public static NitroBolt.Wui.HtmlResult<HElement> HView(object _state, JsonData[] jsons, HttpRequestMessage request)
        {
            var state = _state.As<MainState>() ?? new MainState();

            foreach (var json in jsons.OrEmpty())
            {
                //var account = MemoryDatabase.World.Accounts.FirstOrDefault(_account => _account.Name == "darkgray");

                switch (json.JPath("data", "command")?.ToString())
                {
                    default:
                        //state = new MyLibState(new[] { new Message(json.ToString_Fair()) }.Concat(state.Messages).Take(10).ToArray());
                        break;
                }
            }


            var page = Page(state, request);
            return new NitroBolt.Wui.HtmlResult<HElement>
            {
                Html = page,
                State = state,
            };
        }
Example #15
0
    private static void ProcessRequest(bool isFcgiDebug, FcgiSynchronizer sync, Socket s)
    {
      using (s)
      using (var stream = new NetworkStream(s))
      {
        Log("accepted..");

        for (var i = 0; i < 20; ++i)
        {
          if (stream.DataAvailable)
            break;
          System.Threading.Thread.Sleep(TimeSpan.FromMilliseconds(30));
          if (i == 19)
          {
            Log("cancel");
            return;
          }
        }

        var parameters = new Dictionary<string, string>();
        for (; ; )
        {
          var req = stream.ReadRequest();
          if (isFcgiDebug)
            Log(string.Format("{0}:{1}, {2}:{3}:{4}", req.Version, req.Type, req.RequestId, req.Content.Hex(), req.Padding.Hex()));

          if (req.Type == FcgiType.Params)
          {
            var _parameters = ParseParameters(req.Content);
            if (_parameters.Count > 0)
            {
              parameters = _parameters;
              if (isFcgiDebug)
              {
                Log("parameters:");
                foreach (var pair in parameters)
                  Log(string.Format("  {0}:{1}", pair.Key, pair.Value));
              }
            }
          }
          JsonData json = null;
          if (req.Type == FcgiType.Stdin && req.Content != null && req.Content.Length > 0)
          {
            if (isFcgiDebug)
              Log("Stdin text: " + System.Text.Encoding.UTF8.GetString(req.Content));
            var data = ParseQuery(System.Text.Encoding.UTF8.GetString(req.Content));
            var values = data.ContainsKey("values") ? data["values"] : null;
            if (isFcgiDebug)
              Log("  " + values);
            //var jsSerializer = new System.Net.Json.JsonTextParser();
            var jsSerializer = Newtonsoft.Json.JsonSerializer.Create();
            json = new JsonData(jsSerializer.Deserialize(new Newtonsoft.Json.JsonTextReader(new System.IO.StringReader(values))));

          }
          if (req.Type == FcgiType.Stdin && req.Padding.Length == 0)
          {
            var res_text = string.Format(@"Content-type: text/html

{0}
", sync.ProcessRequest(parameters, json));
            var res_data = System.Text.Encoding.UTF8.GetBytes(res_text);
            var res_pad = new byte[8 - res_data.Length % 8];
            var res = new FcgiRequest { Version = 1, Type = FcgiType.Stdout, RequestId = req.RequestId, Content = res_data, Padding = res_pad };
            stream.Write(res);
            stream.Write(new FcgiRequest { Version = 1, Type = FcgiType.Stdout, RequestId = req.RequestId });
            stream.Write(new FcgiRequest { Version = 1, Type = FcgiType.EndRequest, RequestId = req.RequestId, Content = new byte[8] });
            break;
          }
        }
      }
    }
Example #16
0
    public static HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context)
    {
      var state = _state.As<MainState>() ?? new MainState();

      foreach (JsonData json in jsons)
      {
        switch (json.JPath("data", "command").ToString_Fair())
        {
          case "new-order":
            {
              var name = json.JPath("data", "name").ToString_Fair() ?? "C";
              var isDelivery = json.JPath("data", "is-delivery").ToString_Fair() == "True";
              var toTime = ToTime(json.JPath("data", "to-time").ToString_Fair());
              var status = toTime == null ? ProductStatus.New: ProductStatus.InQueue;
              var products = name == "B" ? new[] { new Product("K", status) } : new[] { new Product("M", status), new Product("P", status) };
              state = state.With(orders: state.Orders.Add(new Order(name: name, isDelivery: isDelivery, status: toTime == null ? OrderStatus.New: OrderStatus.InQueue, products: ImmutableArray.Create(products), toTime: toTime)));  
            }
            break;
          case "product-prepare":
            {
              var orderId = ConvertHlp.ToGuid(json.JPath("data", "order"));
              var productId = ConvertHlp.ToGuid(json.JPath("data", "product"));
              var order = state.Orders.FirstOrDefault(_order => _order.Id == orderId);
              var product = order._f(_ => _.Products).Else_Empty().FirstOrDefault(_product => _product.Id == productId);
              if (product != null && product.Status != ProductStatus.New)
                product = null;
              if (product != null)
              {
                state = state.With(orders: state.Orders.Replace(order, order.With(products: order.Products.Replace(product, product.With(status: ProductStatus.Prepare)))));
              }
            }
            break;
          case "product-ready":
            {
              var orderId = ConvertHlp.ToGuid(json.JPath("data", "order"));
              var productId = ConvertHlp.ToGuid(json.JPath("data", "product"));
              var order = state.Orders.FirstOrDefault(_order => _order.Id == orderId);
              var product = order._f(_ => _.Products).Else_Empty().FirstOrDefault(_product => _product.Id == productId);
              if (product != null && product.Status != ProductStatus.Prepare)
                product = null;
              if (product != null)
              {
                state = state.With(orders: state.Orders.Replace(order, order.With(products: order.Products.Replace(product, product.With(status: ProductStatus.Ready)))));
              }
            }
            break;
          case "order-build":
            {
              var orderId = ConvertHlp.ToGuid(json.JPath("data", "order"));
              var order = state.Orders.FirstOrDefault(_order => _order.Id == orderId);
              if (order != null && order.Status != OrderStatus.Prepare && !order.IsReady)
                order = null;
              if (order != null)
              {
                state = state.With(orders: state.Orders.Replace(order, order.With(status: OrderStatus.Ready)));
              }
            }
            break;
          case "courier":
            {
              var orderId = ConvertHlp.ToGuid(json.JPath("data", "order"));
              var courier = json.JPath("data", "courier").ToString_Fair();
              var order = state.Orders.FirstOrDefault(_order => _order.Id == orderId);
              if (order != null && order.Status != OrderStatus.Ready && !order.IsDelivery)
                order = null;
              if (order != null)
              {
                state = state.With(orders: state.Orders.Replace(order, order.With(status: OrderStatus.ToDelivery, courier: courier)));
              }
            }
            break;
          case "order-deliveried":
            {
              var orderId = ConvertHlp.ToGuid(json.JPath("data", "order"));
              var order = state.Orders.FirstOrDefault(_order => _order.Id == orderId);
              if (order != null && order.Status != OrderStatus.ToDelivery)
                order = null;
              if (order != null)
              {
                state = state.With(orders: state.Orders.Replace(order, order.With(status: OrderStatus.Deliveried)));
              }
            }
            break;
          case "order-to-table":
            {
              var orderId = ConvertHlp.ToGuid(json.JPath("data", "order"));
              var order = state.Orders.FirstOrDefault(_order => _order.Id == orderId);
              if (order != null && order.Status != OrderStatus.Ready && order.IsDelivery)
                order = null;
              if (order != null)
              {
                state = state.With(orders: state.Orders.Replace(order, order.With(status: OrderStatus.ToTable)));
              }
            }
            break;
          default:
            break;
        }
      }
      state = state.With(orders: DeQueue(state.Orders, DateTime.Now));

      var page = Page(state);
      return new HtmlResult<HElement>
      {
        Html = page,
        State = state,
      };
    }
Example #17
0
 static HtmlResult HViewRaw(object _state, JsonData[] jsons, HttpRequestMessage request)
 {
     var result = HView(_state, jsons, request);
     result.FirstHtmlTransformer = html => html;
     return result;
 }
Example #18
0
    //
    //  см. также Global.Application_AuthenticateRequest
    //
    public static HtmlResult<HElement> HView(object _state, JsonData[] jsons, HContext context)
    {

      var logins = new Dictionary<string, string>(StringComparer.InvariantCultureIgnoreCase){{"Demo", "demodemo"}, {"Test", "test"}};

      foreach (var json in jsons.Else_Empty())
      {

        switch (json.JPath("data", "command").ToString_Fair())
        {
          case "login":
            {
              var login = json.JPath("data", "login").ToString_Fair();
              var password = json.JPath("data", "password").ToString_Fair();
              if (logins.Find(login) == password)
                context.HttpContext.SetUserAndCookie(login);
              else
              {
                //display error
              }
            }
            break;
          case "logout":
            context.HttpContext.SetUserAndCookie(null);
            break;
          default:
            break;
        }

        if (context.HttpContext.UserName() != null)
        {
          switch (json.JPath("data", "command").ToString_Fair())
          {
            case "login":
              {
                var login = json.JPath("data", "login").ToString_Fair();
                var password = json.JPath("data", "password").ToString_Fair();
                if (logins.Find(login) == password)
                  context.HttpContext.SetUserAndCookie(login);
                else
                {
                  //display error
                }
              }
              break;
            case "logout":
              context.HttpContext.SetUserAndCookie(null);
              break;
            default:
              break;
          }

        }
      }
      var account = context.HttpContext.UserName();


      var page = Page(logins, account);
      return new HtmlResult<HElement>
      {
        Html = page,
        State = null,
      };
    }