/
WorkflowDesignerViewModel.cs
2009 lines (1737 loc) · 83.3 KB
/
WorkflowDesignerViewModel.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
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
using System;
using System.Activities;
using System.Activities.Core.Presentation;
using System.Activities.Debugger;
using System.Activities.Presentation;
using System.Activities.Presentation.Metadata;
using System.Activities.Presentation.Model;
using System.Activities.Presentation.Services;
using System.Activities.Presentation.View;
using System.Activities.Statements;
using System.Collections;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Xaml;
using System.Xml.Linq;
using Caliburn.Micro;
using Dev2.Activities;
using Dev2.Activities.Designers2.Core;
using Dev2.AppResources.Converters;
using Dev2.Common;
using Dev2.Common.Common;
using Dev2.Common.Interfaces.Core.Collections;
using Dev2.Common.Interfaces.Infrastructure.Providers.Errors;
using Dev2.Common.Interfaces.Security;
using Dev2.Common.Interfaces.Studio.Controller;
using Dev2.CustomControls.Utils;
using Dev2.Data.Interfaces;
using Dev2.Data.SystemTemplates.Models;
using Dev2.Data.Util;
using Dev2.DataList.Contract;
using Dev2.Dialogs;
using Dev2.Enums;
using Dev2.Factories;
using Dev2.Factory;
using Dev2.Interfaces;
using Dev2.Messages;
using Dev2.Models;
using Dev2.Runtime.Configuration.ViewModels.Base;
using Dev2.Services.Events;
using Dev2.Services.Security;
using Dev2.Studio.ActivityDesigners;
using Dev2.Studio.AppResources.AttachedProperties;
using Dev2.Studio.AppResources.ExtensionMethods;
using Dev2.Studio.Core;
using Dev2.Studio.Core.Activities.Services;
using Dev2.Studio.Core.Activities.Utils;
using Dev2.Studio.Core.AppResources.DependencyInjection.EqualityComparers;
using Dev2.Studio.Core.AppResources.Enums;
using Dev2.Studio.Core.Factories;
using Dev2.Studio.Core.Interfaces;
using Dev2.Studio.Core.Interfaces.DataList;
using Dev2.Studio.Core.Messages;
using Dev2.Studio.Core.Network;
using Dev2.Studio.Core.Utils;
using Dev2.Studio.Core.ViewModels;
using Dev2.Studio.ViewModels.WorkSurface;
using Dev2.Threading;
using Dev2.UndoFramework;
using Dev2.Utilities;
using Dev2.Utils;
using Dev2.ViewModels.Workflow;
using Dev2.Workspaces;
using Unlimited.Applications.BusinessDesignStudio.Activities;
// ReSharper disable CheckNamespace
namespace Dev2.Studio.ViewModels.Workflow
// ReSharper restore CheckNamespace
{
public class WorkflowDesignerViewModel : BaseWorkSurfaceViewModel,
IHandle<AddStringListToDataListMessage>,
IHandle<EditActivityMessage>,
IHandle<SaveUnsavedWorkflowMessage>,
IHandle<UpdateWorksurfaceFlowNodeDisplayName>, IWorkflowDesignerViewModel
{
static readonly Type[] DecisionSwitchTypes = { typeof(FlowSwitch<string>), typeof(FlowDecision) };
#region Overrides of Screen
public delegate void SourceLocationEventHandler(SourceLocation src);
protected readonly IDesignerManagementService DesignerManagementService;
readonly IWorkflowHelper _workflowHelper;
DelegateCommand _collapseAllCommand;
protected dynamic DataObject { get; set; }
List<ModelItem> _selectedDebugItems = new List<ModelItem>();
DelegateCommand _expandAllCommand;
protected ModelService ModelService;
UserControl _popupContent;
IContextualResourceModel _resourceModel;
Dictionary<IDataListVerifyPart, string> _uniqueWorkflowParts;
// ReSharper disable InconsistentNaming
protected WorkflowDesigner _wd;
DesignerMetadata _wdMeta;
protected DsfActivityDropViewModel _vm;
ResourcePickerDialog _resourcePickerDialog;
VirtualizedContainerService _virtualizedContainerService;
MethodInfo _virtualizedContainerServicePopulateAllMethod;
StudioSubscriptionService<DebugSelectionChangedEventArgs> _debugSelectionChangedService = new StudioSubscriptionService<DebugSelectionChangedEventArgs>();
#endregion
#region Constructor
public WorkflowDesignerViewModel(IContextualResourceModel resource, bool createDesigner = true)
: this(resource, new WorkflowHelper(), createDesigner)
{
}
public WorkflowDesignerViewModel(IContextualResourceModel resource, IWorkflowHelper workflowHelper, bool createDesigner = true)
: this(EventPublishers.Aggregator, resource, workflowHelper, createDesigner)
{
}
public WorkflowDesignerViewModel(IEventAggregator eventPublisher, IContextualResourceModel resource, IWorkflowHelper workflowHelper, bool createDesigner = true)
: this(eventPublisher, resource, workflowHelper,
CustomContainer.Get<IPopupController>(), createDesigner)
{
}
// BUG 9304 - 2013.05.08 - TWR - Added IWorkflowHelper parameter to facilitate testing
// TODO Can we please not overload constructors for testing purposes. Need to systematically get rid of singletons.
public WorkflowDesignerViewModel(IEventAggregator eventPublisher, IContextualResourceModel resource, IWorkflowHelper workflowHelper, IPopupController popupController, bool createDesigner = true, bool liteInit = false)
: base(eventPublisher)
{
VerifyArgument.IsNotNull("workflowHelper", workflowHelper);
VerifyArgument.IsNotNull("popupController", popupController);
_workflowHelper = workflowHelper;
_resourceModel = resource;
_resourceModel.OnDataListChanged += FireWdChanged;
_resourceModel.OnResourceSaved += UpdateOriginalDataList;
PopUp = popupController;
if(_resourceModel.DataList != null)
{
SetOriginalDataList(_resourceModel);
}
DesignerManagementService = new DesignerManagementService(resource, _resourceModel.Environment.ResourceRepository);
if(createDesigner)
{
ActivityDesignerHelper.AddDesignerAttributes(this, liteInit);
}
OutlineViewTitle = "Navigation Pane";
_workflowInputDataViewModel = WorkflowInputDataViewModel.Create(_resourceModel);
GetWorkflowLink();
}
void SetOriginalDataList(IContextualResourceModel contextualResourceModel)
{
if(!string.IsNullOrEmpty(contextualResourceModel.DataList))
{
_originalDataList = contextualResourceModel.DataList.Replace("<DataList>", "").Replace("</DataList>", "").Replace(Environment.NewLine, "").Trim();
}
}
void UpdateOriginalDataList(IContextualResourceModel obj)
{
if(obj.IsWorkflowSaved)
{
SetOriginalDataList(obj);
}
}
#endregion
#region Properties
public override bool CanSave { get { return ResourceModel.IsAuthorized(AuthorizationContext.Contribute); } }
protected virtual bool IsDesignerViewVisible { get { return DesignerView.IsVisible; } }
public override string DisplayName
{
get
{
var displayName = ResourceModel.UserPermissions == Permissions.View ?
string.Format("{0} [READONLY]", ResourceHelper.GetDisplayName(ResourceModel)) :
ResourceHelper.GetDisplayName(ResourceModel);
return displayName;
}
}
public string GetWorkflowLink()
{
if(!String.IsNullOrEmpty(_resourceModel.DataList))
{
_workflowInputDataViewModel.DebugTo.DataList = _resourceModel.DataList;
}
_workflowLink = "";
if(_workflowInputDataViewModel != null)
{
_workflowInputDataViewModel.LoadWorkflowInputs();
_workflowInputDataViewModel.SetXmlData();
var buildWebPayLoad = _workflowInputDataViewModel.BuildWebPayLoad();
var workflowUri = WebServer.GetWorkflowUri(_resourceModel, buildWebPayLoad, UrlType.JSON);
if(workflowUri != null)
{
_workflowLink = workflowUri.ToString();
}
}
NotifyOfPropertyChange(() => DisplayWorkflowLink);
return _workflowLink;
}
public string DisplayWorkflowLink
{
get
{
var workflowLink = _workflowLink;
if(!String.IsNullOrEmpty(workflowLink))
{
var startIndex = workflowLink.IndexOf("&wid", StringComparison.InvariantCultureIgnoreCase);
if(startIndex != -1)
{
return workflowLink.Remove(startIndex);
}
}
return workflowLink;
}
}
public Visibility WorkflowLinkVisible
{
get
{
return _resourceModel.IsVersionResource ? Visibility.Hidden : Visibility.Visible;
}
}
public override string IconPath
{
get { return ResourceHelper.GetIconPath(ResourceModel); }
}
//2012.10.01: massimo.guerrera - Add Remove buttons made into one:)
public IPopupController PopUp { get; set; }
// ReSharper disable UnusedAutoPropertyAccessor.Local
public IList<IDataListVerifyPart> WorkflowVerifiedDataParts { get; private set; }
// ReSharper restore UnusedAutoPropertyAccessor.Local
public UserControl PopupContent
{
get { return _popupContent; }
set
{
_popupContent = value;
NotifyOfPropertyChange(() => PopupContent);
}
}
public virtual object SelectedModelItem
{
get
{
if(_wd != null)
{
return _wd.Context.Items.GetValue<Selection>().SelectedObjects.FirstOrDefault();
}
return null;
}
}
public bool HasErrors { get; set; }
public IContextualResourceModel ResourceModel { get { return _resourceModel; } set { _resourceModel = value; } }
public string WorkflowName { get { return _resourceModel.ResourceName; } }
public bool RequiredSignOff { get { return _resourceModel.RequiresSignOff; } }
public WorkflowDesigner Designer { get { return _wd; } }
public UIElement DesignerView
{
get
{
return _wd.View;
}
}
public StringBuilder DesignerText { get { return ServiceDefinition; } }
// BUG 9304 - 2013.05.08 - TWR - Refactored and removed setter
public StringBuilder ServiceDefinition { get { return _workflowHelper.SerializeWorkflow(ModelService); } set { } }
public string OutlineViewTitle { get; set; }
#endregion
#region Commands
public ICommand CollapseAllCommand
{
get
{
return _collapseAllCommand ?? (_collapseAllCommand = new DelegateCommand(param =>
{
bool val = Convert.ToBoolean(param);
if(val)
{
DesignerManagementService.RequestCollapseAll();
}
else
{
DesignerManagementService.RequestRestoreAll();
}
}));
}
}
public ICommand ExpandAllCommand
{
get
{
return _expandAllCommand ?? (_expandAllCommand = new DelegateCommand(param =>
{
bool val = Convert.ToBoolean(param);
if(val)
{
DesignerManagementService.RequestExpandAll();
}
else
{
DesignerManagementService.RequestRestoreAll();
}
}));
}
}
public ICommand OpenWorkflowLinkCommand
{
get
{
return _openWorkflowLinkCommand ?? (_openWorkflowLinkCommand = new DelegateCommand(param =>
{
if(!String.IsNullOrEmpty(_workflowLink))
{
if(_workflowInputDataViewModel.WorkflowInputCount == 0)
{
PopUp.ShowNoInputsSelectedWhenClickLink();
}
if(param.ToString() != "Do not perform action")
{
Process.Start(_workflowLink);
}
}
}));
}
}
#endregion
#region Private Methods
protected List<ModelItem> PerformAddItems(List<ModelItem> addedItems)
{
for(int i = 0; i < addedItems.Count(); i++)
{
var mi = addedItems.ToList()[i];
if(mi.Content != null)
{
var computedValue = mi.Content.ComputedValue;
if(computedValue is IDev2Activity)
{
//2013.08.19: Ashley Lewis for bug 10116 - New unique id on paste
(computedValue as IDev2Activity).UniqueID = Guid.NewGuid().ToString();
}
}
if(mi.Parent != null &&
mi.Parent.Parent != null &&
mi.Parent.Parent.Parent != null &&
mi.Parent.Parent.Parent.ItemType == typeof(FlowSwitch<string>))
{
#region Extract the Switch Expression ;)
ModelProperty activityExpression = mi.Parent.Parent.Parent.Properties["Expression"];
if(activityExpression != null)
{
var tmpModelItem = activityExpression.Value;
var switchExpressionValue = string.Empty;
if(tmpModelItem != null)
{
var tmpProperty = tmpModelItem.Properties["ExpressionText"];
if(tmpProperty != null)
{
if(tmpProperty.Value != null)
{
var tmp = tmpProperty.Value.ToString();
if(!string.IsNullOrEmpty(tmp))
{
int start = tmp.IndexOf("(", StringComparison.Ordinal);
int end = tmp.IndexOf(",", StringComparison.Ordinal);
if(start < end && start >= 0)
{
start += 2;
end -= 1;
switchExpressionValue = tmp.Substring(start, (end - start));
}
}
}
}
}
#endregion
ModelProperty modelProperty = mi.Properties["Key"];
if(modelProperty != null && ((modelProperty.Value != null) && modelProperty.Value.ToString().Contains("Case")))
{
Dev2Logger.Log.Info("Publish message of type - " + typeof(ConfigureCaseExpressionMessage));
EventPublisher.Publish(new ConfigureCaseExpressionMessage { ModelItem = mi, ExpressionText = switchExpressionValue, EnvironmentModel = _resourceModel.Environment });
}
}
}
if(mi.ItemType == typeof(FlowSwitch<string>))
{
InitializeFlowSwitch(mi);
}
else if(mi.ItemType == typeof(FlowDecision))
{
InitializeFlowDecision(mi);
}
else if(mi.ItemType == typeof(FlowStep))
{
InitializeFlowStep(mi);
}
}
return addedItems;
}
protected void InitializeFlowStep(ModelItem mi)
{
ModelProperty modelProperty = mi.Properties["Action"];
if(modelProperty != null && modelProperty.ComputedValue is DsfWebPageActivity)
{
var modelService = Designer.Context.Services.GetService<ModelService>();
var items = modelService.Find(modelService.Root, typeof(DsfWebPageActivity));
IEnumerable<ModelItem> modelItems = items as IList<ModelItem> ?? items.ToList();
int totalActivities = modelItems.Count();
ModelProperty property = modelItems.Last().Properties["DisplayName"];
if(property != null)
{
property.SetValue(string.Format("Webpage {0}", totalActivities));
}
}
// PBI 9135 - 2013.07.15 - TWR - Changed to "as" check so that database activity also flows through this
ModelProperty modelProperty1 = mi.Properties["Action"];
if(modelProperty1 != null)
{
var droppedActivity = modelProperty1.ComputedValue as DsfActivity;
if(droppedActivity != null)
{
if(!string.IsNullOrEmpty(droppedActivity.ServiceName))
{
//06-12-2012 - Massimo.Guerrera - Added for PBI 6665
DsfActivity activity = droppedActivity;
IContextualResourceModel resource = _resourceModel.Environment.ResourceRepository.FindSingle(
c => c.Category == activity.ServiceName) as IContextualResourceModel;
droppedActivity = DsfActivityFactory.CreateDsfActivity(resource, droppedActivity, false, EnvironmentRepository.Instance, _resourceModel.Environment.IsLocalHostCheck());
modelProperty1.SetValue(droppedActivity);
}
else
{
if(DataObject != null)
{
var navigationItemViewModel = DataObject as ExplorerItemModel;
if(navigationItemViewModel != null)
{
IEnvironmentModel environmentModel = EnvironmentRepository.Instance.FindSingle(c => c.ID == navigationItemViewModel.EnvironmentId);
if(environmentModel != null)
{
var theResource = environmentModel.ResourceRepository.FindSingle(c => c.ID == navigationItemViewModel.ResourceId) as IContextualResourceModel;
//06-12-2012 - Massimo.Guerrera - Added for PBI 6665
DsfActivity d = DsfActivityFactory.CreateDsfActivity(theResource, droppedActivity, true, EnvironmentRepository.Instance, _resourceModel.Environment.IsLocalHostCheck());
d.ServiceName = d.DisplayName = d.ToolboxFriendlyName = navigationItemViewModel.ResourcePath;
if(theResource != null)
{
d.ServiceName = d.DisplayName = d.ToolboxFriendlyName = theResource.Category;
}
ExplorerItemModelToIconConverter converter = new ExplorerItemModelToIconConverter();
var bitmapImage = converter.Convert(new object[] { navigationItemViewModel.ResourceType, false }, null, null, null) as BitmapImage;
if(bitmapImage != null)
{
d.IconPath = bitmapImage.UriSource.ToString();
}
UpdateForRemote(d, theResource);
//08-07-2013 Removed for bug 9789 - droppedACtivity Is already the action
//Setting it twice causes double connection to startnode
}
}
DataObject = null;
}
else
{
//Massimo.Guerrera:17-04-2012 - PBI 9000
if(_vm != null)
{
IContextualResourceModel resource = _vm.SelectedResourceModel;
if(resource != null)
{
droppedActivity.ServiceName = droppedActivity.DisplayName = droppedActivity.ToolboxFriendlyName = resource.Category;
droppedActivity = DsfActivityFactory.CreateDsfActivity(resource, droppedActivity, false, EnvironmentRepository.Instance, _resourceModel.Environment.IsLocalHostCheck());
modelProperty1.SetValue(droppedActivity);
}
_vm = null;
}
}
}
}
}
}
protected void InitializeFlowSwitch(ModelItem mi)
{
// Travis.Frisinger : 28.01.2013 - Switch Amendments
Dev2Logger.Log.Info("Publish message of type - " + typeof(ConfigureSwitchExpressionMessage));
EventPublisher.Publish(new ConfigureSwitchExpressionMessage { ModelItem = mi, EnvironmentModel = _resourceModel.Environment, IsNew = true });
}
protected void InitializeFlowDecision(ModelItem mi)
{
Dev2Logger.Log.Info("Publish message of type - " + typeof(ConfigureDecisionExpressionMessage));
EventPublisher.Publish(new ConfigureDecisionExpressionMessage { ModelItem = mi, EnvironmentModel = _resourceModel.Environment, IsNew = true });
}
public void EditActivity(ModelItem modelItem, Guid parentEnvironmentID, IEnvironmentRepository catalog)
{
if(Designer == null)
{
return;
}
var modelService = Designer.Context.Services.GetService<ModelService>();
if(modelService.Root == modelItem.Root && (modelItem.ItemType == typeof(DsfActivity) || modelItem.ItemType.BaseType == typeof(DsfActivity)))
{
var resourceID = ModelItemUtils.TryGetResourceID(modelItem);
var envID = ModelItemUtils.GetProperty("EnvironmentID", modelItem) as InArgument<Guid>;
Guid environmentID;
if(envID != null)
{
Guid.TryParse(envID.Expression.ToString(), out environmentID);
}
else
{
environmentID = parentEnvironmentID;
}
if(environmentID == Guid.Empty)
{
// this was created on a localhost ... BUT ... we may be running it remotely!
// so, ensure that we are running in the context of the parent's environment
environmentID = parentEnvironmentID;
}
var environmentModel = catalog.FindSingle(c => c.ID == environmentID);
if(environmentID == Guid.Empty && !catalog.ActiveEnvironment.IsLocalHostCheck())
{
// we have an "localhost" environment id, yet it is not the active environment, must be remote execution
// against a remote server, aka remote treated as local ;)
environmentModel = catalog.ActiveEnvironment;
}
if(environmentModel != null)
{
// BUG 9634 - 2013.07.17 - TWR : added connect
if(!environmentModel.IsConnected)
{
environmentModel.Connect();
environmentModel.LoadResources();
}
IResourceModel resource;
if(resourceID != Guid.Empty)
{
resource = environmentModel.ResourceRepository.FindSingle(c => c.ID == resourceID);
}
else
{
var resourceName = ModelItemUtils.GetProperty("ServiceName", modelItem) as string;
resource = environmentModel.ResourceRepository.FindSingle(c => c.ResourceName == resourceName);
}
if(resource != null && environmentModel.AuthorizationService.IsAuthorized(AuthorizationContext.View, resource.ID.ToString()))
{
WorkflowDesignerUtils.EditResource(resource, EventPublisher);
}
}
}
}
ModelItem RecursiveForEachCheck(dynamic activity)
{
var innerAct = activity.DataFunc.Handler as ModelItem;
if(innerAct != null)
{
if(innerAct.ItemType == typeof(DsfForEachActivity))
{
innerAct = RecursiveForEachCheck(innerAct);
}
}
return innerAct;
}
/// <summary>
/// Prevents the delete from being executed if it is a FlowChart.
/// </summary>
/// <param name="e">
/// The <see cref="CanExecuteRoutedEventArgs" /> instance containing the event data.
/// </param>
void PreventCommandFromBeingExecuted(CanExecuteRoutedEventArgs e)
{
if(Designer != null && Designer.Context != null)
{
var selection = Designer.Context.Items.GetValue<Selection>();
if(selection == null || selection.PrimarySelection == null)
return;
if(selection.PrimarySelection.ItemType != typeof(Flowchart) &&
selection.SelectedObjects.All(modelItem => modelItem.ItemType != typeof(Flowchart)))
return;
}
e.CanExecute = false;
e.Handled = true;
}
/// <summary>
/// Sets the last dropped point.
/// </summary>
/// <param name="e">
/// The <see cref="DragEventArgs" /> instance containing the event data.
/// </param>
void SetLastDroppedPoint(DragEventArgs e)
{
var senderAsFrameworkElement = ModelService.Root.View as FrameworkElement;
if(senderAsFrameworkElement != null)
{
UIElement freePormPanel = senderAsFrameworkElement.FindNameAcrossNamescopes("flowchartPanel");
if(freePormPanel != null)
{
e.GetPosition(freePormPanel);
}
}
}
#region DataList Workflow Specific Methods
// We will be assuming that a workflow field is a recordset based on 2 criteria:
// 1. If the field contains a set of parenthesis
// 2. If the field contains a period, it is a recordset with a field.
IList<IDataListVerifyPart> BuildWorkflowFields()
{
var dataPartVerifyDuplicates = new DataListVerifyPartDuplicationParser();
_uniqueWorkflowParts = new Dictionary<IDataListVerifyPart, string>(dataPartVerifyDuplicates);
if(Designer != null)
{
var modelService = Designer.Context.Services.GetService<ModelService>();
if(modelService != null)
{
var flowNodes = modelService.Find(modelService.Root, typeof(FlowNode));
foreach(var flowNode in flowNodes)
{
var workflowFields = GetWorkflowFieldsFromModelItem(flowNode);
foreach(var field in workflowFields)
{
WorkflowDesignerDataPartUtils.BuildDataPart(field, _uniqueWorkflowParts);
}
}
}
}
var flattenedList = _uniqueWorkflowParts.Keys.ToList();
return flattenedList;
}
IEnumerable<string> GetWorkflowFieldsFromModelItem(ModelItem flowNode)
{
var workflowFields = new List<string>();
var modelProperty = flowNode.Properties["Action"];
if(modelProperty != null)
{
var activity = modelProperty.ComputedValue;
workflowFields = GetActivityElements(activity);
}
else
{
string propertyName = string.Empty;
switch(flowNode.ItemType.Name)
{
case "FlowDecision":
propertyName = "Condition";
break;
case "FlowSwitch`1":
propertyName = "Expression";
break;
}
var property = flowNode.Properties[propertyName];
if(property != null)
{
var activity = property.ComputedValue;
if(activity != null)
{
workflowFields = GetDecisionElements((activity as dynamic).ExpressionText, DataListSingleton.ActiveDataList);
}
}
else
{
return workflowFields;
}
}
return workflowFields;
}
public List<String> GetDecisionElements(string expression, IDataListViewModel datalistModel)
{
var decisionFields = new List<string>();
if(!string.IsNullOrEmpty(expression))
{
int startIndex = expression.IndexOf('"');
startIndex = startIndex + 1;
int endindex = expression.IndexOf('"', startIndex);
string decisionValue = expression.Substring(startIndex, endindex - startIndex);
//2013.06.21: Ashley Lewis for bug 9698 - avoid parsing entire decision stack, instantiate model and just parse column data only
IDataListCompiler c = DataListFactory.CreateDataListCompiler();
try
{
var dds = c.ConvertFromJsonToModel<Dev2DecisionStack>(decisionValue.Replace('!', '\"'));
foreach(var decision in dds.TheStack)
{
var getCols = new[] { decision.Col1, decision.Col2, decision.Col3 };
for(var i = 0; i < 3; i++)
{
var getCol = getCols[i];
decisionFields = decisionFields.Union(GetParsedRegions(getCol, datalistModel)).ToList();
}
}
}
catch(Exception)
{
IList<IIntellisenseResult> parts = DataListFactory.CreateLanguageParser().ParseDataLanguageForIntellisense(decisionValue,
DataListSingleton
.ActiveDataList
.WriteToResourceModel
(), true);
decisionFields.AddRange(parts.Select(part => DataListUtil.StripBracketsFromValue(part.Option.DisplayValue)));
}
}
return decisionFields;
}
static IEnumerable<string> GetParsedRegions(string getCol, IDataListViewModel datalistModel)
{
var result = new List<string>();
// Travis.Frisinger - 25.01.2013
// We now need to parse this data for regions ;)
IDev2DataLanguageParser parser = DataListFactory.CreateLanguageParser();
// NEED - DataList for active workflow
var parts = parser.ParseDataLanguageForIntellisense(getCol, datalistModel.WriteToResourceModel(), true);
foreach(var intellisenseResult in parts)
{
getCol = DataListUtil.StripBracketsFromValue(intellisenseResult.Option.DisplayValue);
if(!string.IsNullOrEmpty(getCol))
{
result.Add(getCol);
}
}
return result;
}
List<String> GetActivityElements(object activity)
{
var assign = activity as DsfActivityAbstract<string>;
var other = activity as DsfActivityAbstract<bool>;
enFindMissingType findMissingType;
if(assign != null)
{
findMissingType = assign.GetFindMissingType();
}
else if(other != null)
{
findMissingType = other.GetFindMissingType();
}
else
{
return new List<String>();
}
var activityFields = new List<string>();
var stratFac = new Dev2FindMissingStrategyFactory();
IFindMissingStrategy strategy = stratFac.CreateFindMissingStrategy(findMissingType);
foreach(var activityField in strategy.GetActivityFields(activity))
{
if(!string.IsNullOrEmpty(activityField))
{
WorkflowDesignerUtils wdu = new WorkflowDesignerUtils();
activityFields.AddRange(wdu.FormatDsfActivityField(activityField).Where(item => !item.Contains("xpath(")));
}
}
return activityFields;
}
#endregion
#endregion
#region Internal Methods
internal void OnItemSelected(Selection item)
{
NotifyItemSelected(item.PrimarySelection);
}
#endregion Internal Methods
#region Public Methods
/// <summary>
/// Handels the list of strings to be added to the data list without a pop up message
/// </summary>
/// <param name="message">The message.</param>
/// <author>Massimo.Guerrera</author>
/// <date>2013/02/06</date>
public void Handle(AddStringListToDataListMessage message)
{
Dev2Logger.Log.Info(message.GetType().Name);
IDataListViewModel dlvm = DataListSingleton.ActiveDataList;
if(dlvm != null)
{
var dataPartVerifyDuplicates = new DataListVerifyPartDuplicationParser();
_uniqueWorkflowParts = new Dictionary<IDataListVerifyPart, string>(dataPartVerifyDuplicates);
foreach(var s in message.ListToAdd)
{
WorkflowDesignerDataPartUtils.BuildDataPart(s, _uniqueWorkflowParts);
}
IList<IDataListVerifyPart> partsToAdd = _uniqueWorkflowParts.Keys.ToList();
List<IDataListVerifyPart> uniqueDataListPartsToAdd = dlvm.MissingDataListParts(partsToAdd);
dlvm.AddMissingDataListItems(uniqueDataListPartsToAdd);
}
}
/// <summary>
/// Handles the specified message.
/// </summary>
/// <param name="message">The message.</param>
public void Handle(UpdateResourceMessage message)
{
Dev2Logger.Log.Debug(message.GetType().Name);
if(ContexttualResourceModelEqualityComparer.Current.Equals(message.ResourceModel, _resourceModel))
{
IObservableReadOnlyList<IErrorInfo> currentErrors = null;
if(message.ResourceModel.Errors != null && message.ResourceModel.Errors.Count > 0)
{
currentErrors = message.ResourceModel.Errors;
}
_resourceModel.Update(message.ResourceModel);
if(currentErrors != null && currentErrors.Count > 0)
{
foreach(var currentError in currentErrors)
{
_resourceModel.AddError(currentError);
}
}
}
}
/// <summary>
/// Notifies the item selected.
/// </summary>
/// <param name="primarySelection">The primary selection.</param>
/// <returns></returns>
public bool NotifyItemSelected(object primarySelection)
{
var selectedItem = primarySelection as ModelItem;
bool isItemSelected = false;
if(selectedItem != null)
{
if(selectedItem.ItemType == typeof(DsfForEachActivity))
{
dynamic test = selectedItem;
ModelItem innerActivity = RecursiveForEachCheck(test);
if(innerActivity != null)
{
selectedItem = innerActivity;
}
}
if(selectedItem.Properties["DisplayName"] != null)
{
var modelProperty = selectedItem.Properties["DisplayName"];
if(modelProperty != null)
{
string displayName = modelProperty.ComputedValue.ToString();
var resourceModel =
_resourceModel.Environment.ResourceRepository.All()
.FirstOrDefault(
resource =>
resource.ResourceName.Equals(displayName,
StringComparison.InvariantCultureIgnoreCase));
if(resourceModel != null || selectedItem.ItemType == typeof(DsfWebPageActivity))
{
WebActivityFactory.CreateWebActivity(selectedItem, resourceModel as IContextualResourceModel, displayName);
isItemSelected = true;
}
}
}
}
return isItemSelected;
}
/// <summary>
/// Saves the new XAML ;)
/// </summary>
public void BindToModel()
{
_resourceModel.WorkflowXaml = ServiceDefinition;
}
/// <summary>
/// Initializes the designer.
/// </summary>
/// <param name="designerAttributes">The designer attributes.</param>
/// <param name="liteInit">if set to <c>true</c> [lite initialize]. THIS IS FOR TESTING!!!!</param>
public void InitializeDesigner(IDictionary<Type, Type> designerAttributes, bool liteInit = false)
{
_wd = new WorkflowDesigner();
if(!liteInit)
{
var hashTable = new Hashtable
{
{WorkflowDesignerColors.FontFamilyKey, Application.Current.Resources["DefaultFontFamily"]},
{WorkflowDesignerColors.FontSizeKey, Application.Current.Resources["DefaultFontSize"]},
{WorkflowDesignerColors.FontWeightKey, Application.Current.Resources["DefaultFontWeight"]},
{WorkflowDesignerColors.RubberBandRectangleColorKey, Application.Current.Resources["DesignerBackground"]},
{WorkflowDesignerColors.WorkflowViewElementBackgroundColorKey, Application.Current.Resources["WorkflowBackgroundBrush"]},
{WorkflowDesignerColors.WorkflowViewElementSelectedBackgroundColorKey, Application.Current.Resources["WorkflowBackgroundBrush"]},
{WorkflowDesignerColors.WorkflowViewElementSelectedBorderColorKey, Application.Current.Resources["WorkflowSelectedBorderBrush"]},
{WorkflowDesignerColors.DesignerViewShellBarControlBackgroundColorKey, Application.Current.Resources["ShellBarViewBackground"]},
{WorkflowDesignerColors.DesignerViewShellBarColorGradientBeginKey, Application.Current.Resources["ShellBarViewBackground"]},
{WorkflowDesignerColors.DesignerViewShellBarColorGradientEndKey, Application.Current.Resources["ShellBarViewBackground"]},
{WorkflowDesignerColors.OutlineViewItemSelectedTextColorKey, Application.Current.Resources["SolidWhite"]},