PageRenderTime 25ms CodeModel.GetById 28ms RepoModel.GetById 1ms app.codeStats 0ms

/jtl.ConnectorTester/Form1.cs

https://gitlab.com/sicbb/connector-tester
C# | 805 lines | 681 code | 109 blank | 15 comment | 60 complexity | 335f5dc48ff86a8f86f3dfbc8340af1e MD5 | raw file
  1. using System.Collections;
  2. using System.Collections.Generic;
  3. using System.Globalization;
  4. using System.Linq;
  5. using System.Reactive.Linq;
  6. using System.Threading.Tasks;
  7. using jtl.ConnectorTester.Core;
  8. using jtl.ConnectorTester.Core.Model;
  9. using jtl.ConnectorTester.Core.Rpc;
  10. using jtl.ConnectorTester.Model;
  11. using jtl.ConnectorTester.Model.Interface;
  12. using Newtonsoft.Json;
  13. using System;
  14. using System.IO;
  15. using System.Windows.Forms;
  16. using Newtonsoft.Json.Linq;
  17. using Prounion.Json;
  18. namespace jtl.ConnectorTester
  19. {
  20. public partial class Form1 : Form
  21. {
  22. public enum Action
  23. {
  24. Pull,
  25. Push,
  26. Delete,
  27. Commit,
  28. FeatureMatrix,
  29. ConnectorStats,
  30. Stats,
  31. SetStatus,
  32. Validate,
  33. Identify,
  34. Finish,
  35. Clear,
  36. Init,
  37. Ack,
  38. Debug,
  39. Logs
  40. }
  41. private Setting _setting;
  42. public Connector Connector;
  43. public string Url = String.Empty;
  44. public string Token = String.Empty;
  45. private PushForm _modelForm;
  46. private IEnumerable _modelList;
  47. public Form1()
  48. {
  49. InitializeComponent();
  50. _setting = new Setting();
  51. _setting.Load();
  52. if (_setting.Resolution.Width > 0 && _setting.Resolution.Height > 0)
  53. {
  54. Width = _setting.Resolution.Width;
  55. Height = _setting.Resolution.Height;
  56. }
  57. var source = rebindEndpointDataSource();
  58. if (source.Current != null)
  59. {
  60. source.Position = _setting.EndpointIndex;
  61. txtToken.Text = (source.Current as Endpoint).Token;
  62. }
  63. //Text += string.Format(" {0}", Assembly.GetExecutingAssembly().GetName().Version);
  64. Text += string.Format(" {0}", Application.ProductVersion);
  65. Connector = new Connector();
  66. cmbType.DataSource = MainModel.MainList;
  67. //cboxUrl.SelectedIndex = _setting.EndpointIndex;
  68. //txtToken.Text = @"5d084502b4de4e25a16be29";
  69. cbAction.DataSource = Enum.GetValues(typeof (Action));
  70. Connector.CalltimeMeasured.ObserveOn(this).Subscribe(e =>
  71. {
  72. lblWatch.Text = string.Format("{0} Milliseconds", e);
  73. });
  74. }
  75. private void btnSession_Click(object sender, EventArgs e)
  76. {
  77. Url = cboxUrl.Text;
  78. Token = txtToken.Text;
  79. DoAction(() => Connector.GetSessionAsync(Url, Token), r =>
  80. {
  81. if (r.Error != null)
  82. {
  83. MessageBox.Show(string.Format("Error: {0} - {1}", r.Error.Code, r.Error.Message));
  84. }
  85. var session = ((JObject) r.Result).ToObject<Session>();
  86. Connector.SessionId = session.SessionId;
  87. rtbResponse.Text = "";
  88. if (Connector.SessionId.Length <= 0) return;
  89. SetWorkStatus(true);
  90. rtbResponse.Text = string.Format("SessionId: {0}", Connector.SessionId);
  91. });
  92. }
  93. #region Actions
  94. private void DoWork(Action action)
  95. {
  96. try
  97. {
  98. if (action != Action.Validate && action != Action.Push && action != Action.Delete && action != Action.Ack)
  99. {
  100. rtbResponse.Text = string.Empty;
  101. }
  102. switch (action)
  103. {
  104. case Action.Push:
  105. Push();
  106. break;
  107. case Action.Pull:
  108. Pull();
  109. break;
  110. case Action.Delete:
  111. Delete();
  112. break;
  113. case Action.SetStatus:
  114. SetStatus();
  115. break;
  116. case Action.FeatureMatrix:
  117. Feature();
  118. break;
  119. case Action.ConnectorStats:
  120. ConnectorStats();
  121. break;
  122. case Action.Stats:
  123. Stats();
  124. break;
  125. case Action.Identify:
  126. Identify();
  127. break;
  128. case Action.Finish:
  129. Finish();
  130. break;
  131. case Action.Commit:
  132. try
  133. {
  134. Commit();
  135. }
  136. catch (Exception exc)
  137. {
  138. Connector.Picture = null;
  139. throw new Exception(exc.Message);
  140. }
  141. break;
  142. case Action.Validate:
  143. Validate();
  144. break;
  145. case Action.Clear:
  146. Clear();
  147. break;
  148. case Action.Init:
  149. Init();
  150. break;
  151. case Action.Ack:
  152. AckFromJson();
  153. break;
  154. case Action.Debug:
  155. Debug();
  156. break;
  157. case Action.Logs:
  158. Logs();
  159. break;
  160. }
  161. }
  162. catch (Exception exc)
  163. {
  164. if (!IsSessionValid(exc.Message))
  165. {
  166. Connector.SessionId = string.Empty;
  167. SetWorkStatus(false);
  168. }
  169. Connector.Picture = null;
  170. rtbResponse.Text = exc.Message;
  171. }
  172. }
  173. private void Init()
  174. {
  175. DoAction(() => Connector.InitAsync(Url), res =>
  176. {
  177. rtbResponse.Text = res.ToString();
  178. });
  179. }
  180. private async void DoAction(Func<Task<RpcResponse>> connectorCall, Action<RpcResponse> guiAction)
  181. {
  182. try
  183. {
  184. var response = await connectorCall();
  185. guiAction(response);
  186. }
  187. catch (Exception e)
  188. {
  189. if (!IsSessionValid(e.Message))
  190. {
  191. Connector.SessionId = string.Empty;
  192. SetWorkStatus(false);
  193. }
  194. Connector.Picture = null;
  195. rtbResponse.Text = e.Message;
  196. }
  197. }
  198. private void Clear()
  199. {
  200. DoAction(() => Connector.ClearLinkerAsync(Url), res =>
  201. {
  202. rtbResponse.Text += res.ToString();
  203. });
  204. }
  205. private void Push()
  206. {
  207. var list = MainModel.DeserializeList(cmbType.SelectedItem.ToString(), rtbResponse.Text);
  208. DoAction(() => Connector.PushListAsync(Url, cmbType.SelectedItem.ToString(), list), res =>
  209. {
  210. rtbResponse.Text = res.ToString();
  211. });
  212. }
  213. private void Pull()
  214. {
  215. var filter = new ModelFilter
  216. {
  217. Limit = Convert.ToInt32(nudLimit.Value),
  218. Offset = Convert.ToInt32(nudOffset.Value)
  219. };
  220. if (ckbFetchChildren.Checked)
  221. {
  222. filter.Filters.Add("fetchChildren", 1);
  223. filter.Filters.Add("parentId", txtParentId.Text);
  224. }
  225. DoAction(() => Connector.PullAsync(Url, cmbType.SelectedItem.ToString(), filter), res =>
  226. {
  227. if (MainModel.MainList.Contains(cmbType.SelectedItem.ToString()))
  228. {
  229. btnContainerPush.Enabled = false;
  230. btnAck.Enabled = false;
  231. try
  232. {
  233. var modelType = cmbType.SelectedItem.ToString();
  234. if (res.Result.ToString() != "[]")
  235. {
  236. _modelList = MainModel.DeserializeList(modelType, res.Result.ToString());
  237. var model = MainModel.Deserialize(modelType, res.Result.ToString(), true);
  238. EditModel(model, modelType);
  239. }
  240. else
  241. {
  242. EditModel(MainModel.CreateObject(modelType), modelType);
  243. }
  244. }
  245. catch (Exception e)
  246. {
  247. rtbResponse.Text += e.Message + Environment.NewLine;
  248. }
  249. }
  250. rtbResponse.Text += res.ToString();
  251. BuildTree(rtbResponse.Text, tvResponse);
  252. });
  253. }
  254. private void EditModel(MainModel model, string modelType)
  255. {
  256. _modelForm = new PushForm(model, this, modelType);
  257. _modelForm.InvalidSessionEvent += ModelFormInvalidSessionEvent;
  258. _modelForm.FormClosed += ModelForm_FormClosed;
  259. btnContainerPush.Enabled = true;
  260. btnAck.Enabled = true;
  261. }
  262. void ModelForm_FormClosed(object sender, FormClosedEventArgs e)
  263. {
  264. _modelForm = null;
  265. btnContainerPush.Enabled = false;
  266. btnAck.Enabled = true;
  267. }
  268. void ModelFormInvalidSessionEvent()
  269. {
  270. Connector.SessionId = string.Empty;
  271. SetWorkStatus(false);
  272. }
  273. private void Delete()
  274. {
  275. IEnumerable list;
  276. if (rtbResponse.Text.Trim()[0].ToString(CultureInfo.InvariantCulture) == @"[")
  277. {
  278. list = MainModel.DeserializeList(cmbType.SelectedItem.ToString(), rtbResponse.Text);
  279. }
  280. else
  281. {
  282. var model = MainModel.Deserialize(cmbType.SelectedItem.ToString(), rtbResponse.Text);
  283. list = new List<MainModel> { (MainModel) model };
  284. }
  285. DoAction(() => Connector.DeleteListAsync(Url, cmbType.SelectedItem.ToString(), list), res =>
  286. {
  287. rtbResponse.Text = res.ToString();
  288. });
  289. }
  290. private void SetStatus()
  291. {
  292. var customerOrderStatus = new CustomerOrderStatus
  293. {
  294. Id = 59,
  295. Status = 2
  296. };
  297. DoAction(() => Connector.SetStatusAsync(Url, customerOrderStatus), res =>
  298. {
  299. rtbResponse.Text += res.ToString();
  300. });
  301. }
  302. private void Feature()
  303. {
  304. DoAction(() => Connector.GetFeatureMatrixAsync(Url), res =>
  305. {
  306. rtbResponse.Text += res.ToString();
  307. });
  308. }
  309. private void ConnectorStats()
  310. {
  311. var filter = new ModelFilter();
  312. DoAction(() => Connector.GetStatsAsync(Url, filter), res =>
  313. {
  314. rtbResponse.Text += res.ToString();
  315. });
  316. }
  317. private void Identify()
  318. {
  319. DoAction(() => Connector.IdentifyAsync(Url), res =>
  320. {
  321. rtbResponse.Text += res.ToString();
  322. });
  323. }
  324. private void Finish()
  325. {
  326. DoAction(() => Connector.FinishAsync(Url), res =>
  327. {
  328. rtbResponse.Text += res.ToString();
  329. });
  330. }
  331. private void AckFromJson()
  332. {
  333. var model = JsonConvert.DeserializeObject<AckModel>(rtbResponse.Text);
  334. DoAction(() => Connector.AckAsync(Url, model), res =>
  335. {
  336. rtbResponse.Text = res.ToString();
  337. });
  338. }
  339. private void Debug()
  340. {
  341. DoAction(() => Connector.SetDebugAsync(Url), res =>
  342. {
  343. rtbResponse.Text += res.ToString();
  344. });
  345. }
  346. private void Logs()
  347. {
  348. DoAction(() => Connector.GetLogsAsync(Url), res =>
  349. {
  350. rtbResponse.Text += res.ToString();
  351. });
  352. }
  353. private void Ack()
  354. {
  355. if (_modelList == null)
  356. {
  357. MessageBox.Show(@"Model list is empty! Pls try another pull");
  358. return;
  359. }
  360. var ack = new AckModel();
  361. var identities = new List<Identity>();
  362. var checksums = new List<IChecksum>();
  363. var modelType = ModelType.Product;
  364. foreach (var identity in from object model in _modelList select (Identity) model.GetType().GetProperty("Id").GetValue(model, null))
  365. {
  366. identity.Host = Helper.Random.Next(1, 1000);
  367. identities.Add(identity);
  368. if (cmbType.SelectedItem.ToString() == "Product")
  369. {
  370. checksums.Add(new ProductChecksumModel
  371. {
  372. ForeignKey = identity,
  373. HasChanged = false,
  374. Host = MainModel.RandomString(25),
  375. Type = 1
  376. });
  377. }
  378. }
  379. switch (cmbType.SelectedItem.ToString())
  380. {
  381. case "Product":
  382. modelType = ModelType.Product;
  383. break;
  384. case "Category":
  385. modelType = ModelType.Category;
  386. break;
  387. case "Customer":
  388. modelType = ModelType.Customer;
  389. break;
  390. case "CustomerOrder":
  391. modelType = ModelType.CustomerOrder;
  392. break;
  393. case "DeliveryNote":
  394. modelType = ModelType.DeliveryNote;
  395. break;
  396. case "Image":
  397. modelType = ModelType.Image;
  398. break;
  399. case "Manufacturer":
  400. modelType = ModelType.Manufacturer;
  401. break;
  402. case "Specific":
  403. modelType = ModelType.Specific;
  404. break;
  405. case "Payment":
  406. modelType = ModelType.Payment;
  407. break;
  408. case "CrossSelling":
  409. modelType = ModelType.CrossSelling;
  410. break;
  411. }
  412. ack.Identities.Add(modelType, identities);
  413. ack.Checksums = checksums;
  414. DoAction(() => Connector.AckAsync(Url, ack), res =>
  415. {
  416. rtbResponse.Text += res.ToString();
  417. });
  418. }
  419. private void Stats()
  420. {
  421. var filter = new ModelFilter();
  422. //filter.Limit = 0;
  423. //filter.Offset = 0;
  424. if (cmbType.SelectedItem.ToString() == "ImageModel")
  425. {
  426. //filter.Filters.Add("relationType", "product");
  427. //filter.Filters.Add("foreignKey", 34);
  428. }
  429. DoAction(() => Connector.StatsAsync(Url, cmbType.SelectedItem.ToString(), filter), res =>
  430. {
  431. rtbResponse.Text += res.ToString();
  432. });
  433. }
  434. private void Commit()
  435. {
  436. DoAction(() => Connector.CommitAsync(Url, cmbType.SelectedItem.ToString()), res =>
  437. {
  438. rtbResponse.Text += res.ToString();
  439. });
  440. }
  441. private void Validate()
  442. {
  443. if (rtbResponse.Text.Length > 0)
  444. {
  445. try
  446. {
  447. var response = JsonConvert.DeserializeObject<RpcResponse>(rtbResponse.Text);
  448. var x = response.Result.GetType().Name;
  449. if (x != "JArray") return;
  450. var validationForm = new ValidationError();
  451. var jArray = (JArray) response.Result;
  452. foreach (var jObject in jArray)
  453. {
  454. try
  455. {
  456. Connector.ValidateModel(cmbType.SelectedItem.ToString(), jObject.ToString());
  457. }
  458. catch (Exception exc)
  459. {
  460. validationForm.Errors.Add(exc.Message);
  461. }
  462. }
  463. if (validationForm.Errors.Count > 0)
  464. {
  465. validationForm.ShowDialog();
  466. }
  467. else
  468. {
  469. validationForm.Dispose();
  470. MessageBox.Show(@"O.K.");
  471. }
  472. }
  473. catch (Exception exc)
  474. {
  475. MessageBox.Show(exc.Message);
  476. }
  477. }
  478. else
  479. {
  480. MessageBox.Show(@"No json data");
  481. }
  482. }
  483. #endregion
  484. private void btnFile_Click(object sender, EventArgs e)
  485. {
  486. if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
  487. Connector.Picture = File.ReadAllBytes(openFileDialog1.FileName);
  488. Connector.Picturename = openFileDialog1.SafeFileName;
  489. }
  490. public static bool IsSessionValid(string exc)
  491. {
  492. return exc.IndexOf("Session is invalid", StringComparison.Ordinal) < 0;
  493. }
  494. private void SetWorkStatus(bool status)
  495. {
  496. gbControl.Enabled = status;
  497. btnDisconnect.Enabled = status;
  498. tcResponse.Enabled = status;
  499. btnSession.Enabled = !status;
  500. cboxUrl.Enabled = !status;
  501. txtToken.Enabled = !status;
  502. ckbFetchChildren.Enabled = status;
  503. txtParentId.Enabled = status;
  504. }
  505. private void cboxUrl_SelectedIndexChanged(object sender, EventArgs e)
  506. {
  507. //txtToken.Text = ((Endpoint) ((BindingSource) cboxUrl.DataSource).Current).Token;
  508. /*
  509. txtToken.Text = @"5d084502b4de4e25a16be29";
  510. if (cboxUrl.SelectedIndex == 1 || cboxUrl.SelectedIndex == 2 || cboxUrl.SelectedIndex == 3 || cboxUrl.SelectedIndex == 4)
  511. {
  512. txtToken.Text = @"aewie7AefaHai4aing9ucoh7saengoh1";
  513. }
  514. */
  515. }
  516. private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
  517. {
  518. switch (tcResponse.SelectedTab.Text)
  519. {
  520. case "Tree":
  521. BuildTree(rtbResponse.Text, tvResponse);
  522. break;
  523. case "HTML":
  524. var i = rtbResponse.Text.IndexOf("Http Response:", StringComparison.Ordinal);
  525. webBrowser1.DocumentText = i != -1 ? rtbResponse.Text.Substring(i).Replace("Http Response:", "") : rtbResponse.Text;
  526. break;
  527. }
  528. }
  529. public void BuildTree(string json, TreeView view)
  530. {
  531. view.Nodes.Clear();
  532. try
  533. {
  534. var node = new Node();
  535. var o = JObject.Parse(json);
  536. view.Nodes.Add(node.FromJson("object", o));
  537. }
  538. catch (Exception exc)
  539. {
  540. MessageBox.Show(exc.Message);
  541. }
  542. }
  543. private void btnAction_Click(object sender, EventArgs e)
  544. {
  545. btnContainerPush.Enabled = false;
  546. btnAck.Enabled = false;
  547. Action action;
  548. Enum.TryParse(cbAction.SelectedItem.ToString(), out action);
  549. DoWork(action);
  550. }
  551. private void btnContainerPush_Click(object sender, EventArgs e)
  552. {
  553. try
  554. {
  555. _modelForm.Show();
  556. }
  557. catch (Exception exc)
  558. {
  559. MessageBox.Show(exc.Message);
  560. }
  561. }
  562. private void btnDisconnect_Click(object sender, EventArgs e)
  563. {
  564. Connector.SessionId = string.Empty;
  565. SetWorkStatus(false);
  566. tvResponse.Nodes.Clear();
  567. rtbResponse.Text = string.Empty;
  568. cmbType.SelectedIndex = 0;
  569. cbAction.SelectedIndex = 0;
  570. }
  571. private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
  572. {
  573. if (cbAction.SelectedItem == null)
  574. {
  575. return;
  576. }
  577. cbAction.Enabled = true;
  578. switch (cmbType.SelectedItem.ToString())
  579. {
  580. case "StatusChange":
  581. cbAction.SelectedIndex = 1;
  582. cbAction.Enabled = false;
  583. rtbResponse.Text = JsonConvert.SerializeObject(new List<StatusChangeModel> { new StatusChangeModel() }, Formatting.Indented);
  584. break;
  585. case "ProductStockLevel":
  586. cbAction.SelectedIndex = 1;
  587. cbAction.Enabled = false;
  588. rtbResponse.Text = JsonConvert.SerializeObject(new List<ProductStockLevelModel> { new ProductStockLevelModel() }, Formatting.Indented);
  589. break;
  590. case "ProductPrice":
  591. cbAction.SelectedIndex = 1;
  592. cbAction.Enabled = false;
  593. var price = new ProductPriceModel
  594. {
  595. Items = new List<ProductPriceItemModel> {new ProductPriceItemModel()}
  596. };
  597. rtbResponse.Text = JsonConvert.SerializeObject(new List<ProductPriceModel> { price }, Formatting.Indented);
  598. break;
  599. }
  600. txtParentId.Enabled = ckbFetchChildren.Enabled = (cmbType.SelectedItem.ToString() == "Product" && cbAction.SelectedItem.ToString() == "Pull");
  601. if (!txtParentId.Enabled)
  602. {
  603. txtParentId.Text = string.Empty;
  604. ckbFetchChildren.Checked = false;
  605. }
  606. }
  607. private void cbAction_SelectedIndexChanged(object sender, EventArgs e)
  608. {
  609. if (cbAction.SelectedItem == null)
  610. {
  611. return;
  612. }
  613. nudLimit.Enabled = cbAction.SelectedItem.ToString() == "Pull";
  614. nudOffset.Enabled = cbAction.SelectedItem.ToString() == "Pull";
  615. }
  616. private void btnAckClear_Click(object sender, EventArgs e)
  617. {
  618. var result = MessageBox.Show(@"Clear all linkings?", @"Warning", MessageBoxButtons.YesNo,
  619. MessageBoxIcon.Warning);
  620. if (result == DialogResult.No)
  621. {
  622. return;
  623. }
  624. try
  625. {
  626. rtbResponse.Text = string.Empty;
  627. Clear();
  628. }
  629. catch (Exception exc)
  630. {
  631. if (!IsSessionValid(exc.Message))
  632. {
  633. Connector.SessionId = string.Empty;
  634. SetWorkStatus(false);
  635. }
  636. Connector.Picture = null;
  637. rtbResponse.Text = exc.Message;
  638. }
  639. }
  640. private void btnAck_Click(object sender, EventArgs e)
  641. {
  642. try
  643. {
  644. rtbResponse.Text = string.Empty;
  645. Ack();
  646. }
  647. catch (Exception ex)
  648. {
  649. if (!IsSessionValid(ex.Message))
  650. {
  651. Connector.SessionId = string.Empty;
  652. SetWorkStatus(false);
  653. }
  654. Connector.Picture = null;
  655. rtbResponse.Text = ex.Message;
  656. }
  657. }
  658. private void closeToolStripMenuItem_Click(object sender, EventArgs e)
  659. {
  660. Application.Exit();
  661. }
  662. private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
  663. {
  664. var settingsForm = new Settings();
  665. if (settingsForm.ShowDialog() == DialogResult.OK)
  666. {
  667. _setting = settingsForm.Setting;
  668. var source = rebindEndpointDataSource();
  669. if (source.Current != null)
  670. {
  671. txtToken.Text = (source.Current as Endpoint).Token;
  672. }
  673. }
  674. }
  675. private BindingSource rebindEndpointDataSource()
  676. {
  677. var source = new BindingSource { DataSource = _setting.Endpoints };
  678. source.CurrentChanged += (s, e) =>
  679. {
  680. txtToken.Text = ((s as BindingSource).Current as Endpoint).Token;
  681. };
  682. cboxUrl.DataSource = source;
  683. return source;
  684. }
  685. private void btnTest_Click(object sender, EventArgs e)
  686. {
  687. var pushTestForm = new PushTestForm(Connector.SessionId, Url);
  688. if (_setting.Resolution.Width > 0 && _setting.Resolution.Height > 0)
  689. {
  690. pushTestForm.Width = _setting.Resolution.Width;
  691. pushTestForm.Height = _setting.Resolution.Height;
  692. }
  693. pushTestForm.Show();
  694. }
  695. }
  696. }