Here are the examples of the csharp api System.Func.Invoke(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1892 Examples
19
View Source File : MetroTextBox.cs
License : MIT License
Project Creator : 1217950746
License : MIT License
Project Creator : 1217950746
void ErrorCheck()
{
// if (PopupHint == null || PopupHint == "") { PopupHint = InputHint; }
if (ErrorCheckAction != null) { State = ErrorCheckAction(Text) ? "true" : "false"; }
}
19
View Source File : JsonContractResolver.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
var property = base.CreateProperty(member, memberSerialization);
property.PropertyName = propertyNameResolver(property.PropertyName);
return property;
}
19
View Source File : NormanAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public override IRedisSocket GetRedisSocket(CommandPacket cmd)
{
string[] poolkeys = null;
if (_redirectRule == null)
{
//crc16
var slots = cmd?._keyIndexes.Select(a => ClusterAdapter.GetClusterSlot(cmd._input[a].ToInvariantCultureToString())).Distinct().ToArray();
poolkeys = slots?.Select(a => _connectionStrings[a % _connectionStrings.Length]).Select(a => $"{a.Host}/{a.Database}").Distinct().ToArray();
}
else
{
poolkeys = cmd?._keyIndexes.Select(a => _redirectRule(cmd._input[a].ToInvariantCultureToString())).Distinct().ToArray();
}
if (poolkeys == null) poolkeys = new[] { $"{_connectionStrings[0].Host}/{_connectionStrings[0].Database}" };
if (poolkeys.Length > 1) throw new RedisClientException($"CROSSSLOT Keys in request don't hash to the same slot: {cmd}");
var poolkey = poolkeys?.FirstOrDefault() ?? $"{_connectionStrings[0].Host}/{_connectionStrings[0].Database}";
var pool = _ib.Get(poolkey);
var cli = pool.Get();
var rds = cli.Value.Adapter.GetRedisSocket(null);
var rdsproxy = DefaultRedisSocket.CreateTempProxy(rds, () => pool.Return(cli));
rdsproxy._poolkey = poolkey;
rdsproxy._pool = pool;
return rdsproxy;
}
19
View Source File : ClientSideCaching.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void After(InterceptorAfterEventArgs args)
{
switch (args.Command._command)
{
case "GET":
if (_iscached == false && args.Exception == null)
{
var getkey = args.Command.GetKey(0);
if (_cscc._options.KeyFilter?.Invoke(getkey) != false)
_cscc.SetCacheValue(args.Command._command, getkey, args.ValueType, args.Value);
}
break;
case "MGET":
if (_iscached == false && args.Exception == null)
{
if (args.Value is Array valueArr)
{
var valueArrElementType = args.ValueType.GetElementType();
var sourceArrLen = valueArr.Length;
for (var a = 0; a < sourceArrLen; a++)
{
var getkey = args.Command.GetKey(a);
if (_cscc._options.KeyFilter?.Invoke(getkey) != false)
_cscc.SetCacheValue("GET", getkey, valueArrElementType, valueArr.GetValue(a));
}
}
}
break;
default:
if (args.Command._keyIndexes.Any())
{
var cmdset = CommandSets.Get(args.Command._command);
if (cmdset != null &&
(cmdset.Flag & CommandSets.ServerFlag.write) == CommandSets.ServerFlag.write &&
(cmdset.Tag & CommandSets.ServerTag.write) == CommandSets.ServerTag.write &&
(cmdset.Tag & [email protected]) == [email protected])
{
_cscc.RemoveCache(args.Command._keyIndexes.Select((item, index) => args.Command.GetKey(index)).ToArray());
}
}
break;
}
}
19
View Source File : DbContextAsync.cs
License : MIT License
Project Creator : 2881099
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
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 : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static object FromObject(this Type targetType, object value, Encoding encoding = null)
{
if (targetType == typeof(object)) return value;
if (encoding == null) encoding = Encoding.UTF8;
var valueIsNull = value == null;
var valueType = valueIsNull ? typeof(string) : value.GetType();
if (valueType == targetType) return value;
if (valueType == typeof(byte[])) //byte[] -> guid
{
if (targetType == typeof(Guid))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? tryguid : Guid.Empty;
}
if (targetType == typeof(Guid?))
{
var bytes = value as byte[];
return Guid.TryParse(BitConverter.ToString(bytes, 0, Math.Min(bytes.Length, 36)).Replace("-", ""), out var tryguid) ? (Guid?)tryguid : null;
}
}
if (targetType == typeof(byte[])) //guid -> byte[]
{
if (valueIsNull) return null;
if (valueType == typeof(Guid) || valueType == typeof(Guid?))
{
var bytes = new byte[16];
var guidN = ((Guid)value).ToString("N");
for (var a = 0; a < guidN.Length; a += 2)
bytes[a / 2] = byte.Parse($"{guidN[a]}{guidN[a + 1]}", NumberStyles.HexNumber);
return bytes;
}
return encoding.GetBytes(value.ToInvariantCultureToString());
}
else if (targetType.IsArray)
{
if (value is Array valueArr)
{
var targetElementType = targetType.GetElementType();
var sourceArrLen = valueArr.Length;
var target = Array.CreateInstance(targetElementType, sourceArrLen);
for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueArr.GetValue(a), encoding), a);
return target;
}
//if (value is IList valueList)
//{
// var targetElementType = targetType.GetElementType();
// var sourceArrLen = valueList.Count;
// var target = Array.CreateInstance(targetElementType, sourceArrLen);
// for (var a = 0; a < sourceArrLen; a++) target.SetValue(targetElementType.FromObject(valueList[a], encoding), a);
// return target;
//}
}
var func = _dicFromObject.GetOrAdd(targetType, tt =>
{
if (tt == typeof(object)) return vs => vs;
if (tt == typeof(string)) return vs => vs;
if (tt == typeof(char[])) return vs => vs == null ? null : vs.ToCharArray();
if (tt == typeof(char)) return vs => vs == null ? default(char) : vs.ToCharArray(0, 1).FirstOrDefault();
if (tt == typeof(bool)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
}
return false;
};
if (tt == typeof(bool?)) return vs =>
{
if (vs == null) return false;
switch (vs.ToLower())
{
case "true":
case "1":
return true;
case "false":
case "0":
return false;
}
return null;
};
if (tt == typeof(byte)) return vs => vs == null ? 0 : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(byte?)) return vs => vs == null ? null : (byte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (byte?)tryval : null);
if (tt == typeof(decimal)) return vs => vs == null ? 0 : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(decimal?)) return vs => vs == null ? null : (decimal.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (decimal?)tryval : null);
if (tt == typeof(double)) return vs => vs == null ? 0 : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(double?)) return vs => vs == null ? null : (double.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (double?)tryval : null);
if (tt == typeof(float)) return vs => vs == null ? 0 : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(float?)) return vs => vs == null ? null : (float.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (float?)tryval : null);
if (tt == typeof(int)) return vs => vs == null ? 0 : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(int?)) return vs => vs == null ? null : (int.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (int?)tryval : null);
if (tt == typeof(long)) return vs => vs == null ? 0 : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(long?)) return vs => vs == null ? null : (long.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (long?)tryval : null);
if (tt == typeof(sbyte)) return vs => vs == null ? 0 : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(sbyte?)) return vs => vs == null ? null : (sbyte.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (sbyte?)tryval : null);
if (tt == typeof(short)) return vs => vs == null ? 0 : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(short?)) return vs => vs == null ? null : (short.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (short?)tryval : null);
if (tt == typeof(uint)) return vs => vs == null ? 0 : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(uint?)) return vs => vs == null ? null : (uint.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (uint?)tryval : null);
if (tt == typeof(ulong)) return vs => vs == null ? 0 : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ulong?)) return vs => vs == null ? null : (ulong.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ulong?)tryval : null);
if (tt == typeof(ushort)) return vs => vs == null ? 0 : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(ushort?)) return vs => vs == null ? null : (ushort.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (ushort?)tryval : null);
if (tt == typeof(DateTime)) return vs => vs == null ? DateTime.MinValue : (DateTime.TryParse(vs, out var tryval) ? tryval : DateTime.MinValue);
if (tt == typeof(DateTime?)) return vs => vs == null ? null : (DateTime.TryParse(vs, out var tryval) ? (DateTime?)tryval : null);
if (tt == typeof(DateTimeOffset)) return vs => vs == null ? DateTimeOffset.MinValue : (DateTimeOffset.TryParse(vs, out var tryval) ? tryval : DateTimeOffset.MinValue);
if (tt == typeof(DateTimeOffset?)) return vs => vs == null ? null : (DateTimeOffset.TryParse(vs, out var tryval) ? (DateTimeOffset?)tryval : null);
if (tt == typeof(TimeSpan)) return vs => vs == null ? TimeSpan.Zero : (TimeSpan.TryParse(vs, out var tryval) ? tryval : TimeSpan.Zero);
if (tt == typeof(TimeSpan?)) return vs => vs == null ? null : (TimeSpan.TryParse(vs, out var tryval) ? (TimeSpan?)tryval : null);
if (tt == typeof(Guid)) return vs => vs == null ? Guid.Empty : (Guid.TryParse(vs, out var tryval) ? tryval : Guid.Empty);
if (tt == typeof(Guid?)) return vs => vs == null ? null : (Guid.TryParse(vs, out var tryval) ? (Guid?)tryval : null);
if (tt == typeof(BigInteger)) return vs => vs == null ? 0 : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? tryval : 0);
if (tt == typeof(BigInteger?)) return vs => vs == null ? null : (BigInteger.TryParse(vs, NumberStyles.Any, null, out var tryval) ? (BigInteger?)tryval : null);
if (tt.NullableTypeOrThis().IsEnum)
{
var tttype = tt.NullableTypeOrThis();
var ttdefval = tt.CreateInstanceGetDefaultValue();
return vs =>
{
if (string.IsNullOrWhiteSpace(vs)) return ttdefval;
return Enum.Parse(tttype, vs, true);
};
}
var localTargetType = targetType;
var localValueType = valueType;
return vs =>
{
if (vs == null) return null;
throw new NotSupportedException($"convert failed {localValueType.DisplayCsharp()} -> {localTargetType.DisplayCsharp()}");
};
});
var valueStr = valueIsNull ? null : (valueType == typeof(byte[]) ? encoding.GetString(value as byte[]) : value.ToInvariantCultureToString());
return func(valueStr);
}
19
View Source File : PanelChat.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public void Drow(Rect inRect)
{
var iconWidth = 25f;
var iconWidthSpase = 30f;
/// -----------------------------------------------------------------------------------------
/// Список каналов
///
if (SessionClientController.Data.Chats != null)
{
lock (SessionClientController.Data.Chats)
{
if (SessionClientController.Data.ChatNotReadPost > 0) SessionClientController.Data.ChatNotReadPost = 0;
//Loger.Log("Client " + SessionClientController.Data.Chats.Count);
if (lbCannalsHeight == 0)
{
var textHeight = new DialogControlBase().TextHeight;
lbCannalsHeight = (float)Math.Round((decimal)(inRect.height / 2f / textHeight)) * textHeight;
}
Widgets.Label(new Rect(inRect.x, inRect.y + iconWidthSpase + lbCannalsHeight, 100f, 22f), "OCity_Dialog_Players".Translate());
if (lbCannals == null)
{
//первый запуск
lbCannals = new ListBox<string>();
lbCannals.Area = new Rect(inRect.x
, inRect.y + iconWidthSpase
, 100f
, lbCannalsHeight);
lbCannals.OnClick += (index, text) => DataLastChatsTime = DateTime.MinValue; /*StatusTemp = text;*/
lbCannals.SelectedIndex = 0;
}
if (lbPlayers == null)
{
//первый запуск
lbPlayers = new ListBox<ListBoxPlayerItem>();
lbPlayers.OnClick += (index, item) =>
{
//убираем выделение
lbPlayers.SelectedIndex = -1;
//вызываем контекстное меню
PlayerItemMenu(item);
};
lbPlayers.Tooltip = (item) => item.Tooltip;
}
if (PanelLastHeight != inRect.height)
{
PanelLastHeight = inRect.height;
lbPlayers.Area = new Rect(inRect.x
, inRect.y + iconWidthSpase + lbCannalsHeight + 22f
, 100f
, inRect.height - (iconWidthSpase + lbCannalsHeight + 22f));
}
if (NeedUpdateChat)
{
lbCannalsLastSelectedIndex = -1;
NeedUpdateChat = false;
}
var nowUpdateChat = DataLastChatsTime != SessionClientController.Data.ChatsTime.Time;
if (nowUpdateChat)
{
Loger.Log("Client UpdateChats nowUpdateChat");
DataLastChatsTime = SessionClientController.Data.ChatsTime.Time;
lbCannalsLastSelectedIndex = -1; //сброс для обновления содержимого окна
NeedUpdateChat = true;
}
if (nowUpdateChat
|| DataLastChatsTimeUpdateTime < DateTime.UtcNow.AddSeconds(-5))
{
DataLastChatsTimeUpdateTime = DateTime.UtcNow;
//пишем в лог
var updateLogHash = SessionClientController.Data.Chats.Count * 1000000
+ SessionClientController.Data.Chats.Sum(c => c.Posts.Count);
if (updateLogHash != UpdateLogHash)
{
UpdateLogHash = updateLogHash;
Loger.Log("Client UpdateChats chats="
+ SessionClientController.Data.Chats.Count.ToString()
+ " players=" + SessionClientController.Data.Players.Count.ToString());
}
//устанавливаем данные
lbCannals.DataSource = SessionClientController.Data.Chats
//.OrderBy(c => (c.OwnerMaker ? "2" : "1") + c.Name) нелья просто отсортировать, т.к. потом находим по индексу
.Select(c => c.Name)
.ToList();
if (lbCannalsGoToChat != null)
{
var lbCannalsGoToChatIndex = lbCannals.DataSource.IndexOf(lbCannalsGoToChat);
if (lbCannalsGoToChatIndex >= 0)
{
lbCannals.SelectedIndex = lbCannalsGoToChatIndex;
lbCannalsGoToChat = null;
}
}
//Заполняем список игроков по группами {
lbPlayers.DataSource = new List<ListBoxPlayerItem>();
var allreadyLogin = new List<string>();
Func<string, string, ListBoxPlayerItem> addPl = (login, text) =>
{
allreadyLogin.Add(login);
var n = new ListBoxPlayerItem()
{
Login = login,
Text = text,
Tooltip = login
};
lbPlayers.DataSource.Add(n);
return n;
};
Action<string> addreplaced = (text) =>
{
if (lbPlayers.DataSource.Count > 0) addPl(null, " ").Groupreplacedle = true;
addPl(null, " <i>– " + text + " –</i> ").Groupreplacedle = true;
};
Func<string, bool> isOnline = (login) => login == SessionClientController.My.Login
|| SessionClientController.Data.Players.ContainsKey(login) && SessionClientController.Data.Players[login].Online;
Func<bool, string, string> frameOnline = (online, txt) =>
online
? "<b>" + txt + "</b>"
: "<color=#888888ff>" + txt + "</color>";
if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
{
var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex];
// в чате создатель
addreplaced("OCity_Dialog_Exchenge_Chat".Translate());
var n = addPl(selectCannal.OwnerLogin
, frameOnline(isOnline(selectCannal.OwnerLogin), "★ " + selectCannal.OwnerLogin));
n.Tooltip += "OCity_Dialog_ChennelOwn".Translate();
n.InChat = true;
// в чате
var offlinePartyLogin = new List<string>();
for (int i = 0; i < selectCannal.PartyLogin.Count; i++)
{
var lo = selectCannal.PartyLogin[i];
if (lo != "system" && lo != selectCannal.OwnerLogin)
{
if (isOnline(lo))
{
n = addPl(lo, frameOnline(true, lo));
n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
n.InChat = true;
}
else
offlinePartyLogin.Add(lo);
}
}
// в чате оффлайн
//addreplaced("оффлайн".Translate());
for (int i = 0; i < offlinePartyLogin.Count; i++)
{
var lo = offlinePartyLogin[i];
n = addPl(lo, frameOnline(false, lo));
n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
n.InChat = true;
}
}
var other = SessionClientController.Data.Chats[0].PartyLogin == null
? new List<string>()
: SessionClientController.Data.Chats[0].PartyLogin
.Where(p => p != "" && p != "system" && !allreadyLogin.Any(al => al == p))
.ToList();
if (other.Count > 0)
{
// игроки
addreplaced("OCity_Dialog_Exchenge_Gamers".Translate());
var offlinePartyLogin = new List<string>();
for (int i = 0; i < other.Count; i++)
{
var lo = other[i];
if (isOnline(lo))
{
var n = addPl(lo, frameOnline(true, lo));
//n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
}
else
offlinePartyLogin.Add(lo);
}
// игроки оффлайн
//addreplaced("оффлайн".Translate());
for (int i = 0; i < offlinePartyLogin.Count; i++)
{
var lo = offlinePartyLogin[i];
var n = addPl(lo, frameOnline(false, lo));
//n.Tooltip += "OCity_Dialog_ChennelUser".Translate();
}
}
}
lbCannals.Drow();
lbPlayers.Drow();
var iconRect = new Rect(inRect.x, inRect.y, iconWidth, iconWidth);
TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelCreate".Translate());
if (Widgets.ButtonImage(iconRect, GeneralTexture.IconAddTex))
{
CannalAdd();
}
if (lbCannals.SelectedIndex > 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
{
//Если что-то выделено, и это не общий чат (строка 0)
iconRect.x += iconWidthSpase;
TooltipHandler.TipRegion(iconRect, "OCity_Dialog_ChennelClose".Translate());
if (Widgets.ButtonImage(iconRect, GeneralTexture.IconDelTex))
{
CannalDelete();
}
}
if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
{
iconRect.x += iconWidthSpase;
TooltipHandler.TipRegion(iconRect, "OCity_Dialog_OthersFunctions".Translate());
if (Widgets.ButtonImage(iconRect, GeneralTexture.IconSubMenuTex))
{
CannalsMenuShow();
}
}
/// -----------------------------------------------------------------------------------------
/// Чат
///
if (lbCannalsLastSelectedIndex != lbCannals.SelectedIndex)
{
lbCannalsLastSelectedIndex = lbCannals.SelectedIndex;
if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
{
var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex];
if (selectCannal.Posts != null && selectCannal.Posts.Count > 0)
{
var chatLastPostTime = selectCannal.Posts.Max(p => p.Time);
if (ChatLastPostTime != chatLastPostTime)
{
ChatLastPostTime = chatLastPostTime;
Func<ChatPost, string> getPost = (cp) => "[" + cp.Time.ToGoodUtcString("dd HH:mm ") + cp.OwnerLogin + "]: " + cp.Message;
var totalLength = 0;
ChatBox.Text = selectCannal.Posts
.Reverse<ChatPost>()
.Where(i => (totalLength += i.Message.Length) < 5000)
.Aggregate("", (r, i) => getPost(i) + (r == "" ? "" : Environment.NewLine + r));
ChatScrollToDown = true;
}
//else ChatBox.Text = "";
}
//else ChatBox.Text = "";
}
else
ChatBox.Text = "";
}
if (lbCannals.SelectedIndex >= 0 && SessionClientController.Data.Chats.Count > lbCannals.SelectedIndex)
{
var selectCannal = SessionClientController.Data.Chats[lbCannals.SelectedIndex];
var chatAreaOuter = new Rect(inRect.x + 110f, inRect.y, inRect.width - 110f, inRect.height - 30f);
ChatBox.Drow(chatAreaOuter, ChatScrollToDown);
ChatScrollToDown = false;
var rrect = new Rect(inRect.x + inRect.width - 25f, inRect.y + inRect.height - 25f, 25f, 25f);
Text.Font = GameFont.Medium;
Text.Anchor = TextAnchor.MiddleCenter;
Widgets.Label(rrect, "▶");
Text.Font = GameFont.Small;
Text.Anchor = TextAnchor.MiddleLeft;
bool rrcklick = Widgets.ButtonInvisible(rrect);
if (ChatInputText != "")
{
if (Mouse.IsOver(rrect))
{
Widgets.DrawHighlight(rrect);
}
var ev = Event.current;
if (ev.isKey && ev.type == EventType.KeyDown && ev.keyCode == KeyCode.Return
|| rrcklick)
{
//SoundDefOf.RadioButtonClicked.PlayOneShotOnCamera();
SessionClientController.Command((connect) =>
{
connect.PostingChat(selectCannal.Id, ChatInputText);
});
ChatInputText = "";
}
}
GUI.SetNextControlName("StartTextField");
ChatInputText = GUI.TextField(new Rect(inRect.x + 110f, inRect.y + inRect.height - 25f, inRect.width - 110f - 30f, 25f)
, ChatInputText, 10000);
if (NeedFockus)
{
NeedFockus = false;
GUI.FocusControl("StartTextField");
}
}
}
}
}
19
View Source File : GameXMLUtils.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public static string ReplaceByTag(string xml, string tagName
, Func<string, string> getNewValue)
{
var tagNameB = "<" + tagName + ">";
int pos = xml.IndexOf(tagNameB);
if (pos < 0) return xml;
pos += tagNameB.Length;
var tagNameE = "</" + tagName + ">";
int posE = xml.IndexOf(tagNameE, pos);
if (posE < 0) return xml;
var newValue = getNewValue(xml.Substring(pos, posE - pos));
if (newValue == null) return xml;
return xml.Substring(0, pos) + newValue + xml.Substring(posE);
}
19
View Source File : EditingCommandHandler.cs
License : MIT License
Project Creator : Abdesol
License : MIT License
Project Creator : Abdesol
static void ConvertCase(Func<string, string> transformText, object target, ExecutedRoutedEventArgs args)
{
TransformSelectedSegments(
delegate (TextArea textArea, ISegment segment) {
string oldText = textArea.Doreplacedent.GetText(segment);
string newText = transformText(oldText);
textArea.Doreplacedent.Replace(segment.Offset, segment.Length, newText, OffsetChangeMappingType.CharacterReplace);
}, target, args, DefaultSegmentType.WholeDoreplacedent);
}
19
View Source File : HttpClientHelpers.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<HttpRequestMessage> CreateAsync(
HttpContext context,
HttpMethod method,
string url,
bool forwardUrlPars,
bool forwardHeaders,
// add new headers,
Func<string, (string Content, string ContentType)> changeBody = null
)
{
string finalUrl = forwardUrlPars ? url + context.Request.QueryString.ToUriComponent() : url;
var request = new HttpRequestMessage(method, finalUrl);
context.Request.QueryString.ToUriComponent();
if (forwardHeaders)
{
foreach (var requestHeader in context.Request.Headers)
{
if (requestHeader.Key.EqualsIC("Host")) continue;
request.Headers.TryAddWithoutValidation(requestHeader.Key, requestHeader.Value.AsEnumerable());
}
}
if (changeBody is null)
{
return request;
}
var body = new StreamReader(context.Request.Body);
//The modelbinder has already read the stream and need to reset the stream index
body.BaseStream.Seek(0, SeekOrigin.Begin);
var requestBody = await body.ReadToEndAsync();
var (content, type) = changeBody(requestBody);
request.Content = new StringContent(content);
request.Content.Headers.ContentType.MediaType = type;
return request;
}
19
View Source File : HttpClientHelpers.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<HttpRequestMessage> CreateAsync(
HttpMethod method,
string url,
bool forwardUrlPars,
bool forwardHeaders,
// add new headers,
Func<string, (string Content, string ContentType)> changeBody = null)
{
string finalUrl = forwardUrlPars ? url + _httpContext.Request.QueryString.ToUriComponent() : url;
var request = new HttpRequestMessage(method, finalUrl);
_httpContext.Request.QueryString.ToUriComponent();
if (forwardHeaders)
{
foreach (var requestHeader in _httpContext.Request.Headers)
{
if (requestHeader.Key.EqualsIC("Host")) continue;
request.Headers.TryAddWithoutValidation(requestHeader.Key, requestHeader.Value.AsEnumerable());
}
}
if (changeBody is null)
{
return request;
}
var body = new StreamReader(_httpContext.Request.Body);
//The modelbinder has already read the stream and need to reset the stream index
body.BaseStream.Seek(0, SeekOrigin.Begin);
var requestBody = await body.ReadToEndAsync();
var (content, type) = changeBody(requestBody);
request.Content = new StringContent(content);
request.Content.Headers.ContentType.MediaType = type;
return request;
}
19
View Source File : IOExtensions.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public static string GetUniqueLocalPath(this string @this, Func<string, bool> predicate = null)
{
if (predicate == null) predicate = File.Exists;
var directoryName = Path.GetDirectoryName(@this) ?? throw new InvalidOperationException();
var fileNameWithoutExtension = Path.GetFileNameWithoutExtension(@this) ?? throw new InvalidOperationException();
fileNameWithoutExtension = FileNameCountRegex.Replace(fileNameWithoutExtension, string.Empty).Trim();
var extension = Path.GetExtension(@this);
for (int i = 2; predicate(@this); i++)
{
@this = $"{Path.Combine(directoryName, fileNameWithoutExtension)} ({i}){extension}";
}
return @this;
}
19
View Source File : FileDownloaderBuilder.cs
License : MIT License
Project Creator : Accelerider
License : MIT License
Project Creator : Accelerider
public IDownloader Build()
{
var context = new DownloadContext(Guid.NewGuid())
{
RemotePathProvider = _remotePathProviderInterceptor(_remotePathProvider),
LocalPath = _localPathInterceptor(_localPath)
};
return InternalBuild(context, GetBlockTransferContextGenerator);
}
19
View Source File : ProjectFile.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
private void WriteFile<T>(Func<string, T> factory, Action<T> callback) where T : IDisposable
{
Directory.CreateDirectory(System.IO.Path.GetDirectoryName(Path));
Log.Verbose("Writing file: {Path}", Path);
using (var writer = factory(Path))
{
callback(writer);
}
_root.FileWritten(Path); // keeps track of files added or updated
}
19
View Source File : ProjectFolder.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
private void WriteFile<T>(string path, Func<string, T> factory, Action<T> callback) where T : IDisposable
{
var fullPath = GetFullPath(path);
Directory.CreateDirectory(Path.GetDirectoryName(fullPath));
if (Directory.Exists(fullPath))
{
Log.Verbose("Deleting directory at: {Path} as it conflicts with a new file to be created at the same location.", fullPath);
Directory.Delete(fullPath, recursive: true);
}
Log.Verbose("Writing file: {Path}", fullPath);
using (var writer = factory(fullPath))
{
callback(writer);
}
_root.FileWritten(fullPath); // keeps track of files added or updated
}
19
View Source File : Resources.cs
License : MIT License
Project Creator : action-bi-toolkit
License : MIT License
Project Creator : action-bi-toolkit
public static T GetEmbeddedResourceFromString<T>(string name, Func<string, T> transform, replacedembly replacedembly = null) =>
GetEmbeddedResource<T>(name, stream =>
{
using (var reader = new StreamReader(stream, Encoding.UTF8))
{
return transform(reader.ReadToEnd());
}
}, replacedembly ?? replacedembly.GetCallingreplacedembly());
19
View Source File : PromptManager.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public string ReadValue(
string argName,
string description,
bool secret,
string defaultValue,
Func<string, bool> validator,
bool unattended,
bool isOptional = false)
{
Trace.Info(nameof(ReadValue));
ArgUtil.NotNull(validator, nameof(validator));
string value = string.Empty;
// Check if unattended.
if (unattended)
{
// Return the default value if specified.
if (!string.IsNullOrEmpty(defaultValue))
{
return defaultValue;
}
else if (isOptional)
{
return string.Empty;
}
// Otherwise throw.
throw new Exception($"Invalid configuration provided for {argName}. Terminating unattended configuration.");
}
// Prompt until a valid value is read.
while (true)
{
// Write the message prompt.
_terminal.Write($"{description} ");
if(!string.IsNullOrEmpty(defaultValue))
{
_terminal.Write($"[press Enter for {defaultValue}] ");
}
else if (isOptional){
_terminal.Write($"[press Enter to skip] ");
}
// Read and trim the value.
value = secret ? _terminal.ReadSecret() : _terminal.ReadLine();
value = value?.Trim() ?? string.Empty;
// Return the default if not specified.
if (string.IsNullOrEmpty(value))
{
if (!string.IsNullOrEmpty(defaultValue))
{
Trace.Info($"Falling back to the default: '{defaultValue}'");
return defaultValue;
}
else if (isOptional)
{
return string.Empty;
}
}
// Return the value if it is not empty and it is valid.
// Otherwise try the loop again.
if (!string.IsNullOrEmpty(value))
{
if (validator(value))
{
return value;
}
else
{
Trace.Info("Invalid value.");
_terminal.WriteLine("Entered value is invalid", ConsoleColor.Yellow);
}
}
}
}
19
View Source File : CommandSettings.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private string GetArgOrPrompt(
string name,
string description,
string defaultValue,
Func<string, bool> validator,
bool isOptional = false)
{
// Check for the arg in the command line parser.
ArgUtil.NotNull(validator, nameof(validator));
string result = GetArg(name);
// Return the arg if it is not empty and is valid.
_trace.Info($"Arg '{name}': '{result}'");
if (!string.IsNullOrEmpty(result))
{
// After read the arg from input commandline args, remove it from Arg dictionary,
// This will help if bad arg value preplaceded through CommandLine arg, when ConfigurationManager ask CommandSetting the second time,
// It will prompt for input instead of continue use the bad input.
_trace.Info($"Remove {name} from Arg dictionary.");
RemoveArg(name);
if (validator(result))
{
return result;
}
_trace.Info("Arg is invalid.");
}
// Otherwise prompt for the arg.
return _promptManager.ReadValue(
argName: name,
description: description,
secret: Constants.Runner.CommandLine.Args.Secrets.Any(x => string.Equals(x, name, StringComparison.OrdinalIgnoreCase)),
defaultValue: defaultValue,
validator: validator,
unattended: Unattended,
isOptional: isOptional);
}
19
View Source File : RegexUtility.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static Boolean IsSafeMatch(
String value,
Func<String, Match> getSafeMatch)
{
Boolean result = true;
try
{
var match = getSafeMatch(value);
result = match.Success;
}
catch (Exception ex) when (ex is RegexMatchTimeoutException || ex is ArgumentException)
{
throw new RegularExpressionValidationFailureException(PipelineStrings.RegexFailed(value, ex.Message), ex);
}
return result;
}
19
View Source File : KXQueryConnection.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
public static void Subscribe(string host, int port, string trade, Func<string, Task> func)
{
c c = null;
try
{
c = new c(host == "" ? "localhost" : host, port == 0 ? 80 : port); // user:preplaced as parameter
c.k(trade == "" ? "sub[`trade;`MSFT.O`IBM.N]" : trade);
while (true)
{
object result = c.k();
c.Flip flip = c.td(result);
int nRows = c.n(flip.y[0]);
int nColumns = c.n(flip.x);
for (int row = 0; row < nRows; row++)
{
for (int column = 0; column < nColumns; column++)
// Define a delimiter within config.
func((column > 0 ? "," : "") + c.at(flip.y[column], row) + "\n"); // make use of function pointer in different framework (as these dont simultaneously exist in both frameworks), to make call for EventHub. Only parsing the message string {RAW}
System.Console.WriteLine();
}
}
}
finally
{
if (c != null) c.Close();
}
}
19
View Source File : KXQueryConnection.cs
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
License : BSD 3-Clause "New" or "Revised" License
Project Creator : ActuarialIntelligence
public static void Query(string host, int port, string CreateQuery, string ReturnQuery, Func<string, string> func)
{
c c = new c("localhost", 5000, @"AFRICA/rajiyer:UnicalcTensor1");
// c.ks("mytable:([]sym:10?`1;time:.z.p+til 10;price:10?100.;size:10?1000)"); // create example table using async msg (c.ks)
Object result = c.k("tab4"); // query the table using a sync msg (c.k)
// A flip is a table. A keyed table is a dictionary where the key and value are both flips.
c.Flip flip = c.td(result); // if the result set is a keyed table, this removes the key.
int nRows = c.n(flip.y[0]); // flip.y is an array of columns. Get the number of rows from the first column.
int nColumns = c.n(flip.x); // flip.x is an array of column names
Console.WriteLine("Number of columns: " + c.n(flip.x));
Console.WriteLine("Number of rows: " + nRows);
string csvMessage = "";
for (int column = 0; column < nColumns; column++)
System.Console.Write((column > 0 ? "," : "") + flip.x[column]);
for (int row = 0; row < nRows; row++)
{ // Define a Delimiter
for (int column = 0; column < nColumns; column++)
{
csvMessage += (column > 0 ? "," : "") + c.at(flip.y[column], row);
}
}
func(csvMessage);
System.Console.WriteLine("Sent Event: " + csvMessage);
c.Close();
}
19
View Source File : DelegatedOptionsMonitor.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public TOptions Get(string name) => _getCurrentValue(name ?? Options.DefaultName);
19
View Source File : DelegatedOptionsMonitor.cs
License : MIT License
Project Creator : adams85
License : MIT License
Project Creator : adams85
public void Reload(string name = null)
{
if (name == null)
name = Options.DefaultName;
_listeners?.Invoke(_getCurrentValue(name), name);
}
19
View Source File : AddShortcutPage.xaml.cs
License : MIT License
Project Creator : adenearnshaw
License : MIT License
Project Creator : adenearnshaw
private async void CreateNewShortcut(object sender, EventArgs args)
{
var icon = ResolveEmbeddedIcon(IconTypePicker.SelectedItem.ToString());
if (!string.IsNullOrWhiteSpace(CustomIconEntry.Text))
{
icon = new CustomIcon(CustomIconEntry.Text);
}
_shortcut.Label = replacedleEntry.Text;
_shortcut.Description = SubreplacedleEntry.Text;
_shortcut.Icon = icon;
_shortcut.Uri = $"stc://{nameof(AppShortcutsTests)}/{nameof(AddShortcutPage)}/{_shortcut.ShortcutId}";
await CrossAppShortcuts.Current.AddShortcut(_shortcut);
Navigation.PopAsync();
}
19
View Source File : Extensions.cs
License : BSD 2-Clause "Simplified" License
Project Creator : adospace
License : BSD 2-Clause "Simplified" License
Project Creator : adospace
public static T ElementValue<T>(this XElement element, string name, Func<string, T> parseFunc, T defaultValue = default(T))
{
var child = element.Element(name);
if (child != null)
return parseFunc(child.Value);
return defaultValue;
}
19
View Source File : AppShortcuts.ios.cs
License : MIT License
Project Creator : adenearnshaw
License : MIT License
Project Creator : adenearnshaw
public async Task<List<Shortcut>> GetShortcuts()
{
if (!_isShortcutsSupported)
throw new NotSupportedOnDeviceException(NOT_SUPPORTED_ERROR_MESSAGE);
var dynamicShortcuts = UIApplication.SharedApplication.Shortcureplacedems.ToList();
var shortcuts = dynamicShortcuts.Select(ds => new Shortcut(ds.Type)
{
Label = ds.Localizedreplacedle,
Description = ds.LocalizedSubreplacedle,
Uri = ds?.UserInfo[ArgumentsHelper.ShortcutUriKey]?.ToString() ?? string.Empty,
Icon = ResolveShortcutIconType(ds?.Icon?.ToString() ?? string.Empty)
}).ToList();
await Task.Delay(200);
return shortcuts;
}
19
View Source File : SqliteSyncProvider.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private async Task SetupTableForFullChangeDetection(SqliteSyncTable table, SqliteCommand cmd, CancellationToken cancellationToken = default)
{
var commandTextBase = new Func<string, string>((op) => [email protected]"CREATE TRIGGER IF NOT EXISTS [__{table.Name}_ct-{op}__]
AFTER {op} ON [{table.Name}]
FOR EACH ROW
BEGIN
INSERT INTO [__CORE_SYNC_CT] (TBL, OP, PK_{table.PrimaryColumnType}) VALUES ('{table.Name}', '{op[0]}', {(op == "DELETE" ? "OLD" : "NEW")}.[{table.PrimaryColumnName}]);
END");
cmd.CommandText = commandTextBase("INSERT");
await cmd.ExecuteNonQueryAsync(cancellationToken);
cmd.CommandText = commandTextBase("UPDATE");
await cmd.ExecuteNonQueryAsync(cancellationToken);
cmd.CommandText = commandTextBase("DELETE");
await cmd.ExecuteNonQueryAsync(cancellationToken);
}
19
View Source File : SqliteSyncProvider.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private async Task SetupTableForUpdatesOrDeletesOnly(SqliteSyncTable table, SqliteCommand cmd, CancellationToken cancellationToken = default)
{
var commandTextBase = new Func<string, string>((op) => [email protected]"CREATE TRIGGER IF NOT EXISTS [__{table.Name}_ct-{op}__]
AFTER {op} ON [{table.Name}]
FOR EACH ROW
BEGIN
INSERT INTO [__CORE_SYNC_CT] (TBL, OP, PK_{table.PrimaryColumnType}) VALUES ('{table.Name}', '{op[0]}', {(op == "DELETE" ? "OLD" : "NEW")}.[{table.PrimaryColumnName}]);
END");
cmd.CommandText = commandTextBase("UPDATE");
await cmd.ExecuteNonQueryAsync(cancellationToken);
cmd.CommandText = commandTextBase("DELETE");
await cmd.ExecuteNonQueryAsync(cancellationToken);
}
19
View Source File : SqliteSyncProvider.cs
License : MIT License
Project Creator : adospace
License : MIT License
Project Creator : adospace
private async Task DisableChangeTrackingForTable(SqliteCommand cmd, string tableName, CancellationToken cancellationToken)
{
var commandTextBase = new Func<string, string>((op) => [email protected]"DROP TRIGGER IF EXISTS [__{tableName}_ct-{op}__]");
cmd.CommandText = commandTextBase("INSERT");
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = commandTextBase("UPDATE");
await cmd.ExecuteNonQueryAsync();
cmd.CommandText = commandTextBase("DELETE");
await cmd.ExecuteNonQueryAsync();
}
19
View Source File : SiteMapNodeBlogDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static IBlogDataAdapter CreateBlogDataAdapter(
SiteMapNode node,
Func<Guid, IBlogDataAdapter> createAuthorArchiveAdapter,
Func<DateTime, DateTime, IBlogDataAdapter> createMonthArchiveAdapter,
Func<string, IBlogDataAdapter> createTagArchiveAdapter,
Func<IBlogDataAdapter> createDefaultAdapter)
{
Guid authorId;
if (BlogSiteMapProvider.TryGetAuthorArchiveNodeAttribute(node, out authorId))
{
return createAuthorArchiveAdapter(authorId);
}
DateTime monthArchiveDate;
if (BlogSiteMapProvider.TryGetMonthArchiveNodeAttribute(node, out monthArchiveDate))
{
return createMonthArchiveAdapter(monthArchiveDate.Date, monthArchiveDate.Date.AddMonths(1));
}
string tag;
if (BlogSiteMapProvider.TryGetTagArchiveNodeAttribute(node, out tag))
{
return createTagArchiveAdapter(tag);
}
return createDefaultAdapter();
}
19
View Source File : SettingDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private T SelectValue<T>(string settingName, Func<string, T> parse)
{
var setting = Select(settingName);
return setting == null ? default(T) : parse(setting.Value);
}
19
View Source File : RoleInstanceEndpointPortalSearchProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private TopPaginator<ICrmEnreplacedySearchResult>.Top GetTopSearchResults(int top, ICrmEnreplacedyQuery query, OrganizationServiceContext serviceContext, IPortalContext portal, Func<OrganizationServiceContext, Enreplacedy, bool> replacedertSecurity, IDependencyProvider dependencyProvider, Func<string, EnreplacedyMetadata> getEnreplacedyMetadata)
{
EnreplacedySearchResultPage searchResponse;
try
{
searchResponse = _service.Search(query.QueryText, 1, top, string.Join(",", query.LogicalNames.ToArray()), portal.Website.Id.ToString(), query.Filter);
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Service exception: {0}", e.ToString()));
throw;
}
if (searchResponse.IndexNotFound)
{
throw new IndexNotFoundException("Search index not found. Please ensure that the search index is constructed before attempting a query.");
}
var currentResultNumber = 0;
var items = searchResponse.Results.Select(result =>
{
var metadata = getEnreplacedyMetadata(result.EnreplacedyLogicalName);
if (metadata == null)
{
return null;
}
var enreplacedy = serviceContext.CreateQuery(metadata.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>(metadata.PrimaryIdAttribute) == result.EnreplacedyID);
if (enreplacedy == null)
{
return null;
}
if (!replacedertSecurity(serviceContext, enreplacedy))
{
return null;
}
var urlProvider = dependencyProvider.GetDependency<IEnreplacedyUrlProvider>();
var path = urlProvider.GetUrl(serviceContext, enreplacedy);
if (path == null)
{
return null;
}
Uri url;
if (!Uri.TryCreate(path, UriKind.RelativeOrAbsolute, out url))
{
return null;
}
currentResultNumber++;
return new CrmEnreplacedySearchResult(enreplacedy, result.Score, currentResultNumber, result.replacedle, url)
{
Fragment = result.Fragment
};
});
return new TopPaginator<ICrmEnreplacedySearchResult>.Top(items, searchResponse.ApproximateTotalHits);
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static T? GetAttribute<T>(this XElement element, XName name, Func<string, T> GetKeyByValue) where T : struct
{
var attribute = element.Attribute(name);
if (attribute != null)
{
return GetKeyByValue(attribute.Value);
}
return null;
}
19
View Source File : Extensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static T? GetAttribute<T>(this JToken element, string name, Func<string, T> GetKeyByValue) where T : struct
{
var attribute = element[name];
if (attribute != null)
{
return GetKeyByValue(attribute.Value<string>());
}
return null;
}
19
View Source File : NamedLock.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public T Get<T>(string key, int millisecondsTimeout, Func<string, object> loadFromCache, Func<string, T> loadFromService)
{
var obj = loadFromCache(key);
// first check
if (obj == null)
{
using (Lock(key, millisecondsTimeout))
{
// second check
obj = loadFromCache(key) ?? loadFromService(key);
}
}
return (T)obj;
}
19
View Source File : NamedLock.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public T Get<T>(string key, int millisecondsTimeout, Func<string, object> loadFromCache, Func<string, T> loadFromService, Action<string, T> addToCache)
{
return Get(key, millisecondsTimeout, loadFromCache,
k =>
{
var obj = loadFromService(k);
addToCache(k, obj);
return obj;
});
}
19
View Source File : AdxCmsDataServiceProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static IEnumerable<Enreplacedy> GetChildEnreplacedies(OrganizationServiceContext context, Enreplacedy enreplacedy)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
if (enreplacedy == null)
{
throw new ArgumentNullException("enreplacedy");
}
if (enreplacedy.LogicalName == "adx_webpage")
{
Func<string, IEnumerable<Enreplacedy>> safeGetRelatedEnreplacedies = relationshipName =>
{
try
{
return enreplacedy.GetRelatedEnreplacedies(context, relationshipName);
}
catch
{
return new List<Enreplacedy>();
}
};
return context.GetChildPages(enreplacedy)
.Union(context.GetChildFiles(enreplacedy))
.Union(context.GetChildShortcuts(enreplacedy))
.Union(safeGetRelatedEnreplacedies("adx_webpage_event"))
.Union(safeGetRelatedEnreplacedies("adx_webpage_communityforum"))
.Union(safeGetRelatedEnreplacedies("adx_webpage_survey"));
}
return new List<Enreplacedy>();
}
19
View Source File : TagCloud.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public override void InstantiateIn(Control container)
{
var item = new HtmlGenericControl("li");
container.Controls.Add(item);
var tagHyperLink = new HyperLink();
tagHyperLink.DataBinding += OnDataBinding<HyperLink>((hyperLink, eval) =>
{
var tagName = eval("Name") as string;
if (string.IsNullOrEmpty(tagName))
{
hyperLink.NavigateUrl = TagNavigateUrl;
return;
}
hyperLink.CssClreplaced = "tag {0}".FormatWith(eval("CssClreplaced"));
hyperLink.Text = tagName;
hyperLink.NavigateUrl = BuildNavigateUrl(tagName);
});
item.Controls.Add(tagHyperLink);
item.Controls.Add(new HtmlGenericControl("span") { InnerHtml = " " });
}
19
View Source File : LockProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual T Get<T>(string key, int millisecondsTimeout, Func<string, object> loadFromCache, Func<string, T> loadFromService)
{
var obj = loadFromCache(key);
// first check
if (obj == null)
{
Lock(
key,
millisecondsTimeout,
() =>
{
// second check
var value = loadFromCache(key) ?? loadFromService(key);
Thread.MemoryBarrier();
obj = value;
});
}
return (T)obj;
}
19
View Source File : MutexExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static T Get<T>(string key, int millisecondsTimeout, Func<string, object> loadFromCache, Func<string, T> loadFromService)
{
var obj = loadFromCache(key);
// first check
if (obj == null)
{
Lock(
key,
millisecondsTimeout,
_ =>
{
// second check
var value = loadFromCache(key) ?? loadFromService(key);
Thread.MemoryBarrier();
obj = value;
});
}
return (T)obj;
}
19
View Source File : MutexExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static T Get<T>(string key, int millisecondsTimeout, Func<string, object> loadFromCache, Func<string, T> loadFromService, Action<string, T> addToCache)
{
return Get(key, millisecondsTimeout, loadFromCache,
k =>
{
var obj = loadFromService(k);
addToCache(k, obj);
return obj;
});
}
19
View Source File : WSFederationAuthenticationModuleExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public static SessionSecurityToken GetSessionSecurityToken(
this WSFederationAuthenticationModule fam,
HttpContext context,
out string idenreplacedyProvider,
out string userName,
out string email,
out string displayName,
string emailClaimType = DefaultEmailClaimType,
string displayNameClaimType = DefaultDisplayNameClaimType,
string idenreplacedyProviderClaimType = DefaultIdenreplacedyProviderClaimType)
{
var principal = fam.GetClaimsPrincipal(context);
var sessionSecurityToken = new SessionSecurityToken(principal);
userName = principal.Idenreplacedy.Name;
Func<string, string> find = claimType => !string.IsNullOrWhiteSpace(claimType)
? principal.Idenreplacedies
.SelectMany(idenreplacedy => idenreplacedy.Claims)
.Where(claim => string.Equals(claim.ClaimType, claimType, StringComparison.OrdinalIgnoreCase))
.Select(claim => claim.Value)
.FirstOrDefault()
: null;
idenreplacedyProvider = find(idenreplacedyProviderClaimType);
email = find(emailClaimType);
displayName = find(displayNameClaimType);
return sessionSecurityToken;
}
19
View Source File : WSFederationAuthenticationModuleExtensions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private static IEnumerable<KeyValuePair<string, string>> GetParameters(
this WSFederationMessage message,
Func<string, bool> compare)
{
return message.Parameters.Where(parameter => compare(parameter.Key));
}
19
View Source File : LockProvider.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual T Get<T>(string key, int millisecondsTimeout, Func<string, object> loadFromCache, Func<string, T> loadFromService, Action<string, T> addToCache)
{
return Get(key, millisecondsTimeout, loadFromCache,
k =>
{
var obj = loadFromService(k);
addToCache(k, obj);
return obj;
});
}
19
View Source File : StringUtilities.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
public static string TransformIf(this string text, bool condition, Func<string, string> transformation)
=> condition ? transformation(text) : text;
19
View Source File : StringUtilities.cs
License : MIT License
Project Creator : AdrianWilczynski
License : MIT License
Project Creator : AdrianWilczynski
public static string TransformIfElse(this string text, bool condition, Func<string, string> transformationIf, Func<string, string> transformationElse)
=> condition ? transformationIf(text) : transformationElse(text);
19
View Source File : ConvertEditLinksFilter.cs
License : Apache License 2.0
Project Creator : advanced-cms
License : Apache License 2.0
Project Creator : advanced-cms
public void Flush(bool rewriteText)
{
var bufferedText = stringBuilder.ToString();
if (rewriteText && textRewriteFunction != null)
{
bufferedText = textRewriteFunction.Invoke(bufferedText);
}
InnerTextWriter.Write(bufferedText);
InnerTextWriter.Flush();
}
19
View Source File : FormConvert.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
public int ToInteger(string name,Func<string,string> procFunc)
{
var str = GetValue(name);
if (string.IsNullOrWhiteSpace(str))
{
return 0;
}
str = procFunc(str);
int vl;
if (!int.TryParse(str, out vl))
{
AddMessage(name, "值无法转为数字");
Failed = true;
return 0;
}
return vl;
}
19
View Source File : MyPageBase.cs
License : Mozilla Public License 2.0
Project Creator : agebullhu
License : Mozilla Public License 2.0
Project Creator : agebullhu
protected T GetArg<T>(string name, Func<string, T> convert, T def)
{
var value = GetArgValue(name);
if (string.IsNullOrEmpty(value) || value == "undefined" || value == "null")
{
return def;
}
return convert(value);
}
See More Examples