System.Collections.Generic.IEnumerable.Where(System.Func)

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

31569 Examples 7

19 Source : DefaultRedisSocket.cs
with MIT License
from 2881099

public static KeyValuePair<string, int> SplitHost(string host)
        {
            if (string.IsNullOrWhiteSpace(host?.Trim()))
                return new KeyValuePair<string, int>("127.0.0.1", 6379);

            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
                return new KeyValuePair<string, int>(ipv6.Groups[1].Value.Trim(), 
                    int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379);

            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
                return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", 6379);

            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                    return new KeyValuePair<string, int>(string.IsNullOrWhiteSpace(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1", testPort2);

                return new KeyValuePair<string, int>(host, 6379);
            }

            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
                return new KeyValuePair<string, int>(host, 6379);

            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                    return new KeyValuePair<string, int>(testHost, 6379);
            }

            return new KeyValuePair<string, int>(host, 6379);
        }

19 Source : XmlHelper.cs
with MIT License
from 279328316

public T DeserializeNode<T>(XmlNode node = null) where T : clreplaced, new()
        {
            T model = new T();
            XmlNode firstChild;
            if (node == null)
            {
                node = root;
            }
            firstChild = node.FirstChild;

            Dictionary<string, string> dict = new Dictionary<string, string>();

            XmlAttributeCollection xmlAttribute = node.Attributes;
            if (node.Attributes.Count > 0)
            {
                for (int i = 0; i < node.Attributes.Count; i++)
                {
                    if (!dict.Keys.Contains(node.Attributes[i].Name))
                    {
                        dict.Add(node.Attributes[i].Name, node.Attributes[i].Value);
                    }
                }
            }
            if (!dict.Keys.Contains(firstChild.Name))
            {
                dict.Add(firstChild.Name, firstChild.InnerText);
            }
            XmlNode next = firstChild.NextSibling;
            while (next != null)
            {
                if (!dict.Keys.Contains(next.Name))
                {
                    dict.Add(next.Name, next.InnerText);
                }
                else
                {
                    throw new Exception($"重复的属性Key:{next.Name}");
                }
                next = next.NextSibling;
            }


            #region 为对象赋值

            Type modelType = typeof(T);
            List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();

            foreach (PropertyInfo pi in piList)
            {
                string dictKey = dict.Keys.FirstOrDefault(key => key.ToLower() == pi.Name.ToLower());
                if (!string.IsNullOrEmpty(dictKey))
                {
                    string value = dict[dictKey];
                    TypeConverter typeConverter = TypeDescriptor.GetConverter(pi.PropertyType);
                    if (typeConverter != null)
                    {
                        if (typeConverter.CanConvertFrom(typeof(string)))
                            pi.SetValue(model, typeConverter.ConvertFromString(value));
                        else
                        {
                            if (typeConverter.CanConvertTo(pi.PropertyType))
                                pi.SetValue(model, typeConverter.ConvertTo(value, pi.PropertyType));
                        }
                    }
                }
            }
            #endregion
            return model;
        }

19 Source : Serializer.cs
with MIT License
from 2881099

static Func<Dictionary<string, string>, T> CompilePropertyDeserializer()
        {
            var o_t = typeof(T);
            var o = Expression.Variable(o_t, "o");
            var o_new = Expression.New(typeof(T));

            var d_t = typeof(Dictionary<string, string>);
            var d = Expression.Parameter(d_t, "d");
            var d_mi_try_get_value = d_t.GetMethod("TryGetValue");

            var item_t = typeof(String);
            var item = Expression.Variable(item_t, "item");

            var tc_t = typeof(TypeConverter);
            var tc = Expression.Variable(tc_t, "tc");
            var tc_mi_can_convert_from = tc_t.GetMethod("CanConvertFrom", new[] { typeof(Type) });
            var tc_mi_convert_from = tc_t.GetMethod("ConvertFrom", new[] { typeof(Object) });

            var td_t = typeof(TypeDescriptor);
            var td_mi_get_converter = td_t.GetMethod("GetConverter", new[] { typeof(Type) });

            var binds = o_t.GetProperties(BindingFlags.Public | BindingFlags.Instance)
                .Where(x => x.CanRead)
                .Select(x =>
                {
                    var value_t = x.PropertyType;
                    var value = Expression.Variable(value_t, "value");
                    var target = Expression.Label(x.PropertyType);

                    return Expression.Bind(x, Expression.Block(new[] { item, value },
                        Expression.replacedign(tc, Expression.Call(null, td_mi_get_converter, Expression.Constant(x.PropertyType))),
                        Expression.IfThen(
                            Expression.Call(d, d_mi_try_get_value, Expression.Constant(x.Name), item),
                            Expression.IfThen(
                                Expression.NotEqual(item, Expression.Constant(null)),
                                Expression.IfThen(
                                    Expression.Call(tc, tc_mi_can_convert_from, Expression.Constant(typeof(String))),
                                    Expression.Block(
                                        Expression.replacedign(value, Expression.Convert(Expression.Call(tc, tc_mi_convert_from, item), x.PropertyType)),
                                        Expression.Return(target, value, x.PropertyType))))),
                        Expression.Label(target, value)
                    ));
                }).ToArray();

            var body = Expression.Block(new[] { o, tc },
                Expression.MemberInit(o_new, binds)
            );

            return Expression.Lambda<Func<Dictionary<string, string>, T>>(body, d)
                .Compile();
        }

19 Source : RedisClientPool.cs
with MIT License
from 2881099

internal void SetHost(string host)
        {
            if (string.IsNullOrEmpty(host?.Trim())) {
                _ip = "127.0.0.1";
                _port = 6379;
                return;
            }
            host = host.Trim();
            var ipv6 = Regex.Match(host, @"^\[([^\]]+)\]\s*(:\s*(\d+))?$");
            if (ipv6.Success) //ipv6+port 格式: [fe80::b164:55b3:4b4f:7ce6%15]:6379
            {
                _ip = ipv6.Groups[1].Value.Trim();
                _port = int.TryParse(ipv6.Groups[3].Value, out var tryint) && tryint > 0 ? tryint : 6379;
                return;
            }
            var spt = (host ?? "").Split(':');
            if (spt.Length == 1) //ipv4 or domain
            {
                _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                _port = 6379;
                return;
            }
            if (spt.Length == 2) //ipv4:port or domain:port
            {
                if (int.TryParse(spt.Last().Trim(), out var testPort2))
                {
                    _ip = string.IsNullOrEmpty(spt[0].Trim()) == false ? spt[0].Trim() : "127.0.0.1";
                    _port = testPort2;
                    return;
                }
                _ip = host;
                _port = 6379;
                return;
            }
            if (IPAddress.TryParse(host, out var tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6) //test ipv6
            {
                _ip = host;
                _port = 6379;
                return;
            }
            if (int.TryParse(spt.Last().Trim(), out var testPort)) //test ipv6:port
            {
                var testHost = string.Join(":", spt.Where((a, b) => b < spt.Length - 1));
                if (IPAddress.TryParse(testHost, out tryip) && tryip.AddressFamily == AddressFamily.InterNetworkV6)
                {
                    _ip = testHost;
                    _port = 6379;
                    return;
                }
            }
            _ip = host;
            _port = 6379;
        }

19 Source : XmlHelper.cs
with MIT License
from 279328316

public static void SerializeCollection<T>(IEnumerable<T> list, string filePath) where T : clreplaced, new()
        {
            XmlDoreplacedent xmlDoc = new XmlDoreplacedent();
            Type modelType = typeof(T);
            XmlDeclaration declaration = xmlDoc.CreateXmlDeclaration("1.0", "utf-8", "");
            xmlDoc.AppendChild(declaration);
            XmlElement root = xmlDoc.CreateElement(string.Format("{0}List", modelType.Name));
            xmlDoc.AppendChild(root);

            List<PropertyInfo> piList = modelType.GetProperties().Where(pro => (pro.PropertyType.Equals(typeof(string)) || pro.PropertyType.IsValueType) && pro.CanRead && pro.CanWrite).ToList();
            foreach (T item in list)
            {
                XmlNode xmlNode = xmlDoc.CreateNode(XmlNodeType.Element, modelType.Name, "");
                root.AppendChild(xmlNode);

                foreach (PropertyInfo pi in piList)
                {
                    object value = pi.GetValue(item);
                    if (value != null)
                    {
                        var propertyNode = xmlDoc.CreateNode(XmlNodeType.Element, pi.Name, "");
                        propertyNode.InnerText = value.ToString();
                        xmlNode.AppendChild(propertyNode);
                    }
                }
            }
            xmlDoc.Save(filePath);
        }

19 Source : Robot.cs
with Apache License 2.0
from 2881099

public void GetPlayerProbableCard() {
			var ret = new Dictionary<int, List<int[]>>();
			var index = this.playerIndex;
			GetPlayerProbableCardPlayerInfo player1 = new GetPlayerProbableCardPlayerInfo { player = this.players[(++index) % 3] };
			GetPlayerProbableCardPlayerInfo player2 = new GetPlayerProbableCardPlayerInfo { player = this.players[(++index) % 3] };
			var cards = this.GetOutsideCard(); //外面所有的牌

			Func<GetPlayerProbableCardPlayerInfo, bool> checkOver = player => {
				if (player.player.pokerLength - player.pokers.Count == 0) {
					
				}
				return false;
			};

			if (this.players[this.playerIndex].role == GamePlayerRole.农民) {
				//判断底牌,确定了的牌
				if (player1.player.role == GamePlayerRole.地主) {
					foreach (var dp in this.dipai) {
						if (cards.Remove(dp)) {
							player1.pokers.Add(dp);
						}
					}
				}
				if (player2.player.role == GamePlayerRole.地主) {
					foreach (var dp in this.dipai) {
						if (cards.Remove(dp)) {
							player2.pokers.Add(dp);
						}
					}
				}
			}

			var dizhu = this.players.Where(a => a.role == GamePlayerRole.地主).First();
			for(var a = 0; a < dizhu.chupai.Count; a++) {

			}

			if (this.players[this.playerIndex].role == GamePlayerRole.地主) {
				//我是地主,我的上家为了顶我出牌套路深,我的下家出牌逻辑较常规,可根据其计算剩余牌型
			}
			if (player1.player.role == GamePlayerRole.地主) {
				//我的下家是地主,地主出牌最没套路,我的上家出牌也没套路
			}
			if (player2.player.role == GamePlayerRole.地主) {
				//我的上家是地主,地主出牌最没牌路,我的下家(也是地主的上家)出牌会顶地主套路深

			}
		}

19 Source : IdleBus`1.cs
with MIT License
from 2881099

public TKey[] GetKeys(Func<TValue, bool> filter = null)
        {
            if (filter == null) return _dic.Keys.ToArray();
            return _dic.Keys.ToArray().Where(key => _dic.TryGetValue(key, out var item) && filter(item.value)).ToArray();
        }

19 Source : PubSub.cs
with MIT License
from 2881099

internal void Cancel(params Guid[] ids)
            {
                if (ids == null) return;
                var readyUnsubInterKeys = new List<string>();
                foreach (var id in ids)
                {
                    if (_cancels.TryRemove(id, out var oldkeys))
                        foreach (var oldkey in oldkeys)
                        {
                            if (_registers.TryGetValue(oldkey, out var oldrecvs) &&
                                oldrecvs.TryRemove(id, out var oldrecv) &&
                                oldrecvs.Any() == false)
                                readyUnsubInterKeys.Add(oldkey);
                        }
                }
                var unsub = readyUnsubInterKeys.Where(a => !a.StartsWith(_psub_regkey_prefix)).ToArray();
                var punsub = readyUnsubInterKeys.Where(a => a.StartsWith(_psub_regkey_prefix)).Select(a => a.Replace(_psub_regkey_prefix, "")).ToArray();
                if (unsub.Any()) Call("UNSUBSCRIBE".Input(unsub));
                if (punsub.Any()) Call("PUNSUBSCRIBE".Input(punsub));

                if (!_cancels.Any())
                    lock (_lock)
                        if (!_cancels.Any())
                            _redisSocket?.ReleaseSocket();
            }

19 Source : PubSub.cs
with MIT License
from 2881099

internal void UnSubscribe(bool punsub, string[] channels)
            {
                channels = channels?.Distinct().Select(a => punsub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
                if (channels.Any() != true) return;
                var ids = channels.Select(a => _registers.TryGetValue(a, out var tryval) ? tryval : null).Where(a => a != null).SelectMany(a => a.Keys).Distinct().ToArray();
                Cancel(ids);
            }

19 Source : PubSub.cs
with MIT License
from 2881099

internal IDisposable Subscribe(bool psub, string[] channels, Action<string, string, object> handler)
            {
                if (_stoped) return new PubSubSubscribeDisposable(this, null);
                channels = channels?.Distinct().Where(a => !string.IsNullOrEmpty(a)).ToArray(); //In case of external modification
                if (channels?.Any() != true) return new PubSubSubscribeDisposable(this, null);

                var id = Guid.NewGuid();
                var time = DateTime.Now;
                var regkeys = channels.Select(a => psub ? $"{_psub_regkey_prefix}{a}" : a).ToArray();
                for (var a = 0; a < regkeys.Length; a++)
                {
                    ConcurrentDictionary<Guid, RegisterInfo> dict = null;
                    lock (_lock) dict = _registers.GetOrAdd(regkeys[a], k1 => new ConcurrentDictionary<Guid, RegisterInfo>());
                    dict.TryAdd(id, new RegisterInfo(id, handler, time));
                }
                lock (_lock)
                    _cancels.TryAdd(id, regkeys);
                var isnew = false;
                if (IsSubscribed == false)
                {
                    lock (_lock)
                    {
                        if (IsSubscribed == false)
                        {
                            _redisSocket = _topOwner.Adapter.GetRedisSocket(null);
                            IsSubscribed = isnew = true;
                        }
                    }
                }
                if (isnew)
                {
                    new Thread(() =>
                    {
                        _redisSocketReceiveTimeoutOld = _redisSocket.ReceiveTimeout;
                        _redisSocket.ReceiveTimeout = TimeSpan.Zero;
                        var timer = new Timer(state =>
                        {
                            _topOwner.Adapter.Refersh(_redisSocket); //防止 IdleBus 超时回收
                            try { _redisSocket.Write("PING"); } catch { }
                        }, null, 10000, 10000);
                        var readCmd = "PubSubRead".SubCommand(null).FlagReadbytes(false);
                        while (_stoped == false)
                        {
                            RedisResult rt = null;
                            try
                            {
                                rt = _redisSocket.Read(readCmd);
                            }
                            catch
                            {
                                Thread.CurrentThread.Join(100);
                                if (_cancels.Any()) continue;
                                break;
                            }
                            var val = rt.Value as object[];
                            if (val == null) continue; //special case

                            var val1 = val[0].ConvertTo<string>();
                            switch (val1)
                            {
                                case "pong":
                                case "punsubscribe":
                                case "unsubscribe":
                                    continue;
                                case "pmessage":
                                    OnData(val[1].ConvertTo<string>(), val[2].ConvertTo<string>(), val[3]);
                                    continue;
                                case "message":
                                    OnData(null, val[1].ConvertTo<string>(), val[2]);
                                    continue;
                            }
                        }
                        timer.Dispose();
                        lock (_lock)
                        {
                            IsSubscribed = false;
                            _redisSocket.ReceiveTimeout = _redisSocketReceiveTimeoutOld;
                            _redisSocket.ReleaseSocket();
                            _redisSocket.Dispose();
                            _redisSocket = null;
                        }
                    }).Start();
                }
                Call((psub ? "PSUBSCRIBE" : "SUBSCRIBE").Input(channels));
                return new PubSubSubscribeDisposable(this, () => Cancel(id));
            }

19 Source : TypeExtension.cs
with MIT License
from 2881099

public static IEnumerable<MethodInfo> GetApis(this Type type)
        {
            var addMethods = type.GetEvents().Select(_event => _event.GetAddMethod());
            var removeMethods = type.GetEvents().Select(_event => _event.GetRemoveMethod());
            var getMethods = type.GetProperties().Select(_propety => _propety.GetGetMethod());
            var setMethods = type.GetProperties().Select(_propety => _propety.GetSetMethod());

            var enumerable = addMethods
                .Concat(removeMethods)
                .Concat(getMethods)
                .Concat(setMethods)
                .Where(_method=>_method != null)
                .Select(_method => _method.Name);

            var methods = enumerable.ToList();
            methods.Add("Dispose");

            return type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly).Where(_method=> !methods.Contains(_method.Name));
        }

19 Source : SagaMaster.cs
with MIT License
from 2881099

async static Task<bool?> CancelAsync(FreeSqlCloud<TDBKey> cloud, SagaMasterInfo masterInfo, List<SagaUnitInfo> unitInfos, ISagaUnit[] units, bool retry)
#endif
        {
            var isCommited = unitInfos.Count == masterInfo.Total;
            var isCanceled = false;
            if (isCommited == false)
            {
                var cancelCount = 0;
                for (var idx = masterInfo.Total - 1; idx >= 0; idx--)
                {
                    var unitInfo = unitInfos.Where(tt => tt.Index == idx + 1 && tt.Stage == SagaUnitStage.Commit).FirstOrDefault();
                    try
                    {
                        if (unitInfo != null)
                        {
                            if ((units[idx] as ISagaUnitSetter)?.StateIsValued != true)
                                SetSagaState(units[idx], unitInfo);
                            var ormMaster = cloud._ormMaster;
#if net40
                            using (var conn = ormMaster.Ado.MasterPool.Get())
#else
                            using (var conn = await ormMaster.Ado.MasterPool.GetAsync())
#endif
                            {
                                var tran = conn.Value.BeginTransaction();
                                var tranIsCommited = false;
                                try
                                {
                                    var fsql = FreeSqlTransaction.Create(ormMaster, () => tran);
                                    (units[idx] as ISagaUnitSetter)?.SetUnit(unitInfo);
                                    var update = fsql.Update<SagaUnitInfo>()
                                        .Where(a => a.Tid == masterInfo.Tid && a.Index == idx + 1 && a.Stage == SagaUnitStage.Commit)
                                        .Set(a => a.Stage, SagaUnitStage.Cancel);
#if net40
                                    if (update.ExecuteAffrows() == 1)
                                        units[idx].Cancel();
#else
                                    if (await update.ExecuteAffrowsAsync() == 1)
                                        await units[idx].Cancel();
#endif
                                    tran.Commit();
                                    tranIsCommited = true;
                                }
                                finally
                                {
                                    if (tranIsCommited == false)
                                        tran.Rollback();
                                }
                            }
                            if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isCommited ? "COMMIT" : "CANCEL")} successful{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}\r\n    State: {unitInfo.State}\r\n    Type:  {unitInfo.TypeName}");
                        }
                        cancelCount++;
                    }
                    catch (Exception ex)
                    {
                        if (unitInfo != null)
                            if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isCommited ? "COMMIT" : "CANCEL")} failed{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}, -ERR {ex.Message}\r\n    State: {unitInfo.State}\r\n    Type:  {unitInfo.TypeName}");
                    }
                }
                isCanceled = cancelCount == masterInfo.Total;
            }
            if (isCommited || isCanceled)
            {
                var update = cloud._ormMaster.Update<SagaMasterInfo>()
                    .Where(a => a.Tid == masterInfo.Tid && a.Status == SagaMasterStatus.Pending)
                    .Set(a => a.RetryCount + 1)
                    .Set(a => a.RetryTime == DateTime.UtcNow)
                    .Set(a => a.Status, isCommited ? SagaMasterStatus.Commited : SagaMasterStatus.Canceled)
                    .Set(a => a.FinishTime == DateTime.UtcNow);
#if net40
                update.ExecuteAffrows();
#else
                await update.ExecuteAffrowsAsync();
#endif

                if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Completed, all units {(isCommited ? "COMMIT" : "CANCEL")} successfully{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}");
                return isCommited;
            }
            else
            {
                var update = cloud._ormMaster.Update<SagaMasterInfo>()
                    .Where(a => a.Tid == masterInfo.Tid && a.Status == SagaMasterStatus.Pending && a.RetryCount < a.MaxRetryCount)
                    .Set(a => a.RetryCount + 1)
                    .Set(a => a.RetryTime == DateTime.UtcNow);
#if net40
                var affrows = update.ExecuteAffrows();
#else
                var affrows = await update.ExecuteAffrowsAsync();
#endif
                if (affrows == 1)
                {
                    if (retry)
                    {
                        //if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({saga.Tid}, {saga.replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
                        cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(masterInfo.RetryInterval), GetTempTask(cloud, masterInfo.Tid, masterInfo.replacedle, masterInfo.RetryInterval));
                    }
                }
                else
                {
                    update = cloud._ormMaster.Update<SagaMasterInfo>()
                        .Where(a => a.Tid == masterInfo.Tid && a.Status == SagaMasterStatus.Pending)
                        .Set(a => a.Status, SagaMasterStatus.ManualOperation);
#if net40
                    update.ExecuteAffrows();
#else
                    await update.ExecuteAffrowsAsync();
#endif

                    if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"SAGA({masterInfo.Tid}, {masterInfo.replacedle}) Not completed, waiting for manual operation 【人工干预】");
                }
                return null;
            }
        }

19 Source : UCGeneratedCode.cs
with MIT License
from 2881099

private void comboBoxEx1_DropDownClosed(object sender, EventArgs e)
        {
            var fileInfo = lst.Where(a => a.Name == comboBoxEx1.Text).FirstOrDefault();
            if (fileInfo != null)
            {
                editorTemplates.Load(fileInfo.FullName);
            }
        }

19 Source : FrmBatch.cs
with MIT License
from 2881099

private async void command_export_Executed(object sender, EventArgs e)
        {

            Properties.Settings.Default.Save();
            if (listBoxAdv2.Items.Count == 0)
            {
                MessageBoxEx.Show("请选择表");
                return;
            }
            if (string.IsNullOrEmpty(textBoxX1.Text))
            {
                MessageBoxEx.Show("命名空间不能为空");
                return;
            }
            if (string.IsNullOrEmpty(textBoxX4.Text))
            {
                MessageBoxEx.Show("请选择导出路径");
                return;
            }
            if (listBoxAdv3.CheckedItems.Count == 0)
            {
                MessageBoxEx.Show("请选择生成模板");
                return;
            }
            var templates = listBoxAdv3.CheckedItems.Cast<ListBoxItem>().Select(a => a.Text).ToArray();     
            var taskBuild = new TaskBuild()
            {
                Fsql = G.GetFreeSql(_node.DataKey),
                DbName = _node.Text,
                FileName = textBoxX3.Text,
                GeneratePath = textBoxX4.Text,
                NamespaceName = textBoxX1.Text,
                RemoveStr = textBoxX2.Text,
                OptionsEnreplacedy01 = checkBoxX1.Checked,
                OptionsEnreplacedy02 = checkBoxX2.Checked,
                OptionsEnreplacedy03 = checkBoxX3.Checked,
                OptionsEnreplacedy04 = checkBoxX4.Checked,
                Templates = templates
            };
            var tables = listBoxAdv2.Items.Cast<string>().ToArray();
            var tableInfos = dbTableInfos.Where(a => tables.Contains(a.Name)).ToList();
            FrmLoading frmLoading=null;
            ThreadPool.QueueUserWorkItem(new WaitCallback(a =>
            {
                this.Invoke((Action)delegate ()
                {
                    frmLoading = new FrmLoading("正在生成中,请稍后.....");
                    frmLoading.ShowDialog();
                });
            }));
            await new CodeGenerate().Setup(taskBuild, tableInfos);
            this.Invoke((Action)delegate () { frmLoading?.Close(); });

        }

19 Source : FrmCreateDataConnection.cs
with MIT License
from 2881099

private void buttonX1_Click(object sender, EventArgs e)
        {
            if (buttonX1.Text == "保存")
            {
                userControl?.SaveDataConnection();
                MessageBoxEx.Show("保存成功", "操作提示", MessageBoxButtons.OK, MessageBoxIcon.Information);
                this.DialogResult = DialogResult.OK;
                this.Close();
            }
            else
            {
                groupPanel1.Text = "配置数据库连接";
                controls = groupPanel1.Controls.Cast<Control>().Where(a => (a is CheckBoxX checkBox)).ToArray();
                groupPanel1.Controls.Clear();
                var checkbox = controls.Where(a => (a is CheckBoxX checkBox) && checkBox.Checked).FirstOrDefault();
                if (checkbox == null) return;
                switch (checkbox.Text)
                {
                    case "MySql": userControl = new UcMysql(); break;
                    case "SqlServer": userControl = new UcSqlServer(); break;
                    case "PostgreSQL": userControl = new UcPostgreSQL(); break;
                    case "Oracle": userControl = new UcOracle(); break;
                    case "Sqlite": userControl = new UcSqlite(); break;
                    case "自定义": userControl = new UCConnection(); break;
                }
                userControl.BackColor = Color.Transparent;
                userControl.Dock = DockStyle.Fill;
                groupPanel1.Controls.Add(userControl);
                buttonX2.Visible = true;
                buttonX3.Visible = true;
                buttonX1.Text = "保存";
            }

        }

19 Source : FrmRazorTemplates.cs
with MIT License
from 2881099

private void ButtonX1_Click(object sender, EventArgs e)
        {
            if (comboBoxEx1.Items.Count <= 0)
            {
                ToastNotification.ToastBackColor = Color.Red;
                ToastNotification.ToastForeColor = Color.White;
                ToastNotification.ToastFont = new Font("微软雅黑", 15);
                ToastNotification.Show(this, "没有可用模板,请新建。", null, 3000, eToastGlowColor.Red, eToastPosition.TopCenter);
                return;
            }
            var enreplacedy = lst.Where(a => a.Name == comboBoxEx1.Text).FirstOrDefault();
            if (enreplacedy != null)
            {
                TemplatesPath = enreplacedy.FullName;
                TemplatesName = enreplacedy.Name.Replace(".tpl", "").Trim();
                this.Close();
                this.DialogResult = System.Windows.Forms.DialogResult.OK;
            }
        }

19 Source : TccMaster.cs
with MIT License
from 2881099

async static Task<bool?> ConfimCancelAsync(FreeSqlCloud<TDBKey> cloud, TccMasterInfo masterInfo, List<TccUnitInfo> unitInfos, ITccUnit[] units, bool retry)
#endif
        {
            var isConfirm = unitInfos.Count == masterInfo.Total;
            var successCount = 0;
            for (var idx = masterInfo.Total - 1; idx >= 0; idx--)
            {
                var unitInfo = unitInfos.Where(tt => tt.Index == idx + 1 && tt.Stage == TccUnitStage.Try).FirstOrDefault();
                try
                {
                    if (unitInfo != null)
                    {
                        if ((units[idx] as ITccUnitSetter)?.StateIsValued != true)
                            SetTccState(units[idx], unitInfo);
                        var ormMaster = cloud._ormMaster;
#if net40
                        using (var conn = cloud.Ado.MasterPool.Get())
#else
                        using (var conn = await cloud.Ado.MasterPool.GetAsync())
#endif
                        {
                            var tran = conn.Value.BeginTransaction();
                            var tranIsCommited = false;
                            try
                            {
                                var fsql = FreeSqlTransaction.Create(ormMaster, () => tran);
                                (units[idx] as ITccUnitSetter)?.SetUnit(unitInfo);
                                var update = fsql.Update<TccUnitInfo>()
                                    .Where(a => a.Tid == masterInfo.Tid && a.Index == idx + 1 && a.Stage == TccUnitStage.Try)
                                    .Set(a => a.Stage, isConfirm ? TccUnitStage.Confirm : TccUnitStage.Cancel);
#if net40
                                if (update.ExecuteAffrows() == 1)
                                {
                                    if (isConfirm) units[idx].Confirm();
                                    else units[idx].Cancel();
                                }
#else
                                if (await update.ExecuteAffrowsAsync() == 1)
                                {
                                    if (isConfirm) await units[idx].Confirm();
                                    else await units[idx].Cancel();
                                }
#endif
                                tran.Commit();
                                tranIsCommited = true;
                            }
                            finally
                            {
                                if (tranIsCommited == false)
                                    tran.Rollback();
                            }
                        }
                        if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isConfirm ? "CONFIRM" : "CANCEL")} successful{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}\r\n    State: {unitInfo.State}\r\n    Type:  {unitInfo.TypeName}");
                    }
                    successCount++;
                }
                catch(Exception ex)
                {
                    if (unitInfo != null)
                        if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Unit{unitInfo.Index}{(string.IsNullOrWhiteSpace(unitInfo.Description) ? "" : $"({unitInfo.Description})")} {(isConfirm ? "CONFIRM" : "CANCEL")} failed{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}, -ERR {ex.Message}\r\n    State: {unitInfo.State}\r\n    Type:  {unitInfo.TypeName}");
                }
            }
            if (successCount == masterInfo.Total)
            {
                var update = cloud._ormMaster.Update<TccMasterInfo>()
                    .Where(a => a.Tid == masterInfo.Tid && a.Status == TccMasterStatus.Pending)
                    .Set(a => a.RetryCount + 1)
                    .Set(a => a.RetryTime == DateTime.UtcNow)
                    .Set(a => a.Status, isConfirm ? TccMasterStatus.Confirmed : TccMasterStatus.Canceled)
                    .Set(a => a.FinishTime == DateTime.UtcNow);
#if net40
                update.ExecuteAffrows();
#else
                await update.ExecuteAffrowsAsync();
#endif
                if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Completed, all units {(isConfirm ? "CONFIRM" : "CANCEL")} successfully{(masterInfo.RetryCount > 0 ? $" after {masterInfo.RetryCount} retries" : "")}");
                return isConfirm;
            }
            else
            {
                var update = cloud._ormMaster.Update<TccMasterInfo>()
                    .Where(a => a.Tid == masterInfo.Tid && a.Status == TccMasterStatus.Pending && a.RetryCount < a.MaxRetryCount)
                    .Set(a => a.RetryCount + 1)
                    .Set(a => a.RetryTime == DateTime.UtcNow);
#if net40
                var affrows = update.ExecuteAffrows();
#else
                var affrows = await update.ExecuteAffrowsAsync();
#endif
                if (affrows == 1)
                {
                    if (retry)
                    {
                        //if (cloud.TccTraceEnable) cloud.OnTccTrace($"TCC ({tcc.Tid}, {tcc.replacedle}) Not completed, waiting to try again, current tasks {cloud._scheduler.QuanreplacedyTempTask}");
                        cloud._scheduler.AddTempTask(TimeSpan.FromSeconds(masterInfo.RetryInterval), GetTempTask(cloud, masterInfo.Tid, masterInfo.replacedle, masterInfo.RetryInterval));
                    }
                }
                else
                {
                    update = cloud._ormMaster.Update<TccMasterInfo>()
                        .Where(a => a.Tid == masterInfo.Tid && a.Status == TccMasterStatus.Pending)
                        .Set(a => a.Status, TccMasterStatus.ManualOperation);
#if net40
                    update.ExecuteAffrows();
#else
                    await update.ExecuteAffrowsAsync();
#endif
                    if (cloud._distributeTraceEnable) cloud._distributedTraceCall($"TCC ({masterInfo.Tid}, {masterInfo.replacedle}) Not completed, waiting for manual operation 【人工干预】");
                }
                return null;
            }
        }

19 Source : DynamicProxy.cs
with MIT License
from 2881099

public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
        {
            if (type == null) return null;
            var typeCSharpName = type.DisplayCsharp();

            if (type.IsNotPublic)
            {
                if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
                return null;
            }

            var matchedMemberInfos = new List<MemberInfo>();
            var matchedAttributes = new List<DynamicProxyAttribute>();
            var matchedAttributesFromServices = new List<FieldInfo[]>();
            var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
            var methodOverrideSb = new StringBuilder();
            var sb = methodOverrideSb;

            #region Common Code

            Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
            {
                var sbt = new StringBuilder();
                for (var a = attrsIndex; a < matchedAttributes.Count; a++)
                {
                    sbt.Append($@"{(proxyMethodName == "Before" ? $@"
        var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
        __DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
        var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
        {(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
        {(proxyMethodName == "Before" ? 
        $@"if (__DP_ARG___is_return == false)
        {{
            __DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
            if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
        }}" : 
        $"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
                }
                return sbt.ToString();
            };
            Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
            {
                var sbt = new StringBuilder();
                var taskType = returnType.ReturnTypeWithoutTask();
                sbt.Append($@"
        {(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
                (taskType.IsValueType || taskType.IsGenericParameter ?
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
                    $"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
                ) :
                (returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
                return sbt.ToString();
            };
            Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
            {
                return $@"
            if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
            };
            #endregion

            #region Methods
            var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
            var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
            foreach (var method in methods)
            {
                if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
                    if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
                var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                if (attrs.Any() == false) continue;
                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => method));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
                if (method.IsVirtual == false || method.IsFinal)
                {
                    if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
                    continue;
                }

#if net40
                var returnType = method.ReturnType;
                var methodIsAsync = false;
#else
                var returnType = method.ReturnType.ReturnTypeWithoutTask();
                var methodIsAsync = method.ReturnType.IsTask();

                //if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
                //    attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
                //{

                //}
#endif

                var baseInvoke = type.IsInterface == false ? $@"

        try
        {{
            if (__DP_ARG___is_return == false)
            {{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
                {(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
            }}
        }}
        catch (Exception __DP_ARG___ex)
        {{
            __DP_ARG___exception = __DP_ARG___ex;
        }}" : "";

                sb.Append($@"

    {(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
    {{
        Exception __DP_ARG___exception = null;
        var __DP_ARG___is_return = false;
        object __DP_ARG___return_value = null;
        var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n        ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
        {getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
        {getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
    }}");
            }
            #endregion

            var propertyOverrideSb = new StringBuilder();
            sb = propertyOverrideSb;
            #region Property
            var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
            foreach (var prop2 in props)
            {
                var getMethod = prop2.GetGetMethod(false);
                var setMethod = prop2.GetSetMethod(false);
                if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
                {
                    if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
                        setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
                    {
                        if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
                        continue;
                    }
                }

                var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                var prop2AttributeAny = attrs.Any();
                var getMethodAttributeAny = prop2AttributeAny;
                var setMethodAttributeAny = prop2AttributeAny;
                if (attrs.Any() == false && getMethod?.IsVirtual == true)
                {
                    attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    getMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false && setMethod?.IsVirtual == true)
                {
                    attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
                    setMethodAttributeAny = attrs.Any();
                }
                if (attrs.Any() == false) continue;

                var attrsIndex = matchedAttributes.Count;
                matchedMemberInfos.AddRange(attrs.Select(a => prop2));
                matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
                matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
                    .Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
                matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif

                var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();

                var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
                var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
                var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
                if (propSetModification == propModification) propSetModification = "";
                if (propGetModification == propModification) propGetModification = "";

                //if (getMethod.IsAbstract) sb.Append("abstract ");
                sb.Append($@"

    {propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
    {{");

                if (getMethod != null)
                {
                    if (getMethodAttributeAny == false) sb.Append($@"
        {propGetModification} get
        {{
            return base.{prop2.Name}
        }}");
                    else sb.Append($@"
        {propGetModification} get
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
            {getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
        }}");
                }

                if (setMethod != null)
                {
                    if (setMethodAttributeAny == false) sb.Append($@"
        {propSetModification} set
        {{
            base.{prop2.Name} = value;
        }}");
                    else sb.Append($@"
        {propSetModification} set
        {{
            Exception __DP_ARG___exception = null;
            var __DP_ARG___is_return = false;
            object __DP_ARG___return_value = null;
            var __DP_ARG___parameters = new Dictionary<string, object>();
            __DP_ARG___parameters.Add(""value"", value);
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}

            try
            {{
                if (__DP_ARG___is_return == false)
                {{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
                    base.{prop2.Name} = value;
                }}
            }}
            catch (Exception __DP_ARG___ex)
            {{
                __DP_ARG___exception = __DP_ARG___ex;
            }}
            {getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
        }}");
                }


                sb.Append($@"
    }}");
            }
            #endregion

            string proxyCscode = "";
            replacedembly proxyreplacedembly = null;
            Type proxyType = null;

            if (matchedMemberInfos.Any())
            {
                #region Constructors
                sb = new StringBuilder();
                var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
                sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
    private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
                foreach (var ctor in ctors)
                {
                    var ctorParams = ctor.GetParameters();
                    sb.Append($@"

    {(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
                        (ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
                        string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
        : base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
    {{{string.Join("", fromServicesTypes.Select(serviceType => $@"
        {serviceType.Value} = parameter{serviceType.Value};"))}
    }}");
                }
                for (var a = 0; a < matchedAttributesFromServices.Count; a++)
                {
                    sb.Append($@"

    private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
    {{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
        __DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
    }}");
                }
                #endregion

                proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;

public clreplaced {clreplacedName} : {typeCSharpName}
{{
    private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));

    //这里要注释掉,如果重写的基类没有无参构造函数,会报错
    //public {clreplacedName}({_metaName} meta)
    //{{
    //    __DP_Meta = meta;
    //}}
    {sb.ToString()}
    {methodOverrideSb.ToString()}

    {propertyOverrideSb.ToString()}
}}";
                proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
                proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
            }
            methodOverrideSb.Clear();
            propertyOverrideSb.Clear();
            sb.Clear();
            return new DynamicProxyMeta(
                type, ctors,
                matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
                isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
        }

19 Source : UserControlBase.cs
with MIT License
from 2881099

protected List<TextBoxX> InitLostFocus(Control control, Highlighter highlighter)
        {
            textBoxs = control.Controls.Cast<Control>().Where(a => (a is TextBoxX textBox))
            .OrderBy(a => a.Name).Select(a => a as TextBoxX).ToList();
            textBoxs.ForEach(a =>
            {
                a.LostFocus += (s, e) =>
                {
                    if (!string.IsNullOrEmpty(((TextBoxX)s).Text))
                    {
                        highlighter.SetHighlightColor(a, eHighlightColor.Green);
                    }
                };

            });
            return textBoxs;
        }

19 Source : DataBaseInfo.cs
with MIT License
from 2881099

public void Delete(Guid id)
        {
            var model = dataBases.Where(a => a.Id == id).FirstOrDefault();
            if (model != null)
            {
                dataBases.Remove(model);
                this.Save();
            }
        }

19 Source : DataBaseInfo.cs
with MIT License
from 2881099

public void Update()
        {
            var model = dataBases.Where(a => a.Id == this.Id).FirstOrDefault();
            if (model != null)
            {
                this.Id = model.Id;
                this.UserId = model.UserId;
                this.Pwd = model.Pwd;
                this.Host = model.Host;
                this.Port = model.Port;
                this.DbName = model.DbName;
                this.Save();
            }
        }

19 Source : InternalExtensions.cs
with MIT License
from 2881099

public static string GetDescription(this Type that)
    {
        object[] attrs = null;
        try
        {
            attrs = that.GetCustomAttributes(false).ToArray(); //.net core 反射存在版本冲突问题,导致该方法异常
        }
        catch { }

        var dyattr = attrs?.Where(a => {
            return ((a as Attribute)?.TypeId as Type)?.Name == "DescriptionAttribute";
        }).FirstOrDefault();
        if (dyattr != null)
        {
            var valueProp = dyattr.GetType().GetProperties().Where(a => a.PropertyType == typeof(string)).FirstOrDefault();
            var comment = valueProp?.GetValue(dyattr, null)?.ToString();
            if (string.IsNullOrEmpty(comment) == false)
                return comment;
        }
        return null;
    }

19 Source : Utils.cs
with MIT License
from 2881099

public static MethodInfo GetLinqContains(Type genericType) {
			return _dicGetLinqContains.GetOrAdd(genericType, gt => {
				var methods = _dicMethods.GetOrAdd(typeof(Enumerable), gt2 => gt2.GetMethods());
				var method = methods.Where(a => a.Name == "Contains" && a.GetParameters().Length == 2).FirstOrDefault();
				return method?.MakeGenericMethod(gt);
			});
		}

19 Source : DbContext.cs
with MIT License
from 2881099

internal void InitPropSets() {
			var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp => 
				tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
					.Where(a => a.PropertyType.IsGenericType &&
						a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GenericTypeArguments[0])).ToArray());

			foreach (var prop in props) {
				var set = this.Set(prop.PropertyType.GenericTypeArguments[0]);

				prop.SetValue(this, set);
				AllSets.Add(prop.Name, set);
			}
		}

19 Source : DynamicProxyMeta.cs
with MIT License
from 2881099

public static void SetPropertyValue(Type sourceType, object source, string propertyOrField, object value)
        {
            if (source == null) return;
            if (sourceType == null) sourceType = source.GetType();
            _dicSetEnreplacedyValueWithPropertyName
                .GetOrAdd(sourceType, et => new ConcurrentDictionary<string, Action<object, string, object>>())
                .GetOrAdd(propertyOrField, pf =>
                {
                    var t = sourceType;
                    var parm1 = Expression.Parameter(typeof(object));
                    var parm2 = Expression.Parameter(typeof(string));
                    var parm3 = Expression.Parameter(typeof(object));
                    var var1Parm = Expression.Variable(t);
                    var exps = new List<Expression>(new Expression[] {
                        Expression.replacedign(var1Parm, Expression.TypeAs(parm1, t))
                    });
                    var memberInfos = t.GetMember(pf, BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.MemberType == MemberTypes.Field || a.MemberType == MemberTypes.Property);
                    foreach (var memberInfo in memberInfos) {
                        exps.Add(
                            Expression.replacedign(
                                Expression.MakeMemberAccess(var1Parm, memberInfo),
                                Expression.Convert(
                                    parm3,
                                    memberInfo.MemberType == MemberTypes.Field ? (memberInfo as FieldInfo)?.FieldType : (memberInfo as PropertyInfo)?.PropertyType
                                )
                            )
                        );
                    }
                    return Expression.Lambda<Action<object, string, object>>(Expression.Block(new[] { var1Parm }, exps), new[] { parm1, parm2, parm3 }).Compile();
                })(source, propertyOrField, value);
        }

19 Source : PrivoxyHandler.cs
with GNU General Public License v3.0
from 2dust

public void Stop()
        {
            if (_process != null)
            {
                KillProcess(_process);
                _process.Dispose();
                _process = null;
                RunningPort = 0;
            }
            else
            {
                Process[] existingPrivoxy = Process.GetProcessesByName(_privoxyName);
                foreach (Process p in existingPrivoxy.Where(IsChildProcess))
                {
                    KillProcess(p);
                }
            }
        }

19 Source : Function.cs
with GNU Affero General Public License v3.0
from 3CORESec

private void initConfig()
        {
            _alerts = new List<ISender>();
            config = JsonConvert.DeserializeObject<Config>(File.ReadAllText("config.json"));
            if (string.IsNullOrEmpty(config.SlackPath))
                config.SlackPath = Environment.GetEnvironmentVariable("SLACKPATH");
            if (string.IsNullOrEmpty(config.WebhookChannel))
                config.WebhookChannel = Environment.GetEnvironmentVariable("WEBHOOKCHANNEL");
            if (string.IsNullOrEmpty(config.WebHookToken))
                config.WebHookToken = Environment.GetEnvironmentVariable("WEBHOOKTOKEN");
            if (string.IsNullOrEmpty(config.PostUrl))
                config.PostUrl = Environment.GetEnvironmentVariable("POSTURL");
            var type = typeof(ISender);
            var types = AppDomain.CurrentDomain.Getreplacedemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsreplacedignableFrom(p) && !p.IsInterface && !p.IsAbstract);
            types.ToList().ForEach(type => {
                ConstructorInfo ctor = type.GetConstructor(new[] { typeof(Storage<SessionLog>), typeof(Config), typeof(IMemoryCache) });
                ISender instance = ctor.Invoke(new object[] { _storage, config, memoryCache }) as ISender;
                _alerts.Add(instance);
            });
        }

19 Source : SlnWriter.cs
with MIT License
from 3F

protected void Validate(IEnumerable<ISection> sections)
        {
            var coh = GetSlnHandlers(sections)
                        .Where(s => s.CoHandlers != null && s.CoHandlers.Count > 0)
                        .ToDictionary(key => key.GetType(), value => value.CoHandlers);

            foreach(var h in Handlers)
            {
                if(coh.ContainsKey(h.Key))
                {
                    if(coh[h.Key].Except(Handlers.Keys).Count() != coh[h.Key].Count) {
                        throw new CoHandlerRuleException(
                            $"Only parent handler is allowed '{h.Key}' <- {String.Join(", ", coh[h.Key].Select(c => c.Name))}"
                        );
                    }
                    continue;
                }

                if(coh.Where(v => v.Value.Contains(h.Key))
                        .Select(v => v.Key)
                        .Except(Handlers.Keys).Count() > 0)
                {
                    throw new CoHandlerRuleException($"Define parent handler instead of '{h.Key}'.");
                }
            }
        }

19 Source : SlnWriter.cs
with MIT License
from 3F

protected HashSet<ISlnHandler> GetSlnHandlers(IEnumerable<ISection> sections)
        {
            //var sh = sections.Where(s => s.Handler is ISlnHandler)
            //                 .GroupBy(s => s.Handler).Select(s => s.Key);

            var sh = new HashSet<ISlnHandler>();
            sections.Where(s => s.Handler is ISlnHandler)
                    .ForEach(s => sh.Add((ISlnHandler)s.Handler));

            return sh;
        }

19 Source : SlnWriter.cs
with MIT License
from 3F

protected IEnumerable<ISection> WritableSections(IEnumerable<ISection> sections)
        {
            var ret     = new List<ISection>();
            var hTypes  = new HashSet<Type>();

            foreach(var part in sections.Where(s => !s.Ignore))
            {
                if(part.Handler == null) {
                    ret.Add(part);
                    continue;
                }

                if(part.Handler is ISlnHandler sh) {
                    sh.CoHandlers?.ForEach(h => hTypes.Add(h));
                }

                var type = part.Handler.GetType();

                if(hTypes.Contains(type)) {
                    continue;
                }

                if(Handlers.ContainsKey(type)) {
                    hTypes.Add(type);
                }
                ret.Add(part);
            }

            return ret;
        }

19 Source : XProject.cs
with MIT License
from 3F

public IEnumerable<ImportElement> GetImports(string project, string label, bool eq = false)
        {
            var ret = GetImports();
            var cmp = StringComparison.InvariantCultureIgnoreCase;

            if(project != null) {
                if(eq) {
                    ret = ret.Where(i => project.Equals(i.project, cmp));
                }
                else {
                    ret = ret.Where(i => i.project != null && i.project.EndsWith(project, cmp));
                }
            }

            if(label != null) {
                ret = ret.Where(i => label.Equals(i.label, cmp));
            }

            return ret;
        }

19 Source : XProjectEnv.cs
with MIT License
from 3F

public IXProject[] XProjectsByGuid(string guid)
        {
            return Projects?.Where(p => p.ProjectGuid == guid).ToArray();
        }

19 Source : XProjectEnv.cs
with MIT License
from 3F

public IEnumerable<IXProject> XProjectsByFile(string file)
        {
            return Projects?.Where(p => p.ProjectFullPath == file);
        }

19 Source : XProjectEnv.cs
with MIT License
from 3F

public IXProject[] XProjectsByName(string name, IConfPlatform cfg)
        {
            return Projects?.Where(
                p => Eq(p.Projecreplacedem.projectConfig, cfg) && p.ProjectName == name
            )
            .ToArray();
        }

19 Source : XProjectEnv.cs
with MIT License
from 3F

public IXProject[] XProjectsByName(string name)
        {
            return Projects?.Where(p => p.ProjectName == name).ToArray();
        }

19 Source : CheckCreateFile.cs
with MIT License
from 3RD-Dimension

public static void CheckAndUpdateXMLFile(int CurrentKeyFileVersion)
        {
            MainWindow.Logger.Info($"Updating HotkeyXML File. Current File Version {CurrentKeyFileVersion}, Update to File Version {HotKeyFileVer}");
            // Define new Hotkey fields - This changes every program update if needed   
            var UpdateHotkey = XDoreplacedent.Load(HotKeyFile);

            // NOTES | Sample Code for Add, Add at position, Rename:
            // Add to end of file: xDoc.Root.Add(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Add to specific Location: xDoc.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase"), new XAttribute("keyfunction", "JDistInc"), new XAttribute("keycode", "")));
            // Rename Hotkey Data
            //var hotKeyRename1 = xDoc.Descendants("bind").Where(arg => arg.Attribute("key_description").Value == "Feed Rate Increase").Single();
            //hotKeyRename1.Attribute("key_description").Value = "Feed Rate Increase X";

            // START FILE MANIPULATION
            // Insert at specific Location - Reverse Order - Bottom will be inserted at the top
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Z"), new XAttribute("keyfunction", "JDistDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Z"), new XAttribute("keyfunction", "JDistIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease Y"), new XAttribute("keyfunction", "JDistDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase Y"), new XAttribute("keyfunction", "JDistIncY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Decrease X"), new XAttribute("keyfunction", "JDistDecX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Distance Increase X"), new XAttribute("keyfunction", "JDistIncX"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Z"), new XAttribute("keyfunction", "JRateDecZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Z"), new XAttribute("keyfunction", "JRateIncZ"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Decrease Y"), new XAttribute("keyfunction", "JRateDecY"), new XAttribute("keycode", "")));
            UpdateHotkey.Element("Hotkeys").Elements("bind").ElementAt(15).AddAfterSelf(new XElement("bind", new XAttribute("key_description", "Jog Rate Increase Y"), new XAttribute("keyfunction", "JRateIncY"), new XAttribute("keycode", "")));

            // Change Hotkey Desciptions and Keyfunction Name
            var hotKeyRename1 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateInc").Single();
            var hotKeyRename2 = UpdateHotkey.Descendants("bind").Where(arg => arg.Attribute("keyfunction").Value == "JRateDec").Single();
            hotKeyRename1.Attribute("key_description").Value = "Jog Rate Increase X";
            hotKeyRename1.Attribute("keyfunction").Value = "JRateIncX";
            hotKeyRename2.Attribute("key_description").Value = "Jog Rate Decrease X";
            hotKeyRename2.Attribute("keyfunction").Value = "JRateDecX";

            // END FILE MANIPULATION
            UpdateHotkey.Root.Attribute("HotkeyFileVer").Value = HotKeyFileVer.ToString(); // Change HotkeyFileVer to current version

            //And save the XML file
            UpdateHotkey.Save(HotKeyFile);

            // Re-load Hotkeys
            HotKeys.LoadHotKeys();
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 3xpl01tc0d3r

public static byte[] StringToByteArray(string hex)
        {
            return Enumerable.Range(0, hex.Length)
                             .Where(x => x % 2 == 0)
                             .Select(x => Convert.ToByte(hex.Substring(x, 2), 16))
                             .ToArray();
        }

19 Source : TypeFuzzer.cs
with Apache License 2.0
from 42skillz

private T InstantiateAndFuzzViaPropertiesWhenTheyHaveSetters<T>(ConstructorInfo constructor, int recursionLevel,
            Type genericType, object instance = null)
        {
            if (instance == null)
            {
                instance = constructor.Invoke(new object[0]);
            }

            var propertyInfos = genericType.GetProperties().Where(prop => prop.CanWrite);
            foreach (var propertyInfo in propertyInfos)
            {
                var propertyType = propertyInfo.PropertyType;
                var propertyValue = FuzzAnyDotNetType(Type.GetTypeCode(propertyType), propertyType, recursionLevel);

                propertyInfo.SetValue(instance, propertyValue);
            }

            return (T)instance;
        }

19 Source : Tlv.cs
with MIT License
from 499116344

private static byte[] GetBytes(string hexString)
        {
            return Enumerable
                .Range(0, hexString.Length)
                .Where(x => x % 2 == 0)
                .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16))
                .ToArray();
        }

19 Source : GeographyExpert.cs
with Apache License 2.0
from 42skillz

public static string[] GiveMeCitiesOf(Country country)
        {
            return CitiesOfTheWorld
                .Where(cw => cw.Country == country)
                .Select(x => x.CityName)
                .Distinct()
                .ToArray();
        }

19 Source : GeographyExpert.cs
with Apache License 2.0
from 42skillz

public static StateProvinceArea[] GiveMeStateProvinceAreaOf(Country country)
        {
            return CitiesOfTheWorld
                .Where(cw => cw.Country == country)
                .Select(x => x.StateProvinceArea)
                .Distinct()
                .ToArray();
        }

19 Source : SeatCollectionExtensions.cs
with Apache License 2.0
from 42skillz

public static IEnumerable<Seat> SelectAvailableSeatsCompliant(this IEnumerable<Seat> seats, PricingCategory pricingCategory)
        {
            return seats.Where(s => s.IsAvailable() && s.MatchCategory(pricingCategory));
        }

19 Source : SeatCollectionExtensions.cs
with Apache License 2.0
from 42skillz

public static IEnumerable<AdjacentSeats> SelectAdjacentSeats(this IEnumerable<Seat> seats, PartyRequested partyRequested)
        {
            var adjacentSeatsGroups = new List<AdjacentSeats>();
            var adjacentSeats = new List<Seat>();

            if (partyRequested.PartySize == 1)
            {
                return seats.Select(s => new AdjacentSeats(new List<Seat> {s}));
            }

            foreach (var candidateSeat in seats.OrderBy(s => s.DistanceFromRowCentroid))
            {
                if (!adjacentSeats.Any())
                {
                    adjacentSeats.Add(candidateSeat);
                    continue;
                }

                adjacentSeats = adjacentSeats.OrderBy(s => s.Number).ToList();

                if (DoesNotExceedPartyRequestedAndCandidateSeatIsAdjacent(candidateSeat, adjacentSeats, partyRequested))
                {
                    adjacentSeats.Add(candidateSeat);
                }
                else
                {
                    if (adjacentSeats.Any())
                    {
                        adjacentSeatsGroups.Add(new AdjacentSeats(adjacentSeats));
                    }

                    adjacentSeats = new List<Seat> {candidateSeat};
                }
            }

            return adjacentSeatsGroups.Where(adjacent => adjacent.Count() == partyRequested.PartySize);
        }

19 Source : BookListApplicationService.cs
with MIT License
from 52ABP

[AbpAuthorize(BookListPermissions.Create)]
        protected virtual async Task<BookListEditDto> Create(BookListEditDto input, List<long> bookIds)
        {
            //TODO:新增前的逻辑判断,是否允许新增

            // var enreplacedy = ObjectMapper.Map <BookList>(input);
            var enreplacedy = input.MapTo<BookList>();


            var enreplacedyId = await _enreplacedyRepository.InsertAndGetIdAsync(enreplacedy);

            if (bookIds != null)
            {
                bookIds = bookIds.Where(o => o > 0).ToList();
                await _bookListAndBookRelationshipManager.CreateRelationship(enreplacedy.Id, bookIds);
            }


            return enreplacedy.MapTo<BookListEditDto>();
        }

19 Source : BookListApplicationService.cs
with MIT License
from 52ABP

[AbpAuthorize(BookListPermissions.Edit)]
        protected virtual async Task Update(BookListEditDto input, List<long> bookIds)
        {
            //TODO:更新前的逻辑判断,是否允许更新

            var enreplacedy = await _enreplacedyRepository.GetAsync(input.Id.Value);
            input.MapTo(enreplacedy);

            // ObjectMapper.Map(input, enreplacedy);
            await _enreplacedyRepository.UpdateAsync(enreplacedy);


            if (bookIds != null)
            {
                bookIds = bookIds.Where(o => o > 0).ToList();
                await _bookListAndBookRelationshipManager.CreateRelationship(enreplacedy.Id, bookIds);
            }
        }

19 Source : BookApplicationService.cs
with MIT License
from 52ABP

[AbpAuthorize(BookPermissions.Create)]
        protected virtual async Task<BookEditDto> Create(BookEditDto input, List<long> tagIds)
        {
            //TODO:新增前的逻辑判断,是否允许新增

            // var enreplacedy = ObjectMapper.Map <Book>(input);
            var enreplacedy = input.MapTo<Book>();

            var enreplacedyId = await _enreplacedyRepository.InsertAndGetIdAsync(enreplacedy);

            // 创建标签关联
            if (tagIds != null)
            {
                // 过滤掉不符合条件的数据
                tagIds = tagIds.Where(o => o > 0).ToList();

                await _bookAndBookTagRelationshipManager.CreateRelationship(enreplacedy.Id, tagIds);
            }


            return enreplacedy.MapTo<BookEditDto>();
        }

19 Source : BookApplicationService.cs
with MIT License
from 52ABP

[AbpAuthorize(BookPermissions.Edit)]
        protected virtual async Task Update(BookEditDto input, List<long> tagIds)
        {
            //TODO:更新前的逻辑判断,是否允许更新

            var enreplacedy = await _enreplacedyRepository.GetAsync(input.Id.Value);
            input.MapTo(enreplacedy);

            // ObjectMapper.Map(input, enreplacedy);
            await _enreplacedyRepository.UpdateAsync(enreplacedy);

            // 创建标签关联
            if (tagIds != null)
            {
                // 过滤掉不符合条件的数据
                tagIds = tagIds.Where(o => o > 0).ToList();

                await _bookAndBookTagRelationshipManager.CreateRelationship(enreplacedy.Id, tagIds);
            }
        }

19 Source : UIImageAlphaMask.cs
with MIT License
from 49hack

private void Update()
	{
		if (!IsValid ()) {
			return;
		}

		if (m_TargetImageList == null || m_TargetImageList.Length <= 0) {
			m_TargetImageList = GetComponentsInChildren<Image> (true);
			m_TargetImageList = m_TargetImageList.Where (o => o.transform != this.transform).ToArray ();
			SetMaterial (m_TargetImageList, Material);
		}

		SetProperties ();
	}

19 Source : JSONParser.cs
with MIT License
from 5minlab

static object ParseObject(Type type, string json) {
            object instance = FormatterServices.GetUninitializedObject(type);

            //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON
            List<string> elems = Split(json);
            if (elems.Count % 2 != 0)
                return instance;

            Dictionary<string, FieldInfo> nameToField;
            Dictionary<string, PropertyInfo> nameToProperty;
            if (!fieldInfoCache.TryGetValue(type, out nameToField)) {
                nameToField = type.GetFields().Where(field => field.IsPublic).ToDictionary(field => field.Name);
                fieldInfoCache.Add(type, nameToField);
            }
            if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) {
                nameToProperty = type.GetProperties().ToDictionary(p => p.Name);
                propertyInfoCache.Add(type, nameToProperty);
            }

            for (int i = 0; i < elems.Count; i += 2) {
                if (elems[i].Length <= 2)
                    continue;
                string key = elems[i].Substring(1, elems[i].Length - 2);
                string value = elems[i + 1];

                FieldInfo fieldInfo;
                PropertyInfo propertyInfo;
                if (nameToField.TryGetValue(key, out fieldInfo))
                    fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value));
                else if (nameToProperty.TryGetValue(key, out propertyInfo))
                    propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null);
            }

            return instance;
        }

19 Source : SimpleJSON.cs
with MIT License
from 71

public override JSONNode Remove(JSONNode aNode)
        {
            try
            {
                var item = m_Dict.Where(k => k.Value == aNode).First();
                m_Dict.Remove(item.Key);
                return aNode;
            }
            catch
            {
                return null;
            }
        }

See More Examples