Example #1
0
 public void SyncObjectState <TEntity>(TEntity entity) where TEntity : class, IObjectState
 {
     Entry(entity).State = StateHelper.ConvertState(entity.ObjectState);
 }
Example #2
0
        public static string Register(List <InputData> fields, IDialogContext context)
        {
            string fail = "";

            string name   = "";
            string email  = "";
            string card   = "";
            string gender = "";

            foreach (InputData f in fields)
            {
                switch (f.attribute)
                {
                case name_field:
                    if (f.value != "")
                    {
                        name = f.value;
                    }
                    else
                    {
                        fail += "Preciso que me diga o seu nome.\n";
                    }
                    break;

                case email_field:
                    if (f.value != "")
                    {
                        try
                        {
                            var m = new MailAddress(f.value);
                            email = f.value;
                        }
                        catch
                        {
                            fail += "O email não está no formato correcto (exemplo: [email protected]).\n";
                        }
                    }
                    else
                    {
                        fail += "Por favor insira o seu email. Com ele irei conseguir identificá-lo melhor.\n";
                    }
                    break;

                case gender_field:
                    gender = f.value;
                    break;

                case client_id_field:
                    if (f.value != "")
                    {
                        card = f.value;
                    }
                    break;
                }
            }

            if (email != StateHelper.GetUser(context).Email&& UserController.getUserByEmail(email) != null && email != "")
            {
                fail += "O email que inseriu já está associado a uma outra conversa.\n";
            }
            else
            {
                Random r = new Random();
                UserController.CreateUser(email, name, (r.Next(25) + 1).ToString(), gender);
                User u = UserController.getUserByEmail(email);
                ContextController.CreateContext(u);
                CRMController.AddCustomer(u);

                if (card != "0")
                {
                    UserController.SetCustomerCard(u, card);
                    u.CustomerCard = card;
                }

                StateHelper.SetUser(context, u);
            }
            return(fail);
        }
Example #3
0
        public ActionResult Puck(string variant = null)
        {
            try
            {
                StateHelper.SetFirstRequestUrl();
                if (PuckCache.ShouldSync && !PuckCache.IsSyncQueued)
                {
                    PuckCache.IsSyncQueued = true;
                    //was using HostingEnvironment.QueueBackgroundWorkItem and passing in cancellation token
                    //can't do that in asp.net core so passing in a new cancellation token which is a bit pointless
                    System.Threading.Tasks.Task.Factory.StartNew(() => SyncHelper.Sync(new CancellationToken()));
                }
                var    uri  = Request.GetUri();
                string path = uri.AbsolutePath.ToLower();

                var dmode = this.GetDisplayModeId();

                if (path == "/")
                {
                    path = string.Empty;
                }

                string domain = uri.Host.ToLower();
                string searchPathPrefix;
                if (!PuckCache.DomainRoots.TryGetValue(domain, out searchPathPrefix))
                {
                    if (!PuckCache.DomainRoots.TryGetValue("*", out searchPathPrefix))
                    {
                        throw new Exception("domain roots not set. DOMAIN:" + domain);
                    }
                }
                string searchPath = searchPathPrefix.ToLower() + path;

                //do redirects
                string redirectUrl;
                if (PuckCache.Redirect301.TryGetValue(searchPath, out redirectUrl))
                {
                    Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromMinutes(PuckCache.RedirectOuputCacheMinutes)
                    };
                    Response.Redirect(redirectUrl, true);
                }
                if (PuckCache.Redirect302.TryGetValue(searchPath, out redirectUrl))
                {
                    Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                    {
                        Public = true,
                        MaxAge = TimeSpan.FromMinutes(PuckCache.RedirectOuputCacheMinutes)
                    };
                    Response.Redirect(redirectUrl, false);
                }

                if (string.IsNullOrEmpty(variant))
                {
                    variant = GetVariant(searchPath);
                }
                HttpContext.Items["variant"] = variant;
                //set thread culture for future api calls on this thread
                //Thread.CurrentThread.CurrentCulture = CultureInfo.CreateSpecificCulture(variant);
                IList <Dictionary <string, string> > results;
#if DEBUG
                using (MiniProfiler.Current.Step("lucene"))
                {
                    results = puck.core.Helpers.QueryHelper <BaseModel> .Query(
                        string.Concat("+", FieldKeys.Published, ":true", " +", FieldKeys.Path, ":", $"\"{searchPath}\"", " +", FieldKeys.Variant, ":", variant)
                        );
                }
#else
                results = puck.core.Helpers.QueryHelper <BaseModel> .Query(
                    string.Concat("+", FieldKeys.Published, ":true", " +", FieldKeys.Path, ":", $"\"{searchPath}\"", " +", FieldKeys.Variant, ":", variant)
                    );
#endif
                var       result = results == null ? null : results.FirstOrDefault();
                BaseModel model  = null;
                if (result != null)
                {
#if DEBUG
                    using (MiniProfiler.Current.Step("deserialize"))
                    {
                        model = JsonConvert.DeserializeObject(result[FieldKeys.PuckValue], ApiHelper.GetTypeFromName(result[FieldKeys.PuckType])) as BaseModel;
                    }
#else
                    model = JsonConvert.DeserializeObject(result[FieldKeys.PuckValue], ApiHelper.GetTypeFromName(result[FieldKeys.PuckType])) as BaseModel;
#endif
                    if (!PuckCache.OutputCacheExclusion.Contains(searchPath))
                    {
                        int cacheMinutes;
                        if (!PuckCache.TypeOutputCache.TryGetValue(result[FieldKeys.PuckType], out cacheMinutes))
                        {
                            if (!PuckCache.TypeOutputCache.TryGetValue(typeof(BaseModel).Name, out cacheMinutes))
                            {
                                cacheMinutes = PuckCache.DefaultOutputCacheMinutes;
                            }
                        }
                        Response.GetTypedHeaders().CacheControl = new Microsoft.Net.Http.Headers.CacheControlHeaderValue()
                        {
                            Public = true,
                            MaxAge = TimeSpan.FromMinutes(cacheMinutes)
                        };
                    }
                }

                if (model == null)
                {
                    //404
                    return(View(PuckCache.Path404));
                }
                var    cache = PuckCache.Cache;
                object cacheValue;
                //string templatePath = result[FieldKeys.TemplatePath];
                string templatePath = model.TemplatePath;

                if (!string.IsNullOrEmpty(dmode))
                {
                    string cacheKey = CacheKeys.PrefixTemplateExist + dmode + templatePath;
                    if (cache.TryGetValue(cacheKey, out cacheValue))
                    {
                        templatePath = cacheValue as string;
                    }
                    else
                    {
                        string dpath = templatePath.Insert(templatePath.LastIndexOf('.') + 1, dmode + ".");
                        if (System.IO.File.Exists(ApiHelper.MapPath(dpath)))
                        {
                            templatePath = dpath;
                        }
                        var cacheEntryOptions = new MemoryCacheEntryOptions()
                                                .SetSlidingExpiration(TimeSpan.FromMinutes(PuckCache.DisplayModesCacheMinutes));
                        cache.Set(cacheKey, templatePath, cacheEntryOptions);
                    }
                }
                return(View(templatePath, model));
            }
            catch (Exception ex)
            {
                PuckCache.PuckLog.Log(ex);
                ViewBag.Error = ex.Message;
                return(View(PuckCache.Path500));
            }
        }
Example #4
0
 public void SyncObjectState(object entity)
 {
     Entry(entity).State = StateHelper.ConvertState(((IObjectState)entity).ObjectState);
 }
        public static StateDictionary GetState(this ResultWrapper result)
        {
            var actionId = result.ActionId;

            return(StateHelper.InitializeState(actionId));
        }
 protected override Overtrade?ComputeByIndexImpl(IEnumerable <decimal> mappedInputs, int index)
 => StateHelper.IsOvertrade(_rsi[index]);
Example #7
0
        public Control RenderMacro(Hashtable pageElements, int documentId)
        {
            TraceInfo("renderMacro", string.Format("Rendering started (macro: {0}, type: {1}, cacheRate: {2})", Name, MacroType, Model.CacheDuration));

            StateHelper.SetContextValue(MacrosAddedKey, StateHelper.GetContextValue <int>(MacrosAddedKey) + 1);

            String  macroHtml    = null;
            Control macroControl = null;

            // zb-00037 #29875 : parse attributes here (and before anything else)
            foreach (var prop in Model.Properties)
            {
                prop.Value = helper.parseAttribute(pageElements, prop.Value);
            }

            Model.CacheIdentifier = GetCacheIdentifier(Model);


            if (Model.CacheDuration > 0)
            {
                if (CacheMacroAsString(Model))
                {
                    macroHtml = _macroCache["macroHtml_" + Model.CacheIdentifier] as String;

                    // FlorisRobbemont:
                    // An empty string means: macroHtml has been cached before, but didn't had any output (Macro doesn't need to be rendered again)
                    // An empty reference (null) means: macroHtml has NOT been cached before
                    if (macroHtml != null)
                    {
                        if (MacroNeedsToBeClearedFromCache(Model, "macroHtml_DateAdded_" + Model.CacheIdentifier))
                        {
                            macroHtml = null;
                            TraceInfo("renderMacro", string.Format("Macro removed from cache due to file change '{0}'.", Model.CacheIdentifier));
                        }
                        else
                        {
                            TraceInfo("renderMacro", string.Format("Macro Content loaded from cache '{0}'.", Model.CacheIdentifier));
                        }
                    }
                }
                else
                {
                    var cacheContent = _macroCache["macroControl_" + Model.CacheIdentifier] as MacroCacheContent;

                    if (cacheContent != null)
                    {
                        macroControl    = cacheContent.Content;
                        macroControl.ID = cacheContent.ID;

                        if (MacroNeedsToBeClearedFromCache(Model, "macroControl_DateAdded_" + Model.CacheIdentifier))
                        {
                            TraceInfo("renderMacro", string.Format("Macro removed from cache due to file change '{0}'.", Model.CacheIdentifier));
                            macroControl = null;
                        }
                        else
                        {
                            TraceInfo("renderMacro", string.Format("Macro Control loaded from cache '{0}'.", Model.CacheIdentifier));
                        }
                    }
                }
            }

            // FlorisRobbemont: Empty macroHtml (not null, but "") doesn't mean a re-render is necessary
            if (macroHtml == null && macroControl == null)
            {
                var renderFailed = false;
                var macroType    = Model.MacroType != MacroTypes.Unknown ? (int)Model.MacroType : MacroType;
                switch (macroType)
                {
                case (int)MacroTypes.XSLT:
                    macroControl = loadMacroXSLT(this, Model, pageElements);
                    break;

                case (int)MacroTypes.Script:
                    try
                    {
                        TraceInfo("umbracoMacro", "MacroEngine script added (" + ScriptFile + ")");

                        var result = LoadMacroScript(Model, documentId);
                        macroControl = new LiteralControl(result.Result);
                        if (result.ResultException != null)
                        {
                            // we'll throw the error if we run in release mode, show details if we're in release mode!
                            renderFailed = true;
                            if (HttpContext.Current != null && !HttpContext.Current.IsDebuggingEnabled)
                            {
                                throw result.ResultException;
                            }
                        }
                        break;
                    }
                    catch (Exception e)
                    {
                        renderFailed = true;
                        Exceptions.Add(e);
                        Log.Instance.LogError("RenderMacro: " + e);

                        var result = new LiteralControl("Error loading MacroEngine script (file: " + ScriptFile + ")");

                        macroControl = result;

                        break;
                    }

                default:
                    if (GlobalSettings.DebugMode)
                    {
                        macroControl = new LiteralControl("&lt;Macro: " + Name + " (" + ScriptAssembly + "," + ScriptType + ")&gt;");
                    }
                    break;
                }

                // Add result to cache if successful
                if (!renderFailed && Model.CacheDuration > 0)
                {
                    // do not add to cache if there's no member and it should cache by personalization
                    if (!Model.CacheByMember || (Model.CacheByMember && Member.GetCurrentMember() != null))
                    {
                        if (macroControl != null)
                        {
                            // NH: Scripts and XSLT can be generated as strings, but not controls as page events wouldn't be hit (such as Page_Load, etc)
                            if (CacheMacroAsString(Model))
                            {
                                string outputCacheString;

                                using (var sw = new StringWriter())
                                {
                                    var hw = new HtmlTextWriter(sw);
                                    macroControl.RenderControl(hw);

                                    outputCacheString = sw.ToString();
                                }

                                _macroCache.Insert("macroHtml_" + Model.CacheIdentifier, outputCacheString, null, DateTime.Now.AddSeconds(Model.CacheDuration), TimeSpan.Zero, CacheItemPriority.NotRemovable,                                 //FlorisRobbemont: issue #27610 -> Macro output cache should not be removable

                                                   null);


                                _macroCache.Insert("macroHtml_DateAdded_" + Model.CacheIdentifier, DateTime.Now, null, DateTime.Now.AddSeconds(Model.CacheDuration), TimeSpan.Zero, CacheItemPriority.NotRemovable,                                 //FlorisRobbemont: issue #27610 -> Macro output cache should not be removable
                                                   null);

                                // zb-00003 #29470 : replace by text if not already text
                                // otherwise it is rendered twice
                                if (!(macroControl is LiteralControl))
                                {
                                    macroControl = new LiteralControl(outputCacheString);
                                }

                                TraceInfo("renderMacro", string.Format("Macro Content saved to cache '{0}'.", Model.CacheIdentifier));
                            }

                            else
                            {
                                _macroCache.Insert("macroControl_" + Model.CacheIdentifier, new MacroCacheContent(macroControl, macroControl.ID), null, DateTime.Now.AddSeconds(Model.CacheDuration), TimeSpan.Zero, CacheItemPriority.NotRemovable,                                 //FlorisRobbemont: issue #27610 -> Macro output cache should not be removable
                                                   null);


                                _macroCache.Insert("macroControl_DateAdded_" + Model.CacheIdentifier, DateTime.Now, null, DateTime.Now.AddSeconds(Model.CacheDuration), TimeSpan.Zero, CacheItemPriority.NotRemovable,                                 //FlorisRobbemont: issue #27610 -> Macro output cache should not be removable
                                                   null);

                                TraceInfo("renderMacro", string.Format("Macro Control saved to cache '{0}'.", Model.CacheIdentifier));
                            }
                        }
                    }
                }
            }
            else if (macroControl == null)
            {
                macroControl = new LiteralControl(macroHtml);
            }

            return(macroControl);
        }
Example #8
0
 protected override Trend?ComputeByIndexImpl(int index)
 => StateHelper.IsTrending(_closePriceChange[index]);
Example #9
0
        private bool validateAccess(XmlNode node)
        {
            // check if this area should be shown at all
            string onlyOnceValue = StateHelper.GetCookieValue(generateCookieKey(node));

            if (!String.IsNullOrEmpty(onlyOnceValue))
            {
                return(false);
            }

            // the root user can always see everything
            if (CurrentUser.IsRoot())
            {
                return(true);
            }
            else if (node != null)
            {
                XmlNode accessRules = node.SelectSingleNode("access");
                bool    retVal      = true;
                if (accessRules != null && accessRules.HasChildNodes)
                {
                    string currentUserType = CurrentUser.UserType.Alias.ToLowerInvariant();

                    //Update access rules so we'll be comparing lower case to lower case always

                    var denies = accessRules.SelectNodes("deny");
                    foreach (XmlNode deny in denies)
                    {
                        deny.InnerText = deny.InnerText.ToLowerInvariant();
                    }

                    var grants = accessRules.SelectNodes("grant");
                    foreach (XmlNode grant in grants)
                    {
                        grant.InnerText = grant.InnerText.ToLowerInvariant();
                    }

                    string allowedSections = ",";
                    foreach (BusinessLogic.Application app in CurrentUser.Applications)
                    {
                        allowedSections += app.alias.ToLower() + ",";
                    }
                    XmlNodeList grantedTypes          = accessRules.SelectNodes("grant");
                    XmlNodeList grantedBySectionTypes = accessRules.SelectNodes("grantBySection");
                    XmlNodeList deniedTypes           = accessRules.SelectNodes("deny");

                    // if there's a grant type, everyone who's not granted is automatically denied
                    if (grantedTypes.Count > 0 || grantedBySectionTypes.Count > 0)
                    {
                        retVal = false;
                        if (grantedBySectionTypes.Count > 0 && accessRules.SelectSingleNode(String.Format("grantBySection [contains('{0}', concat(',',.,','))]", allowedSections)) != null)
                        {
                            retVal = true;
                        }
                        else if (grantedTypes.Count > 0 && accessRules.SelectSingleNode(String.Format("grant [. = '{0}']", currentUserType)) != null)
                        {
                            retVal = true;
                        }
                    }
                    // if the current type of user is denied we'll say nay
                    if (deniedTypes.Count > 0 && accessRules.SelectSingleNode(String.Format("deny [. = '{0}']", currentUserType)) != null)
                    {
                        retVal = false;
                    }
                }

                return(retVal);
            }
            return(false);
        }
        public async Task OnGameActionRequested(GameActionRequest actionRequest, StateHelper stateHelper)
        {
            // OnGameActionRequested is called when the bot actually needs to take an action. Below is an example of how this can
            // be done and what events your bot will need to handle.
            //
            // To see all of the actions your must handle, look at GameActionType.
            //
            // actionRequest.State is the root of the state object for the game. This holds all things like players, coin amounts,
            // what building are in the marketplace, states of the current turn, etc.
            // Essentially, this object is everything you would see on the table when playing the game.
            //
            // The statehelper is a very useful tool that will answer many current state questions. The state helper takes a perspective user
            // when it's created, that it will use as a default player if no player is given.
            // For example, the Player.GetPlayerName function takes an option playerIndex. If not given, it will return your name.
            //
            // There are 4 modules to the state helper. Each helper has functions specific the to topic.
            //     Player
            //         ex. GetPlayer(), GetNumberOfLandmarksOwned(), GetMaxRollsAllowed(), CanHaveExtraTurn()
            //     Marketplace
            //         ex. GetMaxBuildingsInGame(), GetBuiltBuildingsInCurrentGame(), GetBuildingTypesBuildableInMarketplace()
            //     CurrentTurn
            //         ex. CanRollOrReRoll(), GetPossibleActions(), CanTakeAction()
            //     BuildingRules
            //         This helper holds all of the building types and the rules of them. ex. BuildingRules[buildingIndex].GetColor()
            //

            // Always roll if it's an option.
            if (actionRequest.PossibleActions.Contains(GameActionType.RollDice))
            {
                // How many dice can we roll?
                int maxDiceCount = stateHelper.Player.GetMaxCountOfDiceCanRoll();

                // Can we re-roll
                int  rollsSoFar = stateHelper.GetState().CurrentTurnState.Rolls;
                bool canReRoll  = stateHelper.Player.GetMaxRollsAllowed() < rollsSoFar;

                // If we can't reroll, auto commit the dice. Otherwise don't, so we can reroll if we want.
                Logger.Log(Log.Info, "Rolling the dice!");
                GameActionResponse result = await m_bot.SendAction(GameAction <object> .CreateRollDiceAction(maxDiceCount, !canReRoll));

                if (!result.Accepted)
                {
                    await Shutdown("failed to roll dice.", result.Error);
                }
                else
                {
                    Logger.Log(Log.Info, "Done");
                }
                return;
            }

            if (actionRequest.PossibleActions.Contains(GameActionType.CommitDiceResult))
            {
                // This action is used if you want to see the dice results before they are committed.
                // It's useful to see the results if you have the ability to re-roll, so you can decided to re-roll.
                // But if the `autoCommitResults` flag is set to true when you call `CreateRollDiceAction` this wont' get called,
                // because the server will always do this for you.

                GameActionResponse result = await m_bot.SendAction(GameAction <object> .CreateCommitDiceResultAction());

                if (!result.Accepted)
                {
                    await Shutdown("failed to commit dice.", result.Error);
                }
                else
                {
                    Logger.Log(Log.Info, "Done");
                }
            }

            if (actionRequest.PossibleActions.Contains(GameActionType.BuildBuilding))
            {
                // Get all building that are in the marketplace currently.
                List <int> buildable = stateHelper.Marketplace.GetBuildingTypesBuildableInMarketplace();

                // Filter it down to only buildings we can afford.
                List <int> affordable = stateHelper.Player.FilterBuildingIndexesWeCanAfford(buildable);

                // Randomly pick one.
                int buildingIndex = affordable[m_random.RandomInt(0, affordable.Count - 1)];

                Logger.Log(Log.Info, $"Requesting to build {stateHelper.BuildingRules[buildingIndex].GetName()}...");
                GameActionResponse result = await m_bot.SendAction(GameAction <object> .CreateBuildBuildingAction(buildingIndex));

                if (!result.Accepted)
                {
                    await Shutdown("failed to build building.", result.Error);
                }
                else
                {
                    Logger.Log(Log.Info, $"We just bought {stateHelper.BuildingRules[buildingIndex].GetName()}!");
                }
                return;
            }

            if (actionRequest.PossibleActions.Contains(GameActionType.TvStationPayout))
            {
                // Our Tv Station activated! Let's take 5 coins from a player at random.
                GamePlayer randomPlayer = GetRandomPlayer(stateHelper);

                Logger.Log(Log.Info, $"Our Tv Station was activated, let's take coins from player {randomPlayer.Name}!");
                GameActionResponse result = await m_bot.SendAction(GameAction <object> .CreateTvStationPayoutAction(randomPlayer.PlayerIndex));

                if (!result.Accepted)
                {
                    // If random bot fails, it instantly shuts down.
                    await Shutdown("failed to respond to tv station payout.", result.Error);
                }
                else
                {
                    Logger.Log(Log.Info, $"We taken coins from player {randomPlayer.Name} for our tv station!");
                }
                return;
            }

            if (actionRequest.PossibleActions.Contains(GameActionType.BusinessCenterSwap))
            {
                // Our Business Center activated! Let's randomly pick a player and building to swap.
                GamePlayer   randomPlayer  = GetRandomPlayer(stateHelper);
                BuildingBase ourBuilding   = GetRandomOwnedNonMajorBuidling(stateHelper, null);
                BuildingBase theirBuilding = GetRandomOwnedNonMajorBuidling(stateHelper, randomPlayer.PlayerIndex);

                GameActionResponse result;
                if (randomPlayer == null || ourBuilding == null || theirBuilding == null)
                {
                    // If there aren't any building we can use, skip the action.
                    Logger.Log(Log.Info, $"Our Business Center was activated, but there weren't the correct building to swap. So we will skip!");
                    result = await m_bot.SendAction(GameAction <object> .CreateBusinessCenterSwapAction(0, 0, 0, true));
                }
                else
                {
                    Logger.Log(Log.Info, $"Our Business Center was activated, swap our {ourBuilding.GetName()} for {randomPlayer.Name}'s {theirBuilding.GetName()}!");
                    result = await m_bot.SendAction(GameAction <object> .CreateBusinessCenterSwapAction(randomPlayer.PlayerIndex, ourBuilding.GetBuildingIndex(), theirBuilding.GetBuildingIndex()));
                }

                if (!result.Accepted)
                {
                    // If random bot fails, it instantly shuts down.
                    await Shutdown("failed to respond to business center swap.", result.Error);
                }
                else
                {
                    Logger.Log(Log.Info, $"Business center swap done!");
                }
                return;
            }

            if (actionRequest.PossibleActions.Contains(GameActionType.EndTurn))
            {
                // If we can't roll the dice or build a building, we must not have enough funds.
                // Just end the turn.

                Logger.Log(Log.Info, "There's nothing to do, requesting turn end...");
                GameActionResponse result = await m_bot.SendAction(GameAction <object> .CreateEndTurnAction());

                if (!result.Accepted)
                {
                    // If random bot fails, it instantly shuts down.
                    await Shutdown("failed to end our turn.", result.Error);
                }
                else
                {
                    Logger.Log(Log.Info, $"We have {stateHelper.Player.GetPlayer().Coins} coins and can't buy anything, so we ended the turn.");
                }
                return;
            }

            Logger.Log(Log.Error, $"Hmm, we were asked for an action but didn't know what to do with...");
            foreach (GameActionType type in actionRequest.PossibleActions)
            {
                Logger.Log(Log.Error, $"  ... {type.ToString()}");
                await Shutdown("received an unknown action.", null);
            }
        }
Example #11
0
 public virtual void SyncEntityState <TEntity>(TEntity entity) where TEntity : class, IObjectState
 {
     entity.SyncObjectState(StateHelper.ConvertState(Entry(entity).State));
 }
 public void SetUp()
 {
     stateHelper = new StateHelper("Test");
 }
Example #13
0
        /// <summary>
        /// This method will parse the attribute value to look for some special syntax such as
        ///     [@requestKey]
        ///     [%sessionKey]
        ///     [#pageElement]
        ///     [$recursiveValue]
        /// </summary>
        /// <param name="pageElements"></param>
        /// <param name="attributeValue"></param>
        /// <returns></returns>
        /// <remarks>
        /// You can even apply fallback's separated by comma's like:
        ///
        ///     [@requestKey],[%sessionKey]
        ///
        /// </remarks>
        public static string parseAttribute(IDictionary pageElements, string attributeValue)
        {
            // Check for potential querystring/cookie variables
            // SD: not sure why we are checking for len 3 here?
            if (attributeValue.Length > 3 && attributeValue.StartsWith("["))
            {
                var attributeValueSplit = (attributeValue).Split(',');

                // before proceeding, we don't want to process anything here unless each item starts/ends with a [ ]
                // this is because the attribute value could actually just be a json array like [1,2,3] which we don't want to parse
                //
                // however, the last one can be a literal, must take care of this!
                // so here, don't check the last one, which can be just anything
                if (attributeValueSplit.Take(attributeValueSplit.Length - 1).All(x =>
                                                                                 //must end with [
                                                                                 x.EndsWith("]") &&
                                                                                 //must start with [ and a special char
                                                                                 (x.StartsWith("[@") || x.StartsWith("[%") || x.StartsWith("[#") || x.StartsWith("[$"))) == false)
                {
                    return(attributeValue);
                }

                foreach (var attributeValueItem in attributeValueSplit)
                {
                    attributeValue = attributeValueItem;
                    var trimmedValue = attributeValue.Trim();

                    // Check for special variables (always in square-brackets like [name])
                    if (trimmedValue.StartsWith("[") &&
                        trimmedValue.EndsWith("]"))
                    {
                        attributeValue = trimmedValue;

                        // find key name
                        var keyName = attributeValue.Substring(2, attributeValue.Length - 3);
                        var keyType = attributeValue.Substring(1, 1);

                        switch (keyType)
                        {
                        case "@":
                            attributeValue = HttpContext.Current.Request[keyName];
                            break;

                        case "%":
                            attributeValue = StateHelper.GetSessionValue <string>(keyName);
                            if (String.IsNullOrEmpty(attributeValue))
                            {
                                attributeValue = StateHelper.GetCookieValue(keyName);
                            }
                            break;

                        case "#":
                            if (pageElements[keyName] != null)
                            {
                                attributeValue = pageElements[keyName].ToString();
                            }
                            else
                            {
                                attributeValue = "";
                            }
                            break;

                        case "$":
                            if (pageElements[keyName] != null && pageElements[keyName].ToString() != string.Empty)
                            {
                                attributeValue = pageElements[keyName].ToString();
                            }
                            else
                            {
                                // reset attribute value in case no value has been found on parents
                                attributeValue = String.Empty;
                                XmlDocument umbracoXML = presentation.UmbracoContext.Current.GetXml();

                                String[] splitpath = (String[])pageElements["splitpath"];
                                for (int i = 0; i < splitpath.Length - 1; i++)
                                {
                                    XmlNode element = umbracoXML.GetElementById(splitpath[splitpath.Length - i - 1].ToString());
                                    if (element == null)
                                    {
                                        continue;
                                    }
                                    string  xpath       = UmbracoConfig.For.UmbracoSettings().Content.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "{0}";
                                    XmlNode currentNode = element.SelectSingleNode(string.Format(xpath,
                                                                                                 keyName));
                                    if (currentNode != null && currentNode.FirstChild != null &&
                                        !string.IsNullOrEmpty(currentNode.FirstChild.Value) &&
                                        !string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim()))
                                    {
                                        HttpContext.Current.Trace.Write("parameter.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]);
                                        attributeValue = currentNode.FirstChild.Value;
                                        break;
                                    }
                                }
                            }
                            break;
                        }

                        if (attributeValue != null)
                        {
                            attributeValue = attributeValue.Trim();
                            if (attributeValue != string.Empty)
                            {
                                break;
                            }
                        }
                        else
                        {
                            attributeValue = string.Empty;
                        }
                    }
                }
            }

            return(attributeValue);
        }
Example #14
0
        public JsonResult Edit(Settings model)
        {
            string msg     = "";
            bool   success = false;

            try
            {
                // TODO: Add update logic here
                //default language
                if (!string.IsNullOrEmpty(model.DefaultLanguage))
                {
                    var metaDL = repo.GetPuckMeta().Where(x => x.Name == DBNames.Settings && x.Key == DBKeys.DefaultLanguage).FirstOrDefault();
                    if (metaDL != null)
                    {
                        metaDL.Value = model.DefaultLanguage;
                    }
                    else
                    {
                        var newMeta = new PuckMeta();
                        newMeta.Name  = DBNames.Settings;
                        newMeta.Key   = DBKeys.DefaultLanguage;
                        newMeta.Value = model.DefaultLanguage;
                        repo.AddMeta(newMeta);
                    }
                }
                //enable local prefix
                var metaELP = repo.GetPuckMeta().Where(x => x.Name == DBNames.Settings && x.Key == DBKeys.EnableLocalePrefix).FirstOrDefault();
                if (metaELP != null)
                {
                    metaELP.Value = model.EnableLocalePrefix.ToString();
                }
                else
                {
                    var newMeta = new PuckMeta();
                    newMeta.Name  = DBNames.Settings;
                    newMeta.Key   = DBKeys.EnableLocalePrefix;
                    newMeta.Value = model.EnableLocalePrefix.ToString();
                    repo.AddMeta(newMeta);
                }
                //languages
                if (model.Languages != null && model.Languages.Count > 0)
                {
                    var metaLanguages = repo.GetPuckMeta().Where(x => x.Name == DBNames.Settings && x.Key == DBKeys.Languages).ToList();
                    if (metaLanguages.Count > 0)
                    {
                        metaLanguages.ForEach(x =>
                        {
                            repo.DeleteMeta(x);
                        });
                    }
                    model.Languages.ForEach(x => {
                        var newMeta   = new PuckMeta();
                        newMeta.Name  = DBNames.Settings;
                        newMeta.Key   = DBKeys.Languages;
                        newMeta.Value = x;
                        repo.AddMeta(newMeta);
                    });
                }
                //redirects
                if (model.Redirect != null && model.Redirect.Count > 0)
                {
                    var redirectMeta = repo.GetPuckMeta().Where(x => x.Name == DBNames.Redirect301 || x.Name == DBNames.Redirect302).ToList();
                    redirectMeta.ForEach(x => {
                        repo.DeleteMeta(x);
                    });
                    //count of 1 and key/value of null indicates delete only so inserts are skipped
                    if (!(model.Redirect.Count == 1 && string.IsNullOrEmpty(model.Redirect.First().Key)))
                    {
                        model.Redirect.ToList().ForEach(x =>
                        {
                            var newMeta   = new PuckMeta();
                            newMeta.Name  = x.Key.StartsWith(DBNames.Redirect301) ? DBNames.Redirect301 : DBNames.Redirect302;
                            newMeta.Key   = x.Key.Substring(newMeta.Name.Length);
                            newMeta.Value = x.Value;
                            repo.AddMeta(newMeta);
                        });
                    }
                }
                //fieldgroup
                if (model.TypeGroupField != null && model.TypeGroupField.Count > 0)
                {
                    foreach (var mod in apiHelper.AllModels(true))
                    {
                        var fieldGroupMeta = repo.GetPuckMeta().Where(x => x.Name.StartsWith(DBNames.FieldGroups + mod.AssemblyQualifiedName)).ToList();
                        fieldGroupMeta.ForEach(x =>
                        {
                            repo.DeleteMeta(x);
                        });
                    }
                    model.TypeGroupField.ForEach(x => {
                        var values    = x.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        var newMeta   = new PuckMeta();
                        newMeta.Name  = DBNames.FieldGroups + values[0];
                        newMeta.Key   = values[1];
                        newMeta.Value = values[2];
                        repo.AddMeta(newMeta);
                    });
                }
                //typeallowedtypes
                if (model.TypeAllowedTypes != null && model.TypeAllowedTypes.Count > 0)
                {
                    var typeAllowedTypesMeta = repo.GetPuckMeta().Where(x => x.Name == DBNames.TypeAllowedTypes).ToList();
                    typeAllowedTypesMeta.ForEach(x => {
                        repo.DeleteMeta(x);
                    });
                    model.TypeAllowedTypes.ForEach(x => {
                        var values    = x.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        var newMeta   = new PuckMeta();
                        newMeta.Name  = DBNames.TypeAllowedTypes;
                        newMeta.Key   = values[0];
                        newMeta.Value = values[1];
                        repo.AddMeta(newMeta);
                    });
                }
                //typeallowedtemplates
                if (model.TypeAllowedTemplates != null && model.TypeAllowedTemplates.Count > 0)
                {
                    var typeAllowedTemplatesMeta = repo.GetPuckMeta().Where(x => x.Name == DBNames.TypeAllowedTemplates).ToList();
                    typeAllowedTemplatesMeta.ForEach(x =>
                    {
                        repo.DeleteMeta(x);
                    });
                    model.TypeAllowedTemplates.ForEach(x =>
                    {
                        var values    = x.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries);
                        var newMeta   = new PuckMeta();
                        newMeta.Name  = DBNames.TypeAllowedTemplates;
                        newMeta.Key   = values[0];
                        newMeta.Value = values[1];
                        repo.AddMeta(newMeta);
                    });
                }
                //cachepolicy
                if (model.CachePolicy == null)
                {
                    model.CachePolicy = new List <string>();
                }
                var cacheTypes = new List <string>();
                if (model.CachePolicy.Count > 0)
                {
                    foreach (var entry in model.CachePolicy)
                    {
                        var type = entry.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[0];
                        cacheTypes.Add(type);
                        var minutes = entry.Split(new char[] { ':' }, StringSplitOptions.RemoveEmptyEntries)[1];
                        int min;
                        if (!int.TryParse(minutes, out min))
                        {
                            throw new Exception("cache policy minutes not int for type:" + type);
                        }
                        var meta = repo.GetPuckMeta().Where(x => x.Name == DBNames.CachePolicy && x.Key.ToLower().Equals(type.ToLower())).FirstOrDefault();
                        if (meta != null)
                        {
                            meta.Value = minutes;
                        }
                        else
                        {
                            meta = new PuckMeta()
                            {
                                Name = DBNames.CachePolicy, Key = type, Value = minutes
                            };
                            repo.AddMeta(meta);
                        }
                    }
                }
                //delete unset
                repo.GetPuckMeta().Where(x => x.Name == DBNames.CachePolicy && !cacheTypes.Contains(x.Key)).ToList().ForEach(x => repo.DeleteMeta(x));

                //orphan types
                if (model.Orphans != null && model.Orphans.Count > 0)
                {
                    foreach (var entry in model.Orphans)
                    {
                        var t1 = entry.Key;
                        var t2 = entry.Value;
                        contentService.RenameOrphaned(t1, t2);
                    }
                }
                repo.SaveChanges();
                StateHelper.UpdateDefaultLanguage();
                StateHelper.UpdateCacheMappings();
                StateHelper.UpdateRedirectMappings();

                success = true;
            }
            catch (Exception ex)
            {
                msg     = ex.Message;
                success = false;
            }
            return(Json(new { success = success, message = msg }));
        }
Example #15
0
        public static string parseAttribute(IDictionary pageElements, string attributeValue)
        {
            // Check for potential querystring/cookie variables
            if (attributeValue.Length > 3 && attributeValue.Substring(0, 1) == "[")
            {
                string[] attributeValueSplit = (attributeValue).Split(',');
                foreach (string attributeValueItem in attributeValueSplit)
                {
                    attributeValue = attributeValueItem;

                    // Check for special variables (always in square-brackets like [name])
                    if (attributeValueItem.Substring(0, 1) == "[" &&
                        attributeValueItem.Substring(attributeValueItem.Length - 1, 1) == "]")
                    {
                        // find key name
                        string keyName = attributeValueItem.Substring(2, attributeValueItem.Length - 3);
                        string keyType = attributeValueItem.Substring(1, 1);

                        switch (keyType)
                        {
                        case "@":
                            attributeValue = HttpContext.Current.Request[keyName];
                            break;

                        case "%":
                            attributeValue = StateHelper.GetSessionValue <string>(keyName);
                            if (String.IsNullOrEmpty(attributeValue))
                            {
                                attributeValue = StateHelper.GetCookieValue(keyName);
                            }
                            break;

                        case "#":
                            if (pageElements[keyName] != null)
                            {
                                attributeValue = pageElements[keyName].ToString();
                            }
                            else
                            {
                                attributeValue = "";
                            }
                            break;

                        case "$":
                            if (pageElements[keyName] != null && pageElements[keyName].ToString() != string.Empty)
                            {
                                attributeValue = pageElements[keyName].ToString();
                            }
                            else
                            {
                                // reset attribute value in case no value has been found on parents
                                attributeValue = String.Empty;
                                XmlDocument umbracoXML = presentation.UmbracoContext.Current.GetXml();

                                String[] splitpath = (String[])pageElements["splitpath"];
                                for (int i = 0; i < splitpath.Length - 1; i++)
                                {
                                    XmlNode element = umbracoXML.GetElementById(splitpath[splitpath.Length - i - 1].ToString());
                                    if (element == null)
                                    {
                                        continue;
                                    }
                                    string  xpath       = UmbracoSettings.UseLegacyXmlSchema ? "./data [@alias = '{0}']" : "{0}";
                                    XmlNode currentNode = element.SelectSingleNode(string.Format(xpath,
                                                                                                 keyName));
                                    if (currentNode != null && currentNode.FirstChild != null &&
                                        !string.IsNullOrEmpty(currentNode.FirstChild.Value) &&
                                        !string.IsNullOrEmpty(currentNode.FirstChild.Value.Trim()))
                                    {
                                        HttpContext.Current.Trace.Write("parameter.recursive", "Item loaded from " + splitpath[splitpath.Length - i - 1]);
                                        attributeValue = currentNode.FirstChild.Value;
                                        break;
                                    }
                                }
                            }
                            break;
                        }

                        if (attributeValue != null)
                        {
                            attributeValue = attributeValue.Trim();
                            if (attributeValue != string.Empty)
                            {
                                break;
                            }
                        }
                        else
                        {
                            attributeValue = string.Empty;
                        }
                    }
                }
            }

            return(attributeValue);
        }