-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
582 lines (518 loc) · 25.1 KB
/
Copy pathProgram.cs
File metadata and controls
582 lines (518 loc) · 25.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
using System;
using System.Linq;
using System.Reflection;
using System.Collections.Generic;
using System.IO;
using System.Diagnostics;
using System.Net.Http;
using System.Threading.Tasks;
using System.Text.Json;
namespace PackageAnalyzer
{
class Program
{
static async Task Main(string[] args)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine(@"
╔═══════════════════════════════════════════════════════════════╗
║ 📦 .NET Package Analyzer v1.0 ║
║ ║
║ Analyze any NuGet package or .dll assembly ║
╚═══════════════════════════════════════════════════════════════╝");
Console.ResetColor();
if (args.Length == 0)
{
ShowUsage();
return;
}
var target = args[0].ToLower();
// Check for help command
if (target == "help" || target == "--help" || target == "-h" || target == "?")
{
ShowHelp();
return;
}
// Reset target to original case for actual processing
target = args[0];
// Check if it's a file path
if (File.Exists(target) && target.EndsWith(".dll"))
{
AnalyzeAssembly(target);
}
else if (target.EndsWith(".dll"))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"❌ File not found: {target}");
Console.ResetColor();
}
else
{
// It's a NuGet package
await AnalyzeNuGetPackage(target);
}
}
static void ShowUsage()
{
Console.WriteLine("\nUsage:");
Console.WriteLine(" dotnet run <package-name> - Analyze a NuGet package");
Console.WriteLine(" dotnet run <path-to-dll> - Analyze a .dll file");
Console.WriteLine(" dotnet run help - Show detailed help");
Console.WriteLine("\nExamples:");
Console.WriteLine(" dotnet run Newtonsoft.Json");
Console.WriteLine(" dotnet run Conga.Sign.SDK");
Console.WriteLine(" dotnet run /path/to/assembly.dll");
Console.WriteLine("\nOptions:");
Console.WriteLine(" You can pipe output to 'less' for easier navigation:");
Console.WriteLine(" dotnet run Newtonsoft.Json | less");
}
static void ShowHelp()
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine("\n📚 HOW IT WORKS");
Console.ResetColor();
Console.WriteLine(new string('═', 80));
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n🔍 For NuGet Packages:");
Console.ResetColor();
Console.WriteLine(" 1. Creates a temporary .NET project in your temp directory");
Console.WriteLine(" 2. Uses 'dotnet add package' to download the package from NuGet");
Console.WriteLine(" 3. Locates the package in your NuGet cache (~/.nuget/packages)");
Console.WriteLine(" 4. Finds the best matching framework version (net8.0, net7.0, etc.)");
Console.WriteLine(" 5. Loads the assembly using .NET Reflection");
Console.WriteLine(" 6. Analyzes all public types, methods, properties, and enums");
Console.WriteLine(" 7. Cleans up the temporary project automatically");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n📁 For Local DLL Files:");
Console.ResetColor();
Console.WriteLine(" 1. Loads the assembly directly from the specified path");
Console.WriteLine(" 2. Automatically resolves dependencies from:");
Console.WriteLine(" • Same directory as the DLL");
Console.WriteLine(" • NuGet cache for known packages");
Console.WriteLine(" 3. Analyzes all public types and members");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n📖 Understanding the Output:");
Console.ResetColor();
Console.WriteLine(" Icons indicate the type:");
Console.WriteLine(" 📘 = Regular Class");
Console.WriteLine(" 🔒 = Static Class");
Console.WriteLine(" 🎨 = Abstract Class");
Console.WriteLine(" 🔌 = Interface");
Console.WriteLine(" 📝 = Enum");
Console.WriteLine(" 📦 = Struct");
Console.WriteLine("\n Color coding:");
Console.WriteLine(" • Yellow = Constructors");
Console.WriteLine(" • Green = Properties");
Console.WriteLine(" • Cyan = Methods");
Console.WriteLine(" • Magenta = Events");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n⚙️ Requirements:");
Console.ResetColor();
Console.WriteLine(" • .NET SDK 6.0 or later");
Console.WriteLine(" • Internet connection (for NuGet packages)");
Console.WriteLine(" • Read access to ~/.nuget/packages directory");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n💡 Tips:");
Console.ResetColor();
Console.WriteLine(" • Use 'dotnet run <package> | less' for large packages");
Console.WriteLine(" • The analyzer shows only PUBLIC types and members");
Console.WriteLine(" • Generic types show with angle brackets: List<T>");
Console.WriteLine(" • Async methods are marked with 'async' prefix");
Console.WriteLine(" • Static members are marked with 'static' prefix");
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("\n🚀 Advanced Examples:");
Console.ResetColor();
Console.WriteLine(" dotnet run Serilog # Analyze logging library");
Console.WriteLine(" dotnet run Microsoft.EntityFrameworkCore # Analyze EF Core");
Console.WriteLine(" dotnet run Dapper # Analyze micro-ORM");
Console.WriteLine(" dotnet run AutoMapper # Analyze mapping library");
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("\n✨ This tool uses .NET Reflection to inspect assemblies without");
Console.WriteLine(" executing any code from the analyzed packages, making it safe");
Console.WriteLine(" to explore any NuGet package or DLL file.");
Console.ResetColor();
Console.WriteLine("\n" + new string('═', 80));
}
static async Task AnalyzeNuGetPackage(string packageName)
{
Console.WriteLine($"\n🔍 Searching for package: {packageName}");
// Create a temp directory for this analysis
var tempDir = Path.Combine(Path.GetTempPath(), $"pkganalyzer_{Guid.NewGuid():N}");
Directory.CreateDirectory(tempDir);
try
{
// Create a temporary project
var projectPath = Path.Combine(tempDir, "temp.csproj");
var projectContent = @"<Project Sdk=""Microsoft.NET.Sdk"">
<PropertyGroup>
<TargetFramework>net8.0</TargetFramework>
</PropertyGroup>
</Project>";
File.WriteAllText(projectPath, projectContent);
// Add the package
Console.WriteLine($"📥 Downloading package...");
var addResult = await RunCommand("dotnet", $"add \"{projectPath}\" package {packageName}", tempDir);
if (!addResult.success)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"❌ Failed to add package: {addResult.error}");
Console.ResetColor();
return;
}
// Restore to download the package
Console.WriteLine($"📦 Restoring packages...");
var restoreResult = await RunCommand("dotnet", $"restore \"{projectPath}\"", tempDir);
if (!restoreResult.success)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"❌ Failed to restore: {restoreResult.error}");
Console.ResetColor();
return;
}
// Find the package in NuGet cache
var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var nugetCache = Path.Combine(userProfile, ".nuget", "packages");
var packageDir = Path.Combine(nugetCache, packageName.ToLower());
if (!Directory.Exists(packageDir))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"❌ Package not found in cache: {packageDir}");
Console.ResetColor();
return;
}
// Find the latest version
var versions = Directory.GetDirectories(packageDir);
if (versions.Length == 0)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"❌ No versions found for package");
Console.ResetColor();
return;
}
var latestVersion = versions.OrderBy(v => v).Last();
var libDir = Path.Combine(latestVersion, "lib");
if (!Directory.Exists(libDir))
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"❌ No lib directory found");
Console.ResetColor();
return;
}
// Find compatible framework
var frameworks = Directory.GetDirectories(libDir);
string dllPath = null;
// Priority order for frameworks
var preferredFrameworks = new[] { "net8.0", "net7.0", "net6.0", "net5.0", "netstandard2.1", "netstandard2.0", "netcoreapp3.1" };
foreach (var fw in preferredFrameworks)
{
var fwDir = frameworks.FirstOrDefault(f => Path.GetFileName(f).StartsWith(fw));
if (fwDir != null)
{
var dlls = Directory.GetFiles(fwDir, "*.dll");
if (dlls.Length > 0)
{
// Find the main package dll (usually matches package name)
dllPath = dlls.FirstOrDefault(d => Path.GetFileNameWithoutExtension(d).Equals(packageName, StringComparison.OrdinalIgnoreCase))
?? dlls.First();
break;
}
}
}
if (dllPath == null && frameworks.Length > 0)
{
var dlls = Directory.GetFiles(frameworks[0], "*.dll");
if (dlls.Length > 0)
{
dllPath = dlls.First();
}
}
if (dllPath != null)
{
Console.WriteLine($"✅ Found assembly: {dllPath}");
AnalyzeAssembly(dllPath);
}
else
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine("❌ Could not find DLL in package");
Console.ResetColor();
}
}
finally
{
// Clean up temp directory
try
{
Directory.Delete(tempDir, true);
}
catch { }
}
}
static async Task<(bool success, string output, string error)> RunCommand(string command, string arguments, string workingDirectory)
{
var processInfo = new ProcessStartInfo
{
FileName = command,
Arguments = arguments,
WorkingDirectory = workingDirectory,
RedirectStandardOutput = true,
RedirectStandardError = true,
UseShellExecute = false,
CreateNoWindow = true
};
using var process = Process.Start(processInfo);
if (process == null) return (false, "", "Failed to start process");
var output = await process.StandardOutput.ReadToEndAsync();
var error = await process.StandardError.ReadToEndAsync();
await process.WaitForExitAsync();
return (process.ExitCode == 0, output, error);
}
static void AnalyzeAssembly(string assemblyPath)
{
// Set up assembly resolver for dependencies
AppDomain.CurrentDomain.AssemblyResolve += (sender, args) =>
{
var assemblyName = new AssemblyName(args.Name);
var assemblyFileName = assemblyName.Name + ".dll";
// Try to find in the same directory as the main assembly
var directory = Path.GetDirectoryName(assemblyPath);
if (directory != null)
{
var dependencyPath = Path.Combine(directory, assemblyFileName);
if (File.Exists(dependencyPath))
{
return Assembly.LoadFrom(dependencyPath);
}
}
// Try NuGet cache paths
var userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
var nugetCache = Path.Combine(userProfile, ".nuget", "packages");
// Search in common dependency locations
var searchPaths = new[]
{
Path.Combine(nugetCache, assemblyName.Name.ToLower(), assemblyName.Version?.ToString() ?? "*", "lib", "net8.0"),
Path.Combine(nugetCache, assemblyName.Name.ToLower(), assemblyName.Version?.ToString() ?? "*", "lib", "netstandard2.0"),
Path.Combine(nugetCache, assemblyName.Name.ToLower(), assemblyName.Version?.ToString() ?? "*", "lib", "netstandard2.1"),
};
foreach (var path in searchPaths)
{
if (path.Contains("*") && Directory.Exists(Path.GetDirectoryName(path)))
{
var pattern = Path.GetFileName(path);
var dir = Path.GetDirectoryName(path);
if (dir != null)
{
var files = Directory.GetFiles(dir, assemblyFileName, SearchOption.AllDirectories);
if (files.Length > 0)
{
return Assembly.LoadFrom(files[0]);
}
}
}
else
{
var fullPath = Path.Combine(path, assemblyFileName);
if (File.Exists(fullPath))
{
return Assembly.LoadFrom(fullPath);
}
}
}
return null;
};
try
{
var assembly = Assembly.LoadFrom(assemblyPath);
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine($"╔{'═'.ToString().PadRight(78, '═')}╗");
Console.WriteLine($"║ 📦 PACKAGE: {assembly.GetName().Name} v{assembly.GetName().Version}".PadRight(79) + "║");
Console.WriteLine($"╚{'═'.ToString().PadRight(78, '═')}╝");
Console.ResetColor();
// Get all types grouped by namespace
var typesByNamespace = assembly.GetTypes()
.Where(t => t.IsPublic)
.GroupBy(t => t.Namespace ?? "<No Namespace>")
.OrderBy(g => g.Key);
foreach (var namespaceGroup in typesByNamespace)
{
Console.ForegroundColor = ConsoleColor.Cyan;
Console.WriteLine($"\n🗂️ Namespace: {namespaceGroup.Key}");
Console.ResetColor();
Console.WriteLine(new string('─', 60));
foreach (var type in namespaceGroup.OrderBy(t => t.Name))
{
PrintTypeInfo(type);
}
}
// Print summary
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine("📊 SUMMARY");
Console.WriteLine(new string('═', 80));
var allTypes = assembly.GetTypes().Where(t => t.IsPublic);
Console.WriteLine($" Total Namespaces: {typesByNamespace.Count()}");
Console.WriteLine($" Total Types: {allTypes.Count()}");
Console.WriteLine($" • Classes: {allTypes.Count(t => t.IsClass && !t.IsAbstract && !t.IsSealed)}");
Console.WriteLine($" • Static Classes: {allTypes.Count(t => t.IsClass && t.IsAbstract && t.IsSealed)}");
Console.WriteLine($" • Abstract Classes: {allTypes.Count(t => t.IsClass && t.IsAbstract && !t.IsSealed)}");
Console.WriteLine($" • Interfaces: {allTypes.Count(t => t.IsInterface)}");
Console.WriteLine($" • Enums: {allTypes.Count(t => t.IsEnum)}");
Console.WriteLine($" • Structs: {allTypes.Count(t => t.IsValueType && !t.IsEnum)}");
Console.ResetColor();
}
catch (Exception ex)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine($"❌ Error analyzing assembly: {ex.Message}");
Console.ResetColor();
}
}
static void PrintTypeInfo(Type type)
{
// Determine type kind and icon
string icon = "📄";
string kind = "";
if (type.IsInterface)
{
icon = "🔌";
kind = "interface";
}
else if (type.IsEnum)
{
icon = "📝";
kind = "enum";
}
else if (type.IsValueType && !type.IsEnum)
{
icon = "📦";
kind = "struct";
}
else if (type.IsClass)
{
if (type.IsAbstract && type.IsSealed) // static class
{
icon = "🔒";
kind = "static class";
}
else if (type.IsAbstract)
{
icon = "🎨";
kind = "abstract class";
}
else
{
icon = "📘";
kind = "class";
}
}
Console.WriteLine();
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine($"{icon} {type.Name} ({kind})");
Console.ResetColor();
// Print constructors
var constructors = type.GetConstructors(BindingFlags.Public | BindingFlags.Instance)
.Where(c => !c.IsSpecialName || c.IsConstructor);
if (constructors.Any())
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(" Constructors:");
Console.ResetColor();
foreach (var ctor in constructors)
{
var parameters = string.Join(", ", ctor.GetParameters()
.Select(p => $"{GetSimpleTypeName(p.ParameterType)} {p.Name}"));
Console.WriteLine($" • {type.Name}({parameters})");
}
}
// Print properties
var properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
.Where(p => p.DeclaringType == type)
.OrderBy(p => p.Name);
if (properties.Any())
{
Console.ForegroundColor = ConsoleColor.DarkGreen;
Console.WriteLine(" Properties:");
Console.ResetColor();
foreach (var prop in properties)
{
var getSet = "";
if (prop.CanRead && prop.CanWrite)
getSet = " { get; set; }";
else if (prop.CanRead)
getSet = " { get; }";
else if (prop.CanWrite)
getSet = " { set; }";
var staticMod = prop.GetGetMethod()?.IsStatic == true ? "static " : "";
Console.WriteLine($" • {staticMod}{GetSimpleTypeName(prop.PropertyType)} {prop.Name}{getSet}");
}
}
// Print methods (excluding property getters/setters and constructors)
var methods = type.GetMethods(BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static)
.Where(m => !m.IsSpecialName && m.DeclaringType == type)
.OrderBy(m => m.Name);
if (methods.Any())
{
Console.ForegroundColor = ConsoleColor.DarkCyan;
Console.WriteLine(" Methods:");
Console.ResetColor();
foreach (var method in methods)
{
var parameters = string.Join(", ", method.GetParameters()
.Select(p => $"{GetSimpleTypeName(p.ParameterType)} {p.Name}"));
var staticMod = method.IsStatic ? "static " : "";
var asyncMod = method.ReturnType.Name.Contains("Task") ? "async " : "";
Console.WriteLine($" • {staticMod}{asyncMod}{GetSimpleTypeName(method.ReturnType)} {method.Name}({parameters})");
}
}
// Print enum values
if (type.IsEnum)
{
Console.ForegroundColor = ConsoleColor.DarkYellow;
Console.WriteLine(" Values:");
Console.ResetColor();
foreach (var value in Enum.GetValues(type))
{
Console.WriteLine($" • {value} = {(int)value}");
}
}
}
static string GetSimpleTypeName(Type type)
{
if (type == null) return "void";
// Handle nullable types
if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Nullable<>))
{
return GetSimpleTypeName(type.GetGenericArguments()[0]) + "?";
}
// Handle generic types
if (type.IsGenericType)
{
var name = type.Name.Substring(0, type.Name.IndexOf('`'));
var args = string.Join(", ", type.GetGenericArguments().Select(GetSimpleTypeName));
return $"{name}<{args}>";
}
// Handle common types with C# aliases
var aliases = new Dictionary<Type, string>
{
{ typeof(void), "void" },
{ typeof(bool), "bool" },
{ typeof(byte), "byte" },
{ typeof(sbyte), "sbyte" },
{ typeof(char), "char" },
{ typeof(decimal), "decimal" },
{ typeof(double), "double" },
{ typeof(float), "float" },
{ typeof(int), "int" },
{ typeof(uint), "uint" },
{ typeof(long), "long" },
{ typeof(ulong), "ulong" },
{ typeof(short), "short" },
{ typeof(ushort), "ushort" },
{ typeof(string), "string" },
{ typeof(object), "object" }
};
return aliases.ContainsKey(type) ? aliases[type] : type.Name;
}
}
}