예제 #1
0
        public virtual void OnError(Exception error)
        {
            var logData = MultiLogger.GetBaseLoggingData();

            logData.AddCategory("Monitors");
            MultiLogHelper.Error <MonitorBase <T> >("Monitor error: ", error, logData);
        }
예제 #2
0
        /// <summary>
        /// Does the actual work of sending the <see cref="IFormattedNotificationMessage"/>
        /// </summary>
        /// <param name="message">The <see cref="IFormattedNotificationMessage"/> to be sent</param>
        public override void PerformSend(IFormattedNotificationMessage message)
        {
            if (!message.Recipients.Any())
            {
                return;
            }

            var msg = new MailMessage
            {
                From       = new MailAddress(message.From),
                Subject    = message.Name,
                Body       = message.BodyText,
                IsBodyHtml = true
            };

            MultiLogHelper.Info <SmtpNotificationGatewayMethod>("Sending an email to " + string.Join(", ", message.Recipients));

            foreach (var to in message.Recipients)
            {
                if (!string.IsNullOrEmpty(to))
                {
                    msg.To.Add(new MailAddress(to));
                }
            }

            // Event raised to allow further modification to msg (like attachments)
            Sending.RaiseEvent(new ObjectEventArgs <MailMessage>(msg), this);

            this.Send(msg);
        }
        /// <summary>
        /// Creates a line item of a particular type for a shipment rate quote
        /// </summary>
        /// <typeparam name="T">The type of the line item to create</typeparam>
        /// <param name="shipmentRateQuote">The <see cref="ShipmentRateQuote"/> to be translated to a line item</param>
        /// <returns>A <see cref="LineItemBase"/> of type T</returns>
        public static T AsLineItemOf <T>(this IShipmentRateQuote shipmentRateQuote) where T : LineItemBase
        {
            var extendedData = new ExtendedDataCollection();

            extendedData.AddShipment(shipmentRateQuote.Shipment);

            var ctrValues = new object[]
            {
                EnumTypeFieldConverter.LineItemType.Shipping.TypeKey,
                shipmentRateQuote.ShipmentLineItemName(),
                shipmentRateQuote.ShipMethod.ServiceCode,     // TODO this may not be unique (SKU) once multiple shipments are exposed
                1,
                shipmentRateQuote.Rate,
                extendedData
            };

            var attempt = ActivatorHelper.CreateInstance <LineItemBase>(typeof(T), ctrValues);

            if (attempt.Success)
            {
                return(attempt.Result as T);
            }

            MultiLogHelper.Error <ILineItem>("Failed instiating a line item from shipmentRateQuote", attempt.Exception);

            throw attempt.Exception;
        }
        public virtual ActionResult Register(NewMemberModel model)
        {
            if (!ModelState.IsValid)
            {
                return(CurrentUmbracoPage());
            }

            var logData = new ExtendedLoggerData();

            logData.AddCategory("Merchello");
            logData.AddCategory("FastTrack");

            var registerModel = Members.CreateRegistrationModel(model.MemberTypeAlias);

            registerModel.Name            = model.Email;
            registerModel.Email           = model.Email;
            registerModel.Password        = model.Password;
            registerModel.Username        = model.Email;
            registerModel.UsernameIsEmail = true;

            var fn = new UmbracoProperty {
                Alias = "firstName", Name = "First Name", Value = model.FirstName
            };
            var ln = new UmbracoProperty {
                Alias = "lastName", Name = "Last Name", Value = model.LastName
            };

            registerModel.MemberProperties.Add(fn);
            registerModel.MemberProperties.Add(ln);

            MembershipCreateStatus status;

            //// Add a message for the attempt
            MultiLogHelper.Info <CustomerMembershipController>("Registering a new member", logData);

            var member = Members.RegisterMember(registerModel, out status, model.PersistLogin);


            var registration = NewMemberModelFactory.Create(model, status);

            if (registration.ViewData.Success)
            {
                var membership = _memberService.GetByEmail(model.Email);

                if (member != null)
                {
                    _memberService.AssignRole(membership.Id, "Customers");
                    _memberService.Save(membership);
                }

                return(model.SuccessRedirectUrl.IsNullOrWhiteSpace()
                           ? Redirect("/")
                           : Redirect(model.SuccessRedirectUrl));
            }
            else
            {
                ViewData["MerchelloViewData"] = model.ViewData;
                return(CurrentUmbracoPage());
            }
        }
        /// <summary>
        /// Handles an add item operation exception.
        /// </summary>
        /// <param name="model">
        /// The <see cref="IAddItemModel"/>.
        /// </param>
        /// <param name="ex">
        /// The <see cref="Exception"/>.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        protected virtual ActionResult HandleAddItemException(TAddItem model, Exception ex)
        {
            var logData = MultiLogger.GetBaseLoggingData();

            MultiLogHelper.Error <BasketControllerBase <TBasketModel, TBasketItemModel, TAddItem> >("Failed to add item to the basket", ex, logData);
            throw ex;
        }
예제 #6
0
        public HttpResponseMessage PutInvoiceAdjustments(InvoiceAdjustmentDisplay adjustments)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);

            try
            {
                var invoice = _invoiceService.GetByKey(adjustments.InvoiceKey);

                if (invoice != null)
                {
                    var invoiceItems = adjustments.Items.Select(x => x.ToInvoiceLineItem());

                    var success = ((InvoiceService)_invoiceService).AdjustInvoice(invoice, invoiceItems.ToArray());

                    if (success)
                    {
                        return(response);
                    }

                    return(Request.CreateResponse(HttpStatusCode.InternalServerError, "Did not successfully adjust invoice"));
                }

                response = Request.CreateResponse(HttpStatusCode.NotFound, "Invoice not found");
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error <InvoiceApiController>("Failed to adjust invoice", ex);
                response = Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("{0}", ex.Message));
            }


            return(response);
        }
예제 #7
0
        /// <summary>
        /// Deletes the invoice on cancel.
        /// </summary>
        /// <param name="invoiceKey">
        /// The invoice key.
        /// </param>
        /// <param name="paymentKey">
        /// The payment key.
        /// </param>
        /// <returns>
        /// The <see cref="PayPalProviderSettings"/>.
        /// </returns>
        private PayPalProviderSettings EnsureDeleteInvoiceOnCancel(Guid invoiceKey, Guid paymentKey)
        {
            var provider = GatewayContext.Payment.GetProviderByKey(Merchello.Providers.Constants.PayPal.GatewayProviderSettingsKey);
            var settings = provider.ExtendedData.GetPayPalProviderSettings();

            if (settings.DeleteInvoiceOnCancel)
            {
                // validate that this invoice should be deleted
                var invoice = MerchelloServices.InvoiceService.GetByKey(invoiceKey);

                var payments = invoice.Payments().ToArray();

                // we don't want to delete if there is more than one payment
                if (payments.Count() <= 1)
                {
                    // Assert the payment key matches - this is to ensure that the
                    // payment matches the invoice
                    var ensure = payments.All(x => x.Key == paymentKey) || !payments.Any();
                    if (ensure && invoice.InvoiceStatus.Key == Core.Constants.InvoiceStatus.Unpaid)
                    {
                        MultiLogHelper.Info <PayPalExpressPaymentController>(string.Format("Deleted invoice number {0} to prevent duplicate. PayPal ACK response not success", invoice.PrefixedInvoiceNumber()));
                        MerchelloServices.InvoiceService.Delete(invoice);
                    }
                }
            }

            return(settings);
        }
예제 #8
0
        /// <summary>
        /// The convert data to source.
        /// </summary>
        /// <param name="propertyType">
        /// The property type.
        /// </param>
        /// <param name="source">
        /// The source.
        /// </param>
        /// <param name="preview">
        /// The preview.
        /// </param>
        /// <returns>
        /// The <see cref="object"/>.
        /// </returns>
        public override object ConvertDataToSource(PublishedPropertyType propertyType, object source, bool preview)
        {
            var merchello = new MerchelloHelper();

            if (source == null)
            {
                return(null);
            }

            var collectionKey = source.ToString();

            if (collectionKey.IsNullOrWhiteSpace())
            {
                var query = merchello.ProductContentQuery().Page(1).ItemsPerPage(10).OrderBy(ProductSortField.Name);

                //var defaultCollection = merchello.Query.Product.TypedProductContentSearch(1, 10);

                return(new ProductContentListView(Guid.Empty, query.Execute().Items));
            }

            try
            {
                var key = new Guid(collectionKey);

                var query = merchello.ProductContentQuery().Page(1).ItemsPerPage(long.MaxValue).ConstrainByCollectionKey(key);

                return(new ProductContentListView(key, query.Execute().Items));
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error <ProductListViewValueConverter>("Failed to Convert Merchello.ProductListView property", ex);
                return(null);
            }
        }
        /// <summary>
        /// Gets a safe list of customer temp data (asserts the version key).
        /// </summary>
        /// <param name="key">
        /// The key or alias.
        /// </param>
        /// <returns>
        /// The <see cref="List{String}"/>.
        /// </returns>
        protected virtual List <string> BuildVersionedCustomerTempData(string key)
        {
            var data          = new List <string>();
            var queueDataJson = Context.Customer.ExtendedData.GetValue(key);

            if (string.IsNullOrEmpty(queueDataJson))
            {
                return(data);
            }

            try
            {
                var savedData = JsonConvert.DeserializeObject <CheckoutCustomerTempData>(queueDataJson);

                // verify that the offer codes are for this version of the checkout
                if (savedData.VersionKey != Context.VersionKey)
                {
                    return(data);
                }

                data.AddRange(savedData.Data);
            }
            catch (Exception ex)
            {
                // don't throw an exception here as the customer is in the middle of a checkout.
                MultiLogHelper.Error <CheckoutCustomerDataManagerBase>("Failed to deserialize CheckoutCustomerTempData.  Returned empty offer code list instead.", ex);
            }

            return(data);
        }
예제 #10
0
        /// <summary>
        /// Initializes the controller.
        /// </summary>
        private void Initialize()
        {
            var provider = GatewayContext.Payment.GetProviderByKey(Constants.PayPal.GatewayProviderSettingsKey);

            if (provider == null)
            {
                var nullRef =
                    new NullReferenceException(
                        "PayPalPaymentGatewayProvider is not activated or has not been resolved.");
                MultiLogHelper.Error <PayPalExpressApiController>(
                    "Failed to find active PayPalPaymentGatewayProvider.",
                    nullRef,
                    GetExtendedLoggerData());

                throw nullRef;
            }

            _paymentMethod = provider.GetPaymentGatewayMethodByPaymentCode(Constants.PayPal.PaymentCodes.ExpressCheckout) as PayPalExpressCheckoutPaymentGatewayMethod;

            if (_paymentMethod == null)
            {
                var nullRef = new NullReferenceException("PayPalExpressCheckoutPaymentGatewayMethod could not be instantiated");
                MultiLogHelper.Error <PayPalExpressApiController>("PayPalExpressCheckoutPaymentGatewayMethod was null", nullRef, GetExtendedLoggerData());

                throw nullRef;
            }
        }
        public HttpResponseMessage PostAssociateEntityWithFilters(Entity2FilterCollectionsModel model)
        {
            var collections = _entityCollectionService.GetAll(model.CollectionKeys).ToArray();

            foreach (var collection in collections)
            {
                var provider   = collection.ResolveProvider();
                var entityType = provider.EntityCollection.EntityType;
                switch (entityType)
                {
                case EntityType.Customer:
                    var noCustomer = new NotImplementedException("Customer filters not implemented");
                    return(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, noCustomer));

                case EntityType.Invoice:
                    var noInvoice = new NotImplementedException("Invoice filters not implemented");
                    return(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, noInvoice));

                case EntityType.Product:
                    MerchelloContext.Services.ProductService.AddToCollection(model.EntityKey, collection.Key);
                    break;

                default:
                    var invalid =
                        new InvalidOperationException("Merchello service could not be found for the entity type");
                    MultiLogHelper.Error <EntityCollectionApiController>("An attempt was made to add an entity to a collection", invalid);
                    return(Request.CreateErrorResponse(HttpStatusCode.NotImplemented, invalid));
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
예제 #12
0
        /// <summary>
        /// Gets the base website url for constructing PayPal response URLs.
        /// </summary>
        /// <returns>
        /// The <see cref="string"/>.
        /// </returns>
        public static string GetBaseWebsiteUrl()
        {
            var websiteUrl = string.Empty;

            try
            {
                var url = HttpContext.Current.Request.Url;
                websiteUrl =
                    string.Format(
                        "{0}://{1}{2}",
                        url.Scheme,
                        url.Host,
                        url.IsDefaultPort ? string.Empty : ":" + url.Port).EnsureNotEndsWith('/');
            }
            catch (Exception ex)
            {
                var logData = MultiLogger.GetBaseLoggingData();
                logData.AddCategory("PayPal");

                MultiLogHelper.WarnWithException(
                    typeof(PayPalApiHelper),
                    "Failed to initialize factory setting for WebsiteUrl.  HttpContext.Current.Request is likely null.",
                    ex,
                    logData);
            }

            return(websiteUrl);
        }
예제 #13
0
        /// <summary>
        /// Try to apply the award
        /// </summary>
        /// <param name="validatedAgainst">
        /// The validated against.
        /// </param>
        /// <param name="customer">
        /// The customer.
        /// </param>
        /// <returns>
        /// The <see cref="Attempt"/>.
        /// </returns>
        public Attempt <object> TryAward(object validatedAgainst, ICustomerBase customer)
        {
            if (!this.IsInitialized)
            {
                return(Attempt <object> .Fail(new OfferRedemptionException("Offer processor not initialized.")));
            }

            try
            {
                var reward    = _reward as OfferRewardComponentBase <TConstraint, TAward>;
                var converted = validatedAgainst.TryConvertTo <TConstraint>();
                if (converted.Success)
                {
                    if (reward == null)
                    {
                        return(Attempt <object> .Fail(new NullReferenceException("Converted reward was null")));
                    }

                    var rewardAttempt = reward.TryAward(converted.Result, customer);

                    return(!rewardAttempt.Success ?
                           Attempt <object> .Fail(rewardAttempt.Result, rewardAttempt.Exception) :
                           Attempt <object> .Succeed(rewardAttempt.Result));
                }

                MultiLogHelper.Error(typeof(OfferProcessorBase <TConstraint, TAward>), "Failed to convert validation object", converted.Exception);
                throw converted.Exception;
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error(typeof(OfferProcessorBase <TConstraint, TAward>), "Failed to convert reward type", ex);
                throw;
            }
        }
예제 #14
0
        public virtual void OnCompleted()
        {
            var logData = MultiLogger.GetBaseLoggingData();

            logData.AddCategory("Monitors");
            MultiLogHelper.Debug <MonitorBase <T> >(string.Format("Completed monitoring {0}", GetType()), logData);
        }
        /// <summary>
        /// Builds the <see cref="IOfferProcessor"/>
        /// </summary>
        /// <param name="offer">
        /// The offer.
        /// </param>
        /// <returns>
        /// The <see cref="IOfferProcessor"/>.
        /// </returns>
        public IOfferProcessor Build(OfferBase offer)
        {
            var constraints = offer.Constraints;

            var constraintsType = offer.Reward.TypeGrouping;
            var rewardType      = offer.Reward.RewardType;

            var chainType =
                _instanceTypes.FirstOrDefault(
                    x => x.GetCustomAttribute <OfferConstraintChainForAttribute>(false).ConstraintType == constraintsType &&
                    x.GetCustomAttribute <OfferConstraintChainForAttribute>(false).RewardType == rewardType);

            if (chainType == null)
            {
                return(null);
            }


            var ctrArgs = new object[] { };
            var attempt = ActivatorHelper.CreateInstance <IOfferProcessor>(chainType, ctrArgs);

            if (!attempt.Success)
            {
                MultiLogHelper.Error <OfferProcessorFactory>("Failed to create instance of " + chainType.Name, attempt.Exception);
                return(null);
            }

            // initialize the processor
            attempt.Result.Initialize(constraints, offer.Reward);

            return(attempt.Result);
        }
예제 #16
0
        public HttpResponseMessage PutInvoiceShippingAddress(InvoiceShippingUpdateData data)
        {
            var response = Request.CreateResponse(HttpStatusCode.OK);

            try
            {
                var invoice           = _invoiceService.GetByKey(data.InvoiceKey);
                var shippingLineItems = invoice.ShippingLineItems().ToArray();
                if (shippingLineItems.Any())
                {
                    foreach (var lineItem in shippingLineItems)
                    {
                        lineItem.ExtendedData.AddAddress(data.Address.ToAddress(), Constants.ExtendedDataKeys.ShippingDestinationAddress);
                    }
                }
                else
                {
                    // Problem. There is no shipping line item when there should be! Needs more investigating as this does very, very occasionally happen
                    MultiLogHelper.Warn <InvoiceApiController>(string.Format("No shipping address line item when trying to save shipping address for {0}", invoice.PrefixedInvoiceNumber()));
                }

                _invoiceService.Save(invoice);
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error <InvoiceApiController>("Failed to save shipping address", ex);
                response = Request.CreateResponse(HttpStatusCode.NotFound, string.Format("{0}", ex.Message));
            }

            return(response);
        }
        /// <summary>
        /// Deletes a product option
        /// </summary>
        /// <param name="option">
        /// The option to be deleted
        /// </param>
        /// <param name="raiseEvents">
        /// Optional boolean indicating whether or not to raise events.
        /// </param>
        /// <remarks>
        /// This performs a check to ensure the option is valid to be deleted
        /// </remarks>
        public void Delete(IProductOption option, bool raiseEvents = true)
        {
            if (!EnsureSafeOptionDelete(option))
            {
                MultiLogHelper.Warn <ProductOptionService>("A ProductOption delete attempt was aborted.  The option cannot be deleted due to it being shared with one or more products.");
                return;
            }

            if (raiseEvents)
            {
                if (Deleting.IsRaisedEventCancelled(new DeleteEventArgs <IProductOption>(option), this))
                {
                    ((ProductOption)option).WasCancelled = true;
                    return;
                }
            }

            using (new WriteLock(Locker))
            {
                var uow = UowProvider.GetUnitOfWork();
                using (var repository = RepositoryFactory.CreateProductOptionRepository(uow))
                {
                    repository.Delete(option);
                    uow.Commit();
                }
            }

            if (raiseEvents)
            {
                Deleted.RaiseEvent(new DeleteEventArgs <IProductOption>(option), this);
            }
        }
예제 #18
0
        /// <summary>
        /// Creates a <see cref="ICheckoutSummaryModel{TBillingAddress, TShippingAddress, TLineItem}"/>.
        /// </summary>
        /// <param name="checkoutManager">
        /// The <see cref="ICheckoutManagerBase"/>.
        /// </param>
        /// <returns>
        /// The <see cref="ICheckoutSummaryModel{TBillingAddress, TShippingAddress, TLineItem}"/>.
        /// </returns>
        public TSummary Create(ICheckoutManagerBase checkoutManager)
        {
            if (!checkoutManager.Payment.IsReadyToInvoice())
            {
                var logData   = MultiLogger.GetBaseLoggingData();
                var invalidOp = new InvalidOperationException("CheckoutManager is not ready to invoice. Try calling the overloaded Create method passing the IBasket");
                MultiLogHelper.Error <CheckoutSummaryModelFactory <TSummary, TBillingAddress, TShippingAddress, TLineItem> >("Could not create checkout summary", invalidOp, logData);
                throw invalidOp;
            }

            var invoice = checkoutManager.Payment.PrepareInvoice();

            var billing  = invoice.GetBillingAddress();
            var shipping = invoice.GetShippingAddresses().FirstOrDefault();


            return(new TSummary
            {
                BillingAddress = Create <TBillingAddress>(billing ?? new Address {
                    AddressType = AddressType.Billing
                }),
                ShippingAddress = Create <TShippingAddress>(shipping ?? new Address {
                    AddressType = AddressType.Shipping
                }),
                Items = invoice.Items.Select(Create),
                Total = invoice.Total
            });
        }
예제 #19
0
        /// <summary>
        /// Creates an instance of an Umbraco Surface controller from scratch
        /// when no existing ControllerContext is present
        /// </summary>
        /// <param name="routeData">
        /// The route Data.
        /// </param>
        /// <typeparam name="T">
        /// Type of the controller to create
        /// </typeparam>
        /// <returns>
        /// A surface controller of type T
        /// </returns>
        public static T CreateSurfaceController <T>(RouteData routeData = null)
            where T : SurfaceController
        {
            // Create an MVC Controller Context
            var umbracoContext = GetUmbracoContext();

            var umbracoHelper = new UmbracoHelper(umbracoContext);

            var attempt = ActivatorHelper.CreateInstance <T>(typeof(T), new object[] { umbracoContext, umbracoHelper });

            if (!attempt.Success)
            {
                var data = MultiLogger.GetBaseLoggingData();
                data.AddCategory("SurfaceController");
                MultiLogHelper.Error <SurfaceControllerActivationHelper>("Failed to create render controller", attempt.Exception, data);
                throw attempt.Exception;
            }

            var controller = attempt.Result;

            if (routeData == null)
            {
                routeData = new RouteData();
            }

            if (!routeData.Values.ContainsKey("controller") && !routeData.Values.ContainsKey("Controller"))
            {
                routeData.Values.Add(
                    "controller",
                    controller.GetType().Name.ToLower().Replace("controller", string.Empty));
            }

            controller.ControllerContext = new ControllerContext(umbracoContext.HttpContext, routeData, controller);
            return(controller);
        }
        /// <summary>
        /// Maps the <see cref="OfferComponentDefinition"/> to a <see cref="OfferComponentConfiguration"/> so
        /// that it can be serialized and saved to the database as JSON more easily.
        /// </summary>
        /// <param name="definition">
        /// The definition.
        /// </param>
        /// <returns>
        /// The <see cref="OfferComponentConfiguration"/>.
        /// </returns>
        internal static OfferComponentConfiguration AsOfferComponentConfiguration(this OfferComponentDefinition definition)
        {
            if (!OfferComponentResolver.HasCurrent)
            {
                throw new NullReferenceException("The OfferComponentResolver singleton has not been instantiated");
            }

            var type = OfferComponentResolver.Current.GetTypeByComponentKey(definition.ComponentKey);

            if (type != null)
            {
                return(new OfferComponentConfiguration()
                {
                    OfferSettingsKey = definition.OfferSettingsKey,
                    OfferCode = definition.OfferCode,
                    ComponentKey = definition.ComponentKey,
                    TypeFullName = type.FullName,
                    Values = definition.ExtendedData.AsEnumerable().ToArray()
                });
            }

            var nullRef = new NullReferenceException("Was not able to resolve the OfferComponentType with key: " + definition.ComponentKey);

            MultiLogHelper.Error(typeof(OfferComponentDefinitionExtensions), "Unable to resolve OfferCompoent", nullRef);
            throw nullRef;
        }
예제 #21
0
        /// <summary>
        /// Builds the <see cref="AddressType"/>.
        /// </summary>
        /// <param name="address">
        /// The address.
        /// </param>
        /// <returns>
        /// The <see cref="AddressType"/>.
        /// </returns>
        public AddressType Build(IAddress address)
        {
            try
            {
                return(new AddressType
                {
                    Name = address.Name,
                    Street1 = address.Address1,
                    Street2 = address.Address2,
                    PostalCode = address.PostalCode,
                    CityName = address.Locality,
                    StateOrProvince = address.Region,
                    CountryName = address.Country().Name,
                    Country =
                        (CountryCodeType)
                        Enum.Parse(typeof(CountryCodeType), address.Country().CountryCode, true),
                    Phone = address.Phone
                });
            }
            catch (Exception ex)
            {
                var logData = MultiLogger.GetBaseLoggingData();
                logData.AddCategory("PayPal");

                MultiLogHelper.Error <PayPalBasicAmountTypeFactory>("Failed to build an AddressType", ex, logData);

                throw;
            }
        }
예제 #22
0
        public CustomerItemCacheDisplay GetCustomerItemCache(Guid customerKey, ItemCacheType itemCacheType)
        {
            if (itemCacheType != ItemCacheType.Basket && itemCacheType != ItemCacheType.Wishlist)
            {
                var notSupported = new NotSupportedException("Basket and Wishlist are the only supported item caches");
                LogHelper.Error <CustomerApiController>("Unsupported item cache type", notSupported);
                throw notSupported;
            }

            var customer = _customerService.GetAnyByKey(customerKey);

            if (customer == null)
            {
                throw new NullReferenceException("customer for customer key was null");
            }

            if (itemCacheType == ItemCacheType.Wishlist && customer.IsAnonymous)
            {
                var invalid =
                    new InvalidOperationException(
                        "Wishlists are not supported with anonymous customers.  The customer key passed returned an anonymous customer.");
                MultiLogHelper.Error <CustomerApiController>("Could not retrieve customer wish list", invalid);
                throw invalid;
            }

            return(itemCacheType == ItemCacheType.Basket ?
                   ((Basket)customer.Basket()).ItemCache.ToCustomerItemCacheDisplay() :
                   ((WishList)((Customer)customer).WishList()).ItemCache.ToCustomerItemCacheDisplay());
        }
        public HttpResponseMessage DeleteEntityFromCollection(Entity2CollectionModel model)
        {
            var collection = _entityCollectionService.GetByKey(model.CollectionKey);

            if (collection == null)
            {
                return(Request.CreateResponse(HttpStatusCode.NotFound));
            }

            var provider   = collection.ResolveProvider();
            var entityType = provider.EntityCollection.EntityType;

            switch (entityType)
            {
            case EntityType.Customer:
                MerchelloContext.Services.CustomerService.RemoveFromCollection(model.EntityKey, model.CollectionKey);
                break;

            case EntityType.Invoice:
                MerchelloContext.Services.InvoiceService.RemoveFromCollection(model.EntityKey, model.CollectionKey);
                break;

            case EntityType.Product:
                MerchelloContext.Services.ProductService.RemoveFromCollection(model.EntityKey, model.CollectionKey);
                break;

            default:
                var invalid =
                    new InvalidOperationException("Merchello service could not be found for the entity type");
                MultiLogHelper.Error <EntityCollectionApiController>("An attempt was made to remove an entity to a collection", invalid);
                return(Request.CreateResponse(HttpStatusCode.NotImplemented));
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
예제 #24
0
        public async Task <HttpResponseMessage> RecordDomain(MigrationDomain record)
        {
            var setting = _storeSettingService.GetByKey(Constants.StoreSetting.HasDomainRecordKey);

            if (setting != null && setting.Value == "False")
            {
                try
                {
                    var migrationManager = new WebMigrationManager(UmbracoContext.Application);
                    var response         = await migrationManager.PostDomainRecord(record);

                    if (response.StatusCode != HttpStatusCode.OK)
                    {
                        var ex = new Exception(response.ReasonPhrase);
                        MultiLogHelper.Error <SettingsApiController>("Failed to record domain analytic", ex);
                    }

                    setting.Value = true.ToString();
                    _storeSettingService.Save(setting);

                    return(response);
                }
                catch (Exception ex)
                {
                    // this is for analytics only and we don't want to throw
                    MultiLogHelper.Error <SettingsApiController>("Failed to record analytics (Domain)", ex);
                }
            }

            return(Request.CreateResponse(HttpStatusCode.OK));
        }
예제 #25
0
        /// <summary>
        /// Sends an email, logging any errors.
        /// </summary>
        /// <param name="msg">
        /// The <see cref="MailMessage"/>.
        /// </param>
        /// <param name="credentials">
        /// The credentials.
        /// </param>
        /// <returns>
        /// The <see cref="bool"/>.
        /// </returns>
        public bool Send(MailMessage msg, NetworkCredential credentials = null)
        {
            try
            {
                // We want to send the email async
                using (var smtpClient = new SmtpClient(_settings.Host))
                {
                    if (_settings.HasCredentials)
                    {
                        smtpClient.Credentials = _settings.Credentials;
                    }
                    if (_settings.EnableSsl)
                    {
                        smtpClient.EnableSsl = true;
                    }
                    smtpClient.Port = _settings.Port;
                    smtpClient.Send(msg);
                }

                return(true);
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error <SmtpNotificationGatewayMethod>("Merchello.Core.Gateways.Notification.Smtp.SmtpNotificationGatewayMethod  failed sending email", ex);
                return(false);
            }
        }
예제 #26
0
        /// <summary>
        /// The initialize.
        /// </summary>
        private void Initialize()
        {
            foreach (var t in this._instanceTypes)
            {
                var atts = t.GetCustomAttributes <GatewayMethodUiAttribute>(false);
                foreach (var att in atts)
                {
                    if (att == null)
                    {
                        continue;
                    }

                    if (!this._gatewayMethods.ContainsKey(att.Alias))
                    {
                        this._gatewayMethods.Add(att.Alias, t);
                    }
                    else
                    {
                        var exception =
                            new InvalidOperationException(
                                "Resolver expects a single controller associated with a GatewayMethodAttribute.");
                        MultiLogHelper.Error <PaymentMethodUiControllerResolver>("More that one controller found", exception);
                    }
                }
            }
        }
예제 #27
0
        /// <summary>
        /// Initializes this class with default values
        /// </summary>
        private void Initialize()
        {
            // see if the key is already in the request cache
            var cachedContextData = this._cache.RequestCache.GetCacheItem(CustomerCookieName);

            if (cachedContextData != null)
            {
                this.ContextData = (CustomerContextData)cachedContextData;
                var key = this.ContextData.Key;
                this.TryGetCustomer(key);
                return;
            }

            // retrieve the merchello consumer cookie
            var cookie = this._umbracoContext.HttpContext.Request.Cookies[CustomerCookieName];

            if (cookie != null)
            {
                try
                {
                    this.ContextData = cookie.ToCustomerContextData();
                    this.TryGetCustomer(this.ContextData.Key);
                }
                catch (Exception ex)
                {
                    MultiLogHelper.Error <CustomerContext>("Decrypted guid did not parse", ex);
                    this.CreateAnonymousCustomer();
                }
            }
            else
            {
                this.CreateAnonymousCustomer();
            } // a cookie was not found
        }
        /// <summary>
        /// Gets a <see cref="IPaymentGatewayMethod"/> by it's payment code
        /// </summary>
        /// <param name="paymentCode">The payment code of the <see cref="IPaymentGatewayMethod"/></param>
        /// <returns>A <see cref="IPaymentGatewayMethod"/></returns>
        public override IPaymentGatewayMethod GetPaymentGatewayMethodByPaymentCode(string paymentCode)
        {
            var paymentMethod = this.PaymentMethods.FirstOrDefault(x => x.PaymentCode == paymentCode);

            if (paymentMethod != null)
            {
                switch (paymentCode)
                {
                case Constants.PayPal.PaymentCodes.ExpressCheckout:
                    return(new PayPalExpressCheckoutPaymentGatewayMethod(
                               this.GatewayProviderService,
                               paymentMethod,
                               GetPayPalApiService()));
                    //// TODO add additional payment methods here
                }
            }

            var logData = MultiLogger.GetBaseLoggingData();

            logData.AddCategory("GatewayProviders");
            logData.AddCategory("PayPal");

            var nullRef =
                new NullReferenceException(string.Format("PaymentMethod not found for payment code: {0}", paymentCode));

            MultiLogHelper.Error <PayPalPaymentGatewayProvider>(
                "Failed to find payment method for payment code",
                nullRef,
                logData);

            throw nullRef;
        }
예제 #29
0
        /// <summary>
        /// Sends an email asynchronously, logging any errors.
        /// </summary>
        /// <param name="msg">
        /// The <see cref="MailMessage"/> to send.
        /// </param>
        /// <param name="credentials">
        /// The <see cref="NetworkCredential"/>s containing identity credentials.
        /// </param>
        /// <returns>
        /// True if the email is sent successfully; otherwise, false.
        /// </returns>
        public async Task <bool> SendAsync(MailMessage msg, NetworkCredential credentials = null)
        {
            //// TODO ASP.NET 4.5
            //// HostingEnvironment.QueueBackgroundWorkItem(ct => SendMailAsync(msg));
            //// See http://blogs.msdn.com/b/webdev/archive/2014/06/04/queuebackgroundworkitem-to-reliably-schedule-and-run-long-background-process-in-asp-net.aspx

            try
            {
                // We want to send the email async
                using (var smtpClient = new SmtpClient(_settings.Host))
                {
                    if (_settings.HasCredentials)
                    {
                        smtpClient.Credentials = _settings.Credentials;
                    }
                    if (_settings.EnableSsl)
                    {
                        smtpClient.EnableSsl = true;
                    }
                    smtpClient.Port = _settings.Port;
                    await smtpClient.SendMailAsync(msg);
                }

                return(true);
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error <SmtpNotificationGatewayMethod>("Merchello.Core.Gateways.Notification.Smtp.SmtpNotificationGatewayMethod  failed sending email", ex);
                return(false);
            }
        }
        /// <summary>
        /// Adds a <see cref="ILineItem"/> to the collection of items
        /// </summary>
        /// <param name="lineItem">
        /// The line item.
        /// </param>
        /// <remarks>
        /// Intended for custom line item types
        /// http://issues.merchello.com/youtrack/issue/M-381
        /// </remarks>
        public virtual void AddItem(ILineItem lineItem)
        {
            Mandate.ParameterNotNullOrEmpty(lineItem.Sku, "The line item must have a sku");
            Mandate.ParameterNotNullOrEmpty(lineItem.Name, "The line item must have a name");

            if (lineItem.Quantity <= 0)
            {
                lineItem.Quantity = 1;
            }
            if (lineItem.Price < 0)
            {
                lineItem.Price = 0;
            }

            if (lineItem.LineItemType == LineItemType.Custom)
            {
                if (!new LineItemTypeField().CustomTypeFields.Select(x => x.TypeKey).Contains(lineItem.LineItemTfKey))
                {
                    var argError = new ArgumentException("The LineItemTfKey was not found in merchello.config custom type fields");
                    MultiLogHelper.Error <CheckoutContextManagerBase>("The LineItemTfKey was not found in merchello.config custom type fields", argError);

                    throw argError;
                }
            }

            Context.ItemCache.AddItem(lineItem);
        }