public HttpResponseMessage EditSubmission(Submission submission)
        {
            var errors = new List<String>();
            var quotes = new List<Quote>();

	        var savedSubmission = this.SubmissionModule.UpdateSubmission(SubmissionModuleHelpers.SetupWording(submission),
	                                                                     out errors, out quotes);

			if (errors.Count == 0 && submission.AuditTrails != null)
	        {
		        foreach (var auditTrail in submission.AuditTrails
		                                             .Where(at => at.Description.Length >
		                                                          "World Check requested for insured name: ".Length))
		        {
			        this.AuditTrailModule.Audit(auditTrail.Source,
			                                    submission.Id.ToString(),
			                                    auditTrail.Title,
			                                    auditTrail.Description);
		        }
	        }

	        return this.Request.CreateResponse(errors.Count == 0 ? HttpStatusCode.OK : HttpStatusCode.BadRequest, new
	        {
		        Submission = savedSubmission,
		        Error = new Dictionary<string, string[]> { { "Subscribe", errors.ToArray() } }
	        });
        }
        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 string CreateQuoteSheet(CreateQuoteSheetDto dto, out Submission submission)
        {
            // TODO: use the correct quote sheet...
            var quoteSheetTemplateId = dto.QuoteSheetTemplateId;
            dto.QuoteSheetTemplateUrl = this.ConsoleRepository.Query<QuoteTemplate>()
                                            .FirstOrDefault(qt => qt.Id == dto.QuoteSheetTemplateId).RdlPath;
            dto.QuoteSheetTemplateName = this.ConsoleRepository.Query<QuoteTemplate>()
                                            .FirstOrDefault(qt => qt.Id == dto.QuoteSheetTemplateId).Name;

            submission = this.SubmissionModule.GetSubmissionById(dto.SubmissionId);
            //todo this is done to clear previous context. has to be fixed once softdelet is fixed.
            using (IConsoleRepository consoleRepository = new ConsoleRepository())
            {
                if (submission == null)
                    throw new KeyNotFoundException(string.Format(this.NotFoundMessage, dto.SubmissionId));
                consoleRepository.Attach(submission);
                var currentUser = consoleRepository.Query<User>()
                                      .FirstOrDefault(u => u.DomainLogon == this.HttpContext.CurrentUser.Identity.Name);

                if (currentUser == null)
                    throw new ApplicationException("Current user could not be found");

                var quotesheet = new QuoteSheet
                {
                    Title = string.Format(this.QuoteSheetTitle, submission.Title, submission.InsuredName, DateTime.Now),
                    IssuedBy = currentUser,
                    IssuedById = currentUser.Id,
                    IssuedDate = DateTime.Now,
                    ObjectStore = "Underwriting"
                };

                var content = this.QuoteSheetData.CreateQuoteSheetPdf(dto);

                quotesheet.Guid = this.QuoteSheetData.SaveQuoteSheetToDMS(quotesheet, content, submission);

                var versions = (from version in submission.Options.SelectMany(o => o.OptionVersions)
                                from option in dto.OptionList
                                where version.OptionId == option.OptionId
                                from versionNumber in option.OptionVersionNumberList
                                where version.VersionNumber == versionNumber
                                select version).ToList();

                quotesheet.OptionVersions = versions;

                foreach (var quote in versions.SelectMany(ov => ov.Quotes))
                {
                    quote.OptionVersion.IsLocked = true;

                    quote.SubmissionStatus = "QUOTED";
                }

                consoleRepository.Add(quotesheet);
                consoleRepository.SaveChanges();
                return string.Format(this.QuoteSheetUrl,
                               ConfigurationManager.AppSettings["UWDmsFileDownloadURL"],
                               quotesheet.Guid);
            }

          
        }
        public Guid SaveQuoteSheetToDMS(QuoteSheet quoteSheet, byte[] reportBytes, Submission submission)
        {
	        var fileId = Guid.Empty.ToString();

			// TODO: Exception handling
	        using (var dmsService = new DMSService())
	        {
		        fileId = dmsService.FNUploadDocument(quoteSheet.Title + ".pdf", quoteSheet.Title, reportBytes,
		                                             quoteSheet.ObjectStore, quoteSheet.ObjectStore);

				dmsService.FNUpdateDocumentProperties(fileId, quoteSheet.ObjectStore, quoteSheet.ObjectStore,
		                                              this.SetFileNetProperties(quoteSheet, submission));
	        }

			return new Guid(fileId);
        }
        public static Submission RemoveDeletedItems(Submission submission)
        {
            //Todo: this code has to be removed when bug related to soft delete is fixed.
            var removeOptions = submission.Options.Where(o => o.IsDeleted).ToList();
            foreach (var removeOption in removeOptions)
            {
                submission.Options.Remove(removeOption);
            }

            foreach (var activeOption in submission.Options)
            {
                var removeOptionVersions = activeOption.OptionVersions.Where(ov => ov.IsDeleted).ToList();
                foreach (var removeOptionVersion in removeOptionVersions)
                {
                    activeOption.OptionVersions.Remove(removeOptionVersion);
                }
                foreach (var activeOptionVersion in activeOption.OptionVersions)
                {
                    var removeQuotes = activeOptionVersion.Quotes.Where(q => q.IsDeleted).ToList();
                    foreach (var removeQuote in removeQuotes)
                    {
                        activeOptionVersion.Quotes.Remove(removeQuote);
                    }
                }
            }
            return submission;
        }
        public static Submission SetupWording(Submission submission)
        {
            #region wording
            var displayOrder = 0;
            submission.MarketWordingSettings = new List<MarketWordingSetting>();
            if (submission.SubmissionMarketWordingsList != null)
                foreach (var marketWordingSetting in submission.SubmissionMarketWordingsList)
                {
                    displayOrder++;
                    submission.MarketWordingSettings.Add(new MarketWordingSetting { Id = marketWordingSetting.SettingId, DisplayOrder = displayOrder, MarketWording = new MarketWording { Id = marketWordingSetting.Id } });

                }
            displayOrder = 0;
            submission.TermsNConditionWordingSettings = new List<TermsNConditionWordingSetting>();
            if (submission.SubmissionTermsNConditionWordingsList != null)
                foreach (var termsNConditionWordingSetting in submission.SubmissionTermsNConditionWordingsList )
                {
                    displayOrder++;
                    submission.TermsNConditionWordingSettings.Add(new TermsNConditionWordingSetting { Id = termsNConditionWordingSetting.SettingId, DisplayOrder = displayOrder, IsStrikeThrough = termsNConditionWordingSetting.IsStrikeThrough, TermsNConditionWording = new TermsNConditionWording { Id = termsNConditionWordingSetting.Id } });

                }
            displayOrder = 0;
            submission.SubjectToClauseWordingSettings = new List<SubjectToClauseWordingSetting>();
            if (submission.SubmissionSubjectToClauseWordingsList != null)
                foreach (var subjectToClauseWordingSetting in submission.SubmissionSubjectToClauseWordingsList)
                {
                    displayOrder++;
                    submission.SubjectToClauseWordingSettings.Add(new SubjectToClauseWordingSetting { Id = subjectToClauseWordingSetting.SettingId, DisplayOrder = displayOrder, IsStrikeThrough = subjectToClauseWordingSetting.IsStrikeThrough, SubjectToClauseWording = new SubjectToClauseWording { Id = subjectToClauseWordingSetting.Id } });

                }

            displayOrder = 0;
            submission.CustomMarketWordingSettings = new List<MarketWordingSetting>();
            if (submission.CustomSubmissionMarketWordingsList != null)
                foreach (var marketWordingSetting in submission.CustomSubmissionMarketWordingsList )
                {
                    displayOrder++;
                    submission.CustomMarketWordingSettings.Add(new MarketWordingSetting { Id = marketWordingSetting.SettingId, DisplayOrder = displayOrder, MarketWording = new MarketWording { Id = 0, WordingRefNumber = marketWordingSetting.WordingRefNumber, Title = marketWordingSetting.Title, WordingType = "Custom" } });

                }
            displayOrder = 0;
            submission.CustomTermsNConditionWordingSettings = new List<TermsNConditionWordingSetting>();
            if (submission.CustomSubmissionTermsNConditionWordingsList != null)
                foreach (var termsNConditionWordingSetting in submission.CustomSubmissionTermsNConditionWordingsList )
                {
                    displayOrder++;
                    submission.CustomTermsNConditionWordingSettings.Add(new TermsNConditionWordingSetting { Id = termsNConditionWordingSetting.SettingId, DisplayOrder = displayOrder, IsStrikeThrough = termsNConditionWordingSetting.IsStrikeThrough, TermsNConditionWording = new TermsNConditionWording { Id = 0, WordingRefNumber = termsNConditionWordingSetting.WordingRefNumber, Title = termsNConditionWordingSetting.Title, WordingType = "Custom" } });

                }
            displayOrder = 0;
            submission.CustomSubjectToClauseWordingSettings = new List<SubjectToClauseWordingSetting>();
            if (submission.CustomSubmissionSubjectToClauseWordingsList != null)
                foreach (var subjectToClauseWordingSetting in submission.CustomSubmissionSubjectToClauseWordingsList )
                {
                    displayOrder++;
                    submission.CustomSubjectToClauseWordingSettings.Add(new SubjectToClauseWordingSetting { Id = subjectToClauseWordingSetting.SettingId, DisplayOrder = displayOrder, IsStrikeThrough = subjectToClauseWordingSetting.IsStrikeThrough, SubjectToClauseWording = new SubjectToClauseWording { Id = 0, Title = subjectToClauseWordingSetting.Title, WordingType = "Custom" } });

                }

            #endregion

            return submission;
        }
	    public static bool SynchroniseSubmission(Submission submission, PolicyContract polAsSubscribe)
        {
            submission.InsuredName = polAsSubscribe.InsdNm;
            submission.BrokerSequenceId = polAsSubscribe.BkrSeqId;
            submission.NonLondonBrokerCode = polAsSubscribe.NonLonBkr;
            submission.UnderwriterCode = polAsSubscribe.Uwr;
            submission.Brokerage = polAsSubscribe.Brokerage;
            submission.LeaderNo = polAsSubscribe.LdrNo;
            submission.Leader = polAsSubscribe.Ldr;

	        if (polAsSubscribe.AddlInsuredCollection != null)
	        {
	            submission.AdditionalInsuredList = new List<AdditionalInsured>
	                (
	                polAsSubscribe.AddlInsuredCollection
                                  .Where(i => i.AddlInsdTy != "Insured")
	                              .Select(i => new AdditionalInsured
	                                  {
	                                      InsuredId = i.AddlInsdId,
	                                      InsuredName = i.AddlInsdNm,
                                          InsuredType = i.AddlInsdTy
	                                  })
	                );
	        }

	        // TODO: values missing from service response...
            //s.Domicile = polAsSubscribe. 
            //s.BrokerContact = polAsSubscribe.
            //s.Description = polAsSubscribe.

            return true;
        }
        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;
        }
		// TODO: Don't we need know which quote is generating the quotesheet?
        private FileNetProperty[] SetFileNetProperties(QuoteSheet quoteSheet, Submission submission)
        {
            var options = submission.Options.Select(o => o);
            var optionVersions = options.SelectMany(ov => ov.OptionVersions);
            var quotes = optionVersions.SelectMany(ov => ov.Quotes).Where(q => q.IsSubscribeMaster).ToList();

            var subscribeRefList = quotes.Select(q => q.SubscribeReference).Aggregate(string.Empty, (current, subscribeRef) => current + (subscribeRef + ";"));
	        var currentDateTime = DateTime.Now;

			var mainQuote = quotes[0]; // TODO: For the moment, we will use the first quote we come across
			var businessPlanList = string.Empty;

			// TODO: Exception handling
			using (var subscribeService = new SubscribeSoapService.Subscribe())
			{
				businessPlanList = quotes.Select(q => q.SubscribeReference)
					.Select(subscribeService.GetPolicyDetail)
					.Aggregate(businessPlanList, (current, policyDetails) => current + (policyDetails.BusinessPlan + ";"));
            }

            List<FileNetProperty> properties = new List<FileNetProperty>
            {
                    /* Base Document Properties
				 * 
				 * Mandatory;
				 * - DocumentTitle (String)
				 * 
				 * Optional;
				 * - Description (String)
				 */
                    new FileNetProperty {Key = "DocumentTitle", Value = "Quote sheet"},
                 //   new FileNetProperty {Key = "Description", Value = "Quote sheet description"},

                    /* Underwriting Document Properties
				 * 
				 * Mandatory;
				 * - uwPolicyID (ListOfString): List of Subscribe references delimited by semi-colon.
				 * - uwBusinessPlan (ListOfString): List of business plans delimited by semi-colon.
				 * - uwDocType (String): Document type.
				 * - uwInsuredName (String): Insured name.
				 * - uwCOB (String): Class of business code.
				 * - uwUnderwriter (String): Underwriter pseudonym.
				 * - uwBrokerPSU (String): Broker pseudonym.
				 * - uwInceptionDate (Date): Inception date.
				 * - uwAccountingYear (Integer): Accounting year.
				 * - uwStatus (String): Status, which is always "QUOTE" at this stage.
				 * - uwEntryStatus (String): Entry status, which is either "PARTIAL" or "NTU" at this stage.
				 * 
				 * Optional;
				 * - PolicyIDSP (String): List of Subscribe references delimited by semi-colon.
				 * - BusinessPlanSP (String): List of business plans delimited by semi-colon.
				 * - uwWrittenDate (Date): Written date.
				 * - AccountingYearFloat (Float): Accounting year.
				 * 
				 * Note 1: 
				 * FileNet has two fields for each Policy ID and Business Plan. One field is a String data-type 
				 * and the other (the primary field) is a ListOfString. For consistency, both of the values should be
				 * the same with the exception that the ListOfString will be parsed by the web service into an array
				 * by a specified delimiter (this was a quick-fix on the web service).
				 * 
				 * In order to pass back a ListOfString value to the FileNet web service, a delimited string should
				 * be passed with the delimiter specified in the Delimiter property of the FileNetProperty class.
				 * 
				 * Note 2:
				 * The values for the document type must exist in the FileNet document type choice list or it will
				 * throw back an error.
				 * 
				 * Note 3:
				 * FileNet has two fields for accounting year. One field is a Float data-type and the other is an
				 * Integer. For consistency, both of the values should be the same.
				 */
                    new FileNetProperty {Key = "uwPolicyID", Value = subscribeRefList, Delimiter = ";"},
                    new FileNetProperty {Key = "PolicyIDSP", Value = subscribeRefList},
                    new FileNetProperty {Key = "uwBusinessPlan", Value = businessPlanList, Delimiter = ";"},
                    new FileNetProperty {Key = "BusinessPlanSP", Value = businessPlanList},
                    new FileNetProperty {Key = "uwDocType", Value = "Quote"},
                    new FileNetProperty {Key = "uwInsuredName", Value = submission.InsuredName},
                    new FileNetProperty {Key = "uwCOB", Value = mainQuote.COBId},
                    new FileNetProperty {Key = "uwUnderwriter", Value = submission.UnderwriterContactCode},
                    new FileNetProperty {Key = "uwBrokerPSU", Value = submission.BrokerPseudonym},
                    new FileNetProperty {Key = "uwAccountingYear", Value = mainQuote.AccountYear},
                    new FileNetProperty {Key = "uwStatus", Value = "QUOTE"},
                    new FileNetProperty {Key = "uwEntryStatus", Value = mainQuote.EntryStatus},

                    /* Other Custom Document Properties
				 * 
				 * Mandatory;
				 * - uwInputDeviceID (String): The system that uploaded the document ("Console"). The other entry 
				 *		points are Kofax, Worflow (via Web Services) and SharePoint (via ICC). This is to help 
				 *		administrators understand the origins of the document.
				 * - uwIndexPerson (String): Login name of the user that uploaded the document.
				 * - uwLoadToDMSDateAndTime (Date): Upload date.
				 * - uwOpsInfo (String): Delimited string of workflow status flags, which is always
				 *		"Aggs=0;FacRI=0;Group=0;BPQARequired=0;PTradeFile=0;S2000=0;PreBind=0;PostBind=0;ReSign=0;t&cChange=0;UrgentCase=0;ForeignLanguage=0"
				 *		at this stage.
				 * 
				 * Optional;
				 * - uwIndexDateTime (Date): Upload date.
				 * - strLoadToDMSDateAndTime (String): Upload date-time string in the format of "dd/MM/yyyy HH:mm".
				 * - WSTriggerStatus (String): Workflow initiation status flag used by FileNet, which is always
				 *		"INVALID" at this stage.
				 */
                    new FileNetProperty {Key = "uwInputDeviceID", Value = "Console"},
                    new FileNetProperty {Key = "uwIndexPerson", Value = quoteSheet.IssuedBy.DomainLogon},
                    // TODO: Is this the current user?
                    new FileNetProperty {Key = "uwIndexDateTime", Value = currentDateTime},
                    new FileNetProperty {Key = "uwLoadToDMSDateAndTime", Value = currentDateTime},
                    new FileNetProperty
                        {
                            Key = "strLoadToDMSDateAndTime",
                            Value = currentDateTime.ToString("dd/MM/yyyy HH:mm")
                        },
                    new FileNetProperty {Key = "WSTriggerStatus", Value = "INVALID"},
                    new FileNetProperty
                        {
                            Key = "uwOpsInfo",
                            Value =
                                "Aggs=0;FacRI=0;Group=0;BPQARequired=0;PTradeFile=0;S2000=0;PreBind=0;PostBind=0;ReSign=0;t&cChange=0;UrgentCase=0;ForeignLanguage=0"
                        }

                };

            if (mainQuote.InceptionDate != null)
            {
                properties.Add(new FileNetProperty
                {
                    Key = "uwInceptionDate",
                    Value = mainQuote.InceptionDate.GetValueOrDefault()
                });
            }

            return properties.ToArray();
        }
        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);
            }

        }
        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 string CreateQuoteSheet(CreateQuoteSheetDto dto, out Submission submission)
        {
            // TODO: use the correct quote sheet...
            var quoteSheetTemplateId = dto.QuoteSheetTemplateId;
            dto.QuoteSheetTemplateUrl = this.ConsoleRepository.Query<QuoteTemplate>()
                                            .FirstOrDefault(qt => qt.Id == dto.QuoteSheetTemplateId).RdlPath;
            dto.QuoteSheetTemplateName = this.ConsoleRepository.Query<QuoteTemplate>()
                                            .FirstOrDefault(qt => qt.Id == dto.QuoteSheetTemplateId).Name;

            submission = this.SubmissionModule.GetSubmissionById(dto.SubmissionId);
            //todo this is done to clear previous context. has to be fixed once softdelet is fixed.
            using (IConsoleRepository consoleRepository = new ConsoleRepository())
            {
                if (submission == null)
                    throw new KeyNotFoundException(string.Format(this.NotFoundMessage, dto.SubmissionId));
                consoleRepository.Attach(submission);
                var currentUser = consoleRepository.Query<User>()
                                      .FirstOrDefault(u => u.DomainLogon == this.HttpContext.CurrentUser.Identity.Name);

                if (currentUser == null)
                    throw new ApplicationException("Current user could not be found");
                
                var versions = (from version in submission.Options.SelectMany(o => o.OptionVersions)
                                from option in dto.OptionList
                                where version.OptionId == option.OptionId
                                from versionNumber in option.OptionVersionNumberList
                                where version.VersionNumber == versionNumber
                                select version).ToList();

                var isDeclinature = false;
                var submSt = submission.Options.Select(s => s)
                                   .SelectMany(o => o.OptionVersions)
                                   .SelectMany(ov => ov.Quotes)
                                   .Where(q => q.IsSubscribeMaster).Select(s => s.SubmissionStatus).Distinct().ToList();
                if ((submSt.Count == 1) && (submSt.FirstOrDefault().Equals(Settings.Default["DeclinatureSubmissionStatus"].ToString())))
                    isDeclinature = true;

                var quotesheet = new QuoteSheet
                {//Todo: S2Q
                    Title = string.Format(this.QuoteSheetTitle, submission.Title, versions.SelectMany(ov => ov.Quotes).First().InsuredName,  DateTime.Now),
                    IssuedBy = currentUser,
                    IssuedById = currentUser.Id,
                    IssuedDate = DateTime.Now,
                    ObjectStore = Settings.Default["DMSObjectStore"].ToString(),
                    DocumentClass = Settings.Default["DMSDocumentClass"].ToString(),
                    DocumentType = isDeclinature ? Settings.Default["DeclinatureDocType"].ToString() : Settings.Default["QuoteDocType"].ToString()
                };

                var content = this.QuoteSheetData.CreateQuoteSheetPdf(dto, isDeclinature);

                quotesheet.Guid = this.QuoteSheetData.SaveQuoteSheetToDMS(quotesheet, content, submission, isDeclinature);
                
                quotesheet.OptionVersions = versions;

                if (!isDeclinature)
                {
                    foreach (var quote in versions.SelectMany(ov => ov.Quotes))
                    {
                        if (!quote.SubmissionStatus.Equals(Settings.Default["DeclinatureSubmissionStatus"].ToString()))
                        {
                            quote.OptionVersion.IsLocked = true;

                            quote.SubmissionStatus = "QUOTED";
                        }
                    }
                }

                consoleRepository.Add(quotesheet);
                consoleRepository.SaveChanges();
                return string.Format(this.QuoteSheetUrl,
                               ConfigurationManager.AppSettings["UWDmsFileDownloadURL"],
                               quotesheet.Guid);
            }

          
        }
	    public static bool SynchroniseSubmission(Submission submission, PolicyContract polAsSubscribe)
        {
			

	        

	        return true;
        }