/// <summary>
        /// Determines whether this group matches the specified route URI.
        /// </summary>
        /// <param name="uri">The URI.</param>
        /// <returns><c>true</c> if this group is a match for the given URI; otherwise, <c>false</c>.</returns>
        /// <remarks></remarks>
        public ProviderUriMatchResult IsMatchForUri(string uri)
        {
            Mandate.ParameterNotNullOrEmpty(uri, "uri");

            //TODO: Do more validation on the incoming uri, for now just check the incoming scheme and convert http(s) to content
            var incomingUriBuilder = new UriBuilder(uri);

            if (string.Compare(incomingUriBuilder.Scheme, "http", StringComparison.InvariantCultureIgnoreCase) == 0 ||
                string.Compare(incomingUriBuilder.Scheme, "https", StringComparison.InvariantCultureIgnoreCase) == 0)
            {
                incomingUriBuilder.Scheme = "content";
            }

            incomingUriBuilder.Port = -1;
            // We don't care about the port and setting it to -1 causes UriBuilder not to include it in ToString()

            if (WildcardUriMatches == null)
            {
                return(new ProviderUriMatchResult(false, null));
            }

            LogHelper.TraceIfEnabled <ProviderMappingGroup>("Checking '{0}' against {1} UriMatches", () => uri, () => WildcardUriMatches.Count());
            return(_matchCache.GetOrAdd(uri, x =>
            {
                var uriRegexes = GetAndCacheUriMatchRegexes();
                var matches = uriRegexes.Where(uriMatch => uriMatch.Regex.IsMatch(FixUriBugs(incomingUriBuilder.ToString())))
                              .Select(match => new ProviderUriMatchResult(true, match.UriMatch))
                              .FirstOrDefault();
                return matches ?? new ProviderUriMatchResult(false, null);
            }));
        }
        public bool MatchesVisitor(string definition)
        {
            Mandate.ParameterNotNullOrEmpty(definition, "definition");

            try
            {
                var definedGroup = JsonConvert.DeserializeObject <int[]>(definition);

                // Check if there is a Pipeline cookie
                if (definedGroup.Any() && HttpContext.Current.Request.Cookies["PipelineContactId"] != null)
                {
                    // Get the Pipeline contact
                    var contactId = int.Parse(HttpContext.Current.Request.Cookies["PipelineContactId"].Value);
                    var contact   = new ContactService().GetById(contactId);

                    // Check if any of their Organisation is of a type in our criteria settings
                    if (contact != null && contact.Organisations != null && contact.Organisations.Any())
                    {
                        return(definedGroup.Intersect(contact.Organisations.Select(x => x.Id)).Any());
                    }
                }

                // No cookie, or Contact doesn't exist, or it doesn't have an Org - criteria fails
                return(false);
            }
            catch (JsonReaderException)
            {
                throw new ArgumentException(string.Format("Provided definition is not valid JSON: {0}", definition));
            }
        }
        public ProviderMappingGroup(string key,
                                    IEnumerable <WildcardUriMatch> matches,
                                    IEnumerable <ReadonlyProviderSetup> readers,
                                    IEnumerable <ProviderSetup> writers,
                                    IFrameworkContext frameworkContext)
        {
            Mandate.ParameterNotNullOrEmpty(key, "key");
            Mandate.ParameterNotNull(readers, "readers");
            Mandate.ParameterNotNull(writers, "writers");
            var readerCount = readers.Count();
            var writerCount = writers.Count();

            Mandate.That(readerCount > 0 || writerCount > 0,
                         x => new ArgumentOutOfRangeException("readers / writers",
                                                              "ProviderMappingGroup '{0}' must be supplied with at least one reader or writer. Given Readers: {1}, Writers: {2}"
                                                              .InvariantFormat(key, readerCount, writerCount)));

            Mandate.ParameterNotNull(frameworkContext, "frameworkContext");

            Key = key;
            FrameworkContext   = frameworkContext;
            WildcardUriMatches = matches;
            Readers            = readers;
            Writers            = writers;
        }
예제 #4
0
        /// <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 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");
                    LogHelper.Error <SalePreparationBase>("The LineItemTfKey was not found in merchello.config custom type fields", argError);

                    throw argError;
                }
            }

            _itemCache.AddItem(lineItem);
        }
        /// <summary>
        /// Executes an Action the specified controller by finding the action specified by name.
        /// </summary>
        /// <param name="controller"></param>
        /// <param name="proxyController"></param>
        /// <param name="action"></param>
        /// <param name="area"></param>
        /// <param name="actionParams"></param>
        /// <returns></returns>
        /// <remarks>
        /// If a proxy request is made to a custom controller with a custom ActionInvoker, the ActionInvoker will be ignored, this
        /// method simply finds the action by name.
        /// </remarks>
        public static ActionResult ProxyRequestToController(
            this ControllerBase controller,
            ControllerBase proxyController,
            string action,
            string area,
            params object[] actionParams)
        {
            Mandate.ParameterNotNull(proxyController, "proxyController");
            Mandate.ParameterNotNullOrEmpty(action, "action");

            Func <ParameterInfo[], bool> parametersMatch = p =>
            {
                if (p.Count() != actionParams.Count())
                {
                    return(false);
                }
                //ensure the param types match based on index too
                if (actionParams.Select(t => t.GetType()).Where((aType, i) => !TypeFinder.IsTypeAssignableFrom(p[i].ParameterType, aType)).Any())
                {
                    return(false);
                }
                return(true);
            };

            var method = (from m in proxyController.GetType().GetMethods()
                          let p = m.GetParameters()
                                  where m.Name.InvariantEquals(action) && TypeFinder.IsTypeAssignableFrom <ActionResult>(m.ReturnType) && parametersMatch(p)
                                  select m).SingleOrDefault();

            if (method == null)
            {
                throw new InvalidOperationException("Could not find an Action with the name " + action + " with matching parameters (" + actionParams.Count() + ")");
            }
            return(controller.ProxyRequestToController(proxyController, method, area, actionParams));
        }
예제 #6
0
 /// <summary>
 /// Constructor accepting custom connectino string and provider name
 /// </summary>
 /// <param name="connectionString">Connection String to use with Database</param>
 /// <param name="providerName">Database Provider for the Connection String</param>
 public DefaultDatabaseFactory(string connectionString, string providerName)
 {
     Mandate.ParameterNotNullOrEmpty(connectionString, "connectionString");
     Mandate.ParameterNotNullOrEmpty(providerName, "providerName");
     _connectionString = connectionString;
     _providerName     = providerName;
 }
예제 #7
0
        /// <summary>
        /// Creates a customer and saves the record to the database
        /// </summary>
        /// <param name="loginName">
        /// The login Name.
        /// </param>
        /// <param name="firstName">
        /// The first name of the customer
        /// </param>
        /// <param name="lastName">
        /// The last name of the customer
        /// </param>
        /// <param name="email">
        /// the email address of the customer
        /// </param>
        /// <returns>
        /// <see cref="ICustomer"/>
        /// </returns>
        public ICustomer CreateCustomerWithKey(string loginName, string firstName, string lastName, string email)
        {
            Mandate.ParameterNotNullOrEmpty(loginName, "loginName");

            var customer = new Customer(loginName)
            {
                FirstName = firstName,
                LastName  = lastName,
                Email     = email
            };

            if (Creating.IsRaisedEventCancelled(new Events.NewEventArgs <ICustomer>(customer), this))
            {
                customer.WasCancelled = true;
                return(customer);
            }

            using (new WriteLock(Locker))
            {
                var uow = _uowProvider.GetUnitOfWork();
                using (var repository = _repositoryFactory.CreateCustomerRepository(uow))
                {
                    repository.AddOrUpdate(customer);
                    uow.Commit();
                }
            }

            SaveAddresses(customer);

            Created.RaiseEvent(new Events.NewEventArgs <ICustomer>(customer), this);

            return(customer);
        }
예제 #8
0
        /// <summary>
        /// Return the Url for a Web Api service
        /// </summary>
        /// <param name="url"></param>
        /// <param name="actionName"></param>
        /// <param name="controllerName"></param>
        /// <param name="area"></param>
        /// <param name="id"></param>
        /// <returns></returns>
        public static string GetUmbracoApiService(this UrlHelper url, string actionName, string controllerName, string area, object id = null)
        {
            Mandate.ParameterNotNullOrEmpty(controllerName, "controllerName");
            Mandate.ParameterNotNullOrEmpty(actionName, "actionName");

            string routeName;

            if (area.IsNullOrWhiteSpace())
            {
                routeName = string.Format("umbraco-{0}-{1}", "api", controllerName);
                if (id == null)
                {
                    return(url.Link(routeName, new { controller = controllerName, action = actionName }));
                }
                else
                {
                    return(url.Link(routeName, new { controller = controllerName, action = actionName, id = id }));
                }
            }
            else
            {
                routeName = string.Format("umbraco-{0}-{1}-{2}", "api", area, controllerName);
                if (id == null)
                {
                    return(url.Link(routeName, new { controller = controllerName, action = actionName, area = area }));
                }
                else
                {
                    return(url.Link(routeName, new { controller = controllerName, action = actionName, area = area, id = id }));
                }
            }
        }
예제 #9
0
        /// <summary>
        /// Returns a compiled view path based on the FQN of the view (embedded resource)
        /// </summary>
        /// <param name="resourcePath">
        /// The path to the resource without the assembly name
        /// </param>
        /// <param name="assemblyName">
        /// The name of the assembly where the resource is found
        /// </param>
        /// <returns></returns>
        public static string Create(string resourcePath, string assemblyName)
        {
            Mandate.ParameterNotNullOrEmpty(resourcePath, "resourcePath");
            Mandate.ParameterNotNullOrEmpty(assemblyName, "assemblyName");

            //first check if the resource exists in the values already and return the key
            if (ViewPaths.Values.Contains(resourcePath))
            {
                return(ViewPaths
                       .Where(x => x.Value == resourcePath)
                       .Single()
                       .Key);
            }
            else
            {
                Assembly assembly;
                if (ViewResourceExists(resourcePath, assemblyName, out assembly))
                {
                    var md5 = CreateResourcePathHashKey(resourcePath);
                    if (!ViewPaths.ContainsKey(md5))
                    {
                        //add the mapping
                        ViewPaths.TryAdd(md5, resourcePath);
                        ViewAssemblies.TryAdd(resourcePath, assembly);
                    }
                    return(md5);
                }
            }

            throw new TypeLoadException("Could not find resource with resourcePath: " + resourcePath);
        }
예제 #10
0
        /// <summary>
        /// Helper method to create a new form to execute in the Umbraco request pipeline to a surface controller plugin
        /// </summary>
        /// <param name="html"></param>
        /// <param name="action"></param>
        /// <param name="surfaceType">The surface controller to route to</param>
        /// <param name="additionalRouteVals"></param>
        /// <param name="htmlAttributes"></param>
        /// <returns></returns>
        public static MvcForm BeginUmbracoForm(this HtmlHelper html, string action, Type surfaceType,
                                               object additionalRouteVals,
                                               IDictionary <string, object> htmlAttributes)
        {
            Mandate.ParameterNotNullOrEmpty(action, "action");
            Mandate.ParameterNotNull(surfaceType, "surfaceType");

            var area = "";

            var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers
                                    .SingleOrDefault(x => x == surfaceType);

            if (surfaceController == null)
            {
                throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName);
            }
            var metaData = PluginController.GetMetadata(surfaceController);

            if (!metaData.AreaName.IsNullOrWhiteSpace())
            {
                //set the area to the plugin area
                area = metaData.AreaName;
            }
            return(html.BeginUmbracoForm(action, metaData.ControllerName, area, additionalRouteVals, htmlAttributes));
        }
예제 #11
0
 /// <summary>
 /// Creates a new file object with byte contents.
 /// </summary>
 /// <param name="fileName"></param>
 /// <param name="contentBytes"></param>
 public File(string fileName, byte[] contentBytes)
     : this()
 {
     Mandate.ParameterNotNullOrEmpty(fileName, "fileName");
     Name         = fileName;
     ContentBytes = contentBytes;
 }
        /// <summary>
        /// Executes to the Plugin controller's action as a ChildAction but maintains the action's result so that it can be retreived
        /// </summary>
        /// <typeparam name="TResult"></typeparam>
        /// <typeparam name="TControllerType"></typeparam>
        /// <param name="controller"></param>
        /// <param name="proxyController"></param>
        /// <param name="methodSelector"></param>
        /// <param name="pluginDef"></param>
        /// <param name="backOfficePath"></param>
        /// <param name="routeIdParameterName">Plugin controllers routes are constructed with a route Id parameter such as editorId or surfaceId </param>
        /// <returns></returns>
        public static ProxyRequestResult <TResult> ProxyRequestToController <TResult, TControllerType>(
            this ControllerBase controller,
            TControllerType proxyController,
            Expression <Func <TControllerType, TResult> > methodSelector,
            PluginMetadataComposition pluginDef,
            string backOfficePath,
            string routeIdParameterName)
            where TResult : ActionResult
            where TControllerType : class
        {
            Mandate.ParameterNotNull(pluginDef, "pluginDef");
            Mandate.ParameterNotNullOrEmpty(backOfficePath, "backOfficePath");

            IDictionary <string, object> routeDictionary = new Dictionary <string, object>();

            var proxyArea = backOfficePath;

            if (pluginDef.PluginDefinition.HasRoutablePackageArea())
            {
                proxyArea = pluginDef.PluginDefinition.PackageName;
            }

            if (pluginDef.Id != Guid.Empty)
            {
                //need to add the routing id to it
                routeDictionary.Add(routeIdParameterName, pluginDef.Id.ToString("N"));
            }

            return(controller.ProxyRequestToController(proxyController, methodSelector, proxyArea, routeDictionary));
        }
        /// <summary>
        /// Create a new user account.
        /// </summary>
        /// <param name="user">Back office user account</param>
        /// <param name="userGroups">Groups to assign to user</param>
        /// <param name="culture">Culture for user</param>
        /// <param name="email">Email address for user account</param>
        /// <param name="name">Name for user account</param>
        /// <returns></returns>
        protected async virtual Task <IdentityResult> NewCreateUser(BackOfficeIdentityUser user, string[] userGroups, string culture, string email = null, string name = null)
        {
            // Mandate that parameters must be specified.
            Mandate.ParameterNotNull <BackOfficeIdentityUser>(user, "user");
            Mandate.ParameterNotNullOrEmpty <string>(userGroups, "userGroups");
            Mandate.ParameterNotNull <string>(culture, "culture");

            // Assign name to user if not already specified. Use name if specified, otherwise use email address.
            user.Name = user.Name ?? name ?? user.UserName;

            // Assign email to user if not already specified.
            user.Email = user.Email ?? email;
            if (String.IsNullOrWhiteSpace(user.Email))
            {
                throw new ArgumentNullException("email");
            }

            // Assign user to specified groups.
            var groups = Services.UserService.GetUserGroupsByAlias(userGroups);

            foreach (var userGroup in groups)
            {
                user.AddRole(userGroup.Alias);
            }

            // Create user account.
            var userCreationResults = await UserManager.CreateAsync(user);

            return(userCreationResults);
        }
예제 #14
0
        public MigrationRunner(IMigrationEntryService migrationEntryService, ILogger logger, SemVersion currentVersion, SemVersion targetVersion, string productName, params IMigration[] migrations)
        {
            if (migrationEntryService == null)
            {
                throw new ArgumentNullException("migrationEntryService");
            }
            if (logger == null)
            {
                throw new ArgumentNullException("logger");
            }
            if (currentVersion == null)
            {
                throw new ArgumentNullException("currentVersion");
            }
            if (targetVersion == null)
            {
                throw new ArgumentNullException("targetVersion");
            }
            Mandate.ParameterNotNullOrEmpty(productName, "productName");

            _migrationEntryService = migrationEntryService;
            _logger         = logger;
            _currentVersion = currentVersion;
            _targetVersion  = targetVersion;
            _productName    = productName;
            //ensure this is null if there aren't any
            _migrations = migrations == null || migrations.Length == 0 ? null : migrations;
        }
예제 #15
0
        /// <summary>
        /// Returns the result of a child action of a SurfaceController
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="htmlHelper"></param>
        /// <param name="actionName"></param>
        /// <param name="surfaceType"></param>
        /// <returns></returns>
        public static IHtmlString Action(this HtmlHelper htmlHelper, string actionName, Type surfaceType)
        {
            Mandate.ParameterNotNull(surfaceType, "surfaceType");
            Mandate.ParameterNotNullOrEmpty(actionName, "actionName");

            var routeVals = new RouteValueDictionary(new { area = "" });

            var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers
                                    .SingleOrDefault(x => x == surfaceType);

            if (surfaceController == null)
            {
                throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName);
            }
            var metaData = PluginController.GetMetadata(surfaceController);

            if (!metaData.AreaName.IsNullOrWhiteSpace())
            {
                //set the area to the plugin area
                if (routeVals.ContainsKey("area"))
                {
                    routeVals["area"] = metaData.AreaName;
                }
                else
                {
                    routeVals.Add("area", metaData.AreaName);
                }
            }

            return(htmlHelper.Action(actionName, metaData.ControllerName, routeVals));
        }
        /// <summary>
        /// Generates a URL based on the current Umbraco URL with a custom query string that will route to the specified SurfaceController
        /// </summary>
        /// <param name="url"></param>
        /// <param name="action"></param>
        /// <param name="surfaceType"></param>
        /// <param name="additionalRouteVals"></param>
        /// <returns></returns>
        public static string SurfaceAction(this UrlHelper url, string action, Type surfaceType, object additionalRouteVals)
        {
            Mandate.ParameterNotNullOrEmpty(action, "action");
            Mandate.ParameterNotNull(surfaceType, "surfaceType");

            var area = "";

            var surfaceController = SurfaceControllerResolver.Current.RegisteredSurfaceControllers
                                    .SingleOrDefault(x => x == surfaceType);

            if (surfaceController == null)
            {
                throw new InvalidOperationException("Could not find the surface controller of type " + surfaceType.FullName);
            }
            var metaData = PluginController.GetMetadata(surfaceController);

            if (metaData.AreaName.IsNullOrWhiteSpace() == false)
            {
                //set the area to the plugin area
                area = metaData.AreaName;
            }

            var encryptedRoute = UmbracoHelper.CreateEncryptedRouteString(metaData.ControllerName, action, area, additionalRouteVals);

            var result = UmbracoContext.Current.OriginalRequestUrl.AbsolutePath.EnsureEndsWith('?') + "ufprt=" + encryptedRoute;

            return(result);
        }
예제 #17
0
        public bool MatchesVisitor(string definition)
        {
            Mandate.ParameterNotNullOrEmpty(definition, "definition");

            NumberOfVisitsSetting numberOfVisitsSetting;

            try
            {
                numberOfVisitsSetting = JsonConvert.DeserializeObject <NumberOfVisitsSetting>(definition);
            }
            catch (JsonReaderException)
            {
                throw new ArgumentException($"Provided definition is not valid JSON: {definition}");
            }

            var timesVisited = _numberOfVisitsProvider.GetNumberOfVisits();

            switch (numberOfVisitsSetting.Match)
            {
            case NumberOfVisitsSettingMatch.MoreThan:
                return(timesVisited > numberOfVisitsSetting.Number);

            case NumberOfVisitsSettingMatch.LessThan:
                return(timesVisited < numberOfVisitsSetting.Number);

            case NumberOfVisitsSettingMatch.Exactly:
                return(timesVisited == numberOfVisitsSetting.Number);

            default:
                return(false);
            }
        }
예제 #18
0
        /// <summary>
        /// Clears out all cookies starting with the prefix
        /// </summary>
        /// <param name="filterContext"></param>
        /// <remarks>
        /// Generally these cookies will be cleared out on the client side but just in case this will
        /// help ensure that we don't leave residule cookes laying around, even though we've already set
        /// them to expire in a minute... better safe than sorry
        /// </remarks>
        public override void OnActionExecuting(ActionExecutingContext filterContext)
        {
            Mandate.ParameterNotNullOrEmpty(CookieNamePrefix, "CookieNamePrefix");
            Mandate.ParameterNotNullOrEmpty(QueryStringName, "QueryStringParameterName");

            //we don't want to delete this cookie if the notification query string exists, if that is the case
            //then that means that the cookie was written in a 302 redirect and that cookie needs to persist
            //after this request. If the query string doesn't exist, then it means the cookie should have been
            //read by the client side. To be safe, if people are saving/publishing at nearly the same time in multiple
            //windows, we'll also not remove the cookies if it is a POST.);
            if (string.IsNullOrEmpty(filterContext.HttpContext.Request.QueryString[QueryStringName]) &&
                filterContext.HttpContext.Request.RequestType != "POST")
            {
                foreach (var c in filterContext.HttpContext.Request.Cookies.AllKeys.Where(x => x.StartsWith(CookieNamePrefix)))
                {
                    //set it to be expired
                    var cookieToDelete = new HttpCookie(c)
                    {
                        Expires = DateTime.Now.AddDays(-1)
                    };
                    //add this to the response so the cookie is definitely removed when the response is returned
                    filterContext.HttpContext.Response.Cookies.Add(cookieToDelete);
                }
            }
        }
예제 #19
0
        public bool MatchesVisitor(string definition)
        {
            Mandate.ParameterNotNullOrEmpty(definition, "definition");

            MemberProfileFieldSetting setting;

            try
            {
                setting = JsonConvert.DeserializeObject <MemberProfileFieldSetting>(definition);
            }
            catch (JsonReaderException)
            {
                throw new ArgumentException(string.Format("Provided definition is not valid JSON: {0}", definition));
            }

            var value = _memberProfileFieldProvider.GetMemberProfileFieldValue(setting.Alias);

            switch (setting.Match)
            {
            case MemberProfileFieldSettingMatch.MatchesValue:
                return(string.Equals(setting.Value, value, StringComparison.InvariantCultureIgnoreCase));

            case MemberProfileFieldSettingMatch.DoesNotMatchValue:
                return(!string.Equals(setting.Value, value, StringComparison.InvariantCultureIgnoreCase));

            case MemberProfileFieldSettingMatch.GreaterThanValue:
            case MemberProfileFieldSettingMatch.GreaterThanOrEqualToValue:
            case MemberProfileFieldSettingMatch.LessThanValue:
            case MemberProfileFieldSettingMatch.LessThanOrEqualToValue:
                return(ComparisonHelpers.CompareValues(value, setting.Value, GetComparison(setting.Match)));

            default:
                return(false);
            }
        }
예제 #20
0
        public bool MatchesVisitor(string definition)
        {
            Mandate.ParameterNotNullOrEmpty(definition, "definition");

            HostSetting hostSetting;

            try
            {
                hostSetting = JsonConvert.DeserializeObject <HostSetting>(definition);
            }
            catch (JsonReaderException)
            {
                throw new ArgumentException($"Provided definition is not valid JSON: {definition}");
            }

            var host = _hostProvider.GetHost();

            switch (hostSetting.Match)
            {
            case HostSettingMatch.MatchesValue:
                return(MatchesValue(host, hostSetting.Value));

            case HostSettingMatch.DoesNotMatchValue:
                return(!MatchesValue(host, hostSetting.Value));

            case HostSettingMatch.ContainsValue:
                return(ContainsValue(host, hostSetting.Value));

            case HostSettingMatch.DoesNotContainValue:
                return(!ContainsValue(host, hostSetting.Value));

            default:
                return(false);
            }
        }
예제 #21
0
        public bool MatchesVisitor(string definition)
        {
            Mandate.ParameterNotNullOrEmpty(definition, "definition");

            IList <CountrySetting> definedCountries;

            try
            {
                definedCountries = JsonConvert.DeserializeObject <IList <CountrySetting> >(definition);
            }
            catch (JsonReaderException)
            {
                throw new ArgumentException(string.Format("Provided definition is not valid JSON: {0}", definition));
            }

            var ip = _ipProvider.GetIp();

            ip = "2.37.150.125";
            if (!string.IsNullOrEmpty(ip))
            {
                var country = _countryGeoLocationProvider.GetCountryFromIp(ip);
                if (!string.IsNullOrEmpty(country))
                {
                    return(definedCountries
                           .Any(x => string.Equals(x.Code, country, StringComparison.InvariantCultureIgnoreCase)));
                }
            }

            return(false);
        }
예제 #22
0
        /// <summary>
        /// Creates a <see cref="SubscriptionRequest"/>.
        /// </summary>
        /// <param name="paymentMethodToken">
        /// The payment method token.
        /// </param>
        /// <param name="planId">
        /// The plan id.
        /// </param>
        /// <param name="price">
        /// An optional price used to override the plan price.
        /// </param>
        /// <param name="merchantAccountId"></param>
        /// <returns>
        /// The <see cref="SubscriptionRequest"/>.
        /// </returns>
        public SubscriptionRequest CreateSubscriptionRequest(string paymentMethodToken, string planId, decimal?price = null, string merchantAccountId = "")
        {
            Mandate.ParameterNotNullOrEmpty(paymentMethodToken, "paymentMethodToken");
            Mandate.ParameterNotNullOrEmpty(planId, "planId");

            var request = new SubscriptionRequest
            {
                PaymentMethodToken = paymentMethodToken,
                PlanId             = planId
            };

            if (!string.IsNullOrEmpty(merchantAccountId))
            {
                request.MerchantAccountId = merchantAccountId;
            }

            // TODO figure out the descriptor for nicer Credit Card statements
            // TODO https://www.braintreepayments.com/docs/dotnet/transactions/dynamic_descriptors
            //if (_settings.MerchantDescriptor.HasValues())
            //{
            //    request.Descriptor = _settings.MerchantDescriptor.AsDescriptorRequest();
            //}

            if (price != null)
            {
                request.Price = price.Value;
            }

            return(request);
        }
 /// <summary>
 /// This constructor defines both the angular service and method name to use
 /// </summary>
 /// <param name="serviceName"></param>
 /// <param name="methodName"></param>
 public ActionMenuItemAttribute(string serviceName, string methodName)
 {
     Mandate.ParameterNotNullOrEmpty(serviceName, "serviceName");
     Mandate.ParameterNotNullOrEmpty(methodName, "methodName");
     MethodName  = methodName;
     ServiceName = serviceName;
 }
예제 #24
0
        /// <summary>
        /// Checks if the
        /// </summary>
        /// <param name="searchPath"></param>
        /// <param name="sourceDirectory"></param>
        /// <param name="applicationRoot"></param>
        /// <returns></returns>
        private static bool IsRootConfig(string searchPath, string sourceDirectory, string applicationRoot)
        {
            Mandate.ParameterNotNullOrEmpty(searchPath, "searchPath");
            Mandate.ParameterNotNullOrEmpty(sourceDirectory, "sourceDirectory");
            Mandate.ParameterCondition(Path.IsPathRooted(sourceDirectory), "sourceDirectory");
            Mandate.ParameterCondition(Path.IsPathRooted(applicationRoot), "applicationRoot");

            var directoryName = Path.GetDirectoryName(sourceDirectory);

            if (directoryName.Length < applicationRoot.Length)
            {
                return(false);
            }
            var pathWithRootRemoved = "~/" + NormaliseRelativeRoot(directoryName.Substring(applicationRoot.Length - 1));

            if (pathWithRootRemoved.StartsWith(NormaliseRelativeRoot(searchPath), StringComparison.InvariantCultureIgnoreCase))
            {
                //this is a sub folder of our search path, so we'll assume that it is a local config
                return(false);
            }
            else
            {
                //this is not a sub folder or the same folder of our search path so we'll assume that it is a global/root config
                return(true);
            }
        }
        public bool MatchesVisitor(string definition)
        {
            Mandate.ParameterNotNullOrEmpty(definition, "definition");

            CookieSetting cookieSetting;

            try
            {
                cookieSetting = JsonConvert.DeserializeObject <CookieSetting>(definition);
            }
            catch (JsonReaderException)
            {
                throw new ArgumentException($"Provided definition is not valid JSON: {definition}");
            }

            if (string.IsNullOrEmpty(cookieSetting.Key))
            {
                throw new ArgumentNullException("key", "Cookie key not set");
            }

            var cookieExists = _cookieProvider.CookieExists(cookieSetting.Key);
            var cookieValue  = string.Empty;

            if (cookieExists)
            {
                cookieValue = _cookieProvider.GetCookieValue(cookieSetting.Key);
            }

            switch (cookieSetting.Match)
            {
            case CookieSettingMatch.Exists:
                return(cookieExists);

            case CookieSettingMatch.DoesNotExist:
                return(!cookieExists);

            case CookieSettingMatch.MatchesValue:
                return(cookieExists && MatchesValue(cookieValue, cookieSetting.Value));

            case CookieSettingMatch.ContainsValue:
                return(cookieExists && ContainsValue(cookieValue, cookieSetting.Value));

            case CookieSettingMatch.GreaterThanValue:
            case CookieSettingMatch.GreaterThanOrEqualToValue:
            case CookieSettingMatch.LessThanValue:
            case CookieSettingMatch.LessThanOrEqualToValue:
                return(cookieExists &&
                       CompareValues(cookieValue, cookieSetting.Value, GetComparison(cookieSetting.Match)));

            case CookieSettingMatch.MatchesRegex:
                return(cookieExists && MatchesRegex(cookieValue, cookieSetting.Value));

            case CookieSettingMatch.DoesNotMatchRegex:
                return(cookieExists && !MatchesRegex(cookieValue, cookieSetting.Value));

            default:
                return(false);
            }
        }
        public bool MatchesVisitor(string definition)
        {
            Mandate.ParameterNotNullOrEmpty(definition, nameof(definition));

            SessionSetting sessionSetting;

            try
            {
                sessionSetting = JsonConvert.DeserializeObject <SessionSetting>(definition);
            }
            catch (JsonReaderException)
            {
                throw new ArgumentException($"Provided definition is not valid JSON: {definition}");
            }

            if (string.IsNullOrEmpty(sessionSetting.Key))
            {
                throw new ArgumentNullException("key", "Session key not set");
            }

            var keyExists = _sessionProvider.KeyExists(sessionSetting.Key);
            var value     = string.Empty;

            if (keyExists)
            {
                value = _sessionProvider.GetValue(sessionSetting.Key);
            }

            switch (sessionSetting.Match)
            {
            case SessionSettingMatch.Exists:
                return(keyExists);

            case SessionSettingMatch.DoesNotExist:
                return(!keyExists);

            case SessionSettingMatch.MatchesValue:
                return(keyExists && MatchesValue(value, sessionSetting.Value));

            case SessionSettingMatch.ContainsValue:
                return(keyExists && ContainsValue(value, sessionSetting.Value));

            case SessionSettingMatch.GreaterThanValue:
            case SessionSettingMatch.GreaterThanOrEqualToValue:
            case SessionSettingMatch.LessThanValue:
            case SessionSettingMatch.LessThanOrEqualToValue:
                return(keyExists &&
                       CompareValues(value, sessionSetting.Value, GetComparison(sessionSetting.Match)));

            case SessionSettingMatch.MatchesRegex:
                return(keyExists && MatchesRegex(value, sessionSetting.Value));

            case SessionSettingMatch.DoesNotMatchRegex:
                return(keyExists && !MatchesRegex(value, sessionSetting.Value));

            default:
                return(false);
            }
        }
        /// <summary>
        /// Adds a value to the Context Data
        /// </summary>
        /// <param name="contextData">
        /// The context data.
        /// </param>
        /// <param name="alias">
        /// The alias.
        /// </param>
        /// <param name="value">
        /// The value.
        /// </param>
        public static void SetValue(this CustomerContextData contextData, string alias, string value)
        {
            Mandate.ParameterNotNullOrEmpty(alias, "alias");
            Mandate.ParameterNotNullOrEmpty(value, "value");

            contextData.Values.Remove(contextData.Values.FirstOrDefault(x => x.Key == alias));
            contextData.Values.Add(new KeyValuePair <string, string>(alias, value));
        }
예제 #28
0
        /// <summary>
        /// Initializes a new instance of the <see cref="Customer"/> class.
        /// </summary>
        /// <param name="loginName">
        /// The login Name associated with the membership provider users
        /// </param>
        internal Customer(string loginName) : base(false)
        {
            Mandate.ParameterNotNullOrEmpty(loginName, "loginName");

            _loginName = loginName;

            _addresses = new List <ICustomerAddress>();
        }
예제 #29
0
        /// <summary>
        /// Gets the first discoverable value from the 'appSettings' section of configuration, by calling <see cref="GetWebAppSettings{TOut}(string,string)"/>.
        /// </summary>
        /// <typeparam name="TOut">The type of the value returned.</typeparam>
        /// <param name="key">The key of the setting.</param>
        /// <param name="pluginBasePath">The relative plugin root path.</param>
        /// <returns></returns>
        public TOut GetSingleWebAppSetting <TOut>(string key, string pluginBasePath) where TOut : class
        {
            Mandate.ParameterNotNullOrEmpty(key, "key");
            Mandate.ParameterNotNullOrEmpty(pluginBasePath, "pluginBasePath");
            Mandate.ParameterCondition(!Path.IsPathRooted(pluginBasePath), "pluginBasePath");

            return(GetWebAppSettings <TOut>(key, pluginBasePath).FirstOrDefault());
        }
예제 #30
0
        private static string NormaliseRelativeRoot(string path)
        {
            Mandate.ParameterNotNullOrEmpty(path, "path");
            path = path.Trim('\\');
            Mandate.ParameterCondition(!Path.IsPathRooted(path), "path");

            return(path.Replace('\\', '/').Trim('/'));
        }