/jtl.ConnectorTester/Form1.cs
C# | 805 lines | 681 code | 109 blank | 15 comment | 60 complexity | 335f5dc48ff86a8f86f3dfbc8340af1e MD5 | raw file
- using System.Collections;
- using System.Collections.Generic;
- using System.Globalization;
- using System.Linq;
- using System.Reactive.Linq;
- using System.Threading.Tasks;
- using jtl.ConnectorTester.Core;
- using jtl.ConnectorTester.Core.Model;
- using jtl.ConnectorTester.Core.Rpc;
- using jtl.ConnectorTester.Model;
- using jtl.ConnectorTester.Model.Interface;
- using Newtonsoft.Json;
- using System;
- using System.IO;
- using System.Windows.Forms;
- using Newtonsoft.Json.Linq;
- using Prounion.Json;
- namespace jtl.ConnectorTester
- {
- public partial class Form1 : Form
- {
- public enum Action
- {
- Pull,
- Push,
- Delete,
- Commit,
- FeatureMatrix,
- ConnectorStats,
- Stats,
- SetStatus,
- Validate,
- Identify,
- Finish,
- Clear,
- Init,
- Ack,
- Debug,
- Logs
- }
- private Setting _setting;
- public Connector Connector;
- public string Url = String.Empty;
- public string Token = String.Empty;
- private PushForm _modelForm;
- private IEnumerable _modelList;
- public Form1()
- {
- InitializeComponent();
- _setting = new Setting();
- _setting.Load();
- if (_setting.Resolution.Width > 0 && _setting.Resolution.Height > 0)
- {
- Width = _setting.Resolution.Width;
- Height = _setting.Resolution.Height;
- }
- var source = rebindEndpointDataSource();
- if (source.Current != null)
- {
- source.Position = _setting.EndpointIndex;
- txtToken.Text = (source.Current as Endpoint).Token;
- }
- //Text += string.Format(" {0}", Assembly.GetExecutingAssembly().GetName().Version);
- Text += string.Format(" {0}", Application.ProductVersion);
-
- Connector = new Connector();
- cmbType.DataSource = MainModel.MainList;
- //cboxUrl.SelectedIndex = _setting.EndpointIndex;
- //txtToken.Text = @"5d084502b4de4e25a16be29";
- cbAction.DataSource = Enum.GetValues(typeof (Action));
- Connector.CalltimeMeasured.ObserveOn(this).Subscribe(e =>
- {
- lblWatch.Text = string.Format("{0} Milliseconds", e);
- });
- }
- private void btnSession_Click(object sender, EventArgs e)
- {
- Url = cboxUrl.Text;
- Token = txtToken.Text;
- DoAction(() => Connector.GetSessionAsync(Url, Token), r =>
- {
- if (r.Error != null)
- {
- MessageBox.Show(string.Format("Error: {0} - {1}", r.Error.Code, r.Error.Message));
- }
- var session = ((JObject) r.Result).ToObject<Session>();
- Connector.SessionId = session.SessionId;
- rtbResponse.Text = "";
- if (Connector.SessionId.Length <= 0) return;
- SetWorkStatus(true);
- rtbResponse.Text = string.Format("SessionId: {0}", Connector.SessionId);
- });
- }
- #region Actions
- private void DoWork(Action action)
- {
- try
- {
- if (action != Action.Validate && action != Action.Push && action != Action.Delete && action != Action.Ack)
- {
- rtbResponse.Text = string.Empty;
- }
- switch (action)
- {
- case Action.Push:
- Push();
- break;
- case Action.Pull:
- Pull();
- break;
- case Action.Delete:
- Delete();
- break;
- case Action.SetStatus:
- SetStatus();
- break;
- case Action.FeatureMatrix:
- Feature();
- break;
- case Action.ConnectorStats:
- ConnectorStats();
- break;
- case Action.Stats:
- Stats();
- break;
- case Action.Identify:
- Identify();
- break;
-
- case Action.Finish:
- Finish();
- break;
- case Action.Commit:
- try
- {
- Commit();
- }
- catch (Exception exc)
- {
- Connector.Picture = null;
- throw new Exception(exc.Message);
- }
- break;
- case Action.Validate:
- Validate();
- break;
- case Action.Clear:
- Clear();
- break;
- case Action.Init:
- Init();
- break;
- case Action.Ack:
- AckFromJson();
- break;
- case Action.Debug:
- Debug();
- break;
- case Action.Logs:
- Logs();
- break;
- }
- }
- catch (Exception exc)
- {
- if (!IsSessionValid(exc.Message))
- {
- Connector.SessionId = string.Empty;
- SetWorkStatus(false);
- }
- Connector.Picture = null;
- rtbResponse.Text = exc.Message;
- }
- }
- private void Init()
- {
- DoAction(() => Connector.InitAsync(Url), res =>
- {
- rtbResponse.Text = res.ToString();
- });
- }
- private async void DoAction(Func<Task<RpcResponse>> connectorCall, Action<RpcResponse> guiAction)
- {
- try
- {
- var response = await connectorCall();
- guiAction(response);
- }
- catch (Exception e)
- {
- if (!IsSessionValid(e.Message))
- {
- Connector.SessionId = string.Empty;
- SetWorkStatus(false);
- }
- Connector.Picture = null;
- rtbResponse.Text = e.Message;
- }
- }
- private void Clear()
- {
- DoAction(() => Connector.ClearLinkerAsync(Url), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Push()
- {
- var list = MainModel.DeserializeList(cmbType.SelectedItem.ToString(), rtbResponse.Text);
- DoAction(() => Connector.PushListAsync(Url, cmbType.SelectedItem.ToString(), list), res =>
- {
- rtbResponse.Text = res.ToString();
- });
- }
- private void Pull()
- {
- var filter = new ModelFilter
- {
- Limit = Convert.ToInt32(nudLimit.Value),
- Offset = Convert.ToInt32(nudOffset.Value)
- };
- if (ckbFetchChildren.Checked)
- {
- filter.Filters.Add("fetchChildren", 1);
- filter.Filters.Add("parentId", txtParentId.Text);
- }
- DoAction(() => Connector.PullAsync(Url, cmbType.SelectedItem.ToString(), filter), res =>
- {
- if (MainModel.MainList.Contains(cmbType.SelectedItem.ToString()))
- {
- btnContainerPush.Enabled = false;
- btnAck.Enabled = false;
- try
- {
- var modelType = cmbType.SelectedItem.ToString();
- if (res.Result.ToString() != "[]")
- {
- _modelList = MainModel.DeserializeList(modelType, res.Result.ToString());
- var model = MainModel.Deserialize(modelType, res.Result.ToString(), true);
- EditModel(model, modelType);
- }
- else
- {
- EditModel(MainModel.CreateObject(modelType), modelType);
- }
- }
- catch (Exception e)
- {
- rtbResponse.Text += e.Message + Environment.NewLine;
- }
- }
- rtbResponse.Text += res.ToString();
- BuildTree(rtbResponse.Text, tvResponse);
- });
- }
- private void EditModel(MainModel model, string modelType)
- {
- _modelForm = new PushForm(model, this, modelType);
- _modelForm.InvalidSessionEvent += ModelFormInvalidSessionEvent;
- _modelForm.FormClosed += ModelForm_FormClosed;
- btnContainerPush.Enabled = true;
- btnAck.Enabled = true;
- }
- void ModelForm_FormClosed(object sender, FormClosedEventArgs e)
- {
- _modelForm = null;
- btnContainerPush.Enabled = false;
- btnAck.Enabled = true;
- }
- void ModelFormInvalidSessionEvent()
- {
- Connector.SessionId = string.Empty;
- SetWorkStatus(false);
- }
- private void Delete()
- {
- IEnumerable list;
- if (rtbResponse.Text.Trim()[0].ToString(CultureInfo.InvariantCulture) == @"[")
- {
- list = MainModel.DeserializeList(cmbType.SelectedItem.ToString(), rtbResponse.Text);
- }
- else
- {
- var model = MainModel.Deserialize(cmbType.SelectedItem.ToString(), rtbResponse.Text);
- list = new List<MainModel> { (MainModel) model };
- }
- DoAction(() => Connector.DeleteListAsync(Url, cmbType.SelectedItem.ToString(), list), res =>
- {
- rtbResponse.Text = res.ToString();
- });
- }
- private void SetStatus()
- {
- var customerOrderStatus = new CustomerOrderStatus
- {
- Id = 59,
- Status = 2
- };
- DoAction(() => Connector.SetStatusAsync(Url, customerOrderStatus), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Feature()
- {
- DoAction(() => Connector.GetFeatureMatrixAsync(Url), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void ConnectorStats()
- {
- var filter = new ModelFilter();
- DoAction(() => Connector.GetStatsAsync(Url, filter), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Identify()
- {
- DoAction(() => Connector.IdentifyAsync(Url), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Finish()
- {
- DoAction(() => Connector.FinishAsync(Url), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void AckFromJson()
- {
- var model = JsonConvert.DeserializeObject<AckModel>(rtbResponse.Text);
- DoAction(() => Connector.AckAsync(Url, model), res =>
- {
- rtbResponse.Text = res.ToString();
- });
- }
- private void Debug()
- {
- DoAction(() => Connector.SetDebugAsync(Url), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Logs()
- {
- DoAction(() => Connector.GetLogsAsync(Url), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Ack()
- {
- if (_modelList == null)
- {
- MessageBox.Show(@"Model list is empty! Pls try another pull");
- return;
- }
- var ack = new AckModel();
- var identities = new List<Identity>();
- var checksums = new List<IChecksum>();
- var modelType = ModelType.Product;
- foreach (var identity in from object model in _modelList select (Identity) model.GetType().GetProperty("Id").GetValue(model, null))
- {
- identity.Host = Helper.Random.Next(1, 1000);
- identities.Add(identity);
- if (cmbType.SelectedItem.ToString() == "Product")
- {
- checksums.Add(new ProductChecksumModel
- {
- ForeignKey = identity,
- HasChanged = false,
- Host = MainModel.RandomString(25),
- Type = 1
- });
- }
- }
- switch (cmbType.SelectedItem.ToString())
- {
- case "Product":
- modelType = ModelType.Product;
- break;
- case "Category":
- modelType = ModelType.Category;
- break;
- case "Customer":
- modelType = ModelType.Customer;
- break;
- case "CustomerOrder":
- modelType = ModelType.CustomerOrder;
- break;
- case "DeliveryNote":
- modelType = ModelType.DeliveryNote;
- break;
- case "Image":
- modelType = ModelType.Image;
- break;
- case "Manufacturer":
- modelType = ModelType.Manufacturer;
- break;
- case "Specific":
- modelType = ModelType.Specific;
- break;
- case "Payment":
- modelType = ModelType.Payment;
- break;
- case "CrossSelling":
- modelType = ModelType.CrossSelling;
- break;
- }
- ack.Identities.Add(modelType, identities);
- ack.Checksums = checksums;
- DoAction(() => Connector.AckAsync(Url, ack), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Stats()
- {
- var filter = new ModelFilter();
- //filter.Limit = 0;
- //filter.Offset = 0;
- if (cmbType.SelectedItem.ToString() == "ImageModel")
- {
- //filter.Filters.Add("relationType", "product");
- //filter.Filters.Add("foreignKey", 34);
- }
- DoAction(() => Connector.StatsAsync(Url, cmbType.SelectedItem.ToString(), filter), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Commit()
- {
- DoAction(() => Connector.CommitAsync(Url, cmbType.SelectedItem.ToString()), res =>
- {
- rtbResponse.Text += res.ToString();
- });
- }
- private void Validate()
- {
- if (rtbResponse.Text.Length > 0)
- {
- try
- {
- var response = JsonConvert.DeserializeObject<RpcResponse>(rtbResponse.Text);
- var x = response.Result.GetType().Name;
- if (x != "JArray") return;
- var validationForm = new ValidationError();
- var jArray = (JArray) response.Result;
- foreach (var jObject in jArray)
- {
- try
- {
- Connector.ValidateModel(cmbType.SelectedItem.ToString(), jObject.ToString());
- }
- catch (Exception exc)
- {
- validationForm.Errors.Add(exc.Message);
- }
- }
- if (validationForm.Errors.Count > 0)
- {
- validationForm.ShowDialog();
- }
- else
- {
- validationForm.Dispose();
- MessageBox.Show(@"O.K.");
- }
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message);
- }
- }
- else
- {
- MessageBox.Show(@"No json data");
- }
- }
- #endregion
- private void btnFile_Click(object sender, EventArgs e)
- {
- if (openFileDialog1.ShowDialog() != DialogResult.OK) return;
- Connector.Picture = File.ReadAllBytes(openFileDialog1.FileName);
- Connector.Picturename = openFileDialog1.SafeFileName;
- }
- public static bool IsSessionValid(string exc)
- {
- return exc.IndexOf("Session is invalid", StringComparison.Ordinal) < 0;
- }
- private void SetWorkStatus(bool status)
- {
- gbControl.Enabled = status;
- btnDisconnect.Enabled = status;
- tcResponse.Enabled = status;
- btnSession.Enabled = !status;
- cboxUrl.Enabled = !status;
- txtToken.Enabled = !status;
- ckbFetchChildren.Enabled = status;
- txtParentId.Enabled = status;
- }
- private void cboxUrl_SelectedIndexChanged(object sender, EventArgs e)
- {
- //txtToken.Text = ((Endpoint) ((BindingSource) cboxUrl.DataSource).Current).Token;
- /*
- txtToken.Text = @"5d084502b4de4e25a16be29";
- if (cboxUrl.SelectedIndex == 1 || cboxUrl.SelectedIndex == 2 || cboxUrl.SelectedIndex == 3 || cboxUrl.SelectedIndex == 4)
- {
- txtToken.Text = @"aewie7AefaHai4aing9ucoh7saengoh1";
- }
- */
- }
- private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
- {
- switch (tcResponse.SelectedTab.Text)
- {
- case "Tree":
- BuildTree(rtbResponse.Text, tvResponse);
- break;
- case "HTML":
- var i = rtbResponse.Text.IndexOf("Http Response:", StringComparison.Ordinal);
- webBrowser1.DocumentText = i != -1 ? rtbResponse.Text.Substring(i).Replace("Http Response:", "") : rtbResponse.Text;
- break;
- }
- }
- public void BuildTree(string json, TreeView view)
- {
- view.Nodes.Clear();
- try
- {
- var node = new Node();
- var o = JObject.Parse(json);
- view.Nodes.Add(node.FromJson("object", o));
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message);
- }
- }
- private void btnAction_Click(object sender, EventArgs e)
- {
- btnContainerPush.Enabled = false;
- btnAck.Enabled = false;
- Action action;
- Enum.TryParse(cbAction.SelectedItem.ToString(), out action);
- DoWork(action);
- }
- private void btnContainerPush_Click(object sender, EventArgs e)
- {
- try
- {
- _modelForm.Show();
- }
- catch (Exception exc)
- {
- MessageBox.Show(exc.Message);
- }
- }
- private void btnDisconnect_Click(object sender, EventArgs e)
- {
- Connector.SessionId = string.Empty;
- SetWorkStatus(false);
- tvResponse.Nodes.Clear();
- rtbResponse.Text = string.Empty;
- cmbType.SelectedIndex = 0;
- cbAction.SelectedIndex = 0;
- }
- private void cmbType_SelectedIndexChanged(object sender, EventArgs e)
- {
- if (cbAction.SelectedItem == null)
- {
- return;
- }
- cbAction.Enabled = true;
- switch (cmbType.SelectedItem.ToString())
- {
- case "StatusChange":
- cbAction.SelectedIndex = 1;
- cbAction.Enabled = false;
- rtbResponse.Text = JsonConvert.SerializeObject(new List<StatusChangeModel> { new StatusChangeModel() }, Formatting.Indented);
- break;
- case "ProductStockLevel":
- cbAction.SelectedIndex = 1;
- cbAction.Enabled = false;
- rtbResponse.Text = JsonConvert.SerializeObject(new List<ProductStockLevelModel> { new ProductStockLevelModel() }, Formatting.Indented);
- break;
- case "ProductPrice":
- cbAction.SelectedIndex = 1;
- cbAction.Enabled = false;
- var price = new ProductPriceModel
- {
- Items = new List<ProductPriceItemModel> {new ProductPriceItemModel()}
- };
- rtbResponse.Text = JsonConvert.SerializeObject(new List<ProductPriceModel> { price }, Formatting.Indented);
- break;
- }
- txtParentId.Enabled = ckbFetchChildren.Enabled = (cmbType.SelectedItem.ToString() == "Product" && cbAction.SelectedItem.ToString() == "Pull");
- if (!txtParentId.Enabled)
- {
- txtParentId.Text = string.Empty;
- ckbFetchChildren.Checked = false;
- }
- }
- private void cbAction_SelectedIndexChanged(object sender, EventArgs e)
- {
- if (cbAction.SelectedItem == null)
- {
- return;
- }
- nudLimit.Enabled = cbAction.SelectedItem.ToString() == "Pull";
- nudOffset.Enabled = cbAction.SelectedItem.ToString() == "Pull";
- }
- private void btnAckClear_Click(object sender, EventArgs e)
- {
- var result = MessageBox.Show(@"Clear all linkings?", @"Warning", MessageBoxButtons.YesNo,
- MessageBoxIcon.Warning);
- if (result == DialogResult.No)
- {
- return;
- }
- try
- {
- rtbResponse.Text = string.Empty;
- Clear();
- }
- catch (Exception exc)
- {
- if (!IsSessionValid(exc.Message))
- {
- Connector.SessionId = string.Empty;
- SetWorkStatus(false);
- }
- Connector.Picture = null;
- rtbResponse.Text = exc.Message;
- }
- }
- private void btnAck_Click(object sender, EventArgs e)
- {
- try
- {
- rtbResponse.Text = string.Empty;
- Ack();
- }
- catch (Exception ex)
- {
- if (!IsSessionValid(ex.Message))
- {
- Connector.SessionId = string.Empty;
- SetWorkStatus(false);
- }
- Connector.Picture = null;
- rtbResponse.Text = ex.Message;
- }
- }
- private void closeToolStripMenuItem_Click(object sender, EventArgs e)
- {
- Application.Exit();
- }
- private void settingsToolStripMenuItem_Click(object sender, EventArgs e)
- {
- var settingsForm = new Settings();
- if (settingsForm.ShowDialog() == DialogResult.OK)
- {
- _setting = settingsForm.Setting;
- var source = rebindEndpointDataSource();
- if (source.Current != null)
- {
- txtToken.Text = (source.Current as Endpoint).Token;
- }
- }
- }
- private BindingSource rebindEndpointDataSource()
- {
- var source = new BindingSource { DataSource = _setting.Endpoints };
- source.CurrentChanged += (s, e) =>
- {
- txtToken.Text = ((s as BindingSource).Current as Endpoint).Token;
- };
- cboxUrl.DataSource = source;
- return source;
- }
- private void btnTest_Click(object sender, EventArgs e)
- {
- var pushTestForm = new PushTestForm(Connector.SessionId, Url);
- if (_setting.Resolution.Width > 0 && _setting.Resolution.Height > 0)
- {
- pushTestForm.Width = _setting.Resolution.Width;
- pushTestForm.Height = _setting.Resolution.Height;
- }
- pushTestForm.Show();
- }
- }
- }