Skip to content

Commit 873866d

Browse files
committed
Melhorias e refatoração em várias classes
Adicionadas explicações e comentários em `RefreshSPOLists.cs`, `ActivitiesDQ.cs`, `Context.cs`, `InvoiceRequestDQ.cs`, `TimesheetDQ.cs`, `SPOList.cs`, `SPOUser.cs`, `RefreshSQLLists.cs`, `SQLInteraction.cs` e `ConfigHelper.cs`. A lógica de verificação de argumentos, tratamento de exceções e inicialização de listas foi aprimorada. A modularidade do código foi melhorada com a adição de métodos e a legibilidade foi aumentada através de comentários explicativos.
1 parent 90f6f83 commit 873866d

10 files changed

Lines changed: 664 additions & 284 deletions

File tree

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

Lines changed: 61 additions & 26 deletions
Original file line numberDiff line numberDiff line change
@@ -10,82 +10,98 @@ namespace Bring.SPODataQuality
1010
{
1111
internal class RefreshSPOLists
1212
{
13+
// Main entry point of the application, executed when the program starts
1314
private static void Main(string[] args)
1415
{
1516
try
1617
{
18+
// Print debug information and the current timestamp
1719
Console.WriteLine("DEBUG: Iniciando Main");
1820
Console.WriteLine("CURRENT TIME: " + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"));
1921

22+
// Retrieve SharePoint credentials (username and password) from a configuration source
2023
var (username, password) = ConfigurationReader.GetSharePointCredentials();
21-
SPOUser spoUser = new SPOUser(username, password);
24+
SPOUser spoUser = new SPOUser(username, password); // Create a SharePoint user object
2225
Console.WriteLine("DEBUG: SPOUser criado");
2326

27+
// Initialize two SharePoint list objects and assign the user credentials to them
2428
var list1 = new SPOList();
2529
list1.SPOUser = spoUser;
2630
Console.WriteLine("DEBUG: Primeiro SPOList configurado");
2731

2832
var list2 = new SPOList();
2933
list2.SPOUser = spoUser;
3034
Console.WriteLine("DEBUG: Segundo SPOList configurado");
35+
36+
// Check if command-line arguments are provided
3137
if ((uint)args.Length > 0U)
3238
{
33-
string lower = args[0].ToLower();
39+
string lower = args[0].ToLower(); // Convert the first argument to lowercase
3440
Console.WriteLine("DEBUG: Argumento recebido - " + lower);
3541

36-
if (!(lower == "daily"))
42+
// Decide which update to perform based on the argument
43+
if (lower == "daily")
3744
{
38-
if (lower == "monthly")
39-
{
40-
Console.WriteLine("DEBUG: Executando monthly");
41-
RefreshSQLLists.SPOtoSQLUpdate(false);
42-
}
43-
else
44-
{
45-
Console.WriteLine("Unrecognized argument, please use daily or monthly as the argument");
46-
}
45+
// Perform a daily update from SharePoint to SQL Server
46+
Console.WriteLine("DEBUG: Executando daily");
47+
RefreshSQLLists.SPOtoSQLUpdate(true);
48+
}
49+
else if (lower == "monthly")
50+
{
51+
// Perform a monthly update from SharePoint to SQL Server
52+
Console.WriteLine("DEBUG: Executando monthly");
53+
RefreshSQLLists.SPOtoSQLUpdate(false);
4754
}
4855
else
4956
{
50-
Console.WriteLine("DEBUG: Executando daily");
51-
RefreshSQLLists.SPOtoSQLUpdate(true);
57+
// Handle unrecognized arguments
58+
Console.WriteLine("Unrecognized argument, please use daily or monthly as the argument");
5259
}
5360
}
5461

62+
// Indicate the end of processing
5563
Console.WriteLine("End of requests.");
5664
Console.WriteLine();
5765
}
5866
catch (Exception ex)
5967
{
68+
// Catch and display any errors that occur during execution
6069
Console.WriteLine("An error occurred: " + ex.Message);
6170
}
6271
}
6372

73+
// Method to retrieve and display all lists from a specific SharePoint site
6474
public static void GetAllLists()
6575
{
6676
Console.WriteLine("DEBUG: Entrando em GetAllLists");
77+
// Get SharePoint credentials
6778
var (username, password) = ConfigurationReader.GetSharePointCredentials();
6879
SPOUser spoUser = new SPOUser(username, password);
80+
// Set up a context for the SharePoint site named "seed"
6981
Context context = new Context()
7082
{
7183
Site = "seed",
7284
SPOUser = spoUser
7385
};
86+
// Iterate through all lists in the SharePoint site
7487
foreach (List allList in (ClientObjectCollection<List>)context.GetAllLists())
7588
{
7689
Console.WriteLine("DEBUG: Carregando lista - " + allList.Title);
90+
// Load the IsSystemList property to determine if the list is a system list
7791
context.Ctx.Load<List>(allList, new Expression<Func<List, object>>[1]
7892
{
7993
(Expression<Func<List, object>>) (l => (object) l.IsSystemList)
8094
});
81-
context.Ctx.ExecuteQuery();
95+
context.Ctx.ExecuteQuery(); // Execute the query to retrieve the data
8296
Console.WriteLine("List Name: " + allList.Title + "; is: " + allList.IsSystemList.ToString());
8397
}
8498
}
8599

100+
// Debugging method to inspect the properties of a specific SharePoint list
86101
private static void SPODebug(string listName, string ctxURL, SPOUser user)
87102
{
88103
Console.WriteLine("DEBUG: Entrando em SPODebug");
104+
// Create a SharePoint list object with a CAML query limiting to 1 item
89105
SPOList spoList = new SPOList
90106
{
91107
Name = listName,
@@ -95,78 +111,94 @@ private static void SPODebug(string listName, string ctxURL, SPOUser user)
95111
};
96112

97113
Console.WriteLine("DEBUG: Executando Build");
98-
spoList.Build();
114+
spoList.Build(); // Build the list to load its data
99115

100116
Console.WriteLine("DEBUG: Executando PropsToString");
117+
// Print the properties of the first item in the list for debugging
101118
spoList.PropsToString(spoList.ItemCollection[0]);
102119
}
103120

121+
// Method to synchronize data from a source SharePoint list to a destination list
104122
private static void RefreshListsSPO(SPOList sourceList, SPOList destList)
105123
{
106124
try
107125
{
108126
Console.WriteLine("DEBUG: Iniciando RefreshListsSPO");
109127

128+
// Build the source list to load its data
110129
sourceList.Build();
111130
Console.WriteLine("DEBUG: sourceList.Build concluído");
112131

132+
// Build the destination list to load its data
113133
destList.Build();
114134
Console.WriteLine("DEBUG: destList.Build concluído");
115135

116-
int num1 = 0;
117-
int num2 = 0;
136+
int num1 = 0; // Last ID in source list
137+
int num2 = 0; // Last ID in destination list
118138

139+
// Get the field mappings between the source and destination lists
119140
string[,] actualFields = GetActualFields(sourceList, destList);
120141
Console.WriteLine("DEBUG: Campos obtidos");
121142

143+
// Determine the last ID in the source list
122144
if ((uint)sourceList.ItemCollection.Count > 0U)
123145
num1 = (int)sourceList.ItemCollection[sourceList.ItemCollection.Count - 1]["ID"];
146+
// Determine the last ID in the destination list
124147
if ((uint)destList.ItemCollection.Count > 0U)
125148
num2 = (int)destList.ItemCollection[destList.ItemCollection.Count - 1]["ID"];
126149

150+
// If the destination list has fewer items, add new items to match the source
127151
if (num2 < num1)
128152
{
129153
Console.WriteLine("DEBUG: Adicionando novos itens");
130154
do
131155
{
132-
destList.AddItem();
156+
destList.AddItem(); // Add a new item to the destination list
133157
++num2;
134158
}
135159
while (num2 < num1);
136160

137161
Console.WriteLine("Adding new items...");
138-
destList.Update();
162+
destList.Update(); // Update the destination list with the new items
139163
Console.WriteLine("Done adding items.");
140164
}
141165

166+
// Update existing items in the destination list with data from the source
142167
for (int index1 = 0; index1 < sourceList.ItemCollection.Count; ++index1)
143168
{
144169
int id = (int)sourceList.ItemCollection[index1]["ID"];
170+
// Copy field values from source to destination based on the field mappings
145171
for (int index2 = 0; index2 < actualFields.Length / 2; ++index2)
146172
destList.ItemCollection.GetById(id)[actualFields[index2, 0]] = sourceList.ItemCollection[index1][actualFields[index2, 1]];
147-
destList.ItemCollection.GetById(id).Update();
173+
destList.ItemCollection.GetById(id).Update(); // Update the item in the destination list
148174
}
149175

176+
// Execute the query to apply all changes to the SharePoint site
150177
destList.Ctx.ExecuteQuery();
151178
Console.WriteLine(sourceList.Site + " " + sourceList.Name + " -> " + destList.Site + " " + destList.Name + ": Done!");
152179
}
153180
catch (Exception ex)
154181
{
182+
// Catch and display any errors during the sync process
155183
Console.WriteLine("ERROR in RefreshListsSPO: " + ex.Message);
156184
}
157185
}
158186

187+
// Helper method to create a mapping of fields between two lists based on their titles
159188
private static string[,] GetActualFields(SPOList listone, SPOList listtwo)
160189
{
161190
Console.WriteLine("DEBUG: Entrando em GetActualFields");
162191

192+
// Get fields from both lists
163193
List<Field> fields1 = GetFields(listone);
164194
List<Field> fields2 = GetFields(listtwo);
165195

196+
// Create a 2D array to store the field mappings (internal names)
166197
string[,] strArray = new string[fields1.Count, 2];
167198
int index1 = 0;
168199
int index2 = 0;
169200

201+
// Match fields by title and store their internal names
170202
foreach (Field field1 in fields1)
171203
{
172204
Field field2;
@@ -175,36 +207,39 @@ private static void RefreshListsSPO(SPOList sourceList, SPOList destList)
175207
field2 = fields2[index2];
176208
if (field1.Title == field2.Title)
177209
{
178-
strArray[index1, 0] = field2.InternalName;
179-
strArray[index1, 1] = field1.InternalName;
210+
strArray[index1, 0] = field2.InternalName; // Destination field
211+
strArray[index1, 1] = field1.InternalName; // Source field
180212
Console.WriteLine($"DEBUG: Match found - {field1.Title}");
181213
}
182214
++index2;
183215
}
184216
while (field1.Title != field2.Title && index2 < fields2.Count);
185217

186218
++index1;
187-
index2 = 0;
219+
index2 = 0; // Reset index2 for the next field
188220
}
189221

190-
return strArray;
222+
return strArray; // Return the field mappings
191223
}
192224

225+
// Helper method to retrieve fields from a SharePoint list, excluding base type fields except "Title"
193226
private static List<Field> GetFields(SPOList list)
194227
{
195228
Console.WriteLine("DEBUG: Entrando em GetFields");
196229

197230
List<Field> fieldList = new List<Field>();
231+
// Iterate through all fields in the list
198232
foreach (Field field in (ClientObjectCollection<Field>)list.Fields)
199233
{
234+
// Include fields that are not from the base type or are the "Title" field
200235
if (!field.FromBaseType || field.InternalName == "Title")
201236
{
202237
fieldList.Add(field);
203238
Console.WriteLine($"DEBUG: Campo adicionado - {field.Title}");
204239
}
205240
}
206241

207-
return fieldList;
242+
return fieldList; // Return the list of fields
208243
}
209244
}
210245
}
Lines changed: 51 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -1,34 +1,57 @@
1-
// Decompiled with JetBrains decompiler
2-
// Type: Bring.Sharepoint.ActivitiesDQ
3-
// Assembly: ConsoleApp1, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null
4-
// MVID: 2529ACA9-9F81-4C49-8E47-E8B02D261367
5-
// Assembly location: C:\Users\KEVIN\Desktop\Visual Studio\SPtoSP\ConsoleApp1.exe
6-
7-
using Microsoft.SharePoint.Client;
1+
using Microsoft.SharePoint.Client;
82

93
namespace Bring.Sharepoint
104
{
11-
internal class ActivitiesDQ
12-
{
13-
public SPOUser Me { get; set; }
14-
15-
public bool UpdateIDs()
5+
/// <summary>
6+
/// Handles backfilling the '_OpportunityID' field on 'activities' items
7+
/// when it is currently null, by copying the value from 'OpportunityID'.
8+
/// </summary>
9+
internal class ActivitiesDQ
1610
{
17-
string str = "<View><Query><Where><IsNull><FieldRef Name ='_OpportunityID' /></IsNull></Where></Query></View>";
18-
SPOList spoList1 = new SPOList();
19-
spoList1.Name = "activities";
20-
spoList1.Site = "wolf";
21-
spoList1.SPOUser = this.Me;
22-
spoList1.CAMLQuery = str;
23-
SPOList spoList2 = spoList1;
24-
spoList2.Build();
25-
foreach (ListItem listItem in (ClientObjectCollection<ListItem>) spoList2.ItemCollection)
26-
{
27-
listItem["_OpportunityID"] = listItem["OpportunityID"];
28-
listItem.Update();
29-
}
30-
spoList2.Ctx.ExecuteQuery();
31-
return true;
11+
/// <summary>
12+
/// The current SharePoint user context, used for list operations.
13+
/// </summary>
14+
public SPOUser Me { get; set; }
15+
16+
/// <summary>
17+
/// Queries the 'activities' list for items where '_OpportunityID' is null,
18+
/// then updates each item's '_OpportunityID' field to match 'OpportunityID'.
19+
/// </summary>
20+
/// <returns>Always returns true if execution completes without exception.</returns>
21+
public bool UpdateIDs()
22+
{
23+
// Define a CAML query to find items lacking the custom _OpportunityID field
24+
string camlQuery =
25+
"<View>"
26+
+ "<Query><Where><IsNull>"
27+
+ "<FieldRef Name='_OpportunityID' />"
28+
+ "</IsNull></Where></Query>"
29+
+ "</View>";
30+
31+
// Initialize the SPOList wrapper for the 'activities' list
32+
var activitiesList = new SPOList
33+
{
34+
Name = "activities",
35+
Site = "wolf",
36+
SPOUser = this.Me,
37+
CAMLQuery = camlQuery
38+
};
39+
40+
// Retrieve matching items from SharePoint
41+
activitiesList.Build();
42+
43+
// Iterate through each item, copying OpportunityID into _OpportunityID
44+
foreach (ListItem item in activitiesList.ItemCollection)
45+
{
46+
// Copy the existing 'OpportunityID' value into the '_OpportunityID' field
47+
item["_OpportunityID"] = item["OpportunityID"];
48+
item.Update();
49+
}
50+
51+
// Commit all pending updates to SharePoint in a single batch
52+
activitiesList.Ctx.ExecuteQuery();
53+
54+
return true;
55+
}
3256
}
33-
}
3457
}

0 commit comments

Comments
 (0)