Пример #1
0
        public override string GetResponsiveImageUrl(string url, double aspect, string widthFactor, int containerSize = 0)
        {
            int width = GetResponsiveWidth(widthFactor, containerSize);

            //Round the width to the nearest set limit point - important as we do not want
            //to swamp the cache with lots of different sized versions of the same image
            for (int i = 0; i < ImageWidths.Count; i++)
            {
                if (width <= ImageWidths[i] || i == ImageWidths.Count - 1)
                {
                    width = ImageWidths[i];
                    break;
                }
            }

            //Height is calculated from the aspect ratio (0 means preserve aspect ratio)
            string height = (aspect == 0) ? String.Empty : ((int)Math.Ceiling(width / aspect)).ToString(CultureInfo.InvariantCulture);

            //Build the URL
            url = SiteConfiguration.MakeFullUrl(url, WebRequestContext.Localization);
            //remap localhost to real hostname for CID service
            Uri tmp = new Uri(url);

            url = tmp.GetLeftPart(UriPartial.Authority).Replace("localhost", _hostname, StringComparison.InvariantCultureIgnoreCase) + tmp.PathAndQuery;
            // get prefix
            string prefix = url.StartsWith("https") ? "https/" : string.Empty;

            // should encode the url incase it contains special chars in a query string or something
            url = HttpUtility.UrlPathEncode(url.Substring(url.IndexOf("://", StringComparison.Ordinal) + 3));
            return(String.Format(ImageResizeUrlFormat, _cidBaseUrl, width, height, prefix, url));
        }
Пример #2
0
 public TwitterService(SiteConfiguration siteConfiguration, ITwitterClient twitterClient, ITinyUrlService tinyUrlService, IUrlResolver urlResolver)
 {
     _urlResolver       = urlResolver;
     _tinyUrlService    = tinyUrlService;
     _siteConfiguration = siteConfiguration;
     _twitterClient     = twitterClient;
 }
Пример #3
0
        public AssetHandlerManager(SiteConfiguration configuration, Io io,
            IEnumerable<IHandlerPlugin> customHandlerPlugins)
        {
            _configuration = configuration;
            _io = io;
            TemplateHandler = new TemplateHandler(configuration, io, this);
            PostHandler = new PostHandler(configuration, io);
            GeneratedContentHandler = new GeneratedContentHandler(configuration);
            MarkdownPageHandler = new MarkdownPageHandler(configuration, io);
            TransformableContentHandler = new TransformableContentHandler(configuration, io);
            StaticContentHandler = new StaticContentHandler(configuration, io);

            _allHandlers = new List<IAssetHandler>
                {
                    TemplateHandler,
                    PostHandler,
                    GeneratedContentHandler,
                    MarkdownPageHandler,
                    TransformableContentHandler
                };

            var customHandlers = customHandlerPlugins.Select(plugin => plugin.CreateHandler(configuration, io));
            _allHandlers.AddRange(customHandlers);

            _allHandlers.Add(StaticContentHandler);
        }
 public HomeController(
     IOptions <SiteConfiguration> settings,
     ILogger <HomeController> logger)
 {
     _siteConfiguration = settings.Value;
     _logger            = logger;
 }
Пример #5
0
        public void ToSiteConfiguration(SiteConfiguration config)
        {
            config.ID                           = id;
            config.Name                         = name;
            config.Host                         = host;
            config.LanguageDefault              = languageDefault;
            config.PageTitleSeparator           = pageTitleSeparator;
            config.ThemeDefault                 = themeDefault;
            config.FavIconUrl                   = favIconUrl;
            config.ScriptsPath                  = scriptsPath;
            config.CssPath                      = cssFilePath;
            config.ImagesPath                   = imagesPath;
            config.CommentAnonymousStateDefault = commentAnonymousStateDefault;
            config.EmailUsername                = emailUsername;
            config.IncludeOpenSearch            = includeOpenSearch;
            config.AuthorAutoSubscribe          = authorAutoSubscribe;
            config.PostEditTimeout              = postEditTimeout;
            config.SEORobots                    = seoRobots;
            config.GravatarDefault              = gravatarDefault;
            config.TrackbacksEnabled            = trackbacksEnabled;

            if (aliases != null)
            {
                aliases.Each(a => config.AddAlias(a.ToAlias()));
            }
        }
Пример #6
0
        //*********************************************************************
        //
        // GetModuleSettings Method  <a name="GetModuleSettings"></a>
        //
        // The GetModuleSettings Method returns a hashtable of custom,
        // module-specific settings from the configuration file.  This method is
        // used by some user control modules (Xml, Image, etc) to access misc
        // settings.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        public static Hashtable GetModuleSettings(int moduleId)
        {
            // Create a new Hashtable
            Hashtable _settingsHT = new Hashtable();

            // Obtain SiteSettings from Current Context
            SiteConfiguration siteSettings = (SiteConfiguration)HttpContext.Current.Items["SiteSettings"];

            // Find the appropriate Module in the Module table
            SiteConfiguration.ModuleRow moduleRow = siteSettings.Module.FindByModuleId(moduleId);

            // Find the first (only) settings element
            if (moduleRow.GetSettingsRows().Length > 0)
            {
                SiteConfiguration.SettingsRow settingsRow = moduleRow.GetSettingsRows()[0];

                if (settingsRow != null)
                {
                    // Find the child setting elements and add to the hashtable
                    foreach (SiteConfiguration.SettingRow sRow in settingsRow.GetSettingRows())
                    {
                        _settingsHT[sRow.Name] = sRow.Setting_Text;
                    }
                }
            }

            return(_settingsHT);
        }
Пример #7
0
        //*********************************************************************
        //
        // GetSiteSettings Static Method
        //
        // The Configuration.GetSiteSettings Method returns a typed
        // dataset of the all of the site configuration settings from the
        // XML configuration file.  This method is used in Global.asax to
        // push the settings into the current HttpContext, so that all of the
        // pages, content modules and classes throughout the rest of the request
        // may access them.
        //
        // The SiteConfiguration object is cached using the ASP.NET Cache API,
        // with a file-change dependency on the XML configuration file.  Normallly,
        // this method just returns a copy of the object in the cache.  When the
        // configuration is updated and changes are saved to the the XML file,
        // the SiteConfiguration object is evicted from the cache.  The next time
        // this method runs, it will read from the XML file again and insert a
        // fresh copy of the SiteConfiguration into the cache.
        //
        //*********************************************************************
        public static SiteConfiguration GetSiteSettings()
        {
            SiteConfiguration siteSettings = (SiteConfiguration)HttpContext.Current.Cache["SiteSettings"];

            // If the SiteConfiguration isn't cached, load it from the XML file and add it into the cache.
            if (siteSettings == null)
            {
                // Create the dataset
                siteSettings = new SiteConfiguration();

                // Retrieve the location of the XML configuration file
                string configFile = HttpContext.Current.Server.MapPath(ConfigurationSettings.AppSettings["configFile"]);

                // Set the AutoIncrement property to true for easier adding of rows
                siteSettings.Tab.TabIdColumn.AutoIncrement       = true;
                siteSettings.Module.ModuleIdColumn.AutoIncrement = true;
                siteSettings.ModuleDefinition.ModuleDefIdColumn.AutoIncrement = true;

                // Load the XML data into the DataSet
                siteSettings.ReadXml(configFile);

                // Store the dataset in the cache
                HttpContext.Current.Cache.Insert("SiteSettings", siteSettings, new CacheDependency(configFile));
            }

            return(siteSettings);
        }
Пример #8
0
        //*********************************************************************
        //
        // DeleteModule Method  <a name="DeleteModule"></a>
        //
        // The DeleteModule method deletes a specified Module from the settings
        // stored in the Xml file PortalCfg.xml.  This method also deletes any
        // data from the database associated with this module.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //	  + <a href="DeleteModule.htm" style="color:green">DeleteModule stored procedure</a>
        //
        //*********************************************************************
        public void DeleteModule(int moduleId)
        {
            // Obtain SiteSettings from Current Context
            SiteConfiguration siteSettings = (SiteConfiguration)HttpContext.Current.Items["SiteSettings"];

            //
            // Delete information in the Database relating to Module being deleted
            //

            // Create Instance of Connection and Command Object
            SqlConnection myConnection = new SqlConnection(ConfigurationSettings.AppSettings["connectionString"]);
            SqlCommand    myCommand    = new SqlCommand("Portal_DeleteModule", myConnection);

            // Mark the Command as a SPROC
            myCommand.CommandType = CommandType.StoredProcedure;

            // Add Parameters to SPROC
            SqlParameter parameterModuleID = new SqlParameter("@ModuleID", SqlDbType.Int, 4);

            myConnection.Open();

            parameterModuleID.Value = moduleId;
            myCommand.Parameters.Add(parameterModuleID);

            // Open the database connection and execute the command
            myCommand.ExecuteNonQuery();
            myConnection.Close();

            // Finish removing Module
            siteSettings.Module.RemoveModuleRow(siteSettings.Module.FindByModuleId(moduleId));

            // Save the changes
            SaveSiteSettings();
        }
        public void Schedule(SiteConfiguration siteConfiguration)
        {
            try
            {
                lock (_locker)
                {
                    if (_scheduledSiteChecks.TryGetValue(siteConfiguration.Id, out var scheduledSiteCheck))
                    {
                        scheduledSiteCheck.Change(
                            Timeout.Infinite,
                            Timeout.Infinite);
                    }

                    var siteStatusCheckIntervalInMilliseconds = _siteStatusCheckIntervalConverter.ConvertToMilliseconds(
                        siteConfiguration.SiteStatusCheckInterval,
                        siteConfiguration.SiteStatusCheckIntervalTypeId);

                    _scheduledSiteChecks[siteConfiguration.Id] = new Timer(
                        SiteStatusCheckEnqueuer(siteConfiguration),
                        null,
                        0,
                        siteStatusCheckIntervalInMilliseconds);
                }
            }
            catch (Exception exc)
            {
                Debug.WriteLine(exc.Message);
            }
        }
Пример #10
0
        public ActionResult ResetPassword(LoginPage currentPage, string token)
        {
            var service = ServiceLocator.Current.GetInstance <IResetPasswordService>();

            MembershipUser user;

            bool isResetUrlValid = service.IsResetUrlValid(token, out user);

            if (isResetUrlValid)
            {
                ResetPasswordViewModel model = new ResetPasswordViewModel(currentPage);
                model.Token             = token;
                model.ResetPasswordForm = new RegisterForm()
                {
                    Token    = token,
                    UserName = user.UserName
                };
                return(View(model));
            }
            else
            {
                // Token is invalid, we redirect to the login page
                string loginUrl = _urlResolver.GetUrl(SiteConfiguration.Current().Settings.LoginPage);
                return(new RedirectResult(loginUrl));
            }
        }
Пример #11
0
        //*********************************************************************
        //
        // AddModule Method  <a name="AddModule"></a>
        //
        // The AddModule method adds Portal Settings for a new Module within
        // a Tab.  These settings are stored in the Xml file PortalCfg.xml.
        //
        // Other relevant sources:
        //    + <a href="#SaveSiteSettings" style="color:green">SaveSiteSettings() method</a>
        //	  + <a href="PortalCfg.xml" style="color:green">PortalCfg.xml</a>
        //
        //*********************************************************************
        public int AddModule(int tabId, int moduleOrder, String paneName, String title, int moduleDefId, int cacheTime, String editRoles, bool showMobile)
        {
            // Obtain SiteSettings from Current Context
            SiteConfiguration siteSettings = (SiteConfiguration)HttpContext.Current.Items["SiteSettings"];

            // Create a new ModuleRow from the Module table
            SiteConfiguration.ModuleRow newModule = siteSettings.Module.NewModuleRow();

            // Set the properties on the new Module
            newModule.ModuleDefId  = moduleDefId;
            newModule.ModuleOrder  = moduleOrder;
            newModule.ModuleTitle  = title;
            newModule.PaneName     = paneName;
            newModule.EditRoles    = editRoles;
            newModule.CacheTimeout = cacheTime;
            newModule.ShowMobile   = showMobile;
            newModule.TabRow       = siteSettings.Tab.FindByTabId(tabId);

            // Add the new ModuleRow to the Module table
            siteSettings.Module.AddModuleRow(newModule);

            // Save the changes
            SaveSiteSettings();

            // Return the new Module ID
            return(newModule.ModuleId);
        }
Пример #12
0
        public List <PatternMatch> LoadPatterns()
        {
            List <PatternMatch> patternMatches = new List <PatternMatch>();

            if (Tracker.IsActive)
            {
                if (SiteConfiguration.GetSiteSettingsItem() != null)
                {
                    MultilistField profiles = SiteConfiguration.GetSiteSettingsItem().Fields["Visible Profiles"];
                    foreach (Item visibleProfile in profiles.GetItems())
                    {
                        Item visibleProfileItem = Sitecore.Context.Database.GetItem(visibleProfile.ID);
                        if (visibleProfileItem != null)
                        {
                            // show the pattern match if there is one.
                            var userPattern = Tracker.Current.Interaction.Profiles[visibleProfileItem.Name];
                            if (userPattern != null)
                            {
                                // load the details about the matching pattern
                                Item matchingPattern = Sitecore.Context.Database.GetItem(userPattern.PatternId.ToId());
                                if (matchingPattern != null)
                                {
                                    Sitecore.Data.Items.MediaItem image = new Sitecore.Data.Items.MediaItem(((ImageField)matchingPattern.Fields["Image"]).MediaItem);
                                    string src = Sitecore.StringUtil.EnsurePrefix('/', Sitecore.Resources.Media.MediaManager.GetMediaUrl(image));
                                    patternMatches.Add(new PatternMatch(visibleProfileItem["Name"], matchingPattern.Name, src));
                                }
                            }
                        }
                    }
                }
            }
            return(patternMatches);
        }
Пример #13
0
        public void LoadFile(SiteConfiguration configuration)
        {
            var contents = _io.ReadFile(_absoluteFilePath, 3); ;
            this.Body = contents;

            ExtractMetadata();
        }
        public ActionResult SitesNavigation()
        {
            Item contentNode         = SiteConfiguration.GetHomeItem().Parent;
            List <GenericLink> sites = new List <GenericLink>();

            foreach (Item site in contentNode.Children.ToArray().Where(item => SiteConfiguration.DoesItemExistInCurrentLanguage(item)))
            {
                if (site["Show in Sites Menu"] == "1")
                {
                    sites.Add(new GenericLink(site["Site Name"], LinkManager.GetItemUrl(site), false));
                }
            }

            if (SiteConfiguration.GetExternalSitesItem() != null)
            {
                foreach (Item externalsite in SiteConfiguration.GetExternalSitesItem().Children)
                {
                    if (SiteConfiguration.DoesItemExistInCurrentLanguage(externalsite))
                    {
                        Sitecore.Data.Fields.LinkField lf = externalsite.Fields["Site Link"];
                        sites.Add(new GenericLink(lf.Text, lf.Url, true));
                    }
                }
            }

            // Don't show the drop down unless there are multiple sites
            return((sites.Count > 1) ? View("TertiaryNavigationPartialSites", sites as IEnumerable <GenericLink>) : null);
        }
Пример #15
0
        public List <string> LoadEngagementStates()
        {
            List <string> states = new List <string>();

            try
            {
                var engagementstates = AutomationStateManager.Create(Tracker.Current.Contact).GetAutomationStates();

                if (engagementstates.Any())
                {
                    foreach (
                        AutomationStateContext context in
                        AutomationStateManager.Create(Tracker.Current.Contact).GetAutomationStates())
                    {
                        states.Add(String.Format("{0}: {1}", context.PlanItem.DisplayName, context.StateItem.DisplayName));
                    }
                }
                else
                {
                    states.Add(SiteConfiguration.GetDictionaryText("No Engagement States"));
                }
            }
            catch (Exception)
            {
                states.Add(SiteConfiguration.GetDictionaryText("Unable to load Engagement States"));
            }
            return(states);
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            // load the labels from Sitecore
            if (!Page.IsPostBack)
            {
                litHeading.Text         = GetDictionaryText("Register Heading");
                lblName.Text            = GetDictionaryText("Name");
                lblEmail.Text           = GetDictionaryText("Email");
                lblPassword.Text        = GetDictionaryText("Password");
                lblConfirm.Text         = GetDictionaryText("Confirm Password");
                btnRegister.Text        = GetDictionaryText("Register Button");
                valName.Text            = GetDictionaryText("Required");
                valEmail.Text           = GetDictionaryText("Required");
                valPassword.Text        = GetDictionaryText("Required");
                valPasswordConfirm.Text = GetDictionaryText("Required");
                valEmailFormat.Text     = GetDictionaryText("Email is Not Valid");
            }

            Item config = SiteConfiguration.GetSiteSettingsItem();

            if (config["Allow Online Registration"] != "1")
            {
                txtName.Enabled            = false;
                txtEmail.Enabled           = false;
                txtPassword.Enabled        = false;
                txtPasswordConfirm.Enabled = false;
                btnRegister.Enabled        = false;
                lblMessage.Text            = GetDictionaryText("Regisration is currently disabled for this site.");
            }
        }
Пример #17
0
        /// <summary>
        /// Event handler that gets triggered just before the ASP.NET Request Handler gets executed.
        /// </summary>
        /// <param name="sender">The <see cref="HttpApplication"/> sending the event.</param>
        /// <param name="eventArgs">The event arguments.</param>
        private static void OnPreRequestHandlerExecute(object sender, EventArgs eventArgs)
        {
            HttpApplication application     = (HttpApplication)sender;
            HttpContext     context         = application.Context;
            HttpRequest     request         = context.Request;
            HttpResponse    response        = context.Response;
            string          urlPath         = request.Url.AbsolutePath;
            DateTime        ifModifiedSince = Convert.ToDateTime(request.Headers["If-Modified-Since"]);

            using (new Tracer(sender, eventArgs, urlPath, ifModifiedSince))
            {
                Localization localization   = WebRequestContext.Localization;
                string       staticsRootUrl = SiteConfiguration.GetLocalStaticsUrl(localization.LocalizationId);
                urlPath = urlPath.StartsWith("/" + staticsRootUrl) ? urlPath.Substring(staticsRootUrl.Length + 1) : urlPath;
                if (!localization.IsStaticContentUrl(urlPath))
                {
                    // Not a static content item; continue the HTTP pipeline.
                    return;
                }

                try
                {
                    using (StaticContentItem staticContentItem = SiteConfiguration.ContentProvider.GetStaticContentItem(urlPath, localization))
                    {
                        DateTime lastModified = staticContentItem.LastModified;
                        if (lastModified <= ifModifiedSince.AddSeconds(1))
                        {
                            Log.Debug("Static content item last modified at {0} => Sending HTTP 304 (Not Modified).", lastModified);
                            response.StatusCode      = (int)HttpStatusCode.NotModified;
                            response.SuppressContent = true;
                        }
                        else
                        {
                            // Items with a versioned URL can be cached long-term, because the URL will change if needed.
                            bool     isVersionedUrl = context.Items.Contains(IsVersionedUrlContextItem);
                            TimeSpan maxAge         = isVersionedUrl ? new TimeSpan(7, 0, 0, 0) : new TimeSpan(0, 1, 0, 0); // 1 Week or 1 Hour
                            response.Cache.SetLastModified(lastModified);                                                   // Allows the browser to do an If-Modified-Since request next time
                            response.Cache.SetCacheability(HttpCacheability.Public);                                        // Allow caching
                            response.Cache.SetMaxAge(maxAge);
                            response.Cache.SetExpires(DateTime.UtcNow.Add(maxAge));
                            response.ContentType = staticContentItem.ContentType;
                            staticContentItem.GetContentStream().CopyTo(response.OutputStream);
                        }
                    }
                }
                catch (DxaItemNotFoundException ex)
                {
                    SendNotFoundResponse(ex.Message, response);
                }
                catch (Exception ex)
                {
                    // Other exceptions: log and let ASP.NET handle them
                    Log.Error(ex);
                    throw;
                }

                // Terminate the HTTP pipeline.
                application.CompleteRequest();
            }
        }
        /// <summary>
        /// Get base directory for the specified campaign ID
        /// </summary>
        /// <param name="localization"></param>
        /// <param name="campaignId"></param>
        /// <returns></returns>
        protected string GetBaseDir(Localization localization, string campaignId)
        {
            var webAppBaseDir = HttpContext.Current.Server.MapPath("~/");
            var baseDir       = webAppBaseDir + SiteConfiguration.GetLocalStaticsFolder(localization.LocalizationId) + "/campaign-content/" + campaignId;

            return(baseDir);
        }
        private async Task LoadAsync()
        {
            if (_siteConfiguration != null)
            {
                return;
            }

            if (!File.Exists(_fileName))
            {
                _siteConfiguration = new SiteConfiguration
                {
                    Title                     = "Simple Blog",
                    Owner                     = "Simple Blog",
                    BlogPostsPageSize         = 20,
                    LatestBlogPostsCount      = 7,
                    EnableClientSideTelemetry = false,
                    MenuItems                 = new ConcurrentDictionary <string, MenuItem>()
                };
                _siteConfiguration.MenuItems.TryAdd("blog", new MenuItem {
                    Order = 10, Title = "blog", Url = "/blog"
                });
                return;
            }

            var json = await File.ReadAllTextAsync(_fileName);

            _siteConfiguration = JsonSerializer.Deserialize <SiteConfiguration>(json);
        }
        public void SetUp()
        {
            _siteConfiguration = new SiteConfiguration
            {
                TwitterUserName = "******",
                TwitterPassword = "******",
            };

            _twitterClient  = MockRepository.GenerateStub <ITwitterClient>();
            _tinyUrlService = MockRepository.GenerateStub <ITinyUrlService>();
            _urlResolver    = MockRepository.GenerateStub <IUrlResolver>();

            _twitterService = new TwitterService(_siteConfiguration, _twitterClient, _tinyUrlService, _urlResolver);

            _user = new User
            {
                TwitterUserName = "******",
            };

            _post = new Post
            {
                User  = _user,
                Title = "Test title",
            };
        }
Пример #21
0
        protected void rptSearchResults_ItemDataBound(object sender, RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                SearchHit <SitecoreItem> item = (SearchHit <SitecoreItem>)e.Item.DataItem;
                {
                    HyperLink ItemLink        = (HyperLink)e.Item.FindControl("ItemLink");
                    Literal   ItemDescription = (Literal)e.Item.FindControl("ItemDescription");

                    if (ItemLink != null && ItemDescription != null)
                    {
                        Item i = item.Document.GetItem();
                        ItemLink.NavigateUrl = LinkManager.GetItemUrl(i);
                        if (i["menu title"] != string.Empty)
                        {
                            ItemLink.Text = i["menu title"];
                        }
                        else if (i["title"] != string.Empty)
                        {
                            ItemLink.Text = i["title"];
                        }
                        else
                        {
                            ItemLink.Text = i.Name;
                        }

                        ItemDescription.Text = SiteConfiguration.GetPageDescripton(i);
                    }
                }
            }
        }
        /// <summary>
        /// Enriches a given Entity Model using an appropriate (custom) Controller.
        /// </summary>
        /// <param name="entity">The Entity Model to enrich.</param>
        /// <returns>The enriched Entity Model.</returns>
        /// <remarks>
        /// This method is different from <see cref="EnrichModel"/> in that it doesn't expect the current Controller to be able to enrich the Entity Model;
        /// it creates a Controller associated with the Entity Model for that purpose.
        /// It is used by <see cref="PageController.EnrichEmbeddedModels"/>.
        /// </remarks>
        protected EntityModel EnrichEntityModel(EntityModel entity)
        {
            if (entity == null || entity.MvcData == null || !IsCustomAction(entity.MvcData))
            {
                return(entity);
            }

            MvcData mvcData = entity.MvcData;

            using (new Tracer(entity, mvcData))
            {
                string controllerName     = mvcData.ControllerName ?? SiteConfiguration.GetEntityController();
                string controllerAreaName = mvcData.ControllerAreaName ?? SiteConfiguration.GetDefaultModuleName();

                RequestContext tempRequestContext = new RequestContext(HttpContext, new RouteData());
                tempRequestContext.RouteData.DataTokens["Area"]   = controllerAreaName;
                tempRequestContext.RouteData.Values["controller"] = controllerName;
                tempRequestContext.RouteData.Values["area"]       = controllerAreaName;

                // Note: Entity Controllers don't have to inherit from EntityController per se, but they must inherit from BaseController.
                BaseController entityController = (BaseController)ControllerBuilder.Current.GetControllerFactory().CreateController(tempRequestContext, controllerName);
                entityController.ControllerContext = new ControllerContext(HttpContext, tempRequestContext.RouteData, entityController);
                return((EntityModel)entityController.EnrichModel(entity));
            }
        }
        private void Page_PreRender(object sender, EventArgs e)
        {
            Login.Text       = GetDictionaryText("Login");
            Register.Text    = GetDictionaryText("Register");
            MyFavorites.Text = GetDictionaryText("My Favorites");
            btnLogout.Text   = GetDictionaryText("Logout");

            if (Sitecore.Context.IsLoggedIn && Sitecore.Context.Domain.Name.ToLower() == "extranet")
            {
                SetViewableLinks(true);
                LoadFavorites();
            }
            else
            {
                SetViewableLinks(false);
            }

            LoadSitesList();
            LoadLanguagesList();

            // microsites are small so we are limiting the top area.
            if (SiteConfiguration.IsMicrosite())
            {
                loginli.Visible     = false;
                registerli.Visible  = false;
                logoutli.Visible    = false;
                favoritesli.Visible = false;
            }
        }
        protected void rptLanguages_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e)
        {
            if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem)
            {
                Item node = (Item)e.Item.DataItem;

                HyperLink LangLink = (HyperLink)e.Item.FindControl("LangLink");
                System.Web.UI.WebControls.Image LangImage = (System.Web.UI.WebControls.Image)e.Item.FindControl("LangImage");
                Literal LangIso = (Literal)e.Item.FindControl("LangIso");

                //check if context item has a language version
                Item contextItem    = Sitecore.Context.Item;
                Item itemInLanguage = Sitecore.Context.Database.GetItem(contextItem.ID, Sitecore.Globalization.Language.Parse(node.Name));

                if (node != null && SiteConfiguration.DoesItemExistInCurrentLanguage(itemInLanguage) && LangLink != null && LangImage != null && LangIso != null)
                {
                    string icon = node.Appearance.Icon;
                    icon = Sitecore.Resources.Images.GetThemedImageSource(icon);
                    LangImage.ImageUrl   = icon;
                    LangIso.Text         = node["iso"].ToLower();
                    LangLink.NavigateUrl = Configuration.SiteUI.Translation.SiteLanguage.GetLanguageUrl(node);

                    if (!multipleLanguagesHasBeenProcessed)
                    {
                        LiLanguages.Attributes.Add("class", "dropdown");
                        LanguageLink.Text += " <b class=\"caret\"></b>";
                        multipleLanguagesHasBeenProcessed = true;
                    }
                }
            }
        }
Пример #25
0
        private EtlSession[] GetEtlSessions(EtlSessionListModel model)
        {
            var dateTo   = DateTime.ParseExact(model.DateTo, SharedStrings.DateFormat, null);
            var dateFrom = DateTime.ParseExact(model.DateFrom, SharedStrings.DateFormat, null);
            var oneDay   = dateTo == dateFrom;

            dateTo = dateTo.AddDays(1);

            var query = new EtlSessionQuery
            {
                FromDateTime    = dateFrom,
                ToDateTime      = dateTo,
                MaxSessionCount = model.DefaultMaxSessionCount,
            };

            if (model.Status > 0)
            {
                query.EtlStatuses.Add(model.Status);
            }

            var agent     = SiteConfiguration.GetEtlAgent();
            var logParser = agent.GetEtlLogParser();
            var sessions  = logParser.GetEtlSessions(query);

            return(sessions);
        }
Пример #26
0
        /// <summary>
        /// Renders the current (Include) Page as a Region.
        /// </summary>
        /// <param name="htmlHelper">The HtmlHelper instance on which the extension method operates.</param>
        /// <returns>The rendered HTML.</returns>
        public static MvcHtmlString DxaRegion(this HtmlHelper htmlHelper)
        {
            using (new Tracer(htmlHelper))
            {
                PageModel pageModel = (PageModel)htmlHelper.ViewData.Model;

                // Create a new Region Model which reflects the Page Model
                string  regionName = pageModel.Title;
                MvcData mvcData    = new MvcData
                {
                    ViewName           = regionName,
                    AreaName           = SiteConfiguration.GetDefaultModuleName(),
                    ControllerName     = SiteConfiguration.GetRegionController(),
                    ControllerAreaName = SiteConfiguration.GetDefaultModuleName(),
                    ActionName         = SiteConfiguration.GetRegionAction()
                };

                RegionModel regionModel = new RegionModel(regionName)
                {
                    MvcData = mvcData
                };
                regionModel.Regions.UnionWith(pageModel.Regions);

                return(htmlHelper.DxaRegion(regionModel));
            }
        }
Пример #27
0
        public override string GetResponsiveImageUrl(string url, double aspect, string widthFactor, int containerSize = 0)
        {
            int width = GetResponsiveWidth(widthFactor, containerSize);

            //Round the width to the nearest set limit point - important as we do not want
            //to swamp the cache with lots of different sized versions of the same image
            for (int i = 0; i < ImageWidths.Count; i++)
            {
                if (width <= ImageWidths[i] || i == ImageWidths.Count - 1)
                {
                    width = ImageWidths[i];
                    break;
                }
            }
            //Height is calculated from the aspect ratio (0 means preserve aspect ratio)
            string height = aspect == 0 ? String.Empty : ((int)Math.Ceiling(width / aspect)).ToString(CultureInfo.InvariantCulture);

            //Build the URL
            url = SiteConfiguration.MakeFullUrl(url, WebRequestContext.Localization);
            string prefix = SingleSiteToken;

            if (url.StartsWith("http"))
            {
                prefix = "";
                if (url.StartsWith("https"))
                {
                    prefix = "https/";
                }
                url = url.Substring(url.IndexOf("://", StringComparison.Ordinal) + 3);
            }
            return(String.Format(ImageResizeUrlFormat, ImageResizeRoute, width, height, prefix, url));
        }
        public ActionResult RelatedArticles()
        {
            /* make sure the datasource or current has children in the current language and render accordingly */
            List <SimpleItem> items = new List <SimpleItem>();

            //first get items related to me...
            MultilistField related = Sitecore.Context.Item.Fields["Prerequisite Articles"];

            if (related != null)
            {
                foreach (Item i in related.GetItems())
                {
                    if (SiteConfiguration.DoesItemExistInCurrentLanguage(i))
                    {
                        items.Add(new SimpleItem(i));
                    }
                }
            }

            //now get items I am related to
            foreach (Item i in Sitecore.Context.Database.SelectItems(SiteConfiguration.GetFurtherReadingArticlesQuery(Sitecore.Context.Item.ID.ToString())))
            {
                if (SiteConfiguration.DoesItemExistInCurrentLanguage(i))
                {
                    items.Add(new SimpleItem(i));
                }
            }

            // items.Sort(); // TODO: need to implement Comparer
            return(!items.IsNullOrEmpty() ? View(items) : ShowListIsEmptyPageEditorAlert());
        }
Пример #29
0
        /// <summary>
        /// Initializes a new <see cref="MvcData"/> instance for a given qualified View name.
        /// </summary>
        /// <param name="qualifiedViewName">The qualified View name with format AreaName:ControllerName:ViewName.</param>
        public MvcData(string qualifiedViewName)
        {
            string[] qualifiedViewNameParts = qualifiedViewName.Split(':');
            switch (qualifiedViewNameParts.Length)
            {
            case 1:
                AreaName = SiteConfiguration.GetDefaultModuleName();
                ViewName = qualifiedViewNameParts[0];
                break;

            case 2:
                AreaName = qualifiedViewNameParts[0];
                ViewName = qualifiedViewNameParts[1];
                break;

            case 3:
                AreaName       = qualifiedViewNameParts[0];
                ControllerName = qualifiedViewNameParts[1];
                ViewName       = qualifiedViewNameParts[2];
                break;

            default:
                throw new DxaException(
                          string.Format("Invalid format for Qualified View Name: '{0}'. Format must be 'ViewName' or 'AreaName:ViewName' or 'AreaName:ControllerName:Vieweame.'",
                                        qualifiedViewName)
                          );
            }
        }
        public SiteMetaData EnrichSite(SiteConfiguration siteConfiguration, Guid siteGuid, List <PageMetaData> pages)
        {
            var siteInfo = new SiteMetaData(pages.ToArray())
            {
                Id          = siteGuid.ToString(),
                Title       = _siteInfo.Title,
                Description = _siteInfo.Description,
                Language    = _siteInfo.Lang,
                Url         = _siteInfo.Url,
                Author      = null,
                Data        = new Dictionary <string, object>(),
                Tags        = new SortedDictionary <string, PageMetaData[]>(),
                Collections = new SortedDictionary <string, PageMetaData[]>(),
                Types       = new SortedDictionary <string, PageMetaData[]>(),
                Series      = new SortedDictionary <string, PageMetaData[]>(),
                Years       = new SortedDictionary <int, PageMetaData[]>()
            };

            EnrichSiteWithData(siteInfo, siteConfiguration.DataDirectory);
            EnrichSiteWithCollections(siteInfo, siteGuid, pages);
            EnrichSiteWithTags(siteInfo, pages);
            EnrichSiteWithYears(siteInfo, pages);
            EnrichSiteWithTypes(siteInfo, pages);
            EnrichSiteWithSeries(siteInfo, pages);

            return(siteInfo);
        }
Пример #31
0
        /// <summary>
        /// Renders a given Region Model
        /// </summary>
        /// <param name="htmlHelper">The HtmlHelper instance on which the extension method operates.</param>
        /// <param name="region">The Region Model to render. This object determines the View that will be used.</param>
        /// <param name="containerSize">The size (in grid column units) of the containing element.</param>
        /// <returns>The rendered HTML or an empty string if <paramref name="region"/> is <c>null</c>.</returns>
        public static MvcHtmlString DxaRegion(this HtmlHelper htmlHelper, RegionModel region, int containerSize = 0)
        {
            if (region == null)
            {
                return(MvcHtmlString.Empty);
            }

            if (containerSize == 0)
            {
                containerSize = SiteConfiguration.MediaHelper.GridSize;
            }

            using (new Tracer(htmlHelper, region, containerSize))
            {
                MvcData mvcData            = region.MvcData;
                string  actionName         = mvcData.ActionName ?? SiteConfiguration.GetRegionAction();
                string  controllerName     = mvcData.ControllerName ?? SiteConfiguration.GetRegionController();
                string  controllerAreaName = mvcData.ControllerAreaName ?? SiteConfiguration.GetDefaultModuleName();

                MvcHtmlString result = htmlHelper.Action(actionName, controllerName, new { Region = region, containerSize = containerSize, area = controllerAreaName });

                if (WebRequestContext.IsPreview)
                {
                    result = new MvcHtmlString(Markup.TransformXpmMarkupAttributes(result.ToString()));
                }
                return(Markup.DecorateMarkup(result, region));
            }
        }
Пример #32
0
        private void Page_Load(object sender, EventArgs e)
        {
            /* Populate two ways:
             * 1. Children of Datasource
             * 2. Children of Current */
            List <Item> items = new List <Item>();

            foreach (Item item in DataSourceItemOrCurrentItem.Children)
            {
                if (SiteConfiguration.DoesItemExistInCurrentLanguage(item))
                {
                    items.Add(item);
                }
            }

            if (items.Count > 0)
            {
                rptList.DataSource = items;
                rptList.DataBind();
            }
            else
            {
                if (IsPageEditorEditing)
                {
                    WriteAlert("list is empty");
                }
            }
        }
Пример #33
0
 public void ToSiteConfiguration(SiteConfiguration config)
 {
     config.EntityId = id;
     config.Name = name;
     config.Host = host;
     config.LanguageDefault = languageDefault;
     config.ScriptsPath = scriptsPath;
     config.CssPath = cssFilePath;
     config.ImagesPath = imagesPath;
     config.WebSiteRoot = webSiteRoot;
 }
        private SiteConfiguration ParseSiteConfig(XElement siteElement)
        {
            var site = new SiteConfiguration();

            site.Name = GetAttributeValue(siteElement, "name");
            site.Url = GetAttributeValue(siteElement, "url");

            foreach (var itemElement in siteElement.Descendants("item"))
            {
                var item = ParseItemConfig(itemElement);
                site.Items.Add(item);
            }

            return site;
        }
Пример #35
0
 public SiteDrop(SiteConfiguration configuration)
 {
     Url = configuration.Url;
 }
Пример #36
0
 public StaticContentHandler(SiteConfiguration configuration, Io io)
 {
     _configuration = configuration;
     _io = io;
 }
Пример #37
0
 public GeneratedContentHandler(SiteConfiguration configuration)
 {
     _configuration = configuration;
 }
Пример #38
0
        public static void Update(SiteConfiguration configuration)
        {
            if (configuration == null)
            {
                throw new ArgumentNullException("configuration");
            }

            logger.Log(LogLevel.Debug, "Saving site configuration");

            PluginStore.Instance.Save(Instance, configuration);
        }
Пример #39
0
        private static void Inizializzazione()
        {
            //Controllo se esiste il file di configurazione nella directory
            if (!File.Exists(DiskPath + "\\SiteConfiguration.xml"))
            {
                _avviso = "Non esiste il file " + DiskPath + "\\SiteConfiguration.xml";
                HttpContext.Current.Response.Write(_avviso);
                HttpContext.Current.Response.End();
            }

            //Controllo se l'xml è valido, l'xsd lo prendo dalla dir Bin, l'xml dalla dir del sito
            if (!XmlValidator.ValidaXml(out _avviso, AssemblyDirectory + "\\SiteConfiguration.xsd", DiskPath + "\\SiteConfiguration.xml")) throw new Exception(_avviso);

            //Recupero la configurazione
            using (var fileStream = new FileStream(DiskPath + "\\SiteConfiguration.xml", FileMode.Open, FileAccess.Read, FileShare.ReadWrite))
            {
                _siteConfiguration = new XmlSerializer(typeof (SiteConfiguration)).Deserialize(fileStream) as SiteConfiguration;
                if (_siteConfiguration == null) throw new Exception(DiskPath + "\\SiteConfiguration.xml è null");
            }
        }
Пример #40
0
        /// <summary>
        /// Saves all settings that are stored in the database, to the configuration table.
        /// </summary>
        /// <param name="summary">Summary data containing the settings.</param>
        /// <param name="isInstalling">If true, a new <see cref="SiteConfiguration"/> is created, otherwise the current one is updated.</param>
        /// <exception cref="DatabaseException">An NHibernate (database) error occurred while saving the configuration.</exception>
        public static void SaveSiteConfiguration(SettingsSummary summary, bool isInstalling)
        {
            try
            {
                SiteConfiguration config;

                if (isInstalling)
                {
                    config = new SiteConfiguration();
                }
                else
                {
                    config = SiteConfiguration.Current;
                }

                config.AllowedFileTypes = summary.AllowedExtensions;
                config.AllowUserSignup = summary.AllowUserSignup;
                config.EnableRecaptcha = summary.EnableRecaptcha;
                config.MarkupType = summary.MarkupType;
                config.RecaptchaPrivateKey = summary.RecaptchaPrivateKey;
                config.RecaptchaPublicKey = summary.RecaptchaPublicKey;
                config.SiteUrl = summary.SiteUrl;
                config.Title = summary.SiteName;
                config.Theme = summary.Theme;

                config.Version = RoadkillSettings.Version;

                NHibernateRepository.Current.SaveOrUpdate<SiteConfiguration>(config);
            }
            catch (HibernateException ex)
            {
                throw new DatabaseException(ex, "An exception occurred while saving the site configuration.");
            }
        }
Пример #41
0
 public MarkdownPageHandler(SiteConfiguration configuration, Io io)
 {
     _configuration = configuration;
     _io = io;
 }
 // Constructors.
 public Crawler(SiteConfiguration siteConfig)
 {
     _baseUri = new Uri(siteConfig.Url);
     _hasItemsWithUrlPattern = siteConfig.Items.Any(i => i.UrlPattern != null);
     _siteConfig = siteConfig;
 }
Пример #43
0
 /// <summary>
 ///   Initializes a new instance of the <see cref = "OliveSiteInterface" /> class.
 /// </summary>
 /// <param name = "siteConfiguration">The site configuration.</param>
 public OliveSiteInterface(SiteConfiguration siteConfiguration)
     : base(siteConfiguration)
 {
 }
        private Task StartKeepAlive(SiteConfiguration site)
        {
            return Task.Factory.StartNew(() =>
                {
                    this.serviceEventLog.WriteEntry(string.Format("Started keeping '{0}' alive.", site.Url));

                    while (!_isStopRequested)
                    {
                        try
                        {
                            var request = WebRequest.Create(site.Url);
                            request.UseDefaultCredentials = true;
                            request.PreAuthenticate = true;

                            using (var response = request.GetResponse() as HttpWebResponse)
                            {
                                if (response.StatusCode != HttpStatusCode.OK)
                                {
                                    this.serviceEventLog.WriteEntry(string.Format("Call to '{0}' returned status code '{1}'.", site.Url, response.StatusCode), EventLogEntryType.Warning);
                                }
                                Debug.WriteLine("[" + DateTime.Now + "] " + site.Url + " : " + response.StatusCode);
                            }

                        }
                        catch (Exception ex)
                        {
                            this.serviceEventLog.WriteEntry(string.Format("There was a problem with the call to '{0}'. {1}", site.Url, ex.Message), EventLogEntryType.Error);
                            Debug.WriteLine("[" + DateTime.Now + "] " + site.Url + " : " + ex.Message);
                        }

                        Thread.Sleep(site.Delay);
                    }
                }, TaskCreationOptions.LongRunning | TaskCreationOptions.PreferFairness);
        }
        private IEnumerable<SiteConfiguration> LoadSiteUrls()
        {
            try
            {
                var exePath = Assembly.GetExecutingAssembly().Location;
                var exeDirectory = Path.GetDirectoryName(exePath);
                var siteUrlsFile = Path.Combine(exeDirectory, "SiteUrls.txt");

                var lines = File.ReadAllLines(siteUrlsFile);

                var sites = lines.Select(x =>
                    {
                        var parts = x.Split(SiteConfigSplitCharacters, StringSplitOptions.RemoveEmptyEntries);
                        var site = new SiteConfiguration();

                        if (parts.Length > 1)
                        {
                            site.Delay = TimeSpan.Parse(parts[0]);
                            site.Url = parts[1];
                        }
                        else if (parts.Length > 0)
                        {
                            site.Delay = DefaultKeepAliveDelay;
                            site.Url = parts[0];
                        }

                        return site;
                    });

                return sites.Where(x => x.Url != null && x.Delay > TimeSpan.Zero);
            }
            catch (Exception ex)
            {
                this.serviceEventLog.WriteEntry(string.Format("There was a problem loading SiteUrls.txt. {1}", ex.Message), EventLogEntryType.Error);
                return null;
            }
        }
Пример #46
0
 public TemplateHandler(SiteConfiguration configuration, Io io, AssetHandlerManager handlers)
 {
     _configuration = configuration;
     _handlers = handlers;
     _io = io;
 }
Пример #47
0
 public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedDataSetSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
     SiteConfiguration ds = new SiteConfiguration();
     global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
     global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
     global::System.Xml.Schema.XmlSchemaAny any = new global::System.Xml.Schema.XmlSchemaAny();
     any.Namespace = ds.Namespace;
     sequence.Items.Add(any);
     type.Particle = sequence;
     global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
     if (xs.Contains(dsSchema.TargetNamespace)) {
         global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
         global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
         try {
             global::System.Xml.Schema.XmlSchema schema = null;
             dsSchema.Write(s1);
             for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
                 schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                 s2.SetLength(0);
                 schema.Write(s2);
                 if ((s1.Length == s2.Length)) {
                     s1.Position = 0;
                     s2.Position = 0;
                     for (; ((s1.Position != s1.Length) 
                                 && (s1.ReadByte() == s2.ReadByte())); ) {
                         ;
                     }
                     if ((s1.Position == s1.Length)) {
                         return type;
                     }
                 }
             }
         }
         finally {
             if ((s1 != null)) {
                 s1.Close();
             }
             if ((s2 != null)) {
                 s2.Close();
             }
         }
     }
     xs.Add(dsSchema);
     return type;
 }
Пример #48
0
 public static global::System.Xml.Schema.XmlSchemaComplexType GetTypedTableSchema(global::System.Xml.Schema.XmlSchemaSet xs) {
     global::System.Xml.Schema.XmlSchemaComplexType type = new global::System.Xml.Schema.XmlSchemaComplexType();
     global::System.Xml.Schema.XmlSchemaSequence sequence = new global::System.Xml.Schema.XmlSchemaSequence();
     SiteConfiguration ds = new SiteConfiguration();
     global::System.Xml.Schema.XmlSchemaAny any1 = new global::System.Xml.Schema.XmlSchemaAny();
     any1.Namespace = "http://www.w3.org/2001/XMLSchema";
     any1.MinOccurs = new decimal(0);
     any1.MaxOccurs = decimal.MaxValue;
     any1.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
     sequence.Items.Add(any1);
     global::System.Xml.Schema.XmlSchemaAny any2 = new global::System.Xml.Schema.XmlSchemaAny();
     any2.Namespace = "urn:schemas-microsoft-com:xml-diffgram-v1";
     any2.MinOccurs = new decimal(1);
     any2.ProcessContents = global::System.Xml.Schema.XmlSchemaContentProcessing.Lax;
     sequence.Items.Add(any2);
     global::System.Xml.Schema.XmlSchemaAttribute attribute1 = new global::System.Xml.Schema.XmlSchemaAttribute();
     attribute1.Name = "namespace";
     attribute1.FixedValue = ds.Namespace;
     type.Attributes.Add(attribute1);
     global::System.Xml.Schema.XmlSchemaAttribute attribute2 = new global::System.Xml.Schema.XmlSchemaAttribute();
     attribute2.Name = "tableTypeName";
     attribute2.FixedValue = "TabDataTable";
     type.Attributes.Add(attribute2);
     type.Particle = sequence;
     global::System.Xml.Schema.XmlSchema dsSchema = ds.GetSchemaSerializable();
     if (xs.Contains(dsSchema.TargetNamespace)) {
         global::System.IO.MemoryStream s1 = new global::System.IO.MemoryStream();
         global::System.IO.MemoryStream s2 = new global::System.IO.MemoryStream();
         try {
             global::System.Xml.Schema.XmlSchema schema = null;
             dsSchema.Write(s1);
             for (global::System.Collections.IEnumerator schemas = xs.Schemas(dsSchema.TargetNamespace).GetEnumerator(); schemas.MoveNext(); ) {
                 schema = ((global::System.Xml.Schema.XmlSchema)(schemas.Current));
                 s2.SetLength(0);
                 schema.Write(s2);
                 if ((s1.Length == s2.Length)) {
                     s1.Position = 0;
                     s2.Position = 0;
                     for (; ((s1.Position != s1.Length) 
                                 && (s1.ReadByte() == s2.ReadByte())); ) {
                         ;
                     }
                     if ((s1.Position == s1.Length)) {
                         return type;
                     }
                 }
             }
         }
         finally {
             if ((s1 != null)) {
                 s1.Close();
             }
             if ((s2 != null)) {
                 s2.Close();
             }
         }
     }
     xs.Add(dsSchema);
     return type;
 }
Пример #49
0
 public TransformableContentHandler(SiteConfiguration configuration, Io io)
 {
     _configuration = configuration;
     _io = io;
 }
Пример #50
0
 public PostHandler(SiteConfiguration configuration, Io io)
 {
     _configuration = configuration;
     _io = io;
     _posts = new List<Post>();
 }