Skip to content

Commit fbc6573

Browse files
committed
Adiciona suporte a conexão SQL e traduz mensagens de depuração
Novas importações foram adicionadas, incluindo `using System.Data.SqlClient;`, para permitir a conexão com o SQL Server. Mensagens de depuração foram traduzidas do português para o inglês para melhorar a consistência. Uma nova função `TestSQLConnection` foi implementada para testar a conexão com o SQL Server antes da execução do programa, incluindo verificações de permissões e mensagens de erro detalhadas. Métodos como `GetAllLists` também foram atualizados para refletir as novas mensagens de depuração. O código foi modificado para melhorar a legibilidade e a manutenção, mantendo a funcionalidade original.
1 parent 3a87588 commit fbc6573

1 file changed

Lines changed: 92 additions & 22 deletions

File tree

‎SPOtoSQL-Snapshots/ConsoleApp1/SPODataQuality/RefreshSPOLists.cs‎

Lines changed: 92 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@
55
using System;
66
using System.Collections.Generic;
77
using System.Linq.Expressions;
8+
using System.Data.SqlClient;
89

910
namespace Bring.SPODataQuality
1011
{
@@ -16,42 +17,43 @@ private static void Main(string[] args)
1617
try
1718
{
1819
// Print debug information and the current timestamp
19-
Console.WriteLine("DEBUG: Iniciando Main");
20+
Console.WriteLine("DEBUG: Starting Main");
2021
Console.WriteLine("CURRENT TIME: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
2122

23+
// Test SQL connection before proceeding
24+
TestSQLConnection();
25+
2226
// Retrieve SharePoint credentials (username and password) from a configuration source
2327
var (username, password) = ConfigurationReader.GetSharePointCredentials();
24-
Console.WriteLine($"Testing Conection with the username: {username}"); // Debug
25-
Console.WriteLine($"Testing Conection with the password: {password}"); // Debug
2628
SPOUser spoUser = new SPOUser(username, password); // Create a SharePoint user object
27-
Console.WriteLine("DEBUG: SPOUser criado"); // When Username and Password are filled correctly, this line will be printed
29+
Console.WriteLine("DEBUG: SPOUser created"); // When Username and Password are filled correctly, this line will be printed
2830

2931
// Initialize two SharePoint list objects and assign the user credentials to them
3032
var list1 = new SPOList();
3133
list1.SPOUser = spoUser;
32-
Console.WriteLine("DEBUG: Primeiro SPOList configurado");
34+
Console.WriteLine("DEBUG: First SPOList configured");
3335

3436
var list2 = new SPOList();
3537
list2.SPOUser = spoUser;
36-
Console.WriteLine("DEBUG: Segundo SPOList configurado");
38+
Console.WriteLine("DEBUG: Second SPOList configured");
3739

3840
// Check if command-line arguments are provided
3941
if ((uint)args.Length > 0U)
4042
{
4143
string lower = args[0].ToLower(); // Convert the first argument to lowercase
42-
Console.WriteLine("DEBUG: Argumento recebido - " + lower);
44+
Console.WriteLine("DEBUG: Received argument - " + lower);
4345

4446
// Decide which update to perform based on the argument
4547
if (lower == "daily")
4648
{
4749
// Perform a daily update from SharePoint to SQL Server
48-
Console.WriteLine("DEBUG: Executando daily");
50+
Console.WriteLine("DEBUG: Executing daily");
4951
RefreshSQLLists.SPOtoSQLUpdate(true);
5052
}
5153
else if (lower == "monthly")
5254
{
5355
// Perform a monthly update from SharePoint to SQL Server
54-
Console.WriteLine("DEBUG: Executando monthly");
56+
Console.WriteLine("DEBUG: Executing monthly");
5557
RefreshSQLLists.SPOtoSQLUpdate(false);
5658
}
5759
else
@@ -69,13 +71,81 @@ private static void Main(string[] args)
6971
{
7072
// Catch and display any errors that occur during execution
7173
Console.WriteLine("An error occurred: " + ex.Message);
74+
Console.WriteLine("Stack Trace: " + ex.StackTrace);
7275
}
7376
}
7477

78+
private static void TestSQLConnection()
79+
{
80+
Console.WriteLine("Testing SQL Server connection...");
81+
try
82+
{
83+
string connectionString = ConfigurationReader.GetSqlConnectionString();
84+
Console.WriteLine($"Attempting to connect to SQL server...");
85+
86+
using (var connection = new SqlConnection(connectionString))
87+
{
88+
try // Nova verificação específica para VPN
89+
{
90+
connection.Open();
91+
}
92+
catch (SqlException ex) when (ex.Number == -1 || ex.Number == 10060 || ex.Number == 0 || ex.Number == 53)
93+
{
94+
Console.WriteLine("ERROR: Unable to connect to the SQL Server.");
95+
Console.WriteLine("Please check if your VPN connection is active and try again.");
96+
Console.WriteLine($"Technical details: {ex.Message}");
97+
Console.WriteLine("Press any key to exit...");
98+
Console.ReadKey();
99+
Environment.Exit(1);
100+
}
101+
102+
Console.WriteLine($"Server: {connection.DataSource}");
103+
Console.WriteLine($"Database: {connection.Database}");
104+
Console.WriteLine("SQL connection established successfully!");
105+
106+
// Basic permissions test
107+
using (var command = connection.CreateCommand())
108+
{
109+
// SELECT test
110+
command.CommandText = "SELECT COUNT(*) FROM INFORMATION_SCHEMA.TABLES";
111+
int tableCount = (int)command.ExecuteScalar();
112+
Console.WriteLine($"Number of tables in database: {tableCount}");
113+
114+
// CREATE TABLE permission test
115+
try
116+
{
117+
command.CommandText = "CREATE TABLE #TempTest (ID int); DROP TABLE #TempTest;";
118+
command.ExecuteNonQuery();
119+
Console.WriteLine("CREATE TABLE permission: OK");
120+
}
121+
catch (SqlException ex)
122+
{
123+
Console.WriteLine($"Warning: No CREATE TABLE permission: {ex.Message}");
124+
}
125+
}
126+
}
127+
}
128+
// If the connection is not working, catch the exception and print the error message
129+
catch (SqlException ex)
130+
{
131+
Console.WriteLine($"SQL connection error: {ex.Message}");
132+
Console.WriteLine($"Error number: {ex.Number}");
133+
Console.WriteLine($"State: {ex.State}");
134+
Console.WriteLine($"Procedure: {ex.Procedure}");
135+
throw; // Re-throw to stop execution
136+
}
137+
catch (Exception ex)
138+
{
139+
Console.WriteLine($"General error testing SQL connection: {ex.Message}");
140+
throw;
141+
}
142+
}
143+
144+
75145
// Method to retrieve and display all lists from a specific SharePoint site
76146
public static void GetAllLists()
77147
{
78-
Console.WriteLine("DEBUG: Entrando em GetAllLists");
148+
Console.WriteLine("DEBUG: Entering GetAllLists");
79149
// Get SharePoint credentials
80150
var (username, password) = ConfigurationReader.GetSharePointCredentials();
81151
SPOUser spoUser = new SPOUser(username, password);
@@ -88,7 +158,7 @@ public static void GetAllLists()
88158
// Iterate through all lists in the SharePoint site
89159
foreach (List allList in (ClientObjectCollection<List>)context.GetAllLists())
90160
{
91-
Console.WriteLine("DEBUG: Carregando lista - " + allList.Title);
161+
Console.WriteLine("DEBUG: Loading list - " + allList.Title);
92162
// Load the IsSystemList property to determine if the list is a system list
93163
context.Ctx.Load<List>(allList, new Expression<Func<List, object>>[1]
94164
{
@@ -102,7 +172,7 @@ public static void GetAllLists()
102172
// Debugging method to inspect the properties of a specific SharePoint list
103173
private static void SPODebug(string listName, string ctxURL, SPOUser user)
104174
{
105-
Console.WriteLine("DEBUG: Entrando em SPODebug");
175+
Console.WriteLine("DEBUG: Entering SPODebug");
106176
// Create a SharePoint list object with a CAML query limiting to 1 item
107177
SPOList spoList = new SPOList
108178
{
@@ -112,10 +182,10 @@ private static void SPODebug(string listName, string ctxURL, SPOUser user)
112182
CAMLQuery = "<View><RowLimit>1</RowLimit></View>"
113183
};
114184

115-
Console.WriteLine("DEBUG: Executando Build");
185+
Console.WriteLine("DEBUG: Executing Build");
116186
spoList.Build(); // Build the list to load its data
117187

118-
Console.WriteLine("DEBUG: Executando PropsToString");
188+
Console.WriteLine("DEBUG: Executing PropsToString");
119189
// Print the properties of the first item in the list for debugging
120190
spoList.PropsToString(spoList.ItemCollection[0]);
121191
}
@@ -125,22 +195,22 @@ private static void RefreshListsSPO(SPOList sourceList, SPOList destList)
125195
{
126196
try
127197
{
128-
Console.WriteLine("DEBUG: Iniciando RefreshListsSPO");
198+
Console.WriteLine("DEBUG: Starting RefreshListsSPO");
129199

130200
// Build the source list to load its data
131201
sourceList.Build();
132-
Console.WriteLine("DEBUG: sourceList.Build concluído");
202+
Console.WriteLine("DEBUG: sourceList.Build completed");
133203

134204
// Build the destination list to load its data
135205
destList.Build();
136-
Console.WriteLine("DEBUG: destList.Build concluído");
206+
Console.WriteLine("DEBUG: destList.Build completed");
137207

138208
int num1 = 0; // Last ID in source list
139209
int num2 = 0; // Last ID in destination list
140210

141211
// Get the field mappings between the source and destination lists
142212
string[,] actualFields = GetActualFields(sourceList, destList);
143-
Console.WriteLine("DEBUG: Campos obtidos");
213+
Console.WriteLine("DEBUG: Fields obtained");
144214

145215
// Determine the last ID in the source list
146216
if ((uint)sourceList.ItemCollection.Count > 0U)
@@ -152,7 +222,7 @@ private static void RefreshListsSPO(SPOList sourceList, SPOList destList)
152222
// If the destination list has fewer items, add new items to match the source
153223
if (num2 < num1)
154224
{
155-
Console.WriteLine("DEBUG: Adicionando novos itens");
225+
Console.WriteLine("DEBUG: Adding new items");
156226
do
157227
{
158228
destList.AddItem(); // Add a new item to the destination list
@@ -189,7 +259,7 @@ private static void RefreshListsSPO(SPOList sourceList, SPOList destList)
189259
// Helper method to create a mapping of fields between two lists based on their titles
190260
private static string[,] GetActualFields(SPOList listone, SPOList listtwo)
191261
{
192-
Console.WriteLine("DEBUG: Entrando em GetActualFields");
262+
Console.WriteLine("DEBUG: Entering GetActualFields");
193263

194264
// Get fields from both lists
195265
List<Field> fields1 = GetFields(listone);
@@ -227,7 +297,7 @@ private static void RefreshListsSPO(SPOList sourceList, SPOList destList)
227297
// Helper method to retrieve fields from a SharePoint list, excluding base type fields except "Title"
228298
private static List<Field> GetFields(SPOList list)
229299
{
230-
Console.WriteLine("DEBUG: Entrando em GetFields");
300+
Console.WriteLine("DEBUG: Entering GetFields");
231301

232302
List<Field> fieldList = new List<Field>();
233303
// Iterate through all fields in the list
@@ -237,7 +307,7 @@ private static List<Field> GetFields(SPOList list)
237307
if (!field.FromBaseType || field.InternalName == "Title")
238308
{
239309
fieldList.Add(field);
240-
Console.WriteLine($"DEBUG: Campo adicionado - {field.Title}");
310+
Console.WriteLine($"DEBUG: Field added - {field.Title}");
241311
}
242312
}
243313

0 commit comments

Comments
 (0)