Source

main-vinayFork / Source / Excel / Excel.AddIn / Excel.AddIn / Controller / Controller.cs

  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
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using DataUp.Excel.Addin.Properties;
using DataUp.Excel.BizLogic;

namespace DataUp.Excel.Addin
{
    /// <summary>
    /// TODO: Update summary.
    /// </summary>
    internal class Controller
    {
        private static Controller instance;
        private static List<RepositoryModel> cacheRepositoryDetails;
        private TaskPane taskPane;
        private Ribbon ribbon;
        private IExcelManager excelManager;
        private IMetadataManager metadataManager;
        private IRepositoryManager repositoryManager;
        private string userPassword = string.Empty;

        private string[] identifierList;
        private string[] citationList;

        /// <summary>
        /// Gets the respotiory cache details list.
        /// </summary>
        public static List<RepositoryModel> CacheRepositoryDetails
        {
            get
            {
                return cacheRepositoryDetails;
            }
        }

        private Controller()
        {
            // TODO : Need to get these list from some xml file based or somewhere else where the user can configure the values based on the selected metadata XML.
            identifierList = new string[] { "Creator: First name", "Today's date", "Title of dataset" };

            citationList = new string[] { "Creator: First name", "Today's date", "Title of dataset", "Keyword thesaurus used", "Repository name and contact information", Common.Constants.IdentifierKeyName };

            cacheRepositoryDetails = new List<RepositoryModel>();
        }

        /// <summary>
        /// Gets Controller instance
        /// </summary>
        internal static Controller Instance
        {
            get
            {
                if (instance == null)
                {
                    instance = new Controller();
                }

                return instance;
            }
        }

        internal void Initialize(TaskPane taskPane, Ribbon ribbon)
        {
            if (taskPane != null && ribbon != null)
            {
                this.taskPane = taskPane;
                this.ribbon = ribbon;

                cacheRepositoryDetails = new List<RepositoryModel>();

                Globals.ThisAddIn.Application.WorkbookActivate += new Microsoft.Office.Interop.Excel.AppEvents_WorkbookActivateEventHandler(OnWorkbookActivate);

                var activeWorkBook = Globals.ThisAddIn.Application.ActiveWorkbook;

                /** This condition will always be true when a new workbook has been created, 
                    but when we reopen the existing workbook it would require some time
                    to load the active workbook, by then its value will be null. So, wait for 
                    WorkbookActivate event execute and hookup the SheetChange event handler inside 
                 **/
                if (activeWorkBook != null)
                {
                    activeWorkBook.SheetChange += new Microsoft.Office.Interop.Excel.WorkbookEvents_SheetChangeEventHandler(OnSheetChange);
                }

                this.AttachRibbonHandlers();
                this.InitializeManagers();
            }
        }

        public void FixAllErrors()
        {
            try
            {
                if (excelManager != null)
                {
                    excelManager.FixAll();
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        public void FixError(ErrorDetailViewModel error)
        {
            try
            {
                if (excelManager != null)
                {
                    ErrorDetail errorDetail = new ErrorDetail();
                    errorDetail = errorDetail.SetValuesFrom(error);
                    excelManager.FixError(errorDetail);

                    var currentSheet = this.taskPane.ErrorDetails.Model.SelectedSheet.SheetName;

                    Validate(false);

                    this.taskPane.ErrorDetails.Model.SelectSheet(currentSheet);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        public void FixErrors(List<ErrorDetailViewModel> errors)
        {
            try
            {
                if (excelManager != null)
                {
                    List<ErrorDetail> errorDetails = new List<ErrorDetail>();

                    foreach (var error in errors)
                    {
                        ErrorDetail errorDetail = new ErrorDetail();
                        errorDetail = errorDetail.SetValuesFrom(error);
                        errorDetails.Add(errorDetail);
                    }

                    excelManager.FixErrors(errorDetails);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        public void SelectError(ErrorDetailViewModel error)
        {
            try
            {
                ErrorDetail errorDetail = new ErrorDetail();
                errorDetail = errorDetail.SetValuesFrom(error);

                if (excelManager != null)
                {
                    excelManager.Select(errorDetail);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        public void SelectSheet(string sheetName)
        {
            if (!string.IsNullOrWhiteSpace(sheetName))
            {
                this.taskPane.ErrorDetails.Model.SelectSheet(sheetName);
            }
        }

        public void ResolveAllErrors()
        {
            if (MessageBox.Show(Resources.RemoveErrors, Resources.DialogTitle, MessageBoxButtons.YesNo) == DialogResult.Yes)
            {
                FixAllErrors();

                Validate();
            }
        }

        public void ResolveAllErrors(ErrorType typeOfError, string sheetName)
        {
            try
            {
                if (excelManager != null)
                {
                    excelManager.FixErrors(typeOfError, sheetName);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        public IEnumerable<ErrorDetail> GetErrors()
        {
            IEnumerable<ErrorDetail> errors = new List<ErrorDetail>();

            try
            {
                if (excelManager != null)
                {
                    errors = excelManager.Validate();
                }
            }
            catch (Exception)
            {
                // TODO : Error Handling
            }

            return errors;
        }

        public Dictionary<string, string> GetDocumentProperties()
        {
            Dictionary<string, string> documentProperties = new Dictionary<string, string>();
            try
            {
                documentProperties = excelManager.GetDocumentProperties();
            }
            catch (Exception)
            {
                // TODO : Exception handling.
                // MessageBox.Show(ex.Message, Resources.DialogTitle);
            }

            return documentProperties;
        }

        public MetadataListViewModel GetMetadata()
        {
            var metadata = metadataManager.GetMetadata();
            MetadataListViewModel metadataListViewModel = new MetadataListViewModel();
            foreach (var item in metadata)
            {
                MetadataViewModel model = new MetadataViewModel();
                model.SetValuesFrom(item);
                metadataListViewModel.MetadataList.Add(model);
            }

            var parameterMetadataList = metadataManager.GetParamterMetadata();
            foreach (var item in parameterMetadataList)
            {
                if (!string.IsNullOrWhiteSpace(item.Name))
                {
                    ParameterMetadataViewModel model = new ParameterMetadataViewModel();
                    model.SetValuesFrom(item);
                    metadataListViewModel.ParameterMetadataList.Add(model);
                }
            }

            if (!metadataManager.IsGeneralMetadataPresent())
            {
                Dictionary<string, string> documentProperties = GetDocumentProperties();
                metadataListViewModel.UpdateExcelProperties(documentProperties);
            }

            return metadataListViewModel;
        }

        public void UpdateMetadata(MetadataListViewModel metadataListViewModel)
        {
            List<MetadataDetail> updatedMetadata = new List<MetadataDetail>();
            foreach (var item in metadataListViewModel.MetadataList)
            {
                MetadataDetail model = new MetadataDetail();
                model.SetValuesFrom(item);
                updatedMetadata.Add(model);
            }

            List<ParameterDetail> paramterList = new List<ParameterDetail>();
            var paramData = from val in metadataListViewModel.ParameterMetadataList
                            group val by val.EntityName into param
                            select new
                            {
                                EntityName = param.Key,
                                Description = param.Select(q => (String.IsNullOrEmpty(q.EntityDescription) ? "" : q.EntityDescription)).FirstOrDefault(q => !String.IsNullOrEmpty(q)),
                                Values = param.ToList()
                            }; 

            foreach (var item in paramData)
            {
                item.Values.ForEach(q =>
                {
                    paramterList.Add(new ParameterDetail
                    {
                         EntityName = item.EntityName,
                          EntityDescription = item.Description,
                           Name = q.Name,
                            Description = q.Description,
                             Type = q.Type,
                              Units = q.Units
                    });
                });
            }

            metadataManager.UpdateMetadata(updatedMetadata, paramterList);
        }

        public ServiceResponse GetIdentifier(MetadataListViewModel metadataListViewModel, RepositoryModel repositoryModel)
        {
            string author = string.Empty;
            var authorNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith("First name", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(authorNode.Value))
            {
                author = authorNode.Value;
            }

            string title = string.Empty;
            var titleNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith("Title of dataset", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(titleNode.Value))
            {
                title = titleNode.Value;
            }

            DateTime pubDateTime = DateTime.UtcNow;
            string pubDate = string.Empty;
            var pubDateNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith("Today's date", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
            if (!string.IsNullOrWhiteSpace(pubDateNode.Value))
            {
                pubDate = pubDateNode.Value;

                if (!string.IsNullOrWhiteSpace(pubDate))
                {
                    if (DateTime.TryParse(pubDate, out pubDateTime))
                    {
                        pubDate = pubDateTime.ToString(Common.Constants.DefaultDateFormat);
                    }
                }
            }

            IdentifierDetail identifierDetail = new IdentifierDetail();

            identifierDetail.RepositoryName = repositoryModel.RepositoryName;
            if (repositoryModel.IsPasswordRequired)
            {
                identifierDetail.Authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(repositoryModel.UserName + ":" + repositoryModel.UserPassword));
            }

            identifierDetail.What = title;
            identifierDetail.Who = author;
            identifierDetail.When = pubDateTime;

            // Get Identifier from the service            
            return repositoryManager.GetIdentifier(identifierDetail);
        }

        public ServiceResponse PublishFile(MetadataListViewModel metadataListViewModel, bool isExcel, RepositoryModel repositoryModel)
        {
            ServiceResponse status = ServiceResponse.CreateSuccessStatus();
            try
            {
                PostFileDetail postfileDetail = new PostFileDetail();

                postfileDetail.RepositoryName = repositoryModel.RepositoryName;
                if (repositoryModel.IsPasswordRequired)
                {
                    postfileDetail.Authorization = Convert.ToBase64String(System.Text.Encoding.UTF8.GetBytes(repositoryModel.UserName + ":" + repositoryModel.UserPassword));
                }

                postfileDetail.IsCompressed = !isExcel;

                string author = string.Empty;
                var authorNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith("First name", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(authorNode.Value))
                {
                    author = authorNode.Value;
                }

                string title = string.Empty;
                var titleNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith("Title of dataset", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(titleNode.Value))
                {
                    title = titleNode.Value;
                }

                DateTime pubDateTime = DateTime.UtcNow;
                string pubDate = string.Empty;
                var pubDateNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith("Today's date", StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                if (!string.IsNullOrWhiteSpace(pubDateNode.Value))
                {
                    pubDate = pubDateNode.Value;

                    if (!string.IsNullOrWhiteSpace(pubDate))
                    {
                        if (DateTime.TryParse(pubDate, out pubDateTime))
                        {
                            pubDate = pubDateTime.ToString(Common.Constants.DefaultDateFormat);
                        }
                    }
                }

                string identifier = string.Empty;
                var identifierNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith(Common.Constants.IdentifierKeyName, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                if (identifierNode!= null && !string.IsNullOrWhiteSpace(identifierNode.Value))
                {
                    identifier = identifierNode.Value;
                }
                else
                {
                    var getIdentifierResult = GetIdentifier(metadataListViewModel, repositoryModel);
                    if (getIdentifierResult.IsSuccess)
                    {
                        identifier = getIdentifierResult.Message;

                        if (identifierNode != null)
                        {
                            identifierNode.Value = identifier;
                        }

                        // Add Identifer as part of citation if the citation is already generated.
                        string citation = string.Empty;
                        var citationNode = metadataListViewModel.MetadataList.Where(m => m.Name.EndsWith(Common.Constants.CitationContent, StringComparison.InvariantCultureIgnoreCase)).FirstOrDefault();
                        if (!string.IsNullOrWhiteSpace(citationNode.Value))
                        {
                            citation = citationNode.Value;

                            string[] values = citation.Split('.');

                            if (values.Length >= 4)
                            {
                                values[values.Length - 1] = identifier;

                                citationNode.Value = string.Join(". ", values);
                            }
                        }

                        UpdateMetadata(metadataListViewModel);
                    }
                    else
                    {
                        status = getIdentifierResult;
                    }
                }

                if (status.IsSuccess)
                {
                    postfileDetail.What = title;
                    postfileDetail.Who = author;
                    postfileDetail.When = pubDateTime;
                    postfileDetail.Identifier = identifier;

                    string response = string.Empty;
                    if (isExcel)
                    {
                        // 6.a Save a copy of the existing file using  "Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs"
                        // 6.b Stream the file which was saved as copy to the web service.
                        string filepath = Path.Combine(Path.GetTempPath(), Path.GetFileNameWithoutExtension(excelManager.GetWorkbookName()) + ".xlsx");

                        Globals.ThisAddIn.Application.ActiveWorkbook.SaveCopyAs(filepath);

                        postfileDetail.Filename = filepath;
                        postfileDetail.Content = FileToByteArray(filepath);
                    }
                    else
                    {
                        // 6.a Create different csv files for each of the sheets. Naming convention "Filename-sheetname.csv"
                        // 6.b Create a compressed file out of the created csv files.
                        string csvFilePath = repositoryManager.GetCsvZipFile(Path.GetFileNameWithoutExtension(excelManager.GetWorkbookName()));
                        if (!string.IsNullOrWhiteSpace(csvFilePath))
                        {
                            FileInfo f = new FileInfo(csvFilePath);
                            postfileDetail.Filename = f.FullName;
                            postfileDetail.Content = FileToByteArray(f.FullName);
                        }
                    }

                    status = repositoryManager.PublishFile(postfileDetail, metadataListViewModel.GetMetadataList(), metadataManager.GetParamterMetadata());
                }
            }
            catch (Exception ex)
            {
                status = ServiceResponse.CreateFailureStatus(ex);
            }

            return status;
        }

        public List<RepositoryModel> GetRepositories()
        {
            return repositoryManager.GetRespositories();
        }

        public void GenerateParaMetadata()
        {
            try
            {
                bool canContinue = true;

                do
                {
                    this.ribbon.DisableCustomTaskPaneButtons();

                    var output = ThisAddIn.ExcelApplication.InputBox(Resources.ParameterMetadataDescription, Title: Resources.ParameterMetadataTitle, Type: 8);

                    if (output is bool)
                    {
                        canContinue = (bool)output;
                    }

                    if (canContinue)
                    {
                        List<object> obj = metadataManager.GetHeaderRow(output as Microsoft.Office.Interop.Excel.Range);
                        string entityName = metadataManager.ActiveSheetName(output as Microsoft.Office.Interop.Excel.Range);
                        if (obj.Count > 0)
                        {
                            metadataManager.UpdateParaMetadata(obj, sheetName:entityName);
                            canContinue = false;
                        }
                        else
                        {
                            MessageBox.Show(Resources.SelectRange);
                        }
                    }
                } while (canContinue);

                ActivateRibbonTab();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
            finally
            {
                this.ribbon.EnableCustomTaskPaneButtons();
            }
        }

        public List<ParameterDetail> GetNewParameterList()
        {
            List<ParameterDetail> newParameterList = new List<ParameterDetail>();
            try
            {
                bool canContinue = true;

                do
                {
                    this.ribbon.DisableCustomTaskPaneButtons();

                    var output = ThisAddIn.ExcelApplication.InputBox(Resources.ParameterMetadataDescription, Title: Resources.ParameterMetadataTitle, Type: 8);

                    if (output is bool)
                    {
                        canContinue = (bool)output;
                    }

                    if (canContinue)
                    {
                        List<object> obj = metadataManager.GetHeaderRow(output as Microsoft.Office.Interop.Excel.Range);
                        string entityName = metadataManager.ActiveSheetName(output as Microsoft.Office.Interop.Excel.Range);

                        if (obj.Count > 0)
                        {
                            foreach (var item in obj)
                            {
                                if (item != null)
                                {
                                    newParameterList.Add(new ParameterDetail()
                                    {
                                        EntityName = entityName,
                                        Name = item.ToString().Trim()
                                    });
                                }
                            }

                            canContinue = false;
                        }
                        else
                        {
                            MessageBox.Show(Resources.SelectRange);
                        }
                    }
                } while (canContinue);

                ActivateRibbonTab();
            }
            catch (Exception)
            {
                // TODO: Error handling
                // MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
            finally
            {
                this.ribbon.EnableCustomTaskPaneButtons();
            }

            return newParameterList;
        }

        public List<string> GetSheetNames()
        {
            var sheetsNames = this.excelManager.GetSheetNames();
            if (sheetsNames != null)
            {
                return sheetsNames.OrderBy(s => s.Key).Select(s => s.Value).ToList();
            }
            return null;
        }

        public string GetUserAgreement(string repositoryName)
        {
            return this.repositoryManager.GetUserAgreement(repositoryName);
        }

        public void Validate(bool selectSummary = true)
        {
            this.taskPane.ErrorDetails.Model.Validate(selectSummary);
        }

        private static bool ContainsMetadata(MetadataListViewModel metadataListViewModel, string[] searchList)
        {
            bool isValid = true;

            if (searchList != null && searchList.Length > 0)
            {
                // Check if All required fields are present for Generating the Metadata. Check requirement document more details and flow.
                for (int searchIndex = 0; searchIndex < searchList.Length; searchIndex++)
                {
                    isValid = false;
                    for (int i = 0; i < metadataListViewModel.MetadataList.Count; i++)
                    {
                        if ((metadataListViewModel.MetadataList[i]).Name == searchList[searchIndex])
                        {
                            if (!string.IsNullOrWhiteSpace(metadataListViewModel.MetadataList[i].Value))
                            {
                                isValid = true;
                                break;
                            }
                        }
                    }

                    if (!isValid)
                    {
                        break;
                    }
                }
            }

            return isValid;
        }

        private static byte[] FileToByteArray(string fileName)
        {
            byte[] buff = null;
            using (FileStream fs = new FileStream(fileName, FileMode.Open, FileAccess.Read))
            {
                BinaryReader br = new BinaryReader(fs);
                long numBytes = new FileInfo(fileName).Length;
                buff = br.ReadBytes((int)numBytes);
            }
            return buff;
        }

        private void AttachRibbonHandlers()
        {
            this.ribbon.ValidateClicked += new EventHandler(OnValidateClicked);
            this.ribbon.FixAllErrorsClicked += new EventHandler(OnFixAllErrorsClicked);
            this.ribbon.GenerateMetadataClicked += new EventHandler(OnGenerateMetadataClicked);
            this.ribbon.GenerateParaMetaDataClicked += new EventHandler(OnGenerateParaMetadataClicked);
            this.ribbon.ClearParameterMetaDataClicked += new EventHandler(OnClearParameterMetaDataClicked);
            this.ribbon.GenerateCitationClicked += new EventHandler(OnGenerateCitationClicked);
            this.ribbon.PostToRepositoryClicked += new EventHandler(OnPostToRepositoryClicked);
        }

        private void InitializeManagers()
        {
            excelManager = new ExcelManager(Globals.ThisAddIn.Application.ActiveWorkbook);
            metadataManager = new MetadataManager(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.Factory);
            repositoryManager = new RepositoryManager(Globals.ThisAddIn.Application.ActiveWorkbook, Globals.Factory);
        }

        private void OnWorkbookActivate(Microsoft.Office.Interop.Excel.Workbook Wb)
        {
            this.InitializeManagers();

            this.ribbon.HideCustomTaskPane();

            Wb.SheetChange += new Microsoft.Office.Interop.Excel.WorkbookEvents_SheetChangeEventHandler(OnSheetChange);
        }

        private void OnSheetChange(object Sh, Microsoft.Office.Interop.Excel.Range Target)
        {
            try
            {
                Microsoft.Office.Interop.Excel.Worksheet workSheet = Sh as Microsoft.Office.Interop.Excel.Worksheet;

                if (workSheet.Name.Equals(Common.Constants.MetadataSheetName))
                {
                    if (Target != null)
                    {
                        Microsoft.Office.Interop.Excel.Range activeCell = (Microsoft.Office.Interop.Excel.Range)Target;
                        if (activeCell != null && activeCell.Column == 6)
                        {
                            string cellValue = activeCell.Value == null ? string.Empty : Convert.ToString(activeCell.Value);

                            var unitCell = activeCell.Cells.Next;
                            var address = Target.get_Address();
                            if (cellValue.Equals("Numeric"))
                            {
                                unitCell.Validation.Delete();
                                unitCell.Validation.Add(Microsoft.Office.Interop.Excel.XlDVType.xlValidateList
                                    , Microsoft.Office.Interop.Excel.XlDVAlertStyle.xlValidAlertInformation
                                    , Microsoft.Office.Interop.Excel.XlFormatConditionOperator.xlBetween
                                    , "=$M:$M");

                                unitCell.Validation.ErrorMessage = "You have entered a new custom unit.";
                                unitCell.Validation.ErrorTitle = "DataUp.";
                                unitCell.Validation.ShowError = false;

                                unitCell.Validation.InCellDropdown = true;
                            }
                            else if (unitCell != null)
                            {
                                if (unitCell.Value != null)
                                {
                                    unitCell.Clear();
                                }
                                unitCell.Validation.Delete();
                            }
                        }
                    }
                }
            }
            catch { }
        }

        private void OnValidateClicked(object sender, EventArgs e)
        {
            Validate();
        }

        private void OnFixAllErrorsClicked(object sender, EventArgs e)
        {
            ResolveAllErrors();
        }

        private void OnGenerateMetadataClicked(object sender, EventArgs e)
        {
            try
            {
                MetadataViewPaneViewModel viewModel = new MetadataViewPaneViewModel()
                {
                    MetadataListViewModel = GetMetadata()
                };

                CreateMetadata(viewModel);

                ActivateRibbonTab();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        private void OnGenerateParaMetadataClicked(object sender, EventArgs e)
        {
            GenerateParaMetadata();
        }

        private void OnClearParameterMetaDataClicked(object sender, EventArgs e)
        {
            metadataManager.ClearAllParameter();
        }

        private void OnGenerateCitationClicked(object sender, EventArgs e)
        {
            try
            {
                bool isContinue = true;

                MetadataListViewModel metadataListViewModel = GetMetadata();

                // 1. Is metadata sheet present?
                if (!this.metadataManager.IsMetadataSheetAvailable())
                {
                    isContinue = GenerateMetadata(metadataListViewModel);

                    metadataListViewModel = GetMetadata();
                }

                if (isContinue)
                {
                    UpdateCitation(metadataListViewModel);
                }

                ActivateRibbonTab();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        private void OnPostToRepositoryClicked(object sender, EventArgs e)
        {
            try
            {
                PostWizard dialog = new PostWizard();
                System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(dialog);
                helper.Owner = (IntPtr)ThisAddIn.ExcelApplication.Hwnd;
                PostWizardViewModel postWizardViewModel = new PostWizardViewModel();
                postWizardViewModel.RequestClose += new EventHandler(dialog.OnRequestClose);

                // TODO : Initialize
                postWizardViewModel.ShowSelectTab = true;

                postWizardViewModel.Filename = excelManager.GetWorkbookName();

                dialog.Model = postWizardViewModel;

                dialog.UpdateLayout();
                dialog.ShowDialog();

                postWizardViewModel.RequestClose -= new EventHandler(dialog.OnRequestClose);

                dialog.Close();

                ActivateRibbonTab();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, Resources.DialogTitle);
            }
        }

        private bool GenerateMetadata(MetadataListViewModel metadataListViewModel)
        {
            bool isContinue = false;
            var result = AlertHelper.ShowAlert(
                AlertType.GenerateMetadata
                , Resources.GenerateMetadata
                , "Generate Metadata"
                , Resources.IgnoreButtonLabel
                , false);

            switch (result)
            {
                case AlertResult.Generate:
                    {
                        isContinue = CreateMetadata(new MetadataViewPaneViewModel() { MetadataListViewModel = metadataListViewModel });
                        break;
                    }
                default:
                    isContinue = false;
                    break;
            }

            return isContinue;
        }

        private bool CreateMetadata(MetadataViewPaneViewModel metadataViewPaneViewModel)
        {
            bool isSuccess = false;

            MetadataViewPane dialog = new MetadataViewPane();
            System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(dialog);
            helper.Owner = (IntPtr)ThisAddIn.ExcelApplication.Hwnd;

            metadataViewPaneViewModel.RequestClose += new EventHandler(dialog.OnRequestClose);
            dialog.Model = metadataViewPaneViewModel;

            dialog.UpdateLayout();

            dialog.ShowDialog();

            if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
            {
                isSuccess = true;
            }

            metadataViewPaneViewModel.RequestClose -= new EventHandler(dialog.OnRequestClose);

            metadataViewPaneViewModel = dialog.Model;

            dialog.Close();

            ActivateRibbonTab();

            return isSuccess;
        }

        private void UpdateCitation(MetadataListViewModel metadataListViewModel)
        {
            GenerateCitationViewPane dialog = new GenerateCitationViewPane();
            System.Windows.Interop.WindowInteropHelper helper = new System.Windows.Interop.WindowInteropHelper(dialog);
            helper.Owner = (IntPtr)ThisAddIn.ExcelApplication.Hwnd;

            GenerateCitationPaneViewModel viewModel = new GenerateCitationPaneViewModel();
            viewModel.RequestClose += new EventHandler(dialog.OnRequestClose);

            // Add Citation
            viewModel.MetadataListViewModel = metadataListViewModel;

            viewModel.CitationViewModel.LoadValues(metadataListViewModel);

            dialog.Model = viewModel;

            dialog.UpdateLayout();
            dialog.ShowDialog();

            //if (dialog.DialogResult.HasValue && dialog.DialogResult.Value)
            //{
            //    List<MetadataDetail> updatedMetadata = new List<MetadataDetail>();
            //    foreach (var item in metadataListViewModel.MetadataList)
            //    {
            //        MetadataDetail model = new MetadataDetail();
            //        if (item.Name == Common.Constants.CitationContent)
            //        {
            //            item.Value = metadataListViewModel.Citation;
            //        }
            //        model.SetValuesFrom(item);
            //        updatedMetadata.Add(model);
            //    }
            //    metadataManager.UpdateMetadata(updatedMetadata);
            //}

            metadataListViewModel.RequestClose -= new EventHandler(dialog.OnRequestClose);
            dialog.Close();
        }

        private void ActivateRibbonTab()
        {
            this.ribbon.RibbonUI.ActivateTab(this.ribbon.Tabs[0].ControlId.ToString());
        }
    }
}