-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathForm1.cs
More file actions
293 lines (258 loc) · 10.4 KB
/
Copy pathForm1.cs
File metadata and controls
293 lines (258 loc) · 10.4 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
using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Windows.Forms;
using Microsoft.Extensions.Options;
using System.Text.Json.Serialization;
// ODX Proxy Client Libraries
using OdxProxy.Client;
using OdxProxy.Client.Configuration;
using OdxProxy.Client.Models;
// WireMock - Used for local testing/simulating Odoo responses
using WireMock.RequestBuilders;
using WireMock.ResponseBuilders;
using WireMock.Server;
namespace ODXProxyNETDemo
{
/// <summary>
/// Main application window demonstrating Odoo integration via ODX Proxy.
/// Supports Partner/Product retrieval and record updates.
/// </summary>
public partial class Form1 : Form
{
// --- CONSTANTS ---
private const string PROXY_GATEWAY_URL = "https://gateway.odxproxy.io";
private const string MY_ODOO_URL = "odoo-url";
private const string MY_DATABASE = "db-name";
private const string GATEWAY_KEY = "odxproxy-api-key";
// --- PRIVATE FIELDS ---
private WireMockServer _server; // Local mock server for testing
private OdxProxyClient _client; // The main gateway client
public Form1()
{
InitializeComponent();
// Start with data buttons disabled until "Connect" is successful
btnLoad.Enabled = false;
btnLoadProd.Enabled = false;
}
/// <summary>
/// Configures a local mock server to simulate Odoo responses.
/// Useful for UI design without hitting the real live database.
/// </summary>
private void SetupMockServer()
{
_server = WireMockServer.Start();
// Mock for Partner 'search_read' requests
_server
.Given(Request.Create().WithPath("/api/odoo/execute").UsingPost())
.RespondWith(Response.Create()
.WithStatusCode(200)
.WithHeader("Content-Type", "application/json")
.WithBody(@"{
""jsonrpc"": ""2.0"",
""result"": [
{ ""id"": 1, ""name"": ""Test Partner (WireMock)"" },
{ ""id"": 2, ""name"": ""Sample Customer"" }
]
}"));
}
/// <summary>
/// Initializes the ODXProxyClient with credentials from the UI textboxes.
/// </summary>
private void btnConnect_Click(object sender, EventArgs e)
{
UpdateStatus("Connecting...", Color.Black);
try
{
// 1. Basic UI Validation
if (string.IsNullOrWhiteSpace(txtUserId.Text) || string.IsNullOrWhiteSpace(txtApiKey.Text))
{
UpdateStatus("⚠️ Error: Missing User ID or API Key", Color.Red);
return;
}
int userId = int.Parse(txtUserId.Text);
string userKey = txtApiKey.Text;
// 2. Define the Odoo Instance (Where the data actually lives)
var instance = new OdxInstanceInfo(MY_ODOO_URL, userId, MY_DATABASE, userKey);
// 3. Configure Proxy Options (The Gateway settings)
var options = new OdxProxyOptions
{
GatewayUrl = PROXY_GATEWAY_URL,
ApiKey = GATEWAY_KEY,
DefaultInstance = instance
};
// 4. Instantiate the Client using Source-Generated JSON Context for high performance
_client = new OdxProxyClient(
new HttpClient(),
Microsoft.Extensions.Options.Options.Create(options),
TestJsonContext.Default
);
// 5. Enable data operations
btnLoad.Enabled = true;
btnLoadProd.Enabled = true;
UpdateStatus("✅ Connected to Odoo successfully.", Color.DarkGreen);
}
catch (FormatException)
{
UpdateStatus("⚠️ Error: User ID must be a number.", Color.Red);
}
catch (Exception ex)
{
UpdateStatus("❌ Connection Error: " + ex.Message, Color.Red);
}
}
/// <summary>
/// Fetches the first 10 Partner records from Odoo and displays them in the grid.
/// </summary>
private async void btnLoad_Click(object sender, EventArgs e)
{
try
{
btnLoad.Enabled = false;
btnLoad.Text = "Fetching...";
// Call the 'search_read' method for the res.partner model
var response = await _client.SearchReadAsync<TestPartner>(
model: "res.partner",
domain: new List<object>(), // Empty list = fetch all
keyword: new OdxClientKeywordRequest { Limit = 10 }
);
if (response.Result != null)
{
dgPartners.DataSource = response.Result;
}
}
catch (Exception ex)
{
MessageBox.Show("Error loading partners: " + ex.Message);
}
finally
{
btnLoad.Enabled = true;
btnLoad.Text = "Load Partners";
}
}
/// <summary>
/// Fetches the first 20 Product templates and displays them in the products grid.
/// </summary>
private async void btnLoadProd_Click(object sender, EventArgs e)
{
try
{
btnLoadProd.Enabled = false;
btnLoadProd.Text = "Fetching Products...";
var response = await _client.SearchReadAsync<TestProduct>(
model: "product.template",
domain: new List<object>(),
keyword: new OdxClientKeywordRequest { Limit = 20 }
);
if (response.Result != null)
{
dgProducts.DataSource = response.Result;
UpdateStatus($"✅ Loaded {response.Result.Count} products.", Color.DarkGreen);
}
}
catch (Exception ex)
{
UpdateStatus("❌ Product Load Error: " + ex.Message, Color.Red);
}
finally
{
btnLoadProd.Enabled = true;
btnLoadProd.Text = "Load Products";
}
}
/// <summary>
/// Updates the 'Name' of the selected partner in Odoo.
/// This demonstrates the 'Write' (update) capability of the ODX Proxy.
/// </summary>
private async void btnUpdateName_Click(object sender, EventArgs e)
{
if (dgPartners.CurrentRow == null)
{
MessageBox.Show("Please select a partner from the list first.");
return;
}
// Extract the data object from the selected row
var selectedPartner = (TestPartner)dgPartners.CurrentRow.DataBoundItem;
string newName = txtNewName.Text;
if (string.IsNullOrWhiteSpace(newName))
{
UpdateStatus("⚠️ Please enter a new name.", Color.OrangeRed);
return;
}
try
{
btnUpdateName.Enabled = false;
UpdateStatus("Updating Odoo...", Color.Black);
// Odoo 'write' expects a dictionary of field_name -> value
var valuesToUpdate = new Dictionary<string, object>
{
{ "name", newName }
};
// Execute the update
var response = await _client.WriteAsync(
model: "res.partner",
ids: new List<int> { selectedPartner.Id },
values: valuesToUpdate
);
if (response.Result)
{
UpdateStatus("✅ Name updated successfully!", Color.DarkGreen);
// Refresh the grid to reflect changes
btnLoad_Click(null, null);
}
}
catch (Exception ex)
{
MessageBox.Show("Update Failed: " + ex.Message);
}
finally
{
btnUpdateName.Enabled = true;
}
}
/// <summary>
/// When a cell is clicked, populate the Edit textbox with the partner's current name.
/// </summary>
private void dgPartners_CellClick(object sender, DataGridViewCellEventArgs e)
{
if (dgPartners.CurrentRow != null)
{
var selected = (TestPartner)dgPartners.CurrentRow.DataBoundItem;
txtNewName.Text = selected.Name;
}
}
/// <summary>
/// Helper to update the UI status label with color coding.
/// </summary>
private void UpdateStatus(string message, Color color)
{
lblStatus.Text = message;
lblStatus.ForeColor = color;
}
protected override void OnFormClosing(FormClosingEventArgs e)
{
_server?.Stop(); // Ensure mock server is released
base.OnFormClosing(e);
}
}
// --- DATA MODELS ---
/// <summary> Model representing a simplified Odoo Partner (res.partner) </summary>
public record TestPartner(int Id, string Name);
/// <summary> Model representing a simplified Odoo Product (product.template) </summary>
public record TestProduct(int Id, string Name, double ListPrice);
/// <summary>
/// Source-Generated JSON Context.
/// This is required for AOT (Ahead-Of-Time) compatibility and high-performance
/// serialization in modern .NET. It tells the compiler exactly how to turn
/// Odoo's JSON into our C# Records.
/// </summary>
[JsonSourceGenerationOptions(PropertyNamingPolicy = JsonKnownNamingPolicy.CamelCase)]
[JsonSerializable(typeof(List<TestPartner>))]
[JsonSerializable(typeof(OdxServerResponse<List<TestPartner>>))]
[JsonSerializable(typeof(List<TestProduct>))]
[JsonSerializable(typeof(OdxServerResponse<List<TestProduct>>))]
[JsonSerializable(typeof(Dictionary<string, object>))]
[JsonSerializable(typeof(OdxServerResponse<bool>))]
public partial class TestJsonContext : JsonSerializerContext { }
}