-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathProgram.cs
More file actions
1464 lines (1286 loc) · 67.9 KB
/
Program.cs
File metadata and controls
1464 lines (1286 loc) · 67.9 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
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using CosmosToSqlAssessment.Services;
using CosmosToSqlAssessment.Reporting;
using CosmosToSqlAssessment.Models;
using CosmosToSqlAssessment.SqlProject;
using Azure.Identity;
using Microsoft.Azure.Cosmos;
using Azure.Monitor.Query;
using Azure.Monitor.Query.Models;
using Azure;
namespace CosmosToSqlAssessment
{
/// <summary>
/// Cosmos DB to SQL Migration Assessment Tool
/// Provides comprehensive analysis and migration recommendations following Azure best practices
/// </summary>
class Program
{
private static readonly CancellationTokenSource _cancellationTokenSource = new();
// Constants for connection testing
private const string AzureMonitorTestQuery = "AzureDiagnostics | where ResourceProvider == 'MICROSOFT.DOCUMENTDB' | take 1";
private const int AzureMonitorTestQueryDays = 1;
static async Task<int> Main(string[] args)
{
// Handle Ctrl+C gracefully
Console.CancelKeyPress += (_, e) =>
{
e.Cancel = true;
_cancellationTokenSource.Cancel();
Console.WriteLine("\nOperation cancelled by user.");
};
try
{
// Parse command line arguments
var options = ParseCommandLineArguments(args);
if (options == null)
{
return 1; // Help was displayed or invalid arguments
}
// Validate command line options
if (!ValidateCommandLineOptions(options))
{
return 1;
}
// Build configuration
var configuration = BuildConfiguration(options);
// Setup dependency injection
var services = ConfigureServices(configuration);
using var serviceProvider = services.BuildServiceProvider();
// Setup logging
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
// Handle test connection command
if (options.TestConnection)
{
logger.LogInformation("Running connection test");
return await TestConnectionAsync(configuration, options, logger);
}
logger.LogInformation("Starting Cosmos DB to SQL Migration Assessment Tool");
// Display welcome message
DisplayWelcomeMessage();
// Get user inputs
var userInputs = await GetUserInputsAsync(configuration, options, logger);
if (userInputs == null)
{
return 1;
}
// Validate effective configuration (post command-line processing)
if (!ValidateEffectiveConfiguration(userInputs, logger))
{
return 1;
}
// Run the assessment
var assessmentResult = await RunAssessmentAsync(serviceProvider, configuration, userInputs, logger, _cancellationTokenSource.Token);
// Generate outputs based on command line options
await GenerateOutputsAsync(serviceProvider, assessmentResult, userInputs.OutputDirectory, options, logger, _cancellationTokenSource.Token);
// Generate SQL Database Project
await GenerateSqlProjectAsync(serviceProvider, assessmentResult, userInputs.OutputDirectory, logger, _cancellationTokenSource.Token);
// Display completion message
DisplayCompletionMessage(assessmentResult, options);
logger.LogInformation("Assessment completed successfully");
return 0;
}
catch (OperationCanceledException)
{
Console.WriteLine("Assessment cancelled.");
return 130; // Standard exit code for SIGINT
}
catch (Exception ex)
{
Console.WriteLine($"Error: {ex.Message}");
// Log full exception details if logger is available
try
{
var configuration = BuildConfiguration();
var services = ConfigureServices(configuration);
using var serviceProvider = services.BuildServiceProvider();
var logger = serviceProvider.GetRequiredService<ILogger<Program>>();
logger.LogError(ex, "Unhandled exception occurred during assessment");
}
catch
{
// If logging setup fails, just write to console
Console.WriteLine($"Full error details: {ex}");
}
return 1;
}
}
private static IConfiguration BuildConfiguration(CommandLineOptions? options = null)
{
var configBuilder = new ConfigurationBuilder()
.SetBasePath(Directory.GetCurrentDirectory())
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddEnvironmentVariables();
// Add command line overrides if provided
if (options != null)
{
var commandLineConfig = new Dictionary<string, string?>();
if (!string.IsNullOrEmpty(options.WorkspaceId))
{
commandLineConfig["AzureMonitor:WorkspaceId"] = options.WorkspaceId;
}
configBuilder.AddInMemoryCollection(commandLineConfig);
}
return configBuilder.Build();
}
private static IServiceCollection ConfigureServices(IConfiguration configuration)
{
var services = new ServiceCollection();
// Configuration
services.AddSingleton(configuration);
// Logging
services.AddLogging(builder =>
{
builder.AddConfiguration(configuration.GetSection("Logging"));
builder.AddConsole();
builder.AddDebug();
});
// Application services
services.AddScoped<CosmosDbAnalysisService>();
services.AddScoped<SqlMigrationAssessmentService>();
services.AddScoped<DataFactoryEstimateService>();
services.AddScoped<DataQualityAnalysisService>();
services.AddScoped<ReportGenerationService>();
// SQL Project services
services.AddScoped<SqlDatabaseProjectService>();
services.AddScoped<SqlProjectIntegrationService>();
services.AddScoped<SqlProjectGenerationService>();
return services;
}
private static void DisplayWelcomeMessage()
{
Console.WriteLine();
Console.WriteLine("═══════════════════════════════════════════════════════");
Console.WriteLine(" Cosmos DB to SQL Migration Assessment Tool");
Console.WriteLine("═══════════════════════════════════════════════════════");
Console.WriteLine();
Console.WriteLine("This tool will analyze your Cosmos DB database and provide:");
Console.WriteLine("• Comprehensive performance and schema analysis");
Console.WriteLine("• Pre-migration data quality checks");
Console.WriteLine("• SQL migration recommendations and mapping");
Console.WriteLine("• Azure Data Factory migration estimates");
Console.WriteLine("• Detailed Excel and Word reports");
Console.WriteLine("• SQL Database Project for deployment to Azure SQL");
Console.WriteLine("• Ready-to-deploy SQL Database projects (.sqlproj)");
Console.WriteLine();
Console.WriteLine("Features:");
Console.WriteLine("• 6-month performance metrics analysis");
Console.WriteLine("• Data quality analysis (nulls, duplicates, types, outliers)");
Console.WriteLine("• Index recommendations based on usage patterns");
Console.WriteLine("• Azure SQL platform recommendations");
Console.WriteLine("• Migration effort and cost estimates");
Console.WriteLine("• SSDT-compatible SQL projects for deployment");
Console.WriteLine();
}
private static bool ValidateConfiguration(IConfiguration configuration, ILogger logger)
{
var isValid = true;
var validationErrors = new List<string>();
// Validate Cosmos DB configuration
var cosmosEndpoint = configuration["CosmosDb:AccountEndpoint"];
if (string.IsNullOrEmpty(cosmosEndpoint))
{
validationErrors.Add("CosmosDb:AccountEndpoint is required");
isValid = false;
}
var databaseName = configuration["CosmosDb:DatabaseName"];
if (string.IsNullOrEmpty(databaseName))
{
validationErrors.Add("CosmosDb:DatabaseName is required");
isValid = false;
}
// Check Azure Monitor configuration (optional but recommended)
var workspaceId = configuration["AzureMonitor:WorkspaceId"];
if (string.IsNullOrEmpty(workspaceId))
{
logger.LogWarning("Azure Monitor workspace ID not configured. Performance metrics will be limited.");
Console.WriteLine("⚠️ Warning: Azure Monitor not configured - performance analysis will be limited");
}
else
{
// Validate workspace ID format (should be a GUID)
if (!Guid.TryParse(workspaceId, out _))
{
logger.LogWarning("Azure Monitor workspace ID format is invalid. Expected GUID format.");
Console.WriteLine("⚠️ Warning: Invalid workspace ID format - should be a GUID (e.g., 12345678-1234-1234-1234-123456789012)");
}
else
{
Console.WriteLine("✅ Azure Monitor workspace configured");
}
}
// Display validation results
if (!isValid)
{
Console.WriteLine("❌ Configuration validation failed:");
foreach (var error in validationErrors)
{
Console.WriteLine($" • {error}");
}
Console.WriteLine();
Console.WriteLine("Please update appsettings.json with the required configuration values.");
return false;
}
Console.WriteLine("✅ Configuration validation passed");
Console.WriteLine($" • Cosmos DB Endpoint: {cosmosEndpoint}");
Console.WriteLine($" • Database: {databaseName}");
if (!string.IsNullOrEmpty(workspaceId))
{
Console.WriteLine($" • Azure Monitor: Configured");
}
Console.WriteLine();
return true;
}
private static bool ValidateEffectiveConfiguration(UserInputs userInputs, ILogger logger)
{
var isValid = true;
var validationErrors = new List<string>();
// Validate Cosmos DB endpoint
if (string.IsNullOrEmpty(userInputs.AccountEndpoint))
{
validationErrors.Add("Cosmos DB account endpoint is required");
isValid = false;
}
// Validate database names
if (!userInputs.DatabaseNames.Any())
{
validationErrors.Add("At least one database name is required");
isValid = false;
}
// Validate output directory
if (string.IsNullOrEmpty(userInputs.OutputDirectory))
{
validationErrors.Add("Output directory is required");
isValid = false;
}
// Display validation results
if (!isValid)
{
Console.WriteLine("❌ Configuration validation failed:");
foreach (var error in validationErrors)
{
Console.WriteLine($" • {error}");
}
Console.WriteLine();
return false;
}
Console.WriteLine("✅ Configuration validation passed");
Console.WriteLine($" • Cosmos DB Endpoint: {userInputs.AccountEndpoint}");
Console.WriteLine($" • Database(s): {string.Join(", ", userInputs.DatabaseNames)}");
Console.WriteLine($" • Output Directory: {userInputs.OutputDirectory}");
if (userInputs.MonitoringConfig?.WorkspaceId != null)
{
Console.WriteLine($" • Azure Monitor: Configured");
}
else
{
Console.WriteLine("⚠️ Warning: Azure Monitor not configured - performance analysis will be limited");
}
Console.WriteLine();
return true;
}
private static bool ValidateCommandLineOptions(CommandLineOptions options)
{
// Check for conflicting flags
if (options.AssessmentOnly && options.ProjectOnly)
{
Console.WriteLine("❌ Error: Cannot specify both --assessment-only and --project-only flags.");
Console.WriteLine(" Use one or the other, or omit both for default behavior (generate both).");
return false;
}
return true;
}
private static async Task<AssessmentResult> RunAssessmentAsync(
IServiceProvider serviceProvider,
IConfiguration configuration,
UserInputs userInputs,
ILogger logger,
CancellationToken cancellationToken)
{
var assessmentResults = new List<AssessmentResult>();
Console.WriteLine("🔍 Starting assessment...");
Console.WriteLine();
// Process each database
foreach (var databaseName in userInputs.DatabaseNames)
{
Console.WriteLine($"📊 Analyzing database: {databaseName}");
// Use appropriate service provider based on endpoint override
IServiceProvider activeServiceProvider = serviceProvider;
ServiceProvider? overrideServiceProvider = null;
if (!string.IsNullOrEmpty(userInputs.AccountEndpoint) &&
userInputs.AccountEndpoint != configuration["CosmosDb:AccountEndpoint"])
{
// Create a new configuration that overrides the endpoint
var configDict = new Dictionary<string, string>
{
["CosmosDb:AccountEndpoint"] = userInputs.AccountEndpoint
};
var overrideConfig = new ConfigurationBuilder()
.AddInMemoryCollection(configDict!)
.AddConfiguration(configuration)
.Build();
// Create override service provider
var overrideServices = ConfigureServices(overrideConfig);
overrideServiceProvider = overrideServices.BuildServiceProvider();
activeServiceProvider = overrideServiceProvider;
}
var assessmentResult = new AssessmentResult
{
CosmosAccountName = ExtractAccountNameFromEndpoint(userInputs.AccountEndpoint),
DatabaseName = databaseName
};
// Step 1: Cosmos DB Analysis
Console.WriteLine("📊 Phase 1: Analyzing Cosmos DB database...");
var cosmosService = activeServiceProvider.GetRequiredService<CosmosDbAnalysisService>();
try
{
assessmentResult.CosmosAnalysis = await cosmosService.AnalyzeDatabaseAsync(databaseName, cancellationToken);
Console.WriteLine($" ✅ Analyzed {assessmentResult.CosmosAnalysis.Containers.Count} containers");
if (assessmentResult.CosmosAnalysis.MonitoringLimitations.Any())
{
Console.WriteLine($" ⚠️ {assessmentResult.CosmosAnalysis.MonitoringLimitations.Count} monitoring limitations detected");
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to analyze Cosmos DB");
throw new InvalidOperationException($"Cosmos DB analysis failed for database {databaseName}: {ex.Message}", ex);
}
// Step 2: SQL Migration Assessment
Console.WriteLine();
Console.WriteLine("🎯 Phase 2: Generating SQL migration assessment...");
var sqlService = activeServiceProvider.GetRequiredService<SqlMigrationAssessmentService>();
try
{
assessmentResult.SqlAssessment = await sqlService.AssessMigrationAsync(assessmentResult.CosmosAnalysis, databaseName, cancellationToken);
Console.WriteLine($" ✅ Recommended platform: {assessmentResult.SqlAssessment.RecommendedPlatform}");
Console.WriteLine($" ✅ Generated {assessmentResult.SqlAssessment.IndexRecommendations.Count} index recommendations");
Console.WriteLine($" ✅ Migration complexity: {assessmentResult.SqlAssessment.Complexity.OverallComplexity}");
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to assess SQL migration");
throw new InvalidOperationException($"SQL migration assessment failed for database {databaseName}: {ex.Message}", ex);
}
// Step 3: Data Quality Analysis
Console.WriteLine();
Console.WriteLine("🔍 Phase 3: Analyzing data quality...");
var dataQualityService = activeServiceProvider.GetRequiredService<DataQualityAnalysisService>();
try
{
assessmentResult.DataQualityAnalysis = await dataQualityService.AnalyzeDataQualityAsync(
assessmentResult.CosmosAnalysis,
databaseName,
cancellationToken);
Console.WriteLine($" ✅ Analyzed {assessmentResult.DataQualityAnalysis.TotalDocumentsAnalyzed} documents");
Console.WriteLine($" ✅ Found {assessmentResult.DataQualityAnalysis.CriticalIssuesCount} critical issues");
Console.WriteLine($" ✅ Found {assessmentResult.DataQualityAnalysis.WarningIssuesCount} warnings");
Console.WriteLine($" ✅ Quality score: {assessmentResult.DataQualityAnalysis.Summary.OverallQualityScore:F1}/100 ({assessmentResult.DataQualityAnalysis.Summary.QualityRating})");
}
catch (Exception ex)
{
logger.LogWarning(ex, "Failed to perform data quality analysis - continuing without it");
Console.WriteLine($" ⚠️ Data quality analysis skipped due to error: {ex.Message}");
}
// Step 4: Data Factory Estimates
Console.WriteLine();
Console.WriteLine("⏱️ Phase 4: Calculating migration estimates...");
var dataFactoryService = activeServiceProvider.GetRequiredService<DataFactoryEstimateService>();
try
{
assessmentResult.DataFactoryEstimate = await dataFactoryService.EstimateMigrationAsync(
assessmentResult.CosmosAnalysis,
assessmentResult.SqlAssessment,
cancellationToken);
Console.WriteLine($" ✅ Estimated migration time: {assessmentResult.DataFactoryEstimate.EstimatedDuration:hh\\:mm\\:ss}");
Console.WriteLine($" ✅ Estimated cost: ${assessmentResult.DataFactoryEstimate.EstimatedCostUSD:F2}");
Console.WriteLine($" ✅ Recommended DIUs: {assessmentResult.DataFactoryEstimate.RecommendedDIUs}");
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to calculate Data Factory estimates");
throw new InvalidOperationException($"Data Factory estimation failed for database {databaseName}: {ex.Message}", ex);
}
assessmentResults.Add(assessmentResult);
Console.WriteLine($"✅ Completed assessment for database: {databaseName}");
Console.WriteLine();
// Clean up override service provider if created
overrideServiceProvider?.Dispose();
}
// Generate reports for each database separately (Excel) and combined (Word)
if (assessmentResults.Count == 1)
{
return assessmentResults[0];
}
else
{
// Store individual results for separate Excel generation
foreach (var result in assessmentResults)
{
result.GenerateSeparateExcel = true;
}
// Create a combined assessment result for Word report
var combinedResult = new AssessmentResult
{
CosmosAccountName = assessmentResults[0].CosmosAccountName,
DatabaseName = $"Multiple Databases ({assessmentResults.Count})",
CosmosAnalysis = CombineCosmosAnalyses(assessmentResults.Select(r => r.CosmosAnalysis).ToList()),
SqlAssessment = CombineSqlAssessments(assessmentResults.Select(r => r.SqlAssessment).ToList()),
DataFactoryEstimate = CombineDataFactoryEstimates(assessmentResults.Select(r => r.DataFactoryEstimate).ToList()),
IndividualDatabaseResults = assessmentResults.ToList()
};
return combinedResult;
}
}
private static async Task GenerateOutputsAsync(
IServiceProvider serviceProvider,
AssessmentResult assessmentResult,
string outputDirectory,
CommandLineOptions options,
ILogger logger,
CancellationToken cancellationToken)
{
Console.WriteLine();
// Generate assessment reports (unless --project-only is specified)
if (!options.ProjectOnly)
{
Console.WriteLine("📄 Phase 5a: Generating assessment reports...");
var reportingService = serviceProvider.GetRequiredService<ReportGenerationService>();
try
{
var (excelPaths, wordPath, analysisFolderPath) = await reportingService.GenerateAssessmentReportAsync(assessmentResult, outputDirectory, cancellationToken);
foreach (var excelPath in excelPaths)
{
Console.WriteLine($" ✅ Excel report: {excelPath}");
}
Console.WriteLine($" ✅ Word summary: {wordPath}");
// Store analysis folder path for SQL project generation
assessmentResult.AnalysisFolderPath = analysisFolderPath;
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to generate assessment reports");
Console.WriteLine($" ❌ Assessment report generation failed: {ex.Message}");
throw;
}
}
// Generate SQL projects (unless --assessment-only is specified)
if (!options.AssessmentOnly)
{
Console.WriteLine("🏗️ Phase 5b: Generating SQL database projects...");
var sqlProjectService = serviceProvider.GetRequiredService<SqlProjectGenerationService>();
try
{
// Use the analysis folder path from report generation
var analysisFolderPath = !string.IsNullOrEmpty(assessmentResult.AnalysisFolderPath)
? assessmentResult.AnalysisFolderPath
: outputDirectory;
await sqlProjectService.GenerateSqlProjectsAsync(assessmentResult, analysisFolderPath, cancellationToken);
foreach (var databaseMapping in assessmentResult.SqlAssessment.DatabaseMappings)
{
var projectName = $"{SanitizeName(databaseMapping.TargetDatabase)}.Database";
var projectPath = Path.Combine(analysisFolderPath, "sql-projects", projectName);
Console.WriteLine($" ✅ SQL project: {projectPath}");
}
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to generate SQL projects");
Console.WriteLine($" ❌ SQL project generation failed: {ex.Message}");
throw;
}
}
}
private static string SanitizeName(string name)
{
if (string.IsNullOrWhiteSpace(name))
return "Database";
// Remove invalid characters for file system and SQL identifiers
var invalidChars = Path.GetInvalidFileNameChars().Concat(new[] { ' ', '-', '.' }).ToArray();
var sanitized = name;
foreach (var invalidChar in invalidChars)
{
sanitized = sanitized.Replace(invalidChar, '_');
}
// Ensure it starts with a letter (SQL identifier requirement)
if (!char.IsLetter(sanitized[0]) && sanitized[0] != '_')
{
sanitized = "DB_" + sanitized;
}
return sanitized;
}
private static async Task GenerateReportsAsync(
IServiceProvider serviceProvider,
AssessmentResult assessmentResult,
string outputDirectory,
ILogger logger,
CancellationToken cancellationToken)
{
Console.WriteLine();
Console.WriteLine("📄 Phase 5: Generating reports...");
var reportingService = serviceProvider.GetRequiredService<ReportGenerationService>();
try
{
var (excelPaths, wordPath, analysisFolderPath) = await reportingService.GenerateAssessmentReportAsync(assessmentResult, outputDirectory, cancellationToken);
foreach (var excelPath in excelPaths)
{
Console.WriteLine($" ✅ Excel report: {excelPath}");
}
Console.WriteLine($" ✅ Word summary: {wordPath}");
}
catch (Exception ex)
{
logger.LogError(ex, "Failed to generate reports");
Console.WriteLine($" ❌ Report generation failed: {ex.Message}");
throw;
}
}
private static CosmosDbAnalysis CombineCosmosAnalyses(List<CosmosDbAnalysis> analyses)
{
var combined = new CosmosDbAnalysis
{
Containers = new List<ContainerAnalysis>(),
MonitoringLimitations = new List<string>(),
DatabaseMetrics = new DatabaseMetrics() // Initialize with default or combine appropriately
};
foreach (var analysis in analyses)
{
combined.Containers.AddRange(analysis.Containers);
combined.MonitoringLimitations.AddRange(analysis.MonitoringLimitations);
}
return combined;
}
private static SqlMigrationAssessment CombineSqlAssessments(List<SqlMigrationAssessment> assessments)
{
var combined = new SqlMigrationAssessment
{
RecommendedPlatform = assessments.FirstOrDefault()?.RecommendedPlatform ?? "Azure SQL Database",
IndexRecommendations = new List<IndexRecommendation>(),
Complexity = new MigrationComplexity(),
DatabaseMappings = new List<DatabaseMapping>()
};
foreach (var assessment in assessments)
{
combined.IndexRecommendations.AddRange(assessment.IndexRecommendations);
combined.DatabaseMappings.AddRange(assessment.DatabaseMappings);
}
// Combine complexity - take the highest complexity level
var complexities = assessments.Select(a => a.Complexity.OverallComplexity).ToList();
if (complexities.Contains("High"))
combined.Complexity.OverallComplexity = "High";
else if (complexities.Contains("Medium"))
combined.Complexity.OverallComplexity = "Medium";
else
combined.Complexity.OverallComplexity = "Low";
return combined;
}
private static DataFactoryEstimate CombineDataFactoryEstimates(List<DataFactoryEstimate> estimates)
{
return new DataFactoryEstimate
{
EstimatedDuration = TimeSpan.FromMilliseconds(estimates.Sum(e => e.EstimatedDuration.TotalMilliseconds)),
EstimatedCostUSD = estimates.Sum(e => e.EstimatedCostUSD),
RecommendedDIUs = estimates.Max(e => e.RecommendedDIUs),
RecommendedParallelCopies = estimates.Max(e => e.RecommendedParallelCopies),
TotalDataSizeGB = estimates.Sum(e => e.TotalDataSizeGB),
PipelineEstimates = estimates.SelectMany(e => e.PipelineEstimates).ToList(),
Prerequisites = estimates.SelectMany(e => e.Prerequisites).Distinct().ToList(),
Recommendations = estimates.SelectMany(e => e.Recommendations).Distinct().ToList()
};
}
private static void DisplayCompletionMessage(AssessmentResult assessment, CommandLineOptions options)
{
Console.WriteLine();
Console.WriteLine("═══════════════════════════════════════════════════════");
Console.WriteLine(" Assessment Complete!");
Console.WriteLine("═══════════════════════════════════════════════════════");
Console.WriteLine();
Console.WriteLine("📋 Assessment Summary:");
Console.WriteLine($" • Database: {assessment.DatabaseName}");
Console.WriteLine($" • Containers: {assessment.CosmosAnalysis.Containers.Count}");
Console.WriteLine($" • Total Documents: {assessment.CosmosAnalysis.Containers.Sum(c => c.DocumentCount):N0}");
Console.WriteLine($" • Total Size: {assessment.CosmosAnalysis.Containers.Sum(c => c.SizeBytes) / (1024.0 * 1024.0 * 1024.0):F2} GB");
Console.WriteLine();
Console.WriteLine("🎯 Migration Recommendations:");
Console.WriteLine($" • Recommended Platform: {assessment.SqlAssessment.RecommendedPlatform}");
Console.WriteLine($" • Recommended Tier: {assessment.SqlAssessment.RecommendedTier}");
Console.WriteLine($" • Complexity: {assessment.SqlAssessment.Complexity.OverallComplexity}");
Console.WriteLine($" • Estimated Migration Days: {assessment.SqlAssessment.Complexity.EstimatedMigrationDays}");
Console.WriteLine();
Console.WriteLine("🏭 Data Factory Estimates:");
Console.WriteLine($" • Migration Duration: {assessment.DataFactoryEstimate.EstimatedDuration.TotalHours:F1} hours");
Console.WriteLine($" • Estimated Cost: ${assessment.DataFactoryEstimate.EstimatedCostUSD:F2}");
Console.WriteLine($" • Recommended DIUs: {assessment.DataFactoryEstimate.RecommendedDIUs}");
Console.WriteLine();
// Display generated outputs based on options
Console.WriteLine("📊 Generated Outputs:");
if (!options.ProjectOnly)
{
Console.WriteLine(" • Excel reports: Detailed analysis and recommendations");
Console.WriteLine(" • Word summary: Executive overview for stakeholders");
}
if (!options.AssessmentOnly)
{
Console.WriteLine(" • SQL Database projects: Ready for SSDT/SqlPackage deployment");
Console.WriteLine($" • {assessment.SqlAssessment.DatabaseMappings.Count} project(s) in sql-projects/ directory");
}
Console.WriteLine();
Console.WriteLine("📊 Next Steps:");
if (!options.ProjectOnly)
{
Console.WriteLine(" 1. Review the generated Excel report for detailed analysis");
Console.WriteLine(" 2. Share the Word document with stakeholders");
}
if (!options.AssessmentOnly)
{
Console.WriteLine(" 3. Deploy SQL projects using Visual Studio or SqlPackage.exe");
Console.WriteLine(" 4. Test schema with sample data");
}
Console.WriteLine(" 5. Plan migration based on complexity assessment");
Console.WriteLine(" 6. Provision target Azure SQL infrastructure");
Console.WriteLine(" 7. Execute proof-of-concept migration if complexity is high");
Console.WriteLine();
}
private static List<RecommendationItem> GenerateOverallRecommendations(AssessmentResult assessment)
{
var recommendations = new List<RecommendationItem>();
// Platform-specific recommendations
var platformRec = new RecommendationItem
{
Category = "Platform",
Priority = "High",
Title = "Azure SQL Platform Selection",
Description = $"Based on analysis, {assessment.SqlAssessment.RecommendedPlatform} is recommended for optimal cost-performance balance.",
Impact = "Significant impact on migration complexity, cost, and ongoing operations",
ActionItems = new List<string>
{
$"Provision {assessment.SqlAssessment.RecommendedPlatform} with {assessment.SqlAssessment.RecommendedTier} tier",
"Configure networking and security settings",
"Set up monitoring and alerting"
}
};
recommendations.Add(platformRec);
// Complexity-based recommendations
if (assessment.SqlAssessment.Complexity.OverallComplexity == "High")
{
var complexityRec = new RecommendationItem
{
Category = "Migration Strategy",
Priority = "High",
Title = "High Complexity Migration Approach",
Description = "The migration has been assessed as high complexity, requiring careful planning and phased approach.",
Impact = "Risk mitigation for data integrity and minimal downtime",
ActionItems = new List<string>
{
"Conduct proof-of-concept with sample data",
"Plan phased migration approach",
"Prepare comprehensive rollback strategy",
"Schedule extended testing phase"
}
};
recommendations.Add(complexityRec);
}
// Performance recommendations
if (assessment.DataFactoryEstimate.EstimatedDuration.TotalHours > 24)
{
var performanceRec = new RecommendationItem
{
Category = "Performance",
Priority = "Medium",
Title = "Long Migration Duration Optimization",
Description = "Migration estimated to take over 24 hours. Consider optimization strategies.",
Impact = "Reduced migration window and business impact",
ActionItems = new List<string>
{
"Consider parallel migration of containers",
"Optimize Data Factory pipeline settings",
"Schedule migration during maintenance windows",
"Implement incremental migration strategy"
}
};
recommendations.Add(performanceRec);
}
// Cost optimization recommendations
if (assessment.DataFactoryEstimate.EstimatedCostUSD > 500)
{
var costRec = new RecommendationItem
{
Category = "Cost Optimization",
Priority = "Medium",
Title = "Migration Cost Optimization",
Description = "Migration costs are estimated to be significant. Consider optimization opportunities.",
Impact = "Reduced migration costs without compromising quality",
ActionItems = new List<string>
{
"Evaluate self-hosted integration runtime for large data volumes",
"Optimize pipeline parallel copy settings",
"Consider regional data placement strategy",
"Monitor and adjust DIU settings based on actual performance"
}
};
recommendations.Add(costRec);
}
// Index optimization recommendations
var highPriorityIndexes = assessment.SqlAssessment.IndexRecommendations.Count(i => i.Priority <= 2);
if (highPriorityIndexes > 0)
{
var indexRec = new RecommendationItem
{
Category = "Performance",
Priority = "High",
Title = "Index Implementation Strategy",
Description = $"Implement {highPriorityIndexes} high-priority indexes for optimal query performance.",
Impact = "Significant improvement in query performance and user experience",
ActionItems = new List<string>
{
"Create clustered indexes on primary keys first",
"Implement partition key indexes",
"Add composite indexes based on query patterns",
"Monitor index usage and performance impact"
}
};
recommendations.Add(indexRec);
}
// Monitoring recommendations
if (assessment.CosmosAnalysis.MonitoringLimitations.Any())
{
var monitoringRec = new RecommendationItem
{
Category = "Monitoring",
Priority = "Medium",
Title = "Enhanced Monitoring Setup",
Description = "Limited monitoring data was available during assessment. Enhance monitoring for future optimization.",
Impact = "Better insights for ongoing optimization and troubleshooting",
ActionItems = new List<string>
{
"Configure Application Insights for Cosmos DB",
"Set up Log Analytics workspace",
"Implement custom monitoring dashboards",
"Create performance baselines for comparison"
}
};
recommendations.Add(monitoringRec);
}
return recommendations;
}
private static string ExtractAccountNameFromEndpoint(string? endpoint)
{
if (string.IsNullOrEmpty(endpoint))
return "Unknown";
try
{
var uri = new Uri(endpoint);
return uri.Host.Split('.')[0];
}
catch
{
return "Unknown";
}
}
private static CommandLineOptions? ParseCommandLineArguments(string[] args)
{
var options = new CommandLineOptions();
for (int i = 0; i < args.Length; i++)
{
switch (args[i].ToLower())
{
case "--help":
case "-h":
DisplayHelp();
return null;
case "--all-databases":
case "-a":
options.AnalyzeAllDatabases = true;
break;
case "--database":
case "-d":
if (i + 1 < args.Length)
{
options.DatabaseName = args[++i];
}
break;
case "--output":
case "-o":
if (i + 1 < args.Length)
{
options.OutputDirectory = args[++i];
}
break;
case "--auto-discover":
options.AutoDiscoverMonitoring = true;
break;
case "--endpoint":
case "-e":
if (i + 1 < args.Length)
{
options.AccountEndpoint = args[++i];
}
break;
case "--workspace-id":
case "-w":
if (i + 1 < args.Length)
{
options.WorkspaceId = args[++i];
}
break;
case "--assessment-only":
options.AssessmentOnly = true;
break;
case "--project-only":
options.ProjectOnly = true;
break;
case "--test-connection":
options.TestConnection = true;
break;
default:
Console.WriteLine($"Unknown argument: {args[i]}");
DisplayHelp();
return null;
}
}
return options;
}
private static void DisplayHelp()
{
Console.WriteLine();
Console.WriteLine("Cosmos DB to SQL Migration Assessment Tool");
Console.WriteLine();
Console.WriteLine("Usage:");
Console.WriteLine(" CosmosToSqlAssessment [options]");
Console.WriteLine();
Console.WriteLine("Options:");
Console.WriteLine(" -h, --help Show this help message");
Console.WriteLine(" -a, --all-databases Analyze all databases in the Cosmos DB account");
Console.WriteLine(" -d, --database <name> Analyze specific database (overrides config)");
Console.WriteLine(" -e, --endpoint <url> Cosmos DB account endpoint (overrides config)");
Console.WriteLine(" -w, --workspace-id <id> Log Analytics workspace ID for performance metrics");
Console.WriteLine(" -o, --output <path> Output directory for reports (will prompt if not specified)");
Console.WriteLine(" --auto-discover Automatically discover Azure Monitor settings");
Console.WriteLine(" --assessment-only Generate assessment reports only (skip SQL project generation)");
Console.WriteLine(" --project-only Generate SQL projects only (skip assessment reports)");
Console.WriteLine(" --test-connection Test connectivity to Cosmos DB and Azure Monitor");
Console.WriteLine();
Console.WriteLine("Examples:");
Console.WriteLine(" CosmosToSqlAssessment --all-databases");
Console.WriteLine(" CosmosToSqlAssessment --database MyDatabase --output C:\\Reports");
Console.WriteLine(" CosmosToSqlAssessment --endpoint https://myaccount.documents.azure.com:443/");
Console.WriteLine(" CosmosToSqlAssessment --endpoint https://myaccount.documents.azure.com:443/ --all-databases");
Console.WriteLine(" CosmosToSqlAssessment --workspace-id 12345678-1234-1234-1234-123456789012 --all-databases");
Console.WriteLine(" CosmosToSqlAssessment --auto-discover");
Console.WriteLine(" CosmosToSqlAssessment --assessment-only --database MyDatabase");
Console.WriteLine(" CosmosToSqlAssessment --project-only --all-databases");
Console.WriteLine(" CosmosToSqlAssessment --test-connection");
Console.WriteLine();
}
private static async Task<UserInputs?> GetUserInputsAsync(IConfiguration configuration, CommandLineOptions options, ILogger logger)
{
var inputs = new UserInputs();
try
{