public static void SetCopiedFrom(Quote quote, Submission submission) 
        {
			if (quote.CorrelationToken.HasValue)
			{
				var masters = submission.Options
				                        .SelectMany(o => o.OptionVersions)
				                        .SelectMany(ov => ov.Quotes)
				                        .Where(q => (q.CorrelationToken.Value == quote.CorrelationToken.Value &&
				                                     q.IsSubscribeMaster == true))
				                        .ToList();
                
				if (masters.Count == 1)
                {
					quote.CopiedFromQuoteId = masters[0].Id;
					quote.SubscribeReference = masters[0].SubscribeReference;
					quote.SubscribeTimestamp = masters[0].SubscribeTimestamp.Value;
                }
                else
                {
                    //  We've got either more than one or no master for the quote.
                    throw new ApplicationException("Couldn't find master quote.");
                }
            }
            else
            {
                //  The non-master quote doesn't have a correlation token
                throw new ApplicationException("Couldn't find master quote.");
            }
        }
        public static Quote CopyQuote(Quote q)
        {
            return new Quote
            {
                Id = q.Id,
                AccountYear = q.AccountYear,
                BenchmarkPremium = q.BenchmarkPremium,
                COBId = q.COBId,
                Comment = q.Comment,
                CopiedFromQuoteId = q.CopiedFromQuoteId,
                CorrelationToken = q.CorrelationToken,
                CreatedBy = q.CreatedBy,
                CreatedOn = q.CreatedOn,
                Currency = q.Currency,
                DeclinatureComments = q.DeclinatureComments,
                DeclinatureReason = q.DeclinatureReason,
                EntryStatus = q.EntryStatus,
                ExcessAmount = q.ExcessAmount,
                ExcessCCY = q.ExcessCCY,
                ExpiryDate = q.ExpiryDate,
                FacilityRef = q.FacilityRef,
                InceptionDate = q.InceptionDate,
                IsSubscribeMaster = q.IsSubscribeMaster,
                ModifiedBy = q.ModifiedBy,
                ModifiedOn = q.ModifiedOn,
                LimitCCY = q.LimitCCY,
                LimitAmount = q.LimitAmount,
                MOA = q.MOA,
                OptionId = q.OptionId,
                OptionVersion = q.OptionVersion,
                OriginatingOfficeId = q.OriginatingOfficeId,
                PolicyType = q.PolicyType,
                QuoteExpiryDate = q.QuoteExpiryDate,
                QuotedPremium = q.QuotedPremium,
                RenPolId = q.RenPolId,
                SubmissionStatus = q.SubmissionStatus,
                SubscribeReference = q.SubscribeReference,
                SubscribeTimestamp = q.SubscribeTimestamp,
                TechnicalPremium = q.TechnicalPremium,
                TechnicalPricingBindStatus = q.TechnicalPricingBindStatus,
                TechnicalPricingMethod = q.TechnicalPricingMethod,
                TechnicalPricingPremiumPctgAmt = q.TechnicalPricingPremiumPctgAmt,
                Timestamp = q.Timestamp,
                VersionNumber = q.VersionNumber,
                Description = q.Description,

                RenewalRate = q.RenewalRate,
                RenewalConditions = q.RenewalConditions,
                RenewalDeductibles = q.RenewalDeductibles,
                RenewalExposure = q.RenewalExposure,
                RenewalBase = q.RenewalBase,
                RenewalFull = q.RenewalFull
            };
        }
        public static UpdatePolicyResponse UpdateSubscribeRecord(Quote q, Submission s, ILogHandler logHandler, IPolicyService subsribeService)
        {
            var insuredList = new InsuredCollection();
            if (s.AdditionalInsuredList != null)
            {
                insuredList.AddRange(s.AdditionalInsuredList
                                      .Select(insured => new Insured
                                      {
                                          AddlInsdId = insured.InsuredId,
                                          AddlInsdNm = insured.InsuredId == 0 ? insured.InsuredName : null,
                                          AddlInsdTy = insured.InsuredType
                                      }));
            }

            var policyContract = new PolicyContract
            {
                AccYr = q.AccountYear.ToString(),
                BenchPrm = q.BenchmarkPremium,
                BindSt = q.TechnicalPricingBindStatus,
                BkrNo = "???", // TODO - not referenced in CreateQuote sp
                BkrPsu = s.BrokerPseudonym, // No validation carried out in service validation sp
                BkrSeqId = s.BrokerSequenceId,
                Brokerage = s.Brokerage,
                COB = q.COBId,
                DeclineReason = q.DeclinatureReason,
                DOM = s.Domicile,
                EntSt = q.EntryStatus,
                ExpyDt = (q.ExpiryDate.HasValue) ? q.ExpiryDate.Value.ToString("yyyyMMdd") : null,
                ExsAmt = q.ExcessAmount,
                FacyPolId = q.FacilityRef,
                LdrNo = s.LeaderNo,
                Ldr = s.Leader,
                IncpDt = (q.InceptionDate.HasValue) ? q.InceptionDate.Value.ToString("yyyyMMdd") : null,
                InsdId = s.InsuredId,
                InsdNm = s.InsuredName,
                AddlInsuredCollection = insuredList,
                LmtAmt = q.LimitAmount,
                LmtCcy = q.LimitCCY,
                MOA = q.MOA,
                OrigOff = q.OriginatingOfficeId,
                PolTy = q.PolicyType,
                PricingCcy = q.Currency,
                RenPolId = q.RenPolId,
                Status = q.SubmissionStatus,
                TechPrm = q.TechnicalPremium,
                UnitPsu = "AGY",
                Uwr = s.UnderwriterCode,
                ExsCcy = q.ExcessCCY,
                Method = q.TechnicalPricingMethod,
                NonLonBkr = s.NonLondonBrokerCode,
                PctgAmt = q.TechnicalPricingPremiumPctgAmt,
                SettDueDt = q.QuoteExpiryDate.ToString("yyyyMMdd"),
                TechPmTy = "TechPm", // TODO - not referenced in CreateQuote sp
                PolDsc = q.Description,

                //  These are the fields required for edit only
                TimeStamp = q.SubscribeTimestamp,
                PolId = q.SubscribeReference,

                CtcNm = (string.IsNullOrEmpty(s.BrokerContact)) ? s.NewBrokerContactName : s.BrokerContact,
                CtcTelNo = s.NewBrokerContactPhoneNumber,
                CtcEmail = s.NewBrokerContactEmail
            };

            if (q.RenewalRate.HasValue) policyContract.RenewalRate = q.RenewalRate;
            if (q.RenewalConditions.HasValue) policyContract.RenewalConditions = q.RenewalConditions;
            if (q.RenewalDeductibles.HasValue) policyContract.RenewalDeductibles = q.RenewalDeductibles;
            if (q.RenewalExposure.HasValue) policyContract.RenewalExposurePctg = q.RenewalExposure;
            if (q.RenewalBase.HasValue) policyContract.RenewalBase = q.RenewalBase;
            if (q.RenewalFull.HasValue) policyContract.RenewalFull = q.RenewalFull;

            var updateResp = subsribeService.UpdatePolicy(new UpdatePolicyRequest
            {
                objPolicyContract = policyContract
            });
          
            if (updateResp.UpdatePolicyResult.ErrorInfo == null)
            {
                
                    var doc = new XmlDocument();

                    doc.LoadXml(updateResp.UpdatePolicyResult.OutputXml);

                    q.SubscribeTimestamp = long.Parse(doc.GetElementsByTagName("TimeStamp")[0].InnerText);

                    q.FacilityRef = string.IsNullOrEmpty(doc.GetElementsByTagName("NewFacyPolId")[0].InnerText)
                                        ? q.FacilityRef
                                        : doc.GetElementsByTagName("NewFacyPolId")[0].InnerText;
               
               
            }
            else
            {
                logHandler.WriteLog(updateResp.UpdatePolicyResult.ErrorInfo.ErrorXML, LogSeverity.Error,
                                     LogCategory.BusinessComponent);

                throw new ApplicationException(
                    string.IsNullOrEmpty(updateResp.UpdatePolicyResult.ErrorInfo.Description)
                        ? ParseDetailedError(updateResp.UpdatePolicyResult.ErrorInfo.DetailedDescription)
                        : updateResp.UpdatePolicyResult.ErrorInfo.Description);
            }

            return updateResp;
        }
	    public static void SynchroniseQuote(Quote q, PolicyContract polAsSubscribe)
	    {
		    q.TechnicalPricingMethod = polAsSubscribe.Method;
            
		    q.AccountYear = int.Parse(polAsSubscribe.AccYr);
		    q.BenchmarkPremium = polAsSubscribe.BenchPrm.HasValue ? polAsSubscribe.BenchPrm.Value : 0;
		    q.TechnicalPricingBindStatus = polAsSubscribe.BindSt;
		    q.COBId = polAsSubscribe.COB;
		    q.Currency = polAsSubscribe.PricingCcy;
		    q.DeclinatureReason = polAsSubscribe.DeclineReason;
		    q.EntryStatus = polAsSubscribe.EntSt;

		    q.ExpiryDate = polAsSubscribe.ExpyDt != null
			                   ? (DateTime?)DateTime.ParseExact(polAsSubscribe.ExpyDt, "yyyyMMdd",
			                                                    CultureInfo.InvariantCulture,
			                                                    DateTimeStyles.None)
			                   : null;

		    q.InceptionDate = polAsSubscribe.IncpDt != null
			                      ? (DateTime?)DateTime.ParseExact(polAsSubscribe.IncpDt, "yyyyMMdd",
			                                                       CultureInfo.InvariantCulture,
			                                                       DateTimeStyles.None)
								  : null;

			// TODO: Why is QuoteExpiryDate nullable ?
			q.QuoteExpiryDate = DateTime.ParseExact(polAsSubscribe.SettDueDt, "yyyyMMdd",
													CultureInfo.InvariantCulture,
													DateTimeStyles.None);

		    q.ExcessAmount = polAsSubscribe.ExsAmt.HasValue ? polAsSubscribe.ExsAmt.Value : 0;
		    q.ExcessCCY = polAsSubscribe.ExsCcy;
		    q.FacilityRef = polAsSubscribe.FacyPolId;
		    q.LimitAmount = polAsSubscribe.LmtAmt.HasValue ? polAsSubscribe.LmtAmt.Value : 0;
		    q.LimitCCY = polAsSubscribe.LmtCcy;
		    q.MOA = polAsSubscribe.MOA;
		    q.OriginatingOfficeId = polAsSubscribe.OrigOff;
		    q.PolicyType = polAsSubscribe.PolTy;
		    q.RenPolId = polAsSubscribe.RenPolId;
		    q.SubmissionStatus = polAsSubscribe.Status;
		    q.SubscribeTimestamp = polAsSubscribe.TimeStamp.HasValue ? polAsSubscribe.TimeStamp.Value : 0;
		    q.TechnicalPremium = polAsSubscribe.TechPrm.HasValue ? polAsSubscribe.TechPrm.Value : 0;
		    q.TechnicalPricingMethod = polAsSubscribe.Method;
		    q.TechnicalPricingPremiumPctgAmt = polAsSubscribe.PctgAmt;
	        q.Description = polAsSubscribe.PolDsc;
	    }
        public static bool QuoteValuesMatchSubscribePolicy(PolicyContract polAsSubscribe, Quote q, Submission s)
        {
	        //  Is this most efficient, or are separate if statements better?
	        return polAsSubscribe.AccYr == q.AccountYear.ToString()
	               && (polAsSubscribe.BenchPrm.HasValue
		                ? polAsSubscribe.BenchPrm.Value == q.BenchmarkPremium
		                : q.BenchmarkPremium == 0)
	               && polAsSubscribe.BindSt == q.TechnicalPricingBindStatus
	               //&& polAsSubscribe.BkrNo == s.?        // Should we bother checking? not used by service
	               && polAsSubscribe.BkrPsu == s.BrokerPseudonym
	               && polAsSubscribe.BkrSeqId == s.BrokerSequenceId
	               &&
	               (polAsSubscribe.Brokerage.HasValue ? polAsSubscribe.Brokerage.Value == s.Brokerage : s.Brokerage == 0)
	               && polAsSubscribe.COB == q.COBId
	               && polAsSubscribe.CtcNm == s.BrokerContact
	               && polAsSubscribe.DeclineReason == q.DeclinatureReason
	               && polAsSubscribe.DOM == s.Domicile
	               && polAsSubscribe.EntSt == q.EntryStatus

	               && (q.ExpiryDate.HasValue
		                ? polAsSubscribe.ExpyDt == q.ExpiryDate.Value.ToString("yyyyMMdd")
						: string.IsNullOrEmpty(polAsSubscribe.ExpyDt))
				   && (q.InceptionDate.HasValue
						? polAsSubscribe.IncpDt == q.InceptionDate.Value.ToString("yyyyMMdd")
						: string.IsNullOrEmpty(polAsSubscribe.IncpDt))
				   && (polAsSubscribe.SettDueDt == q.QuoteExpiryDate.ToString("yyyyMMdd"))

	               && (polAsSubscribe.ExsAmt.HasValue ? polAsSubscribe.ExsAmt == q.ExcessAmount : q.ExcessAmount == 0)
	               && polAsSubscribe.ExsCcy == q.ExcessCCY
	               && polAsSubscribe.FacyPolId == q.FacilityRef
	               && polAsSubscribe.InsdId == s.InsuredId
	               && polAsSubscribe.InsdNm == s.InsuredName
	               && (polAsSubscribe.LmtAmt.HasValue ? polAsSubscribe.LmtAmt.Value == q.LimitAmount : q.LimitAmount == 0)
	               && polAsSubscribe.LmtCcy == q.LimitCCY
	               && polAsSubscribe.Method == q.TechnicalPricingMethod
	               && polAsSubscribe.MOA == q.MOA
	               && polAsSubscribe.NonLonBkr == s.NonLondonBrokerCode
	               && polAsSubscribe.OrigOff == q.OriginatingOfficeId
	               && polAsSubscribe.PctgAmt == q.TechnicalPricingPremiumPctgAmt
	               && polAsSubscribe.PolId == q.SubscribeReference
	               && polAsSubscribe.PolTy == q.PolicyType
	               && polAsSubscribe.PricingCcy == q.Currency
	               && polAsSubscribe.RenPolId == q.RenPolId
	               && polAsSubscribe.Status == q.SubmissionStatus
	               //&& polAsSubscribe.TechPmTy == "TechPm"
	               && (polAsSubscribe.TechPrm.HasValue
		                ? polAsSubscribe.TechPrm.Value == q.TechnicalPremium
		                : q.TechnicalPremium == 0)
	               && polAsSubscribe.Uwr == s.UnderwriterCode;
        }
	    public static void SynchroniseQuote(Quote q, PolicyContract polAsSubscribe)
        {
            // Fields used to determine if submission quote is the same as subscribe policy
            q.AccountYear = int.Parse(polAsSubscribe.AccYr);
            q.TechnicalPricingBindStatus = polAsSubscribe.BindSt;
            q.BrokerPseudonym = polAsSubscribe.BkrPsu;
            q.BrokerSequenceId = polAsSubscribe.BkrSeqId;
            q.COBId = polAsSubscribe.COB;
            q.BrokerContact = polAsSubscribe.CtcNm;
            q.DeclinatureReason = polAsSubscribe.DeclineReason;
            q.Domicile = polAsSubscribe.DOM;
            q.EntryStatus = polAsSubscribe.EntSt;
            q.ExcessCCY = polAsSubscribe.ExsCcy;
            q.FacilityRef = polAsSubscribe.FacyPolId;
            q.InsuredId = polAsSubscribe.InsdId;
            q.InsuredName = polAsSubscribe.InsdNm;
            q.LimitCCY = polAsSubscribe.LmtCcy;
            q.TechnicalPricingMethod = polAsSubscribe.Method;
            q.MOA = polAsSubscribe.MOA;
            q.FSAClass = polAsSubscribe.FSA_Class;
            q.AggsRequired = polAsSubscribe.AggsReqd;
            q.WordingRequired = polAsSubscribe.WordReqd;
            q.NonLondonBrokerCode = polAsSubscribe.NonLonBkr;
            q.OriginatingOfficeId = polAsSubscribe.OrigOff;
            q.TechnicalPricingPremiumPctgAmt = polAsSubscribe.PctgAmt;
            q.SubscribeReference = polAsSubscribe.PolId;
            q.PolicyType = polAsSubscribe.PolTy;
            q.Currency = polAsSubscribe.PricingCcy; // BUG: "???" problem in quotesheet
            q.RenPolId = polAsSubscribe.RenPolId;
            q.SubmissionStatus = polAsSubscribe.Status;
            q.UnderwriterCode = polAsSubscribe.Uwr;
            q.LeaderNo = polAsSubscribe.LdrNo;
            q.Leader = polAsSubscribe.Ldr;
            q.BenchmarkPremium = polAsSubscribe.BenchPrm.HasValue ? polAsSubscribe.BenchPrm.Value : 0;
            q.TechnicalPremium = polAsSubscribe.TechPrm.HasValue ? polAsSubscribe.TechPrm.Value : 0;
            q.Brokerage = polAsSubscribe.Brokerage;
            q.ExpiryDate = polAsSubscribe.ExpyDt != null
                               ? (DateTime?)DateTime.ParseExact(polAsSubscribe.ExpyDt, "yyyyMMdd",
                                                                CultureInfo.InvariantCulture,
                                                                DateTimeStyles.None)
                               : null;
            q.InceptionDate = polAsSubscribe.IncpDt != null
                                  ? (DateTime?)DateTime.ParseExact(polAsSubscribe.IncpDt, "yyyyMMdd",
                                                                   CultureInfo.InvariantCulture,
                                                                   DateTimeStyles.None)
                                  : null;
            q.ExcessAmount = polAsSubscribe.ExsAmt.HasValue ? polAsSubscribe.ExsAmt.Value : 0;
            q.LimitAmount = polAsSubscribe.LmtAmt.HasValue ? polAsSubscribe.LmtAmt.Value : 0;
            // end of fields used to compare submission quote vs subscribe policy 

            if (q.AdditionalInsuredList != null)
	        {
            //Remove the one deleted in subscribe
                var removeListAdditionalInsureds =
                    q.AdditionalInsuredList.Where(
	                    additionalInsured =>
	                    polAsSubscribe.AddlInsuredCollection.Where(i => i.AddlInsdTy != "Insured")
	                                  .All(psai => psai.AddlInsdId != additionalInsured.InsuredId)).ToList();
                foreach (var additionalInsured in removeListAdditionalInsureds)
                {
                    q.AdditionalInsuredList.Remove(additionalInsured);                    
                }
                //sync old ones
                foreach (var additionalInsured in q.AdditionalInsuredList)
                {
                    if (polAsSubscribe.AddlInsuredCollection.Where(i => i.AddlInsdTy != "Insured")
                        .All(psai => psai.AddlInsdId == additionalInsured.InsuredId))
                    {
                        var polsubsAdditionalInsured =
                            polAsSubscribe.AddlInsuredCollection.Single(
                            i => i.AddlInsdTy != "Insured" && i.AddlInsdId == additionalInsured.InsuredId);
                        additionalInsured.InsuredName = polsubsAdditionalInsured.AddlInsdNm;
                        additionalInsured.InsuredType = polsubsAdditionalInsured.AddlInsdTy;
                    }
                }
                //Add new ones
                foreach (
                    var polAssubsAdditionalInsured in
                    polAsSubscribe.AddlInsuredCollection.Where(i => i.AddlInsdTy != "Insured")
                    .Where(
                    polsubsAdditionalInsured =>
                        q.AdditionalInsuredList.All(
                        ai => ai.InsuredId != polsubsAdditionalInsured.AddlInsdId)))
                        {
                            q.AdditionalInsuredList.Add(new AdditionalInsured
                            {
                                InsuredId = polAssubsAdditionalInsured.AddlInsdId,
                                InsuredName = polAssubsAdditionalInsured.AddlInsdNm,
                                InsuredType = polAssubsAdditionalInsured.AddlInsdTy
                            });
                        }
            }     
            // Note: Bug 1631 - do not sync back the SDD... 
            //q.QuoteExpiryDate = DateTime.ParseExact(polAsSubscribe.SettDueDt, "yyyyMMdd",
            //                                        CultureInfo.InvariantCulture,
            //                                        DateTimeStyles.None);

		    q.SubscribeTimestamp = polAsSubscribe.TimeStamp.HasValue ? polAsSubscribe.TimeStamp.Value : 0;
		    q.TechnicalPricingMethod = polAsSubscribe.Method;
	        q.Description = polAsSubscribe.PolDsc;

	        q.RenewalRate = polAsSubscribe.RenewalRate;
	        q.RenewalConditions = polAsSubscribe.RenewalConditions;
	        q.RenewalDeductibles = polAsSubscribe.RenewalDeductibles;
	        q.RenewalExposure = polAsSubscribe.RenewalExposurePctg;
	        q.RenewalBase = polAsSubscribe.RenewalBase;
	        q.RenewalFull = polAsSubscribe.RenewalFull;
	    }
        public static bool QuoteValuesMatchSubscribePolicy(PolicyContract polAsSubscribe, Quote q, Submission s)
        {
	        //  Is this most efficient, or are separate if statements better?
            // For debugging this has been split out, it is hard to debug if all one line of && evaluations
            var retVal = true;
            if (polAsSubscribe.AccYr != q.AccountYear.ToString())
                retVal = false;
            else if (polAsSubscribe.BindSt != q.TechnicalPricingBindStatus)
                retVal = false;
            else if (polAsSubscribe.BkrPsu != q.BrokerPseudonym)
                retVal = false;
            else if (polAsSubscribe.BkrSeqId != q.BrokerSequenceId)
                retVal = false;
            else if (polAsSubscribe.COB != q.COBId)
                retVal = false;
            else if (polAsSubscribe.CtcNm != q.BrokerContact)
                retVal = false;
            else if (polAsSubscribe.DeclineReason != q.DeclinatureReason)
                retVal = false;
            else if (polAsSubscribe.DOM != q.Domicile)
                retVal = false;
            else if (polAsSubscribe.EntSt != q.EntryStatus)
                retVal = false;
            else if (polAsSubscribe.ExsCcy != q.ExcessCCY)
                retVal = false;
            else if (polAsSubscribe.FacyPolId != q.FacilityRef)
                retVal = false;
            else if (polAsSubscribe.InsdId != q.InsuredId)
                retVal = false;
            else if (polAsSubscribe.InsdNm != q.InsuredName)
                retVal = false;
            else if (polAsSubscribe.LmtCcy != q.LimitCCY)
                retVal = false;
            else if (polAsSubscribe.Method != q.TechnicalPricingMethod)
                retVal = false;
            else if (polAsSubscribe.MOA != q.MOA)
                retVal = false;
            else if (polAsSubscribe.FSA_Class != q.FSAClass)
                retVal = false;
            else if (polAsSubscribe.AggsReqd != q.AggsRequired)
                retVal = false;
            else if (polAsSubscribe.WordReqd != q.WordingRequired)
                retVal = false;
            else if (polAsSubscribe.NonLonBkr != q.NonLondonBrokerCode)
                retVal = false;
            else if (polAsSubscribe.OrigOff != q.OriginatingOfficeId)
                retVal = false;
            else if (polAsSubscribe.PctgAmt != q.TechnicalPricingPremiumPctgAmt)
                retVal = false;
            else if (polAsSubscribe.PolId != q.SubscribeReference)
                retVal = false;
            else if (polAsSubscribe.PolTy != q.PolicyType)
                retVal = false;
            else if (polAsSubscribe.PricingCcy != q.Currency)
                retVal = false;
            else if (polAsSubscribe.RenPolId != q.RenPolId)
                retVal = false;
            else if (polAsSubscribe.Status != q.SubmissionStatus)
                retVal = false;
            else if (polAsSubscribe.Uwr != q.UnderwriterCode)
                retVal = false;
            else if ((polAsSubscribe.BenchPrm.HasValue) && (polAsSubscribe.BenchPrm.Value != q.BenchmarkPremium))
                retVal = false;
            else if ((!polAsSubscribe.BenchPrm.HasValue) && (q.BenchmarkPremium != 0))
                retVal = false;
            else if ((polAsSubscribe.TechPrm.HasValue) && (polAsSubscribe.TechPrm.Value != q.TechnicalPremium))
                retVal = false;
            else if ((!polAsSubscribe.TechPrm.HasValue) && (q.TechnicalPremium != 0))
                retVal = false;
            else if ((polAsSubscribe.Brokerage.HasValue) && (polAsSubscribe.Brokerage.Value != q.Brokerage))
                retVal = false;
            else if ((!polAsSubscribe.Brokerage.HasValue) && (q.Brokerage.HasValue) && (q.Brokerage != 0))
                retVal = false;
            else if ((q.ExpiryDate.HasValue) && (polAsSubscribe.ExpyDt != q.ExpiryDate.Value.ToString("yyyyMMdd")))
                retVal = false;
            else if ((!q.ExpiryDate.HasValue) && (!string.IsNullOrEmpty(polAsSubscribe.ExpyDt)))
                retVal = false;
            else if ((q.InceptionDate.HasValue) && (polAsSubscribe.IncpDt != q.InceptionDate.Value.ToString("yyyyMMdd")))
                retVal = false;
            else if ((!q.InceptionDate.HasValue) && (!string.IsNullOrEmpty(polAsSubscribe.IncpDt)))
                retVal = false;
            else if (q.QuoteExpiryDate.HasValue && polAsSubscribe.SettDueDt != SetSettlementDueDate(q.QuoteExpiryDate.Value, s.ExpiryDateOffset, q.InceptionDate))
                retVal = false;
            else if ((polAsSubscribe.ExsAmt.HasValue) && (polAsSubscribe.ExsAmt.Value != q.ExcessAmount))
                retVal = false;
            else if ((!polAsSubscribe.ExsAmt.HasValue) && (q.ExcessAmount != 0))
                retVal = false;
            else if ((polAsSubscribe.LmtAmt.HasValue) && (polAsSubscribe.LmtAmt.Value != q.LimitAmount))
                retVal = false;
            else if ((!polAsSubscribe.LmtAmt.HasValue) && (q.LimitAmount != 0))
                retVal = false;
            return retVal;
        }
        private static void SyncQuoteCreateAndUpdate(Submission s, Quote q, IPolicyService subsribeService)
        {
            var response = subsribeService.GetReference(new GetReferenceRequest
                {
                    strPolId = q.SubscribeReference
                });

            var errorInfo = response.GetReferenceResult.ErrorInfo;
            var outputXml = response.GetReferenceResult.OutputXml;

            if (errorInfo == null)
            {
                var policyCon = Utility.XmlDeserializeFromString<PolicyContract>(outputXml);
                SynchroniseSubmission(s, policyCon);
                SynchroniseQuote(q, policyCon);
            }
        }
        public static CreateQuoteResponse CreateSubscribeRecord(Quote q, Submission s, ILogHandler logHandler, IPolicyService subsribeService)
        {
            var insuredList = new InsuredCollection();
            if (q.AdditionalInsuredList != null)
            {
                insuredList.AddRange(q.AdditionalInsuredList
                                      .Select(insured => new Insured
                                          {
                                              AddlInsdId = insured.InsuredId,
                                              AddlInsdNm = insured.InsuredId == 0 ? insured.InsuredName : null,
                                              AddlInsdTy = insured.InsuredType
                                          }));
            }

            var policyContract = new PolicyContract
                {
                    AccYr = q.AccountYear.ToString(),
                    BenchPrm = q.BenchmarkPremium,
                    BindSt = q.TechnicalPricingBindStatus,
                    BkrNo = "???", // TODO - not referenced in CreateQuote sp
                    BkrPsu = q.BrokerPseudonym, // No validation carried out in service validation sp
                    BkrSeqId = q.BrokerSequenceId,
                    Brokerage = q.Brokerage,
                    COB = q.COBId,
                    DeclineReason = q.DeclinatureReason,
                    DOM = q.Domicile,
                    EntSt = q.EntryStatus,
                    ExpyDt = (q.ExpiryDate.HasValue) ? q.ExpiryDate.Value.ToString("yyyyMMdd") : null,
                    ExsAmt = q.ExcessAmount,
                    FacyPolId = (String.IsNullOrEmpty(q.RenPolId) ? q.FacilityRef : String.Empty),
                    LdrNo = q.LeaderNo,
                    Ldr = q.Leader,
                    IncpDt = (q.InceptionDate.HasValue) ? q.InceptionDate.Value.ToString("yyyyMMdd") : null,
                    InsdId = q.InsuredId,
                    InsdNm = q.InsuredName,
                    AddlInsuredCollection = insuredList,
                    LmtAmt = q.LimitAmount,
                    LmtCcy = q.LimitCCY,
                    MOA = q.MOA,
                    OrigOff = q.OriginatingOfficeId,
                    PolTy = q.PolicyType,
                    PricingCcy = q.Currency,
                    RenPolId = q.RenPolId,
                    Status = q.SubmissionStatus,
                    TechPrm = q.TechnicalPremium,
                    UnitPsu = "AGY",
                    Uwr = q.UnderwriterCode,
                    ExsCcy = q.ExcessCCY,
                    Method = q.TechnicalPricingMethod,
                    NonLonBkr = q.NonLondonBrokerCode,
                    PctgAmt = q.TechnicalPricingPremiumPctgAmt,
                    
                    TechPmTy = "TechPm", // TODO - not referenced in CreateQuote sp
                    PolDsc = q.Description,

                    //  These are the fields required for edit only
                    TimeStamp = q.SubscribeTimestamp,
                    PolId = q.SubscribeReference,  

                    // PolAnlyCd
                    // TODO: Update this win value from form.
                    WordReqd = (string.IsNullOrEmpty(q.WordingRequired)) ? "" : q.WordingRequired,
                    AggsReqd = (string.IsNullOrEmpty(q.AggsRequired)) ? "" : q.AggsRequired,
                    FSA_Class = (string.IsNullOrEmpty(q.FSAClass)) ? "" : q.FSAClass,

					CtcNm = q.BrokerContact,
                    //CtcTelNo = q.BrokerContactPhone,
                    //CtcEmail = q.BrokerContactEmail
                };
            if (q.QuoteExpiryDate != null)
                policyContract.SettDueDt = SetSettlementDueDate(q.QuoteExpiryDate.Value, s.ExpiryDateOffset, q.InceptionDate);
            if (!string.IsNullOrEmpty(q.BrokerContactPhone)) policyContract.CtcTelNo = q.BrokerContactPhone;
            if (!string.IsNullOrEmpty(q.BrokerContactEmail)) policyContract.CtcEmail = q.BrokerContactEmail;

            if (q.RenewalRate.HasValue) policyContract.RenewalRate = q.RenewalRate;
            if (q.RenewalConditions.HasValue) policyContract.RenewalConditions = q.RenewalConditions;
            if (q.RenewalDeductibles.HasValue) policyContract.RenewalDeductibles = q.RenewalDeductibles;
            if (q.RenewalExposure.HasValue) policyContract.RenewalExposurePctg = q.RenewalExposure;
            if (q.RenewalBase.HasValue) policyContract.RenewalBase = q.RenewalBase;
            if (q.RenewalFull.HasValue) policyContract.RenewalFull = q.RenewalFull;

            var createQuoteResponse = subsribeService.CreateQuote(new CreateQuoteRequest
                {
                    objPolicyContract = policyContract
                });

            if (createQuoteResponse.CreateQuoteResult.ErrorInfo == null)
            {
                q.SubscribeReference = createQuoteResponse.objInfoCollection.PolId;

                var doc = new XmlDocument();

                doc.LoadXml(createQuoteResponse.CreateQuoteResult.OutputXml);
                
				var subscribeTimestamp = default(long);

	            q.SubscribeTimestamp = long.TryParse(doc.GetElementsByTagName("TimeStamp")[0].InnerText,
	                                                 out subscribeTimestamp)
		                                   ? subscribeTimestamp
		                                   : 0;

                SyncQuoteCreateAndUpdate(s, q, subsribeService);
            }
            else
            {
                logHandler.WriteLog(createQuoteResponse.CreateQuoteResult.ErrorInfo.ErrorXML, LogSeverity.Error,
                                     LogCategory.BusinessComponent);

	            throw new ApplicationException(
		            string.IsNullOrEmpty(createQuoteResponse.CreateQuoteResult.ErrorInfo.Description)
			            ? ParseDetailedError(createQuoteResponse.CreateQuoteResult.ErrorInfo.DetailedDescription)
			            : createQuoteResponse.CreateQuoteResult.ErrorInfo.Description);
            }

            return createQuoteResponse;
        }
        public static void SetCopiedFrom(Quote quote, Submission submission) 
        {
			if (quote.CorrelationToken.HasValue)
			{
				var masters = submission.Options
				                        .SelectMany(o => o.OptionVersions)
				                        .SelectMany(ov => ov.Quotes)
				                        .Where(q => (q.CorrelationToken.Value == quote.CorrelationToken.Value &&
				                                     q.IsSubscribeMaster == true))
				                        .ToList();
                
				if (masters.Count == 1)
                {
					quote.CopiedFromQuoteId = masters[0].Id;
					quote.SubscribeReference = masters[0].SubscribeReference;
					quote.SubscribeTimestamp = masters[0].SubscribeTimestamp.Value;
                    
                    quote.AccountYear = masters[0].AccountYear;
                    quote.DeclinatureComments = masters[0].DeclinatureComments;
                    quote.DeclinatureReason = masters[0].DeclinatureReason;
                    quote.EntryStatus = masters[0].EntryStatus;
                    quote.ExpiryDate = masters[0].ExpiryDate;
                    quote.FacilityRef = masters[0].FacilityRef;
                    quote.InceptionDate = masters[0].InceptionDate;
                    quote.MOA = masters[0].MOA;
                    quote.OriginatingOffice = masters[0].OriginatingOffice;
                    quote.OriginatingOfficeId = masters[0].OriginatingOfficeId;
                    quote.PolicyType = masters[0].PolicyType;
                    quote.SubmissionStatus = masters[0].SubmissionStatus;

                    #region - Copied from Submission
                    quote.InsuredId = masters[0].InsuredId;
                    quote.InsuredName = masters[0].InsuredName;
                    //sync AdditionalInsured
                    if (quote.AdditionalInsuredList != null)
                    {
                        //Remove the one deleted in masters
                        var removeAdditionalInsuredList = new List<AdditionalInsured>();
                        quote.AdditionalInsuredList.Where(ai => !masters[0].AdditionalInsuredList.Any(mai => ai.InsuredId == mai.InsuredId)).ToList().ForEach(ai =>
                        {
                            if (ai.Id > 0) { ai.Id = -ai.Id; }
                            else{
                                removeAdditionalInsuredList.Add(ai);
                            }
                        });
                        removeAdditionalInsuredList.ForEach(rai => quote.AdditionalInsuredList.Remove(rai));
                        //sync old ones in masters
                        quote.AdditionalInsuredList.Where(ai => masters[0].AdditionalInsuredList.Any(mai => ai.InsuredId == mai.InsuredId)).ToList().ForEach(ai =>
                        {
                            var tempmai = masters[0].AdditionalInsuredList.Single(mai => ai.InsuredId == mai.InsuredId);
                            ai.InsuredId = tempmai.InsuredId;
                            ai.InsuredName = tempmai.InsuredName;
                            ai.InsuredType = tempmai.InsuredType;
                        });
                        //Add new ones in masters
                        masters[0].AdditionalInsuredList.Where(mai => !quote.AdditionalInsuredList.Any(ai => mai.InsuredId == ai.InsuredId)).ToList().ForEach(mai =>
                        {
                            quote.AdditionalInsuredList.Add(new AdditionalInsured
                            {
                                Id=0,
                                InsuredId = mai.InsuredId,
                                InsuredName = mai.InsuredName,
                                InsuredType = mai.InsuredType
                            });
                        });
                    }    

                    quote.BrokerSequenceId = masters[0].BrokerSequenceId;
                    quote.BrokerCode = masters[0].BrokerCode;
                    quote.BrokerPseudonym = masters[0].BrokerPseudonym;
                    quote.BrokerContact = masters[0].BrokerContact;
                    quote.NonLondonBrokerCode = masters[0].NonLondonBrokerCode;
                    quote.NonLondonBrokerName = masters[0].NonLondonBrokerName;
                    quote.UnderwriterCode = masters[0].UnderwriterCode;
                    quote.UnderwriterContactCode = masters[0].UnderwriterContactCode;
                    quote.QuotingOfficeId = masters[0].QuotingOfficeId;
                    quote.Domicile = masters[0].Domicile;
                    quote.LeaderNo = masters[0].LeaderNo;
                    quote.Leader = masters[0].Leader;
                    var brokerage = masters[0].Brokerage;
                    if (brokerage != null) quote.Brokerage = brokerage.Value;
                    #endregion - Copied from Submission

                }
                else
                {
                    //  We've got either more than one or no master for the quote.
                    throw new ApplicationException("Couldn't find master quote.");
                }
            }
            else
            {
                //  The non-master quote doesn't have a correlation token
                throw new ApplicationException("Couldn't find master quote.");
            }
        }
        public static void SeedData(IConsoleRepository context)
        {
            var domainPrefix = global::Validus.Console.Properties.Settings.Default.DomainPrefix;

            var AG = new COB { Id = "AG", Narrative = "Direct - Property - Construction", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            context.AddOrUpdate<COB>(AG);
            var AR = new COB { Id = "AR", Narrative = "Direct - Property - Rig", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            context.AddOrUpdate<COB>(AR);
            var AT = new COB { Id = "AT", Narrative = "Direct - Property - Hull", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            context.AddOrUpdate<COB>(AT);
            var CC = new COB { Id = "CC", Narrative = "Direct - Casualty - Construction", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            context.AddOrUpdate<COB>(CC);


            var c = new COB { Id = "CA", Narrative = "Cargo", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            context.AddOrUpdate<COB>(c);

            var c1 = new COB { Id = "AD", Narrative = "Direct - Property - Contingency", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            context.AddOrUpdate<COB>(c1);

            var userWriter1 = new Underwriter
            {
                Name = "Alex Colquhoun",
                Code = "JAC",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            context.AddOrUpdate<Underwriter>(userWriter1);

            var userWriter2 = new Underwriter
            {
                Name = "Alexandra Davies",
                Code = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            context.AddOrUpdate<Underwriter>(userWriter2);

            var underWriter = new User
            {
                DomainLogon = domainPrefix + @"\defaultunderwriter",
                IsActive = true,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now,
                UnderwriterCode = "AED"
            };
            context.AddOrUpdate<User>(underWriter);

            var quoteSheetPerson = new User
            {
                DomainLogon = domainPrefix + @"\quoteSheetPerson",
                IsActive = true,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now,
                UnderwriterCode = "AED"
            };
            context.AddOrUpdate<User>(quoteSheetPerson);

            // Note - SubmissionStatus - SUBMITTED, QUOTED, FIRM ORDER, DECLINED, WITHDRAWN, ADDL INFO REQST, FIRM ORDER REQST, OTHER OFFICE
            var masterQuote = new Quote
            {
                AccountYear = 2013,
                COB = c,
                COBId = c.Id,
                Currency = "USD",
                //<??>
                //QuoteCreated = DateTime.Now,
                //QuoteLastModified = DateTime.Now,
                //QuoteLastModifiedBy = underWriter,
                //QuoteCreatedBy = underWriter,
                SubscribeReference = "ADC118440A110006", //"AJH105451C12", // Policy Ref
                SubmissionStatus = "SUBMITTED",
                EntryStatus = "PARTIAL",
                PolicyType = "NONMARINE",
                TechnicalPricingMethod = "MODEL",
                QuotedPremium = 25000,
                FacilityRef = "ADC118440A11",
                IsSubscribeMaster = true,
                InceptionDate = DateTime.Now,
                ExpiryDate = DateTime.Now.AddYears(1),
                QuoteExpiryDate = DateTime.Now.AddDays(30),
                //OriginatingOfficeId = "LON",
                MOA = "FA",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var q = new Quote
            {
                AccountYear = 2013,
                COB = c,
                COBId = c.Id,
                Currency = "USD",
                //<??>
                //QuoteCreated = DateTime.Now,
                //QuoteLastModified = DateTime.Now,
                //QuoteLastModifiedBy = underWriter,
                //QuoteCreatedBy = underWriter,
                SubscribeReference = "ADC118440A110006",
                SubmissionStatus = "QUOTED",
                EntryStatus = "PARTIAL",
                PolicyType = "NONMARINE",
                TechnicalPricingMethod = "MODEL",
                QuotedPremium = 60000,
                FacilityRef = "ADC118440A11",
                IsSubscribeMaster = false,
                InceptionDate = DateTime.Now,
                ExpiryDate = DateTime.Now.AddYears(1),
                QuoteExpiryDate = DateTime.Now.AddDays(30),
                //OriginatingOfficeId = "LON",
                MOA = "FA",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var q3 = new Quote
            {
                AccountYear = 2013,
                COB = c,
                COBId = c.Id,
                Currency = "USD",
                //<??>
                //QuoteCreated = DateTime.Now,
                //QuoteLastModified = DateTime.Now,
                //QuoteLastModifiedBy = underWriter,
                //QuoteCreatedBy = underWriter,
                SubscribeReference = "AJE125510B12",
                SubmissionStatus = "DECLINED",
                EntryStatus = "PARTIAL",
                PolicyType = "NONMARINE",
                TechnicalPricingMethod = "MODEL",
                QuotedPremium = 360000,
                FacilityRef = "ADC118440A11",
                IsSubscribeMaster = false,
                InceptionDate = DateTime.Now,
                ExpiryDate = DateTime.Now.AddYears(1),
                QuoteExpiryDate = DateTime.Now.AddDays(30),
                //OriginatingOfficeId = "LON",
                MOA = "FA",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var q4master = new Quote
            {
                AccountYear = 2013,
                COB = c,
                COBId = c.Id,
                Currency = "USD",
                //<??>
                //QuoteCreated = DateTime.Now,
                //QuoteLastModified = DateTime.Now,
                //QuoteLastModifiedBy = underWriter,
                //QuoteCreatedBy = underWriter,
                SubscribeReference = "AJE125510B12",
                SubmissionStatus = "SUBMITTED",
                EntryStatus = "PARTIAL",
                PolicyType = "NONMARINE",
                TechnicalPricingMethod = "MODEL",
                QuotedPremium = 100000,
                FacilityRef = "ADC118440A11",
                IsSubscribeMaster = true,
                InceptionDate = DateTime.Now,
                ExpiryDate = DateTime.Now.AddYears(1),
                QuoteExpiryDate = DateTime.Now.AddDays(30),
                //OriginatingOfficeId = "LON",
                MOA = "FA",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var q5 = new Quote
            {
                AccountYear = 2013,
                COB = c,
                COBId = c.Id,
                Currency = "USD",
                //<??>
                //QuoteCreated = DateTime.Now,
                //QuoteLastModified = DateTime.Now,
                //QuoteLastModifiedBy = underWriter,
                //QuoteCreatedBy = underWriter,
                SubscribeReference = "AJE125510B12",
                SubmissionStatus = "SUBMITTED",
                EntryStatus = "PARTIAL",
                PolicyType = "NONMARINE",
                TechnicalPricingMethod = "MODEL",
                QuotedPremium = 1000,
                FacilityRef = "ADC118440A11",
                IsSubscribeMaster = false,
                InceptionDate = DateTime.Now,
                ExpiryDate = DateTime.Now.AddYears(1),
                QuoteExpiryDate = DateTime.Now.AddDays(30),
                // OriginatingOfficeId = "LON",
                MOA = "FA",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var q6master = new Quote
            {
                AccountYear = 2013,
                COB = c,
                COBId = c.Id,
                Currency = "USD",
                //<??>
                //QuoteCreated = DateTime.Now,
                //QuoteLastModified = DateTime.Now,
                //QuoteLastModifiedBy = underWriter,
                //QuoteCreatedBy = underWriter,
                SubscribeReference = "AJY087986D12",
                SubmissionStatus = "SUBMITTED",
                EntryStatus = "PARTIAL",
                PolicyType = "NONMARINE",
                TechnicalPricingMethod = "MODEL",
                QuotedPremium = 890000,
                FacilityRef = "ADC118440A11",
                IsSubscribeMaster = true,
                InceptionDate = DateTime.Now,
                ExpiryDate = DateTime.Now.AddYears(1),
                QuoteExpiryDate = DateTime.Now.AddDays(30),
                //OriginatingOfficeId = "LON",
                MOA = "FA",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var q7master = new Quote
            {
                AccountYear = 2013,
                COB = c,
                COBId = c.Id,
                Currency = "USD",
                //<??>
                //QuoteCreated = DateTime.Now,
                //QuoteLastModified = DateTime.Now,
                //QuoteLastModifiedBy = underWriter,
                //QuoteCreatedBy = underWriter,
                SubscribeReference = "AJJ144268A12",
                SubmissionStatus = "ADDL INFO REQST",
                EntryStatus = "PARTIAL",
                PolicyType = "NONMARINE",
                TechnicalPricingMethod = "MODEL",
                QuotedPremium = 39000,
                FacilityRef = "ADC118440A11",
                IsSubscribeMaster = true,
                InceptionDate = DateTime.Now,
                ExpiryDate = DateTime.Now.AddYears(1),
                QuoteExpiryDate = DateTime.Now.AddDays(30),
                //OriginatingOfficeId = "LON",
                MOA = "FA",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };


            var quoteSheet1 = new QuoteSheet { Title = "QS_1", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-1), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var quoteSheet2 = new QuoteSheet { Title = "QS_2", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-2), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var quoteSheet3 = new QuoteSheet { Title = "QS_2", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-3), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var quoteSheet4 = new QuoteSheet { Title = "QS_2", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-4), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var quoteSheet5 = new QuoteSheet { Title = "QS_2", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-5), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var quoteSheet6 = new QuoteSheet { Title = "QS_2", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-6), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var quoteSheet7 = new QuoteSheet { Title = "QS_2", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-7), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var quoteSheet8 = new QuoteSheet { Title = "QS_2", Guid = Guid.NewGuid(), IssuedBy = quoteSheetPerson, IssuedDate = DateTime.Now.AddDays(-8), ObjectStore = "Underwriting", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };

            var ov = new OptionVersion
            {
                Title = "Version 1",
                VersionNumber = 1,
                Quotes = new List<Quote> { q, masterQuote },
                QuoteSheets =
                    new List<QuoteSheet>
                                {
                                    quoteSheet1,
                                    quoteSheet2,
                                    quoteSheet3,
                                    quoteSheet4,
                                    quoteSheet5,
                                    quoteSheet6
                                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var ov2 = new OptionVersion
            {
                Title = "Version 2",
                VersionNumber = 2,
                Quotes = new List<Quote> { q3, q4master, q5 },
                QuoteSheets = new List<QuoteSheet> { quoteSheet7, quoteSheet8 },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };


            var ov3 = new OptionVersion
            {
                Title = "Version 3",
                VersionNumber = 1,
                Quotes = new List<Quote> { q6master },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };


            var ov4 = new OptionVersion
            {
                Title = "Version 4",
                VersionNumber = 1,
                Quotes = new List<Quote> { q7master },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var o1 = new Option
            {
                Title = "Option 1",
                Comments =
                    "There is a known issue with this technique where creating databases is not supported on SqlClient provider. Other providers may or may not support this functionality depending on implementation. In general, because of that it is recommended to use unwrapped connections when using DDL APIs (CreateDatabase, DeleteDatabase, DatabaseExists()) as demonstrated in the sample.",
                OptionVersions = new List<OptionVersion> { ov, ov2 },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var o2 = new Option
            {
                Title = "Option 2",
                Comments =
                    "In order to efficiently manage tracing for the application we need to create a central factory class which will create ObjectContext instances for us. This is the place where we will create tracing provider connection and use it to instantiate ObjectContext. Assuming our Object Context class is called MyContainer, the factory class will be called MyContainerFactory and will have a method called CreateContext, so the usage becomes:",
                OptionVersions = new List<OptionVersion> { ov3 },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var o3 = new Option
            {
                Title = "Option 3",
                Comments =
                    "Entity Framework/Code First feature released as part of Feature CTP 3 can work with any EF-enabled data provider. In addition to regular providers which target databases, it is possible to use wrapping providers which can add interesting functionality, such as caching and tracing. In this post I’m going to explain how to use EFTracingProvider to produce diagnostic trace of all SQL commands executed by EF in Code First.",
                OptionVersions = new List<OptionVersion> { ov4 },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var lon = new Office
            {
                Id = "LON",
                Name = "London",
                Title = "Talbot Underwriting Ltd",
                Footer = "Talbot Underwriting Ltd is Authorised by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority.",
                Address = new Address
                {
                    AddressLine1 = "60 Threadneedle Street",
                    AddressLine2 = "",
                    City = "London",
                    ZipPostalCode = "EC2R 8HP",
                    Country = "England",
                    CreatedBy = "InitialSetup",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "InitialSetup",
                    ModifiedOn = DateTime.Now
                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var mia = new Office
            {
                Id = "MIA",
                Name = "Miami",
                Title = "Validus Reaseguros, Inc.",
                Address = new Address
                {
                    AddressLine1 = "2601 South Bayshore Drive",
                    AddressLine2 = "Suite 1850, Coconut Grove",
                    City = "Miami",
                    StateProvinceRegion = "Florida",
                    ZipPostalCode = "33133",
                    Country = "U.S.A.",
                    CreatedBy = "InitialSetup",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "InitialSetup",
                    ModifiedOn = DateTime.Now
                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            var lab = new Office
            {
                Id = "LAB",
                Name = "Labuan",
                Title = "Talbot Risk Services (Labuan) Pte Ltd",
                Address = new Address
                {
                    AddressLine1 = "Brighton Place, Ground Floor,",
                    AddressLine2 = "No. U0215, Jalan Bahasa,",
                    City = "Labuan FT",
                    Country = "Malaysia",
                    ZipPostalCode = "87000",
                    CreatedBy = "InitialSetup",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "InitialSetup",
                    ModifiedOn = DateTime.Now
                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            var nyc = new Office
            {
                Id = "NYC",
                Name = "New York",
                Title = "Talbot Underwriting (US) Ltd. ",
                Address = new Address
                {
                    AddressLine1 = "48 Wall Street 17th Floor",
                    AddressLine2 = "",
                    Country = "USA",
                    StateProvinceRegion = "NY",
                    City = "New York",
                    ZipPostalCode = "10005",
                    CreatedBy = "InitialSetup",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "InitialSetup",
                    ModifiedOn = DateTime.Now
                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            var sng = new Office
            {
                Id = "SNG",
                Name = "Singapore",
                Title = "Talbot Risk Services Pte Ltd",
                Address = new Address
                {
                    AddressLine1 = "8 Marina View #14-01",
                    AddressLine2 = "Asia Square Tower 1",
                    City = "Singapore",
                    ZipPostalCode = "018960",
                    CreatedBy = "InitialSetup",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "InitialSetup",
                    ModifiedOn = DateTime.Now
                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            var dubai = new Office
            {
                Id = "DUB",
                Name = "Dubai",
                Title = "Talbot Underwriting (MENA) Ltd",
                Footer = "Underwriting Risk Services (Middle East) Ltd ('URSME') is authorised and regulated by the Dubai Financial Services Authority.",
                Address = new Address
                {
                    AddressLine1 = "Dubai International Financial Centre",
                    AddressLine2 = "Gate Village Building 10, Level 5",
                    City = "Dubai",
                    Country = "UAE",
                    ZipPostalCode = "PO Box 506809",
                    CreatedBy = "InitialSetup",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "InitialSetup",
                    ModifiedOn = DateTime.Now
                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            var usrl = new Office
            {
                Id = "URS",
                Name = "URSL",
                Title = "Talbot Underwriting Risk Services Ltd",
                Footer = "Talbot Underwriting Risk Services Ltd is an appointed representative of Talbot Underwriting Ltd which is Authorised by the Prudential Regulation Authority and regulated by the Financial Conduct Authority and the Prudential Regulation Authority.",
                Address = new Address
                {
                    AddressLine1 = "60 Threadneedle Street",
                    AddressLine2 = "",
                    City = "London",
                    Country = "England",
                    ZipPostalCode = "EC2R 8HP",
                    CreatedBy = "InitialSetup",
                    CreatedOn = DateTime.Now,
                    ModifiedBy = "InitialSetup",
                    ModifiedOn = DateTime.Now
                },
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            context.AddOrUpdate<Office>(lon);
            context.AddOrUpdate<Office>(mia);
            context.AddOrUpdate<Office>(lab);
            context.AddOrUpdate<Office>(nyc);
            context.AddOrUpdate<Office>(sng);
            context.AddOrUpdate<Office>(dubai);
            context.AddOrUpdate<Office>(usrl);

            //var userWriter1 = new Underwriter
            //{
            //    Name = "Alex Colquhoun",
            //    Code = "JAC",
            //    CreatedBy = "InitialSetup",
            //    CreatedOn = DateTime.Now,
            //    ModifiedBy = "InitialSetup",
            //    ModifiedOn = DateTime.Now
            //};
            //context.AddOrUpdate<Underwriter>(userWriter1);

            //userWriter2 = new Underwriter
            //{
            //    Name = "Alexandra Davies",
            //    Code = "AED",
            //    CreatedBy = "InitialSetup",
            //    CreatedOn = DateTime.Now,
            //    ModifiedBy = "InitialSetup",
            //    ModifiedOn = DateTime.Now
            //};
            //context.AddOrUpdate<Underwriter>(userWriter2);


            var submissionTypes = new List<SubmissionType>
                {
                    new SubmissionType { Id = "EN", Title = "EN Submission" },
                    new SubmissionType { Id = "PV", Title = "PV Submission" },
                    new SubmissionType { Id = "FI", Title = "FI Submission" },
                    new SubmissionType { Id = "CA", Title = "CA Submission" },
                    new SubmissionType { Id = "HM", Title = "HM Submission" },
                    new SubmissionType { Id = "ME", Title = "ME Submission" },
                };

            foreach (var submissionType in submissionTypes)
            {
                context.AddOrUpdate<SubmissionType>(submissionType);
            }


            var submission = new Submission
            {
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now,
                InsuredName = "- N/A",
                BrokerCode = "1111",
                BrokerPseudonym = "AAA",
                BrokerSequenceId = 822,
                InsuredId = 182396,
                Brokerage = 1,
                BrokerContact = "ALLAN MURRAY",
                UnderwriterCode = "AED",
                UnderwriterContactCode = "JAC",
                QuotingOfficeId = "LON",
                Leader = "AG",
                Domicile = "AD",
                Title = "Seed Submission",
                SubmissionTypeId = submissionTypes[0].Id,

                Options = new List<Option>{
                        new Option { 
                            CreatedOn = DateTime.Now,
                            ModifiedBy = "InitialSetup",
                            ModifiedOn = DateTime.Now,
                            Id = 1, 
                            Title = "Seed Submission",
                            OptionVersions = new List<OptionVersion>{
                                new OptionVersion { 
                                    OptionId = 0, 
                                    VersionNumber = 0, 
                                    Comments = "OptionVersion Comments", 
                                    Title = "Unit Test Submission", 
                                    CreatedBy = "InitialSetup",

                                    CreatedOn = DateTime.Now,
                                    ModifiedBy = "InitialSetup",
                                    ModifiedOn = DateTime.Now,
                                    Quotes = new List<Quote>
                                        {
                                            new Quote
                                            { 
                                            COBId = "AD", 
                                            MOA = "FA", 
                                            InceptionDate = DateTime.Now, 
                                            ExpiryDate = DateTime.Now.AddMonths(12), 
                                            QuoteExpiryDate = DateTime.Now, 
                                            AccountYear = 2013, 
                                            Currency = "USD", 
                                            LimitCCY = "USD", 
                                            ExcessCCY = "USD", 
                                            CorrelationToken = Guid.NewGuid(), 
                                            IsSubscribeMaster = true, 
                                            PolicyType = "NONMARINE", 
                                            EntryStatus = "PARTIAL", 
                                            SubmissionStatus = "SUBMITTED", 
                                            TechnicalPricingBindStatus = "PRE", 
                                            TechnicalPricingPremiumPctgAmt = "AMT", 
                                            TechnicalPricingMethod = "UW" ,
                                            OriginatingOfficeId = "LON",
                                            //Energy_QuoteExtraProperty1 = "Seed Val...",

                                            CreatedBy = "InitialSetup",
                                            CreatedOn = DateTime.Now,
                                            ModifiedBy = "InitialSetup",
                                            ModifiedOn = DateTime.Now
                                            }
                                        }
                                }}
                        }}
            };
            context.AddOrUpdate<Submission>(submission);

            var addUser1 = new User { DomainLogon = domainPrefix + @"\DaviesA", IsActive = true, UnderwriterCode = "AED", PrimaryOffice = lon, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };//, FilterCOBs = energyCobs };
            ////developers


            var globalTim = new User
            {
                DomainLogon = domainPrefix + @"\tim",
                IsActive = true,
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                AdditionalUsers = new List<User> { addUser1 },
                OpenTabs =
                    new List<Tab> { new Tab { Url = "/Submission/CreateSubmission", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }, new Tab { Url = "/Submission/_Edit/1", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now } },
                UnderwriterCode = "AED",
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            context.AddOrUpdate<User>(globalTim);

            var u2 = new User
            {
                DomainLogon = domainPrefix + @"\baillief",
                IsActive = true,
                FilterCOBs = new List<COB> { c, c1 },
                FilterOffices = new List<Office> { lon },
                UnderwriterCode = "AED",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                AdditionalUsers = new List<User> { addUser1 },
                OpenTabs =
                    new List<Tab> { new Tab { Url = "/Submission/CreateSubmission", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }, new Tab { Url = "/Submission/_Edit/1", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now } },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            context.AddOrUpdate<User>(u2);


            var u6 = new User
            {
                DomainLogon = @"TALBOTDEV\svcUKDEVTFSBuild",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                AdditionalUsers = new List<User> { addUser1 },
                UnderwriterCode = "AED",
                IsActive = true,
                OpenTabs = new List<Tab> { new Tab { Url = "/Submission/CreateSubmission", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }, new Tab { Url = "/Submission/_Edit/1", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now } },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            u6.FilterMembers = new List<User> { u6 };
            context.AddOrUpdate<User>(u6);
            var u5 = new User
            {
                DomainLogon = @"GLOBALDEV\anandarr",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                AdditionalUsers = new List<User> { addUser1 },
                IsActive = true,
                UnderwriterCode = "AED",
                OpenTabs = new List<Tab> { new Tab { Url = "/Submission/CreateSubmission", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }, new Tab { Url = "/Submission/_Edit/1", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now } },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            u5.FilterMembers = new List<User> { u5 };
            context.AddOrUpdate<User>(u5);

            var u4 = new User
            {
                DomainLogon = domainPrefix + @"\SheppaA",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                AdditionalUsers = new List<User> { addUser1 },
                IsActive = true,
                OpenTabs = new List<Tab> { new Tab { Url = "/Submission/CreateSubmission", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }, new Tab { Url = "/Submission/_Edit/1", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now } },
                UnderwriterCode = "AED",
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            u4.FilterMembers = new List<User> { u4 };
            context.AddOrUpdate<User>(u4);

            var u3 = new User
            {
                DomainLogon = domainPrefix + @"\MurrayE",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                AdditionalUsers = new List<User> { addUser1 },
                IsActive = true,
                OpenTabs = new List<Tab> { new Tab { Url = "/Submission/CreateSubmission", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }, new Tab { Url = "/Submission/_Edit/1", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now } },
                UnderwriterCode = "AED",
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };

            var u = new User
            {
                DomainLogon = domainPrefix + @"\seigelj",
                IsActive = true,
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                FilterMembers = new List<User> { u2, u4, u3, u5, u6, globalTim },
                OpenTabs =
                    new List<Tab> { new Tab { Url = "/Submission/CreateSubmission", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }, new Tab { Url = "/Submission/_Edit/1", CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now } },
                UnderwriterCode = "AED",
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };
            context.AddOrUpdate<User>(u);
            u2.AdditionalUsers = new List<User> { u };

            // Energy
            var energyUser1 = new User
            {
                DomainLogon = domainPrefix + @"\McDonaldJ",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            }; //, FilterCOBs = energyCobs };
            var energyUser2 = new User
            {
                DomainLogon = domainPrefix + @"\sarjeat",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser3 = new User
            {
                DomainLogon = domainPrefix + @"\MassieZ",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser4 = new User
            {
                DomainLogon = domainPrefix + @"\CantwellJ",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser5 = new User
            {
                DomainLogon = domainPrefix + @"\GreenM",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser6 = new User
            {
                DomainLogon = domainPrefix + @"\EwingtonJ",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser7 = new User
            {
                DomainLogon = domainPrefix + @"\ShilingS",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser8 = new User
            {
                DomainLogon = domainPrefix + @"\GarrettJ",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser9 = new User
            {
                DomainLogon = domainPrefix + @"\StoopE",
                IsActive = true,
                UnderwriterCode = "AED",
                FilterCOBs = new List<COB> { AR, AG, CC, AT },
                FilterOffices = new List<Office> { lon, mia, sng, lab, nyc },
                PrimaryOffice = lon,
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser10 = new User
            {
                DomainLogon = domainPrefix + @"\KeoganA",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                IsActive = true,
                PrimaryOffice = lon,
                UnderwriterCode = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser11 = new User
            {
                DomainLogon = domainPrefix + @"\ShawI",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                IsActive = true,
                PrimaryOffice = lon,
                UnderwriterCode = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser12 = new User
            {
                DomainLogon = domainPrefix + @"\IsmailR",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                IsActive = true,
                PrimaryOffice = lon,
                UnderwriterCode = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser13 = new User
            {
                DomainLogon = domainPrefix + @"\SibleyA",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                IsActive = true,
                PrimaryOffice = lon,
                UnderwriterCode = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser14 = new User
            {
                DomainLogon = domainPrefix + @"\DaviesK",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                IsActive = true,
                PrimaryOffice = lon,
                UnderwriterCode = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser15 = new User
            {
                DomainLogon = domainPrefix + @"\orsoc",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                IsActive = true,
                PrimaryOffice = lon,
                UnderwriterCode = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };
            var energyUser16 = new User
            {
                DomainLogon = domainPrefix + @"\dempsef",
                AdditionalOffices = new List<Office> { lon, mia, sng, lab, nyc },
                IsActive = true,
                PrimaryOffice = lon,
                UnderwriterCode = "AED",
                CreatedBy = "InitialSetup",
                CreatedOn = DateTime.Now,
                ModifiedBy = "InitialSetup",
                ModifiedOn = DateTime.Now
            };//, FilterCOBs = energyCobs };


            var energyTeamUsersList = new List<User>
                    {
                        energyUser1,
                        energyUser2,
                        energyUser3,
                        energyUser4,
                        energyUser5,
                        energyUser6,
                        energyUser7,
                        energyUser8,
                        energyUser9,
                        energyUser10,
                        energyUser11,
                        energyUser12,
                        energyUser13,
                        energyUser14,
                        energyUser15,
                        energyUser16
                    };

            // TeamList and Link List
            var linkList = CreateLinksList();

            var teamList = CreateTeamList(submissionTypes);

            teamList[0].Links = new List<Link>();
            foreach (var link in linkList.GetRange(0, 3))
            {
                teamList[0].Links.Add(link);
            }

            teamList[1].Links = new List<Link>();
            foreach (var link in linkList)
            {
                teamList[1].Links.Add(link);
            }
            var appAccelerators = CreateAppAcceleratorsList();
            teamList[0].AppAccelerators = new List<AppAccelerator>();
            foreach (var appAccelerator in appAccelerators)
            {
                teamList[0].AppAccelerators.Add(appAccelerator);
            }

            teamList[1].AppAccelerators = new List<AppAccelerator>();
            foreach (var appAccelerator in appAccelerators)
            {
                teamList[1].AppAccelerators.Add(appAccelerator);
            }

            teamList[0].RelatedOffices = new List<Office> { lon };
            teamList[1].RelatedOffices = new List<Office> { dubai };
            teamList[0].TeamOfficeSettings = new List<TeamOfficeSetting> { new TeamOfficeSetting { Office = lon, MarketWordingSettings = new List<MarketWordingSetting>(), TermsNConditionWordingSettings = new List<TermsNConditionWordingSetting>(), SubjectToClauseWordingSettings = new List<SubjectToClauseWordingSetting>() } };
            teamList[1].TeamOfficeSettings = new List<TeamOfficeSetting> { new TeamOfficeSetting { Office = dubai, MarketWordingSettings = new List<MarketWordingSetting>(), TermsNConditionWordingSettings = new List<TermsNConditionWordingSetting>(), SubjectToClauseWordingSettings = new List<SubjectToClauseWordingSetting>() } };

            var marketWordings = CreateMarketWordingsList();
            foreach (var marketWording in marketWordings.Take(10))
            {
                teamList[0].TeamOfficeSettings.First().MarketWordingSettings.Add(new MarketWordingSetting { MarketWording = marketWording });
            }

            foreach (var marketWording in marketWordings.Skip(10).Take(10))
            {
                teamList[1].TeamOfficeSettings.First().MarketWordingSettings.Add(new MarketWordingSetting { MarketWording = marketWording });
            }

            foreach (var marketWording in marketWordings.Skip(20))
            {
                context.AddOrUpdate(marketWording);
            }

            var termsNConditionWordings = CreateTermsNConditionWordingsList();
            foreach (var termsNConditionWording in termsNConditionWordings.Take(5))
            {
                teamList[0].TeamOfficeSettings.First().TermsNConditionWordingSettings.Add(new TermsNConditionWordingSetting { TermsNConditionWording = termsNConditionWording });
            }

            foreach (var termsNConditionWording in termsNConditionWordings.Take(5))
            {
                teamList[1].TeamOfficeSettings.First().TermsNConditionWordingSettings.Add(new TermsNConditionWordingSetting { TermsNConditionWording = termsNConditionWording });
            }

            foreach (var termsNConditionWording in termsNConditionWordings.Take(5))
            {
                context.AddOrUpdate(termsNConditionWording);
            }


            var subjectToClauseWordings = CreateSubjectToClauseWordingsList();
            foreach (var subjectToClauseWording in subjectToClauseWordings.Take(5))
            {
                teamList[0].TeamOfficeSettings.First().SubjectToClauseWordingSettings.Add(new SubjectToClauseWordingSetting { SubjectToClauseWording = subjectToClauseWording });
            }

            foreach (var subjectToClauseWording in subjectToClauseWordings.Take(5))
            {
                teamList[1].TeamOfficeSettings.First().SubjectToClauseWordingSettings.Add(new SubjectToClauseWordingSetting { SubjectToClauseWording = subjectToClauseWording });
            }

            foreach (var subjectToClauseWording in subjectToClauseWordings.Take(5))
            {
                context.AddOrUpdate(subjectToClauseWording);
            }

            var energyTeamMemberships = energyTeamUsersList.Select(energyTeamUser => new TeamMembership { PrimaryTeamMembership = true, User = energyTeamUser, Team = teamList[1], IsCurrent = true, StartDate = DateTime.Now, EndDate = null, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now }).ToList();
            energyTeamMemberships.Add(new TeamMembership { PrimaryTeamMembership = false, Team = teamList[1], User = u5, StartDate = DateTime.Now, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now });

            var teamMemberships = new List<TeamMembership> 
                { 
                    new TeamMembership { User = u3, Team = teamList[0], IsCurrent = true, StartDate = DateTime.Now, EndDate = DateTime.Now.AddYears(4), CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now  },
                };

            var memb1 = new TeamMembership { PrimaryTeamMembership = true, Team = teamList[0], User = u, StartDate = DateTime.Now, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var memb3 = new TeamMembership { PrimaryTeamMembership = true, Team = teamList[0], User = u4, StartDate = DateTime.Now, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var memb2 = new TeamMembership { PrimaryTeamMembership = true, Team = teamList[0], User = u2, StartDate = DateTime.Now, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var memb5 = new TeamMembership { PrimaryTeamMembership = true, Team = teamList[0], User = u5, StartDate = DateTime.Now, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var memb6 = new TeamMembership { PrimaryTeamMembership = true, Team = teamList[0], User = u6, StartDate = DateTime.Now, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };
            var memb4 = new TeamMembership { PrimaryTeamMembership = true, Team = teamList[0], User = globalTim, StartDate = DateTime.Now, CreatedBy = "InitialSetup", CreatedOn = DateTime.Now, ModifiedBy = "InitialSetup", ModifiedOn = DateTime.Now };

            teamList[0].RelatedCOBs = new List<COB> { AR, AG, CC, AT };
            teamList[1].RelatedCOBs = new List<COB> { AR, AG, CC, AT };

            teamList[0].Memberships = new List<TeamMembership> { memb1, memb2, memb4, memb3, memb5, memb6 };

            foreach (var teamM in teamMemberships)
            {
                teamList[0].Memberships.Add(teamM);
            }

            teamList[1].Memberships = new List<TeamMembership>();
            foreach (var energyTeamMembership in energyTeamMemberships)
            {
                teamList[1].Memberships.Add(energyTeamMembership);
            }

            foreach (var team in teamList)
            {
                context.AddOrUpdate<Team>(team);
            }

        }