示例#1
0
        /// <summary>
        /// Renders a sales receipt.
        /// </summary>
        /// <param name="view">
        /// The optional view.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        /// <exception cref="NullReferenceException">
        /// Throws a null reference exception if the "invoiceKey" is not stored in the CustomerContext
        /// </exception>
        public virtual ActionResult SalesReceipt(string view = "")
        {
            var logData = MultiLogger.GetBaseLoggingData();

            logData.AddCategory("Controllers");

            var invoiceKey = CustomerContext.GetValue("invoiceKey");

            if (invoiceKey.IsNullOrWhiteSpace())
            {
                var nullRef = new NullReferenceException("The parameter invoiceKey was not found in the CustomerContext");
                MultiLogHelper.Error <CheckoutSummaryControllerBase <TSummary, TBillingAddress, TShippingAddress, TLineItem> >("The 'invoiceKey' parameter was not found in the CustomerContext", nullRef, logData);
                throw nullRef;
            }

            try
            {
                var key     = new Guid(invoiceKey);
                var invoice = MerchelloServices.InvoiceService.GetByKey(key);
                var model   = CheckoutSummaryFactory.Create(invoice);
                return(view.IsNullOrWhiteSpace() ? this.PartialView(model) : this.PartialView(view, model));
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error <CheckoutSummaryControllerBase <TSummary, TBillingAddress, TShippingAddress, TLineItem> >("Could not render the receipt.", ex, logData);
                throw;
            }
        }
示例#2
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
            });
        }
        /// <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;
        }
示例#4
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;
            }
        }
示例#5
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>
        /// 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;
        }
示例#7
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);
        }
示例#8
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;
            }
        }
示例#9
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;
            }
        }
        /// <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);
        }
示例#11
0
        public virtual void OnError(Exception error)
        {
            var logData = MultiLogger.GetBaseLoggingData();

            logData.AddCategory("Monitors");
            MultiLogHelper.Error <MonitorBase <T> >("Monitor error: ", error, logData);
        }
示例#12
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 defaultCollection = merchello.Query.Product.TypedProductContentSearch(1, 10);

                return(new ProductContentListView(Guid.Empty, defaultCollection));
            }

            try
            {
                var key = new Guid(collectionKey);
                return(new ProductContentListView(key, merchello.TypedProductContentFromCollection(key)));
            }
            catch (Exception ex)
            {
                MultiLogHelper.Error <ProductDisplayValueConverter>("Failed to Convert ProductDisplay property", ex);
                return(null);
            }
        }
示例#13
0
        /// <summary>
        /// Creates a new view.
        /// </summary>
        /// <param name="fileName">
        /// The file name.
        /// </param>
        /// <param name="viewType">
        /// The view type.
        /// </param>
        /// <param name="modelName">
        /// The model name.
        /// </param>
        /// <param name="viewBody">
        /// The view body.
        /// </param>
        /// <returns>
        /// A value indicating whether or not the create was successful.
        /// </returns>
        public override PluginViewEditorContent CreateNewView(string fileName, PluginViewType viewType, string modelName, string viewBody)
        {
            var virtualPath = GetVirtualPathByPlugViewType(viewType);

            var mapped = EnsureMappedPath(virtualPath);

            fileName = fileName.Replace(" ", string.Empty);

            var fullFileName = string.Format("{0}{1}", mapped, fileName);

            if (!File.Exists(fullFileName))
            {
                using (var sw = File.CreateText(fullFileName))
                {
                    sw.WriteLine("@inherits Merchello.Web.Mvc.MerchelloHelperViewPage<{0}>", modelName);
                    sw.WriteLine("@using Merchello.Core");
                    sw.WriteLine("@using Merchello.Core.Models");
                    sw.WriteLine("@*");
                    sw.WriteLine("     MerchelloHelperViewPage<T> inherits from UmbracoViewPage<t> and exposes the MerchelloHelper as 'Merchello'");
                    sw.WriteLine("     Example usage:  var product = Merchello.TypedProductContent(YOURPRODUCTKEY);");
                    sw.WriteLine("*@");
                    sw.Close();
                }

                return(GetView(virtualPath, fileName, viewType));
            }

            var logData = MultiLogger.GetBaseLoggingData();
            var ex      = new InvalidDataException("File already exists");

            MultiLogHelper.Error <PluginViewEditorProvider>("Cannot create a duplicate file", ex, logData);
            throw ex;
        }
        public ProductAttributeDisplay PutProductAttributeDetachedContent(
            [ModelBinder(typeof(ProductAttributeContentSaveBinder))]
            ProductAttributeContentSave attributeContentItem)
        {
            var contentTypeAlias = attributeContentItem.DetachedContentType.UmbContentType.Alias;
            var contentType      = _contentTypeService.GetContentType(contentTypeAlias);

            if (contentType == null)
            {
                var nullRef = new NullReferenceException("Could not find ContentType with alias: " + contentTypeAlias);
                MultiLogHelper.Error <ProductOptionApiController>("Failed to find content type", nullRef);
                throw nullRef;
            }

            var attribute = attributeContentItem.Display;

            attribute.DetachedDataValues = DetachedContentHelper.GetUpdatedValues <ProductAttributeContentSave, ProductAttributeDisplay>(contentType, attributeContentItem);
            var destination = _productOptionService.GetProductAttributeByKey(attribute.Key);

            destination = attribute.ToProductAttribute(destination);

            ((ProductOptionService)_productOptionService).Save(destination);

            return(destination.ToProductAttributeDisplay(contentType, DetachedValuesConversionType.Editor));
        }
示例#15
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));
        }
        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));
        }
示例#17
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);
                    }
                }
            }
        }
示例#18
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>
        /// 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);
        }
        /// <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);
        }
示例#21
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);
        }
示例#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());
        }
示例#23
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>
        /// 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;
        }
示例#25
0
        /// <summary>
        /// Constructs an error response message from an exception.
        /// </summary>
        /// <param name="ex">
        /// The ex.
        /// </param>
        /// <returns>
        /// The <see cref="ExpressCheckoutResponse"/>.
        /// </returns>
        public ExpressCheckoutResponse Build(Exception ex)
        {
            var logData = MultiLogger.GetBaseLoggingData();

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

            // bubble up the error
            var errorType = new ErrorType()
            {
                SeverityCode = SeverityCodeType.CUSTOMCODE,
                ShortMessage = ex.Message,
                LongMessage  = ex.Message,
                ErrorCode    = "PPEService"
            };

            logData.SetValue("payPalErrorType", errorType);

            MultiLogHelper.Error <PayPalExpressCheckoutService>("Failed to get response from PayPalAPIInterfaceServiceService", ex, logData);

            return(new ExpressCheckoutResponse {
                Ack = AckCodeType.CUSTOMCODE, ErrorTypes = new List <ErrorType> {
                    errorType
                }
            });
        }
示例#26
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
        }
示例#27
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);
            }
        }
        /// <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;
        }
        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));
        }
        /// <summary>
        /// Handles a wish list update exception
        /// </summary>
        /// <param name="model">
        /// The model.
        /// </param>
        /// <param name="ex">
        /// The ex.
        /// </param>
        /// <returns>
        /// The <see cref="ActionResult"/>.
        /// </returns>
        /// <remarks>
        /// Allows for customization of the redirection after a custom update basket operation
        /// </remarks>
        protected virtual ActionResult HandleUpdateWishListException(TItemCacheModel model, Exception ex)
        {
            var logData = MultiLogger.GetBaseLoggingData();

            MultiLogHelper.Error <WishListControllerBase <TItemCacheModel, TLineItemModel> >("Failed to update wish list", ex, logData);

            throw ex;
        }