System.Collections.Generic.List.Add(object)

Here are the examples of the csharp api System.Collections.Generic.List.Add(object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

3557 Examples 7

19 View Source File : RCEPControl.cs
License : MIT License
Project Creator : 0x0ade

[RCEndpoint(false, "/chatlog", "?count={count}&detailed={true|false}", "?count=20&detailed=false", "Chat Log", "Basic chat log.")]
        public static void ChatLog(Frontend f, HttpRequestEventArgs c) {
            bool auth = f.IsAuthorized(c);
            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);

            if (!int.TryParse(args["count"], out int count) || count <= 0)
                count = 20;
            if (!auth && count > 100)
                count = 100;

            if (!bool.TryParse(args["detailed"], out bool detailed))
                detailed = false;

            ChatModule chat = f.Server.Get<ChatModule>();
            List<object> log = new();
            RingBuffer<DataChat?> buffer = chat.ChatBuffer;
            lock (buffer) {
                for (int i = Math.Max(-buffer.Moved, -count); i < 0; i++) {
                    DataChat? msg = buffer[i];
                    if (msg != null && (msg.Target == null || auth))
                        log.Add(detailed ? msg.ToDetailedFrontendChat() : msg.ToFrontendChat());
                }
            }

            f.RespondJSON(c, log);
        }

19 View Source File : MessageDecoder.cs
License : MIT License
Project Creator : 1100100

protected override void Decode(IChannelHandlerContext context, IByteBuffer message, List<object> output)
        {
            var len = message.ReadableBytes;
            var array = new byte[len];
            message.GetBytes(message.ReaderIndex, array, 0, len);
            //output.Add(SerializerHelper.Deserialize<TransportMessage<T>>(array));
            output.Add(Codec.Deserialize(array, typeof(T)));
        }

19 View Source File : DbContext.cs
License : Apache License 2.0
Project Creator : 1448376744

private void Initialize(IDbCommand cmd, string sql, object parameter, int? commandTimeout = null, CommandType? commandType = null)
        {
            var dbParameters = new List<IDbDataParameter>();
            cmd.Transaction = _transaction;
            cmd.CommandText = sql;
            if (commandTimeout.HasValue)
            {
                cmd.CommandTimeout = commandTimeout.Value;
            }
            if (commandType.HasValue)
            {
                cmd.CommandType = commandType.Value;
            }
            if (parameter is IDbDataParameter)
            {
                dbParameters.Add(parameter as IDbDataParameter);
            }
            else if (parameter is IEnumerable<IDbDataParameter> parameters)
            {
                dbParameters.AddRange(parameters);
            }
            else if (parameter is Dictionary<string, object> keyValues)
            {
                foreach (var item in keyValues)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            else if (parameter != null)
            {
                var handler = GlobalSettings.EnreplacedyMapperProvider.GetDeserializer(parameter.GetType());
                var values = handler(parameter);
                foreach (var item in values)
                {
                    var param = CreateParameter(cmd, item.Key, item.Value);
                    dbParameters.Add(param);
                }
            }
            if (dbParameters.Count > 0)
            {
                foreach (IDataParameter item in dbParameters)
                {
                    if (item.Value == null)
                    {
                        item.Value = DBNull.Value;
                    }
                    var pattern = [email protected]"in\s+([\@,\:,\?]?{item.ParameterName})";
                    var options = RegexOptions.IgnoreCase | RegexOptions.Singleline | RegexOptions.Multiline;
                    if (cmd.CommandText.IndexOf("in", StringComparison.OrdinalIgnoreCase) != -1 && Regex.IsMatch(cmd.CommandText, pattern, options))
                    {
                        var name = Regex.Match(cmd.CommandText, pattern, options).Groups[1].Value;
                        var list = new List<object>();
                        if (item.Value is IEnumerable<object> || item.Value is Array)
                        {
                            list = (item.Value as IEnumerable).Cast<object>().Where(a => a != null && a != DBNull.Value).ToList();
                        }
                        else
                        {
                            list.Add(item.Value);
                        }
                        if (list.Count() > 0)
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"({string.Join(",", list.Select(s => $"{name}{list.IndexOf(s)}"))})");
                            foreach (var iitem in list)
                            {
                                var key = $"{item.ParameterName}{list.IndexOf(iitem)}";
                                var param = CreateParameter(cmd, key, iitem);
                                cmd.Parameters.Add(param);
                            }
                        }
                        else
                        {
                            cmd.CommandText = Regex.Replace(cmd.CommandText, name, $"(SELECT 1 WHERE 1 = 0)");
                        }
                    }
                    else
                    {
                        cmd.Parameters.Add(item);
                    }
                }
            }
            if (Logging != null)
            {
                var parameters = new Dictionary<string, object>();
                foreach (IDbDataParameter item in cmd.Parameters)
                {
                    parameters.Add(item.ParameterName, item.Value);
                }
                Logging.Invoke(cmd.CommandText, parameters, commandTimeout, commandType);
            }
        }

19 View Source File : BssomValueFormatters.cs
License : MIT License
Project Creator : 1996v

public static object DeserializeBssObject(ref BssomReader reader, ref BssomDeserializeContext context,
            bool isPriorityToDeserializeObjectAsBssomValue)
        {
            byte type = reader.SkipBlankCharacterAndPeekBssomType();
            switch (type)
            {
                case BssomType.NullCode:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return BssomNull.Value;
                    }
                    return null;

                case BssomType.BooleanCode:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomBoolean(reader.ReadBooleanWithOutTypeHead());
                    }

                    return reader.ReadBooleanWithOutTypeHead();
                case BssomType.Int32Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadInt32WithOutTypeHead());
                    }

                    return reader.ReadInt32WithOutTypeHead();
                case BssomType.Int16Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadInt16WithOutTypeHead());
                    }

                    return reader.ReadInt16WithOutTypeHead();
                case BssomType.Int64Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadInt64WithOutTypeHead());
                    }

                    return reader.ReadInt64WithOutTypeHead();
                case BssomType.UInt64Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadUInt64WithOutTypeHead());
                    }

                    return reader.ReadUInt64WithOutTypeHead();
                case BssomType.UInt32Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadUInt32WithOutTypeHead());
                    }

                    return reader.ReadUInt32WithOutTypeHead();
                case BssomType.UInt16Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadUInt16WithOutTypeHead());
                    }

                    return reader.ReadUInt16WithOutTypeHead();
                case BssomType.UInt8Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadUInt8WithOutTypeHead());
                    }

                    return reader.ReadUInt8WithOutTypeHead();
                case BssomType.Int8Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomNumber(reader.ReadInt8WithOutTypeHead());
                    }

                    return reader.ReadInt8WithOutTypeHead();

                case BssomType.Float32Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomFloat(reader.ReadFloat32WithOutTypeHead());
                    }

                    return reader.ReadFloat32WithOutTypeHead();
                case BssomType.Float64Code:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomFloat(reader.ReadFloat64WithOutTypeHead());
                    }

                    return reader.ReadFloat64WithOutTypeHead();

                case BssomType.TimestampCode:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomDateTime(reader.ReadStandDateTimeWithOutTypeHead());
                    }

                    return reader.ReadStandDateTimeWithOutTypeHead();

                case BssomType.StringCode:
                    reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                    if (isPriorityToDeserializeObjectAsBssomValue)
                    {
                        return new BssomString(reader.ReadStringWithOutTypeHead());
                    }

                    return reader.ReadStringWithOutTypeHead();

                case BssomType.NativeCode:
                    {
                        reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                        type = reader.ReadBssomType();
                        switch (type)
                        {
                            case NativeBssomType.CharCode:
                                if (isPriorityToDeserializeObjectAsBssomValue)
                                {
                                    return new BssomChar(reader.ReadCharWithOutTypeHead());
                                }

                                return reader.ReadCharWithOutTypeHead();
                            case NativeBssomType.DecimalCode:
                                if (isPriorityToDeserializeObjectAsBssomValue)
                                {
                                    return new BssomDecimal(reader.ReadDecimalWithOutTypeHead());
                                }

                                return reader.ReadDecimalWithOutTypeHead();
                            case NativeBssomType.DateTimeCode:
                                if (isPriorityToDeserializeObjectAsBssomValue)
                                {
                                    return new BssomDateTime(reader.ReadNativeDateTimeWithOutTypeHead());
                                }

                                return reader.ReadNativeDateTimeWithOutTypeHead();
                            case NativeBssomType.GuidCode:
                                if (isPriorityToDeserializeObjectAsBssomValue)
                                {
                                    return new BssomGuid(reader.ReadGuidWithOutTypeHead());
                                }

                                return reader.ReadGuidWithOutTypeHead();
                        }
                    }
                    break;

                case BssomType.Array1:
                    {
                        reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                        byte eleType = reader.ReadBssomType();
                        if (eleType != BssomType.NativeCode)
                        {
                            reader.BssomBuffer.Seek(-BssomBinaryPrimitives.Array1BuildInTypeCodeSize, BssomSeekOrgin.Current);
                        }

                        switch (eleType)
                        {
                            case BssomType.BooleanCode:
                                return new BssomArray(BooleanListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.Int32Code:
                                return new BssomArray(Int32ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.Int16Code:
                                return new BssomArray(Int16ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.Int64Code:
                                return new BssomArray(Int64ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.UInt64Code:
                                return new BssomArray(UInt64ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.UInt32Code:
                                return new BssomArray(UInt32ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.UInt16Code:
                                return new BssomArray(UInt16ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.UInt8Code:
                                return new BssomArray(UInt8ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.Int8Code:
                                return new BssomArray(Int8ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.Float32Code:
                                return new BssomArray(Float32ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.Float64Code:
                                return new BssomArray(Float64ListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.TimestampCode:
                                return new BssomArray(DateTimeListFormatter.Instance.Deserialize(ref reader, ref context), false);
                            case BssomType.NativeCode:
                                {
                                    type = reader.ReadBssomType();
                                    reader.BssomBuffer.Seek(-BssomBinaryPrimitives.Array1NativeTypeCodeSize, BssomSeekOrgin.Current);
                                    switch (type)
                                    {
                                        case NativeBssomType.CharCode:
                                            return new BssomArray(CharListFormatter.Instance.Deserialize(ref reader, ref context), false);
                                        case NativeBssomType.DecimalCode:
                                            return new BssomArray(DecimalListFormatter.Instance.Deserialize(ref reader, ref context), false);
                                        case NativeBssomType.DateTimeCode:
                                            return new BssomArray(DateTimeListFormatter.Instance.Deserialize(ref reader, ref context), false);
                                        case NativeBssomType.GuidCode:
                                            return new BssomArray(GuidListFormatter.Instance.Deserialize(ref reader, ref context), false);
                                    }
                                    break;
                                }
                        }
                        break;
                    }
                case BssomType.Array2:
                case BssomType.Array3:
                    {
                        reader.BssomBuffer.SeekWithOutVerify(1, BssomSeekOrgin.Current);
                        reader.SkipVariableNumber();
                        int count = reader.ReadVariableNumber();
                        if (type == BssomType.Array3)
                        {
                            for (int i = 0; i < count; i++)
                            {
                                reader.SkipVariableNumber();
                            }
                        }
                        List<object> ary = new List<object>(count);
                        for (int i = 0; i < count; i++)
                        {
                            ary.Add(DeserializeBssObject(ref reader, ref context, isPriorityToDeserializeObjectAsBssomValue));
                        }
                        return new BssomArray(ary, false);
                    }
                case BssomType.Map1:
                case BssomType.Map2:
                    {
                        return new BssomMap(MapFormatterHelper.GenericDictionaryDeserialize<object, object>(ref reader, ref context));
                    }
            }
            throw BssomSerializationOperationException.UnexpectedCodeRead(type, reader.Position);
        }

19 View Source File : SftpLinuxForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void transferToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView2.SelectedItems.Count;
            if (count > 0)
            {
                List<Object> fileList = new List<object>();
                foreach (ListViewItem item in listView2.SelectedItems)
                {
                    fileList.Add(item.Tag);
                }
                sftpForm.TransferFilesToLocal(fileList);
            }
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

public CommandPacket InputKey(string key)
        {
            _keyIndexes.Add(_input.Count);
            _input.Add(key);
            return this;
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

public CommandPacket InputKey(string[] keys)
        {
            if (keys == null) return this;
            foreach (var key in keys)
            {
                _keyIndexes.Add(_input.Count);
                _input.Add(key);
            }
            return this;
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

public CommandPacket InputRaw(object arg)
        {
            _input.Add(arg);
            return this;
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

public CommandPacket Input(string[] args)
        {
            foreach (var arg in args) _input.Add(arg);
            return this;
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

public CommandPacket Input(int[] args)
        {
            foreach (var arg in args) _input.Add(arg);
            return this;
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

public CommandPacket Input(long[] args)
        {
            foreach (var arg in args) _input.Add(arg);
            return this;
        }

19 View Source File : CommandPacket.cs
License : MIT License
Project Creator : 2881099

public CommandPacket InputIf(bool condition, params object[] args)
        {
            if (condition && args != null)
            {
                foreach (var item in args)
                {
                    if (item is object[] objs) _input.AddRange(objs);
                    else if (item is string[] strs) _input.AddRange(strs.Select(a => (object)a));
                    else if (item is int[] ints) _input.AddRange(ints.Select(a => (object)a));
                    else if (item is long[] longs) _input.AddRange(longs.Select(a => (object)a));
                    else if (item is KeyValuePair<string, long>[] kvps1) _input.AddRange(kvps1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else if (item is KeyValuePair<string, string>[] kvps2) _input.AddRange(kvps2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else if (item is Dictionary<string, long> dict1) _input.AddRange(dict1.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else if (item is Dictionary<string, string> dict2) _input.AddRange(dict2.Select(a => new object[] { a.Key, a.Value }).SelectMany(a => a).ToArray());
                    else _input.Add(item);
                }
            }
            return this;
        }

19 View Source File : SftpWinForm.cs
License : Apache License 2.0
Project Creator : 214175590

private void transferToolStripMenuItem_Click(object sender, EventArgs e)
        {
            int count = listView1.SelectedItems.Count;
            if (count > 0)
            {
                List<Object> fileList = new List<object>();
                foreach (ListViewItem item in listView1.SelectedItems)
                {
                    fileList.Add(item.Tag);
                }
                sftpForm.TransferFilesToRemote(fileList);
            }            
        }

19 View Source File : DbContextSync.cs
License : MIT License
Project Creator : 2881099

internal void ExecCommand() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, int> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], int>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(int));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(int)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Action funcDelete = () => {
				_affrows += dbContextBetch("DbContextBetchRemove");
				states.Clear();
			};
			Action funcInsert = () => {
				_affrows += dbContextBetch("DbContextBetchAdd");
				states.Clear();
			};
			Action<bool> funcUpdate = isLiveUpdate => {
				var affrows = 0;
				if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
				else affrows = dbContextBetch("DbContextBetchUpdate");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099

async internal Task ExecCommandAsync() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, Task<int>> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(Task<int>));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Func<Task> funcDelete = async () => {
				_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
				states.Clear();
			};
			Func<Task> funcInsert = async  () => {
				_affrows += await dbContextBetch("DbContextBetchAddAsync");
				states.Clear();
			};
			Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
				var affrows = 0;
				if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
				else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							await funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							await funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						await funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099

async internal Task ExecCommandAsync() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, Task<int>> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetchAsync.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], Task<int>>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(Task<int>));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], Task<int>>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(Task<int>)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Func<Task> funcDelete = async () => {
				_affrows += await dbContextBetch("DbContextBetchRemoveAsync");
				states.Clear();
			};
			Func<Task> funcInsert = async  () => {
				_affrows += await dbContextBetch("DbContextBetchAddAsync");
				states.Clear();
			};
			Func<bool, Task> funcUpdate = async (isLiveUpdate) => {
				var affrows = 0;
				if (isLiveUpdate) affrows = await dbContextBetch("DbContextBetchUpdateNowAsync");
				else affrows = await dbContextBetch("DbContextBetchUpdateAsync");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							await funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							await funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						await funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : DbContextSync.cs
License : MIT License
Project Creator : 2881099

internal void ExecCommand() {
			if (isExecCommanding) return;
			if (_actions.Any() == false) return;
			isExecCommanding = true;

			ExecCommandInfo oldinfo = null;
			var states = new List<object>();

			Func<string, int> dbContextBetch = methodName => {
				if (_dicExecCommandDbContextBetch.TryGetValue(oldinfo.stateType, out var trydic) == false)
					trydic = new Dictionary<string, Func<object, object[], int>>();
				if (trydic.TryGetValue(methodName, out var tryfunc) == false) {
					var arrType = oldinfo.stateType.MakeArrayType();
					var dbsetType = oldinfo.dbSet.GetType().BaseType;
					var dbsetTypeMethod = dbsetType.GetMethod(methodName, BindingFlags.NonPublic | BindingFlags.Instance, null, new[] { arrType }, null);

					var returnTarget = Expression.Label(typeof(int));
					var parm1DbSet = Expression.Parameter(typeof(object));
					var parm2Vals = Expression.Parameter(typeof(object[]));
					var var1Vals = Expression.Variable(arrType);
					tryfunc = Expression.Lambda<Func<object, object[], int>>(Expression.Block(
						new[] { var1Vals },
						Expression.replacedign(var1Vals, Expression.Convert(global::FreeSql.Internal.Utils.GetDataReaderValueBlockExpression(arrType, parm2Vals), arrType)),
						Expression.Return(returnTarget, Expression.Call(Expression.Convert(parm1DbSet, dbsetType), dbsetTypeMethod, var1Vals)),
						Expression.Label(returnTarget, Expression.Default(typeof(int)))
					), new[] { parm1DbSet, parm2Vals }).Compile();
					trydic.Add(methodName, tryfunc);
				}
				return tryfunc(oldinfo.dbSet, states.ToArray());
			};
			Action funcDelete = () => {
				_affrows += dbContextBetch("DbContextBetchRemove");
				states.Clear();
			};
			Action funcInsert = () => {
				_affrows += dbContextBetch("DbContextBetchAdd");
				states.Clear();
			};
			Action<bool> funcUpdate = isLiveUpdate => {
				var affrows = 0;
				if (isLiveUpdate) affrows = dbContextBetch("DbContextBetchUpdateNow");
				else affrows = dbContextBetch("DbContextBetchUpdate");
				if (affrows == -999) { //最后一个元素已被删除
					states.RemoveAt(states.Count - 1);
					return;
				}
				if (affrows == -998 || affrows == -997) { //没有执行更新
					var laststate = states[states.Count - 1];
					states.Clear();
					if (affrows == -997) states.Add(laststate); //保留最后一个
				}
				if (affrows > 0) {
					_affrows += affrows;
					var islastNotUpdated = states.Count != affrows;
					var laststate = states[states.Count - 1];
					states.Clear();
					if (islastNotUpdated) states.Add(laststate); //保留最后一个
				}
			};

			while (_actions.Any() || states.Any()) {
				var info = _actions.Any() ? _actions.Dequeue() : null;
				if (oldinfo == null) oldinfo = info;
				var isLiveUpdate = false;

				if (_actions.Any() == false && states.Any() ||
					info != null && oldinfo.actionType != info.actionType ||
					info != null && oldinfo.stateType != info.stateType) {

					if (info != null && oldinfo.actionType == info.actionType && oldinfo.stateType == info.stateType) {
						//最后一个,合起来发送
						states.Add(info.state);
						info = null;
					}

					switch (oldinfo.actionType) {
						case ExecCommandInfoType.Insert:
							funcInsert();
							break;
						case ExecCommandInfoType.Delete:
							funcDelete();
							break;
					}
					isLiveUpdate = true;
				}

				if (isLiveUpdate || oldinfo.actionType == ExecCommandInfoType.Update) {
					if (states.Any())
						funcUpdate(isLiveUpdate);
				}

				if (info != null) {
					states.Add(info.state);
					oldinfo = info;
				}
			}
			isExecCommanding = false;
		}

19 View Source File : TypeFuzzer.cs
License : Apache License 2.0
Project Creator : 42skillz

private object[] PrepareFuzzedParametersForThisConstructor(ConstructorInfo constructor, int recursionLevel)
        {
            var parameters = new List<object>();
            var parameterInfos = constructor.GetParameters();
            foreach (var parameterInfo in parameterInfos)
            {
                var type = parameterInfo.ParameterType;

                // Default .NET types
                parameters.Add(FuzzAnyDotNetType(Type.GetTypeCode(type), type, recursionLevel));
            }

            return parameters.ToArray();
        }

19 View Source File : JSONParser.cs
License : MIT License
Project Creator : 5minlab

static object ParseAnonymousValue(string json) {
            if (json.Length == 0)
                return null;
            if (json[0] == '{' && json[json.Length - 1] == '}') {
                List<string> elems = Split(json);
                if (elems.Count % 2 != 0)
                    return null;
                var dict = new Dictionary<string, object>(elems.Count / 2);
                for (int i = 0; i < elems.Count; i += 2)
                    dict.Add(elems[i].Substring(1, elems[i].Length - 2), ParseAnonymousValue(elems[i + 1]));
                return dict;
            }
            if (json[0] == '[' && json[json.Length - 1] == ']') {
                List<string> items = Split(json);
                var finalList = new List<object>(items.Count);
                for (int i = 0; i < items.Count; i++)
                    finalList.Add(ParseAnonymousValue(items[i]));
                return finalList;
            }
            if (json[0] == '\"' && json[json.Length - 1] == '\"') {
                string str = json.Substring(1, json.Length - 2);
                return str.Replace("\\", string.Empty);
            }
            if (char.IsDigit(json[0]) || json[0] == '-') {
                if (json.Contains(".")) {
                    double result;
                    double.TryParse(json, out result);
                    return result;
                } else {
                    int result;
                    int.TryParse(json, out result);
                    return result;
                }
            }
            if (json == "true")
                return true;
            if (json == "false")
                return false;
            // handles json == "null" as well as invalid JSON
            return null;
        }

19 View Source File : IoCBindData.cs
License : MIT License
Project Creator : 7Bytes-Studio

private object SelfBindTypeBuild()
        {
            if (IsSingleInstance)
            {
                return SingleInstance ?? (SingleInstance = Activator.CreateInstance(SelfBindType, BindTypeParameter));
            }
            else
            {
                var instance = Activator.CreateInstance(SelfBindType, BindTypeParameter);
                if (null != instance)
                {
                    m_InstanceList.Add(instance);
                    return instance;
                }
            }
            return null;
        }

19 View Source File : IoCBindData.cs
License : MIT License
Project Creator : 7Bytes-Studio

private object NormalBuild()
        {
            if (null != Instance)
            {
                if (IsSingleInstance)
                {
                    return SingleInstance ?? (SingleInstance = Instance);
                }
                else
                {
                    if (Instance is ICloneable)
                    {
                        var clone = (Instance as ICloneable).Clone();
                        m_InstanceList.Add(clone);
                        return clone;
                    }
                    else
                    {
                        throw new System.Exception(string.Format("Type '{0}' is not replacedignable from 'ICloneable' interface.",Instance.GetType()));
                    }
                }

            }
            else
            {
                if (IsSingleInstance)
                {
                    return SingleInstance ?? (SingleInstance = Activator.CreateInstance(BindType, BindTypeParameter));
                }
                else
                {
                    var instance = Activator.CreateInstance(BindType, BindTypeParameter);
                    if (null != instance)
                    {
                        m_InstanceList.Add(instance);
                        return instance;
                    }
                }
            }
            return null;
        }

19 View Source File : ServiceInvoker.cs
License : MIT License
Project Creator : 99x

public static Task Invoke(Kernel kernel, RadiumContext context)
        {
            DefaultResponseBody responseBody = new DefaultResponseBody();

            var req = context.Request;
            var res = context.Response;


            string reqContentType = req.ContentType;
            if (String.IsNullOrEmpty(reqContentType))
                reqContentType = "application/json";
            else
                reqContentType = reqContentType.ToLower();

            PathExecutionParams exeParams = ResourceRepository.Repo[req.Method, req.Path.Value];

            try
            {
                if (exeParams != null)
                {

                    Filters.FilterChainResponse chainResponse =  kernel.FilterManager.ExecuteChain();
                    bool isSuccess = chainResponse.LastResponse !=null ? chainResponse.LastResponse.Success : true;

                    if (!isSuccess)
                    {
                        res.ContentType = reqContentType;
                        responseBody.success = false; 
                        responseBody.result = chainResponse.LastResponse.Message;
                        responseBody.error = chainResponse.LastResponse.Error;
                        res.StatusCode = chainResponse.LastResponse.StatusCode;
                    }
                    else
                    {
                        RestResourceHandler newObj = (RestResourceHandler)Activator.CreateInstance(exeParams.ExecutionInfo.Type);
                        newObj.OContext = context;
                        newObj.DataBag = chainResponse.FilterResponse;
                        var exeMethod = exeParams.ExecutionInfo.Method;
                        List<object> activatorParams = new List<object>();
                        var methodParams = exeMethod.GetParameters();

                        foreach (var mParam in methodParams)
                        {
                            if (exeParams.Parameters.ContainsKey(mParam.Name))
                            {
                                var strValue = exeParams.Parameters[mParam.Name];
                                object convertedValue = Convert.ChangeType(strValue, mParam.ParameterType);
                                activatorParams.Add(convertedValue);
                            }
                            else
                            {
                                throw new ParameterMismatchException();
                            }
                        }

                        object output = exeMethod.Invoke(newObj, activatorParams.ToArray());
                        responseBody.success = true;
                        responseBody.result = output;
                        res.ContentType = reqContentType;
                    }

                }
                else
                {
                    res.ContentType = reqContentType;
                    responseBody.success = false;
                    responseBody.result = "404 Not Found";
                    res.StatusCode = 404;
                }
            }
            catch (Exception ex) 
            {
                res.ContentType = reqContentType;
                responseBody.success = false;
                responseBody.result = ex;
                res.StatusCode = 500;
            }

            var formatter = kernel.ResponseFormatter.GetFormatter(reqContentType);
            return res.WriteAsync(formatter.Format(responseBody));
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

private async void HandleVideoMessage(VideoMessage message)
        {
            try
            {
                _currentTimestamp = Math.Max(_currentTimestamp, message.MessageHeader.Timestamp);

                var head = message.Data.Span[0];

                var data = FlvDemuxer.DemultiplexVideoData(message);
                if (data.FrameType == FrameType.KeyFrame)
                {
                    _keyframeTimes.Add((double)message.MessageHeader.Timestamp / 1000);
                    _keyframeFilePositions.Add((double)_recordFileData.Position);
                }

                await SaveMessage(message);
            }
            catch
            {
                RtmpSession.Close();
            }
        }

19 View Source File : RecordStream.cs
License : MIT License
Project Creator : a1q123456

private async void HandleVideoMessage(VideoMessage message)
        {
            try
            {
                _currentTimestamp = Math.Max(_currentTimestamp, message.MessageHeader.Timestamp);

                var head = message.Data.Span[0];

                var data = FlvDemuxer.DemultiplexVideoData(message);
                if (data.FrameType == FrameType.KeyFrame)
                {
                    _keyframeTimes.Add((double)message.MessageHeader.Timestamp / 1000);
                    _keyframeFilePositions.Add((double)_recordFileData.Position);
                }

                await SaveMessage(message);
            }
            catch
            {
                RtmpSession.Close();
            }
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = 0;
            if (!DataIsType(buffer, Amf3Type.Object))
            {
                return false;
            }
            consumed = Amf3CommonValues.MARKER_LENGTH;
            if (!TryGetU29Impl(buffer.Slice(Amf3CommonValues.MARKER_LENGTH), out var header, out var headerLength))
            {
                return false;
            }
            consumed += headerLength;

            if (!TryGetReference(header, _objectReferenceTable, out var headerData, out object refValue, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                value = refValue;
                return true;
            }
            Amf3ClreplacedTraits traits = null;
            if ((header & 0x02) == 0x00)
            {
                var referenceIndex = (int)((header >> 2) & 0x3FFFFFFF);
                if (_objectTraitsReferenceTable.Count <= referenceIndex)
                {
                    return false;
                }

                if (_objectTraitsReferenceTable[referenceIndex] is Amf3ClreplacedTraits obj)
                {
                    traits = obj;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                traits = new Amf3ClreplacedTraits();
                var dataBuffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH + headerLength);
                if ((header & 0x04) == 0x04)
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Externalizable;
                    if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var extClreplacedName, out int extClreplacedNameConsumed))
                    {
                        return false;
                    }
                    consumed += extClreplacedNameConsumed;
                    traits.ClreplacedName = extClreplacedName;
                    var externailzableBuffer = dataBuffer.Slice(extClreplacedNameConsumed);

                    if (!_registeredExternalizable.TryGetValue(extClreplacedName, out var extType))
                    {
                        return false;
                    }
                    var extObj = Activator.CreateInstance(extType) as IExternalizable;
                    if (!extObj.TryDecodeData(externailzableBuffer, out var extConsumed))
                    {
                        return false;
                    }

                    value = extObj;
                    consumed = Amf3CommonValues.MARKER_LENGTH + headerLength + extClreplacedNameConsumed + extConsumed;
                    return true;
                }

                if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var clreplacedName, out int clreplacedNameConsumed))
                {
                    return false;
                }
                dataBuffer = dataBuffer.Slice(clreplacedNameConsumed);
                consumed += clreplacedNameConsumed;
                if (clreplacedName.Any())
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Typed;
                    traits.ClreplacedName = clreplacedName;
                }
                else
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Anonymous;
                }

                if ((header & 0x08) == 0x08)
                {
                    traits.IsDynamic = true;
                }
                var memberCount = header >> 4;
                for (int i = 0; i < memberCount; i++)
                {
                    if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var key, out var keyConsumed))
                    {
                        return false;
                    }
                    traits.Members.Add(key);
                    dataBuffer = dataBuffer.Slice(keyConsumed);
                    consumed += keyConsumed;
                }
                _objectTraitsReferenceTable.Add(traits);
            }

            object deserailziedObject = null;
            var valueBuffer = buffer.Slice(consumed);
            if (traits.ClreplacedType == Amf3ClreplacedType.Typed)
            {
                if (!_registeredTypedObejectStates.TryGetValue(traits.ClreplacedName, out var state))
                {
                    return false;
                }

                var clreplacedType = state.Type;
                if (!traits.Members.OrderBy(m => m).SequenceEqual(state.Members.Keys.OrderBy(p => p)))
                {
                    return false;
                }

                deserailziedObject = Activator.CreateInstance(clreplacedType);
                _objectReferenceTable.Add(deserailziedObject);
                foreach (var member in traits.Members)
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;
                    state.Members[member](deserailziedObject, data);
                }
            }
            else
            {
                var obj = new AmfObject();
                _objectReferenceTable.Add(obj);
                foreach (var member in traits.Members)
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;
                    obj.Add(member, data);
                }

                deserailziedObject = obj;
            }
            if (traits.IsDynamic)
            {
                var dynamicObject = deserailziedObject as IDynamicObject;
                if (dynamicObject == null)
                {
                    return false;
                }
                if (!TryGetStringImpl(valueBuffer, _stringReferenceTable, out var key, out var keyConsumed))
                {
                    return false;
                }
                consumed += keyConsumed;
                valueBuffer = valueBuffer.Slice(keyConsumed);
                while (key.Any())
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;

                    dynamicObject.AddDynamic(key, data);

                    if (!TryGetStringImpl(valueBuffer, _stringReferenceTable, out key, out keyConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(keyConsumed);
                    consumed += keyConsumed;
                }
            }

            value = deserailziedObject;

            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetByteArray(Span<byte> buffer, out byte[] value, out int consumed)
        {
            value = default;
            consumed = default;
            if (!DataIsType(buffer, Amf3Type.ByteArray))
            {
                return false;
            }

            var objectBuffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);

            if (!TryGetU29Impl(objectBuffer, out var header, out int headerLen))
            {
                return false;
            }

            if (!TryGetReference(header, _objectReferenceTable, out var headerData, out byte[] refValue, out var isRef))
            {
                return false;
            }
            if (isRef)
            {
                value = refValue;
                consumed = Amf3CommonValues.MARKER_LENGTH + headerLen;
                return true;
            }

            var arrayLen = (int)headerData;
            if (objectBuffer.Length - headerLen < arrayLen)
            {
                return false;
            }

            value = new byte[arrayLen];

            objectBuffer.Slice(headerLen, arrayLen).CopyTo(value);
            _objectReferenceTable.Add(value);
            consumed = Amf3CommonValues.MARKER_LENGTH + headerLen + arrayLen;
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorInt(Span<byte> buffer, out Vector<int> value, out int consumed)
        {
            value = default;
            consumed = Amf3CommonValues.MARKER_LENGTH;
            if (!DataIsType(buffer, Amf3Type.VectorInt))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);
            if (!ReadVectorHeader(ref buffer, ref value, ref consumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                return true;
            }

            var vector = new Vector<int> { IsFixedSize = isFixedSize };
            _objectReferenceTable.Add(vector);
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetIntVectorData(ref buffer, vector, ref consumed))
                {
                    return false;
                }
            }
            value = vector;
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorUint(Span<byte> buffer, out Vector<uint> value, out int consumed)
        {
            value = default;
            consumed = Amf3CommonValues.MARKER_LENGTH;
            if (!DataIsType(buffer, Amf3Type.VectorUInt))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);
            if (!ReadVectorHeader(ref buffer, ref value, ref consumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                return true;
            }

            var vector = new Vector<uint> { IsFixedSize = isFixedSize };
            _objectReferenceTable.Add(vector);
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetUIntVectorData(ref buffer, vector, ref consumed))
                {
                    return false;
                }
            }

            value = vector;
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorDouble(Span<byte> buffer, out Vector<double> value, out int consumed)
        {
            value = default;
            consumed = default;
            if (!DataIsType(buffer, Amf3Type.VectorDouble))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);
            if (!ReadVectorHeader(ref buffer, ref value, ref consumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                return true;
            }

            var vector = new Vector<double>() { IsFixedSize = isFixedSize };
            _objectReferenceTable.Add(vector);
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetDoubleVectorData(ref buffer, vector, ref consumed))
                {
                    return false;
                }
            }

            value = vector;
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = default;

            if (!DataIsType(buffer, Amf3Type.VectorObject))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);

            int arrayConsumed = 0;

            if (!ReadVectorHeader(ref buffer, ref value, ref arrayConsumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                consumed = arrayConsumed;
                return true;
            }

            if (!ReadVectorTypeName(ref buffer, out var typeName, out var typeNameConsumed))
            {
                return false;
            }

            var arrayBodyBuffer = buffer;

            object resultVector = null;
            Type elementType = null;
            Action<object> addAction = null;
            if (typeName == "*")
            {
                elementType = typeof(object);
                var v = new Vector<object>();
                _objectReferenceTable.Add(v);
                v.IsFixedSize = isFixedSize;
                resultVector = v;
                addAction = v.Add;
            }
            else
            {
                if (!_registeredTypedObejectStates.TryGetValue(typeName, out var state))
                {
                    return false;
                }
                elementType = state.Type;

                var vectorType = typeof(Vector<>).MakeGenericType(elementType);
                resultVector = Activator.CreateInstance(vectorType);
                _objectReferenceTable.Add(resultVector);
                vectorType.GetProperty("IsFixedSize").SetValue(resultVector, isFixedSize);
                var addMethod = vectorType.GetMethod("Add");
                addAction = o => addMethod.Invoke(resultVector, new object[] { o });
            }
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetValue(arrayBodyBuffer, out var item, out var itemConsumed))
                {
                    return false;
                }
                addAction(item);

                arrayBodyBuffer = arrayBodyBuffer.Slice(itemConsumed);
                arrayConsumed += itemConsumed;
            }
            value = resultVector;
            consumed = typeNameConsumed + arrayConsumed;
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetVectorObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = default;

            if (!DataIsType(buffer, Amf3Type.VectorObject))
            {
                return false;
            }

            buffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);

            int arrayConsumed = 0;

            if (!ReadVectorHeader(ref buffer, ref value, ref arrayConsumed, out var itemCount, out var isFixedSize, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                consumed = arrayConsumed;
                return true;
            }

            if (!ReadVectorTypeName(ref buffer, out var typeName, out var typeNameConsumed))
            {
                return false;
            }

            var arrayBodyBuffer = buffer;

            object resultVector = null;
            Type elementType = null;
            Action<object> addAction = null;
            if (typeName == "*")
            {
                elementType = typeof(object);
                var v = new Vector<object>();
                _objectReferenceTable.Add(v);
                v.IsFixedSize = isFixedSize;
                resultVector = v;
                addAction = v.Add;
            }
            else
            {
                if (!_registeredTypedObejectStates.TryGetValue(typeName, out var state))
                {
                    return false;
                }
                elementType = state.Type;

                var vectorType = typeof(Vector<>).MakeGenericType(elementType);
                resultVector = Activator.CreateInstance(vectorType);
                _objectReferenceTable.Add(resultVector);
                vectorType.GetProperty("IsFixedSize").SetValue(resultVector, isFixedSize);
                var addMethod = vectorType.GetMethod("Add");
                addAction = o => addMethod.Invoke(resultVector, new object[] { o });
            }
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetValue(arrayBodyBuffer, out var item, out var itemConsumed))
                {
                    return false;
                }
                addAction(item);

                arrayBodyBuffer = arrayBodyBuffer.Slice(itemConsumed);
                arrayConsumed += itemConsumed;
            }
            value = resultVector;
            consumed = typeNameConsumed + arrayConsumed;
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetDictionary(Span<byte> buffer, out Amf3Dictionary<object, object> value, out int consumed)
        {
            value = default;
            consumed = default;
            if (!DataIsType(buffer, Amf3Type.Dictionary))
            {
                return false;
            }

            if (!TryGetU29Impl(buffer.Slice(Amf3CommonValues.MARKER_LENGTH), out var header, out var headerLength))
            {
                return false;
            }

            if (!TryGetReference(header, _objectReferenceTable, out var headerData, out Amf3Dictionary<object, object> refValue, out var isRef))
            {
                return false;
            }
            if (isRef)
            {
                value = refValue;
                consumed = Amf3CommonValues.MARKER_LENGTH + headerLength;
                return true;
            }

            var itemCount = (int)headerData;
            var dictConsumed = 0;
            if (buffer.Length - Amf3CommonValues.MARKER_LENGTH - headerLength < sizeof(byte))
            {
                return false;
            }
            var weakKeys = buffer[Amf3CommonValues.MARKER_LENGTH + headerLength] == 0x01;

            var dictBuffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH + headerLength + /* weak key flag */ sizeof(byte));
            var dict = new Amf3Dictionary<object, object>()
            {
                WeakKeys = weakKeys
            };
            _objectReferenceTable.Add(dict);
            for (int i = 0; i < itemCount; i++)
            {
                if (!TryGetValue(dictBuffer, out var key, out var keyConsumed))
                {
                    return false;
                }
                dictBuffer = dictBuffer.Slice(keyConsumed);
                dictConsumed += keyConsumed;
                if (!TryGetValue(dictBuffer, out var data, out var dataConsumed))
                {
                    return false;
                }
                dictBuffer = dictBuffer.Slice(dataConsumed);
                dict.Add(key, data);
                dictConsumed += dataConsumed;
            }
            value = dict;
            consumed = Amf3CommonValues.MARKER_LENGTH + headerLength + dictConsumed + /* weak key flag */ sizeof(byte);
            return true;
        }

19 View Source File : Amf3Writer.cs
License : MIT License
Project Creator : a1q123456

public void WriteBytes(object value, SerializationContext context)
        {
            uint header = 0;
            if (value == null)
            {
                context.Buffer.WriteToBuffer((byte)Amf3Type.Null);
                return;
            }
            else
            {
                context.Buffer.WriteToBuffer((byte)Amf3Type.Object);
            }

            var refIndex = context.ObjectReferenceTable.IndexOf(value);
            if (refIndex >= 0)
            {
                header = (uint)refIndex << 1;
                WriteU29BytesImpl(header, context);
                return;
            }

            var objType = value.GetType();
            string attrTypeName = null;
            var clreplacedAttr = objType.GetCustomAttribute<TypedObjectAttribute>();
            if (clreplacedAttr != null)
            {
                attrTypeName = clreplacedAttr.Name;
            }
            var traits = new Amf3ClreplacedTraits();
            var memberValues = new List<object>();
            if (value is AmfObject amf3Object)
            {
                if (amf3Object.IsAnonymous)
                {
                    traits.ClreplacedName = "";
                    traits.ClreplacedType = Amf3ClreplacedType.Anonymous;
                }
                else
                {
                    traits.ClreplacedName = attrTypeName ?? objType.Name;
                    traits.ClreplacedType = Amf3ClreplacedType.Typed;
                }
                traits.IsDynamic = amf3Object.IsDynamic;
                traits.Members = new List<string>(amf3Object.Fields.Keys);
                memberValues = new List<object>(amf3Object.Fields.Keys.Select(k => amf3Object.Fields[k]));
            }
            else if (value is IExternalizable)
            {
                traits.ClreplacedName = attrTypeName ?? objType.Name;
                traits.ClreplacedType = Amf3ClreplacedType.Externalizable;
            }
            else
            {
                traits.ClreplacedName = attrTypeName ?? objType.Name;
                traits.ClreplacedType = Amf3ClreplacedType.Typed;
                var props = objType.GetProperties();
                foreach (var prop in props)
                {
                    var attr = (ClreplacedFieldAttribute)Attribute.GetCustomAttribute(prop, typeof(ClreplacedFieldAttribute));
                    if (attr != null)
                    {
                        traits.Members.Add(attr.Name ?? prop.Name);
                        memberValues.Add(prop.GetValue(value));
                    }
                }
                traits.IsDynamic = value is IDynamicObject;
            }
            context.ObjectReferenceTable.Add(value);


            var traitRefIndex = context.ObjectTraitsReferenceTable.IndexOf(traits);
            if (traitRefIndex >= 0)
            {
                header = ((uint)traitRefIndex << 2) | 0x01;
                WriteU29BytesImpl(header, context);
            }
            else
            {
                if (traits.ClreplacedType == Amf3ClreplacedType.Externalizable)
                {
                    header = 0x07;
                    WriteU29BytesImpl(header, context);
                    WriteStringBytesImpl(traits.ClreplacedName, context, context.StringReferenceTable);
                    var extObj = value as IExternalizable;
                    extObj.TryEncodeData(context.Buffer);
                    return;
                }
                else
                {
                    header = 0x03;
                    if (traits.IsDynamic)
                    {
                        header |= 0x08;
                    }
                    var memberCount = (uint)traits.Members.Count;
                    header |= memberCount << 4;
                    WriteU29BytesImpl(header, context);
                    WriteStringBytesImpl(traits.ClreplacedName, context, context.StringReferenceTable);

                    foreach (var memberName in traits.Members)
                    {
                        WriteStringBytesImpl(memberName, context, context.StringReferenceTable);
                    }
                }
                context.ObjectTraitsReferenceTable.Add(traits);
            }


            foreach (var memberValue in memberValues)
            {
                WriteValueBytes(memberValue, context);
            }

            if (traits.IsDynamic)
            {
                var amf3Obj = value as IDynamicObject;
                foreach ((var key, var item) in amf3Obj.DynamicFields)
                {
                    WriteStringBytesImpl(key, context, context.StringReferenceTable);
                    WriteValueBytes(item, context);
                }
                WriteStringBytesImpl("", context, context.StringReferenceTable);
            }
        }

19 View Source File : DataMessage.cs
License : MIT License
Project Creator : a1q123456

public override void Deserialize(SerializationContext context)
        {
            Data = new List<object>();
            var span = context.ReadBuffer.Span;
            if (MessageHeader.MessageType == MessageType.Amf0Data)
            {
                while (span.Length != 0)
                {
                    if (!context.Amf0Reader.TryGetValue(span, out _, out var data, out var consumed))
                    {
                        throw new ProtocolViolationException();
                    }
                    Data.Add(data);
                    span = span.Slice(consumed);
                }

            }
            else
            {
                while (span.Length != 0)
                {
                    if (!context.Amf3Reader.TryGetValue(span, out var data, out var consumed))
                    {
                        throw new ProtocolViolationException();
                    }
                    Data.Add(data);
                    span = span.Slice(consumed);
                }
            }

        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetDate(Span<byte> buffer, out DateTime value, out int consumed)
        {
            value = default;
            consumed = default;
            if (!DataIsType(buffer, Amf3Type.Date))
            {
                return false;
            }

            var objectBuffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH);

            if (!TryGetU29Impl(objectBuffer, out var header, out var headerLength))
            {
                return false;
            }
            if (!TryGetReference(header, _objectReferenceTable, out var headerData, out DateTime refValue, out var isRef))
            {
                return false;
            }
            if (isRef)
            {
                value = refValue;
                consumed = Amf3CommonValues.MARKER_LENGTH + headerLength;
                return true;
            }

            var timestamp = NetworkBitConverter.ToDouble(objectBuffer.Slice(headerLength));
            value = DateTimeOffset.FromUnixTimeMilliseconds((long)(timestamp)).LocalDateTime;
            consumed = Amf3CommonValues.MARKER_LENGTH + headerLength + sizeof(double);
            _objectReferenceTable.Add(value);
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetArray(Span<byte> buffer, out Amf3Array value, out int consumed)
        {
            value = default;
            consumed = default;
            if (!DataIsType(buffer, Amf3Type.Array))
            {
                return false;
            }

            if (!TryGetU29Impl(buffer.Slice(Amf3CommonValues.MARKER_LENGTH), out var header, out var headerConsumed))
            {
                return false;
            }

            if (!TryGetReference(header, _objectReferenceTable, out var headerData, out Amf3Array refValue, out var isRef))
            {
                return false;
            }
            if (isRef)
            {
                value = refValue;
                consumed = Amf3CommonValues.MARKER_LENGTH + headerConsumed;
                return true;
            }

            var arrayConsumed = 0;
            var arrayBuffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH + headerConsumed);
            var denseItemCount = (int)headerData;

            if (!TryGetStringImpl(arrayBuffer, _stringReferenceTable, out var key, out var keyConsumed))
            {
                return false;
            }
            var array = new Amf3Array();
            _objectReferenceTable.Add(array);
            if (key.Any())
            {
                do
                {
                    arrayBuffer = arrayBuffer.Slice(keyConsumed);
                    arrayConsumed += keyConsumed;
                    if (!TryGetValue(arrayBuffer, out var item, out var itemConsumed))
                    {
                        return false;
                    }

                    arrayConsumed += itemConsumed;
                    arrayBuffer = arrayBuffer.Slice(itemConsumed);
                    array.SparsePart.Add(key, item);
                    if (!TryGetStringImpl(arrayBuffer, _stringReferenceTable, out key, out keyConsumed))
                    {
                        return false;
                    }
                }
                while (key.Any());
            }
            arrayConsumed += keyConsumed;
            arrayBuffer = arrayBuffer.Slice(keyConsumed);

            for (int i = 0; i < denseItemCount; i++)
            {
                if (!TryGetValue(arrayBuffer, out var item, out var itemConsumed))
                {
                    return false;
                }
                array.DensePart.Add(item);
                arrayConsumed += itemConsumed;
                arrayBuffer = arrayBuffer.Slice(itemConsumed);
            }

            value = array;
            consumed = Amf3CommonValues.MARKER_LENGTH + headerConsumed + arrayConsumed;
            return true;
        }

19 View Source File : Amf3Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetObject(Span<byte> buffer, out object value, out int consumed)
        {
            value = default;
            consumed = 0;
            if (!DataIsType(buffer, Amf3Type.Object))
            {
                return false;
            }
            consumed = Amf3CommonValues.MARKER_LENGTH;
            if (!TryGetU29Impl(buffer.Slice(Amf3CommonValues.MARKER_LENGTH), out var header, out var headerLength))
            {
                return false;
            }
            consumed += headerLength;

            if (!TryGetReference(header, _objectReferenceTable, out var headerData, out object refValue, out var isRef))
            {
                return false;
            }

            if (isRef)
            {
                value = refValue;
                return true;
            }
            Amf3ClreplacedTraits traits = null;
            if ((header & 0x02) == 0x00)
            {
                var referenceIndex = (int)((header >> 2) & 0x3FFFFFFF);
                if (_objectTraitsReferenceTable.Count <= referenceIndex)
                {
                    return false;
                }

                if (_objectTraitsReferenceTable[referenceIndex] is Amf3ClreplacedTraits obj)
                {
                    traits = obj;
                }
                else
                {
                    return false;
                }
            }
            else
            {
                traits = new Amf3ClreplacedTraits();
                var dataBuffer = buffer.Slice(Amf3CommonValues.MARKER_LENGTH + headerLength);
                if ((header & 0x04) == 0x04)
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Externalizable;
                    if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var extClreplacedName, out int extClreplacedNameConsumed))
                    {
                        return false;
                    }
                    consumed += extClreplacedNameConsumed;
                    traits.ClreplacedName = extClreplacedName;
                    var externailzableBuffer = dataBuffer.Slice(extClreplacedNameConsumed);

                    if (!_registeredExternalizable.TryGetValue(extClreplacedName, out var extType))
                    {
                        return false;
                    }
                    var extObj = Activator.CreateInstance(extType) as IExternalizable;
                    if (!extObj.TryDecodeData(externailzableBuffer, out var extConsumed))
                    {
                        return false;
                    }

                    value = extObj;
                    consumed = Amf3CommonValues.MARKER_LENGTH + headerLength + extClreplacedNameConsumed + extConsumed;
                    return true;
                }

                if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var clreplacedName, out int clreplacedNameConsumed))
                {
                    return false;
                }
                dataBuffer = dataBuffer.Slice(clreplacedNameConsumed);
                consumed += clreplacedNameConsumed;
                if (clreplacedName.Any())
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Typed;
                    traits.ClreplacedName = clreplacedName;
                }
                else
                {
                    traits.ClreplacedType = Amf3ClreplacedType.Anonymous;
                }

                if ((header & 0x08) == 0x08)
                {
                    traits.IsDynamic = true;
                }
                var memberCount = header >> 4;
                for (int i = 0; i < memberCount; i++)
                {
                    if (!TryGetStringImpl(dataBuffer, _stringReferenceTable, out var key, out var keyConsumed))
                    {
                        return false;
                    }
                    traits.Members.Add(key);
                    dataBuffer = dataBuffer.Slice(keyConsumed);
                    consumed += keyConsumed;
                }
                _objectTraitsReferenceTable.Add(traits);
            }

            object deserailziedObject = null;
            var valueBuffer = buffer.Slice(consumed);
            if (traits.ClreplacedType == Amf3ClreplacedType.Typed)
            {
                if (!_registeredTypedObejectStates.TryGetValue(traits.ClreplacedName, out var state))
                {
                    return false;
                }

                var clreplacedType = state.Type;
                if (!traits.Members.OrderBy(m => m).SequenceEqual(state.Members.Keys.OrderBy(p => p)))
                {
                    return false;
                }

                deserailziedObject = Activator.CreateInstance(clreplacedType);
                _objectReferenceTable.Add(deserailziedObject);
                foreach (var member in traits.Members)
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;
                    state.Members[member](deserailziedObject, data);
                }
            }
            else
            {
                var obj = new AmfObject();
                _objectReferenceTable.Add(obj);
                foreach (var member in traits.Members)
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;
                    obj.Add(member, data);
                }

                deserailziedObject = obj;
            }
            if (traits.IsDynamic)
            {
                var dynamicObject = deserailziedObject as IDynamicObject;
                if (dynamicObject == null)
                {
                    return false;
                }
                if (!TryGetStringImpl(valueBuffer, _stringReferenceTable, out var key, out var keyConsumed))
                {
                    return false;
                }
                consumed += keyConsumed;
                valueBuffer = valueBuffer.Slice(keyConsumed);
                while (key.Any())
                {
                    if (!TryGetValue(valueBuffer, out var data, out var dataConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(dataConsumed);
                    consumed += dataConsumed;

                    dynamicObject.AddDynamic(key, data);

                    if (!TryGetStringImpl(valueBuffer, _stringReferenceTable, out key, out keyConsumed))
                    {
                        return false;
                    }
                    valueBuffer = valueBuffer.Slice(keyConsumed);
                    consumed += keyConsumed;
                }
            }

            value = deserailziedObject;

            return true;
        }

19 View Source File : Amf0Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetString(Span<byte> buffer, out string value, out int bytesConsumed)
        {
            value = default;
            bytesConsumed = default;

            if (!TryDescribeData(buffer, out var type, out _))
            {
                return false;
            }

            if (type != Amf0Type.String)
            {
                return false;
            }

            if (!TryGetStringImpl(buffer.Slice(Amf0CommonValues.MARKER_LENGTH), Amf0CommonValues.STRING_HEADER_LENGTH, out value, out bytesConsumed))
            {
                return false;
            }

            bytesConsumed += Amf0CommonValues.MARKER_LENGTH;
            _referenceTable.Add(value);
            return true;
        }

19 View Source File : Amf0Reader.cs
License : MIT License
Project Creator : a1q123456

private bool TryGetObjectImpl(Span<byte> objectBuffer, out Dictionary<string, object> value, out int bytesConsumed)
        {
            value = default;
            bytesConsumed = default;
            var obj = new Dictionary<string, object>();
            _referenceTable.Add(obj);
            var consumed = 0;
            while (true)
            {
                if (!TryGetStringImpl(objectBuffer, Amf0CommonValues.STRING_HEADER_LENGTH, out var key, out var keyLength))
                {
                    return false;
                }
                consumed += keyLength;
                objectBuffer = objectBuffer.Slice(keyLength);

                if (!TryGetValue(objectBuffer, out var dataType, out var data, out var valueLength))
                {
                    return false;
                }
                consumed += valueLength;
                objectBuffer = objectBuffer.Slice(valueLength);

                if (!key.Any() && dataType == Amf0Type.ObjectEnd)
                {
                    break;
                }
                obj.Add(key, data);
            }
            value = obj;
            bytesConsumed = consumed;
            return true;
        }

19 View Source File : Amf0Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetEcmaArray(Span<byte> buffer, out Dictionary<string, object> value, out int consumedLength)
        {
            value = default;
            consumedLength = default;
            int consumed = 0;

            if (!TryDescribeData(buffer, out var type, out _))
            {
                return false;
            }

            if (type != Amf0Type.EcmaArray)
            {
                return false;
            }

            var obj = new Dictionary<string, object>();
            _referenceTable.Add(obj);

            var elementCount = NetworkBitConverter.ToUInt32(buffer.Slice(Amf0CommonValues.MARKER_LENGTH, sizeof(uint)));

            var arrayBodyBuffer = buffer.Slice(Amf0CommonValues.MARKER_LENGTH + sizeof(uint));
            consumed = Amf0CommonValues.MARKER_LENGTH + sizeof(uint);
            if (StrictMode)
            {
                for (int i = 0; i < elementCount; i++)
                {
                    if (!TryGetKeyValuePair(arrayBodyBuffer, out var kv, out _, out var kvConsumed))
                    {
                        return false;
                    }
                    arrayBodyBuffer = arrayBodyBuffer.Slice(kvConsumed);
                    consumed += kvConsumed;
                    obj.Add(kv.Key, kv.Value);
                }
                if (!TryGetStringImpl(arrayBodyBuffer, Amf0CommonValues.STRING_HEADER_LENGTH, out var emptyStr, out var emptyStrConsumed))
                {
                    return false;
                }
                if (emptyStr.Any())
                {
                    return false;
                }
                consumed += emptyStrConsumed;
                arrayBodyBuffer = arrayBodyBuffer.Slice(emptyStrConsumed);
                if (!TryDescribeData(arrayBodyBuffer, out var objEndType, out var objEndConsumed))
                {
                    return false;
                }
                if (objEndType != Amf0Type.ObjectEnd)
                {
                    return false;
                }
                consumed += objEndConsumed;
            }
            else
            {
                while (true)
                {
                    if (!TryGetKeyValuePair(arrayBodyBuffer, out var kv, out var isEnd, out var kvConsumed))
                    {
                        return false;
                    }
                    arrayBodyBuffer = arrayBodyBuffer.Slice(kvConsumed);
                    consumed += kvConsumed;
                    if (isEnd)
                    {
                        break;
                    }
                    obj.Add(kv.Key, kv.Value);
                }
            }


            value = obj;
            consumedLength = consumed;
            return true;
        }

19 View Source File : Amf0Reader.cs
License : MIT License
Project Creator : a1q123456

public bool TryGetStrictArray(Span<byte> buffer, out List<object> array, out int consumedLength)
        {
            array = default;
            consumedLength = default;

            if (!TryDescribeData(buffer, out var type, out _))
            {
                return false;
            }

            if (type != Amf0Type.StrictArray)
            {
                return false;
            }

            var obj = new List<object>();
            _referenceTable.Add(obj);

            var elementCount = NetworkBitConverter.ToUInt32(buffer.Slice(Amf0CommonValues.MARKER_LENGTH, sizeof(uint)));

            int consumed = Amf0CommonValues.MARKER_LENGTH + sizeof(uint);
            var arrayBodyBuffer = buffer.Slice(consumed);
            var elementBodyBuffer = arrayBodyBuffer;
            System.Diagnostics.Debug.WriteLine(elementCount);
            for (uint i = 0; i < elementCount; i++)
            {
                if (!TryGetValue(elementBodyBuffer, out _, out var element, out var bufferConsumed))
                {
                    return false;
                }

                obj.Add(element);
                if (elementBodyBuffer.Length - bufferConsumed < 0)
                {
                    return false;
                }
                elementBodyBuffer = elementBodyBuffer.Slice(bufferConsumed);
                consumed += bufferConsumed;
            }
            array = obj;
            consumedLength = consumed;

            return true;
        }

19 View Source File : CallbackOnDispose.cs
License : MIT License
Project Creator : Abdesol

public static BusyLock Enter(object obj)
		{
			List<object> activeObjects = _activeObjects;
			if (activeObjects == null)
				activeObjects = _activeObjects = new List<object>();
			for (int i = 0; i < activeObjects.Count; i++) {
				if (activeObjects[i] == obj)
					return BusyLock.Failed;
			}
			activeObjects.Add(obj);
			return new BusyLock(activeObjects);
		}

19 View Source File : NetworkingTests.cs
License : MIT License
Project Creator : abdullin

static void AddHelloWorldClient(TestDef run, string endpoint, List<object> responses) {
            run.AddScript("localhost:console", async env => {
                try {
                    using (var conn = await env.Connect(endpoint, 80)) {
                        await conn.Write("Hello");
                        var response = await conn.Read(5.Sec());
                        responses.Add(response);
                    }
                } catch (IOException ex) {
                    env.Debug(ex.Message);
                    responses.Add(ex);
                }
            });
        }

19 View Source File : NetworkingTests.cs
License : MIT License
Project Creator : abdullin

static void AddHelloWorldServer(TestDef run, string endpoint, List<object> requests) {
            run.AddScript(endpoint + ":engine", async env => {
                async void Handler(IConn conn) {
                    using (conn) {
                        var msg = await conn.Read(5.Sec());
                        requests.Add(msg);
                        await conn.Write("World");
                    }
                }

                using (var socket = await env.Bind(80)) {
                    while (!env.Token.IsCancellationRequested) {
                        Handler(await socket.Accept());
                    }
                }
            });
        }

19 View Source File : NetworkingTests.cs
License : MIT License
Project Creator : abdullin

static void AddHelloWorldClient(TestDef run, string endpoint, List<object> responses) {
            run.AddScript("localhost:console", async env => {
                try {
                    using (var conn = await env.Connect(endpoint, 80)) {
                        await conn.Write("Hello");
                        var response = await conn.Read(5.Sec());
                        responses.Add(response);
                    }
                } catch (IOException ex) {
                    env.Debug(ex.Message);
                    responses.Add(ex);
                }
            });
        }

19 View Source File : BaseDataProviderAccessCoreSystem.cs
License : Apache License 2.0
Project Creator : abist-co-ltd

private bool RegisterDataProviderInternal<T>(
            bool retryWithRegistrar,
            Type concreteType,
            SupportedPlatforms supportedPlatforms = (SupportedPlatforms)(-1),
            params object[] args) where T : IMixedRealityDataProvider
        {
#if !UNITY_EDITOR
            if (!Application.platform.IsPlatformSupported(supportedPlatforms))
#else
            if (!EditorUserBuildSettings.activeBuildTarget.IsPlatformSupported(supportedPlatforms))
#endif
            {
                return false;
            }

            if (concreteType == null)
            {
                Debug.LogError($"Unable to register {typeof(T).Name} service with a null concrete type.");
                return false;
            }

            if (!typeof(IMixedRealityDataProvider).IsreplacedignableFrom(concreteType))
            {
                Debug.LogError($"Unable to register the {concreteType.Name} data provider. It does not implement {typeof(IMixedRealityDataProvider)}.");
                return false;
            }

            T dataProviderInstance;

            try
            {
                dataProviderInstance = (T)Activator.CreateInstance(concreteType, args);
            }
            catch (Exception e)
            {
                if (retryWithRegistrar && (e is MissingMethodException))
                {
                    Debug.LogWarning($"Failed to find an appropriate constructor for the {concreteType.Name} data provider. Adding the Registrar instance and re-attempting registration.");
#pragma warning disable 0618
                    List<object> updatedArgs = new List<object>();
                    updatedArgs.Add(Registrar);
                    if (args != null)
                    {
                        updatedArgs.AddRange(args);
                    }
                    return RegisterDataProviderInternal<T>(
                        false, // Do NOT retry, we have already added the configured IMIxedRealityServiceRegistrar
                        concreteType,
                        supportedPlatforms,
                        updatedArgs.ToArray());
#pragma warning restore 0618
                }

                Debug.LogError($"Failed to register the {concreteType.Name} data provider: {e.GetType()} - {e.Message}");

                // Failures to create the concrete type generally surface as nested exceptions - just logging
                // the top level exception itself may not be helpful. If there is a nested exception (for example,
                // null reference in the constructor of the object itself), it's helpful to also surface those here.
                if (e.InnerException != null)
                {
                    Debug.LogError("Underlying exception information: " + e.InnerException);
                }
                return false;
            }

            return RegisterDataProvider(dataProviderInstance);
        }

19 View Source File : Format.cs
License : MIT License
Project Creator : actions

internal void Append(String value)
            {
                if (value?.Length > 0)
                {
                    // Track memory
                    m_counter.Add(value);

                    // Append the segment
                    m_segments.Add(value);
                }
            }

19 View Source File : Format.cs
License : MIT License
Project Creator : actions

internal void Append(
                Int32 argIndex,
                String formatSpecifiers)
            {
                // Delay execution until the final ToString
                m_segments.Add(new Lazy<String>(() =>
                {
                    String result;

                    // Get the arg from the cache
                    var argValue = m_cache[argIndex];

                    // Evaluate the arg and cache the result
                    if (argValue == null)
                    {
                        // The evaluation result is required when format specifiers are used. Otherwise the string
                        // result is required. Go ahead and store both values. Since ConvertToString produces tracing,
                        // we need to run that now so the tracing appears in order in the log.
                        var evaluationResult = m_node.Parameters[argIndex + 1].Evaluate(m_context);
                        var stringResult = evaluationResult.ConvertToString();
                        argValue = new ArgValue(evaluationResult, stringResult);
                        m_cache[argIndex] = argValue;
                    }

                    // No format specifiers
                    if (String.IsNullOrEmpty(formatSpecifiers))
                    {
                        result = argValue.StringResult;
                    }
                    // Invalid
                    else
                    {
                        throw new FormatException(ExpressionResources.InvalidFormatSpecifiers(formatSpecifiers, argValue.EvaluationResult.Kind));
                    }

                    // Track memory
                    if (!String.IsNullOrEmpty(result))
                    {
                        m_counter.Add(result);
                    }

                    return result;
                }));
            }

19 View Source File : MainControl.xaml.cs
License : MIT License
Project Creator : Actipro

private void UpdateQuickLaunchItemsSource() {
			var options = new List<object>();

			options.Add(new QuickLaunchItem() { Text = "New Doreplacedent", ImageSource = new BitmapImage(new Uri("/Images/Icons/New16.png", UriKind.Relative)) });
			options.Add(new QuickLaunchItem() { Text = "Open Doreplacedent", ImageSource = new BitmapImage(new Uri("/Images/Icons/Open16.png", UriKind.Relative)) });
			options.Add(new QuickLaunchItem() { Text = "Save Doreplacedent", ImageSource = new BitmapImage(new Uri("/Images/Icons/Save16.png", UriKind.Relative)) });
			options.Add(new QuickLaunchItem() { Text = "Save All Doreplacedents" });
			options.Add(new QuickLaunchItem() { Text = "Help", ImageSource = new BitmapImage(new Uri("/Images/Icons/Help16.png", UriKind.Relative)) });

			var text = quickLaunchBox.Text;
			if (!String.IsNullOrEmpty(text)) {
				for (var index = options.Count - 1; index >= 0; index--) {
					var item = options[index] as QuickLaunchItem;
					if ((item != null) && (item.Text.IndexOf(text, 0, StringComparison.OrdinalIgnoreCase) == -1))
						options.RemoveAt(index);
				}

				if (options.Count > 0)
					options.Add(new QuickLaunchSeparator());

				options.Add(new QuickLaunchItem() { Text = String.Format("Get Help on \"{0}\"", text), ImageSource = new BitmapImage(new Uri("/Images/Icons/Help16.png", UriKind.Relative)) });
				options.Add(new QuickLaunchItem() { Text = String.Format("Smart Lookup on \"{0}\"", text), ImageSource = new BitmapImage(new Uri("/Images/Icons/Find16.png", UriKind.Relative)) });
			}

			quickLaunchBox.ItemsSource = options;
		}

19 View Source File : CustomTreeListBoxItemAdapter.cs
License : MIT License
Project Creator : Actipro

public override void OnDrop(DragEventArgs e, TreeListBox targetControl, object targereplacedem, TreeItemDropArea dropArea) {
			var originalEffects = e.Effects;
			e.Effects = DragDropEffects.None;

			// If the drag is over an item and there is item data present...
			var targetModel = targereplacedem as TreeNodeModel;
			if ((targetModel != null) && (dropArea != TreeItemDropArea.None) && (e.Data.GetDataPresent(TreeListBox.ItemDataFormat))) {
				// Resolve the real target item (in case the drop area is above or below the target item)
				var targetDropIndex = targetModel.Children.Count;
				switch (dropArea) {
					case TreeItemDropArea.Before:
					case TreeItemDropArea.After:
						var nav = targetControl.GereplacedemNavigator(targereplacedem);
						if (nav != null) {
							var targetChildModel = targetModel;
							var targetChildItem = targereplacedem;

							if (!nav.GoToParent())
								return;
							targereplacedem = nav.Currenreplacedem;
							targetModel = targereplacedem as TreeNodeModel;
							if (targetModel == null)
								return;

							var index = targetModel.Children.IndexOf(targetChildModel);
							if (index != -1)
								targetDropIndex = index + (dropArea == TreeItemDropArea.After ? 1 : 0);
						}
						break;
				}

				// Get the items
				var fullPaths = e.Data.GetData(TreeListBox.ItemDataFormat) as string;
				if (!string.IsNullOrEmpty(fullPaths)) {
					// Locate items based on full path
					var items = new List<object>();
					foreach (var fullPath in fullPaths.Split(new char[] { '\r', '\n' })) {
						if (!string.IsNullOrEmpty(fullPath)) {
							var item = targetControl.GereplacedemByFullPath(fullPath);
							if (item != null)
								items.Add(item);
						}
					}

					if (items.Count > 0) {
						// Check each item and validate that various drop operations are allowed before actually executing the drop
						foreach (var item in items) {
							if (item == targereplacedem) {
								MessageBox.Show("Cannot drop an item on itself.", "Drag and Drop", MessageBoxButton.OK);
								return;
							}
							else {
								var nav = targetControl.GereplacedemNavigator(item);
								if (nav == null) {
									MessageBox.Show("Cannot drop from a different control.", "Drag and Drop", MessageBoxButton.OK);
									return;
								}
								else {
									if (nav.GoToCommonAncestor(targereplacedem)) {
										if (nav.Currenreplacedem == item) {
											MessageBox.Show("Cannot drop onto a descendant item.", "Drag and Drop", MessageBoxButton.OK);
											return;
										}
									}
								}
							}
						}

						// Only support a single effect (you could add support for other effects like Copy if the Ctrl key is down here)
						if ((originalEffects & DragDropEffects.Move) == DragDropEffects.Move) {
							e.Effects = DragDropEffects.Move;
							e.Handled = true;
						}

						// Move items
						foreach (var item in items) {
							var nav = targetControl.GereplacedemNavigator(item);
							if (nav.GoToParent()) {
								var itemModel = item as TreeNodeModel;
								var parentModel = nav.Currenreplacedem as TreeNodeModel;
								if ((itemModel != null) && (parentModel != null)) {
									var index = parentModel.Children.IndexOf(itemModel);
									if (index != -1) {
										if ((parentModel == targetModel) && (index < targetDropIndex))
											targetDropIndex--;

										parentModel.Children.RemoveAt(index);
									}
									else
										break;
								}
								else
									break;

								targetModel.Children.Insert(Math.Max(0, Math.Min(targetModel.Children.Count, targetDropIndex++)), itemModel);
								targetModel.IsExpanded = true;
										
								// Focus the last item
								if (items[items.Count - 1] == item)
									targetControl.FocusItem(itemModel);
							}
						}
					}
				}
			}
		}

See More Examples