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