public String CreateChangeRequest(ChangeRequest changeRequest)
        {
            db.ChangeRequests.Add(changeRequest);
            db.SaveChanges();

            return "Success";
        }
        public String EditChangeRequest(ChangeRequest changeRequest)
        {
            db.Entry(changeRequest).State = EntityState.Modified;
            db.SaveChanges();

            return "Success";
        }
        public String DeleteChangeRequest(ChangeRequest changeRequest)
        {
            db.ChangeRequests.Remove(changeRequest);
            db.SaveChanges();

            return "Success";
        }
Пример #4
0
	IEnumerator AddMoney(Player player)
	{
		if (m_applying)
		{
			yield break;
		}

		m_applying = true;
		var task = new MetagameTask<InstanceResponse<User>>();
		var changeRequest = new ChangeRequest("grantCurrencyInsecure", new { currency = Value });
		yield return StartCoroutine(Collection.Users.ApplyChange(task, player.User.ID, changeRequest));
		m_applying = false;

		if (task.Error == null)
		{
			player.LoadProfile(task.Data.Instance);
			gameObject.SetActive(false);
		}
	}
Пример #5
0
        protected void lbSimpleSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            var         person                = GetPerson();
            var         personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));
            var         changeRequest         = new ChangeRequest
            {
                EntityTypeId     = personAliasEntityType.Id,
                EntityId         = person.PrimaryAliasId ?? 0,
                RequestorAliasId = CurrentPersonAliasId ?? 0,
                RequestorComment = tbSimpleRequest.Text
            };

            ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);

            changeRequestService.Add(changeRequest);
            rockContext.SaveChanges();

            pnlSimple.Visible = false;
            pnlDone.Visible   = true;
            btnDone.Visible   = false;
        }
        public void CalculateChange_WithValidValue()
        {
            ChangeManager changeManager = new ChangeManager();

            ChangeRequest changeRequest = new ChangeRequest();

            changeRequest.PaidAmount    = 73891;
            changeRequest.ProductAmount = 100;
            ChangeResponse changeResponse = changeManager.CalculateChange(changeRequest);

            Assert.IsNotNull(changeResponse);
            Assert.IsNotNull(changeResponse.ChangeDataCollection);
            Assert.AreEqual(7, changeResponse.ChangeDataCollection.SingleOrDefault(o => o.AmountInCents == 10000).Quantity);
            Assert.AreEqual(1, changeResponse.ChangeDataCollection.SingleOrDefault(o => o.AmountInCents == 2000).Quantity);
            Assert.AreEqual(1, changeResponse.ChangeDataCollection.SingleOrDefault(o => o.AmountInCents == 1000).Quantity);
            Assert.AreEqual(1, changeResponse.ChangeDataCollection.SingleOrDefault(o => o.AmountInCents == 500).Quantity);
            Assert.AreEqual(1, changeResponse.ChangeDataCollection.SingleOrDefault(o => o.AmountInCents == 200).Quantity);

            Assert.AreEqual(1, changeResponse.ChangeDataCollection.SingleOrDefault(o => o.AmountInCents == 90).Quantity);

            Assert.AreEqual(1, changeResponse.ChangeDataCollection.SingleOrDefault(o => o.AmountInCents == 1).Quantity);
        }
Пример #7
0
        public ChangeResponse CoinReturn(ChangeRequest transaction)
        {
            var coinCount = new Change();

            coinCount.SilverDollars = transaction.ChangeOwed / 100;
            coinCount.Quarters      = (transaction.ChangeOwed - coinCount.SilverDollars * 100) / 25;
            coinCount.Dimes         = (transaction.ChangeOwed - (coinCount.SilverDollars * 100 + coinCount.Quarters * 25)) / 10;
            coinCount.Nickels       = (transaction.ChangeOwed - (coinCount.SilverDollars * 100 + coinCount.Quarters * 25 + coinCount.Dimes * 10)) / 5;
            coinCount.Pennies       = (transaction.ChangeOwed -
                                       (coinCount.SilverDollars * 100 + coinCount.Quarters * 25 + coinCount.Dimes * 10 +
                                        coinCount.Nickels * 5));

            var changeResponse = new ChangeResponse();

            changeResponse.Coins = coinCount;
            //  changeResponse.Item = transaction.Item;
            changeResponse.ChangeOwed = (transaction.ChangeOwed);
            changeResponse.Payment    = (transaction.Payment);
            changeResponse.ChangeOwed = changeResponse.ChangeOwed / 100;
            changeResponse.Payment    = changeResponse.Payment / 100;
            return(changeResponse);
        }
Пример #8
0
        public void ParseTest()
        {
            byte[] bytes = new byte[]
            {
                0x00, 0x04, 0x00, 0x04,
                0x00, 0x00, 0x00, 0x00,
            };

            int           startIndex = 0;
            ChangeRequest target     = new ChangeRequest();

            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(8, startIndex);
            Assert.AreEqual(false, target.ChangeIp);
            Assert.AreEqual(false, target.ChangePort);

            startIndex = 0;
            bytes[7]   = 0x04;
            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(true, target.ChangeIp);
            Assert.AreEqual(false, target.ChangePort);

            startIndex = 0;
            bytes[7]   = 0x02;
            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(false, target.ChangeIp);
            Assert.AreEqual(true, target.ChangePort);

            startIndex = 0;
            bytes[7]   = 0x06;
            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(true, target.ChangeIp);
            Assert.AreEqual(true, target.ChangePort);
        }
        public JsonResult Delete(int id)
        {
            var result = new jsonMessage();

            try
            {
                var change = new ChangeRequest()
                {
                    ChangeRequestId = id
                };
                db.Entry(change).State = EntityState.Deleted;
                db.SaveChanges();

                result.Message = "Hapus Berhasil";
                result.Status  = true;
            }
            catch (Exception)
            {
                result.Message = "We are unable to process your request at this time. Please try again later.";
                result.Status  = false;
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Пример #10
0
        public static ChangeRecord DeleteEntity(this ChangeRequest changeRequest, IEntity entity, bool isRelated = false, string comment = "")
        {
            var serializedEntity = entity.ToJson();
            var changeRecord     = new ChangeRecord()
            {
                OldValue   = serializedEntity,
                NewValue   = "",
                Action     = ChangeRecordAction.Delete,
                IsRejected = false,
                WasApplied = false,
                Property   = "",
                Comment    = comment
            };

            if (isRelated)
            {
                changeRecord.RelatedEntityId     = entity.Id;
                changeRecord.RelatedEntityTypeId = EntityTypeCache.Get(entity.GetType()).Id;
            }

            changeRequest.ChangeRecords.Add(changeRecord);
            return(changeRecord);
        }
Пример #11
0
        public override bool CanHandleChangeRequest(ChangeRequest changeRequest, out ChangeItemRequest changeItemRequest)
        {
            changeItemRequest = null;
            if (CanHandleChangeRequest(changeRequest, OpenShiftRequestUriTemplate, out ChangeItemRequest itemRequest))
            {
                if (itemRequest.Method.Equals("delete", StringComparison.OrdinalIgnoreCase))
                {
                    changeItemRequest = itemRequest;
                }
                else if (itemRequest.Body != null)
                {
                    var openShiftRequest = itemRequest.Body.ToObject <OpenShiftsChangeRequest>();

                    if (openShiftRequest.AssignedTo.Equals(ChangeRequestAssignedTo.System, StringComparison.OrdinalIgnoreCase) &&
                        openShiftRequest.State.Equals(ChangeRequestPhase.Declined, StringComparison.OrdinalIgnoreCase))
                    {
                        changeItemRequest = itemRequest;
                    }
                }
            }

            return(changeItemRequest != null);
        }
Пример #12
0
        static void Main(string[] args)
        {
            //<SnippetUseClasses>
            // Create an instance of WorkItem by using the constructor in the
            // base class that takes three arguments.
            WorkItem item = new WorkItem("Fix Bugs",
                                         "Fix all bugs in my code branch",
                                         new TimeSpan(3, 4, 0, 0));

            // Create an instance of ChangeRequest by using the constructor in
            // the derived class that takes four arguments.
            ChangeRequest change = new ChangeRequest("Change Base Class Design",
                                                     "Add members to the class",
                                                     new TimeSpan(4, 0, 0),
                                                     1);

            // Use the ToString method defined in WorkItem.
            Console.WriteLine(item.ToString());

            // Use the inherited Update method to change the title of the
            // ChangeRequest object.
            change.Update("Change the Design of the Base Class",
                          new TimeSpan(4, 0, 0));

            // ChangeRequest inherits WorkItem's override of ToString.
            Console.WriteLine(change.ToString());

            /* Output:
             *  1 - Fix Bugs
             *  2 - Change the Design of the Base Class
             */
            //</SnippetUseClasses>

            Polymorphism.Example();
            Polymorphism.VirtualExamples();
            NewMethodHierarchy.NewMethods.Example();
        }
        public JsonResult CreateAndUpdate(int ChangeRequestId, int RequirementId, string ChangeRequestNumber, string Description, decimal MandaysEstimation)
        {
            var result = new jsonMessage();

            try
            {
                ChangeRequest changeRe = new ChangeRequest();

                changeRe.ChangeRequestId     = ChangeRequestId;
                changeRe.RequimentId         = RequirementId;
                changeRe.ChangeRequestNumber = ChangeRequestNumber;
                changeRe.Description         = Description;
                changeRe.MandaysEstimation   = MandaysEstimation;

                if (ChangeRequestId == 0)
                {
                    db.ChangeRequests.Add(changeRe);
                    result.Message = "Tambah Berhasil";
                    result.Status  = true;
                }
                else
                {
                    db.Entry(changeRe).State = EntityState.Modified;
                    result.Message           = "Update Berhasil";
                    result.Status            = true;
                }


                db.SaveChanges();
            }
            catch (Exception)
            {
                result.Message = "We are unable to process your request at this time. Please try again later.";
                result.Status  = false;
            }
            return(Json(result, JsonRequestBehavior.AllowGet));
        }
Пример #14
0
        private static Boolean HandleWorkLog(CrudOperationData entity, ChangeRequest maximoTicket)
        {
            var maximoWorklogs = entity.GetRelationship("worklog_");
            var worklogList    = new List <ChangeLog>();
            var user           = SecurityFacade.CurrentUser();

            foreach (var jsonWorklog in (IEnumerable <CrudOperationData>)maximoWorklogs)
            {
                var worklogid = jsonWorklog.GetAttribute("worklogid");
                if (worklogid == null)
                {
                    var changeLog = new ChangeLog {
                        Log                  = (string)jsonWorklog.GetAttribute("description"),
                        ActionID             = "CLIENTNOTE",
                        UserID               = ISMConstants.AddEmailIfNeeded(user.MaximoPersonId),
                        LogDateTimeSpecified = true,
                        LogDateTime          = DateTime.Now
                    };
                    var longDesc = "";
                    var ld       = (CrudOperationData)jsonWorklog.GetRelationship("longdescription");
                    if (ld != null)
                    {
                        longDesc = (string)ld.GetAttribute("ldtext");
                    }
                    changeLog.FlexFields = new[] {
                        new FlexFieldsFlexField {
                            mappedTo = "WLLongDesc", id = "0", Value = longDesc
                        }
                    };

                    worklogList.Add(changeLog);
                }
            }

            maximoTicket.ChangeLog = ArrayUtil.PushRange(maximoTicket.ChangeLog, worklogList);
            return(worklogList.Any());
        }
Пример #15
0
        public void ParseTest()
        {
            byte[] bytes = new byte[]
            {
                0x00, 0x04, 0x00, 0x04,
                0x00, 0x00, 0x00, 0x00,
            };

            int startIndex = 0;
            ChangeRequest target = new ChangeRequest();
            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(8, startIndex);
            Assert.AreEqual(false, target.ChangeIp);
            Assert.AreEqual(false, target.ChangePort);

            startIndex = 0;
            bytes[7] = 0x04;
            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(true, target.ChangeIp);
            Assert.AreEqual(false, target.ChangePort);

            startIndex = 0;
            bytes[7] = 0x02;
            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(false, target.ChangeIp);
            Assert.AreEqual(true, target.ChangePort);

            startIndex = 0;
            bytes[7] = 0x06;
            target.Parse(bytes, ref startIndex);

            Assert.AreEqual(true, target.ChangeIp);
            Assert.AreEqual(true, target.ChangePort);
        }
Пример #16
0
        public ActionResult VendingMachine(VendingTool model)
        {
            if (ModelState.IsValid)
            {//need to add validation for insufficient funds
                var request = new ChangeRequest();
                request.Payment    = (int)(model.Payment.Value * 100);
                request.Price      = (int)(model.Item.Price * 100);
                request.ChangeOwed = request.Payment - request.Price;
                var cm       = new ChangeMaker();
                var response = cm.MakeChange(request);
                return(View("VendingResult", response));
            }

            var itemList = new List <VendingItem> //Hard coded until I can figure out how to get filereader to find my txt file.
            {
                new VendingItem()
                {
                    Name = "Starburst - $1.25", Price = 1.25M
                },
                new VendingItem()
                {
                    Name = "French Fries - $2.05", Price = 2.05M
                },
                new VendingItem()
                {
                    Name = "Butterfingers - $1.25", Price = 1.35M
                },
                new VendingItem()
                {
                    Name = "Puppy - $0.89", Price = .89M
                }
            };

            model.Items = itemList;

            return(View("VendingMachine", model));
        }
Пример #17
0
        public void SendApproveCrEmailTest()
        {
            ChangeRequestInterface api = new CRSubSystemAPI();

            ChangeRequest changeRequest = new ChangeRequest();

            changeRequest.ApprovalStatus          = "PENDING";
            changeRequest.ApprovalReason          = "";
            changeRequest.ChangeCategoryId        = "EMERGENCY_CHANGE";
            changeRequest.ChangeRequestId         = DateTime.Now.Ticks.ToString();
            changeRequest.ChangeEndDateTime       = DateTime.Now;
            changeRequest.ChangeStartDateTime     = DateTime.Now;
            changeRequest.ImpactOfNotImplementing = "Bad Stuff";
            changeRequest.ImplementerCompany      = "Pegasus";
            changeRequest.ImplementerEmail        = "*****@*****.**";
            changeRequest.ImplementerName         = "kasozi";
            changeRequest.ImplementerPhone        = "0785975800";
            changeRequest.Justification           = "We need to do this";
            changeRequest.RequesterCompany        = "Stanbic";
            changeRequest.RequesterEmail          = "*****@*****.**";
            changeRequest.RequesterName           = "Damalie";
            changeRequest.RequesterPhone          = "0785975800";
            changeRequest.Title    = "Changing Transaction Status";
            changeRequest.Problem  = "Pegasus server 192.168.55.3 wishes to access UTL airtime listening on URL http://172.25.100.6/atpurchase.php  in order to be able to send Airtime Top Up requests for UTL phone numbers";
            changeRequest.Solution = "Creation of UTL VPN";
            changeRequest.Save();

            ApproverForChangeRequest systemAffected = new ApproverForChangeRequest();

            systemAffected.ChangeRequestId = changeRequest.ChangeRequestId;
            systemAffected.ApproverId      = "nsubugak";
            string    ApproveURL = "";
            ApiResult result     = api.SendApproveCrEmail(systemAffected);

            Assert.AreEqual(Globals.SUCCESS_STATUS_TEXT, result.StatusDesc);
        }
Пример #18
0
        private async void createChangeRequestAsync(object sender, RoutedEventArgs e)
        {
            try
            {
                // Prevents creation of CR duplicates; Could make sense if a ChangeRequest has been rejected before to revisit it
                if (this.changeRequests.ContainsKey(createGitHash.Text))
                {
                    MessageBox.Show($"ChangeRequest already exists:  { createGitHash.Text }");
                    return;
                }
                string privateKey = createKey.Password;

                ChangeRequest changeRequest = new ChangeRequest(this.contractAddress);
                await changeRequest.createChangeRequestAsync(privateKey, createGitHash.Text, createAdditionalInformation.Text, UInt32.Parse(createEstimation.Text), UInt32.Parse(createCosts.Text));

                this.changeRequests.Add(createGitHash.Text, changeRequest);

                MessageBox.Show($"Created ChangeRequest:  { createGitHash.Text }");
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
            }
        }
Пример #19
0
        // Let the responsible parties vote on the ChangeRequest
        private async void responsibleVote(object sender, RoutedEventArgs e)
        {
            try
            {
                string privateKey = responsibleKey.Password;

                ChangeRequest changeRequest = (ChangeRequest)changeRequestsTable.SelectedItem;

                if (responsibleAccept.IsChecked == true)
                {
                    await changeRequest.responsibleVoteAsync(privateKey, true, responsibleInfo.Text);
                }
                else if (responsibleReject.IsChecked == true)
                {
                    await changeRequest.responsibleVoteAsync(privateKey, false, responsibleInfo.Text);
                }

                MessageBox.Show($"Voted on ChangeRequest:  { changeRequest.gitHash }");
            }
            catch (Exception ex)
            {
                Debug.Write(ex);
            }
        }
        public override bool CanHandleChangeRequest(ChangeRequest changeRequest, out ChangeItemRequest changeItemRequest)
        {
            // we cannot use the base class method here as we need to handle the invalid url's that
            // Teams is sending with this request
            changeItemRequest = null;
            if (changeRequest.Requests.Length == 1)
            {
                // the url as supplied by Teams looks something like the following:
                //"/shifts/SHFT_bff7961c-1bff-4c39-b2b1-7808eca233de/requestableShifts?requestType=SwapRequest&startTime=5/31/2020 11:00:00 PM +00:00&endTime=6/30/2020 10:59:59 PM +00:00"
                // because the datetime values are not valid in a url we are having to strip them so that the url parser
                // does not fail in the TryMatch method
                var request = changeRequest.Requests[0];
                var url     = request.Url.Substring(0, request.Url.IndexOf("&"));
                if (ShiftSwapFilterRequestUriTemplate.TryMatch(url, out var changeItemParams))
                {
                    if (changeItemParams.ContainsKey("requestType") && changeItemParams["requestType"].ToString().Equals("SwapRequest", StringComparison.OrdinalIgnoreCase))
                    {
                        changeItemRequest = request;
                    }
                }
            }

            return(changeItemRequest != null);
        }
Пример #21
0
 protected virtual void HandleDescription(CrudOperationData operationData, string description, ChangeRequest maximoTicket)
 {
     if (description != null && !description.StartsWith("@@"))
     {
         if (description.Length > 98)
         {
             //we need to make sure the size is never bigger than 100
             //https://controltechnologysolutions.atlassian.net/browse/HAP-642
             description = "@@" + description.Substring(0, 98);
         }
         else
         {
             description = "@@" + description;
         }
         maximoTicket.Change.Description = description;
     }
 }
 public static ChangeRequest CreateChangeRequest(int ID, string reference, string changeRequestTitle, string changeRequestDescription, int changeRequest_Employee, global::System.DateTime dateRaised, global::System.DateTime targetClosureDate, int changeRequestStatus_ChangeRequest, byte[] rowVersion)
 {
     ChangeRequest changeRequest = new ChangeRequest();
     changeRequest.Id = ID;
     changeRequest.Reference = reference;
     changeRequest.ChangeRequestTitle = changeRequestTitle;
     changeRequest.ChangeRequestDescription = changeRequestDescription;
     changeRequest.ChangeRequest_Employee = changeRequest_Employee;
     changeRequest.DateRaised = dateRaised;
     changeRequest.TargetClosureDate = targetClosureDate;
     changeRequest.ChangeRequestStatus_ChangeRequest = changeRequestStatus_ChangeRequest;
     changeRequest.RowVersion = rowVersion;
     return changeRequest;
 }
 public void AddToChangeRequests(ChangeRequest changeRequest)
 {
     base.AddObject("ChangeRequests", changeRequest);
 }
Пример #24
0
        public IActionResult Edit(ChangeRequest model)
        {
            try
            {
                _changeRequestRepository.UpdateChangeRequest(model, _userManager.GetUserName(this.User));
                return(RedirectToAction("Index", "Home"));
            }
            catch (DbUpdateConcurrencyException ex)
            {
                var exceptionEntry = ex.Entries.Single();
                if (exceptionEntry.Entity.GetType() == typeof(ChangeRequest))
                {
                    var clientValues = (ChangeRequest)exceptionEntry.Entity;
                    var dbEntry      = exceptionEntry.GetDatabaseValues();
                    if (dbEntry == null)
                    {
                        ModelState.AddModelError(string.Empty,
                                                 "Unable to save changes. Change Request was deleted by another user.");
                    }
                    else
                    {
                        var dbValues = (ChangeRequest)dbEntry.ToObject();
                        if (dbValues.Name != clientValues.Name)
                        {
                            ModelState.AddModelError("Name", $"Current Value: {dbValues.Name}");
                        }

                        if (dbValues.Summary != clientValues.Summary)
                        {
                            ModelState.AddModelError("Summary", $"Current Value: {dbValues.Summary}");
                        }

                        if (dbValues.Status != clientValues.Status)
                        {
                            ModelState.AddModelError("Status", $"Current Value: {dbValues.Status}");
                        }

                        if (dbValues.Priority != clientValues.Priority)
                        {
                            ModelState.AddModelError("Priority", $"Current Value: {dbValues.Priority}");
                        }

                        if (dbValues.Urgency != clientValues.Urgency)
                        {
                            ModelState.AddModelError("Urgency", $"Current Value: {dbValues.Urgency}");
                        }

                        if (dbValues.TargetDate != clientValues.TargetDate)
                        {
                            ModelState.AddModelError("TargetDate", $"Current Value: {dbValues.TargetDate}");
                        }

                        if (dbValues.ActualDate != clientValues.ActualDate)
                        {
                            ModelState.AddModelError("ActualDate", $"Current Value: {dbValues.ActualDate}");
                        }

                        if (dbValues.Owner != clientValues.Owner)
                        {
                            ModelState.AddModelError("Owner", $"Current Value: {dbValues.Owner}");
                        }

                        if (dbValues.Modified != clientValues.Modified)
                        {
                            ModelState.AddModelError("Modified", $"Current Value: {dbValues.Modified}");
                        }

                        if (dbValues.ModifiedBy != clientValues.ModifiedBy)
                        {
                            ModelState.AddModelError("ModifiedBy", $"Current Value: {dbValues.ModifiedBy}");
                        }

                        ModelState.AddModelError(string.Empty, "The record you attempted to edit "
                                                 + "was modified by another user after you got the original value. The "
                                                 + "edit operation was cancelled and the current values in the database "
                                                 + "have been displayed.");

                        model.RowVersion = (byte[])dbValues.RowVersion;
                        ModelState.Remove("RowVersion");
                    }
                }
            }
            catch (Exception ex)
            {
                ModelState.AddModelError(string.Empty, "An error occurred saving the record.");
            }

            return(View(model));
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            if (GetAttributeValue(AttributeKeys.DisplayTerms).AsBoolean() && !cbTOS.Checked)
            {
                nbTOS.Visible = true;
                return;
            }

            var rockContext   = new RockContext();
            var personService = new PersonService(rockContext);

            var person = GetPerson(personService);

            var personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));

            if (person.Id != 0)
            {
                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };


                if (person.PhotoId != imgPhoto.BinaryFileId)
                {
                    changeRequest.EvaluatePropertyChange(person, "PhotoId", imgPhoto.BinaryFileId);
                    if (person.Photo != null)
                    {
                        changeRequest.EvaluatePropertyChange(person.Photo, "IsTemporary", true, true);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
                changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
                changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
                changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
                changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

                var birthMonth = person.BirthMonth;
                var birthDay   = person.BirthDay;
                var birthYear  = person.BirthYear;

                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                    changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                    }
                    else
                    {
                        changeRequest.EvaluatePropertyChange(person, "BirthYear", ( int? )null);
                    }
                }

                if (ddlGradePicker.Visible)
                {
                    changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);
                }
                changeRequest.EvaluatePropertyChange(person, "Gender", rblGender.SelectedValue.ConvertToEnum <Gender>());

                var primaryFamilyMembers = person.GetFamilyMembers(true).Where(m => m.PersonId == person.Id).ToList();
                foreach (var member in primaryFamilyMembers)
                {
                    changeRequest.EvaluatePropertyChange(member, "GroupRoleId", rblRole.SelectedValue.AsInteger(), true);
                }

                var primaryFamily       = person.GetFamily(rockContext);
                var familyChangeRequest = new ChangeRequest
                {
                    EntityTypeId     = EntityTypeCache.Get(typeof(Group)).Id,
                    EntityId         = primaryFamily.Id,
                    RequestorAliasId = CurrentPersonAliasId ?? 0
                };

                // update campus
                bool showCampus = GetAttributeValue("ShowCampusSelector").AsBoolean();
                if (showCampus)
                {
                    // Only update campus for adults
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    var adultGuid = Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid();
                    var adultRole = groupTypeRoleService.Get(adultGuid);
                    if (rblRole.SelectedValue.AsInteger() == adultRole.Id)
                    {
                        familyChangeRequest.EvaluatePropertyChange(primaryFamily, "CampusId", cpCampus.SelectedCampusId);
                    }
                }

                //Evaluate PhoneNumbers
                bool showPhoneNumbers = GetAttributeValue("ShowPhoneNumbers").AsBoolean();
                if (showPhoneNumbers)
                {
                    var  phoneNumberTypeIds = new List <int>();
                    var  phoneNumbersScreen = new List <PhoneNumber>();
                    bool smsSelected        = false;
                    foreach (RepeaterItem item in rContactInfo.Items)
                    {
                        HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                        PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                        CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                        CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                        if (hfPhoneType != null &&
                            pnbPhone != null &&
                            cbSms != null &&
                            cbUnlisted != null)
                        {
                            int phoneNumberTypeId;
                            if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                            {
                                var    phoneNumberList = person.PhoneNumbers.Where(n => n.NumberTypeValueId == phoneNumberTypeId).ToList();
                                var    phoneNumber     = phoneNumberList.FirstOrDefault(pn => pn.Number == PhoneNumber.CleanNumber(pnbPhone.Number));
                                string oldPhoneNumber  = string.Empty;

                                if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                                {
                                    phoneNumber = new PhoneNumber
                                    {
                                        PersonId           = person.Id,
                                        NumberTypeValueId  = phoneNumberTypeId,
                                        CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                        IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                        Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                                    };
                                    var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                                    changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                                else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                                {
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                                    changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                                    phoneNumbersScreen.Add(phoneNumber);
                                }
                            }
                        }
                    }
                    //Remove old phone numbers or changed
                    var phoneNumbersToRemove = person.PhoneNumbers
                                               .Where(n => !phoneNumbersScreen.Any(n2 => n2.Number == n.Number && n2.NumberTypeValueId == n.NumberTypeValueId)).ToList();

                    foreach (var number in phoneNumbersToRemove)
                    {
                        var phoneComment = string.Format("{0}: {1}.", number.NumberTypeValue.Value, number.NumberFormatted);
                        changeRequest.DeleteEntity(number, true, phoneComment);
                    }
                }

                changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text.Trim());
                changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
                changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());

                // if they used the ImageEditor, and cropped it, the non-cropped file is still in BinaryFile. So clean it up
                if (imgPhoto.CropBinaryFileId.HasValue)
                {
                    if (imgPhoto.CropBinaryFileId != person.PhotoId)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(imgPhoto.CropBinaryFileId.Value);
                        if (binaryFile != null && binaryFile.IsTemporary)
                        {
                            string errorMessage;
                            if (binaryFileService.CanDelete(binaryFile, out errorMessage))
                            {
                                binaryFileService.Delete(binaryFile);
                                rockContext.SaveChanges();
                            }
                        }
                    }
                }


                // save family information
                if (pnlAddress.Visible)
                {
                    var      currentLocation = person.GetHomeLocation();
                    Location location        = new Location
                    {
                        Street1    = acAddress.Street1,
                        Street2    = acAddress.Street2,
                        City       = acAddress.City,
                        State      = acAddress.State,
                        PostalCode = acAddress.PostalCode,
                    };
                    var globalAttributesCache = GlobalAttributesCache.Get();
                    location.Country = globalAttributesCache.OrganizationCountry;
                    location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

                    if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                        (currentLocation != null && currentLocation.Street1 != location.Street1))
                    {
                        LocationService locationService = new LocationService(rockContext);
                        locationService.Add(location);
                        rockContext.SaveChanges();

                        var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                        var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                        GroupLocation groupLocation = new GroupLocation
                        {
                            CreatedByPersonAliasId  = CurrentPersonAliasId,
                            ModifiedByPersonAliasId = CurrentPersonAliasId,
                            GroupId    = primaryFamily.Id,
                            LocationId = location.Id,
                            GroupLocationTypeValueId = homeLocationType.Id,
                            IsMailingLocation        = true,
                            IsMappedLocation         = true
                        };

                        var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                        var homelocations = primaryFamily.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                        foreach (var homelocation in homelocations)
                        {
                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "GroupLocationTypeValue",
                                previousLocationType,
                                true,
                                homelocation.Location.ToString());

                            familyChangeRequest.EvaluatePropertyChange(
                                homelocation,
                                "IsMailingLocation",
                                false,
                                true,
                                homelocation.Location.ToString());
                        }
                    }
                }

                // Handle both Child and Adult attributes together here
                var attributeGuids = GetAttributeValue(AttributeKeys.PersonAttributesAdult).SplitDelimitedValues().AsGuidList();
                attributeGuids.AddRange(GetAttributeValue(AttributeKeys.PersonAttributesChild).SplitDelimitedValues().AsGuidList());
                if (attributeGuids.Count > 0)
                {
                    person.LoadAttributes();
                    Helper.GetEditValues(phAttributes, person);
                    changeRequest.EvaluateAttributes(person);
                }

                List <string> errors;

                if (changeRequest.ChangeRecords.Any() ||
                    (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
                {
                    changeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(changeRequest);
                    rockContext.SaveChanges();

                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                if (familyChangeRequest.ChangeRecords.Any())
                {
                    familyChangeRequest.RequestorComment = tbComments.Text;
                    ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                    changeRequestService.Add(familyChangeRequest);
                    rockContext.SaveChanges();
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
            }
            else
            {
                var primaryFamily = CurrentPerson.GetFamily(rockContext);

                person.PhotoId = imgPhoto.BinaryFileId;

                if (imgPhoto.BinaryFileId.HasValue)
                {
                    BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                    var binaryFile = binaryFileService.Get(imgPhoto.BinaryFileId.Value);
                    binaryFile.IsTemporary = false;
                }

                person.FirstName     = tbFirstName.Text;
                person.NickName      = tbNickName.Text;
                person.LastName      = tbLastName.Text;
                person.TitleValueId  = ddlTitle.SelectedValue.AsIntegerOrNull();
                person.SuffixValueId = ddlSuffix.SelectedValue.AsIntegerOrNull();
                var birthday = bpBirthDay.SelectedDate;
                if (birthday.HasValue)
                {
                    // If setting a future birth date, subtract a century until birth date is not greater than today.
                    var today = RockDateTime.Today;
                    while (birthday.Value.CompareTo(today) > 0)
                    {
                        birthday = birthday.Value.AddYears(-100);
                    }

                    person.BirthMonth = birthday.Value.Month;
                    person.BirthDay   = birthday.Value.Day;

                    if (birthday.Value.Year != DateTime.MinValue.Year)
                    {
                        person.BirthYear = birthday.Value.Year;
                    }
                    else
                    {
                        person.BirthYear = null;
                    }
                }

                person.Gender          = rblGender.SelectedValue.ConvertToEnum <Gender>();
                person.Email           = tbEmail.Text;
                person.EmailPreference = rblEmailPreference.SelectedValue.ConvertToEnum <EmailPreference>();

                if (ddlGradePicker.Visible)
                {
                    person.GraduationYear = ypGraduation.SelectedYear;
                }


                GroupMember groupMember = new GroupMember
                {
                    PersonId    = person.Id,
                    GroupId     = primaryFamily.Id,
                    GroupRoleId = rblRole.SelectedValue.AsInteger()
                };

                PersonService.AddPersonToFamily(person, true, primaryFamily.Id, rblRole.SelectedValue.AsInteger(), rockContext);

                PhoneNumberService phoneNumberService = new PhoneNumberService(rockContext);

                foreach (RepeaterItem item in rContactInfo.Items)
                {
                    HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                    PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                    CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                    CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                    if (hfPhoneType != null &&
                        pnbPhone != null &&
                        cbSms != null &&
                        cbUnlisted != null &&
                        pnbPhone.Number.IsNotNullOrWhiteSpace())
                    {
                        int phoneNumberTypeId;
                        if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                        {
                            var phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            phoneNumberService.Add(phoneNumber);
                        }
                    }
                }
                rockContext.SaveChanges();

                var changeRequest = new ChangeRequest
                {
                    EntityTypeId     = personAliasEntityType.Id,
                    EntityId         = person.PrimaryAliasId ?? 0,
                    RequestorAliasId = CurrentPersonAliasId ?? 0,
                    RequestorComment = "Added as new person from My Account."
                };

                if (tbComments.Text.IsNotNullOrWhiteSpace())
                {
                    changeRequest.RequestorComment += "<br><br>Comment: " + tbComments.Text;
                }

                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();

                List <string> errors;
                changeRequest.CompleteChanges(rockContext, out errors);
            }

            NavigateToParentPage();
        }
Пример #26
0
        public ChangeResponse MakeChange(ChangeRequest transaction)
        {
            var changeResponse = CoinReturn(transaction);

            return(changeResponse);
        }
Пример #27
0
 public Guid Create(ChangeRequest changeRequest)
 {
     return(ScsmClient.ChangeRequest().Create(changeRequest));
 }
Пример #28
0
        public Task ParseTask(Issue issue)
        {
            if (issue == null || issue.Fields == null)
            {
                return(null);
            }

            var jiraBaseUrl = ConfigurationManager.AppSettings["JiraBaseUrl"];

            var ticket = default(Task);

            switch (issue.Fields.IssueType.Name)
            {
            case "Acceptance Test":
                ticket = new AcceptanceTest(issue, jiraBaseUrl);
                break;

            case "Bug":
                ticket = new Bug(issue, jiraBaseUrl);
                break;

            case "Defect":
                ticket = new Defect(issue, jiraBaseUrl);
                break;

            case "Data Fix":
                ticket = new DataFix(issue, jiraBaseUrl);
                break;

            case "Data Migration":
                ticket = new DataMigration(issue, jiraBaseUrl);
                break;

            case "Epic":
                ticket = new Epic(issue, jiraBaseUrl);
                break;

            case "Change Request":
                ticket = new ChangeRequest(issue, jiraBaseUrl);
                break;

            case "Technical Ticket":
                ticket = new TechnicalTicket(issue, jiraBaseUrl);
                break;

            case "Spike":
                ticket = new Spike(issue, jiraBaseUrl);
                break;

            case "Task":
                ticket = new StorySubTask(issue, jiraBaseUrl);
                break;

            default:            // Story
                ticket = new Story(issue, jiraBaseUrl);
                break;
            }
            if (ticket.Issue.Fields.SubTasks.Count > 0)
            {
                ticket.SubTasks = ParseSubTasks(ticket.Issue.Fields.SubTasks);
            }
            ticket.TransitionHistory = ParseTransitionHistory(ticket);
            return(ticket);
        }
Пример #29
0
        private void ParseAttributes(byte[] bytes, int startIndex, int length, TurnMessageRfc rfc)
        {
            int currentIndex = startIndex + HeaderLength;
            int endIndex = startIndex + length;

            while (currentIndex < endIndex)
            {
                UInt16 attributeType1 = bytes.BigendianToUInt16(currentIndex);
                if (Enum.IsDefined(typeof(AttributeType), (Int32)attributeType1) == false)
                    throw new TurnMessageException(ErrorCode.UnknownAttribute);
                AttributeType attributeType = (AttributeType)attributeType1;

                if (rfc == TurnMessageRfc.Rfc3489)
                    if (IsRfc3489(attributeType))
                        throw new TurnMessageException(ErrorCode.UnknownAttribute);

                if (attributeType == AttributeType.Fingerprint)
                {
                    if (Fingerprint == null)
                    {
                        if (storedBytes == null)
                        {
                            storedBytes = new byte[length];
                            Array.Copy(bytes, startIndex, storedBytes, 0, length);
                        }
                        fingerprintStartOffset = currentIndex - startIndex;
                        Fingerprint = new Fingerprint();
                        Fingerprint.Parse(bytes, ref currentIndex);
                    }
                    else
                    {
                        Attribute.Skip(bytes, ref currentIndex);
                    }
                }
                else if (MessageIntegrity != null)
                {
                    Attribute.Skip(bytes, ref currentIndex);
                }
                else
                {
                    switch (attributeType)
                    {
                        case AttributeType.AlternateServer:
                            AlternateServer = new AlternateServer();
                            AlternateServer.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.Bandwidth:
                            Bandwidth = new Bandwidth();
                            Bandwidth.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.Data:
                            Data = new Data();
                            Data.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.DestinationAddress:
                            DestinationAddress = new DestinationAddress();
                            DestinationAddress.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.ErrorCode:
                            ErrorCodeAttribute = new ErrorCodeAttribute();
                            ErrorCodeAttribute.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.Fingerprint:
                            break;

                        case AttributeType.Lifetime:
                            Lifetime = new Lifetime();
                            Lifetime.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.MagicCookie:
                            MagicCookie = new MagicCookie();
                            MagicCookie.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.MappedAddress:
                            MappedAddress = new MappedAddress();
                            MappedAddress.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.MessageIntegrity:
                            messageIntegrityStartOffset = currentIndex - startIndex;
                            if (storedBytes == null)
                            {
                                if (rfc == TurnMessageRfc.MsTurn)
                                {
                                    storedBytes = new byte[GetPadded64(messageIntegrityStartOffset)];
                                    Array.Copy(bytes, startIndex, storedBytes, 0, messageIntegrityStartOffset);
                                }
                                else
                                {
                                    storedBytes = new byte[length];
                                    Array.Copy(bytes, startIndex, storedBytes, 0, length);
                                }
                            }
                            MessageIntegrity = new MessageIntegrity();
                            MessageIntegrity.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.MsVersion:
                            MsVersion = new MsVersion();
                            MsVersion.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.MsSequenceNumber:
                            MsSequenceNumber = new MsSequenceNumber();
                            MsSequenceNumber.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.RemoteAddress:
                            RemoteAddress = new RemoteAddress();
                            RemoteAddress.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.Software:
                            Software = new Software();
                            Software.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.UnknownAttributes:
                            UnknownAttributes = new UnknownAttributes();
                            // Not Implemented
                            UnknownAttributes.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.Username:
                            if (MsVersion != null)
                            {
                                MsUsername = new MsUsername();
                                MsUsername.Parse(bytes, ref currentIndex);
                            }
                            else
                            {
                                Username = new Username();
                                Username.Parse(bytes, ref currentIndex);
                            }
                            break;

                        // ietf-mmusic-ice
                        case AttributeType.Priority:
                        case AttributeType.UseCandidate:
                        case AttributeType.IceControlled:
                        case AttributeType.IceControlling:
                            Attribute.Skip(bytes, ref currentIndex);
                            break;

                        // rfc3489
                        case AttributeType.ChangedAddress:
                            ChangedAddress = new ChangedAddress();
                            ChangedAddress.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.ChangeRequest:
                            ChangeRequest = new ChangeRequest();
                            ChangeRequest.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.ResponseAddress:
                            ResponseAddress = new ResponseAddress();
                            ResponseAddress.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.SourceAddress:
                            SourceAddress = new SourceAddress();
                            SourceAddress.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.ReflectedFrom:
                            ReflectedFrom = new ReflectedFrom();
                            ReflectedFrom.Parse(bytes, ref currentIndex);
                            break;

                        case AttributeType.Password:
                            Password = new Password();
                            Password.Parse(bytes, ref currentIndex);
                            break;

                        default:
                            if (rfc == TurnMessageRfc.MsTurn)
                            {
                                switch (attributeType)
                                {
                                    case AttributeType.Nonce:
                                        Nonce = new Nonce(rfc);
                                        Nonce.Parse(bytes, ref currentIndex);
                                        break;

                                    case AttributeType.Realm:
                                        Realm = new Realm(rfc);
                                        Realm.Parse(bytes, ref currentIndex);
                                        break;

                                    case AttributeType.XorMappedAddress:
                                        XorMappedAddress = new XorMappedAddress(rfc);
                                        XorMappedAddress.Parse(bytes, ref currentIndex, TransactionId);
                                        break;

                                    default:
                                        throw new NotImplementedException();
                                }
                            }
                            else
                            {
                                switch (attributeType)
                                {
                                    case AttributeType.NonceStun:
                                        Nonce = new Nonce(rfc);
                                        Nonce.Parse(bytes, ref currentIndex);
                                        break;

                                    case AttributeType.RealmStun:
                                        Realm = new Realm(rfc);
                                        Realm.Parse(bytes, ref currentIndex);
                                        break;

                                    case AttributeType.XorMappedAddressStun:
                                        XorMappedAddress = new XorMappedAddress(rfc);
                                        XorMappedAddress.Parse(bytes, ref currentIndex, TransactionId);
                                        break;

                                    default:
                                        throw new NotImplementedException();
                                }
                            }
                            break;
                    }
                }

                if (rfc != TurnMessageRfc.MsTurn)
                {
                    if (currentIndex % 4 > 0)
                        currentIndex += 4 - currentIndex % 4;
                }
            }
        }
        partial void ChangeRequests_Inserted(ChangeRequest entity)
        {
            string subject = string.Format("Change Requested to {0} v{1}.{2}", entity.DocumentVersion.Document.DocumentTitle, entity.DocumentVersion.MajorVersionNumber, entity.DocumentVersion.MinorVersionNumber);

            string message = string.Format("<html><body>Dear {0} {1}.<br></br><p>The following a change request has been made against for following document. Please log in to review:<br></br>Reference: {2}.<br></br>Title: {3}.<br></br>Version: {4}.{5}.<br></br>Change Reference: {6}.<br></br>Change Title: {7}.<br></br>Change Description: {8}.<br></br></p>Date raised: {9}.<br></br>Target Date: {10}.<br></br></body></html>", entity.DocumentVersion.Author.FirstName, entity.DocumentVersion.Author.LastName, entity.DocumentVersion.Document.Reference, entity.DocumentVersion.Document.DocumentTitle, entity.DocumentVersion.MajorVersionNumber, entity.DocumentVersion.MinorVersionNumber, entity.Reference, entity.ChangeRequestTitle, entity.ChangeRequestDescription, entity.DateRaised, entity.TargetClosureDate);

            List<string> mailTos = new List<string>();

            mailTos.Add(entity.DocumentVersion.Author.Email);

            SendEmail(mailTos, subject, message);
        }
Пример #31
0
        private ChangeRequest ReadChangeRequestFromSQL(SQLiteDataReader reader)
        {
            var changeRequest = new ChangeRequest();

            changeRequest.ID = Convert.ToInt32(reader[1]);
            changeRequest.VersionImplemented = reader[2].ToString();
            changeRequest.DetailedDescription = reader[3].ToString();
            changeRequest.Justification = reader[4].ToString();

            return changeRequest;
        }
        private void BindGrid()
        {
            var changeId = hfChangeId.ValueAsInt();

            if (changeId == 0)
            {
                changeId = PageParameter("ChangeRequest").AsInteger();
                hfChangeId.SetValue(changeId);
            }
            RockContext          rockContext          = new RockContext();
            ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
            ChangeRequest        changeRequest        = changeRequestService.Get(changeId);

            if (changeRequest == null)
            {
                return;
            }

            if (!IsUserAuthorized(Rock.Security.Authorization.EDIT) &&
                (CurrentPerson == null || !CurrentPerson.Aliases.Select(a => a.Id).Contains(changeRequest.RequestorAliasId)))
            {
                this.Visible = false;
                return;
            }

            CheckForBlacklist(changeRequest);

            var link = "";

            if (changeRequest.EntityTypeId == EntityTypeCache.Get(typeof(PersonAlias)).Id)
            {
                PersonAliasService personAliasService = new PersonAliasService(rockContext);
                var personAlias = personAliasService.Get(changeRequest.EntityId);
                if (personAlias != null)
                {
                    link = string.Format("<a href='/Person/{0}' target='_blank' class='btn btn-default btn-sm'><i class='fa fa-user'></i></a>", personAlias.Person.Id);
                }
            }

            lName.Text = string.Format(@"
<h1 class='panel-title'>{0} {1}</h1>
<div class='panel-labels'>
    <span class='label label-default'>
        Requested by: <a href='/Person/{2}' target='_blank'>{3}</a>
    </span>
    <span class='label label-{4}'>
        {5}
    </span>
</div>",
                                       link,
                                       changeRequest.Name,
                                       changeRequest.RequestorAlias.PersonId,
                                       changeRequest.RequestorAlias.Person.FullName,
                                       changeRequest.IsComplete ? "primary" : "success",
                                       changeRequest.IsComplete ? "Complete" : "Active");

            var changeRecords = changeRequest.ChangeRecords.ToList();

            var entity = ChangeRequest.GetEntity(changeRequest.EntityTypeId, changeRequest.EntityId, rockContext);

            foreach (var changeRecord in changeRecords)
            {
                FormatValues(changeRequest.EntityTypeId, entity, changeRecord, rockContext);
            }

            if (changeRecords.Any())
            {
                gRecords.DataSource = changeRecords;
                gRecords.DataBind();
            }
            else
            {
                gRecords.Visible = false;
            }

            if (changeRequest.RequestorComment.IsNotNullOrWhiteSpace())
            {
                ltRequestComments.Visible = true;
                ltRequestComments.Text    = changeRequest.RequestorComment;
            }

            ltApproverComment.Text = changeRequest.ApproverComment;
            tbApproverComment.Text = changeRequest.ApproverComment;

            if (!IsUserAuthorized(Rock.Security.Authorization.EDIT))
            {
                btnComplete.Visible       = false;
                tbApproverComment.Visible = false;
                ltApproverComment.Visible = true;
                (( DataControlField )gRecords.Columns
                 .Cast <DataControlField>()
                 .Where(fld => (fld.HeaderText == "Is Rejected"))
                 .SingleOrDefault()).Visible = false;
            }
        }
        private void FormatValues(int entityTypeId, IEntity targetEntity, ChangeRecord changeRecord, RockContext rockContext)
        {
            //Get the target Entity
            if (changeRecord.RelatedEntityId.HasValue &&
                changeRecord.RelatedEntityId.Value != 0 &&
                changeRecord.RelatedEntityTypeId.HasValue)
            {
                entityTypeId = changeRecord.RelatedEntityTypeId.Value;

                switch (changeRecord.Action)
                {
                case ChangeRecordAction.Create:
                    targetEntity = ChangeRequest.CreateNewEntity(changeRecord.RelatedEntityTypeId.Value, changeRecord.NewValue, rockContext, false);
                    break;

                case ChangeRecordAction.Delete:
                    targetEntity = ChangeRequest.CreateNewEntity(changeRecord.RelatedEntityTypeId.Value, changeRecord.OldValue, rockContext, false);
                    break;

                default:
                    targetEntity = ChangeRequest.GetEntity(changeRecord.RelatedEntityTypeId.Value, changeRecord.RelatedEntityId.Value, rockContext);
                    break;
                }
            }

            //Enums
            if (changeRecord.Property.IsNotNullOrWhiteSpace())
            {
                PropertyInfo enumProp = targetEntity.GetType().GetProperty(changeRecord.Property, BindingFlags.Public | BindingFlags.Instance);
                if (enumProp != null && enumProp.PropertyType != null && enumProp.PropertyType.IsEnum)
                {
                    enumProp.PropertyType.GetEnumUnderlyingType();
                    changeRecord.NewValue = System.Enum.GetName(enumProp.PropertyType, changeRecord.NewValue.AsInteger()).SplitCase();
                    changeRecord.OldValue = System.Enum.GetName(enumProp.PropertyType, changeRecord.OldValue.AsInteger()).SplitCase();
                }
            }

            //Format new value
            var newObject = changeRecord.NewValue.FromJsonOrNull <BasicEntity>();

            if (newObject != null)
            {
                if (changeRecord.Property.IsNullOrWhiteSpace())
                {
                    changeRecord.NewValue = targetEntity.ToString();
                }
                else
                {
                    PropertyInfo prop = targetEntity.GetType().GetProperty(changeRecord.Property, BindingFlags.Public | BindingFlags.Instance);

                    if (prop.PropertyType.GetInterfaces().Any(i => i.IsInterface && i.GetInterfaces().Contains(typeof(IEntity))))
                    {
                        var entityTypeCache = EntityTypeCache.Get(prop.PropertyType);

                        var entityType = entityTypeCache.GetEntityType();
                        var dyn        = changeRecord.NewValue.FromJsonOrNull <Dictionary <string, object> >();
                        var entity     = (( IEntity )Activator.CreateInstance(entityType));
                        foreach (var key in dyn.Keys)
                        {
                            var eleProp = entity.GetType().GetProperty(key);
                            if (eleProp != null)
                            {
                                ChangeRequest.SetProperty(entity, eleProp, dyn[key].ToStringSafe());
                            }
                        }
                        if (entity != null)
                        {
                            changeRecord.NewValue = entity.ToString();
                        }
                    }
                }
            }

            //Format old Value
            var oldObject = changeRecord.OldValue.FromJsonOrNull <BasicEntity>();

            if (oldObject != null)
            {
                if (changeRecord.Property.IsNullOrWhiteSpace())
                {
                    changeRecord.OldValue = targetEntity.ToString();
                }
                else
                {
                    PropertyInfo prop = targetEntity.GetType().GetProperty(changeRecord.Property, BindingFlags.Public | BindingFlags.Instance);

                    if (prop.PropertyType.GetInterfaces().Any(i => i.IsInterface && i.GetInterfaces().Contains(typeof(IEntity))))
                    {
                        var entityTypeCache = EntityTypeCache.Get(prop.PropertyType);

                        var entityType = entityTypeCache.GetEntityType();
                        var dyn        = changeRecord.OldValue.FromJsonOrNull <Dictionary <string, object> >();
                        var entity     = (( IEntity )Activator.CreateInstance(entityType));
                        foreach (var key in dyn.Keys)
                        {
                            var eleProp = entity.GetType().GetProperty(key);
                            if (eleProp != null)
                            {
                                ChangeRequest.SetProperty(entity, eleProp, dyn[key].ToStringSafe());
                            }
                        }
                        if (entity != null)
                        {
                            changeRecord.OldValue = entity.ToString();
                        }
                    }
                }
            }

            //Special Dispensation for the photo.
            if (changeRecord.Property == "PhotoId")
            {
                if (changeRecord.NewValue.AsInteger() != 0)
                {
                    changeRecord.NewValue = string.Format("<a href='/GetImage.ashx?id={0}' target='_blank'><img src='/GetImage.ashx?id={0}' height=50></a>",
                                                          changeRecord.NewValue);
                }
                if (changeRecord.OldValue.AsInteger() != 0)
                {
                    changeRecord.OldValue = string.Format("<a href='/GetImage.ashx?id={0}' target='_blank'><img src='/GetImage.ashx?id={0}' height=50></a>",
                                                          changeRecord.OldValue);
                }
            }
            else
            {
                //Format Property Name

                if (changeRecord.RelatedEntityType != null)
                {
                    changeRecord.Property = changeRecord.RelatedEntityType.Name.Split('.').Last() + ": " + changeRecord.Property.SplitCase();
                }
                else
                {
                    changeRecord.Property = changeRecord.Property.SplitCase();
                }
                if (changeRecord.Comment.IsNotNullOrWhiteSpace())
                {
                    changeRecord.Property += "<br>(" + changeRecord.Comment + ")";
                }
            }
        }
Пример #34
0
 private void InsertChangeRequestInDB(ChangeRequest changeRequest, int issueID)
 {
     new SQLiteCommand(SQLFixedQueries.InsertChangeRequest(issueID,
                                                           changeRequest.VersionImplemented,
                                                           changeRequest.DetailedDescription,
                                                           changeRequest.Justification),
                         conn).ExecuteNonQuery();
 }
Пример #35
0
        /// <summary>
        /// Login to the RTC server and perform some OSLC actions
        /// </summary>
        /// <param name="args"></param>
        static void Main(string[] args)
        {
            log4net.Config.XmlConfigurator.Configure();

            CommandLineDictionary cmd = CommandLineDictionary.FromArguments(args);

            if (!ValidateOptions(cmd))
            {
                logger.Error("Syntax:  /url=https://<server>:port/<context>/ /user=<user> /password=<password> /project=\"<project_area>\"");
                logger.Error("Example: /url=https://exmple.com:9443/ccm /user=ADMIN /password=ADMIN /project=\"JKE Banking (Change Management)\"");
                return;
            }

            String webContextUrl = cmd["url"];
            String user          = cmd["user"];
            String passwd        = cmd["password"];
            String projectArea   = cmd["project"];

            try {
                //STEP 1: Initialize a Jazz rootservices helper and indicate we're looking for the ChangeManagement catalog
                //RTC contains a service provider for CM and SCM, so we need to indicate our interest in CM
                JazzRootServicesHelper helper = new JazzRootServicesHelper(webContextUrl, OSLCConstants.OSLC_CM_V2);

                //STEP 2: Create a new Form Auth client with the supplied user/password
                JazzFormAuthClient client = helper.InitFormClient(user, passwd);

                //STEP 3: Login in to Jazz Server
                if (client.FormLogin() == HttpStatusCode.OK)
                {
                    //STEP 4: Get the URL of the OSLC ChangeManagement catalog
                    String catalogUrl = helper.GetCatalogUrl();

                    //STEP 5: Find the OSLC Service Provider for the project area we want to work with
                    String serviceProviderUrl = client.LookupServiceProviderUrl(catalogUrl, projectArea);

                    //STEP 6: Get the Query Capabilities URL so that we can run some OSLC queries
                    String queryCapability = client.LookupQueryCapability(serviceProviderUrl,
                                                                          OSLCConstants.OSLC_CM_V2,
                                                                          OSLCConstants.CM_CHANGE_REQUEST_TYPE);

                    //SCENARIO A: Run a query for all open ChangeRequests with OSLC paging of 10 items per
                    //page turned on and list the members of the result
                    OslcQueryParameters queryParams = new OslcQueryParameters();
                    queryParams.SetWhere("oslc_cm:closed=false");
                    queryParams.SetSelect("dcterms:identifier,dcterms:title,oslc_cm:status");
                    OslcQuery query = new OslcQuery(client, queryCapability, 10, queryParams);

                    OslcQueryResult result = query.Submit();

                    bool processAsJavaObjects = true;
                    ProcessPagedQueryResults(result, client, processAsJavaObjects);

                    Console.WriteLine("\n------------------------------\n");

                    //SCENARIO B:  Run a query for a specific ChangeRequest selecting only certain
                    //attributes and then print it as raw XML.  Change the dcterms:identifier below to match a
                    //real workitem in your RTC project area
                    OslcQueryParameters queryParams2 = new OslcQueryParameters();
                    queryParams2.SetWhere("dcterms:identifier=\"10\"");
                    queryParams2.SetSelect("dcterms:identifier,dcterms:title,dcterms:creator,dcterms:created,oslc_cm:status");
                    OslcQuery query2 = new OslcQuery(client, queryCapability, queryParams2);

                    OslcQueryResult     result2     = query2.Submit();
                    HttpResponseMessage rawResponse = result2.GetRawResponse();
                    ProcessRawResponse(rawResponse);
                    rawResponse.ConsumeContent();

                    //SCENARIO C:  RTC Workitem creation and update
                    ChangeRequest changeRequest = new ChangeRequest();
                    changeRequest.SetTitle("Implement accessibility in Pet Store application");
                    changeRequest.SetDescription("Image elements must provide a description in the 'alt' attribute for consumption by screen readers.");
                    changeRequest.AddTestedByTestCase(new Link(new Uri("http://qmprovider/testcase/1"), "Accessibility verification using a screen reader"));
                    changeRequest.AddDctermsType("task");

                    //Get the Creation Factory URL for change requests so that we can create one
                    String changeRequestCreation = client.LookupCreationFactory(
                        serviceProviderUrl, OSLCConstants.OSLC_CM_V2,
                        changeRequest.GetRdfTypes()[0].ToString());

                    //Create the change request
                    HttpResponseMessage creationResponse = client.CreateResource(
                        changeRequestCreation, changeRequest,
                        OslcMediaType.APPLICATION_RDF_XML,
                        OslcMediaType.APPLICATION_RDF_XML);

                    if (creationResponse.StatusCode != HttpStatusCode.Created)
                    {
                        String errorString = creationResponse.Content.ReadAsStringAsync().Result;
                        Console.Error.WriteLine("Failed to create change request: " + errorString);
                        return;
                    }

                    String changeRequestLocation = creationResponse.Headers.Location.ToString();
                    creationResponse.ConsumeContent();
                    Console.WriteLine("Change Request created a location " + changeRequestLocation);


                    //Get the change request from the service provider and update its title property
                    changeRequest = client.GetResource(changeRequestLocation,
                                                       OslcMediaType.APPLICATION_RDF_XML).Content.ReadAsAsync <ChangeRequest>(client.GetFormatters()).Result;
                    changeRequest.SetTitle(changeRequest.GetTitle() + " (updated)");

                    //Create a partial update URL so that only the title will be updated.
                    //Assuming (for readability) that the change request URL does not already contain a '?'
                    String updateUrl = changeRequest.GetAbout() + "?oslc.properties=dcterms:title";

                    //Update the change request at the service provider
                    HttpResponseMessage updateResponse = client.UpdateResource(
                        updateUrl, changeRequest,
                        OslcMediaType.APPLICATION_RDF_XML,
                        OslcMediaType.APPLICATION_RDF_XML);

                    updateResponse.ConsumeContent();
                }
            } catch (RootServicesException re) {
                logger.Error("Unable to access the Jazz rootservices document at: " + webContextUrl + "/rootservices", re);
            } catch (Exception e) {
                logger.Error(e.Message, e);
            }
        }
Пример #36
0
        protected void btnSave_Click(object sender, EventArgs e)
        {
            RockContext rockContext           = new RockContext();
            var         person                = GetPerson();
            var         personAliasEntityType = EntityTypeCache.Get(typeof(PersonAlias));
            var         changeRequest         = new ChangeRequest
            {
                EntityTypeId     = personAliasEntityType.Id,
                EntityId         = person.PrimaryAliasId ?? 0,
                RequestorAliasId = CurrentPersonAliasId ?? 0,
                RequestorComment = tbComments.Text
            };

            changeRequest.EvaluatePropertyChange(person, "PhotoId", iuPhoto.BinaryFileId);
            changeRequest.EvaluatePropertyChange(person, "TitleValue", DefinedValueCache.Get(ddlTitle.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "FirstName", tbFirstName.Text);
            changeRequest.EvaluatePropertyChange(person, "NickName", tbNickName.Text);
            changeRequest.EvaluatePropertyChange(person, "MiddleName", tbMiddleName.Text);
            changeRequest.EvaluatePropertyChange(person, "LastName", tbLastName.Text);
            changeRequest.EvaluatePropertyChange(person, "SuffixValue", DefinedValueCache.Get(ddlSuffix.SelectedValueAsInt() ?? 0));

            var families = person.GetFamilies();

            if (families.Count() == 1)
            {
                var groupMember = person.PrimaryFamily.Members.Where(gm => gm.PersonId == person.Id).FirstOrDefault();
                if (groupMember != null)
                {
                    GroupTypeRole        groupTypeRole        = null;
                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);
                    if (ddlFamilyRole.SelectedValue == "A")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid());
                    }
                    else if (ddlFamilyRole.SelectedValue == "C")
                    {
                        groupTypeRole = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid());
                    }
                    changeRequest.EvaluatePropertyChange(groupMember, "GroupRole", groupTypeRole, true);
                }
            }

            //Evaluate PhoneNumbers
            var  phoneNumberTypeIds = new List <int>();
            bool smsSelected        = false;

            foreach (RepeaterItem item in rContactInfo.Items)
            {
                HiddenField    hfPhoneType = item.FindControl("hfPhoneType") as HiddenField;
                PhoneNumberBox pnbPhone    = item.FindControl("pnbPhone") as PhoneNumberBox;
                CheckBox       cbUnlisted  = item.FindControl("cbUnlisted") as CheckBox;
                CheckBox       cbSms       = item.FindControl("cbSms") as CheckBox;

                if (hfPhoneType != null &&
                    pnbPhone != null &&
                    cbSms != null &&
                    cbUnlisted != null)
                {
                    int phoneNumberTypeId;
                    if (int.TryParse(hfPhoneType.Value, out phoneNumberTypeId))
                    {
                        var    phoneNumber    = person.PhoneNumbers.FirstOrDefault(n => n.NumberTypeValueId == phoneNumberTypeId);
                        string oldPhoneNumber = string.Empty;
                        if (phoneNumber == null && pnbPhone.Number.IsNotNullOrWhiteSpace())   //Add number
                        {
                            phoneNumber = new PhoneNumber
                            {
                                PersonId           = person.Id,
                                NumberTypeValueId  = phoneNumberTypeId,
                                CountryCode        = PhoneNumber.CleanNumber(pnbPhone.CountryCode),
                                IsMessagingEnabled = !smsSelected && cbSms.Checked,
                                Number             = PhoneNumber.CleanNumber(pnbPhone.Number)
                            };
                            var phoneComment = string.Format("{0}: {1}.", DefinedValueCache.Get(phoneNumberTypeId).Value, pnbPhone.Number);
                            changeRequest.AddEntity(phoneNumber, rockContext, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNullOrWhiteSpace())   // delete number
                        {
                            var phoneComment = string.Format("{0}: {1}.", phoneNumber.NumberTypeValue.Value, phoneNumber.NumberFormatted);
                            changeRequest.DeleteEntity(phoneNumber, true, phoneComment);
                        }
                        else if (phoneNumber != null && pnbPhone.Text.IsNotNullOrWhiteSpace())   // update number
                        {
                            changeRequest.EvaluatePropertyChange(phoneNumber, "Number", PhoneNumber.CleanNumber(pnbPhone.Number), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsMessagingEnabled", (!smsSelected && cbSms.Checked), true);
                            changeRequest.EvaluatePropertyChange(phoneNumber, "IsUnlisted", cbUnlisted.Checked, true);
                        }

                        if (hfPhoneType.Value.AsInteger() == DefinedValueCache.GetId(Rock.SystemGuid.DefinedValue.PERSON_PHONE_TYPE_MOBILE.AsGuid()))
                        {
                            var validationInfo = ValidateMobilePhoneNumber(PhoneNumber.CleanNumber(pnbPhone.Number));
                            if (validationInfo.IsNotNullOrWhiteSpace())
                            {
                                changeRequest.RequestorComment += "<h4>Dynamically Generated Warnings:</h4>" + validationInfo;
                            }
                        }
                    }
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Email", tbEmail.Text);
            changeRequest.EvaluatePropertyChange(person, "IsEmailActive", cbIsEmailActive.Checked);
            changeRequest.EvaluatePropertyChange(person, "EmailPreference", rblEmailPreference.SelectedValueAsEnum <EmailPreference>());
            changeRequest.EvaluatePropertyChange(person, "CommunicationPreference", rblCommunicationPreference.SelectedValueAsEnum <CommunicationType>());


            var birthday = bpBirthday.SelectedDate;

            if (birthday.HasValue)
            {
                changeRequest.EvaluatePropertyChange(person, "BirthMonth", birthday.Value.Month);
                changeRequest.EvaluatePropertyChange(person, "BirthDay", birthday.Value.Day);
                if (birthday.Value.Year != DateTime.MinValue.Year)
                {
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", birthday.Value.Year);
                }
                else
                {
                    int?year = null;
                    changeRequest.EvaluatePropertyChange(person, "BirthYear", year);
                }
            }

            changeRequest.EvaluatePropertyChange(person, "Gender", ddlGender.SelectedValueAsEnum <Gender>());
            changeRequest.EvaluatePropertyChange(person, "MaritalStatusValue", DefinedValueCache.Get(ddlMaritalStatus.SelectedValueAsInt() ?? 0));
            changeRequest.EvaluatePropertyChange(person, "AnniversaryDate", dpAnniversaryDate.SelectedDate);
            changeRequest.EvaluatePropertyChange(person, "GraduationYear", ypGraduation.SelectedYear);

            var groupEntity         = EntityTypeCache.Get(typeof(Group));
            var groupLocationEntity = EntityTypeCache.Get(typeof(GroupLocation));
            var family = person.GetFamily();

            var familyChangeRequest = new ChangeRequest()
            {
                EntityTypeId     = groupEntity.Id,
                EntityId         = family.Id,
                RequestorAliasId = CurrentPersonAliasId ?? 0
            };

            familyChangeRequest.EvaluatePropertyChange(family, "Campus", CampusCache.Get(ddlCampus.SelectedValueAsInt() ?? 0));

            var      currentLocation = person.GetHomeLocation();
            Location location        = new Location
            {
                Street1    = acAddress.Street1,
                Street2    = acAddress.Street2,
                City       = acAddress.City,
                State      = acAddress.State,
                PostalCode = acAddress.PostalCode,
            };
            var globalAttributesCache = GlobalAttributesCache.Get();

            location.Country = globalAttributesCache.OrganizationCountry;
            location.Country = string.IsNullOrWhiteSpace(location.Country) ? "US" : location.Country;

            if ((currentLocation == null && location.Street1.IsNotNullOrWhiteSpace()) ||
                (currentLocation != null && currentLocation.Street1 != location.Street1))
            {
                LocationService locationService = new LocationService(rockContext);
                locationService.Add(location);
                rockContext.SaveChanges();

                var previousLocationType = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_PREVIOUS.AsGuid());
                var homeLocationType     = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.GROUP_LOCATION_TYPE_HOME.AsGuid());

                GroupLocation groupLocation = new GroupLocation
                {
                    CreatedByPersonAliasId  = CurrentPersonAliasId,
                    ModifiedByPersonAliasId = CurrentPersonAliasId,
                    GroupId    = family.Id,
                    LocationId = location.Id,
                    GroupLocationTypeValueId = homeLocationType.Id,
                    IsMailingLocation        = true,
                    IsMappedLocation         = true
                };

                var newGroupLocation = familyChangeRequest.AddEntity(groupLocation, rockContext, true, location.ToString());

                var homelocations = family.GroupLocations.Where(gl => gl.GroupLocationTypeValueId == homeLocationType.Id);
                foreach (var homelocation in homelocations)
                {
                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "GroupLocationTypeValue",
                        previousLocationType,
                        true,
                        homelocation.Location.ToString());

                    familyChangeRequest.EvaluatePropertyChange(
                        homelocation,
                        "IsMailingLocation",
                        false,
                        true,
                        homelocation.Location.ToString());
                }
            }

            //Adding a new family member
            if (pAddPerson.SelectedValue.HasValue)
            {
                PersonService personService = new PersonService(rockContext);
                var           insertPerson  = personService.Get(pAddPerson.SelectedValue.Value);
                if (insertPerson != null)
                {
                    GroupMemberService groupMemberService = new GroupMemberService(rockContext);
                    var familyGroupTypeId = GroupTypeCache.Get(Rock.SystemGuid.GroupType.GROUPTYPE_FAMILY.AsGuid()).Id;

                    //Remove all other group members
                    if (cbRemovePerson.Checked)
                    {
                        var members = groupMemberService.Queryable()
                                      .Where(m => m.PersonId == pAddPerson.SelectedValue.Value && m.Group.GroupTypeId == familyGroupTypeId);
                        foreach (var member in members)
                        {
                            var comment = string.Format("Removed {0} from {1}", insertPerson.FullName, member.Group.Name);
                            familyChangeRequest.DeleteEntity(member, true, comment);
                        }
                    }

                    var personFamilies = person.GetFamilies().ToList();

                    GroupTypeRoleService groupTypeRoleService = new GroupTypeRoleService(rockContext);

                    var roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_ADULT.AsGuid()).Id;
                    if (insertPerson.Age.HasValue && insertPerson.Age.Value < 18)
                    {
                        roleId = groupTypeRoleService.Get(Rock.SystemGuid.GroupRole.GROUPROLE_FAMILY_MEMBER_CHILD.AsGuid()).Id;
                    }

                    foreach (var personFamily in personFamilies)
                    {
                        //Make a new group member
                        GroupMember familyMember = new GroupMember
                        {
                            PersonId          = pAddPerson.SelectedValue.Value,
                            GroupId           = personFamily.Id,
                            GroupMemberStatus = GroupMemberStatus.Active,
                            Guid        = Guid.NewGuid(),
                            GroupRoleId = roleId
                        };
                        var insertComment = string.Format("Added {0} to {1}", insertPerson.FullName, personFamily.Name);
                        familyChangeRequest.AddEntity(familyMember, rockContext, true, insertComment);
                    }
                }
            }

            bool          autoApply = CanAutoApply(person);
            List <string> errors;

            if (changeRequest.ChangeRecords.Any() ||
                (!familyChangeRequest.ChangeRecords.Any() && tbComments.Text.IsNotNullOrWhiteSpace()))
            {
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(changeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    changeRequest.CompleteChanges(rockContext, out errors);
                }

                changeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (familyChangeRequest.ChangeRecords.Any())
            {
                familyChangeRequest.RequestorComment = tbComments.Text;
                ChangeRequestService changeRequestService = new ChangeRequestService(rockContext);
                changeRequestService.Add(familyChangeRequest);
                rockContext.SaveChanges();
                if (autoApply)
                {
                    familyChangeRequest.CompleteChanges(rockContext, out errors);
                }
                familyChangeRequest.LaunchWorkflow(GetAttributeValue("Workflow").AsGuidOrNull());
            }

            if (autoApply)
            {
                NavigateToPerson();
            }
            else
            {
                pnlMain.Visible     = false;
                pnlNoPerson.Visible = false;
                pnlDone.Visible     = true;
            }
        }
 private void AddReason(ChangeRequest request)
 {
     _reasonRepository.Add(Reason.FromChangeRequest(request));
 }
Пример #38
0
 private void UpdateChangeRequestInDB(ChangeRequest changeRequest)
 {
     new SQLiteCommand(SQLFixedQueries.UpdateChangeRequest(changeRequest.ID,
                                                           changeRequest.VersionImplemented,
                                                           changeRequest.DetailedDescription,
                                                           changeRequest.Justification),
                         conn).ExecuteNonQuery();
 }
Пример #39
0
 public Guid CreateFromTemplate(string templateName, ChangeRequest changeRequest)
 {
     return(ScsmClient.ChangeRequest().CreateFromTemplate(templateName, changeRequest));
 }
Пример #40
0
 public void ChangeRequestConstructorTest()
 {
     ChangeRequest target = new ChangeRequest();
     Assert.AreEqual(AttributeType.ChangeRequest, target.AttributeType);
 }
        partial void ChangeRequests_Updated(ChangeRequest entity)
        {
            if(entity.DateClosed != null)
            {
                string subject = string.Format("Change Requested to {0} v{1}.{2}", entity.DocumentVersion.Document.DocumentTitle, entity.DocumentVersion.MajorVersionNumber, entity.DocumentVersion.MinorVersionNumber);

                string message = string.Format("<html><body>Dear {0} {1}.<br></br><p>The following a change request has been reviewed:<br></br>Reference: {2}.<br></br>Title: {3}.<br></br>Version: {4}.{5}.<br></br>Change Reference: {6}.<br></br>Change Title: {7}.<br></br>Change Description: {8}.<br></br></p>Date raised: {9}.<br></br>Date Closed: {10}.<br></br>Status: {11}.<br></br></body></html>", entity.RaisedBy.FirstName, entity.RaisedBy.LastName, entity.DocumentVersion.Document.Reference, entity.DocumentVersion.Document.DocumentTitle, entity.DocumentVersion.MajorVersionNumber, entity.DocumentVersion.MinorVersionNumber, entity.Reference, entity.ChangeRequestTitle, entity.ChangeRequestDescription, entity.DateRaised, entity.DateClosed, entity.ChangeRequestStatus.Status);

                List<string> mailTos = new List<string>();

                mailTos.Add(entity.RaisedBy.Email);

                SendEmail(mailTos, subject, message);
            }
        }
    static void Main()
    {
        // Create an instance of WorkItem by using the constructor in the
                // base class that takes three arguments.
                WorkItem item = new WorkItem("Fix Bugs",
                                             "Fix all bugs in my code branch",
                                             new TimeSpan(3, 4, 0, 0));

                // Create an instance of ChangeRequest by using the constructor in
                // the derived class that takes four arguments.
                ChangeRequest change = new ChangeRequest("Change Base Class Design",
                                                         "Add members to the class",
                                                         new TimeSpan(4, 0, 0),
                                                         1);

                // Use the ToString method defined in WorkItem.
                Console.WriteLine(item.ToString());

                // Use the inherited Update method to change the title of the
                // ChangeRequest object.
                change.Update("Change the Design of the Base Class",
                    new TimeSpan(4, 0, 0));

                // ChangeRequest inherits WorkItem's override of ToString.
                Console.WriteLine(change.ToString());

                // Keep the console open in debug mode.
                Console.WriteLine("Press any key to exit.");
                Console.ReadKey();
    }
        partial void ChangeRequests_Validate(ChangeRequest entity, EntitySetValidationResultsBuilder results)
        {
            if (entity.TargetClosureDate != null & entity.DateRaised != null)
            {
                if (entity.TargetClosureDate < entity.DateRaised)
                {
                    results.AddEntityError("The target closure date cannot be before the date raised");
                }
            }

            if (entity.DateClosed != null & entity.DateRaised != null)
            {
                if (entity.DateClosed < entity.DateRaised)
                {
                    results.AddEntityError("The date closed cannot be before the date raised");
                }
            }
        }
Пример #44
0
        int IDataAccess.SaveChangeRequest(Issue issue, ChangeRequest changeRequest)
        {
            using (conn = new SQLiteConnection(connectionString))
            {
                conn.Open();

                if (issue.IssueID == 0 || !IssueExists(issue.IssueID))
                {
                    int ID = InsertIssueInDBAndGetID(issue, GetUserID(issue.UserCreated));
                    InsertChangeRequestInDB(changeRequest, ID);
                    return ID;
                }
                else
                {
                    UpdateIssueInDB(issue, GetUserID(issue.UserClosed));
                    UpdateChangeRequestInDB(changeRequest);
                    return issue.IssueID;
                }
            }
        }
Пример #45
0
        /// <summary>
        /// Gets the customer shared change requests.
        /// </summary>
        /// <param name="CustomerID">The customer identifier.</param>
        /// <returns></returns>
        public async Task <DatabaseResponse> GetCustomerSharedChangeRequests(int CustomerID)
        {
            try
            {
                SqlParameter[] parameters =
                {
                    new SqlParameter("@CustomerID", SqlDbType.Int)
                };

                parameters[0].Value = CustomerID;

                _DataHelper = new DataAccessHelper("Admin_GetCustomerSharedChangeRequests", parameters, _configuration);

                DataSet ds = new DataSet();

                int result = await _DataHelper.RunAsync(ds); // 105 /102

                DatabaseResponse response = new DatabaseResponse();

                if (result == 105)
                {
                    List <ChangeRequest> orders = new List <ChangeRequest>();
                    foreach (DataRow dr in ds.Tables[0].Rows)
                    {
                        ChangeRequest orderDetails = new ChangeRequest();

                        if (dr != null)
                        {
                            orderDetails.ChangeRequestID       = Convert.ToInt32(dr["ChangeRequestID"]);
                            orderDetails.ListingStatus         = dr["ListingStatus"].ToString();
                            orderDetails.OrderNumber           = dr["OrderNumber"].ToString();
                            orderDetails.RequestOn             = Convert.ToDateTime(dr["RequestOn"]);
                            orderDetails.OrderStatus           = dr["OrderStatus"].ToString();
                            orderDetails.RequestType           = dr["RequestType"].ToString();
                            orderDetails.BillingUnit           = dr["BillingUnit"].ToString();
                            orderDetails.BillingFloor          = dr["BillingFloor"].ToString();
                            orderDetails.BillingBuildingNumber = dr["BillingBuildingNumber"].ToString();
                            orderDetails.BillingBuildingName   = dr["BillingBuildingName"].ToString();
                            orderDetails.BillingStreetName     = dr["BillingStreetName"].ToString();
                            orderDetails.BillingPostCode       = dr["BillingPostCode"].ToString();
                            orderDetails.BillingContactNumber  = dr["BillingContactNumber"].ToString();
                            orderDetails.Name                      = dr["Name"].ToString();
                            orderDetails.Email                     = dr["Email"].ToString();
                            orderDetails.IDType                    = dr["IDType"].ToString();
                            orderDetails.IDNumber                  = dr["IDNumber"].ToString();
                            orderDetails.IsSameAsBilling           = (dr["IsSameAsBilling"] == DBNull.Value ? 0 : Convert.ToInt32(dr["IsSameAsBilling"]));
                            orderDetails.ShippingUnit              = dr["ShippingUnit"].ToString();
                            orderDetails.ShippingFloor             = dr["ShippingFloor"].ToString();
                            orderDetails.ShippingBuildingNumber    = dr["ShippingBuildingNumber"].ToString();
                            orderDetails.ShippingBuildingName      = dr["ShippingBuildingName"].ToString();
                            orderDetails.ShippingStreetName        = dr["ShippingStreetName"].ToString();
                            orderDetails.ShippingPostCode          = dr["ShippingPostCode"].ToString();
                            orderDetails.ShippingContactNumber     = dr["ShippingContactNumber"].ToString();
                            orderDetails.AlternateRecipientContact = dr["AlternateRecipientContact"].ToString();
                            orderDetails.AlternateRecipientName    = dr["AlternateRecipientName"].ToString();
                            orderDetails.AlternateRecipientEmail   = dr["AlternateRecipientEmail"].ToString();
                            orderDetails.PortalSlotID              = dr["PortalSlotID"].ToString();
                            if (dr["SlotDate"] == DBNull.Value)
                            {
                                orderDetails.SlotDate = null;
                            }
                            else
                            {
                                orderDetails.SlotDate = Convert.ToDateTime(dr["SlotDate"]);
                            }
                            TimeSpan val;
                            TimeSpan.TryParse(dr["SlotFromTime"].ToString(), out val);
                            orderDetails.SlotFromTime = val;
                            TimeSpan.TryParse(dr["SlotToTime"].ToString(), out val);
                            orderDetails.SlotToTime = val;
                            try { orderDetails.ScheduledDate = Convert.ToDateTime(dr["ScheduledDate"]); }
                            catch { }
                            try { orderDetails.ServiceFee = Convert.ToDouble(dr["ServiceFee"]); }
                            catch { }
                        }
                        orders.Add(orderDetails);
                    }
                    response = new DatabaseResponse {
                        ResponseCode = result, Results = orders
                    };
                }

                else
                {
                    response = new DatabaseResponse {
                        ResponseCode = result
                    };
                }

                return(response);
            }

            catch (Exception ex)
            {
                LogInfo.Error(new ExceptionHelper().GetLogString(ex, ErrorLevel.Critical));

                throw (ex);
            }
            finally
            {
                _DataHelper.Dispose();
            }
        }
Пример #46
0
 public async Task <ChangeResponse> ChangeAsync(ChangeRequest model)
 {
     return(await this.Reply(() => this.Channel.ChangeAsync(model)));
 }
Пример #47
0
        public async Task <IActionResult> OnPostAsync(int id)
        {
            //if (Epf.Type == "Cancel Project")
            //{
            //    if (Epf.Reason == null)
            //    {
            //        ErrorMessage = "The reason cannot be empty.";
            //        return RedirectToPage("/Supervisor/Project/EditProject", id);
            //    }

            //    var project = await _context.Project.Where(p => p.DateDeleted == null).FirstOrDefaultAsync(p => p.ProjectId == id);

            //    if (project == null)
            //    {
            //        ErrorMessage = "Project not found.";
            //        return RedirectToPage("/Supervisor/Project/ViewProject", id);
            //    }

            //    if (project.ProjectStatus != "Available" && project.ProjectStatus != "Taken")
            //    {
            //        ErrorMessage = "Action denied";
            //        return RedirectToPage("/Supervisor/Project/ViewProject", id);
            //    }

            //    var changeRequest = new ChangeRequest
            //    {
            //        ChangeRequestType = Epf.Type,
            //        ReasonToChange = Epf.Reason,
            //        ChangeRequestStatus = "New",
            //        DateCreated = DateTime.Now
            //    };


            //}

            if (Epf.Type == null)
            {
                ErrorMessage = "Change type cannot be empty.";
                return(RedirectToPage("/Supervisor/Project/EditProject", id));
            }

            if (Epf.Type == "Edit Project")
            {
                if (Epf.Reason == null)
                {
                    ErrorMessage = "The reason cannot be empty.";
                    return(RedirectToPage("/Supervisor/Project/EditProject", id));
                }

                if (Epf.Title == null || Epf.Description == null || Epf.Objective == null || Epf.Scope == null)
                {
                    ErrorMessage = "The field cannot be empty.";
                    return(RedirectToPage("/Supervisor/Project/EditProject", id));
                }

                var project = await _context.Project.Where(p => p.DateDeleted == null).FirstOrDefaultAsync(p => p.ProjectId == id);

                if (project == null)
                {
                    ErrorMessage = "Project not found.";
                    return(RedirectToPage("/Supervisor/Project/ViewProject", id));
                }

                if (project.ProjectStatus != "Available" && project.ProjectStatus != "Taken")
                {
                    ErrorMessage = "Action denied";
                    return(RedirectToPage("/Supervisor/Project/ViewProject", id));
                }

                var changeRequest = new ChangeRequest
                {
                    ChangeRequestType   = Epf.Type,
                    Title               = Epf.Title,
                    Description         = Epf.Description,
                    Objective           = Epf.Objective,
                    Scope               = Epf.Scope,
                    ReasonToChange      = Epf.Reason,
                    ChangeRequestStatus = "New",
                    ProjectId           = id,
                    DateCreated         = DateTime.Now
                };
                _context.ChangeRequest.Add(changeRequest);
                await _context.SaveChangesAsync();

                var username   = HttpContext.Session.GetString("_username");
                var supervisor = await _context.Supervisor.Where(s => s.DateDeleted == null).FirstOrDefaultAsync(s => s.AssignedId == username);

                var coordinator = await _context.Coordinator.Where(c => c.DateDeleted == null).FirstOrDefaultAsync();

                var mailsubject = "FYP System - Project (Request for Modification)";
                var mailbody    = $@"Dear {coordinator.CoordinatorName}, 

The following project is requesting for change approval. 

Project ID: {project.AssignedId}
Project Title: {project.ProjectTitle}

New Project Title: 
{Epf.Title}

New Project Description:
{Epf.Description}

New Project Objective:
{Epf.Objective}

New Project Scope:
{Epf.Scope}

Please navigate to the system menu under Project --> Manage Project Change to check for more information. 

Please contact the Coordinator if you found any problem or difficulty using the system. Thank You.

Yours Sincerely,
{supervisor.SupervisorName}
(FYP Supervisor)";

                await _emailSender.SendEmailAsync(supervisor.SupervisorEmail, coordinator.CoordinatorEmail, mailsubject, mailbody);

                //var projectSpecializations = await _context.ProjectSpecialization.Include(p => p.Specialization).Where(ps => ps.ProjectId == project.ProjectId).ToListAsync();

                //projectSpecializations[0].ProjectDescription = Epf.Description;
                //projectSpecializations[0].ProjectObjective = Epf.Objective;
                //projectSpecializations[0].ProjectScope = Epf.Scope;
                //await _context.SaveChangesAsync();

                //                var supervisor = await _context.Supervisor.Where(s => s.DateDeleted == null).FirstOrDefaultAsync(s => s.AssignedId == project.SupervisorId);

                //                var student = await _context.Student.Where(s => s.DateDeleted == null).FirstOrDefaultAsync(s => s.ProjectId == project.ProjectId);

                //                if (student != null)
                //                {
                //                    var mailsubject = "FYP System - Project (Modified)";
                //                    var mailbody = $@"Dear {student.StudentName},

                //Your following project had been modified.

                //Project ID: {project.AssignedId}
                //Project Title: {project.ProjectTitle}

                //New Project Description:
                //{Epf.Description}

                //New Project Objective:
                //{Epf.Objective}

                //New Project Scope:
                //{Epf.Scope}

                //Please navigate to the system menu under Project --> My Project to check for more information.

                //Please contact the Coordinator if you found any problem or difficulty using the system. Thank You.

                //Yours Sincerely,
                //{supervisor.SupervisorName}
                //(FYP Supervisor)";

                //                    await _emailSender.SendEmailAsync(supervisor.SupervisorEmail, student.StudentEmail, mailsubject, mailbody);
                //                }

                SuccessMessage = "Change request sent.";
            }

            return(RedirectToPage("/Supervisor/Project/ViewProject", id));
        }
Пример #48
0
        ChangeRequest IDataAccess.GetChangeRequest(int id)
        {
            using (conn = new SQLiteConnection(connectionString))
            {
                conn.Open();

                var changeRequest = new ChangeRequest();

                var reader = new SQLiteCommand(SQLFixedQueries.SelectChangeRequest(id), conn)
                                                    .ExecuteReader();

                while (reader.Read())
                    changeRequest = ReadChangeRequestFromSQL(reader);

                return changeRequest;
            }
        }