public void StormsMilestoneRequirement(Models.DTO.WorkRequest workRequest, Models.DTO.WorkPacket workPacket)
        {
            try
            {
                //check to see if the requirement exists on the work request
                Forestry.Models.DTO.MilestoneRequirement mreq = _workRequestMilestoneRequirementRequestor.Get(
                    new Uri(BaseManagedWorkApiUri + ResolveCurlyBrackets(Properties.Settings.Default.ManagedWorkOrderApiResourse_MilestoneRequirement, workPacket.WorkRequestId.ToString(), "624"))
                    );

                if (mreq == null)
                {
                    CreateMilestoneRequirement(workRequest, workPacket);
                }
                else
                {
                    mreq.Status = "R";
                    UpdateMilestoneRequirement(workRequest, workPacket, mreq);
                }
            }
            catch (HttpResponseException ex)
            {
                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][FAILED-]-failed to log to STORMS milestone requirement");
                Console.WriteLine("Http Status Code:" + ex.Response.StatusCode.ToString());
                Console.WriteLine("*************Http Response Error***************");

                foreach (var header in ex.Response.Headers)
                {
                    Console.WriteLine(header.Key + ", " + header.Value.ToList()[0]);
                }

                Console.WriteLine("*************Http Response Error***************");

                CreateRemedyTicket(workRequest, workPacket, ex);
            }
        }
        public void ProcessForestry(Models.DTO.WorkRequest workRequest, Models.DTO.WorkPacket workPacket, ForestryRequest forestry)
        {
            Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][BEGIN--]-sending Forestry Job to IBM MQ");

            try
            {
                var obj = Newtonsoft.Json.JsonConvert.SerializeObject(forestry);

                HttpResponseMessage htm = _forestryRequestor.Post(
                    new Uri(Properties.Settings.Default.MqApiUriHost + Properties.Settings.Default.MqApiUri),
                    forestry
                    );

                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][SUCCESS]-sent Forestry Job to IBM MQ");
            }
            catch (HttpResponseException ex)
            {
                AddStormsTracking(workRequest, workPacket, "FOBATCH", "FOCREATE", "Failed to create order in Forestry system");

                foreach (var header in ex.Response.Headers)
                {
                    Console.WriteLine(header.Key + ", " + header.Value.ToList()[0]);
                }

                CreateRemedyTicket(workRequest, workPacket, ex);
            }
        }
        private List <ValidationResult> ValidateWorkRequest(Models.DTO.WorkRequest workRequest)
        {
            var objectToValidate  = workRequest;
            var validationContext = new ValidationContext(objectToValidate);
            var validationResults = new List <ValidationResult>();
            var isValid           = Validator.TryValidateObject(objectToValidate, validationContext, validationResults, false);

            if (!isValid)
            {
                return(validationResults);
            }

            return(null);
        }
        public void ProcessWorkPacket(Forestry.Models.DTO.WorkPacket workPacket)
        {
            Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][BEGIN--]-processing...");

            Models.DTO.WorkRequest workRequest = null;

            try
            {
                //call managed work API to get all the data
                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][BEGIN--]-retrieving Managed Work Order data");
                workRequest = GetWorkRequestFromApi(workPacket);

                if (workRequest != null)
                {
                    //validate work request
                    Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][BEGIN--]-validating WorkRequest data");
                    List <ValidationResult> validationResults = ValidateWorkRequest(workRequest);

                    //process validation
                    if (validationResults == null || !validationResults.Any())
                    {
                        Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][SUCCESS]-valid WorkRequest data");
                        ValidationSuccess(workPacket, workRequest);
                    }
                    else
                    {
                        Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][SUCCESS]-invalid WorkRequest data");
                        ValidationInvalid(workPacket, workRequest, validationResults);
                    }
                }
                else
                {
                    Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "]" + " NOT FOUND");
                }
            }
            catch (Exception ex)
            {
                //add to tracking
                AddStormsTracking(workRequest, workPacket, "FOBATCH", "FODATCHK", "Failed to create order in Forestry system");

                //create IT Remedy Ticket
                CreateRemedyTicket(workRequest, workPacket, ex);

                Environment.ExitCode = 1;
            }
        }
        public void AddStormsTracking(Models.DTO.WorkRequest workRequest, Models.DTO.WorkPacket workPacket, string operatorId, string function, string typeOfChange)
        {
            try
            {
                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][BEGIN--]-adding to STORMS tracking audit log");

                string timeStamp = Convert.ToDateTime(DateTime.Now).ToString("dd-MMM-yy HH:mm:ss");

                HttpResponseMessage hrm = _workRequestTrackingRequestor.Post(
                    new Uri(BaseManagedWorkApiUri + ResolveCurlyBrackets(Properties.Settings.Default.ManagedWorkOrderApiResourse_WorkRequestTrackings, workRequest.Id.ToString())),
                    new Forestry.Models.DTO.WorkRequestTracking()
                {
                    District      = workRequest.District.Trim(),
                    Status        = workRequest.Status,
                    OperatorId    = operatorId,
                    WorkRequestId = Convert.ToInt64(workRequest.Id),
                    ChangeDate    = Convert.ToDateTime(timeStamp),
                    Function      = function,
                    TypeOfChange  = typeOfChange
                }
                    );

                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][SUCCESS]-added to STORMS tracking audit log");
            }
            catch (HttpResponseException ex)
            {
                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][FAILED-]-failed to log to STORMS tracking audit log");
                Console.WriteLine("*************Http Response Error***************");
                Console.WriteLine("Http Status Code:" + ex.Response.StatusCode.ToString());

                foreach (var header in ex.Response.Headers)
                {
                    Console.WriteLine(header.Key + ", " + header.Value.ToList()[0]);
                }

                Console.WriteLine("*************Http Response Error***************");

                CreateRemedyTicket(workRequest, workPacket, ex);
            }
        }
        public void AddStormsWorkQueue(Models.DTO.WorkRequest workRequest, Models.DTO.WorkPacket workPacket, string details)
        {
            //add to STORMS TWMIFEXCEPTIONCOND table.. then an existing STORMS process will automatically run to add it to STORMS
            try
            {
                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][BEGIN--]-logging invalid data to STORMS work queue");

                HttpResponseMessage hrm = _stormsWorkQueueRequestor.Post(
                    new Uri(BaseManagedWorkApiUri + ResolveCurlyBrackets(Properties.Settings.Default.ManagedWorkOrderApiResourse_IfExceptionConditions, workRequest.Id.ToString())),
                    new IFExceptionCond()
                {
                    CD_DIST            = workRequest.District,
                    CD_WR              = Convert.ToInt64(workRequest.Id),
                    DS_COND            = details,
                    ID_OPER            = workRequest.AssignedTo,
                    FG_ERROR           = "N",
                    TS_IFEXCEPTIONCOND = DateTime.Now,
                    CD_SEQ             = 0
                }
                    );

                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][SUCCESS]-logged invalid data to STORMS work queue");
            }
            catch (HttpResponseException ex)
            {
                Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][FAILED-]-failed to log to STORMS work queue");
                Console.WriteLine("Http Status Code:" + ex.Response.StatusCode.ToString());
                Console.WriteLine("*************Http Response Error***************");

                foreach (var header in ex.Response.Headers)
                {
                    Console.WriteLine(header.Key + ", " + header.Value.ToList()[0]);
                }

                Console.WriteLine("*************Http Response Error***************");

                CreateRemedyTicket(workRequest, workPacket, ex);
            }
        }
        public ForestryRequest MapToForestry(Models.DTO.WorkRequest workRequest, Models.DTO.WorkPacket workPacket)
        {
            Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][BEGIN--]-converting WorkRequest into Forestry Job");

            Forestry.Models.ForestryRequest forestry = new Forestry.Models.ForestryRequest();

            forestry.CorellationId = Guid.NewGuid().ToString();
            //REQUIRED
            forestry.Timestamp = DateTime.UtcNow.ToString("yyyy-MM-ddTHH:mm:ssZ");
            //REQUIRED
            forestry.Origin       = new CodeModel();
            forestry.Origin.Value = "STORMS";
            //REQUIRED
            forestry.Method = "POST";

            //REQUIRED
            forestry.Model    = new Models.Forestry();
            forestry.Model.Id = ((long)workRequest.Id).ToString();
            DateTime dateValue;

            if (DateTime.TryParse(workRequest.RequiredDate, out dateValue))
            {
                forestry.Model.WantedDate = DateTime.Parse(workRequest.RequiredDate).ToString("yyyy-MM-ddTHH:mm:ssZ");
            }
            forestry.Model.FinancialDetails          = new FinancialDetails();
            forestry.Model.FinancialDetails.IoNumber = Convert.ToInt32(workRequest.IoInstallation);

            forestry.Model.GeographicDetails      = new GeographicDetails();
            forestry.Model.GeographicDetails.Area = workRequest.CrewHeadquarter;

            forestry.Model.Type       = new Models.Type();
            forestry.Model.Type.Value = workRequest.JobType;

            forestry.Model.Contact              = new Contact();
            forestry.Model.Contact.Name         = workRequest.ContactName;
            forestry.Model.Contact.PhoneNumbers = new List <PhoneNumber>();
            long contactPhoneResult;

            forestry.Model.Contact.PhoneNumbers.Add(new PhoneNumber
            {
                Number    = (long.TryParse(workRequest.ContactPhone, out contactPhoneResult) == true) ? contactPhoneResult : 0,
                IsDefault = true,
            });

            if (workRequest.Customers != null && workRequest.Customers.Count > 0)
            {
                forestry.Model.Customer      = new Models.Customer();
                forestry.Model.Customer.Name = workRequest.Customers[0].Name;

                if (!string.IsNullOrEmpty(workRequest.Customers[0].Phones.Number))
                {
                    forestry.Model.Customer.PhoneNumbers = new List <PhoneNumber>();
                    long extentionRemoved = 0;
                    if (workRequest.Customers[0].Phones.Number.IndexOf(" ") > 0)
                    {
                        extentionRemoved =
                            Convert.ToInt64(
                                ((string)workRequest.Customers[0].Phones.Number).Substring(
                                    0,
                                    workRequest.Customers[0].Phones.Number.IndexOf(" ")
                                    )
                                );
                    }
                    else
                    {
                        extentionRemoved = Convert.ToInt64(workRequest.Customers[0].Phones.Number);
                    }

                    string extention = string.Empty;
                    if (workRequest.Customers[0].Phones.Number.IndexOf(" ") > 0)
                    {
                        extention =
                            ((string)workRequest.Customers[0].Phones.Number).Substring(
                                workRequest.Customers[0].Phones.Number.IndexOf(" "),
                                workRequest.Customers[0].Phones.Number.Length - workRequest.Customers[0].Phones.Number.IndexOf(" ")
                                );
                    }

                    forestry.Model.Customer.PhoneNumbers.Add(new PhoneNumber
                    {
                        Number                = extentionRemoved,
                        IsDefault             = true,
                        AdditionalInformation = extention
                    });
                }
            }

            forestry.Model.Location         = new Location();
            forestry.Model.Location.Address = new Models.Address();
            forestry.Model.Location.Address.StreetNumber  = workRequest.Address.StreetNumber != null ? workRequest.Address.StreetNumber : string.Empty;
            forestry.Model.Location.Address.StreetAddress = workRequest.Address.StreetPrefix != null ? workRequest.Address.StreetPrefix : string.Empty;
            forestry.Model.Location.Address.StreetAddress =
                workRequest.Address.StreetName != null
                    ? forestry.Model.Location.Address.StreetAddress + " " + workRequest.Address.StreetName
                    : forestry.Model.Location.Address.StreetAddress;
            forestry.Model.Location.Address.StreetAddress =
                workRequest.Address.StreetType != null
                    ? forestry.Model.Location.Address.StreetAddress + " " + workRequest.Address.StreetType
                    : forestry.Model.Location.Address.StreetAddress;
            forestry.Model.Location.Address.StreetAddress =
                workRequest.Address.StreetSuffix != null
                    ? forestry.Model.Location.Address.StreetAddress + " " + workRequest.Address.StreetSuffix
                    : forestry.Model.Location.Address.StreetAddress;
            forestry.Model.Location.Address.City             = workRequest.Address.City;
            forestry.Model.Location.Address.State            = workRequest.Address.State;
            forestry.Model.Location.Address.County           = workRequest.Address.County;
            forestry.Model.Location.Address.PostalCode       = workRequest.Address.Zip;
            forestry.Model.Location.Address.FormattedAddress = workRequest.Address.FreeFormat;

            forestry.Model.GeographicDetails             = new GeographicDetails();
            forestry.Model.GeographicDetails.XCoordinate = workRequest?.Geo?.XCoordinate;
            forestry.Model.GeographicDetails.YCoordinate = workRequest?.Geo?.YCoordinate;

            if (workRequest.Geo != null)
            {
                forestry.Model.GeographicDetails.Area = workRequest?.Geo?.Zone;
            }

            forestry.Model.Origin = new Origin();
            //REQUIRED
            forestry.Model.Origin.Company       = new Company();
            forestry.Model.Origin.Company.Value = "30";
            //REQUIRED
            forestry.Model.Origin.OriginOrderTimestamp = DateTime.Parse(workRequest.RequiredDate).ToString("yyyy-MM-ddTHH:mm:ssZ");
            //REQUIRED
            //forestry.Model.Origin.OriginSystem = "STORMS";
            forestry.Model.Origin.OriginSystem = GetOrigin(workRequest);

            //REQUIRED
            forestry.Model.Origin.OriginSystemId = ((long)workRequest.Id).ToString();

            if (workRequest.Premises != null && workRequest.Premises.Count > 0)
            {
                forestry.Model.Origin.PremiseId = workRequest.Premises[0].PremiseId;
            }

            if (workRequest.ExtraDetails != null)
            {
                forestry.Model.Origin.FeederNumber = workRequest.ExtraDetails.FeederId;
                forestry.Model.Origin.Voltage      = workRequest.ExtraDetails.ServiceVoltageCode;
            }

            if (workRequest.Remarks != null && workRequest.Remarks.Count > 0)
            {
                foreach (var item in workRequest.Remarks)
                {
                    forestry.Model.Comments += item.Type + " " + item.RemarkText;
                }
            }

            Console.WriteLine("[WR:" + workPacket.WorkRequestId + " " + "WP:" + workPacket.WorkPacketId + "][SUCCESS]-converted WorkRequest into Forestry Job");

            return(forestry);
        }