/// <summary>
        /// Executes the get cards invocation.
        /// </summary>
        public void Execute()
        {
            // get userid if its there
            Guid userId = Context[Key.GlobalUserId] == null ? Guid.Empty : (Guid)Context[Key.GlobalUserId];

            if (userId == Guid.Empty)
            {
                // no user specified so get all active cards
                ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary];
                resultSummary.SetResultCode(GetAllActiveCards());
            }
            else
            {
                SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));

                User user = sharedUserLogic.RetrieveUser();
                Context[Key.User] = user;
                ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary];
                if (user != null)
                {
                    resultSummary.SetResultCode(GetCards());
                }
                else
                {
                    resultSummary.SetResultCode(ResultCode.UnregisteredUser);
                }
            }
        }
        /// <summary>
        /// Executes the get redemption history invocation.
        /// </summary>
        public void Execute()
        {
            SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));

            User user = sharedUserLogic.RetrieveUser();

            Context[Key.User] = user;
            ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary];

            if (user != null)
            {
                RewardPrograms rewardProgram = (RewardPrograms)Context[Key.RewardProgramType];

                if ((rewardProgram & RewardPrograms.CardLinkOffers) == RewardPrograms.CardLinkOffers)
                {
                    resultSummary.SetResultCode(GetRedemptionHistory());
                }
                else if ((rewardProgram & RewardPrograms.EarnBurn) == RewardPrograms.EarnBurn)
                {
                    resultSummary.SetResultCode(GetEarnBurnHistory());
                }
            }
            else
            {
                resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser);
            }
        }
        /// <summary>
        /// Executes the distribute MSSV API invocation.
        /// </summary>
        public void Execute()
        {
            ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary];

            // Make sure the user exists.
            SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));

            if (sharedUserLogic.RetrieveUser() != null)
            {
                // Validate the distribution amount.
                decimal distributionAmount = (decimal)Context[Key.DistributionAmount];
                if (distributionAmount >= 0 && distributionAmount % 10 == 0)
                {
                    // Validate the voucher expiration date.
                    DateTime voucherExpiration = (DateTime)Context[Key.VoucherExpirationUtc];
                    DateTime utcNow            = DateTime.UtcNow;
                    if (voucherExpiration > utcNow && voucherExpiration <= utcNow + TimeSpan.FromDays(366))
                    {
                        // HTML encode user-submitted text to prevent script injection and then truncate to maximum length. (SQL injection is prevented through use of a
                        //  paramterized stored procedure.)
                        string notes = Context[Key.Notes] as string;
                        if (String.IsNullOrWhiteSpace(notes) == false)
                        {
                            notes = HttpUtility.HtmlEncode(notes);
                            if (notes.Length > MaxNotesLength)
                            {
                                notes = notes.Substring(0, MaxNotesLength);
                            }
                        }

                        // Submit the distribution request to the database.
                        ResultCode             result   = CommerceOperationsFactory.RedeemedDealOperations(Context).DistributeMssv();
                        DistributeMssvResponse response = (DistributeMssvResponse)Context[Key.Response];
                        response.RemainingFunds = (decimal)Context[Key.RemainingFunds];
                        resultSummary.SetResultCode(result);
                    }
                    else
                    {
                        resultSummary.SetResultCode(ResultCode.InvalidExpirationDate);
                    }
                }
                else
                {
                    resultSummary.SetResultCode(ResultCode.InvalidDistributionAmount);
                }
            }
            else
            {
                resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser);
            }
        }
        /// <summary>
        /// Executes the distribute MSSV API invocation.
        /// </summary>
        public void Execute()
        {
            ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary];

            // Make sure the user exists.
            SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));

            if (sharedUserLogic.RetrieveUser() != null)
            {
                ResultCode result = CommerceOperationsFactory.RedeemedDealOperations(Context).MssVoucherDistributionHistory();
                MssVoucherDistributionHistory history = (MssVoucherDistributionHistory)Context[Key.MssVoucherDistributionHistory];

                GetMssVoucherDistributionHistoryResponse response = (GetMssVoucherDistributionHistoryResponse)Context[Key.Response];
                response.AmountRemaining = (decimal)history.AmountRemaining / 100;

                List <DistributionHistoryDataContract> distributionHistoryList = new List <DistributionHistoryDataContract>();
                response.DistributionHistory = distributionHistoryList;
                foreach (DistributionHistory distributionHistoryItem in history.DistributionHistory)
                {
                    DistributionHistoryDataContract distributionHistoryItemDataContract = new DistributionHistoryDataContract
                    {
                        DistributionDate = distributionHistoryItem.DistributionDate,
                        Amount           = (decimal)distributionHistoryItem.Amount / 100,
                        Currency         = distributionHistoryItem.Currency,
                        ExpirationDate   = distributionHistoryItem.ExpirationDate
                    };
                    distributionHistoryList.Add(distributionHistoryItemDataContract);
                }

                List <TransactionHistoryDataContract> transactionHistoryList = new List <TransactionHistoryDataContract>();
                response.TransactionHistory = transactionHistoryList;
                foreach (TransactionHistory transactionHistoryItem in history.TransactionHistory)
                {
                    TransactionHistoryDataContract transactionHistoryItemDataContract = new TransactionHistoryDataContract
                    {
                        Business       = transactionHistoryItem.Business,
                        CreditStatus   = transactionHistoryItem.CreditStatus.ToString(),
                        PurchaseDate   = transactionHistoryItem.PurchaseDate,
                        DiscountAmount = (decimal)transactionHistoryItem.DiscountAmount / 100
                    };
                    transactionHistoryList.Add(transactionHistoryItemDataContract);
                }

                resultSummary.SetResultCode(result);
            }
            else
            {
                resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser);
            }
        }
        /// <summary>
        /// Executes the add referral type API invocation.
        /// </summary>
        public virtual void Execute()
        {
            SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));
            ResultSummary   resultSummary   = (ResultSummary)Context[Key.ResultSummary];

            if (sharedUserLogic.RetrieveUser() != null)
            {
                resultSummary.SetResultCode(CoreExecute());
            }
            else
            {
                resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser);
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Executes the get user's referrals API invocation.
        /// </summary>
        public void Execute()
        {
            SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));
            ResultSummary   resultSummary   = (ResultSummary)Context[Key.ResultSummary];

            if (sharedUserLogic.RetrieveUser() != null)
            {
                Context[Key.ReferrerId]   = Context[Key.GlobalUserId];
                Context[Key.ReferrerType] = ReferrerType.User;
                resultSummary.SetResultCode(GetUsersReferrals());
            }
            else
            {
                resultSummary.SetResultCode(ResultCode.UnexpectedUnregisteredUser);
            }
        }
Ejemplo n.º 7
0
        /// <summary>
        /// Executes the Remove card invocation.
        /// </summary>
        public async Task Execute()
        {
            try
            {
                SharedUserLogic sharedUserLogic = new SharedUserLogic(Context,
                                                                      CommerceOperationsFactory.UserOperations(Context));
                SharedCardLogic sharedCardLogic = new SharedCardLogic(Context,
                                                                      CommerceOperationsFactory.CardOperations(Context));
                RemoveCardConcluder removeCardConcluder = new RemoveCardConcluder(Context);

                User user = sharedUserLogic.RetrieveUser();
                Context[Key.User] = user;
                if (user != null)
                {
                    Card card = sharedCardLogic.RetrieveCard();
                    Context[Key.Card] = card;
                    if (card != null)
                    {
                        if (card.GlobalUserId == user.GlobalId)
                        {
                            Context.Log.Verbose("Attempting to remove the card from all current partners.");
                            RemoveCardInvoker removeCardInvoker = new RemoveCardInvoker(Context);
                            await removeCardInvoker.Invoke();
                        }
                        else
                        {
                            removeCardConcluder.Conclude(ResultCode.CardDoesNotBelongToUser);
                        }
                    }
                    else
                    {
                        removeCardConcluder.Conclude(ResultCode.UnregisteredCard);
                    }
                }
                else
                {
                    removeCardConcluder.Conclude(ResultCode.UnexpectedUnregisteredUser);
                }
            }
            catch (Exception ex)
            {
                ((ResultSummary)Context[Key.ResultSummary]).SetResultCode(ResultCode.UnknownError);
                RestResponder.BuildAsynchronousResponse(Context, ex);
            }
        }
        /// <summary>
        /// Executes the get claimed deals invocation.
        /// </summary>
        public void Execute()
        {
            SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));

            User user = sharedUserLogic.RetrieveUser();

            Context[Key.User] = user;
            ResultSummary resultSummary = (ResultSummary)Context[Key.ResultSummary];

            if (user != null)
            {
                resultSummary.SetResultCode(GetClaimedDeals());
            }
            else
            {
                resultSummary.SetResultCode(ResultCode.UnregisteredUser);
            }
        }
Ejemplo n.º 9
0
        /// <summary>
        /// Validates the user ID in the context.
        /// </summary>
        /// <param name="crud">
        /// The CRUD operation for which a token is being created.
        /// </param>
        /// <returns>
        /// The ResultCode corresponding to the result of the operation.
        /// </returns>
        /// <remarks>
        /// Authenticated user is automatically created within the system if necessary when validating the user ID in the
        /// context while obtaining a token for Create operations.
        /// </remarks>
        private ResultCode ValidateUserId(Crud crud)
        {
            ResultCode result = ResultCode.Success;

            // Attempt to retrieve the user.
            SharedUserLogic sharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));
            User            user            = sharedUserLogic.RetrieveUser();

            // If the user is null and the CRUD operation is Create, implicitly create the user.
            if (user == null)
            {
                if (crud == Crud.Create)
                {
                    if (Context.ContainsKey(Key.CorrelationId) == true)
                    {
                        Guid userId = (Guid)Context[Key.GlobalUserId];
                        user = new User(userId, Guid.NewGuid());
                        Context[Key.User] = user;
                        sharedUserLogic.AddUser();

                        // Update analytics.
                        Analytics.AddRegisterUserEvent(userId, user.AnalyticsEventId, (Guid)Context[Key.CorrelationId], Context[Key.ReferrerId] as string);

                        // Add referral, if any.
                        SharedReferralLogic sharedReferralLogic = new SharedReferralLogic(Context,
                                                                                          CommerceOperationsFactory.ReferralOperations(Context));
                        sharedReferralLogic.AddReferral((string)Context[Key.ReferredUserId]);
                    }
                    else
                    {
                        Context.Log.Warning("No correlation ID could be found in the context.");
                        result = ResultCode.ParameterCannotBeNull;
                    }
                }
                else
                {
                    result = ResultCode.UnexpectedUnregisteredUser;
                }
            }

            return(result);
        }
        /// <summary>
        ///     Executes processing of the request.
        /// </summary>
        public ResultCode Execute()
        {
            ResultCode                  result  = ResultCode.None;
            EndPointMessageRequest      request = (EndPointMessageRequest)Context[Key.Request];
            Dictionary <String, String> messageElementCollectionDictionary = new Dictionary <string, string>();

            foreach (MessageElementsCollection c in request.MessageElementsCollection)
            {
                messageElementCollectionDictionary.Add(c.Key, c.Value);
            }

            String requestType = messageElementCollectionDictionary[VisaEPMConstants.EventEventType];

            if (string.Equals(requestType, VisaEPMConstants.OnClearEventTypeValue, StringComparison.OrdinalIgnoreCase))
            {
                Dictionary <String, String> userDefinedFieldsCollectionDictionary = new Dictionary <string, string>();
                foreach (UserDefinedFieldsCollection c in request.UserDefinedFieldsCollection)
                {
                    userDefinedFieldsCollectionDictionary.Add(c.Key, c.Value);
                }

                String cardId     = request.CardId;
                String merchantId = messageElementCollectionDictionary[VisaEPMConstants.TransactionVisaMerchantId];
                String storeId    = messageElementCollectionDictionary[VisaEPMConstants.TransactionVisaStoreId];

                // Marshal the redeem deal request into a RedeemedDeal object.
                RedeemedDeal redeemedDeal = new RedeemedDeal()
                {
                    AnalyticsEventId = Guid.NewGuid()
                };
                Context[Key.RedeemedDeal] = redeemedDeal;

                redeemedDeal.CallbackEvent = RedemptionEvent.Settlement;
                redeemedDeal.PartnerRedeemedDealScopeId = messageElementCollectionDictionary[VisaEPMConstants.TransactionVipTransactionId];
                redeemedDeal.PartnerRedeemedDealId      =
                    messageElementCollectionDictionary[VisaEPMConstants.TransactionTransactionID];
                String time = messageElementCollectionDictionary[VisaEPMConstants.TransactionTimeStampYYMMDD];
                // UTC Time: 2013-12-05T07:25:06
                redeemedDeal.PurchaseDateTime = DateTime.Parse(time);
                redeemedDeal.PurchaseDateTime = DateTime.SpecifyKind(redeemedDeal.PurchaseDateTime, DateTimeKind.Utc);
                String amount = messageElementCollectionDictionary[VisaEPMConstants.TransactionClearingAmount];
                redeemedDeal.AuthorizationAmount = AmexUtilities.ParseAuthAmount(amount);
                redeemedDeal.Currency            = VisaConstants.CurrencyUSD;

                Context[Key.PartnerCardId]           = cardId;
                Context[Key.PartnerClaimedDealId]    = null; // could be the BingOfferDealId
                Context[Key.PartnerMerchantId]       = string.Format("{0};{1}", merchantId, storeId);
                Context[Key.OutletPartnerMerchantId] = null; // storedId;
                Context[Key.CreditStatus]            = CreditStatus.ClearingReceived;

                string merchantCity       = messageElementCollectionDictionary.NullIfNotExist(VisaEPMConstants.MerchantCityString);
                string merchantState      = messageElementCollectionDictionary.NullIfNotExist(VisaEPMConstants.MerchantStateString);
                var    merchantPostalCode = messageElementCollectionDictionary.NullIfNotExist(VisaEPMConstants.MerchantPostalCodeString);

                KeyTransactionData keyTransactionData = new KeyTransactionData
                {
                    MerchantCity       = merchantCity,
                    MerchantState      = merchantState,
                    MerchantPostalCode = merchantPostalCode
                };

                Context[Key.PartnerData] = keyTransactionData.XmlSerialize();

                LogRedeedmedDealRequestParameters(redeemedDeal);

                result = AddRedeemedDeal();
                Context[Key.ResultCode] = result;

                // If the deal was successfully redeemed, apply any applicable rewards.
                if (result == ResultCode.Created)
                {
                    RedeemedDealInfo redeemedDealInfo = (RedeemedDealInfo)Context[Key.RedeemedDealInfo];
                    if (redeemedDealInfo != null)
                    {
                        // Update analytics.
                        SharedUserLogic sharedUserLogic = new SharedUserLogic(Context,
                                                                              CommerceOperationsFactory.UserOperations(
                                                                                  Context));
                        Context[Key.GlobalUserId] = redeemedDealInfo.GlobalUserId;
                        User user = sharedUserLogic.RetrieveUser();
                        if (user != null)
                        {
                            Analytics.AddRedemptionEvent(redeemedDealInfo.GlobalUserId, redeemedDeal.AnalyticsEventId,
                                                         user.AnalyticsEventId,
                                                         redeemedDealInfo.ParentDealId, redeemedDealInfo.Currency,
                                                         redeemedDeal.AuthorizationAmount,
                                                         redeemedDealInfo.DiscountAmount,
                                                         redeemedDealInfo.GlobalId, (string)Context[Key.PartnerMerchantId]);
                        }

                        // Add rewards for any active rewards program.
                        AddRedemptionRewards();
                    }
                }
            }
            return(result);
        }
        /// <summary>
        /// Executes processing of the deal redemption request.
        /// </summary>
        public ResultCode Execute()
        {
            ResultCode result;

            // Marshal the First Data redeem deal request into a RedeemedDeal object.
            RedeemedDeal redeemedDeal = new RedeemedDeal()
            {
                AnalyticsEventId = Guid.NewGuid()
            };

            Context[Key.RedeemedDeal] = redeemedDeal;
            FirstData firstData = new FirstData(Context);

            firstData.MarshalRedeemDeal();

            // If the purchase date and time was valid, Add the RedeemedDeal to the data store.
            if (redeemedDeal.PurchaseDateTime != DateTime.MinValue)
            {
                string disallowedReason = Context[Key.DisallowedReason] as string;
                if (String.IsNullOrWhiteSpace(disallowedReason) == true)
                {
                    result = AddRedeemedDeal();
                }
                else
                {
                    Context.Log.Warning("Transaction is disallowed because tender type was: {0}.", disallowedReason);
                    Context[Key.RedeemedDealInfo] = new RedeemedDealInfo
                    {
                        PartnerDealId        = (string)Context[Key.PartnerDealId],
                        PartnerClaimedDealId = (string)Context[Key.PartnerClaimedDealId]
                    };
                    result = ResultCode.TransactionDisallowed;
                }
            }
            else
            {
                result = ResultCode.InvalidPurchaseDateTime;
            }

            // Build the response to send back to First Data based on the result of adding the RedeemedDeal.
            Context[Key.ResultCode] = result;
            firstData.BuildRedeemedDealResponse();

            // If the deal was successfully redeemed, send user notification and update analytics.
            if (result == ResultCode.Created)
            {
                RedeemedDealInfo redeemedDealInfo = (RedeemedDealInfo)Context[Key.RedeemedDealInfo];

                // Send notification.
                NotifyAuthorization notifyAuthorization = new NotifyAuthorization(Context);
                Task.Run(new Action(notifyAuthorization.SendNotification));

                // Update analytics.
                SharedUserLogic sharedUserLogic = new SharedUserLogic(Context,
                                                                      CommerceOperationsFactory.UserOperations(Context));
                Context[Key.GlobalUserId] = redeemedDealInfo.GlobalUserId;
                User user = sharedUserLogic.RetrieveUser();
                Analytics.AddRedemptionEvent(redeemedDealInfo.GlobalUserId, redeemedDeal.AnalyticsEventId, user.AnalyticsEventId,
                                             redeemedDealInfo.ParentDealId, redeemedDealInfo.Currency,
                                             redeemedDeal.AuthorizationAmount, redeemedDealInfo.DiscountAmount,
                                             redeemedDealInfo.GlobalId, (string)Context[Key.PartnerMerchantId]);
            }

            return(result);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Executes the Claim Deal API invocation.
        /// </summary>
        public async Task Execute()
        {
            try
            {
                SharedUserLogic sharedUserLogic = new SharedUserLogic(Context,
                                                                      CommerceOperationsFactory.UserOperations(Context));
                SharedCardLogic sharedCardLogic = new SharedCardLogic(Context,
                                                                      CommerceOperationsFactory.CardOperations(Context));
                SharedDealLogic sharedDealLogic = new SharedDealLogic(Context,
                                                                      CommerceOperationsFactory.DealOperations(Context));
                ClaimDealConcluder claimDealConcluder = new ClaimDealConcluder(Context);

                ResultCode extractionResult = ExtractClaimDealPayload();
                if (extractionResult == ResultCode.Success)
                {
                    Deal deal = sharedDealLogic.RetrieveDeal();
                    Context[Key.Deal] = deal;
                    if (deal != null)
                    {
                        Context[Key.DealDiscountSummary] = deal.DiscountSummary;
                        User user = sharedUserLogic.RetrieveUser();
                        Context[Key.User] = user;
                        if (user != null)
                        {
                            Card card = sharedCardLogic.RetrieveCard();
                            Context[Key.Card] = card;
                            if (card != null)
                            {
                                // If the deal and card have common ground, claim the deal for the card.
                                if (MustClaim(deal, card) == true)
                                {
                                    Context[Key.MerchantName] = deal.MerchantName;
                                    Context.Log.Verbose("Trying to claim the deal for the user with the appropriate partner.");
                                    ClaimDealInvoker claimDealInvoker = new ClaimDealInvoker(Context);
                                    await claimDealInvoker.Invoke();
                                }
                                else
                                {
                                    Context.Log.Verbose("It is not necessary to claim this deal for this card.");
                                    ((ResultSummary)Context[Key.ResultSummary]).SetResultCode(ResultCode.Success);
                                    RestResponder.BuildAsynchronousResponse(Context);
                                }
                            }
                            else
                            {
                                claimDealConcluder.Conclude(ResultCode.UnregisteredCard);
                            }
                        }
                        else
                        {
                            claimDealConcluder.Conclude(ResultCode.UnexpectedUnregisteredUser);
                        }
                    }
                    else
                    {
                        claimDealConcluder.Conclude(ResultCode.UnactionableDealId);
                    }
                }
                else
                {
                    claimDealConcluder.Conclude(extractionResult);
                }
            }
            catch (Exception ex)
            {
                ((ResultSummary)Context[Key.ResultSummary]).SetResultCode(ResultCode.UnknownError);
                RestResponder.BuildAsynchronousResponse(Context, ex);
            }
        }
Ejemplo n.º 13
0
 /// <summary>
 /// Initializes a new instance of the AddCardExecutor class.
 /// </summary>
 /// <param name="context">
 /// The context to use while processing the request.
 /// </param>
 public AddCardExecutor(CommerceContext context)
 {
     Context         = context;
     SharedUserLogic = new SharedUserLogic(Context, CommerceOperationsFactory.UserOperations(Context));
 }
Ejemplo n.º 14
0
        /// <summary>
        /// Places the User object representing the person making this request to the context.
        /// </summary>
        /// <returns>
        /// The ResultCode corresponding to the result of the operation.
        /// </returns>
        /// <remarks>
        /// If flagged to do so, a user account will be created and associated with the specified e-mail address, if the e-mail
        /// address has not already been used.
        /// </remarks>
        private ResultCode PlaceUserInContext()
        {
            ResultCode result = ResultCode.Success;

            bool createUnauthenticatedAccount = false;

            if (Context[Key.CreateUnauthenticatedAccount] != null)
            {
                createUnauthenticatedAccount = (bool)Context[Key.CreateUnauthenticatedAccount];
            }

            if (createUnauthenticatedAccount == true)
            {
                string emailAddress = Context[Key.EmailAddress] as string;
                if (String.IsNullOrWhiteSpace(emailAddress) == false)
                {
                    try
                    {
                        // Ensure the e-mail address may be valid.
                        MailAddress mailAddress = new MailAddress(emailAddress);

                        // Attempt to add a user to User Services via Users Dal and obtain its authentication vector.
                        IUsersDal usersDal = PartnerFactory.UsersDal(Context.Config);
                        Users.Dal.DataModel.User fullUser = usersDal.CreateUnauthenticatedUser(mailAddress.Address, (string)Context[Key.ReferrerId],
                                                                                               (string)Context[Key.UserLocation]);
                        UnauthenticatedAddCardResponse response = (UnauthenticatedAddCardResponse)Context[Key.Response];
                        if (String.IsNullOrWhiteSpace(fullUser.MsId) == true)
                        {
                            response.AuthenticationVector = AuthenticationVector.Email.ToString();
                        }
                        else if (fullUser.MsId.StartsWith("FB-", StringComparison.OrdinalIgnoreCase) == true)
                        {
                            response.AuthenticationVector = AuthenticationVector.Facebook.ToString();
                        }
                        else
                        {
                            response.AuthenticationVector = AuthenticationVector.MicrosoftAccount.ToString();
                        }

                        Guid userId = fullUser.Id;
                        Context[Key.GlobalUserId] = userId;

                        // If the user returned by User Services has not already been registered in the Commerce system, register a new Commerce user.
                        User user = SharedUserLogic.RetrieveUser();
                        if (user == null)
                        {
                            user = new User(userId, Guid.NewGuid());
                            Context[Key.User] = user;
                            result            = SharedUserLogic.AddUser();

                            if (result == ResultCode.Created)
                            {
                                Analytics.AddRegisterUserEvent(user.GlobalId, user.AnalyticsEventId, Guid.Empty, Context[Key.ReferrerId] as string);
                                result = ResultCode.Success;
                            }
                        }
                        else
                        {
                            Context[Key.User] = user;
                        }

                        // If the user was added or retrieved successfully, proceed.
                        if (result == ResultCode.Success)
                        {
                            // If the user has not already signed up officially with Bing Offers, proceed.
                            if (response.AuthenticationVector == AuthenticationVector.Email.ToString())
                            {
                                // If the user has not already added a card, proceed.
                                SharedCardLogic sharedCardLogic = new SharedCardLogic(Context, CommerceOperationsFactory.CardOperations(Context));
                                if (sharedCardLogic.RetrieveUserCards().Count() == 0)
                                {
                                    response.ActivationToken = fullUser.ActivationToken;
                                }
                                else
                                {
                                    result = ResultCode.UnauthenticatedUserAlreadyExists;
                                }
                            }
                            else
                            {
                                result = ResultCode.UserAlreadyExists;
                            }
                        }
                    }
                    catch (FormatException)
                    {
                        result = ResultCode.InvalidParameter;
                    }
                }
                else
                {
                    result = ResultCode.ParameterCannotBeNull;
                }
            }
            else
            {
                Context[Key.User] = SharedUserLogic.RetrieveUser();
            }

            return(result);
        }