atlassian.net-sdk /Atlassian.Jira/Issue.cs

Language C# Lines 808
MD5 Hash 5fd58759928e808d07cf895fe50e68d1 Estimated Cost $14,835 (why?)
Repository https://bitbucket.org/miketrebilcock/atlassian.net-sdk.git View Raw File View Project SPDX
  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
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using System.IO;
using System.Collections;
using System.Collections.ObjectModel;
using System.Dynamic;
using Atlassian.Jira.Remote;
using Atlassian.Jira.Linq;
using Newtonsoft.Json.Linq;

namespace Atlassian.Jira
{
    /// <summary>
    /// A JIRA issue
    /// </summary>
    public class Issue : IRemoteIssueFieldProvider
    {
        private readonly Jira _jira;
        private readonly string _parentIssueKey;

        private ComparableString _key;
        private string _project;
        private RemoteIssue _originalIssue;
        private DateTime? _createDate;
        private DateTime? _updateDate;
        private DateTime? _dueDate;
        private ProjectVersionCollection _affectsVersions = null;
        private ProjectVersionCollection _fixVersions = null;
        private ProjectComponentCollection _components = null;
        private CustomFieldCollection _customFields = null;

        /// <summary>
        /// Create an issue to be saved into JIRA
        /// </summary>
        /// <param name="jira">The JIRA server where the issue will be saved at.</param>
        /// <param name="projectKey">The project that the issue will be saved at.</param>
        /// <param name="parentIssueKey">An optional parent issue key</param>
        public Issue(Jira jira, string projectKey, string parentIssueKey = null)
            : this(jira, new RemoteIssue() { project = projectKey }, parentIssueKey)
        {
        }

        /// <summary>
        /// Create an issue from a JSON represantation
        /// </summary>
        /// <param name="jira">The Jira object that retrieved the issue</param>
        /// <param name="json">The JSON representation of this issue</param>
        public static Issue FromJson(Jira jira, string json)
        {
            var jsonIssue = JObject.Parse(json);

            var fields = jsonIssue["fields"] as JObject;
            var remoteIssue = new RemoteIssue()
            {
                key = (string)jsonIssue["key"],
                summary = (string)fields["summary"],
                assignee = fields["assignee"].Type == JTokenType.Null ? null : (string)fields["assignee"]["name"],
                created = fields["created"].Type == JTokenType.Null ? null : (DateTime?)fields["created"],
                duedate = fields["duedate"].Type == JTokenType.Null ? null : (DateTime?)fields["duedate"],
                description = fields["description"].Type == JTokenType.Null ? null : (string)fields["description"],
                environment = fields["environment"].Type == JTokenType.Null ? null : (string)fields["environment"],
                priority = fields["priority"].Type == JTokenType.Null ? null : (string)fields["priority"]["id"],
                project = (string) fields["project"]["key"],
                reporter = fields["reporter"].Type == JTokenType.Null ? null : (string)fields["reporter"]["name"],
                resolution = fields["resolution"].Type == JTokenType.Null? null: (string) fields["resolution"]["id"],
                status = fields["status"].Type == JTokenType.Null? null: (string) fields["status"]["id"],
                type = fields["issuetype"].Type == JTokenType.Null? null: (string) fields["issuetype"]["id"],
                updated = fields["updated"].Type == JTokenType.Null ? null : (DateTime?)fields["updated"],
                votes = fields["votes"].Type == JTokenType.Null ? null : (long?)fields["votes"]["votes"]
            };

            if (fields["versions"].Type != JTokenType.Null)
            {
                remoteIssue.affectsVersions = (from v in (JArray)fields["versions"]
                                               select new RemoteVersion() { id = (string)v["id"], name = (string)v["name"] }).ToArray();
            }
            if (fields["fixVersions"].Type != JTokenType.Null)
            {
                remoteIssue.fixVersions = (from v in (JArray)fields["fixVersions"]
                                               select new RemoteVersion() { id = (string)v["id"], name = (string)v["name"] }).ToArray();
            }
            if (fields["components"].Type != JTokenType.Null)
            {
                remoteIssue.components = (from v in (JArray)fields["components"]
                                           select new RemoteComponent() { id = (string)v["id"], name = (string)v["name"] }).ToArray();
            }

            var customFields = new List<RemoteCustomFieldValue>();
            foreach (var p in fields)
            {
                if (p.Key.StartsWith("customfield", StringComparison.InvariantCulture))
                {
                    customFields.Add(new RemoteCustomFieldValue() { customfieldId = p.Key, values = new string[] { (string)p.Value }});
                }
            }
            remoteIssue.customFieldValues = customFields.Count > 0? customFields.ToArray(): null;

            return new Issue(jira, remoteIssue);
        }

        internal Issue(Jira jira, RemoteIssue remoteIssue, string parentIssueKey = null)
        {
            _jira = jira;
            _parentIssueKey = parentIssueKey;
            Initialize(remoteIssue);
        }

        private void Initialize(RemoteIssue remoteIssue)
        {
            _originalIssue = remoteIssue;

            _project = remoteIssue.project;
            _key = remoteIssue.key;
            _createDate = remoteIssue.created;
            _dueDate = remoteIssue.duedate;
            _updateDate = remoteIssue.updated;

            Assignee = remoteIssue.assignee;
            Description = remoteIssue.description;
            Environment = remoteIssue.environment;
            Reporter = remoteIssue.reporter;
            Summary = remoteIssue.summary;
            Votes = remoteIssue.votes;

            // named entities
            Status = String.IsNullOrEmpty(remoteIssue.status) ? null : new IssueStatus(_jira, remoteIssue.status);
            Priority = String.IsNullOrEmpty(remoteIssue.priority) ? null : new IssuePriority(_jira, remoteIssue.priority);
            Resolution = String.IsNullOrEmpty(remoteIssue.resolution) ? null : new IssueResolution(_jira, remoteIssue.resolution);
            Type = String.IsNullOrEmpty(remoteIssue.type)? null: new IssueType(_jira, remoteIssue.type);

            // collections
            _affectsVersions = _originalIssue.affectsVersions == null ? new ProjectVersionCollection("versions", _jira, Project)
                : new ProjectVersionCollection("versions", _jira, Project, _originalIssue.affectsVersions.Select(v => new ProjectVersion(v)).ToList());

            _fixVersions = _originalIssue.fixVersions == null ? new ProjectVersionCollection("fixVersions", _jira, Project)
                : new ProjectVersionCollection("fixVersions", _jira, Project, _originalIssue.fixVersions.Select(v => new ProjectVersion(v)).ToList());

            _components = _originalIssue.components == null ? new ProjectComponentCollection("components", _jira, Project)
                : new ProjectComponentCollection("components", _jira, Project, _originalIssue.components.Select(c => new ProjectComponent(c)).ToList());

            _customFields = _originalIssue.customFieldValues == null ? new CustomFieldCollection(_jira, Project)
                : new CustomFieldCollection(_jira, Project, _originalIssue.customFieldValues.Select(f => new CustomField(f.customfieldId, Project, _jira) { Values = f.values }).ToList());
  
        }

        /// <summary>
        /// The JIRA server that created this issue
        /// </summary>
        public Jira Jira
        {
            get
            {
                return _jira;
            }
        }
       
        /// <summary>
        /// Brief one-line summary of the issue
        /// </summary>
        [JqlContainsEquality]
        public string Summary { get; set; }

        /// <summary>
        /// Detailed description of the issue
        /// </summary>
        [JqlContainsEquality]
        public string Description { get; set; }

        /// <summary>
        /// Hardware or software environment to which the issue relates
        /// </summary>
        [JqlContainsEquality]
        public string Environment { get; set; }

        /// <summary>
        /// Person to whom the issue is currently assigned
        /// </summary>
        public string Assignee { get; set; }

        /// <summary>
        /// Unique identifier for this issue
        /// </summary>
        public ComparableString Key 
        {
            get
            {
                return _key;
            }
        }

        /// <summary>
        /// Importance of the issue in relation to other issues
        /// </summary>
        public IssuePriority Priority { get; set; }

        /// <summary>
        /// Parent project to which the issue belongs
        /// </summary>
        public string Project 
        {
            get
            {
                return _project;
            }
        }

        /// <summary>
        /// Person who entered the issue into the system
        /// </summary>
        public string Reporter { get; set; }
        
        /// <summary>
        /// Record of the issue's resolution, if the issue has been resolved or closed
        /// </summary>
        public IssueResolution Resolution { get; set; }

        /// <summary>
        /// The stage the issue is currently at in its lifecycle.
        /// </summary>
        public IssueStatus Status { get; set; }

        /// <summary>
        /// The type of the issue
        /// </summary>
        [RemoteFieldName("issuetype")]
        public IssueType Type { get; set; }
        
        /// <summary>
        /// Number of votes the issue has
        /// </summary>
        public long? Votes { get; set; }

        /// <summary>
        /// Time and date on which this issue was entered into JIRA
        /// </summary>
        public DateTime? Created 
        {
            get
            {
                return _createDate;
            }
        }

        /// <summary>
        /// Date by which this issue is scheduled to be completed
        /// </summary>
        public DateTime? DueDate 
        {
            get
            {
                return _dueDate;
            }
            set
            {
                _dueDate = value;
            }
        }

        /// <summary>
        /// Time and date on which this issue was last edited
        /// </summary>
        public DateTime? Updated 
        {
            get
            {
                return _updateDate;
            }
        }

        /// <summary>
        /// The components associated with this issue
        /// </summary>
        [JqlFieldName("component")]
        public ProjectComponentCollection Components
        {
            get
            {
                return _components;
            }
        }

        /// <summary>
        /// The versions that are affected by this issue
        /// </summary>
        [JqlFieldName("AffectedVersion")]
        public ProjectVersionCollection AffectsVersions
        {
            get
            {
                return _affectsVersions;
            }
        }

        /// <summary>
        /// The versions in which this issue is fixed
        /// </summary>
        [JqlFieldName("FixVersion")]
        public ProjectVersionCollection FixVersions
        {
            get
            {
                return _fixVersions;
            }
        }

        /// <summary>
        /// The custom fields associated with this issue
        /// </summary>
        public CustomFieldCollection CustomFields
        {
            get
            {
                return _customFields;
            }
        }

        /// <summary>
        /// Gets or sets the value of a custom field
        /// </summary>
        /// <param name="customFieldName">Custom field name</param>
        /// <returns>Value of the custom field</returns>
        public ComparableString this[string customFieldName]
        {
            get
            {
                var customField = _customFields[customFieldName];

                if(customField != null && customField.Values != null && customField.Values.Count() > 0)
                {
                    return customField.Values[0];
                }
                return null;
            }
            set
            {
                var customField = _customFields[customFieldName];

                if (customField != null)
                {
                    customField.Values = new string[] { value.Value };
                }
                else
                {
                    _customFields.Add(customFieldName, new string[] { value.Value });
                }
            }
        }

        /// <summary>
        /// Saves field changes to server
        /// </summary>
        public void SaveChanges()
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {   
                var remoteIssue = this.ToRemote();

                _jira.WithToken(token =>
                {
                    if (String.IsNullOrEmpty(_parentIssueKey))
                    {
                        remoteIssue = _jira.RemoteService.CreateIssue(token, remoteIssue);
                    }
                    else
                    {
                        remoteIssue = _jira.RemoteService.CreateIssueWithParent(token, remoteIssue, _parentIssueKey);
                    }
                });

                Initialize(remoteIssue);
            }
            else
            {
                UpdateRemoteFields(((IRemoteIssueFieldProvider)this).GetRemoteFields());
            }
        }

        /// <summary>
        /// Transition an issue through a workflow
        /// </summary>
        /// <param name="actionName">The workflow action to transition to</param>
        public void WorkflowTransition(string actionName)
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to execute workflow transition, issue has not been created.");
            }

            var action = this.GetAvailableActions().FirstOrDefault(a => a.Name.Equals(actionName, StringComparison.OrdinalIgnoreCase));
            if (action == null)
            {
                throw new InvalidOperationException(String.Format("Worflow action with name '{0}' not found.", actionName));
            }
            
            _jira.WithToken(token =>
            {
                var remoteIssue = _jira.RemoteService.ProgressWorkflowAction(
                                                                token,
                                                                _originalIssue.key,
                                                                action.Id,
                                                                ((IRemoteIssueFieldProvider)this).GetRemoteFields());
                Initialize(remoteIssue);
            });
        }

        private void UpdateRemoteFields(RemoteFieldValue[] remoteFields)
        {
            var remoteIssue = _jira.WithToken(token =>
            {
                return _jira.RemoteService.UpdateIssue(token, this.Key.Value, remoteFields);
            });
            Initialize(remoteIssue);
        }

        /// <summary>
        /// Retrieve attachment metadata from server for this issue
        /// </summary>
        public ReadOnlyCollection<Attachment> GetAttachments()
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to retrieve attachments from server, issue has not been created.");
            }

            return _jira.WithToken(token =>
            {
                return _jira.RemoteService.GetAttachmentsFromIssue(token, _originalIssue.key)
                    .Select(a => new Attachment(_jira, new WebClientWrapper(), a)).ToList().AsReadOnly();
            });
        }

        /// <summary>
        /// Add one or more attachments to this issue
        /// </summary>
        /// <param name="filePaths">Full paths of files to upload</param>
        public void AddAttachment(params string[] filePaths)
        {
            var attachments = filePaths.Select(f => new UploadAttachmentInfo(Path.GetFileName(f), _jira.FileSystem.FileReadAllBytes(f))).ToArray();

            AddAttachment(attachments);
        }

        /// <summary>
        /// Add an attachment to this issue
        /// </summary>
        /// <param name="name">Attachment name with extension</param>
        /// <param name="data">Attachment data</param>
        public void AddAttachment(string name, byte[] data)
        {
            AddAttachment(new UploadAttachmentInfo(name, data));
        }

        /// <summary>
        /// Add one or more attachments to this issue
        /// </summary>
        public void AddAttachment(params UploadAttachmentInfo[] attachments)
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to upload attachments to server, issue has not been created.");
            }

            var content = new List<string>();
            var names = new List<string>();
            
            foreach (var a in attachments)
            {
                names.Add(a.Name);
                content.Add(Convert.ToBase64String(a.Data));
            }

            _jira.WithToken(token =>
            {
                _jira.RemoteService.AddBase64EncodedAttachmentsToIssue(
                    token, 
                    _originalIssue.key, 
                    names.ToArray(), 
                    content.ToArray());
            });
        }

        /// <summary>
        /// Retrieve comments from server for this issue
        /// </summary>
        public ReadOnlyCollection<Comment> GetComments()
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to retrieve comments from server, issue has not been created.");
            }

            return _jira.WithToken(token =>
            {
                return _jira.RemoteService.GetCommentsFromIssue(token, _originalIssue.key).Select(c => new Comment(c)).ToList().AsReadOnly();   
            });
        }

        /// <summary>
        /// Add a comment to this issue
        /// </summary>
        /// <param name="comment">Comment text to add</param>
        public void AddComment(string comment)
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to add comment to issue, issue has not been created.");
            }

            var newComment = new Comment() { Author = _jira.UserName, Body = comment };

            _jira.WithToken(token =>
            {
                _jira.RemoteService.AddComment(token, _originalIssue.key, newComment.toRemote());
            });
        }

        /// <summary>
        /// Add labels to this issue
        /// </summary>
        /// <param name="labels">Label(s) to add</param>
        public void AddLabels(params string[] labels)
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to add label to issue, issue has not been created.");
            }

            var fields = new RemoteFieldValue[] { 
                            new RemoteFieldValue() { 
                                id="labels",
                                values = labels
                            }
                        };

            UpdateRemoteFields(fields);
        }
       
        /// <summary>
        ///  Adds a worklog to this issue.
        /// </summary>
        /// <param name="timespent">Specifies a time duration in JIRA duration format, representing the time spent working on the worklog</param>
        /// <param name="worklogStrategy">How to handle the remaining estimate, defaults to AutoAdjustRemainingEstimate</param>
        /// <param name="newEstimate">New estimate (only used if worklogStrategy set to NewRemainingEstimate)</param>
        /// <returns>Worklog as constructed by server</returns>
        public Worklog AddWorklog(string timespent, 
                                  WorklogStrategy worklogStrategy = WorklogStrategy.AutoAdjustRemainingEstimate,
                                  string newEstimate = null)
        {
            return AddWorklog(new Worklog(timespent, DateTime.Now), worklogStrategy, newEstimate);
        }

        /// <summary>
        ///  Adds a worklog to this issue.
        /// </summary>
        /// <param name="worklog">The worklog instance to add</param>
        /// <param name="worklogStrategy">How to handle the remaining estimate, defaults to AutoAdjustRemainingEstimate</param>
        /// <param name="newEstimate">New estimate (only used if worklogStrategy set to NewRemainingEstimate)</param>
        /// <returns>Worklog as constructed by server</returns>
        public Worklog AddWorklog(Worklog worklog,
                                  WorklogStrategy worklogStrategy = WorklogStrategy.AutoAdjustRemainingEstimate,
                                  string newEstimate = null)
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to add worklog to issue, issue has not been saved to server.");
            }

            RemoteWorklog remoteWorklog = worklog.ToRemote();
            _jira.WithToken(token =>
            {
                switch (worklogStrategy)
                {
                    case WorklogStrategy.RetainRemainingEstimate:
                        remoteWorklog = _jira.RemoteService.AddWorklogAndRetainRemainingEstimate(token, _originalIssue.key, remoteWorklog);
                        break;
                    case WorklogStrategy.NewRemainingEstimate:
                        remoteWorklog = _jira.RemoteService.AddWorklogWithNewRemainingEstimate(token, _originalIssue.key, remoteWorklog, newEstimate);
                        break;
                    default:
                        remoteWorklog = _jira.RemoteService.AddWorklogAndAutoAdjustRemainingEstimate(token, _originalIssue.key, remoteWorklog);
                        break;
                }
            });

            return new Worklog(remoteWorklog);
        }

        /// <summary>
        /// Deletes the worklog with the given id and updates the remaining estimate field on the isssue
        /// </summary>
        public void DeleteWorklog(Worklog worklog, WorklogStrategy worklogStrategy = WorklogStrategy.AutoAdjustRemainingEstimate, string newEstimate = null)
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to delete worklog from issue, issue has not been saved to server.");
            }

            Jira.WithToken((token, client) =>
            {
                switch (worklogStrategy)
                {
                    case WorklogStrategy.AutoAdjustRemainingEstimate:
                        client.DeleteWorklogAndAutoAdjustRemainingEstimate(token, worklog.Id);
                        break;
                    case WorklogStrategy.RetainRemainingEstimate:
                        client.DeleteWorklogAndRetainRemainingEstimate(token, worklog.Id);
                        break;
                    case WorklogStrategy.NewRemainingEstimate:
                        client.DeleteWorklogWithNewRemainingEstimate(token, worklog.Id, newEstimate);
                        break;
                }
            });
        }

        /// <summary>
        /// Retrieve worklogs for current issue
        /// </summary>
        public ReadOnlyCollection<Worklog> GetWorklogs()
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to retrieve worklog, issue has not been saved to server.");
            }

            return _jira.WithToken(token =>
            {
                return _jira.RemoteService.GetWorkLogs(token, _originalIssue.key).Select(w => new Worklog(w)).ToList().AsReadOnly();
            });
        }

        /// <summary>
        /// Updates all fields from server
        /// </summary>
        public void Refresh()
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to refresh, issue has not been saved to server.");
            }

            var remoteIssue = _jira.WithToken(token =>
            {
                return _jira.RemoteService.GetIssuesFromJqlSearch(token, "key = " + _originalIssue.key, 1).First();
            });
            Initialize(remoteIssue);
        }

        internal RemoteIssue ToRemote()
        {
            var remote = new RemoteIssue()
            {
                assignee = this.Assignee,
                description = this.Description,
                environment = this.Environment,
                project = this.Project,
                reporter = this.Reporter,
                summary = this.Summary,
                votes = this.Votes,
                duedate = this.DueDate
            };

            remote.key = this.Key != null ? this.Key.Value : null;

            if (Status != null)
            {
                remote.status = Status.Id ?? Status.Load(_jira, Project).Id;
            }

            if (Resolution != null)
            {
                remote.resolution = Resolution.Id ?? Resolution.Load(_jira, Project).Id;
            }

            if (Priority != null)
            {
                remote.priority = Priority.Id ?? Priority.Load(_jira, Project).Id;
            }

            if (Type != null)
            {
                remote.type = Type.Id ?? Type.Load(_jira, Project).Id;
            }

            if (this.AffectsVersions.Count > 0)
            {
                remote.affectsVersions = this.AffectsVersions.Select(v => v.RemoteVersion).ToArray();
            }

            if(this.FixVersions.Count > 0)
            {
                remote.fixVersions = this.FixVersions.Select(v => v.RemoteVersion).ToArray();
            }

            if (this.Components.Count > 0)
            {
                remote.components = this.Components.Select(c => c.RemoteComponent).ToArray();
            }

            if (this.CustomFields.Count > 0)
            {
                remote.customFieldValues = this.CustomFields.Select(f => new RemoteCustomFieldValue()
                {
                    customfieldId = f.Id,
                    values = f.Values
                }).ToArray();
            }

            return remote;
        }

        /// <summary>
        /// Gets the workflow actions that the issue can be transitioned to
        /// </summary>
        /// <returns></returns>
        public IEnumerable<JiraNamedEntity> GetAvailableActions()
        {
            if (String.IsNullOrEmpty(_originalIssue.key))
            {
                throw new InvalidOperationException("Unable to retrieve actions, issue has not been saved to server.");
            }

            return _jira.WithToken(token =>
            {
                return _jira.RemoteService.GetAvailableActions(token, _originalIssue.key).Select(a => new JiraNamedEntity(a));
            });
        }

        /// <summary>
        /// Gets the RemoteFields representing the fields that were updated
        /// </summary>
        RemoteFieldValue[] IRemoteIssueFieldProvider.GetRemoteFields()
        {
            var fields = new List<RemoteFieldValue>();

            var remoteFields = typeof(RemoteIssue).GetProperties();
            foreach (var localProperty in typeof(Issue).GetProperties())
            {
                if (typeof(IRemoteIssueFieldProvider).IsAssignableFrom(localProperty.PropertyType))
                {
                    var fieldsProvider = localProperty.GetValue(this, null) as IRemoteIssueFieldProvider;

                    if (fieldsProvider != null)
                    {
                        fields.AddRange(fieldsProvider.GetRemoteFields());
                    }
                }
                else
                {
                    var remoteProperty = remoteFields.FirstOrDefault(i => i.Name.Equals(localProperty.Name, StringComparison.OrdinalIgnoreCase));
                    if (remoteProperty == null)
                    {
                        continue;
                    }

                    var localStringValue = GetStringValueForProperty(this, localProperty);
                    var remoteStringValue = GetStringValueForProperty(_originalIssue, remoteProperty);

                    if (remoteStringValue != localStringValue)
                    {
                        var remoteFieldName = remoteProperty.Name;

                        var remoteFieldNameAttr = localProperty.GetCustomAttributes(typeof(RemoteFieldNameAttribute), true).OfType<RemoteFieldNameAttribute>().FirstOrDefault();
                        if (remoteFieldNameAttr != null)
                        {
                            remoteFieldName = remoteFieldNameAttr.Name;
                        }

                        fields.Add(new RemoteFieldValue()
                        {
                            id = remoteFieldName,
                            values = new string[1] { localStringValue }
                        });
                    }
                }
            }

            return fields.ToArray();
        }

        private string GetStringValueForProperty(object container, PropertyInfo property)
        {
            var value = property.GetValue(container, null);

            if (property.PropertyType == typeof(DateTime?))
            {
                var dateValue = (DateTime?)value;
                return dateValue.HasValue ? dateValue.Value.ToString("d/MMM/yy") : null;
            }
            else if (typeof(JiraNamedEntity).IsAssignableFrom(property.PropertyType))
            {
                var jiraNamedEntity = property.GetValue(container, null) as JiraNamedEntity;
                if (jiraNamedEntity != null)
                {
                    return jiraNamedEntity.Id ?? jiraNamedEntity.Load(_jira, this.Project).Id;
                }
                return null;
            }
            else
            {
                return value != null ? value.ToString() : null;
            }
        }
    }
}
Back to Top