/// <summary> /// 在Action执行之前调用 /// </summary> /// <param name="context"></param> /// <returns></returns> public void OnActionExecuting(ActionExecutingContext context) { var query = context.HttpContext.Request.Query; string nonce = query["nonce"]; //随机数 string timestamp = query["timestamp"]; //时间戳 string signature = query["signature"]; //微信加密签名,signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数 string openId = query.ContainsKey("openid") ? $"{query["openid"]}" : ""; //用户的标识,对当前公众号唯一 string echostr = query.ContainsKey("echostr") ? $"{query["echostr"]}" : ""; //随机字符串 WeChatAccount account = ((BaseController)context.Controller).Account; //微信账户信息配置 if (!SignatureVerifyUtil.CheckSignature(signature, timestamp, nonce, account.Token)) { ContractResult result = new ContractResult(); result.SetError(ErrorCodeType.CheckSignFail); context.Result = new JsonResult(result); _log.Debug($"【微信签名校验】请求参数=》signature:{signature},timestamp:{timestamp},nonce:{nonce},echostr:{echostr},appid:{account.AppId},openid:{openId}"); return; } if (context.HttpContext.Request.Method.Equals("GET", StringComparison.InvariantCultureIgnoreCase) && !string.IsNullOrEmpty(echostr)) { ContentResult result = new ContentResult() { Content = echostr }; context.Result = result; return; } }
private static string JoinGame(string playerTwoJson) { var game = FindOpenGame(); var playerTwo = CastPlayer(playerTwoJson); bool operationResult; string error; if (game == null) { operationResult = false; error = "No games available"; } else if (playerTwo == null) { operationResult = false; error = "Invalid Player JSON (" + playerTwo + ")"; } else { if (game.JoinGame(playerTwo)) { operationResult = true; error = null; CloseGame(game); } else { operationResult = false; error = "Game full (" + game.Id + ")"; } } return(ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString()); }
public ContractResult Find(long id) { Data.Entity.Contract entity = ContractDao.Find(id); ContractResult result = ContractResultConverter.Convert(entity); return(result); }
/// <summary> /// 生成签名 /// </summary> /// <param name="appId"></param> /// <param name="secretKey"></param> /// <param name="noncestr"></param> /// <param name="timestamp">时间戳</param> /// <param name="pageUrl">h5页面地址</param> /// <param name="account">微信账户配置</param> /// <returns></returns> private static ContractResult <string> GetJsApiTicket(string appId, string secretKey, string noncestr, long timestamp, string pageUrl) { ContractResult <string> result = new ContractResult <string>(); var ticketResult = GetJsApiTicket(appId, secretKey); if (ticketResult.ErrorCode != "0") { result.SetError(ticketResult.ErrorCode, ticketResult.ErrorMessage); return(result); } var dictParam = new SortedDictionary <string, string> { { "url", pageUrl }, { "noncestr", noncestr }, { "timestamp", $"{timestamp}" }, { "jsapi_ticket", ticketResult.Data } }; var source = ""; foreach (var pair in dictParam) { source += pair.Key + "=" + pair.Value + "&"; } source = source.TrimEnd('&'); result.Data = source.Encode(); return(result); }
private async Task <ContractResult> UpdateContract(Contract co) { _logger.LogInformation(GetLogMessage($@"For Contract: {co.Id}")); var retVal = new ContractResult() { ContractId = co.Id }; co.Updated = DateTimeOffset.UtcNow; co.UpdatedById = _userInfo.UserId; var result = await Repository.UpdateAsync(co, true); _logger.LogDebug(GetLogMessage("{0} records updated"), result); if (result > 0) { retVal.Succeeded = true; await Task.Run(() => { RaiseEvent(new ContractUpdatedEvent() { ContractId = co.Id }); }); } return(retVal); }
/// <summary> /// 在Action执行之前调用 /// </summary> /// <param name="context"></param> /// <returns></returns> public void OnActionExecuting(ActionExecutingContext context) { ContractResult result = new ContractResult(); var baseController = ((BaseOAuthController)context.Controller); if (baseController.UserTicket != null) { baseController.UserTicket = AccessTokenUtil.RefreshToken(baseController.Account.AppId, baseController.UserTicket); return; } string codeKey = context.HttpContext.Request.Query.Keys.FirstOrDefault(key => key.ToLower() == "code"); if (!string.IsNullOrEmpty(codeKey)) { string secretKey = baseController.Account.SecretKey; string code = context.HttpContext.Request.Query[codeKey]; baseController.UserTicket = AccessTokenUtil.GetOAuthToken(baseController.Account.AppId, code, baseController.Account.SecretKey); } else { string authorizeUrl = WeChatSettingsUtil.Settings.AuthorizeUrl; string urlKey = context.HttpContext.Request.Query.Keys.FirstOrDefault(key => key.ToLower() == "url"); if (string.IsNullOrEmpty(urlKey)) { result.SetError(ErrorCodeType.InvalidUrl); context.Result = new JsonResult(result); return; } string redirect_uri = context.HttpContext.Request.Query[urlKey]; string location = $"{authorizeUrl}?appid={baseController.Account.AppId}&redirect_uri={redirect_uri}&response_type=code&scope=snsapi_userinfo&state=STATE#wechat_redirect"; context.Result = new RedirectResult(location);//302重定向跳转 } }
private static string MarkLocation(string gameId, string playerId, int row, int column) { var game = GetGame(gameId); bool operationResult; string error; if (game == null) { operationResult = false; error = "Game not found (" + gameId + ")"; } else if (game.CurrentPlayer.Id != playerId) { operationResult = false; error = "Not player's turn (" + playerId + ")"; } else { operationResult = true; error = null; game.MarkLocation(row, column); SaveGame(game); } return(ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString()); }
/// <summary> /// <see cref="IContract.Finalize(ContractResult)" /> /// </summary> public void Finalize(ContractResult result) { SwitchStatus(ContractStatus.FINALIZED); Status.Dispose(); Result.OnNext(result); Result.Dispose(); }
private async Task <ContractResult> RestartContract(Contract contract) { _logger.LogInformation(GetLogMessage($@"For Contract: {contract.Id}")); var retValue = new ContractResult { ContractId = contract.Id }; if (contract.Status != ContractStatus.Paused) { retValue.ErrorMessage = "You can only restart a contract that has been paused"; return(retValue); } _logger.LogDebug(GetLogMessage("Contract is ready to be restarted")); contract.ObjectState = ObjectState.Modified; contract.ContractorPauseDate = null; contract.ContractorEndDate = null; contract.AccountManagerEndDate = null; contract.AccountManagerPauseDate = null; contract.CustomerEndDate = null; contract.CustomerPauseDate = null; contract.AgencyOwnerEndDate = null; contract.AgencyOwnerPauseDate = null; contract.CustomerPauseDate = null; contract.CustomerEndDate = null; contract.Status = ContractStatus.Active; contract.Updated = DateTimeOffset.UtcNow; contract.UpdatedById = _userInfo.UserId; contract.StatusTransitions.Add(new ContractStatusTransition() { Status = contract.Status, ObjectState = ObjectState.Added }); var records = Repository.InsertOrUpdateGraph(contract, true); _logger.LogDebug(GetLogMessage("{0} records updated"), records); if (records > 0) { retValue.Succeeded = true; await Task.Run(() => { RaiseEvent(new ContractRestartedEvent() { ContractId = contract.Id }); }); } return(retValue); }
public void AddContractResult(ContractResult contractResult) { contractResult.Date = DateTime.UtcNow; contractResult.Id = Guid.NewGuid(); _unitOfWork.GetRepository <ContractResult>().Add(contractResult); _unitOfWork.Save(); }
/// <summary> /// 发生异常时调用 /// </summary> /// <param name="context"></param> public void OnException(ExceptionContext context) { Exception ex = context.Exception; context.ExceptionHandled = true; var result = new ContractResult(); result.SetError(ErrorCodeType.Exception); context.Result = new JsonResult(result); context.HttpContext.Response.StatusCode = (int)HttpStatusCode.OK; _log.Error($"【全局异常】发生未经处理的全局异常:{ex}"); }
public static string Main(string operation, params object[] args) { string error = "null"; if (Runtime.Trigger == TriggerType.Application) { if (operation == "creategame") { if (args.Length == 1) { return(CreateGame((string)args[0])); } error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else if (operation == "joingame") { if (args.Length == 1) { return(JoinGame((string)args[1])); } error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else if (operation == "marklocation") { if (args.Length == 4) { return(MarkLocation((string)args[0], (string)args[1], (int)args[2], (int)args[3])); } error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else if (operation == "fetchgame") { if (args.Length == 1) { return(FetchGame((string)args[0])); } error = "Incorrect number of args (" + args.Length + ") for operation (" + operation + ")"; } else { error = "Invalid operation (" + operation + ")"; } } return(ContractResult.NewContractResult(false, error).Serialize().AsString()); }
public ActionResult MakeConfirmation(ContractForConfirmationViewModel model) { model.AdminId = new Guid(User.Identity.GetUserId()); var contractResult = new ContractResult(); Mapper.Map(model, contractResult); _contractService.ChangeStatus(contractResult.ContractId, contractResult.Status); _contractResultService.AddContractResult(contractResult); return(RedirectToAction("GetAllContracts")); }
public async Task <ContractResult> DeleteContract(IProviderAgencyOwner agencyOwner, Guid contractId) { _logger.LogInformation(GetLogMessage($@"Deleting Contract: {contractId}")); var retVal = new ContractResult { ContractId = contractId }; var c = await Repository .Queryable() .Include(x => x.TimeEntries) .ForAgencyOwner(agencyOwner) .FindById(contractId) .FirstOrDefaultAsync(); if (c.TimeEntries.Any()) { foreach (var entry in c.TimeEntries) { entry.IsDeleted = true; entry.Updated = DateTimeOffset.UtcNow; entry.ObjectState = ObjectState.Modified; } } c.IsDeleted = true; c.Updated = DateTimeOffset.UtcNow; c.UpdatedById = _userInfo.UserId; c.ObjectState = ObjectState.Modified; int result = Repository.InsertOrUpdateGraph(c, true); _logger.LogDebug(GetLogMessage("{0} results updated"), result); if (result > 0) { retVal.Succeeded = true; await Task.Run(() => { RaiseEvent(new ContractDeletedEvent() { ContractId = c.Id }); }); } return(retVal); }
private async Task <ContractResult> EndContract(Contract contract) { _logger.LogInformation(GetLogMessage($@"For Contract: {contract.Id}")); var retVal = new ContractResult() { ContractId = contract.Id }; if (contract.Status != ContractStatus.Ended) { _logger.LogDebug(GetLogMessage("Contract ready to be ended")); contract.Updated = DateTimeOffset.UtcNow; contract.UpdatedById = _userInfo.UserId; contract.Status = ContractStatus.Ended; contract.ObjectState = ObjectState.Modified; contract.StatusTransitions.Add(new ContractStatusTransition() { Status = contract.Status, ObjectState = ObjectState.Added }); var records = Repository.InsertOrUpdateGraph(contract, true); _logger.LogDebug(GetLogMessage("{0} records updated"), records); if (records > 0) { retVal.Succeeded = true; retVal.ContractId = contract.Id; await Task.Run(() => { RaiseEvent(new ContractEndedEvent() { ContractId = contract.Id }); }); } } return(retVal); }
private static string FetchGame(string gameId) { var game = GetGame(gameId); bool operationResult; string error; if (game == null) { operationResult = false; error = "Game not found (" + gameId + ")"; } else { operationResult = true; error = null; } return(ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString()); }
private void HandleGetContractResults(ContractResult contractResult) { if (!contractResult.hasError) { if (contractResult.result.HasValue) { contractData = contractResult.result.Value; Debug.Log("List Contracts Responce:\nContract Data Found ... please view the inspector."); } else { //TODO: Handle no contract found Debug.Log("List Contracts Responce:\nNo contract found."); } } else { //TODO: Handle your errors Debug.Log("List Contracts Responce:\nHas Error: " + contractResult.hasError + "\nMessage: " + contractResult.message); } }
/// <summary> /// Fetch details about a specific contract for the current app Id /// </summary> /// <param name="contract">The contract to get</param> /// <param name="callback">The method to call back into with the results.</param> /// <returns>The Unity routine enumerator</returns> /// <remarks> /// <para> /// For more information please see <see href="https://docs.arkane.network/pages/token-management.html#_get_contract">https://docs.arkane.network/pages/token-management.html</see> /// </para> /// </remarks> /// <example> /// <para> /// How to call: /// </para> /// <code> /// StartCoroutine(API.TokenManagement.GetContract(Identity, contract, HandleGetContractResults)); /// </code> /// </example> public static IEnumerator GetContract(Engine.Contract contract, Action<ContractResult> callback) { if (BGSDKSettings.current == null) { callback(new ContractResult() { hasError = true, message = "Attempted to call BGSDK.TokenManagement.GetContract with no BGSDK.Settings object applied.", result = null }); yield return null; } else { if (BGSDKSettings.user == null) { callback(new ContractResult() { hasError = true, message = "BGSDKIdentity required, null identity provided.\nPlease initalize the Settings.user variable before calling GetContract", result = null }); yield return null; } else { UnityWebRequest www = UnityWebRequest.Get(BGSDKSettings.current.ContractUri + "/" + contract.Id); www.SetRequestHeader("Authorization", BGSDKSettings.user.authentication.token_type + " " + BGSDKSettings.user.authentication.access_token); var co = www.SendWebRequest(); while (!co.isDone) yield return null; if (!www.isNetworkError && !www.isHttpError) { string resultContent = www.downloadHandler.text; var results = new ContractResult(); results.result = JsonUtility.FromJson<DataModel.ContractData>(resultContent); results.message = "Get Contract complete."; results.httpCode = www.responseCode; callback(results); } else { callback(new ContractResult() { hasError = true, message = "Error:" + (www.isNetworkError ? " a network error occured while requesting the contract." : " a HTTP error occured while requesting the contract."), result = null, httpCode = www.responseCode }); } } } }
/// <summary> /// 获取签名 /// </summary> /// <param name="appId"></param> /// <param name="secretKey"></param> /// <param name="pageUrl">h5页面地址</param> /// <returns></returns> public static ContractResult <WeChatSignatureResult> GetJsApiTicket(string appId, string secretKey, string pageUrl) { long timestamp = DateTime.Now.ToUnixTimeForSeconds(); string noncestr = random.GenString(32, true, false, true, false, ""); ContractResult <WeChatSignatureResult> result = new ContractResult <WeChatSignatureResult>(); var signatureResult = GetJsApiTicket(appId, secretKey, noncestr, timestamp, pageUrl); if (signatureResult.ErrorCode != "0") { result.SetError(signatureResult.ErrorCode, signatureResult.ErrorMessage); return(result); } result.Data = new WeChatSignatureResult() { NonceStr = noncestr, Timestamp = timestamp, AppId = appId, Signature = signatureResult.Data }; return(result); }
/// <summary> /// 获取普通授权Token信息 /// </summary> /// <param name="appId"></param> /// <param name="appSecret">开发者密码</param> /// <returns></returns> public static ContractResult <string> GetAccessToken(string appId, string secretKey) { ContractResult <string> result = new ContractResult <string>(); var dictParam = new Dictionary <string, string> { { "secret", secretKey }, { "appid", $"{appId}" }, { "grant_type", "client_credential" } }; string accessTokenUrl = WeChatSettingsUtil.Settings.AccessTokenUrl; AccessTokenMpResult response = HttpClientUtil.GetResponse <AccessTokenMpResult>(accessTokenUrl, dictParam); if (response.ErrorCode != "0") { result.SetError(response.ErrorCode, response.ErrorMessage); return(result); } result.Data = response.Access_Token; return(result); }
private static string CreateGame(string playerOneJson) { var playerOne = CastPlayer(playerOneJson); bool operationResult; string error; TicTacToeGame game; if (playerOne == null) { operationResult = false; error = "Invalid Player JSON (" + playerOneJson + ")"; game = null; } else { operationResult = true; error = null; game = TicTacToeGame.NewTicTacToeGame(GetNextGameId(), playerOne); OpenGame(game); } return(ContractResult.NewContractResult(operationResult, error, game).Serialize().AsString()); }
/// <summary> /// 获取jsapi_ticket /// </summary> /// <param name="account">微信账户配置</param> /// <returns></returns> private static ContractResult <string> GetJsApiTicket(string appId, string secretKey) { ContractResult <string> result = new ContractResult <string>(); var tokenResult = AccessTokenUtil.GetAccessToken(appId, secretKey); if (tokenResult.ErrorCode != "0") { result.SetError(tokenResult.ErrorCode, tokenResult.ErrorMessage); return(result); } var apiUrl = $"{WeChatSettingsUtil.Settings.JSAPITicketApiUrl}&access_token={tokenResult.Data}"; JsApiTicketMpResult response = HttpClientUtil.GetResponse <JsApiTicketMpResult>(apiUrl); if (response.ErrorCode != 0) { result.SetError($"{response.ErrorCode}", response.ErrorMessage); return(result); } result.Data = response.Ticket; return(result); }
/// <summary> /// 在Action执行之前调用 /// </summary> /// <param name="context"></param> /// <returns></returns> public void OnActionExecuting(ActionExecutingContext context) { ContractResult result = new ContractResult(); IQueryCollection query = context.HttpContext.Request.Query; string appIdKey = query.Keys.FirstOrDefault(key => key.ToLower() == "appid"); string openIdKey = query.Keys.FirstOrDefault(key => key.ToLower() == "openid"); if (string.IsNullOrWhiteSpace(appIdKey)) { result.SetError(ErrorCodeType.NoAppId); context.Result = new JsonResult(result); _log.Debug($"【全局配置过滤器】请求参数:{JsonConvert.SerializeObject(query)}"); return; } if (string.IsNullOrWhiteSpace(openIdKey)) { result.SetError(ErrorCodeType.NoOpenId); context.Result = new JsonResult(result); _log.Debug($"【全局配置过滤器】请求参数:{JsonConvert.SerializeObject(query)}"); return; } var baseController = ((BaseController)context.Controller); baseController.AppId = query[appIdKey]; //公众号Id baseController.OpenId = query[openIdKey]; //用户的标识,对当前公众号唯一 baseController.Account = WeChatSettingsUtil.GetAccountConfig(baseController.AppId); if (baseController.Account == null) { result.SetError(ErrorCodeType.ConfigErr); context.Result = new JsonResult(result); _log.Debug($"【全局配置过滤器】请求参数:{JsonConvert.SerializeObject(query)}"); return; } }
/// <summary> /// Méthode interne d'enregistrement. /// </summary> /// <param name="treatment">Traitement évalué.</param> /// <param name="result">Résultat du traitement.</param> /// <param name="configuration">Configuration.</param> public abstract void Postback(ITreatment treatment, ContractResult result, TConfiguration configuration);
/// <summary> /// <see cref="ITreatmentRuler.Postback(ITreatment, ContractResult)" /> /// </summary> public void Postback(ITreatment treatment, ContractResult result) { Postback(treatment, result, GetConfiguration(treatment)); }
static void Main(string[] args) { #region Setup and Authentication var clientId = File.ReadAllText(clientIdFile); var secretKey = File.ReadAllText(secretKeyFile); var code = File.Exists(codeFile) ? File.ReadAllText(codeFile) : null; var authToken = File.Exists(tokenFile) ? JsonConvert.DeserializeObject <AuthToken>(File.ReadAllText(tokenFile)) : null; var api = new HFAPI(clientId, secretKey, authToken); if (authToken == null) { if (api.TryGetAuthToken(code, out authToken)) { File.WriteAllText(tokenFile, JsonConvert.SerializeObject(authToken)); api.SetAuthToken(authToken); } else { Console.WriteLine("Failed to acquire authentication token from code in file: " + codeFile); Console.WriteLine(authToken.ExceptionMessage); Console.WriteLine("Press any key to exit..."); Console.ReadKey(); Environment.Exit(1); } } #endregion //--------------------- Reads ------------------------- // Profile ProfileResult profile = api.ProfileRead(); AdvancedProfileResult AdvancedProfileRead = api.AdvancedProfileRead(); // Forums ForumResult ForumGet = api.ForumGet(2); // Threads ThreadResult ThreadGet = api.ThreadGet(6083735); // Automatically loads nested result types UserResult firstPostUser = ThreadGet.FirstPost.User; ThreadResult[] ThreadSearchByUserId = api.ThreadSearchByUserId(authToken.UserId, 55709, 3); // Posts PostResult PostGet = api.PostGet(59991944); PostResult[] PostSearchByThreadId = api.PostSearchByThreadId(6083735, 1, 2); PostResult[] PostSearchByUserId = api.PostSearchByUserId(55709, 1, 4); // Byte Transactions ByteTransactionResult[] ByteTransactionSearchByUserId = api.ByteTransactionSearchByUserId(55709, 1, 2); ByteTransactionResult[] ByteTransactionSearchByFromUserId = api.ByteTransactionSearchByFromUserId(55709, 1, 3); ByteTransactionResult[] ByteTransactionSearchByToUserId = api.ByteTransactionSearchByToUserId(55709, 1, 4); ByteTransactionResult ByteTransactionGet = api.ByteTransactionGet(ByteTransactionSearchByUserId.First().Id); // Contracts ContractResult[] ContractSearchByUserId = api.ContractSearchByUserId(55709, 1, 1); ContractResult ContractGet = api.ContractGet(ContractSearchByUserId.First().Id); //--------------------- Writes ------------------------- // ThreadResult createThread = api.ThreadCreate(375, "HFAPI.ThreadCreate Test", "Testing thread creation with my C# wrapper for the HF API."); }
private async Task <ContractResult> CreateContract(ContractInput input) { _logger.LogInformation( GetLogMessage( $@"Creating Contract For Contractor: {input.ContractorId} in Project: {input.ProjectId}")); var retVal = new ContractResult { }; var project = await _projectRepository.Queryable() .Include(x => x.CustomerAccount) .ThenInclude(x => x.OrganizationCustomer) .Include(x => x.Customer) .ThenInclude(x => x.OrganizationMarketer) .Include(x => x.OrganizationProjectManager) .Where(x => x.Id == input.ProjectId && x.ProjectManagerOrganizationId == input.ContractorOrganizationId) .FirstAsync(); if (project.Status == ProjectStatus.Paused || project.Status == ProjectStatus.Ended) { retVal.ErrorMessage = "Contracts cannot be added to inactive projects"; return(retVal); } var orgCustomer = _cuService.GetCustomerForProject <OrganizationCustomerOutput>(input.ProjectId); var providerOrganization = _organizationService.Repository.Queryable() .Include(x => x.ProviderOrganization) .Where(x => x.Id == input.ContractorOrganizationId).FirstAsync(); var orgAccountManager = _amService.GetAccountManagerForProject <OrganizationAccountManagerOutput>(input.ProjectId); var orgMarketer = project.Customer.OrganizationMarketer; var orgContractor = _coService.Repository.Queryable() .Include(x => x.Contractor) .ThenInclude(x => x.OrganizationRecruiter) .ThenInclude(x => x.Organization) .ThenInclude(x => x.RecruitingOrganization) .Include(x => x.Contractor) .ThenInclude(x => x.OrganizationRecruiter) .ThenInclude(x => x.Recruiter) .Where(x => x.ContractorId == input.ContractorId && x.OrganizationId == input.ContractorOrganizationId) .FirstAsync(); var recruiterStream = orgContractor.Result.Contractor.OrganizationRecruiter.RecruiterStream; await Task.WhenAll( orgCustomer, providerOrganization, orgAccountManager, orgContractor); var nextProviderContractId = await GetNextProviderContractId (input.ContractorOrganizationId); var nextMarketingContractId = await GetNextMarketingContractId (project.CustomerAccount.Customer.MarketerOrganizationId); var nextBuyerContractId = await GetNextBuyerContractId (orgCustomer.Result.OrganizationId); var recruitingAgencyStream = orgContractor.Result.Contractor .OrganizationRecruiter.Organization.RecruitingOrganization.RecruitingAgencyStream; var recruitingAgreement = await _recruitingAgreements.Queryable() .Where(x => x.RecruitingOrganizationId == orgContractor.Result.Contractor.RecruiterOrganizationId && x.ProviderOrganizationId == project.ProjectManagerOrganizationId && x.Status == AgreementStatus.Approved) .FirstOrDefaultAsync(); if (recruitingAgreement != null) { _logger.LogDebug( GetLogMessage("Recruiter agreement found, using agreement values for RE and RAO streams")); recruiterStream = recruitingAgreement.RecruiterStream; recruitingAgencyStream = recruitingAgreement.RecruitingAgencyStream; } else { _logger.LogDebug(GetLogMessage( "Recruiter agreement not found, using default values from recruiting org settings")); } if (orgContractor.Result.Contractor.RecruiterOrganizationId == providerOrganization.Result.Id) { _logger.LogDebug(GetLogMessage( "Recruiter organization is same as provider organization, setting RAO stream to 0")); recruitingAgencyStream = 0; } var contract = new Contract() .InjectFrom(input) as Contract; // init() contract.ProviderNumber = nextProviderContractId; contract.BuyerNumber = nextBuyerContractId; contract.RecruitingNumber = await GetNextRecruitingContractId (orgContractor.Result.Contractor.RecruiterOrganizationId); contract.MarketingNumber = nextMarketingContractId; // figure out implicit relationships contract.RecruiterOrganizationId = orgContractor.Result.Contractor.RecruiterOrganizationId; contract.RecruiterId = orgContractor.Result.Contractor.RecruiterId; contract.MarketerId = orgMarketer.MarketerId; contract.MarketerOrganizationId = orgMarketer.OrganizationId; contract.AccountManagerOrganizationId = orgAccountManager.Result.OrganizationId; contract.ProjectManagerOrganizationId = project.ProjectManagerOrganizationId; contract.ContractorOrganizationId = orgContractor.Result.OrganizationId; contract.CustomerId = project.CustomerId; contract.BuyerOrganizationId = project.CustomerOrganizationId; var agencyStream = providerOrganization.Result.ProviderOrganization.AgencyStream; var accountManagerStream = orgAccountManager.Result.AccountManagerStream; var projectManagerStream = project.OrganizationProjectManager.ProjectManagerStream; var marketingAgencyStream = project.CustomerAccount.MarketingAgencyStream; switch (project.Status) { case ProjectStatus.Pending: contract.Status = ContractStatus.Pending; break; case ProjectStatus.Active: contract.Status = ContractStatus.Active; break; } //if (project.CustomerAccount.IsInternal) //{ // contract.Status = ContractStatus.Active; // agencyStream = 0; // if (project.CustomerAccount.IsCorporate) // { // recruitingAgencyStream = 0; // accountManagerStream = 0; // projectManagerStream = 0; // marketingAgencyStream = 0; // } //} // determine streams contract.AgencyStream = agencyStream; contract.RecruitingAgencyStream = recruitingAgencyStream; contract.MarketingAgencyStream = marketingAgencyStream; contract.RecruiterStream = recruiterStream; contract.MarketerStream = project.CustomerAccount.MarketerStream; contract.AccountManagerStream = accountManagerStream; contract.ProjectManagerStream = projectManagerStream; contract.ContractorStream = orgContractor.Result.ContractorStream; contract.SystemStream = providerOrganization.Result.ProviderOrganization.SystemStream; contract.CreatedById = _userInfo.UserId; contract.UpdatedById = _userInfo.UserId; contract.AccountManagerId = orgAccountManager.Result.AccountManagerId; contract.ProjectManagerId = project.ProjectManagerId; contract.ObjectState = ObjectState.Added; contract.StatusTransitions.Add(new ContractStatusTransition() { Status = contract.Status, ObjectState = ObjectState.Added }); var result = Repository.Insert(contract, true); _logger.LogDebug(GetLogMessage("{0} Contract Records updated in database"), result); if (result > 0) { retVal.ContractId = contract.Id; retVal.Succeeded = true; await Task.Run(() => RaiseEvent(new ContractCreatedEvent() { ContractId = contract.Id })); } return(retVal); }