Here are the examples of the csharp api System.Guid.TryParse(string, out System.Guid) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
1157 Examples
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override ExprLiteral FromString(string? value) =>
value == null
? throw new SqExpressException($"Value cannot be null for '{this.ColumnName.Name}' non nullable column")
: Guid.TryParse(value, out var result)
? SqQueryBuilder.Literal(result)
: throw new SqExpressException($"Could not parse '{value}' as GUID for column '{this.ColumnName.Name}'.");
19
View Source File : TableColumn.Types.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public override ExprLiteral FromString(string? value) =>
value == null
? SqQueryBuilder.Literal((Guid?)null)
: Guid.TryParse(value, out var result)
? SqQueryBuilder.Literal(result)
: throw new SqExpressException($"Could not parse '{value}' as GUID for column '{this.ColumnName.Name}'.");
19
View Source File : CommonExtensions.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public static Guid ToGuid(this string s)
{
if (s.NotNull() && Guid.TryParse(s, out Guid val))
return val;
return Guid.Empty;
}
19
View Source File : RedisClient.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
{
if (valueRaw == null) return default(T);
var type = typeof(T);
var typename = type.ToString().TrimEnd(']');
if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
if (valueRaw.Length == 0) return default(T);
string valueStr = null;
if (type.IsValueType)
{
valueStr = encoding.GetString(valueRaw);
bool isNullable = typename.StartsWith("System.Nullable`1[");
var basename = isNullable ? typename.Substring(18) : typename;
bool isElse = false;
object obj = null;
switch (basename)
{
case "System.Boolean":
if (valueStr == "1") obj = true;
else if (valueStr == "0") obj = false;
break;
case "System.Byte":
if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
break;
case "System.Char":
if (valueStr.Length > 0) obj = valueStr[0];
break;
case "System.Decimal":
if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
break;
case "System.Double":
if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
break;
case "System.Single":
if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
break;
case "System.Int32":
if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
break;
case "System.Int64":
if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
break;
case "System.SByte":
if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
break;
case "System.Int16":
if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
break;
case "System.UInt32":
if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
break;
case "System.UInt64":
if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
break;
case "System.UInt16":
if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
break;
case "System.DateTime":
if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
break;
case "System.DateTimeOffset":
if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
break;
case "System.TimeSpan":
if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
break;
case "System.Guid":
if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
break;
default:
isElse = true;
break;
}
if (isElse == false)
{
if (obj == null) return default(T);
return (T)obj;
}
}
if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));
if (valueStr == null) valueStr = encoding.GetString(valueRaw);
if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
return valueStr.ConvertTo<T>();
}
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 : editCode.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
protected override void OnLoad()
{
base.OnLoad();
var a= this.Url.IndexOf("=")+1;
Guid.TryParse(this.Url.Substring(a, 36), out id);
templates = Curd.Templates.Select.WhereDynamic(id).ToOne();
}
19
View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public async Task CodeGenerate(string id)
{
if (stateKeyValues.ContainsKey(id))
{
InvokeJS("Helper.ui.message.error('当前任务未结束,请稍后再试.');");
}
else
{
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
stateKeyValues.Add(id, true);
var model = Curd.TaskBuild.Select.WhereDynamic(gid)
.LeftJoin(a => a.Templates.Id == a.TemplatesId)
.IncludeMany(a => a.TaskBuildInfos, b => b.Include(p => p.DataBaseConfig))
.ToOne();
var res = await new CodeGenerate().Setup(model);
InvokeJS($"Helper.ui.message.info('[{model.TaskName}]{res}');");
stateKeyValues.Remove(id);
}
else
{
InvokeJS("Helper.ui.alert.error('生成失败','参数不是有效的.');");
}
}
}
19
View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public async Task CodeGenerates(string jsonStr)
{
var ids = Newtonsoft.Json.JsonConvert.DeserializeObject<string[]>(jsonStr);
foreach(var id in ids)
{
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
var model = Curd.TaskBuild.Select.WhereDynamic(gid)
.LeftJoin(a => a.Templates.Id == a.TemplatesId)
.IncludeMany(a => a.TaskBuildInfos, b => b.Include(p => p.DataBaseConfig))
.ToOne();
InvokeJS($"$('.helper-loading-text').text('正在生成[{model.TaskName}]请稍后....')");
await Task.Delay(500);
var res = await new CodeGenerate().Setup(model);
InvokeJS($"$('.helper-loading-text').text('[{model.TaskName}]{res}')");
if(res.Contains("发生异常")) await Task.Delay(3000);
}
else
{
InvokeJS("Helper.ui.alert.error('生成失败','参数不是有效的.');");
}
}
await Task.FromResult(0);
InvokeJS("Helper.ui.removeDialog();");
}
19
View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public string GetDataBase(string id, string tableName, int level)
{
DataBaseConfig model = null;
try
{
var data = new object();
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
model = Curd.DataBase.Select.WhereDynamic(gid).ToOne();
using (IFreeSql fsql = new FreeSql.FreeSqlBuilder().UseConnectionString(model.DataType,
model.ConnectionStrings).Build())
{
if (level == 0)
{
var res = fsql.DbFirst.GetDatabases();
if (!string.IsNullOrEmpty(model.DataBaseName))
{
res = res.Where(a => a.ToUpper() == model.DataBaseName.ToUpper()).ToList();
}
data = res.Select(a => new
{
id = gid,
name = a,
children = fsql.DbFirst.GetTablesByDatabase(a).Select(b => new
{
id = gid,
name = b.Name
}).ToList()
}).ToList();
}
else
{
var res = fsql.DbFirst.GetTablesByDatabase(tableName);
data = res.Select(a => new { name = a.Name }).ToList();
}
}
}
return JsonConvert.SerializeObject(new { code = 0, data });
}
catch (Exception e)
{
return JsonConvert.SerializeObject(new { code = 1, msg = e.Message + "<br/> 数据库连接串:" + model?.ConnectionStrings });
}
}
19
View Source File : TaskBuild.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public async Task delTaslBuild(string id)
{
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
Curd.TaskBuildInfo.Delete(a => a.TaskBuildId == gid);
Curd.TaskBuild.Delete(gid);
var _temp = Data.FirstOrDefault(a => a.Id == gid);
Data.Remove(_temp);
Data.SaveChanges();
InvokeJS("tableTaskBuild.bootstrapTable('load', page.Data);$('[data-toggle=\"tooltip\"]').tooltip();");
InvokeJS("Helper.ui.message.success('删除任务成功');");
await Task.FromResult(0);
}
}
19
View Source File : Template.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public async Task delTemplate(string id)
{
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
if(Curd.TaskBuild.Select.Any(a => a.TemplatesId == gid))
{
InvokeJS("Helper.ui.message.error('当前模板有任务构建,删除失败.');");
return;
}
Curd.Templates.Delete(gid);
var _temp = Data.FirstOrDefault(a => a.Id == gid);
Data.Remove(_temp);
Data.SaveChanges();
InvokeJS("departments.bootstrapTable('load', page.Data);$('[data-toggle=\"tooltip\"]').tooltip();");
InvokeJS("Helper.ui.message.success('删除数据库信息成功');");
await Task.FromResult(0);
}
}
19
View Source File : RazorModel.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public string GetColumnDefaultValue(DbColumnInfo col, bool isInsertValueSql)
{
var defval = col.DefaultValue?.Trim();
if (string.IsNullOrEmpty(defval)) return null;
var cstype = col.CsType.NullableTypeOrThis();
if (fsql.Ado.DataType == DataType.SqlServer || fsql.Ado.DataType == DataType.OdbcSqlServer)
{
if (defval.StartsWith("((") && defval.EndsWith("))")) defval = defval.Substring(2, defval.Length - 4);
else if (defval.StartsWith("('") && defval.EndsWith("')")) defval = defval.Substring(2, defval.Length - 4).Replace("''", "'");
else if(defval.StartsWith("(") && defval.EndsWith(")")) defval = defval.Substring(1, defval.Length - 2);
else return null;
}
else if ((cstype == typeof(string) && defval.StartsWith("'") && defval.EndsWith("'::character varying") ||
cstype == typeof(Guid) && defval.StartsWith("'") && defval.EndsWith("'::uuid")
) && (fsql.Ado.DataType == DataType.PostgreSQL || fsql.Ado.DataType == DataType.OdbcPostgreSQL ||
fsql.Ado.DataType == DataType.OdbcKingbaseES ||
fsql.Ado.DataType == DataType.ShenTong))
{
defval = defval.Substring(1, defval.LastIndexOf("'::") - 1).Replace("''", "'");
}
else if (defval.StartsWith("'") && defval.EndsWith("'"))
{
defval = defval.Substring(1, defval.Length - 2).Replace("''", "'");
if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql) defval = defval.Replace("\\\\", "\\");
}
if (cstype.IsNumberType() && decimal.TryParse(defval, out var trydec))
{
if (isInsertValueSql) return defval;
if (cstype == typeof(float)) return defval + "f";
if (cstype == typeof(double)) return defval + "d";
if (cstype == typeof(decimal)) return defval + "M";
return defval;
}
if (cstype == typeof(Guid) && Guid.TryParse(defval, out var tryguid)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"Guid.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(DateTime) && DateTime.TryParse(defval, out var trydt)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"DateTime.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(TimeSpan) && TimeSpan.TryParse(defval, out var tryts)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"TimeSpan.Parse(\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\")";
if (cstype == typeof(string)) return isInsertValueSql ? (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval) : $"\"{defval.Replace("\r\n", "\\r\\n").Replace("\"", "\\\"")}\"";
if (cstype == typeof(bool)) return isInsertValueSql ? defval : (defval == "1" || defval == "t" ? "true" : "false");
if (fsql.Ado.DataType == DataType.MySql || fsql.Ado.DataType == DataType.OdbcMySql)
if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
if (isInsertValueSql) return (fsql.Select<TestTb>() as Select0Provider)._commonUtils.FormatSql("{0}", defval);
return isInsertValueSql ? defval : null; //sql function or exp
}
19
View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public IEnumerable<Guid> GetClientListByOnline()
{
return _redis.HKeys($"{_redisPrefix}Online").Select(a => Guid.TryParse(a, out var tryguid) ? tryguid : Guid.Empty).Where(a => a != Guid.Empty);
}
19
View Source File : DbList.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public async Task TestDbconnection(string id)
{
await Task.Run(() =>
{
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
var enreplacedy = Curd.DataBase.Select.WhereDynamic(gid).ToOne();
try
{
using (var fsql = new FreeSql.FreeSqlBuilder()
.UseConnectionString(enreplacedy.DataType, enreplacedy.ConnectionStrings).Build())
{
Invoke(() =>
{
InvokeJS("Helper.ui.removeDialog();");
InvokeJS($"Helper.ui.dialogSuccess('提示','数据库连接成功');");
});
}
}
catch (Exception e)
{
Invoke(() =>
{
InvokeJS("Helper.ui.removeDialog();");
InvokeJS($"Helper.ui.dialogError('连接失败','{e.Message}');");
});
}
}
});
}
19
View Source File : DbList.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
[JSFunction]
public async Task delDataBase(string id)
{
if (Guid.TryParse(id, out Guid gid) && gid != Guid.Empty)
{
Curd.TaskBuildInfo.Delete(a => a.DataBaseConfigId == gid);
Curd.DataBase.Delete(gid);
var _temp = Data.FirstOrDefault(a => a.Id == gid);
Data.Remove(_temp);
Data.SaveChanges();
InvokeJS("departments.bootstrapTable('load', page.Data);$('[data-toggle=\"tooltip\"]').tooltip();");
InvokeJS("Helper.ui.message.success('删除数据库信息成功');");
await Task.FromResult(0);
}
}
19
View Source File : ImClient.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public void SendChanMessage(Guid senderClientId, string chan, object message)
{
var websocketIds = _redis.HKeys($"{_redisPrefix}Chan{chan}");
SendMessage(Guid.Empty, websocketIds.Where(a => !string.IsNullOrEmpty(a)).Select(a => Guid.TryParse(a, out var tryuuid) ? tryuuid : Guid.Empty).ToArray(), message);
}
19
View Source File : StringExtension.cs
License : MIT License
Project Creator : 3F
License : MIT License
Project Creator : 3F
public static Guid Guid(this string str)
{
if(System.Guid.TryParse(str, out Guid res)) {
return res;
}
if(str == null) {
str = String.Empty;
}
using(MD5 md5 = MD5.Create()) {
return new Guid(md5.ComputeHash(Encoding.UTF8.GetBytes(str)));
}
}
19
View Source File : StringExtension.cs
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
License : GNU Lesser General Public License v3.0
Project Creator : 8720826
public static Guid? ToGuid(this string str)
{
if (string.IsNullOrEmpty(str))
{
return null;
}
Guid id;
if (Guid.TryParse(str, out id))
{
return id;
}
return null;
}
19
View Source File : RegCommand.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
protected string CanExecute(SocketCommandContext context, string ip, string token, out IPEndPoint serverAdr)
{
// RU: Проверка на дурака: такой сервер не зарегистрирован, и сервер живой
// RU: Регистрируем сервер и сохраняем параметры: в виде таблицы: IDканала, IPserver
serverAdr = Helper.TryParseStringToIp(ip);
if (serverAdr == null)
{
return Languages.Translator.ErrInvalidIP;
}
if (_appContext.DiscrordToOCServer.TryGetValue(context.Channel.Id, out SessionClientWrapper server2Chanel))
{
if (!ip.Equals(server2Chanel.Chanel2Server.IP))
{
return Languages.Translator.ErrTryAddToExistChannel + $"{server2Chanel.Chanel2Server.IP}, Register on new discrord channel pls ";
}
else
{
// TO DO: if ip is eqauls,
return Languages.Translator.ErrTryAddToExistChannel + $"{server2Chanel.Chanel2Server.IP}, Register on new discrord channel pls ";
}
}
if (context.IsPrivate)
{
return Languages.Translator.InfResctrictInPrivate;
}
if (!Guid.TryParse(token, out Guid guidToken))
{
return Languages.Translator.ErrInvalidToken;
}
return string.Empty;
}
19
View Source File : RegisterUserCommand.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
public string Execute(SocketCommandContext context, string token)
{
if (!context.IsPrivate)
{
return Translator.InfResctrictInChannel;
}
if (!Guid.TryParse(token, out Guid guidToken))
{
return Translator.ErrInvalidToken;
}
//Check each Online City Server for this User
foreach (var ocServerKeyPair in _appContext.DiscrordToOCServer.Where(srv => srv.Value.IsLogined))
{
var ocServer = ocServerKeyPair.Value;
var player = ocServer.GetPlayerByToken(guidToken);
if (player != null)
{
OCUser user = _appContext.TryGetOCUser(ocServerKeyPair.Key, context.User.Id);
if (user != null)
{
return string.Format(Translator.ErrUserTokenExist, user.OCLogin, user.DiscordIdChanel);
}
user = new OCUser() { DiscordIdChanel = ocServerKeyPair.Key, LastActiveTime = player.LastOnlineTime, OCLogin = player.Login, UserId = context.Message.Author.Id };
_appContext.UserOnServers[ocServerKeyPair.Key][context.Message.Author.Id] = user;
_userRepository.AddNewItem(user);
// to do register user
return string.Format(Translator.InfUserFound, player.Login, ocServer.Chanel2Server.IP);
}
}
return "User not found or server is offline";
}
19
View Source File : BotRepositoryTests.cs
License : Apache License 2.0
Project Creator : AantCoder
License : Apache License 2.0
Project Creator : AantCoder
private void checkGetToken(string msg, int index)
{
var res = _sessionClient.PostingChat(1, msg);
replacedert.IsTrue(res.Status == 0);
var ic = new ModelUpdateTime();
var dc = _sessionClient.UpdateChat(ic);
replacedert.IsNotNull(dc);
replacedert.IsTrue(dc.Chats[0].OwnerLogin == userName);
var m = dc.Chats[0].Posts[index].Message;
var boolres = Guid.TryParse(m, out Guid guid);
replacedert.IsTrue(boolres);
}
19
View Source File : Uuid128.cs
License : MIT License
Project Creator : abdullin
License : MIT License
Project Creator : abdullin
public static bool TryParse(string input, out Uuid128 result)
{
Guid guid;
if (!Guid.TryParse(input, out guid))
{
result = default(Uuid128);
return false;
}
result = new Uuid128(guid);
return true;
}
19
View Source File : UserLoginInformationGetter.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public LoginInformationDto GetUserLoginInformation(string tokenId)
{
if (tokenId is null)
{
throw new ArgumentNullException(nameof(tokenId));
}
if (!Guid.TryParse(tokenId, out var guidTokenId))
{
throw new ArgumentException("Couldn't parse tokenId into Guid", nameof(tokenId));
}
var login = (from l in _loginRepository.Table
where l.LoginId == guidTokenId
orderby l.LoggedAt
descending
select new LoginInformationDto
{
UserId = l.UserId,
Username = l.User.UserName,
Email = l.User.Email,
LoggedAtUtc = l.LoggedAt,
TokenId = l.LoginId.ToString(),
Longitude = l.LoginLocation == null ? null as double? : l.LoginLocation.X,
Lareplacedude = l.LoginLocation == null ? null as double? : l.LoginLocation.Y
}).FirstOrDefault();
return login;
}
19
View Source File : CommentService.cs
License : MIT License
Project Creator : Abdulrhman5
License : MIT License
Project Creator : Abdulrhman5
public async Task<CommandResult> AuthorizedDeleteComment(DeleteCommentDto deleteCommentDto)
{
if (deleteCommentDto == null || deleteCommentDto.CommentId.IsNullOrEmpty())
{
return new CommandResult(new ErrorMessage
{
ErrorCode = "CATALOG.OBJECT.COMMENT.DELETE.NULL",
Message = "Please send a valid data",
StatusCode = System.Net.HttpStatusCode.BadRequest
});
}
if (!Guid.TryParse(deleteCommentDto.CommentId, out var commentIdGuid))
{
return new CommandResult(new ErrorMessage
{
ErrorCode = "CATALOG.OBJECT.COMMENT.DELETE.INVALID.ID",
Message = "Please send a valid data",
StatusCode = System.Net.HttpStatusCode.BadRequest
});
}
var comment = _commentRepo.Table.SingleOrDefault(c => c.ObjectCommentId == commentIdGuid);
if (comment == null)
{
return new CommandResult(new ErrorMessage
{
ErrorCode = "CATALOG.OBJECT.COMMENT.DELETE.INVALID.ID",
Message = "The comment you are trying to delete does not exists",
StatusCode = System.Net.HttpStatusCode.BadRequest
});
}
try
{
_commentRepo.Delete(comment);
await _commentRepo.SaveChangesAsync();
return new CommandResult();
}
catch (Exception e)
{
_logger.LogError(e, $"There were a problem deleting the object:{deleteCommentDto.CommentId}");
return new CommandResult(new ErrorMessage
{
ErrorCode = "CATALOG.OBJECT.DELETE.INTERNAL.ERROR",
Message = "There were an error deleting your object",
StatusCode = System.Net.HttpStatusCode.InternalServerError
});
}
}
19
View Source File : GuidGenerator.cs
License : MIT License
Project Creator : abock
License : MIT License
Project Creator : abock
protected sealed override Guid GenerateGuid(IEnumerable<string> args)
{
var name = args.FirstOrDefault();
if (string.IsNullOrEmpty(name))
throw new Exception("Must specify NAME as the first positional argument.");
if (name == "-")
name = Console.In.ReadToEnd();
var @namespace = args.Skip(1).FirstOrDefault();
Guid namespaceGuid = default;
if (!string.IsNullOrEmpty(@namespace))
{
switch (@namespace.ToLowerInvariant())
{
case "url":
namespaceGuid = GuidNamespace.URL;
break;
case "dns":
namespaceGuid = GuidNamespace.DNS;
break;
case "oid":
namespaceGuid = GuidNamespace.OID;
break;
default:
if (!Guid.TryParse(@namespace, out namespaceGuid))
throw new Exception("Invalid namespace GUID");
break;
}
}
if (namespaceGuid == default)
namespaceGuid = GuidNamespace.URL;
return generator(namespaceGuid, name);
}
19
View Source File : BaseListViewModel.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public void FilterFeatureDefinitions(string searchQuery)
{
// In case feature definiton is scope=invalid,
// and faulty activated feature is searched for with unique ID ending with "/0",
// it will not be found on the left
// Therefore, "/0" is cut of here
if (!string.IsNullOrEmpty(searchQuery) && searchQuery.EndsWith("/0"))
{
// check if first part of search query is a guid
var firstPartOfQuery = searchQuery.Split('/');
Guid notNeededGuid;
if (firstPartOfQuery.Length > 0 && Guid.TryParse(firstPartOfQuery[0], out notNeededGuid))
{
// then remove "/0" from the end
searchQuery = firstPartOfQuery[0];
}
}
var searchFilter = new SetSearchFilter<Core.Models.FeatureDefinition>(
searchQuery, null);
eventAggregator.BeginPublishOnUIThread(searchFilter);
}
19
View Source File : FeatureDefinitionListViewModel.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public void FilterRight(string searchQuery)
{
// In case feature definiton is scope=invalid,
// and faulty activated feature is searched for with unique ID ending with "/15",
// it will not be found, as activated feature will be faulty and will probably have ending "/0"
// Therefore, "/15" is cut of here
if (ActiveItem != null && ActiveItem.Item != null && ActiveItem.Item.Scope == Core.Models.Enums.Scope.ScopeInvalid)
{
// check if first part of search query is a guid
var firstPartOfQuery = searchQuery.Split('/');
Guid notNeededGuid;
if (firstPartOfQuery.Length > 0 && Guid.TryParse(firstPartOfQuery[0], out notNeededGuid))
{
// then remove "/0" from the end
searchQuery = firstPartOfQuery[0];
}
}
var searchFilter = new SetSearchFilter<Core.Models.Location>(
searchQuery, null);
eventAggregator.BeginPublishOnUIThread(searchFilter);
}
19
View Source File : StringHelper.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public static Guid UniqueIdToGuid(string uniqueId)
{
if (string.IsNullOrEmpty(uniqueId))
{
return Guid.Empty;
}
Guid newGuid;
if (Guid.TryParse(uniqueId, out newGuid))
{ return newGuid; }
else if (uniqueId.Contains(Core.Common.Constants.MagicStrings.GuidSeparator))
{
string[] guids = uniqueId.Split(Core.Common.Constants.MagicStrings.GuidSeparator);
if (Guid.TryParse(guids[0], out newGuid))
{ return newGuid; }
}
return Guid.Empty;
}
19
View Source File : FeatureDefinitionFactory.cs
License : Microsoft Public License
Project Creator : achimismaili
License : Microsoft Public License
Project Creator : achimismaili
public static FeatureDefinition GetFaultyDefinition(
string uniqueIdentifier,
Scope scope,
Version version
)
{
if (string.IsNullOrEmpty(uniqueIdentifier))
{
return null;
}
Guid featureId;
int compatibilityLevel;
string sandBoxedSolutionLocation;
var splittedId = uniqueIdentifier.Split(Common.Constants.MagicStrings.GuidSeparator);
if (splittedId.Length >= 1)
{
var featureIdreplacedtring = splittedId[0];
if (!Guid.TryParse(featureIdreplacedtring, out featureId))
{
return null;
}
}
else
{
return null;
}
if (splittedId.Length >= 2)
{
var compatibilityLevelreplacedtring = splittedId[1];
if (!Int32.TryParse(compatibilityLevelreplacedtring, out compatibilityLevel))
{
compatibilityLevel = Common.Constants.Labels.FaultyFeatureCompatibilityLevel;
}
}
else
{
compatibilityLevel = Common.Constants.Labels.FaultyFeatureCompatibilityLevel;
}
if (splittedId.Length >= 3)
{
sandBoxedSolutionLocation = splittedId[2];
}
else
{
sandBoxedSolutionLocation = null;
}
var featureDefinition = new FeatureDefinition(
featureId,
compatibilityLevel,
Common.Constants.Labels.FaultyFeatureDescription,
Common.Constants.Labels.FaultyFeatureName,
false,
Common.Constants.Labels.FaultyFeatureName,
null,
scope,
Common.Constants.Labels.FaultyFeatureName,
Guid.Empty,
Common.Constants.Labels.FaultyFeatureUiVersion,
version,
sandBoxedSolutionLocation
);
return featureDefinition;
}
19
View Source File : Variables.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public Guid? GetGuid(string name)
{
Guid val;
if (Guid.TryParse(Get(name), out val))
{
return val;
}
return null;
}
19
View Source File : PatchOperation.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
private static object DeserializeValue(Type type, object jsonValue)
{
object value = null;
if (jsonValue is JToken)
{
try
{
value = ((JToken)jsonValue).ToObject(type, serializer);
}
catch (JsonException ex)
{
throw new VssPropertyValidationException("Value", PatchResources.InvalidValue(jsonValue, type), ex);
}
}
else
{
// Not a JToken, so it must be a primitive type. Will
// attempt to convert to the requested type.
if (type.IsreplacedignableOrConvertibleFrom(jsonValue))
{
value = ConvertUtility.ChangeType(jsonValue, type);
}
else
{
Guid guidValue;
if (Guid.TryParse((string)jsonValue, out guidValue))
{
value = guidValue;
}
else
{
throw new VssPropertyValidationException("Value", PatchResources.InvalidValue(jsonValue, type));
}
}
}
return value;
}
19
View Source File : DictionaryExtensions.cs
License : MIT License
Project Creator : actions
License : MIT License
Project Creator : actions
public static bool TryGetGuid(this IDictionary<string, object> dictionary, string key, out Guid value)
{
value = Guid.Empty;
object objValue = null;
if (dictionary.TryGetValue(key, out objValue))
{
if (objValue is Guid)
{
value = (Guid)objValue;
return true;
}
else if (objValue is string)
{
return Guid.TryParse((string)objValue, out value);
}
}
return false;
}
19
View Source File : CodeMapWindowViewModel.CodeMapDteEventsObserver.cs
License : GNU General Public License v3.0
Project Creator : Acumatica
License : GNU General Public License v3.0
Project Creator : Acumatica
[SuppressMessage("Usage", "VSTHRD010:Invoke single-threaded types on Main thread", Justification = "Already checked with CheckAccess()")]
private void SetVisibilityForCodeMapWindow(EnvDTE.Window window, bool windowIsVisible)
{
if (!ThreadHelper.CheckAccess())
return;
string windowObjectKind, windowKind, windowDoreplacedentPath, doreplacedentLanguage;
try
{
//Sometimes COM interop exceptions popup from getter, so we need to query properties safely
windowObjectKind = window.ObjectKind;
windowDoreplacedentPath = window.Doreplacedent?.FullName;
doreplacedentLanguage = window.Doreplacedent?.Language;
windowKind = window.Kind;
}
catch
{
return;
}
if (windowObjectKind == null || !Guid.TryParse(windowObjectKind, out Guid windowId))
return;
if (windowId == CodeMapWindow.CodeMapWindowGuid) //Case when Code Map is displayed
{
bool wasVisible = _codeMapViewModel.IsVisible;
_codeMapViewModel.IsVisible = windowIsVisible;
if (!wasVisible && _codeMapViewModel.IsVisible) //Handle the case when WindowShowing event happens after WindowActivated event
{
RefreshCodeMapAsync()
.FileAndForget($"vs/{AreplacedinatorVSPackage.PackageName}/{nameof(CodeMapWindowViewModel)}/{nameof(SetVisibilityForCodeMapWindow)}");
}
}
else if (IsSwitchingToAnotherDoreplacedentWhileCodeMapIsEmpty())
{
RefreshCodeMapAsync()
.FileAndForget($"vs/{AreplacedinatorVSPackage.PackageName}/{nameof(CodeMapWindowViewModel)}/{nameof(SetVisibilityForCodeMapWindow)}");
}
//-------------------------------------------Local Function----------------------------------------------------------------------------------------
bool IsSwitchingToAnotherDoreplacedentWhileCodeMapIsEmpty() =>
_codeMapViewModel.IsVisible && _codeMapViewModel.Doreplacedent == null && windowIsVisible && windowKind == "Doreplacedent" && windowId != default &&
doreplacedentLanguage == LegacyLanguageNames.CSharp && !windowDoreplacedentPath.IsNullOrWhiteSpace();
}
19
View Source File : GuidComponent.xaml.cs
License : MIT License
Project Creator : ADeltaX
License : MIT License
Project Creator : ADeltaX
public override ValidationResult Validate(object value, CultureInfo cultureInfo)
{
if (Guid.TryParse((string)value, out _))
return ValidationResult.ValidResult;
else
return new ValidationResult(false, "Not a valid guid");
}
19
View Source File : DynS2SOptions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public void replacedert()
{
if (string.IsNullOrEmpty(ClientId) || !Guid.TryParse(ClientId, out Guid tempGuid))
{
throw new ArgumentException($"{nameof(ClientId)} is null or not valid format");
}
if (string.IsNullOrEmpty(ClientSecret))
{
throw new ArgumentNullException($"{nameof(ClientSecret)} is null");
}
if (!Uri.IsWellFormedUriString(Resource, UriKind.Absolute))
{
throw new UriFormatException($"{nameof(Resource)} is not well formed URI");
}
if (string.IsNullOrEmpty(TenantId) || !Guid.TryParse(TenantId, out tempGuid))
{
throw new ArgumentException($"{nameof(TenantId)} is null or not valid format");
}
Trace.TraceInformation("Successfully replacederted Dynamics S2S Options");
}
19
View Source File : WebsiteManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public virtual async Task<TWebsite> FindAsync(RequestContext request, PortalHostingEnvironment environment)
{
ThrowIfDisposed();
// Attempt to match website by a special route parameter. Use by the front-side editing services to target the
// correct website, in the absense of website URL paths.
Guid portalScopeId;
if (request != null && Guid.TryParse(request.RouteData.Values["__portalScopeId__"] as string, out portalScopeId))
{
return await Store.FindByIdAsync(ToKey(portalScopeId)).WithCurrentCulture();
}
// retrieve all websites in list format only containing the related website bindings
var websites = Websites.ToList();
if (!string.IsNullOrWhiteSpace(WebsiteName))
{
var website = await FindByNameAsync(WebsiteName).WithCurrentCulture();
if (website == null)
{
CmsEventSource.Log.WebsiteBindingNotFoundByWebsiteName(WebsiteName);
throw new ApplicationException("Unable to find a unique and active website with the name {0}.".FormatWith(WebsiteName));
}
return website;
}
else
{
var website = GetWebsiteByBinding(environment, websites) ?? GetWebsiteByAppSettingAndCreateBinding(environment, websites);
if (website == null)
{
CmsEventSource.Log.WebsiteBindingNotFoundByHostingEnvironment(environment);
throw new ApplicationException("Unable to find a unique and active website binding for the IIS site named {0} with a virtual path named {1}.".FormatWith(environment.SiteName, environment.ApplicationVirtualPath));
}
return await ExpandWebsite(website).WithCurrentCulture();
}
}
19
View Source File : WebsiteManager.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
private TWebsite GetWebsiteByAppSettingAndCreateBinding(PortalHostingEnvironment environment, IEnumerable<TWebsite> websites)
{
if (!PortalSettings.Instance.UseOnlineSetup)
{
// PortalOnlineSetup app setting is not set to true, return null and do not create binding.
return null;
}
var portalWebsiteId = ConfigurationManager.AppSettings["PortalPackageName"];
Guid websiteId;
if (!Guid.TryParse(portalWebsiteId, out websiteId))
{
// A valid guid was not found in the app setting.
return null;
}
var website = websites.FirstOrDefault(site => site.Id.ToGuid() == websiteId);
if (website == null)
{
// No website found with the id from the app setting.
return null;
}
if (!_websiteByAppSettingAndCreateBinding)
{
_websiteByAppSettingAndCreateBinding = true;
var bindingId = CreateWebsiteBindingAsync(environment, website).Result;
}
return website;
}
19
View Source File : BlogFeedHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override IBlogDataAdapter GetDataAdapter(IPortalContext portal, HttpContext context)
{
Guid parsedId;
var id = Id ?? (Guid.TryParse(context.Request.Params["id"], out parsedId) ? new Guid?(parsedId) : null);
if (id == null)
{
throw new HttpException(400, "Unable to determine blog ID from request.");
}
return new BlogDataAdapter(
new EnreplacedyReference("adx_blog", id.Value),
new PortalContextDataAdapterDependencies(portal, PortalName, context.Request.RequestContext));
}
19
View Source File : BlogFeedRouteHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
Guid parsedId;
var id = Guid.TryParse(requestContext.RouteData.Values["id"] as string, out parsedId) ? new Guid?(parsedId) : null;
return new BlogFeedHandler(PortalName, id);
}
19
View Source File : PayPalPaymentDataTransferHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override bool TryGetQuoteAndReturnUrl(HttpRequest request, IDataAdapterDependencies dataAdapterDependencies, out Tuple<Guid, string> quoteAndReturnUrl)
{
quoteAndReturnUrl = null;
Guid quoteGuid;
var returnUrl = request.QueryString["ReturnUrl"];
if (string.IsNullOrWhiteSpace(returnUrl))
{
return false;
}
var url = new UrlBuilder(returnUrl);
var quoteid = url.QueryString.Get("quoteid");
if (string.IsNullOrWhiteSpace(quoteid)) return false;
if (Guid.TryParse(quoteid, out quoteGuid))
{
quoteAndReturnUrl = new Tuple<Guid, string>(quoteGuid, returnUrl);
return true;
}
return false;
}
19
View Source File : EntityFormFunctions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static void replacedociate(OrganizationServiceContext serviceContext, EnreplacedyReference related)
{
var targetEnreplacedyLogicalName = HttpContext.Current.Request["refenreplacedy"];
var targetEnreplacedyId = HttpContext.Current.Request["refid"];
var relationshipName = HttpContext.Current.Request["refrel"];
var relationshipRole = HttpContext.Current.Request["refrelrole"];
Guid targetId;
if (string.IsNullOrWhiteSpace(targetEnreplacedyLogicalName) || string.IsNullOrWhiteSpace(targetEnreplacedyId) ||
string.IsNullOrWhiteSpace(relationshipName) || related == null)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Request did not contain parameters 'refenreplacedy', 'refid', 'refrel'");
return;
}
if (!Guid.TryParse(targetEnreplacedyId, out targetId))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Request did not contain a valid guid 'refid'");
return;
}
try
{
var relationship = new Relationship(relationshipName);
if (!string.IsNullOrWhiteSpace(relationshipRole))
{
switch (relationshipRole)
{
case "Referenced":
relationship.PrimaryEnreplacedyRole = EnreplacedyRole.Referenced;
break;
case "Referencing":
relationship.PrimaryEnreplacedyRole = EnreplacedyRole.Referencing;
return;
break;
default:
ADXTrace.Instance.TraceError(TraceCategory.Application, "Relationship Primary Enreplacedy Role provided by parameter named 'refrelrole' is not valid.");
break;
}
}
var replacedociateRequest = new replacedociateRequest
{
Target = new EnreplacedyReference(targetEnreplacedyLogicalName, targetId),
Relationship = relationship,
RelatedEnreplacedies = new EnreplacedyReferenceCollection { related }
};
serviceContext.Execute(replacedociateRequest);
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, ex.ToString());
}
}
19
View Source File : EntityFormFunctions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static void replacedociateEnreplacedy(OrganizationServiceContext context, Enreplacedy enreplacedyform, Guid sourceEnreplacedyId)
{
var setEnreplacedyReference = enreplacedyform.GetAttributeValue<bool?>("adx_setenreplacedyreference") ?? false;
if (!setEnreplacedyReference) return;
var targetEnreplacedyId = Guid.Empty;
var targetEnreplacedyPrimaryKey = string.Empty;
var sourceEnreplacedyName = enreplacedyform.GetAttributeValue<string>("adx_enreplacedyname");
var sourceEnreplacedyPrimaryKey = enreplacedyform.GetAttributeValue<string>("adx_primarykeyname");
var targetEnreplacedyName = enreplacedyform.GetAttributeValue<string>("adx_referenceenreplacedylogicalname");
var relationshipName = enreplacedyform.GetAttributeValue<string>("adx_referenceenreplacedyrelationshipname") ?? string.Empty;
if (string.IsNullOrWhiteSpace(relationshipName))
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "Enreplacedy Relationship Name not provided. Enreplacedy replacedociation not required.");
return;
}
try
{
var referenceQueryStringName = enreplacedyform.GetAttributeValue<string>("adx_referencequerystringname") ?? string.Empty;
var referenceQueryStringValue = HttpContext.Current.Request[referenceQueryStringName];
var querystringIsPrimaryKey = enreplacedyform.GetAttributeValue<bool?>("adx_referencequerystringisprimarykey") ?? false;
if (!querystringIsPrimaryKey)
{
var referenceQueryAttributeName = enreplacedyform.GetAttributeValue<string>("adx_referencequeryattributelogicalname");
var enreplacedy =
context.CreateQuery(targetEnreplacedyName).FirstOrDefault(
o => o.GetAttributeValue<string>(referenceQueryAttributeName) == referenceQueryStringValue);
if (enreplacedy != null) { targetEnreplacedyId = enreplacedy.Id; }
}
else
{
Guid.TryParse(referenceQueryStringValue, out targetEnreplacedyId);
}
if (sourceEnreplacedyId == Guid.Empty || targetEnreplacedyId == Guid.Empty)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Source and Target enreplacedy ids must not be null or empty.");
return;
}
// get the source enreplacedy
if (string.IsNullOrWhiteSpace(sourceEnreplacedyName))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "adx_enreplacedyform.adx_targetenreplacedylogicalname must not be null.");
return;
}
if (string.IsNullOrWhiteSpace(sourceEnreplacedyPrimaryKey))
{
sourceEnreplacedyPrimaryKey = MetadataHelper.GetEnreplacedyPrimaryKeyAttributeLogicalName(context, sourceEnreplacedyName);
}
if (string.IsNullOrWhiteSpace(sourceEnreplacedyPrimaryKey))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine source enreplacedy primary key logical name.");
return;
}
var sourceEnreplacedy = context.CreateQuery(sourceEnreplacedyName).FirstOrDefault(o => o.GetAttributeValue<Guid>(sourceEnreplacedyPrimaryKey) == sourceEnreplacedyId);
if (sourceEnreplacedy == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Source enreplacedy is null.");
return;
}
// Get the target enreplacedy
if (string.IsNullOrWhiteSpace(targetEnreplacedyName))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Target enreplacedy name must not be null or empty.");
return;
}
if (string.IsNullOrWhiteSpace(targetEnreplacedyPrimaryKey))
{
targetEnreplacedyPrimaryKey = MetadataHelper.GetEnreplacedyPrimaryKeyAttributeLogicalName(context, targetEnreplacedyName);
}
if (string.IsNullOrWhiteSpace(targetEnreplacedyPrimaryKey))
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Failed to determine target enreplacedy primary key logical name.");
return;
}
var targetEnreplacedy = context.CreateQuery(targetEnreplacedyName).FirstOrDefault(o => o.GetAttributeValue<Guid>(targetEnreplacedyPrimaryKey) == targetEnreplacedyId);
if (targetEnreplacedy == null)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, "Target enreplacedy is null.");
return;
}
context.AddLink(sourceEnreplacedy, relationshipName, targetEnreplacedy);
}
catch (Exception ex)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0}", ex.ToString()));
}
}
19
View Source File : EntityFormFunctions.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
internal static void CalculateValueOpportunity()
{
if (string.IsNullOrEmpty(HttpContext.Current.Request["refid"])) return;
var targetEnreplacedyId = HttpContext.Current.Request["refid"];
var portal = PortalCrmConfigurationManager.CreatePortalContext();
var serviceContext = portal.ServiceContext;
var adapter = new CoreDataAdapter(portal, serviceContext);
Guid id;
if (!Guid.TryParse(targetEnreplacedyId, out id)) return;
if (string.IsNullOrEmpty(HttpContext.Current.Request["refenreplacedy"])) return;
var enreplacedyReference = new EnreplacedyReference(HttpContext.Current.Request["refenreplacedy"], id);
adapter.CalculateActualValueOfOpportunity(enreplacedyReference);
var enreplacedy =
serviceContext.CreateQuery(enreplacedyReference.LogicalName)
.FirstOrDefault(e => e.GetAttributeValue<Guid>("opportunityid") == enreplacedyReference.Id);
if (enreplacedy == null) return;
serviceContext.TryRemoveFromCache(enreplacedy);
serviceContext.UpdateObject(enreplacedy);
serviceContext.SaveChanges();
}
19
View Source File : AuthorizeNetPaymentHandlerBase.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override bool TryGetQuoteAndReturnUrl(HttpRequest request, IDataAdapterDependencies dataAdapterDependencies, out Tuple<Guid, string> quoteAndReturnUrl)
{
quoteAndReturnUrl = null;
var param = request.Form["order_id"];
if (string.IsNullOrEmpty(param))
{
return false;
}
var values = HttpUtility.ParseQueryString(param);
var logicalName = values["LogicalName"];
if (string.IsNullOrEmpty(logicalName))
{
return false;
}
Guid id;
if (!Guid.TryParse(values["Id"], out id))
{
return false;
}
var returnUrlParam = request.QueryString["ReturnUrl"];
if (string.IsNullOrEmpty(returnUrlParam))
{
return false;
}
var returnUrl = new UrlBuilder(returnUrlParam);
if (string.Equals(logicalName, "quote", StringComparison.InvariantCultureIgnoreCase))
{
quoteAndReturnUrl = new Tuple<Guid, string>(id, returnUrl.PathWithQueryString);
return true;
}
if (string.Equals(logicalName, "adx_webformsession", StringComparison.InvariantCultureIgnoreCase))
{
var serviceContext = dataAdapterDependencies.GetServiceContext();
var webFormSession = serviceContext.CreateQuery("adx_webformsession")
.FirstOrDefault(e => e.GetAttributeValue<Guid>("adx_webformsessionid") == id);
if (webFormSession == null)
{
return false;
}
var webFormSessionQuote = webFormSession.GetAttributeValue<EnreplacedyReference>("adx_quoteid");
if (webFormSessionQuote == null)
{
return false;
}
quoteAndReturnUrl = new Tuple<Guid, string>(webFormSessionQuote.Id, returnUrl.PathWithQueryString);
return true;
}
return false;
}
19
View Source File : DemoPaypalRequestHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override bool TryGetQuoteAndReturnUrl(HttpRequest request, IDataAdapterDependencies dataAdapterDependencies, out Tuple<Guid, string> quoteAndReturnUrl)
{
quoteAndReturnUrl = null;
Guid quoteId;
//Get the original request parameters
var incomingReqVariables = request.QueryString;
if (Guid.TryParse(incomingReqVariables["invoice"], out quoteId))
{
quoteAndReturnUrl = new Tuple<Guid, string>(quoteId, incomingReqVariables["return"]);
return true;
}
return false;
}
19
View Source File : PayPalPaymentHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected override bool TryGetQuoteAndReturnUrl(HttpRequest request, IDataAdapterDependencies dataAdapterDependencies, out Tuple<Guid, string> quoteAndReturnUrl)
{
quoteAndReturnUrl = null;
Guid quoteId;
if (Guid.TryParse(request.Form["invoice"], out quoteId))
{
quoteAndReturnUrl = new Tuple<Guid, string>(quoteId, null);
return true;
}
return false;
}
19
View Source File : EntityListDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
protected static bool TryGetViewId(Enreplacedy enreplacedyList, EnreplacedyReference viewReference, out Guid? viewId)
{
// First, try get the view from the newer view configuration JSON.
var viewMetadataJson = enreplacedyList.GetAttributeValue<string>("adx_views");
if (!string.IsNullOrWhiteSpace(viewMetadataJson))
{
try
{
var viewMetadata = ViewMetadata.Parse(viewMetadataJson);
var view = viewMetadata.Views.FirstOrDefault(e => e.ViewId == viewReference.Id);
if (view != null)
{
viewId = view.ViewId;
return true;
}
}
catch (Exception e)
{
ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("Error parsing adx_views JSON: {0}", e.ToString()));
}
}
// Fall back to the legacy comma-delimited list of IDs.
var viewIds = (enreplacedyList.GetAttributeValue<string>("adx_view") ?? string.Empty)
.Split(',')
.Select(s =>
{
Guid id;
return Guid.TryParse(s, out id) ? new Guid?(id) : null;
})
.Where(id => id != null);
viewId = viewIds.FirstOrDefault(id => id == viewReference.Id);
return viewId != null;
}
19
View Source File : EventAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public bool TryMatchRequestEventOccurrence(HttpRequest request, IEnumerable<IEventOccurrence> occurrences, out IEventOccurrence requestOccurrence)
{
if (request == null) throw new ArgumentNullException("request");
if (occurrences == null) throw new ArgumentNullException("occurrences");
requestOccurrence = null;
Guid schedule;
if (!Guid.TryParse(request["schedule"], out schedule))
{
return false;
}
DateTime start;
if (!DateTime.TryParseExact(request["start"], "o", CultureInfo.InvariantCulture, DateTimeStyles.RoundtripKind, out start))
{
return false;
}
requestOccurrence = occurrences.FirstOrDefault(e => e.EventSchedule.Id == schedule && e.Start == start);
return requestOccurrence != null;
}
19
View Source File : CalendarRouteHandler.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IHttpHandler GetHttpHandler(RequestContext requestContext)
{
var eventScheduleIdRouteValue = requestContext.RouteData.Values["eventScheduleId"];
Guid eventScheduleId;
if (eventScheduleIdRouteValue == null || !Guid.TryParse(eventScheduleIdRouteValue.ToString(), out eventScheduleId))
{
throw new InvalidOperationException("Unable to retrieve the event schedule ID from route data.");
}
return new CalendarHandler(eventScheduleId);
}
19
View Source File : ProductAggregationDataAdapter.cs
License : MIT License
Project Creator : Adoxio
License : MIT License
Project Creator : Adoxio
public IEnumerable<IProduct> SelectProducts(string brand, int? rating, int startRowIndex, int maximumRows, string sortExpression)
{
ADXTrace.Instance.TraceInfo(TraceCategory.Application, string.Format("brand={0}, rating={1}, startRowIndex={2}, maximumRows={3}, sortExpression={4}: Start", brand, rating, startRowIndex, maximumRows, sortExpression));
if (startRowIndex < 0)
{
throw new ArgumentException("Value must be a positive integer.", "startRowIndex");
}
if (maximumRows == 0)
{
return Enumerable.Empty<IProduct>();
}
var serviceContext = Dependencies.GetServiceContext();
var query = SelectEnreplacedies(serviceContext);
Guid brandId;
if (Guid.TryParse(brand, out brandId))
{
query = query.Where(e => e.GetAttributeValue<EnreplacedyReference>("adx_brand") == new EnreplacedyReference("adx_brand", brandId));
}
if (rating.HasValue)
{
var minValue = Convert.ToDouble(rating.Value);
query = query.Where(e => e.GetAttributeValue<double?>("adx_ratingaverage") >= minValue);
}
var sorts = ParseSortExpression(string.IsNullOrEmpty(sortExpression) ? DefaultSortExpression : sortExpression);
query = sorts.Aggregate(query, (current, sort) => sort.Item2 == SortDirection.Ascending
? current.OrderBy(sort.Item1)
: current.OrderByDescending(sort.Item1));
if (startRowIndex > 0)
{
query = query.Skip(startRowIndex);
}
if (maximumRows > 0)
{
query = query.Take(maximumRows);
}
var user = Dependencies.GetPortalUser();
var website = Dependencies.GetWebsite();
var products = new ProductFactory(serviceContext, user, website).Create(query);
ADXTrace.Instance.TraceInfo(TraceCategory.Application, "End");
if (FeatureCheckHelper.IsFeatureEnabled(FeatureNames.TelemetryFeatureUsage))
{
PortalFeatureTrace.TraceInstance.LogFeatureUsage(FeatureTraceCategory.Product, HttpContext.Current, "read_product", string.Empty, products.Count(), string.Empty, "read");
}
return products;
}
See More Examples