Пример #1
0
        public void ReadValue(JsonAction <object, JsonValueType> value, JsonAction readArray, JsonAction readObject)
        {
            if (value is null)
            {
                throw new ArgumentNullException(nameof(value));
            }
            if (readArray is null)
            {
                throw new ArgumentNullException(nameof(readArray));
            }
            if (readObject is null)
            {
                throw new ArgumentNullException(nameof(readObject));
            }
            switch (Values.Peek().Type)
            {
            case JsonValueType.Array:
                readArray();
                return;

            case JsonValueType.Object:
                readObject();
                return;
            }
            if (JsonApi.HasFlag(Values.Peek().Type, JsonValueType.Value))
            {
                value(Values.Peek().Value, Values.Peek().Type);
                return;
            }
            throw new JsonNotSupportException(Values.Peek().Type);
        }
Пример #2
0
        public ActionResult SaveAppendix()
        {
            HelpPermissions.ViewHelp.AssertAuthorized();

            var ctx = this.ExtractEntity <AppendixHelpEntity>().ApplyChanges(this);

            var entity = ctx.Value;

            if (!entity.Title.HasText() && !entity.Description.HasText())
            {
                if (!entity.IsNew)
                {
                    entity.Delete();
                }

                return(JsonAction.RedirectAjax(RouteHelper.New().Action((HelpController a) => a.Index())));
            }
            else
            {
                var wasNew = entity.IsNew;

                entity.Execute(AppendixHelpOperation.Save);


                if (wasNew)
                {
                    return(JsonAction.RedirectAjax(RouteHelper.New().Action((HelpController a) => a.ViewAppendix(entity.UniqueName))));
                }
                return(null);
            }
        }
        public ActionResult UpdateRegions(Guid?CityId = null)
        {
            try
            {
                var regions = new core.Controllers.RegionController().GetList(CityId);
                regions.Insert(0, new Region()
                {
                    RegionName = "Select"
                });

                IEnumerable <SelectListItem> list = regions
                                                    .Select(o => new SelectListItem
                {
                    Value = o.RegionId.ToString(),
                    Text  = o.RegionName
                });

                var ret = new JsonAction
                {
                    success = true,
                    data    = list
                };

                ViewBag.Regions = list;

                return(Json(ret));
            }
            catch (Exception)
            {
                var ret = new JsonAction {
                    success = false, message = "Something's Wrong"
                };
                return(Json(ret));
            }
        }
Пример #4
0
        public void Add(HttpRequest httpRequest, HttpResponse httpResponse, object objRequest = null, object objResponse = null)
        {
            lock (View)
            {
                ++Count;
                JsonType   jsonType   = JsonType.Handshake;
                JsonAction jsonAction = JsonAction.Request;
                LogDevice  device     = LogDevice.Client;

                if (objRequest != null && objRequest is JsonPacket)
                {
                    JsonPacket  jsonRequest = (JsonPacket)objRequest;
                    JsonMessage jsonMessage = JsonMessage.Parse(jsonRequest.Message);
                    jsonAction = jsonMessage.Action;
                    jsonType   = jsonMessage.Type;

                    if (!httpRequest.HasSession())
                    {
                        device = LogDevice.Server;
                    }
                }

                StringBuilder sb = new StringBuilder();
                sb.Append("[ ").Append(device.ToString().ToUpper()).Append(" ]").Append(Constant.Newline);
                sb.Append("[ ").Append(jsonType.ToString().ToUpper()).Append(" ").Append(jsonAction.ToString().ToUpper()).Append(" ]");
                Add(sb);

                Add(httpRequest, objRequest, Suffix.EOM);
                Add(httpResponse, objResponse, Suffix.EOL);
            }
        }
Пример #5
0
    private void LoadAction(Subtask subtask, JsonAction jsonAction, string mode)
    {
        AppAction action = subtask.gameObject.AddComponent <AppAction>();

        action.actor      = AppController.instance.FindObjectByName(jsonAction.actor);
        action.actionName = jsonAction.name;
        action.parameters = new List <string>(jsonAction.parameters);
        action.parameters.Insert(0, mode.ToLower());
        subtask.Action = action;
    }
Пример #6
0
 public void ReadObject(JsonFunc <string, bool> key, JsonAction readValue)
 {
     if (key is null)
     {
         throw new ArgumentNullException(nameof(key));
     }
     if (readValue is null)
     {
         throw new ArgumentNullException(nameof(readValue));
     }
     Read(false, key, i => readValue());
 }
        private static JsonTimelineMessage CreateJsonTimelineMessage(JsonAction action, string type)
        {
            JsonTimelineMessage timelineMessage = new JsonTimelineMessage();
            string eventName = action.ToString("G");

            if (type != null)
            {
                eventName += " - " + RemoveAssemblyDetails(type);
            }
            timelineMessage.AsTimelineMessage(eventName, new TimelineCategoryItem(action.ToString("G"), "#B3DF00", "#9BBB59"));
            return(timelineMessage);
        }
Пример #8
0
        public void ReadValue(JsonAction <object, JsonValueType> value, JsonAction readArray, JsonAction readObject)
        {
            if (readArray is null)
            {
                throw new ArgumentNullException(nameof(readArray));
            }
            if (readObject is null)
            {
                throw new ArgumentNullException(nameof(readObject));
            }
            switch (Current.Type)
            {
            case JsonTokenType.Integer:
                value?.Invoke(Current.Value, JsonValueType.Integer);
                return;

            case JsonTokenType.Decimal:
                value?.Invoke(Current.Value, JsonValueType.Decimal);
                return;

            case JsonTokenType.String: {
                string text = Current;
                if (DateTime.TryParse(text, out DateTime dateTime))
                {
                    value?.Invoke(dateTime, JsonValueType.DateTime);
                    return;
                }
                value?.Invoke(Regex.Unescape(text), JsonValueType.String);
                return;
            }

            case JsonTokenType.Null:
                value?.Invoke(Current.Value, JsonValueType.Null);
                return;

            case JsonTokenType.Bool:
                value?.Invoke(Current.Value, JsonValueType.Bool);
                return;

            case JsonTokenType.LeftBracket:
                readArray();
                return;

            case JsonTokenType.LeftBrace:
                readObject();
                return;
            }
            throw new JsonTextReaderException(
                      this,
                      JsonKeyword.Null, "整数", "小数", JsonKeyword.True, JsonKeyword.False, "字符串", JsonKeyword.LeftBracket, JsonKeyword.LeftBrace
                      );
        }
Пример #9
0
 public void ReadValue(JsonAction <object, JsonValueType> value, JsonAction readArray, JsonAction readObject)
 {
     if (value is null)
     {
         throw new ArgumentNullException(nameof(value));
     }
     if (readArray is null)
     {
         throw new ArgumentNullException(nameof(readArray));
     }
     if (readObject is null)
     {
         throw new ArgumentNullException(nameof(readObject));
     }
     if (Stacks.Peek().ArrayType != JsonArrayType.Unknown)
     {
         readArray();
         return;
     }
     if (Stacks.Peek().ObjectType != JsonObjectType.Unknown)
     {
         readObject();
         return;
     }
     Stacks.Peek().IsInitialized = true;
     if (Stacks.Peek().Instance is null)
     {
         value(null, JsonValueType.Null);
         return;
     }
     if (Stacks.Peek().Type is null)
     {
         Stacks.Peek().Type = Stacks.Peek().Instance.GetType();
     }
     if (JsonApi.TryGetValueType(Stacks.Peek().Type, out JsonValueType valueType, Config))
     {
         value(Stacks.Peek().Instance, valueType);
         return;
     }
     if (JsonApi.TryGetArrayType(Stacks.Peek().Type, out Stacks.Peek().ArrayType))
     {
         readArray();
         return;
     }
     if (JsonApi.TryGetObjectType(Stacks.Peek().Type, out Stacks.Peek().ObjectType))
     {
         readObject();
         return;
     }
     throw new JsonNotSupportException(Stacks.Peek().Type);
 }
Пример #10
0
    public float[] getTau(JsonAction action, Character character)
    {
        List <JsonPDController> jsonPDs = character.mjsonObject.PDControllers;
        List <GameObject>       bodies  = character.mBodies;

        int numJoint = jsonPDs.Count;

        float[] targetTau = new float[numJoint];
        float[] tauErr    = new float[numJoint];

        for (int i = 1; i < numJoint; i++)
        {
            targetTau [i] = 0;
            JsonPDController pd   = jsonPDs [i];
            GameObject       body = bodies [i];

            HingeJoint joint     = bodies [i].GetComponent <HingeJoint> ();
            float      currTheta = Mathf.Deg2Rad * joint.angle;
            float      currVel   = Mathf.Deg2Rad * joint.velocity;
            float      targetTheta;

            // if current joint is controlled by action, use that theta
            if (pd.Name.Contains("spine"))
            {
                targetTheta = getTargetTheta(action.StateParams, "SpineCurve");
            }
            else if (CONTROL_PARAMS.Contains(pd.Name))
            {
                targetTheta = getTargetTheta(action.StateParams, pd.Name);
            }
            else
            {
                targetTheta = pd.TargetTheta;
            }

            JointSpring spring = joint.spring;
            spring.targetPosition = Mathf.Rad2Deg * targetTheta;
            joint.spring          = spring;

            //targetTau[i] += calcSPD(currTheta, targetTheta, currVel, pd);
            int   parent = character.mjsonObject.Skeleton.Joints[i].Parent;
            float mass   = character.mjsonObject.BodyDefs [i].Mass;
            calcGravity(ref targetTau, body, joint, mass, i, parent);
            // targetTau[i] += calcVirtual

            tauErr [i]   = targetTau [i] - mPastTau [i];
            mPastTau [i] = targetTau [i];
        }

        return(tauErr);
    }
Пример #11
0
 public static void ForEachSerializableMembers(Type type, JsonAction <MemberInfo, FieldInfo, PropertyInfo, JsonField> action)
 {
     if (type is null)
     {
         throw new ArgumentNullException(nameof(type));
     }
     if (action is null)
     {
         throw new ArgumentNullException(nameof(action));
     }
     foreach (MemberInfo memberInfo in GetMembers(type))
     {
         if (CanSerializeMember(memberInfo, out FieldInfo fieldInfo, out PropertyInfo propertyInfo, out JsonField field))
         {
             action(memberInfo, fieldInfo, propertyInfo, field);
         }
     }
 }
Пример #12
0
        public override async Task <EntityView> Run(EntityView entityView, CommercePipelineExecutionContext context)
        {
            if (entityView == null ||
                !entityView.Action.Equals("DevOps-CleanEnvironment", StringComparison.OrdinalIgnoreCase))
            {
                return(entityView);
            }

            var appService = await this._commerceCommander.GetEntity <AppService>(context.CommerceContext, entityView.ItemId);

            var jsonAction = new JsonAction {
                Environment = context.CommerceContext.Environment.Name
            };

            await this._commerceCommander.Command <JsonCommander>()
            .Put(context.CommerceContext, $"http://{appService.Host}/commerceops/CleanEnvironment()", jsonAction);

            return(entityView);
        }
Пример #13
0
    void FixedUpdate()
    {
        float time = Time.time;

        /*
         * mPolicy.updatePolicy ();
         */
        JsonAction action = mPolicy.getAction(mActionJson);

        float[] t = mController.getTau(action, mCharacter);
        mCharacter.simulate(t);

        //if (Input.anyKeyDown) {
        if (lastTime + 0.125 < time)
        {
            mController.advanceState();
            lastTime = time;
        }
    }
Пример #14
0
 public void ReadObject(JsonFunc <string, bool> key, JsonAction readValue)
 {
     if (key is null)
     {
         throw new ArgumentNullException(nameof(key));
     }
     if (readValue is null)
     {
         throw new ArgumentNullException(nameof(readValue));
     }
     foreach (JsonKey jsonKey in Values.Peek())
     {
         if (key(jsonKey.Name))
         {
             Values.Push(jsonKey);
             readValue();
             Values.Pop();
         }
     }
 }
Пример #15
0
        public ActionResult Authentication(string username, string password)
        {
            Session.Clear();
            password = Utils.Encryption.getHashSha256(password);

            try
            {
                User user = new Auth().Authentication(username, password);

                SiteSession.Current.User          = user;
                SiteSession.Current.Login         = user.Email;
                SiteSession.Current.Password      = user.Password;
                SiteSession.Current.Administrator = user.Name.ToUpper().Contains("ADMIN");

                JsonAction jsonObject = new JsonAction();
                jsonObject.success = true;
                if (user.Name.ToUpper().Contains("SELLER") ||  /// == (int)UserTypes.Role.Seller)
                    user.Name.ToUpper().Contains("ADMIN"))     /// == (int)UserTypes.Role.Admin)
                {
                    jsonObject.data = Url.Action("Index", "Home");
                }

                return(Json(jsonObject));
            }
            catch (Exception ex)
            {
                JsonAction jsonObject = new JsonAction();
                jsonObject.success = false;

                if (ex.GetType() == typeof(WrongUserPasswordException))
                {
                    jsonObject.message = Resources.Resource.ResourceManager.GetString("Error_Wrong_UserPwd");
                }
                else
                {
                    jsonObject.message = "Something's Wrong";
                }

                return(Json(jsonObject));
            }
        }
Пример #16
0
        public async Task <JsonResponse> Put(CommerceContext commerceContext, string uri, JsonAction body)
        {
            var response = new JsonResponse {
                Uri = uri
            };

            using (CommandActivity.Start(commerceContext, this))
            {
                try
                {
                    using (var httpClient = new HttpClient())
                    {
                        var postResponse = await httpClient.PutAsJsonAsync(response.Uri, body);

                        response.Json = await postResponse.Content.ReadAsStringAsync();
                    }

                    var reader = new StringReader(response.Json);

                    response.Reader = new JsonTextReader(reader);
                }
                catch (Exception ex)
                {
                    await commerceContext.AddMessage(
                        commerceContext.GetPolicy <KnownResultCodes>().Error,
                        "FailedToDeserialize",
                        new object[] { ex },
                        $"GetProdPadCommand.Exception: Message={ex.Message}|Stack={ex.StackTrace}");

                    commerceContext.Logger.LogWarning($"Exception: {ex.Message}");

                    response = null;
                }
                return(response);
            }
        }
Пример #17
0
        public JsonAction Execute(HttpRequest httpRequest, JsonPacket jsonRequest, SessionComponent session)
        {
            Clear();

            // Connect
            NetworkChannel channel = new NetworkChannel(Connection);

            // Request
            JsonAction jsonAction = JsonAction.None;
            JsonDownloadRequestMessage jsonRequestMessage = JsonDownloadRequestMessage.Parse(jsonRequest.Message);
            string jsonId = jsonRequestMessage.Id;

            if (jsonId != null)
            {
                // Data
                Entity entity = TransferMap.Get(jsonId);
                if (entity == null)
                {
                    channel.SendNotFound();
                    return(jsonAction);
                }

                ChunkComponent transfer = entity.Get <ChunkComponent>();
                if (transfer == null)
                {
                    channel.SendNotFound();
                    return(jsonAction);
                }

                JsonTransfer jsonTransfer = transfer.PopData();
                if (!transfer.Finished)
                {
                    jsonAction = JsonAction.Request;
                    entity.Update();
                }
                else
                {
                    TransferMap.Remove(jsonId);
                }

                string    jsonData  = null;
                JsonChunk jsonChunk = null;
                if (jsonTransfer != null)
                {
                    jsonData  = jsonTransfer.Data;
                    jsonChunk = jsonTransfer.Chunk;
                }

                // Response
                JsonDownloadResponseMessage jsonResponseMessage = new JsonDownloadResponseMessage(jsonId)
                {
                    Chunk = jsonChunk
                };
                JsonPacket jsonResponse = new JsonPacket(jsonResponseMessage, jsonData);

                HttpResponse httpResponse = new HttpResponse()
                {
                    Data = session.Encrypt(jsonResponse)
                };
                channel.Send(httpResponse);
#if DEBUG
                jsonResponse.Data = null;
                Log.Add(httpRequest, httpResponse, jsonRequest, jsonResponse);
#endif
            }
            else
            {
                // Data
                Entity entity = session.Owner;
                SearchListComponent search     = entity.Get <SearchListComponent>();
                JsonClient          jsonClient = jsonRequestMessage.Client;

                // Request
                if (jsonClient == null && search.Empty)
                {
                    channel.SendNotFound();
                    return(jsonAction);
                }

                // Response
                jsonId = SecurityUtil.CreateKeyString();
                JsonDownloadResponseMessage jsonResponseMessage = new JsonDownloadResponseMessage(jsonId);
                JsonPacket jsonResponse = new JsonPacket(jsonResponseMessage);

                HttpResponse httpResponse = new HttpResponse()
                {
                    Data = session.Encrypt(jsonResponse)
                };
                channel.Send(httpResponse);
#if DEBUG
                Log.Add(httpRequest, httpResponse, jsonRequest, jsonResponse);
#endif
                // Data
                entity = new Entity(jsonId);
                EntityIdleComponent idle = new EntityIdleComponent();
                entity.Add(idle);

                JsonChunk      jsonChunk = jsonRequestMessage.Chunk;
                ChunkComponent transfer  = new ChunkComponent(jsonChunk.Size, Options.ChunkSize, Options.MaxChunks);
                entity.Add(transfer);

                TransferMap.Add(entity);

                // Command
                string jsonData = jsonRequest.Data;
                jsonChunk = transfer.PopChunk();

                if (jsonClient == null)
                {
                    foreach (Entity e in search)
                    {
                        CommandState state = new CommandState()
                        {
                            Id = jsonId, Data = jsonData, Chunk = jsonChunk, Entity = e
                        };
                        Thread thread = new Thread(new ParameterizedThreadStart(ExecuteThread))
                        {
                            Priority = ThreadPriority.BelowNormal, IsBackground = true
                        };
                        thread.Start(state);
                    }
                }
                else
                {
                    Entity e = ClientMap.Get(jsonClient.Id);
                    if (e == null)
                    {
                        channel.SendNotFound();
                        return(jsonAction);
                    }

                    CommandState state = new CommandState()
                    {
                        Id = jsonId, Data = jsonData, Chunk = jsonChunk, Entity = e
                    };
                    Thread thread = new Thread(new ParameterizedThreadStart(ExecuteThread))
                    {
                        Priority = ThreadPriority.BelowNormal, IsBackground = true
                    };
                    thread.Start(state);
                }

                jsonAction = JsonAction.Request;
            }

            return(jsonAction);
        }
Пример #18
0
        private void ListenState()
        {
            NetworkChannel channel = null;

            try
            {
                // Connect
                if (!Connected)
                {
                    State  = DemonState.Restart;
                    Status = DemonStatus.Info;
                    return;
                }

                // NOTE: No need to close the channel
                channel = new NetworkChannel(Connection);
                Status  = DemonStatus.Success;

                // Request
                HttpRequest httpRequest;
                channel.Receive(out httpRequest);
                if (httpRequest == null)
                {
                    Status = DemonStatus.Warning;
                    return;
                }

                // TODO: Version check
                //
                // Message
                SessionComponent session            = Owner.Get <SessionComponent>();
                string           decrypted          = session.Decrypt(httpRequest.Data);
                JsonPacket       jsonRequest        = JsonPacket.Parse(decrypted);
                JsonMessage      jsonRequestMessage = JsonMessage.Parse(jsonRequest.Message);
                JsonType         jsonType           = jsonRequestMessage.Type;

                switch (jsonType)
                {
                case JsonType.Ping:
                {
                    PingResponseCommand command = new PingResponseCommand(Owner, Connection);
                    command.Execute(httpRequest, jsonRequest);
                    break;
                }

                case JsonType.Search:
                {
                    JsonAction action = jsonRequestMessage.Action;

                    switch (action)
                    {
                    case JsonAction.Request:
                    {
                        SearchRequestCommand command = new SearchRequestCommand(Owner, Connection);
                        command.Execute(httpRequest, jsonRequest);
                        break;
                    }

                    case JsonAction.Response:
                    {
                        SearchResponseCommand command = new SearchResponseCommand(Owner, Connection);
                        List <FileComponent>  list    = command.Execute(httpRequest, jsonRequest);
                        OnListAdded(list);
                        break;
                    }

                    default:
                    {
                        channel.SendBadRequest();
                        break;
                    }
                    }

                    break;
                }

                case JsonType.Browse:
                {
                    BrowseResponseCommand command = new BrowseResponseCommand(Owner, Connection);
                    command.Execute(httpRequest, jsonRequest);
                    break;
                }

                case JsonType.Download:
                {
                    // TODO
                    //
                    DownloadResponseCommand command = new DownloadResponseCommand(Owner, Connection);                            // { Handler = UploadEvent };
                    command.Execute(httpRequest, jsonRequest);
                    break;
                }

                default:
                {
                    channel.SendBadRequest();
                    State  = DemonState.Restart;
                    Status = DemonStatus.Info;
                    return;
                }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Status = DemonStatus.Error;

                if (channel != null)
                {
                    try
                    {
                        channel.SendInternalServerError();
                    }
                    catch (Exception) { }
                }
            }
        }
Пример #19
0
        private void ProcessState(object obj)
        {
            Socket         socket  = (Socket)obj;
            NetworkChannel channel = null;

            JsonAction action   = JsonAction.None;
            JsonType   jsonType = JsonType.None;

            try
            {
                do
                {
                    // Connect
                    channel = new NetworkChannel(socket);

                    // Receive
                    HttpRequest httpRequest;
                    channel.Receive(out httpRequest);
                    if (httpRequest == null)
                    {
                        channel.SendBadRequest();
                        return;
                    }

                    // Data
                    Status = DemonStatus.Success;

                    // Handshake
                    if (httpRequest.Session == null)
                    {
                        ServerStatusComponent    status  = Owner.Get <ServerStatusComponent>();
                        HandshakeResponseCommand command = new HandshakeResponseCommand(Owner, socket)
                        {
                            Listener = status.Update
                        };
                        command.Execute(httpRequest);
                        break;
                    }

                    // Session
                    SessionMapComponent sessions = Owner.Get <SessionMapComponent>();
                    Entity entity = sessions.Get(httpRequest.Session);
                    if (entity == null)
                    {
                        channel.SendUnauthorized();
                        break;
                    }

                    // TODO: Version check
                    //
                    // Message
                    SessionComponent session            = entity.Get <SessionComponent>();
                    string           decrypted          = session.Decrypt(httpRequest.Data);
                    JsonPacket       jsonRequest        = JsonPacket.Parse(decrypted);
                    JsonMessage      jsonRequestMessage = JsonMessage.Parse(jsonRequest.Message);
                    jsonType = jsonRequestMessage.Type;

                    switch (jsonType)
                    {
                    case JsonType.Handshake:
                    {
                        HandshakeResponseCommand command = new HandshakeResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Ping:
                    {
                        PingResponseCommand command = new PingResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Info:
                    {
                        InfoResponseCommand command = new InfoResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Join:
                    {
                        JoinResponseCommand command = new JoinResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Tunnel:
                    {
                        TunnelResponseCommand command = new TunnelResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Search:
                    {
                        SearchResponseCommand command = new SearchResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Group:
                    {
                        GroupResponseCommand command = new GroupResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Browse:
                    {
                        BrowseResponseCommand command = new BrowseResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Download:
                    {
                        // TODO: Add max transfer check!
                        //
                        DownloadResponseCommand command = new DownloadResponseCommand(Owner, socket);
                        action = command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Upload:
                    {
                        UploadResponseCommand command = new UploadResponseCommand(Owner, socket);
                        action = command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    case JsonType.Quit:
                    {
                        QuitResponseCommand command = new QuitResponseCommand(Owner, socket);
                        command.Execute(httpRequest, jsonRequest, session);
                        break;
                    }

                    default:
                    {
                        channel.SendBadRequest();
                        return;
                    }
                    }
                }while (action != JsonAction.None);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Status = DemonStatus.Error;
                channel.SendInternalServerError();
            }
            finally
            {
                if (channel != null)
                {
                    channel.Shutdown();
                }

                if (jsonType != JsonType.Tunnel)
                {
                    socket.Shutdown(SocketShutdown.Both);
                    socket.Close();
                }
            }
        }
Пример #20
0
        public void ReadObject(JsonFunc <string, bool> key, JsonAction readValue)
        {
            if (key is null)
            {
                throw new ArgumentNullException(nameof(key));
            }
            if (readValue is null)
            {
                throw new ArgumentNullException(nameof(readValue));
            }
            Initialize(false);
            switch (Stacks.Peek().ObjectType)
            {
            default:
                throw new JsonNotSupportException(Stacks.Peek().ObjectType);

            case JsonObjectType.Class:
                JsonApi.ForEachSerializableMembers(Stacks.Peek().Type, (memberInfo, fieldInfo, propertyInfo, field) => {
                    bool isReaded   = false;
                    object instance = null;
                    Type fieldType  = null;
                    object Read()
                    {
                        if (isReaded)
                        {
                            return(instance);
                        }
                        isReaded = true;
                        switch (memberInfo.MemberType)
                        {
                        default:
                            throw new JsonNotSupportException(memberInfo.MemberType);

                        case MemberTypes.Field:
                            fieldType = fieldInfo.FieldType;
                            return(instance = fieldInfo.GetValue(Stacks.Peek().Instance));

                        case MemberTypes.Property:
                            fieldType = propertyInfo.PropertyType;
                            return(instance = propertyInfo.GetValue(Stacks.Peek().Instance, null));
                        }
                    }
                    object ConverterWrite(object value)
                    {
                        if (field?.HasConverter ?? false)
                        {
                            if (field.ConverterWriteType != fieldType.BaseType &&
                                JsonApi.GetElementType(field.ConverterWriteType) != JsonApi.GetElementType(fieldType).BaseType
                                )
                            {
                                fieldType = field.ConverterWriteType;
                            }
                            return(field.ConverterWrite(value, Config));
                        }
                        return(value);
                    }
                    if (!JsonApi.CanSerializeValue(Read(), Config))
                    {
                        return;
                    }
                    if (key(field?.Name ?? memberInfo.Name))
                    {
                        Stacks.Push(new JsonSerializerStack(ConverterWrite(Read()), field));
                        Stacks.Peek().Type = fieldType;
                        readValue();
                        Stacks.Pop();
                    }
                });
                break;

            case JsonObjectType.DataRow: {
                DataRow dataRow = (DataRow)Stacks.Peek().Instance;
                for (int i = 0; i < dataRow.Table.Columns.Count; i++)
                {
                    if (key(dataRow.Table.Columns[i].ColumnName))
                    {
                        Stacks.Push(new JsonSerializerStack(dataRow[i]));
                        readValue();
                        Stacks.Pop();
                    }
                }
                break;
            }

            case JsonObjectType.DataSet: {
                DataSet dataSet = (DataSet)Stacks.Peek().Instance;
                foreach (DataTable dataTable in dataSet.Tables)
                {
                    if (key(dataTable.TableName))
                    {
                        Stacks.Push(new JsonSerializerStack(dataTable));
                        readValue();
                        Stacks.Pop();
                    }
                }
                break;
            }

            case JsonObjectType.GenericDictionary:
            case JsonObjectType.GenericSortedDictionary:
            case JsonObjectType.GenericSortedList: {
                IDictionary dictionary = (IDictionary)Stacks.Peek().Instance;
                foreach (DictionaryEntry entry in dictionary)
                {
                    if (key(Convert.ToString(entry.Key)))
                    {
                        Stacks.Push(new JsonSerializerStack(entry.Value));
                        readValue();
                        Stacks.Pop();
                    }
                }
                break;
            }

            case JsonObjectType.GenericKeyValuePair: {
                if (key(Convert.ToString(Stacks.Peek().Type.GetProperty("Key").GetValue(Stacks.Peek().Instance, null))))
                {
                    Stacks.Push(new JsonSerializerStack(Stacks.Peek().Type.GetProperty("Value").GetValue(Stacks.Peek().Instance, null)));
                    readValue();
                    Stacks.Pop();
                }
                break;
            }
            }
        }
Пример #21
0
        public void ReadArray(Action <int> readValue)
        {
            if (readValue is null)
            {
                throw new ArgumentNullException(nameof(readValue));
            }
            Initialize(true);
            switch (Stacks.Peek().ArrayType)
            {
            default:
                throw new JsonNotSupportException(Stacks.Peek().ArrayType);

            case JsonArrayType.Array: {
                if (ForEachArray is null)
                {
                    Array array = (Array)Stacks.Peek().Instance;
                    if (array.Rank == 1)
                    {
                        for (int i = 0; i < array.Length; i++)
                        {
                            Stacks.Push(new JsonSerializerStack(array.GetValue(i)));
                            readValue(i);
                            Stacks.Pop();
                        }
                        return;
                    }
                    int[] indices   = new int[array.Rank];
                    int   dimension = 0;
                    int   count     = 0;
                    ForEachArray = () => {
                        int length = array.GetLength(dimension);
                        for (int i = 0; i < length; i++)
                        {
                            indices[dimension] = i;
                            if (dimension == indices.Length - 1)
                            {
                                Stacks.Push(new JsonSerializerStack(array.GetValue(indices)));
                                readValue(count++);
                                Stacks.Pop();
                                continue;
                            }
                            dimension++;
                            readValue(count++);
                        }
                        dimension--;
                        if (dimension < 0)
                        {
                            ForEachArray = null;
                        }
                    };
                }
                ForEachArray();
                break;
            }

            case JsonArrayType.GenericList:
            case JsonArrayType.GenericIList:
            case JsonArrayType.GenericObservableCollection: {
                IList list = (IList)Stacks.Peek().Instance;
                for (int i = 0; i < list.Count; i++)
                {
                    Stacks.Push(new JsonSerializerStack(list[i]));
                    readValue(i);
                    Stacks.Pop();
                }
                break;
            }

            case JsonArrayType.DataTable: {
                DataTable dataTable = (DataTable)Stacks.Peek().Instance;
                for (int i = 0; i < dataTable.Rows.Count; i++)
                {
                    Stacks.Push(new JsonSerializerStack(dataTable.Rows[i]));
                    readValue(i);
                    Stacks.Pop();
                }
                break;
            }
            }
        }
Пример #22
0
 protected JsonMessage(JsonType type, JsonAction action)
 {
     Type = type; Action = action;
 }
Пример #23
0
        private void Listen()
        {
            NetworkChannel channel = null;

            try
            {
                // Connect
                if (!Connected)
                {
                    Data.Status = DemonStatus.Info;
                    State       = DemonState.Restart;
                    return;
                }

                // NOTE: No need to close the channel
                channel     = new NetworkChannel(Connection);
                Data.Status = DemonStatus.Success;

                // Response
                HttpRequest httpRequest;
                channel.Receive(out httpRequest);
                if (httpRequest == null)
                {
                    return;
                }

                string     decrypted   = Data.Session.Decrypt(httpRequest.Data);
                JsonPacket jsonRequest = JsonPacket.Parse(decrypted);
                if (jsonRequest == null)
                {
                    return;
                }

                JsonMessage jsonRequestMessage = JsonMessage.Parse(jsonRequest.Message);

                switch (jsonRequestMessage.Type)
                {
                case JsonType.Ping:
                {
                    //ClientPingCommand command = new ClientPingCommand(Connection, Data);
                    //command.SetLogHandlers(RequestHandler, ResponseHandler, CommandHandler);
                    //command.Execute(httpRequest, jsonRequest);
                    break;
                }

                case JsonType.Search:
                {
                    JsonAction action = jsonRequestMessage.Action;

                    switch (action)
                    {
                    case JsonAction.Request:
                    {
                        //ClientSearchCommand command = new ClientSearchCommand(Connection, Data);
                        //command.SetLogHandlers(RequestHandler, ResponseHandler, CommandHandler);
                        //command.Execute(httpRequest, jsonRequest);
                        break;
                    }

                    case JsonAction.Response:
                    {
                        //ClientSearchCommand2 command = new ClientSearchCommand2(Connection, Data) { SearchHandler = SearchEvent };
                        //command.SetLogHandlers(RequestHandler, ResponseHandler, CommandHandler);
                        //command.Execute(httpRequest, jsonRequest);
                        break;
                    }

                    default:
                    {
                        channel.SendBadRequest();
                        break;
                    }
                    }

                    break;
                }

                case JsonType.Browse:
                {
                    //ClientBrowseCommand command = new ClientBrowseCommand(Connection, Data);
                    //command.SetLogHandlers(RequestHandler, ResponseHandler, CommandHandler);
                    //command.Execute(httpRequest, jsonRequest);
                    break;
                }

                case JsonType.Download:
                {
                    //ClientDownloadCommand command = new ClientDownloadCommand(Connection, Data) { Handler = UploadEvent };
                    //command.SetLogHandlers(RequestHandler, ResponseHandler, CommandHandler);
                    //command.Execute(httpRequest, jsonRequest);
                    break;
                }

                default:
                {
                    channel.SendBadRequest();
                    Data.Status = DemonStatus.Info;
                    State       = DemonState.Restart;
                    return;
                }
                }

                Data.Status = DemonStatus.Success;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                Data.Status = DemonStatus.Info;
                State       = DemonState.Restart;

                if (channel != null)
                {
                    try
                    {
                        channel.SendInternalServerError();
                    }
                    catch (Exception) { }
                }
            }
        }
        public void Trace(TraceLevel level, string message, Exception ex)
        {
            // write to any existing trace writer
            if (_innerTraceWriter != null && level <= _innerTraceWriter.LevelFilter)
            {
                _innerTraceWriter.Trace(level, message, ex);
            }

            IExecutionTimer timer = _timerStrategy();

            if (_traceMessages.Count > 0)
            {
                // check message to see if serialization is complete
                if (message.StartsWith("Serialized JSON:", StringComparison.Ordinal) || message.StartsWith("Deserialized JSON:", StringComparison.Ordinal))
                {
                    TimerResult timeResult = null;
                    if (timer != null)
                    {
                        timeResult = timer.Stop(_start);
                        _timelineMessage.AsTimedMessage(timeResult);
                    }

                    // set final JSON onto previous message
                    JsonTraceMessage lastMessage = _traceMessages.Last();
                    lastMessage.JsonText = message.Substring(message.IndexOf(Environment.NewLine, StringComparison.Ordinal)).Trim();
                    lastMessage.Duration = (timeResult != null) ? (TimeSpan?)timeResult.Duration : null;

                    _traceMessages.Clear();
                    return;
                }
            }

            JsonAction action = JsonAction.Unknown;
            string     type   = null;
            string     json   = null;

            if (_traceMessages.Count == 0)
            {
                Match match = Regex.Match(message, @"^Started serializing ([^\s]+)", RegexOptions.Compiled | RegexOptions.CultureInvariant);
                if (match.Success)
                {
                    type   = match.Groups[1].Value.TrimEnd('.');
                    action = JsonAction.Serialize;
                }
                else
                {
                    match = Regex.Match(message, @"^Started deserializing ([^\s]+)", RegexOptions.Compiled | RegexOptions.CultureInvariant);
                    if (match.Success)
                    {
                        type   = match.Groups[1].Value.TrimEnd('.');
                        action = JsonAction.Deserialize;
                    }
                    else
                    {
                        if (message.StartsWith("Serialized JSON:", StringComparison.Ordinal))
                        {
                            action = JsonAction.Serialize;
                        }
                        else if (message.StartsWith("Deserialized JSON:", StringComparison.Ordinal))
                        {
                            action = JsonAction.Deserialize;
                        }

                        if (action != JsonAction.Unknown)
                        {
                            json    = message.Substring(message.IndexOf(Environment.NewLine, StringComparison.Ordinal)).Trim();
                            message = null;
                        }
                    }
                }

                // create timeline message
                // will be updated each trace with new duration
                _timelineMessage = CreateJsonTimelineMessage(action, type);
                _messageBroker.Publish(_timelineMessage);

                if (timer != null)
                {
                    _start = timer.Start();
                }
            }
            else
            {
                JsonTraceMessage previous = _traceMessages.Last();
                previous.Duration = null;

                action = previous.Action;
                type   = previous.Type;
            }

            TimerResult result = null;

            if (timer != null)
            {
                result = timer.Stop(_start);
                _timelineMessage.AsTimedMessage(result);
            }

            JsonTraceMessage traceMessage = new JsonTraceMessage
            {
                Ordinal     = _traceMessages.Count,
                MessageDate = DateTime.Now,
                Level       = level,
                Message     = message,
                Exception   = ex,
                JsonText    = json,
                Action      = action,
                Type        = (type != null) ? RemoveAssemblyDetails(type) : null,
                Duration    = (result != null) ? (TimeSpan?)result.Duration : null
            };

            _messageBroker.Publish(traceMessage);
            _traceMessages.Add(traceMessage);
        }
Пример #25
0
 protected JsonIdMessage(JsonType type, JsonAction action, string id = null) : base(type, action)
 {
     Id = id;
 }
 private static JsonTimelineMessage CreateJsonTimelineMessage(JsonAction action, string type)
 {
   JsonTimelineMessage timelineMessage = new JsonTimelineMessage();
   string eventName = action.ToString("G");
   if (type != null)
     eventName += " - " + RemoveAssemblyDetails(type);
   timelineMessage.AsTimelineMessage(eventName, new TimelineCategoryItem(action.ToString("G"), "#B3DF00", "#9BBB59"));
   return timelineMessage;
 }
    IEnumerator DoBenchmark()
    {
        yield return(null);

        // Attempt to find a wrapper matching the selection name
        IJsonLibrary wrapper = null;

        foreach (var w in m_knownJsonLibraryWrappers)
        {
            System.Type t = w.GetType();
            if (t.ToString() == Lib)
            {
                wrapper = w;
                break;
            }
        }

        if (wrapper != null)
        {
            yield return(null);

            LastLibName.text    = Lib;
            LastActionName.text = Action.ToString();

            long   sum     = 0;
            long   samples = long.Parse(NumSamplesToRun.text);
            string notes   = string.Empty; // Gets overwritten, only last notes are shown
            long   avg     = 0;
#if !UNITY_EDITOR
            long memoryAllocatedDuringAction = 0;
#endif

            if (samples > 0)
            {
                for (int i = 0; i < samples; i++)
                {
                    Stopwatch timer = new Stopwatch();

#if !UNITY_EDITOR
                    System.GC.Collect();
                    UnityEngine.Scripting.GarbageCollector.GCMode = UnityEngine.Scripting.GarbageCollector.Mode.Disabled;
                    long totalGCBeforeAction = System.GC.GetTotalMemory(true);
#endif

                    if (Action == JsonAction.Deserialize)
                    {
                        notes  = string.Format("Json being used is {0} char long", m_jsonText.Length);
                        notes += wrapper.Deserialize(timer);
                    }
                    else if (Action == JsonAction.Serialize)
                    {
                        notes  = string.Format("Class being serialized has {0} complex elements", m_holder.junkList.Length);
                        notes += wrapper.Serialize(timer);
                    }

                    if (!timer.IsRunning)
                    {
                        throw new System.Exception("Stopwatch timer was not started by wrapper");
                    }

                    timer.Stop();

                    sum += timer.ElapsedMilliseconds;

#if !UNITY_EDITOR
                    memoryAllocatedDuringAction += System.GC.GetTotalMemory(true) - totalGCBeforeAction;
                    UnityEngine.Scripting.GarbageCollector.GCMode = UnityEngine.Scripting.GarbageCollector.Mode.Enabled;
#endif

                    //UnityEngine.Debug.Log(string.Format("----> {0} using {1} took {2}", Action, Lib, timer.ElapsedMilliseconds));
                    yield return(null);
                }

                avg = (sum / samples);
            }

            notes += "\n" + samples.ToString() + " samples taken";
#if !UNITY_EDITOR
            notes += "\n" + (memoryAllocatedDuringAction / samples * 1e-6).ToString("F2") + " mb GC allocated";
#endif
            Notes.text         = notes;
            LastTimeValue.text = avg.ToString();
        }
        else
        {
            UnityEngine.Debug.Log(string.Format("Unable to find suitable IJsonWrapper to match selection {0}", Lib));
        }

        Action    = JsonAction.None;
        m_working = -1;
    }
Пример #28
0
 // Constructors
 protected JsonChunkMessage(JsonType type, JsonAction action, string id = null) : base(type, action, id)
 {
 }