public JsonResult Add([FromBody] SiteVM model)
        {
            var site = Mapper.Map <Site>(model);

            _siteService.Add(site);
            _siteService.SaveChanges();
            return(Json(_siteService.Get(site.Id)));
        }
Beispiel #2
0
        /// <summary>
        /// Reads the specified GUID.
        /// </summary>
        /// <param name="guid">The GUID.</param>
        /// <returns></returns>
        public static SiteCache Read(Guid guid)
        {
            ObjectCache cache    = MemoryCache.Default;
            object      cacheObj = cache[guid.ToString()];

            if (cacheObj != null)
            {
                return(Read((int)cacheObj));
            }
            else
            {
                var siteService = new SiteService();
                var siteModel   = siteService.Get(guid);
                if (siteModel != null)
                {
                    siteModel.LoadAttributes();
                    var site = new SiteCache(siteModel);

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set(SiteCache.CacheKey(site.Id), site, cachePolicy);
                    cache.Set(site.Guid.ToString(), site.Id, cachePolicy);

                    return(site);
                }
                else
                {
                    return(null);
                }
            }
        }
Beispiel #3
0
        /// <summary>
        /// Returns Site object from cache.  If site does not already exist in cache, it
        /// will be read and added to cache
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        public static SiteCache Read(int id)
        {
            string cacheKey = SiteCache.CacheKey(id);

            ObjectCache cache = MemoryCache.Default;
            SiteCache   site  = cache[cacheKey] as SiteCache;

            if (site != null)
            {
                return(site);
            }
            else
            {
                var siteService = new SiteService();
                var siteModel   = siteService.Get(id);
                if (siteModel != null)
                {
                    siteModel.LoadAttributes();
                    site = new SiteCache(siteModel);

                    var cachePolicy = new CacheItemPolicy();
                    cache.Set(cacheKey, site, cachePolicy);
                    cache.Set(site.Guid.ToString(), site.Id, cachePolicy);

                    return(site);
                }
                else
                {
                    return(null);
                }
            }
        }
Beispiel #4
0
        /// <summary>
        /// Handles the Click event of the btnDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            bool canDelete = false;

            var         rockContext = new RockContext();
            SiteService siteService = new SiteService(rockContext);
            Site        site        = siteService.Get(int.Parse(hfSiteId.Value));

            if (site != null)
            {
                string errorMessage;
                canDelete = siteService.CanDelete(site, out errorMessage, includeSecondLvl: true);
                if (!canDelete)
                {
                    mdDeleteWarning.Show(errorMessage, ModalAlertType.Alert);
                    return;
                }

                siteService.Delete(site);

                rockContext.SaveChanges();

                SiteCache.Flush(site.Id);
            }

            NavigateToParentPage();
        }
Beispiel #5
0
        /// <summary>
        /// Handles the Delete event of the gSites control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gSites_Delete(object sender, RowEventArgs e)
        {
            bool canDelete = false;

            var         rockContext = new RockContext();
            SiteService siteService = new SiteService(rockContext);
            Site        site        = siteService.Get(e.RowKeyId);

            if (site != null)
            {
                string errorMessage;
                canDelete = siteService.CanDelete(site, out errorMessage, includeSecondLvl: true);
                if (!canDelete)
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Alert);
                    return;
                }

                siteService.Delete(site);

                rockContext.SaveChanges();

                SiteCache.Flush(site.Id);
            }

            BindGrid();
        }
Beispiel #6
0
        /// <summary>
        /// Handles the Delete event of the gSites control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gSites_Delete(object sender, RowEventArgs e)
        {
            var              rockContext      = new RockContext();
            SiteService      siteService      = new SiteService(rockContext);
            Site             site             = siteService.Get(e.RowKeyId);
            LayoutService    layoutService    = new LayoutService(rockContext);
            PageService      pageService      = new PageService(rockContext);
            UserLoginService userLoginService = new UserLoginService(rockContext);

            if (site != null)
            {
                var additionalSettings = site.AdditionalSettings.FromJsonOrNull <AdditionalSiteSettings>() ?? new AdditionalSiteSettings();

                var sitePages = new List <int> {
                    site.DefaultPageId ?? -1,
                    site.LoginPageId ?? -1,
                    site.RegistrationPageId ?? -1,
                    site.PageNotFoundPageId ?? -1
                };

                var pageQry = pageService.Queryable("Layout")
                              .Where(t =>
                                     t.Layout.SiteId == site.Id ||
                                     sitePages.Contains(t.Id));

                pageService.DeleteRange(pageQry);

                var layoutQry = layoutService.Queryable()
                                .Where(l =>
                                       l.SiteId == site.Id);
                layoutService.DeleteRange(layoutQry);
                rockContext.SaveChanges(true);

                string errorMessage;
                var    canDelete = siteService.CanDelete(site, out errorMessage, includeSecondLvl: true);
                if (!canDelete)
                {
                    mdGridWarning.Show(errorMessage, ModalAlertType.Alert);
                    return;
                }

                UserLogin userLogin = null;
                if (additionalSettings.ApiKeyId.HasValue)
                {
                    userLogin = userLoginService.Get(additionalSettings.ApiKeyId.Value);
                }

                rockContext.WrapTransaction(() =>
                {
                    siteService.Delete(site);
                    if (userLogin != null)
                    {
                        userLoginService.Delete(userLogin);
                    }
                    rockContext.SaveChanges();
                });
            }

            BindGrid();
        }
Beispiel #7
0
        private HiteContext()
        {
            int    currentSiteId = 1;
            string domain        = Goodspeed.Web.UrlHelper.Current.Domain.ToLower(); //当前域名称
            string url           = Goodspeed.Web.UrlHelper.Current.Url.ToLower();    //当前URL

            Language = WebLanguage.zh_cn;                                            //默认中文


            try
            {
                Regex r = new Regex(URLPATTERN);
                Match m = r.Match(url);
                if (m.Success)
                {
                    string value = m.Groups[1].Value;
                    if (value == "en")
                    {
                        Language = WebLanguage.en;
                    }
                }
                //Controleng.Common.Utils.WriteCookie("language",Language.ToString());

                XElement sitesElement = XElement.Load(String.Concat(System.AppDomain.CurrentDomain.BaseDirectory, SITECONFIGPATH));
                var      items        = sitesElement.Elements();

                foreach (var item in items)
                {
                    string _domain = (string)item.Attribute("url");
                    int    _id     = (int)item.Attribute("siteid");
                    int    _enId   = (int)item.Attribute("ensiteid");
                    if (_domain == domain)
                    {
                        currentSiteId = _id;
                        if (Language == WebLanguage.en)
                        {
                            if (_enId > 0)
                            {
                                currentSiteId = _enId;  //英文版
                            }
                        }
                        break;
                    }
                }
                SiteAllUrlList = items.Select(p => (string)p.Attribute("url")).ToList();
            }
            catch (Exception ex) {
                log4net.LogManager.GetLogger(typeof(HiteContext))
                .Error(ex.ToString(), ex);
            }
            Site     = SiteService.Get(currentSiteId, true);
            UserInfo = new UserInfo();
            if (HttpContext.Current.Request.IsAuthenticated)
            {
                UserInfo = UserService.Get(HttpContext.Current.User.Identity.Name);
            }
        }
Beispiel #8
0
        private static SiteCache LoadById2(int id, RockContext rockContext)
        {
            var siteService = new SiteService(rockContext);
            var siteModel   = siteService.Get(id);

            if (siteModel != null)
            {
                return(new SiteCache(siteModel));
            }

            return(null);
        }
Beispiel #9
0
        public async Task <IHttpActionResult> GetList()
        {
            var list = await service.Get();

            var model = new SexSpiderModel();

            model.site_list = list.ToList();
            model.ext_dic   = service.GetExtDic();
            model.stop_dic  = service.GetStopDic();
            model.del_dic   = service.GetDelDic();

            return(new JsonLowercase(model, Request));
        }
Beispiel #10
0
        /// <summary>
        /// Handles the Click event of the btnDeleteConfirm control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnDeleteConfirm_Click(object sender, EventArgs e)
        {
            bool canDelete = false;

            var           rockContext   = new RockContext();
            SiteService   siteService   = new SiteService(rockContext);
            Site          site          = siteService.Get(hfSiteId.Value.AsInteger());
            LayoutService layoutService = new LayoutService(rockContext);
            PageService   pageService   = new PageService(rockContext);

            if (site != null)
            {
                var sitePages = new List <int> {
                    site.DefaultPageId ?? -1,
                    site.LoginPageId ?? -1,
                    site.RegistrationPageId ?? -1,
                    site.PageNotFoundPageId ?? -1
                };

                var pageQry = pageService.Queryable("Layout")
                              .Where(t =>
                                     t.Layout.SiteId == site.Id ||
                                     sitePages.Contains(t.Id));

                pageService.DeleteRange(pageQry);

                var layoutQry = layoutService.Queryable()
                                .Where(l =>
                                       l.SiteId == site.Id);
                layoutService.DeleteRange(layoutQry);
                rockContext.SaveChanges(true);

                string errorMessage;
                canDelete = siteService.CanDelete(site, out errorMessage, includeSecondLvl: true);
                if (!canDelete)
                {
                    mdDeleteWarning.Show(errorMessage, ModalAlertType.Alert);
                    return;
                }

                siteService.Delete(site);

                rockContext.SaveChanges();

                SiteCache.Flush(site.Id);
            }

            NavigateToParentPage();
        }
Beispiel #11
0
        /// <summary>
        /// Handles the Delete event of the gSites control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gSites_Delete(object sender, RowEventArgs e)
        {
            SiteService siteService = new SiteService();
            Site        site        = siteService.Get((int)gSites.DataKeys[e.RowIndex]["id"]);

            if (CurrentBlock != null)
            {
                siteService.Delete(site, CurrentPersonId);
                siteService.Save(site, CurrentPersonId);

                SiteCache.Flush(site.Id);
            }

            BindGrid();
        }
Beispiel #12
0
        public async Task <IHttpActionResult> Get(int id, int page)
        {
            var site = await service.Get(id);

            string siteLink = site.SiteLink; // bakup sitelink

            SetNextPage(site, page);
            var list   = SiteHelper.GetSiteList(site);
            var result = list.ToList();

            site.SiteLink = siteLink;
            SaveLastStart(result, site);

            return(new JsonLowercase(result, Request));
        }
Beispiel #13
0
        /// <summary>
        /// Binds the pages grid.
        /// </summary>
        protected void BindPagesGrid()
        {
            pnlPages.Visible = false;
            int siteId = PageParameter("siteId").AsInteger() ?? 0;

            if (siteId == 0)
            {
                // quit if the siteId can't be determined
                return;
            }

            hfSiteId.SetValue(siteId);
            pnlPages.Visible = true;

            LayoutService layoutService = new LayoutService();

            layoutService.RegisterLayouts(Request.MapPath("~"), SiteCache.Read(siteId), CurrentPersonId);
            var layouts = layoutService.Queryable().Where(a => a.SiteId.Equals(siteId)).Select(a => a.Id).ToList();

            var siteService = new SiteService();
            var pageId      = siteService.Get(siteId).DefaultPageId;

            var pageService = new PageService();
            var qry         = pageService.GetAllDescendents((int)pageId).AsQueryable().Where(a => layouts.Contains(a.LayoutId));

            string layoutFilter = gPagesFilter.GetUserPreference("Layout");

            if (!string.IsNullOrWhiteSpace(layoutFilter) && layoutFilter != Rock.Constants.All.Text)
            {
                qry = qry.Where(a => a.Layout.ToString() == layoutFilter);
            }

            SortProperty sortProperty = gPages.SortProperty;

            if (sortProperty != null)
            {
                qry = qry.Sort(sortProperty);
            }
            else
            {
                qry = qry.OrderBy(q => q.Id);
            }

            gPages.DataSource = qry.ToList();
            gPages.DataBind();
        }
Beispiel #14
0
        public async Task <IHttpActionResult> Get(int id, string url)
        {
            var decUrl = System.Net.WebUtility.UrlDecode(url);
            var site   = await service.Get(id);

            var list = new List <ImageModel>();

            if (site.PageLevel == 0)
            {
                list = SiteHelper.GetListImage(site, decUrl).ToList();
            }
            else
            {
                list = SiteHelper.GetListImagePage(site, decUrl).ToList();
            }

            return(new JsonLowercase(list, Request));
        }
Beispiel #15
0
        /// <summary>
        /// Build filter values/summary with user friendly data from filters
        /// </summary>
        /// <param name="sender">The sender.</param>
        /// <param name="e">The e.</param>
        protected void fExceptionList_DisplayFilterValue(object sender, GridFilter.DisplayFilterValueArgs e)
        {
            switch (e.Key)
            {
            case "Site":
                int siteId;
                if (int.TryParse(e.Value, out siteId))
                {
                    SiteService siteService = new SiteService();
                    var         site        = siteService.Get(siteId);
                    if (site != null)
                    {
                        e.Value = site.Name;
                    }
                }
                break;

            case "Page":
                int pageId;
                if (int.TryParse(e.Value, out pageId))
                {
                    PageService pageService = new PageService();
                    var         page        = pageService.Get(pageId);
                    if (page != null)
                    {
                        e.Value = page.InternalName;
                    }
                }
                break;

            case "User":
                int userPersonId;
                if (int.TryParse(e.Value, out userPersonId))
                {
                    PersonService personService = new PersonService();
                    var           user          = personService.Get(userPersonId);
                    if (user != null)
                    {
                        e.Value = user.FullName;
                    }
                }
                break;
            }
        }
Beispiel #16
0
        /// <summary>
        /// Handles the Click event of the btnCompileTheme control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
        protected void btnCompileTheme_Click(object sender, EventArgs e)
        {
            var         rockContext = new RockContext();
            SiteService siteService = new SiteService(rockContext);
            Site        site        = siteService.Get(hfSiteId.Value.AsInteger());

            string messages = string.Empty;
            var    theme    = new RockTheme(site.Theme);
            bool   success  = theme.Compile(out messages);

            if (success)
            {
                mdThemeCompile.Show("Theme was successfully compiled.", ModalAlertType.Information);
            }
            else
            {
                mdThemeCompile.Show(string.Format("An error occurred compiling the theme {0}. Message: {1}.", site.Theme, messages), ModalAlertType.Warning);
            }
        }
Beispiel #17
0
        public ActionResult CategoryListForHeader(int siteId)
        {
            string html     = string.Empty;
            var    siteInfo = SiteService.Get(siteId, true);

            if (siteInfo.Language == WebLanguage.en)
            {
                //英文的只显示二级分类
                var sb       = new StringBuilder();
                var pList    = CategoryService.ListBySiteId(siteId, true);
                var rootList = pList.Where(p => (p.ParentId == 0 && p.IsEnabled && !p.IsDeleted));
                foreach (var item in rootList)
                {
                    sb.Append("<li>");

                    //创建链接 Start
                    sb.Append(CategoryLinkUrlHelper.BuildLink(item, string.Empty, null, WebLanguage.en));
                    //创建链接 End

                    var subList = pList.Where(p => (p.ParentId == item.Id && p.IsEnabled && !p.IsDeleted));
                    if (subList.Count() > 0)
                    {
                        sb.Append("<ul>");
                        foreach (var sub in subList)
                        {
                            sb.Append("<li>");
                            //创建链接 Start
                            sb.Append(CategoryLinkUrlHelper.BuildLink(sub, string.Empty, null, WebLanguage.en));
                            //创建链接 End
                            sb.Append("</li>");
                        }
                        sb.Append("</ul>");
                    }
                    sb.Append("</li>");
                }
                html = sb.ToString();
            }
            else
            {
                html = CategoryService.RenderTreeViewForHtml(siteId);
            }
            return(Content(html));
        }
Beispiel #18
0
        public async void Open_Increments_TimesVisited()
        {
            //arrange
            var testSite       = testSites[0];
            var expectedVisits = testSite.TimesVisited + 1;

            var mockSiteRepo = new Mock <ISiteRepository>();

            mockSiteRepo.Setup(repo => repo.GetSite(testSite.Id))
            .Returns(testSite);

            var siteService = new SiteService(mockSiteRepo.Object);

            //act
            await siteService.Open(testSite.Id);

            var site = siteService.Get(testSite.Id); //get site for assertion

            //assert
            Assert.Equal(expectedVisits, site.TimesVisited);
        }
Beispiel #19
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        protected void ShowEdit(int siteId)
        {
            SiteService siteService = new SiteService();
            Site        site        = siteService.Get(siteId);

            if (site != null)
            {
                lAction.Text   = "Edit";
                hfSiteId.Value = site.Id.ToString();

                tbSiteName.Text    = site.Name;
                tbDescription.Text = site.Description;
                ddlTheme.SetValue(site.Theme);
                if (site.DefaultPageId.HasValue)
                {
                    ddlDefaultPage.SelectedValue = site.DefaultPageId.Value.ToString();
                }

                tbSiteDomains.Text       = string.Join("\n", site.SiteDomains.Select(dom => dom.Domain).ToArray());
                tbFaviconUrl.Text        = site.FaviconUrl;
                tbAppleTouchIconUrl.Text = site.AppleTouchIconUrl;
                tbFacebookAppId.Text     = site.FacebookAppId;
                tbFacebookAppSecret.Text = site.FacebookAppSecret;
            }
            else
            {
                lAction.Text             = "Add";
                tbSiteName.Text          = string.Empty;
                tbDescription.Text       = string.Empty;
                ddlTheme.Text            = CurrentPage.Site.Theme;
                tbSiteDomains.Text       = string.Empty;
                tbFaviconUrl.Text        = string.Empty;
                tbAppleTouchIconUrl.Text = string.Empty;
                tbFacebookAppId.Text     = string.Empty;
                tbFacebookAppSecret.Text = string.Empty;
            }

            pnlList.Visible    = false;
            pnlDetails.Visible = true;
        }
Beispiel #20
0
        /// <summary>
        /// Handles the Click event of the btnDelete control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnDelete_Click(object sender, EventArgs e)
        {
            RockTransactionScope.WrapTransaction(() =>
            {
                SiteService siteService = new SiteService();
                Site site = siteService.Get(int.Parse(hfSiteId.Value));
                if (site != null)
                {
                    string errorMessage;
                    if (!siteService.CanDelete(site, out errorMessage))
                    {
                        mdDeleteWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    siteService.Delete(site, CurrentPersonId);
                    siteService.Save(site, CurrentPersonId);

                    SiteCache.Flush(site.Id);
                }
            });

            NavigateToParentPage();
        }
        /// <summary>
        /// Handles the Delete event of the gSites control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="RowEventArgs" /> instance containing the event data.</param>
        protected void gSites_Delete(object sender, RowEventArgs e)
        {
            RockTransactionScope.WrapTransaction(() =>
            {
                SiteService siteService = new SiteService();
                Site site = siteService.Get((int)e.RowKeyValue);
                if (site != null)
                {
                    string errorMessage;
                    if (!siteService.CanDelete(site, out errorMessage))
                    {
                        mdGridWarning.Show(errorMessage, ModalAlertType.Information);
                        return;
                    }

                    siteService.Delete(site, CurrentPersonId);
                    siteService.Save(site, CurrentPersonId);

                    SiteCache.Flush(site.Id);
                }
            });

            BindGrid();
        }
Beispiel #22
0
        public async Task <IActionResult> Get([FromQuery] SiteFilter filter, int rowsPerPage = 0, int pageNumber = 1)
        {
            var sites = siteService.Get(filter, rowsPerPage, pageNumber);

            return(Ok(Mapper.Map <PaginatedItemsDto <SiteOverviewDto> >(sites)));
        }
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Site site;

            if (Page.IsValid)
            {
                var               rockContext       = new RockContext();
                SiteService       siteService       = new SiteService(rockContext);
                SiteDomainService siteDomainService = new SiteDomainService(rockContext);
                bool              newSite           = false;

                int siteId = hfSiteId.Value.AsInteger();

                if (siteId == 0)
                {
                    newSite = true;
                    site    = new Rock.Model.Site();
                    siteService.Add(site);
                }
                else
                {
                    site = siteService.Get(siteId);
                }

                site.Name                        = tbSiteName.Text;
                site.Description                 = tbDescription.Text;
                site.Theme                       = ddlTheme.Text;
                site.DefaultPageId               = ppDefaultPage.PageId;
                site.DefaultPageRouteId          = ppDefaultPage.PageRouteId;
                site.LoginPageId                 = ppLoginPage.PageId;
                site.LoginPageRouteId            = ppLoginPage.PageRouteId;
                site.ChangePasswordPageId        = ppChangePasswordPage.PageId;
                site.ChangePasswordPageRouteId   = ppChangePasswordPage.PageRouteId;
                site.CommunicationPageId         = ppCommunicationPage.PageId;
                site.CommunicationPageRouteId    = ppCommunicationPage.PageRouteId;
                site.RegistrationPageId          = ppRegistrationPage.PageId;
                site.RegistrationPageRouteId     = ppRegistrationPage.PageRouteId;
                site.PageNotFoundPageId          = ppPageNotFoundPage.PageId;
                site.PageNotFoundPageRouteId     = ppPageNotFoundPage.PageRouteId;
                site.ErrorPage                   = tbErrorPage.Text;
                site.GoogleAnalyticsCode         = tbGoogleAnalytics.Text;
                site.RequiresEncryption          = cbRequireEncryption.Checked;
                site.EnableMobileRedirect        = cbEnableMobileRedirect.Checked;
                site.MobilePageId                = ppMobilePage.PageId;
                site.ExternalUrl                 = tbExternalURL.Text;
                site.AllowedFrameDomains         = tbAllowedFrameDomains.Text;
                site.RedirectTablets             = cbRedirectTablets.Checked;
                site.EnablePageViews             = cbEnablePageViews.Checked;
                site.PageViewRetentionPeriodDays = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull();

                site.AllowIndexing     = cbAllowIndexing.Checked;
                site.PageHeaderContent = cePageHeaderContent.Text;

                var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>();
                site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>();

                // Remove any deleted domains
                foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList())
                {
                    site.SiteDomains.Remove(domain);
                    siteDomainService.Delete(domain);
                }

                foreach (string domain in currentDomains)
                {
                    SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault();
                    if (sd == null)
                    {
                        sd        = new SiteDomain();
                        sd.Domain = domain;
                        sd.Guid   = Guid.NewGuid();
                        site.SiteDomains.Add(sd);
                    }
                }

                if (!site.DefaultPageId.HasValue && !newSite)
                {
                    ppDefaultPage.ShowErrorMessage("Default Page is required.");
                    return;
                }

                if (!site.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    if (newSite)
                    {
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE);
                    }
                });

                SiteCache.Flush(site.Id);

                // Create the default page is this is a new site
                if (!site.DefaultPageId.HasValue && newSite)
                {
                    var siteCache = SiteCache.Read(site.Id);

                    // Create the layouts for the site, and find the first one
                    LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache);

                    var    layoutService = new LayoutService(rockContext);
                    var    layouts       = layoutService.GetBySiteId(siteCache.Id);
                    Layout layout        = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase));
                    if (layout == null)
                    {
                        layout = layouts.FirstOrDefault();
                    }

                    if (layout != null)
                    {
                        var pageService = new PageService(rockContext);
                        var page        = new Page();
                        page.LayoutId              = layout.Id;
                        page.PageTitle             = siteCache.Name + " Home Page";
                        page.InternalName          = page.PageTitle;
                        page.BrowserTitle          = page.PageTitle;
                        page.EnableViewState       = true;
                        page.IncludeAdminFooter    = true;
                        page.MenuDisplayChildPages = true;

                        var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault();

                        page.Order = lastPage != null ? lastPage.Order + 1 : 0;
                        pageService.Add(page);

                        rockContext.SaveChanges();

                        site = siteService.Get(siteCache.Id);
                        site.DefaultPageId = page.Id;

                        rockContext.SaveChanges();

                        SiteCache.Flush(site.Id);
                    }
                }

                var qryParams = new Dictionary <string, string>();
                qryParams["siteId"] = site.Id.ToString();

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
Beispiel #24
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            Site site;

            if (Page.IsValid)
            {
                var               rockContext       = new RockContext();
                PageService       pageService       = new PageService(rockContext);
                SiteService       siteService       = new SiteService(rockContext);
                SiteDomainService siteDomainService = new SiteDomainService(rockContext);
                bool              newSite           = false;

                int siteId = hfSiteId.Value.AsInteger();

                if (siteId == 0)
                {
                    newSite = true;
                    site    = new Rock.Model.Site();
                    siteService.Add(site);
                }
                else
                {
                    site = siteService.Get(siteId);
                }

                site.Name                      = tbSiteName.Text;
                site.Description               = tbDescription.Text;
                site.Theme                     = ddlTheme.Text;
                site.DefaultPageId             = ppDefaultPage.PageId;
                site.DefaultPageRouteId        = ppDefaultPage.PageRouteId;
                site.LoginPageId               = ppLoginPage.PageId;
                site.LoginPageRouteId          = ppLoginPage.PageRouteId;
                site.ChangePasswordPageId      = ppChangePasswordPage.PageId;
                site.ChangePasswordPageRouteId = ppChangePasswordPage.PageRouteId;
                site.CommunicationPageId       = ppCommunicationPage.PageId;
                site.CommunicationPageRouteId  = ppCommunicationPage.PageRouteId;
                site.RegistrationPageId        = ppRegistrationPage.PageId;
                site.RegistrationPageRouteId   = ppRegistrationPage.PageRouteId;
                site.PageNotFoundPageId        = ppPageNotFoundPage.PageId;
                site.PageNotFoundPageRouteId   = ppPageNotFoundPage.PageRouteId;
                site.ErrorPage                 = tbErrorPage.Text;
                site.GoogleAnalyticsCode       = tbGoogleAnalytics.Text;
                site.RequiresEncryption        = cbRequireEncryption.Checked;
                site.EnabledForShortening      = cbEnableForShortening.Checked;
                site.EnableMobileRedirect      = cbEnableMobileRedirect.Checked;
                site.MobilePageId              = ppMobilePage.PageId;
                site.ExternalUrl               = tbExternalURL.Text;
                site.AllowedFrameDomains       = tbAllowedFrameDomains.Text;
                site.RedirectTablets           = cbRedirectTablets.Checked;
                site.EnablePageViews           = cbEnablePageViews.Checked;

                site.AllowIndexing         = cbAllowIndexing.Checked;
                site.IsIndexEnabled        = cbEnableIndexing.Checked;
                site.IndexStartingLocation = tbIndexStartingLocation.Text;

                site.PageHeaderContent = cePageHeaderContent.Text;

                int?existingIconId = null;
                if (site.FavIconBinaryFileId != imgSiteIcon.BinaryFileId)
                {
                    existingIconId           = site.FavIconBinaryFileId;
                    site.FavIconBinaryFileId = imgSiteIcon.BinaryFileId;
                }

                int?existingLogoId = null;
                if (site.SiteLogoBinaryFileId != imgSiteLogo.BinaryFileId)
                {
                    existingLogoId            = site.SiteLogoBinaryFileId;
                    site.SiteLogoBinaryFileId = imgSiteLogo.BinaryFileId;
                }

                var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>();
                site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>();

                // Remove any deleted domains
                foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList())
                {
                    site.SiteDomains.Remove(domain);
                    siteDomainService.Delete(domain);
                }

                int order = 0;
                foreach (string domain in currentDomains)
                {
                    SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault();
                    if (sd == null)
                    {
                        sd        = new SiteDomain();
                        sd.Domain = domain;
                        sd.Guid   = Guid.NewGuid();
                        site.SiteDomains.Add(sd);
                    }
                    sd.Order = order++;
                }

                if (!site.DefaultPageId.HasValue && !newSite)
                {
                    ppDefaultPage.ShowErrorMessage("Default Page is required.");
                    return;
                }

                if (!site.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                rockContext.WrapTransaction(() =>
                {
                    rockContext.SaveChanges();

                    SaveAttributes(new Page().TypeId, "SiteId", site.Id.ToString(), PageAttributesState, rockContext);

                    if (existingIconId.HasValue)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(existingIconId.Value);
                        if (binaryFile != null)
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            rockContext.SaveChanges();
                        }
                    }

                    if (existingLogoId.HasValue)
                    {
                        BinaryFileService binaryFileService = new BinaryFileService(rockContext);
                        var binaryFile = binaryFileService.Get(existingLogoId.Value);
                        if (binaryFile != null)
                        {
                            // marked the old images as IsTemporary so they will get cleaned up later
                            binaryFile.IsTemporary = true;
                            rockContext.SaveChanges();
                        }
                    }

                    if (newSite)
                    {
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.EDIT);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.ADMINISTRATE);
                        Rock.Security.Authorization.CopyAuthorization(RockPage.Layout.Site, site, rockContext, Authorization.APPROVE);
                    }
                });

                // add/update for the InteractionChannel for this site and set the RetentionPeriod
                var interactionChannelService   = new InteractionChannelService(rockContext);
                int channelMediumWebsiteValueId = DefinedValueCache.Get(Rock.SystemGuid.DefinedValue.INTERACTIONCHANNELTYPE_WEBSITE.AsGuid()).Id;
                var interactionChannelForSite   = interactionChannelService.Queryable()
                                                  .Where(a => a.ChannelTypeMediumValueId == channelMediumWebsiteValueId && a.ChannelEntityId == site.Id).FirstOrDefault();

                if (interactionChannelForSite == null)
                {
                    interactionChannelForSite = new InteractionChannel();
                    interactionChannelForSite.ChannelTypeMediumValueId = channelMediumWebsiteValueId;
                    interactionChannelForSite.ChannelEntityId          = site.Id;
                    interactionChannelService.Add(interactionChannelForSite);
                }

                interactionChannelForSite.Name = site.Name;
                interactionChannelForSite.RetentionDuration     = nbPageViewRetentionPeriodDays.Text.AsIntegerOrNull();
                interactionChannelForSite.ComponentEntityTypeId = EntityTypeCache.Get <Rock.Model.Page>().Id;

                rockContext.SaveChanges();


                // Create the default page is this is a new site
                if (!site.DefaultPageId.HasValue && newSite)
                {
                    var siteCache = SiteCache.Get(site.Id);

                    // Create the layouts for the site, and find the first one
                    LayoutService.RegisterLayouts(Request.MapPath("~"), siteCache);

                    var    layoutService = new LayoutService(rockContext);
                    var    layouts       = layoutService.GetBySiteId(siteCache.Id);
                    Layout layout        = layouts.FirstOrDefault(l => l.FileName.Equals("FullWidth", StringComparison.OrdinalIgnoreCase));
                    if (layout == null)
                    {
                        layout = layouts.FirstOrDefault();
                    }

                    if (layout != null)
                    {
                        var page = new Page();
                        page.LayoutId              = layout.Id;
                        page.PageTitle             = siteCache.Name + " Home Page";
                        page.InternalName          = page.PageTitle;
                        page.BrowserTitle          = page.PageTitle;
                        page.EnableViewState       = true;
                        page.IncludeAdminFooter    = true;
                        page.MenuDisplayChildPages = true;

                        var lastPage = pageService.GetByParentPageId(null).OrderByDescending(b => b.Order).FirstOrDefault();

                        page.Order = lastPage != null ? lastPage.Order + 1 : 0;
                        pageService.Add(page);

                        rockContext.SaveChanges();

                        site = siteService.Get(siteCache.Id);
                        site.DefaultPageId = page.Id;

                        rockContext.SaveChanges();
                    }
                }

                var qryParams = new Dictionary <string, string>();
                qryParams["siteId"] = site.Id.ToString();

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
Beispiel #25
0
        public void ModifyFirstPartnerApplication(string connectionString)
        {
            string syncXml =
                "<CloudSync>" +
                "<FromDataVersion>6</FromDataVersion>" +
                "<ToDataVersion>7</ToDataVersion>" +
                "<Stores />" +
                "<Partners>" +
                "<Partner>" +
                "<Id>1</Id>" +
                "<Name>test partner 1AAA</Name>" +
                "<ExternalId>testpartner1AAA</ExternalId>" +
                "<Applications>" +
                "<Application>" +
                "<Id>1</Id>" +
                "<ExternalApplicationId>TestExternalApplicationidAAA</ExternalApplicationId>" +
                "<Name>TestNameAAA</Name>" +
                "<Sites>123</Sites>" +
                "</Application>" +
                "</Applications>" +
                "</Partner>" +
                "</Partners>" +
                "</CloudSync>";

            string errorMessage = AcsSyncHelper.ImportSyncXml(syncXml);

            Assert.AreEqual <string>("", errorMessage);

            IDataAccessFactory dataAccess = new EntityFrameworkDataAccessFactory()
            {
                ConnectionStringOverride = connectionString
            };
            string sourceId = "";

            // Expected site list xml
            string expectedSiteListXml =
                "<Sites>" +
                "<Site>" +
                "<SiteId>TestExternalSiteIdZZZ</SiteId>" +
                "<Name>TestExternalSiteNameZZZ</Name>" +
                "<MenuVersion>1</MenuVersion>" +
                "<IsOpen>false</IsOpen>" +
                "<EstDelivTime>0</EstDelivTime>" +
                "</Site>" +
                "</Sites>";

            // Get the site list
            Response siteListResponse = SiteService.Get("TestExternalApplicationidAAA", "", "", "", null, AndroCloudHelper.DataTypeEnum.XML, dataAccess, out sourceId);

            Assert.AreEqual <string>(
                expectedSiteListXml,
                siteListResponse.ResponseText,
                "Wrong site list xml");

            // Expected site details xml
            string expectedSiteDetailsXml =
                "<SiteDetails>" +
                "<SiteId>TestExternalSiteIdZZZ</SiteId>" +
                "<Name>TestExternalSiteNameZZZ</Name>" +
                "<MenuVersion>1</MenuVersion>" +
                "<IsOpen>false</IsOpen>" +
                "<EstDelivTime>0</EstDelivTime>" +
                "<TimeZone>GMT+1</TimeZone>" +
                "<Phone>1234567890ZZZ</Phone>" +
                "<Address>" +
                "<Long>7.6</Long>" +
                "<Lat>9.8</Lat>" +
                "<Prem1>Test1_Prem1ZZZ</Prem1>" +
                "<Prem2>Test1_Prem2ZZZ</Prem2>" +
                "<Prem3>Test1_Prem3ZZZ</Prem3>" +
                "<Prem4>Test1_Prem4ZZZ</Prem4>" +
                "<Prem5>Test1_Prem5ZZZ</Prem5>" +
                "<Prem6>Test1_Prem6ZZZ</Prem6>" +
                "<Org1>Test1_Org1ZZZ</Org1>" +
                "<Org2>Test1_Org2ZZZ</Org2>" +
                "<Org3>Test1_Org3ZZZ</Org3>" +
                "<RoadNum>Test1_RoadNumZZZ</RoadNum>" +
                "<RoadName>Test1_RoadNameZZZ</RoadName>" +
                "<Town>Test1_TownZZZ</Town>" +
                "<Postcode>Test1_PostCodeZZ</Postcode>" +
                "<Dps>ZZZ1</Dps>" +
                "<County>Test1_CountyZZZ</County>" +
                "<Locality>Test1_LocalityZZZ</Locality>" +
                "<Country>United States</Country>" +
                "</Address>" +
                "<OpeningHours />" +
                "<PaymentProvider />" +
                "<PaymentClientId />" +
                "<PaymentClientPassword />" +
                "</SiteDetails>";

            // Get the site details
            Response siteDetailsResponse = SiteDetailsService.Get("TestExternalApplicationidAAA", "TestExternalSiteIdZZZ", AndroCloudHelper.DataTypeEnum.XML, dataAccess, out sourceId);

            Assert.AreEqual <string>(
                expectedSiteDetailsXml,
                siteDetailsResponse.ResponseText,
                "Wrong site details xml");
        }
Beispiel #26
0
        public async Task <IActionResult> GetSite(string id)
        {
            var data = await _siteService.Get(id);

            return(Ok(data));
        }
Beispiel #27
0
        // default error handling
        protected void Application_Error( object sender, EventArgs e )
        {
            // log error
            System.Web.HttpContext context = HttpContext.Current;
            System.Exception ex = Context.Server.GetLastError();

            bool logException = true;

            // string to send a message to the error page to prevent infinite loops
            // of error reporting from incurring if there is an exception on the error page
            string errorQueryParm = "?error=1";

            if (context.Request.Url.ToString().Contains("?error=1"))
            {
                errorQueryParm = "?error=2";
            }
            else if ( context.Request.Url.ToString().Contains( "?error=2" ) )
            {
                // something really bad is occurring stop logging errors as we're in an infinate loop
                logException = false;
            }

            if ( logException )
            {
                string status = "500";

                // determine if 404's should be tracked as exceptions
                bool track404 = Convert.ToBoolean( Rock.Web.Cache.GlobalAttributes.Value( "Log404AsException" ) );

                // set status to 404
                if ( ex.Message == "File does not exist." && ex.Source == "System.Web" )
                {
                    status = "404";
                }

                if (status == "500" || track404)
                {
                    LogError( ex, -1, status, context );
                    context.Server.ClearError();

                    string errorPage = string.Empty;

                    // determine error page based on the site
                    SiteService service = new SiteService();
                    Site site = null;
                    string siteName = string.Empty;

                    if ( context.Items["Rock:SiteId"] != null )
                    {
                        int siteId = Int32.Parse( context.Items["Rock:SiteId"].ToString() );

                        // load site
                        site = service.Get( siteId );

                        siteName = site.Name;
                        errorPage = site.ErrorPage;
                    }

                    // store exception in session
                    Session["Exception"] = ex;

                    // email notifications if 500 error
                    if ( status == "500" )
                    {
                        // setup merge codes for email
                        var mergeObjects = new List<object>();

                        var values = new Dictionary<string, string>();

                        string exceptionDetails = "An error occurred on the " + siteName + " site on page: <br>" + context.Request.Url.OriginalString + "<p>" + FormatException( ex, "" );
                        values.Add( "ExceptionDetails", exceptionDetails );
                        mergeObjects.Add( values );

                        // get email addresses to send to
                        string emailAddressesList = Rock.Web.Cache.GlobalAttributes.Value( "EmailExceptionsList" );
                        if ( emailAddressesList != null )
                        {
                            string[] emailAddresses = emailAddressesList.Split( new char[] { ',' } );

                            var recipients = new Dictionary<string, List<object>>();

                            foreach ( string emailAddress in emailAddresses )
                            {
                                recipients.Add( emailAddress, mergeObjects );
                            }

                            if ( recipients.Count > 0 )
                            {
                                Email email = new Email( Rock.SystemGuid.EmailTemplate.CONFIG_EXCEPTION_NOTIFICATION );
                                SetSMTPParameters( email );  //TODO move this set up to the email object
                                email.Send( recipients );
                            }
                        }
                    }

                    // redirect to error page
                    if ( errorPage != null && errorPage != string.Empty )
                        Response.Redirect( errorPage + errorQueryParm );
                    else
                        Response.Redirect( "~/error.aspx" + errorQueryParm );  // default error page
                }
            }
        }
Beispiel #28
0
        /// <summary>
        /// Binds the pages grid.
        /// </summary>
        protected void BindPagesGrid()
        {
            pnlPages.Visible = false;
            int siteId = PageParameter("siteId").AsInteger();

            if (siteId == 0)
            {
                // quit if the siteId can't be determined
                return;
            }

            hfSiteId.SetValue(siteId);
            pnlPages.Visible = true;

            // Question: Is this RegisterLayouts necessary here?  Since if it's a new layout
            // there would not be any pages on them (which is our concern here).
            // It seems like it should be the concern of some other part of the puzzle.
            LayoutService.RegisterLayouts(Request.MapPath("~"), SiteCache.Read(siteId));
            //var layouts = layoutService.Queryable().Where( a => a.SiteId.Equals( siteId ) ).Select( a => a.Id ).ToList();

            // Find all the pages that are related to this site...
            // 1) pages used by one of this site's layouts and
            // 2) the site's 'special' pages used directly by the site.
            var rockContext = new RockContext();
            var siteService = new SiteService(rockContext);
            var pageService = new PageService(rockContext);

            var site = siteService.Get(siteId);

            if (site != null)
            {
                var sitePages = new List <int> {
                    site.DefaultPageId ?? -1,
                    site.LoginPageId ?? -1,
                    site.RegistrationPageId ?? -1,
                    site.PageNotFoundPageId ?? -1
                };

                var qry = pageService.Queryable("Layout")
                          .Where(t =>
                                 t.Layout.SiteId == siteId ||
                                 sitePages.Contains(t.Id));

                string layoutFilter = gPagesFilter.GetUserPreference("Layout");
                if (!string.IsNullOrWhiteSpace(layoutFilter) && layoutFilter != Rock.Constants.All.Text)
                {
                    qry = qry.Where(a => a.Layout.ToString() == layoutFilter);
                }

                SortProperty sortProperty = gPages.SortProperty;
                if (sortProperty != null)
                {
                    qry = qry.Sort(sortProperty);
                }
                else
                {
                    qry = qry
                          .OrderBy(t => t.Layout.Name)
                          .ThenBy(t => t.InternalName);
                }

                gPages.DataSource = qry.ToList();
                gPages.DataBind();
            }
        }
Beispiel #29
0
        public void DeleteFirstPartnerApplicationStore(string connectionString)
        {
            string syncXml =
                "<CloudSync>" +
                "<FromDataVersion>9</FromDataVersion>" +
                "<ToDataVersion>10</ToDataVersion>" +
                "<Stores />" +
                "<Partners>" +
                "<Partner>" +
                "<Id>1</Id>" +
                "<Name>test partner 1AAA</Name>" +
                "<ExternalId>testpartner1AAA</ExternalId>" +
                "<Applications>" +
                "<Application>" +
                "<Id>1</Id>" +
                "<ExternalApplicationId>TestExternalApplicationidAAA</ExternalApplicationId>" +
                "<Name>TestNameAAA</Name>" +
                "<Sites>124</Sites>" +
                "</Application>" +
                "</Applications>" +
                "</Partner>" +
                "</Partners>" +
                "</CloudSync>";

            string errorMessage = AcsSyncHelper.ImportSyncXml(syncXml);

            Assert.AreEqual <string>("", errorMessage);

            IDataAccessFactory dataAccess = new EntityFrameworkDataAccessFactory()
            {
                ConnectionStringOverride = connectionString
            };
            string sourceId = "";

            // Expected site list xml
            //string expectedSiteListXml =
            //    "<Sites>" +
            //        "<Site>" +
            //            "<SiteId>TestExternalSiteIdZZZ</SiteId>" +
            //            "<Name>TestExternalSiteNameZZZ</Name>" +
            //            "<MenuVersion>1</MenuVersion>" +
            //            "<IsOpen>false</IsOpen>" +
            //            "<EstDelivTime>0</EstDelivTime>" +
            //        "</Site>" +
            //    "</Sites>";

            // Get the site list
            Response siteListResponse = SiteService.Get("TestExternalApplicationidAAA", "", "", "", null, AndroCloudHelper.DataTypeEnum.XML, dataAccess, out sourceId);

            // Parse the sites xml
            XElement xElement = XElement.Parse(siteListResponse.ResponseText);

            // Check that the correct number of sites were returned
            var actualSites = (from sites in xElement.Elements("Site")
                               select sites).ToList();

            Assert.AreEqual <int>(1, actualSites.Count);

            // Try and get the fiirst site details.  This should fail
            Response siteDetailsResponse = SiteDetailsService.Get("TestExternalApplicationidAAA", "TestExternalSiteIdZZZ", AndroCloudHelper.DataTypeEnum.XML, dataAccess, out sourceId);

            // Parse the xml
            Assert.AreEqual <string>(
                "<Error><ErrorCode>1030</ErrorCode><Message>ApplicationId is not authorized to access this siteId</Message></Error>",
                siteDetailsResponse.ResponseText);

            //// Expected site details xml
            //string expectedSite2DetailsXml =
            //    "<SiteDetails>" +
            //        "<SiteId>Test2ExternalSiteId</SiteId>" +
            //        "<Name>Test2ExternalSiteName</Name>" +
            //        "<MenuVersion>1</MenuVersion>" +
            //        "<IsOpen>false</IsOpen>" +
            //        "<EstDelivTime>0</EstDelivTime>" +
            //        "<TimeZone>GMT+4</TimeZone>" +
            //        "<Phone>2222222</Phone>" +
            //        "<Address>" +
            //            "<Long>4.333</Long>" +
            //            "<Lat>2.111</Lat>" +
            //            "<Prem1>Test2_Prem1</Prem1>" +
            //            "<Prem2>Test2_Prem2/Prem2>" +
            //            "<Prem3>Test2_Prem3</Prem3>" +
            //            "<Prem4>Test2_Prem4</Prem4>" +
            //            "<Prem5>Test2_Prem5</Prem5>" +
            //            "<Prem6>Test2_Prem6</Prem6>" +
            //            "<Org1>Test2_Org1</Org1>" +
            //            "<Org2>Test2_Org2</Org2>" +
            //            "<Org3>Test2_Org3</Org3>" +
            //            "<RoadNum>Test2_RoadNum</RoadNum>" +
            //            "<RoadName>Test2_RoadName</RoadName>" +
            //            "<Town>Test2_Town</Town>" +
            //            "<Postcode>Test2_PostCode</Postcode>" +
            //            "<Dps>DPS2</Dps>" +
            //            "<County>Test2_County</County>" +
            //            "<Locality>Test2_Locality</Locality>" +
            //            "<Country>United Kingdom</Country>" +
            //        "</Address>" +
            //        "<OpeningHours />" +
            //        "<PaymentProvider />" +
            //        "<PaymentClientId />" +
            //        "<PaymentClientPassword />" +
            //    "</SiteDetails>";

            // Get the site2 details
            siteDetailsResponse = SiteDetailsService.Get("TestExternalApplicationidAAA", "Test2ExternalSiteId", AndroCloudHelper.DataTypeEnum.XML, dataAccess, out sourceId);

            // Parse the xml
            xElement = XElement.Parse(siteDetailsResponse.ResponseText);

            // Check to see if the first site was returned
            errorMessage = XmlHelper.CheckSiteDetails(
                xElement,
                "Test2ExternalSiteId",
                "Test2ExternalSiteName",
                "GMT+4",
                "2222222",
                "4.333",
                "2.111",
                "Test2_Prem1",
                "Test2_Prem2",
                "Test2_Prem3",
                "Test2_Prem4",
                "Test2_Prem5",
                "Test2_Prem6",
                "Test2_Org1",
                "Test2_Org2",
                "Test2_Org3",
                "Test2_RoadNum",
                "Test2_RoadName",
                "Test2_Town",
                "Test2_PostCode",
                "DPS2",
                "Test2_County",
                "Test2_Locality",
                "United Kingdom");
        }
Beispiel #30
0
        // default error handling
        /// <summary>
        /// Handles the Error event of the Application control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void Application_Error(object sender, EventArgs e)
        {
            // log error
            System.Web.HttpContext context = HttpContext.Current;
            System.Exception       ex      = Context.Server.GetLastError();

            if (ex != null)
            {
                bool logException = true;

                // string to send a message to the error page to prevent infinite loops
                // of error reporting from incurring if there is an exception on the error page
                string errorQueryParm = "?error=1";

                if (context.Request.Url.ToString().Contains("?error=1"))
                {
                    errorQueryParm = "?error=2";
                }
                else if (context.Request.Url.ToString().Contains("?error=2"))
                {
                    // something really bad is occurring stop logging errors as we're in an infinate loop
                    logException = false;
                }


                if (logException)
                {
                    string status = "500";

                    var globalAttributesCache = GlobalAttributesCache.Read();

                    // determine if 404's should be tracked as exceptions
                    bool track404 = Convert.ToBoolean(globalAttributesCache.GetValue("Log404AsException"));

                    // set status to 404
                    if (ex.Message == "File does not exist." && ex.Source == "System.Web")
                    {
                        status = "404";
                    }

                    if (status == "500" || track404)
                    {
                        LogError(ex, -1, status, context);
                        context.Server.ClearError();

                        string errorPage = string.Empty;

                        // determine error page based on the site
                        SiteService service  = new SiteService();
                        Site        site     = null;
                        string      siteName = string.Empty;

                        if (context.Items["Rock:SiteId"] != null)
                        {
                            int siteId = Int32.Parse(context.Items["Rock:SiteId"].ToString());

                            // load site
                            site = service.Get(siteId);

                            siteName  = site.Name;
                            errorPage = site.ErrorPage;
                        }

                        // store exception in session
                        Session["Exception"] = ex;

                        // email notifications if 500 error
                        if (status == "500")
                        {
                            // setup merge codes for email
                            var mergeObjects = new Dictionary <string, object>();
                            mergeObjects.Add("ExceptionDetails", "An error occurred on the " + siteName + " site on page: <br>" + context.Request.Url.OriginalString + "<p>" + FormatException(ex, ""));

                            // get email addresses to send to
                            string emailAddressesList = globalAttributesCache.GetValue("EmailExceptionsList");
                            if (!string.IsNullOrWhiteSpace(emailAddressesList))
                            {
                                string[] emailAddresses = emailAddressesList.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                                var recipients = new Dictionary <string, Dictionary <string, object> >();

                                foreach (string emailAddress in emailAddresses)
                                {
                                    recipients.Add(emailAddress, mergeObjects);
                                }

                                if (recipients.Count > 0)
                                {
                                    Email email = new Email(Rock.SystemGuid.EmailTemplate.CONFIG_EXCEPTION_NOTIFICATION);
                                    email.Send(recipients);
                                }
                            }
                        }

                        // redirect to error page
                        if (errorPage != null && errorPage != string.Empty)
                        {
                            Response.Redirect(errorPage + errorQueryParm, false);
                            Context.ApplicationInstance.CompleteRequest();
                        }
                        else
                        {
                            Response.Redirect("~/error.aspx" + errorQueryParm, false);    // default error page
                            Context.ApplicationInstance.CompleteRequest();
                        }

                        // intentially throw ThreadAbort
                        Response.End();
                    }
                }
            }
        }
Beispiel #31
0
        /// <summary>
        /// Handles the Click event of the btnSave control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param>
        protected void btnSave_Click(object sender, EventArgs e)
        {
            using (new Rock.Data.UnitOfWorkScope())
            {
                Site              site;
                SiteService       siteService       = new SiteService();
                SiteDomainService siteDomainService = new SiteDomainService();
                bool              newSite           = false;

                int siteId = int.Parse(hfSiteId.Value);

                if (siteId == 0)
                {
                    newSite = true;
                    site    = new Rock.Model.Site();
                    siteService.Add(site, CurrentPersonId);
                }
                else
                {
                    site = siteService.Get(siteId);
                }

                site.Name               = tbSiteName.Text;
                site.Description        = tbDescription.Text;
                site.Theme              = ddlTheme.Text;
                site.DefaultPageId      = int.Parse(ppDefaultPage.SelectedValue);
                site.LoginPageReference = tbLoginPageReference.Text;

                var currentDomains = tbSiteDomains.Text.SplitDelimitedValues().ToList <string>();
                site.SiteDomains = site.SiteDomains ?? new List <SiteDomain>();

                // Remove any deleted domains
                foreach (var domain in site.SiteDomains.Where(w => !currentDomains.Contains(w.Domain)).ToList())
                {
                    site.SiteDomains.Remove(domain);
                    siteDomainService.Delete(domain, CurrentPersonId);
                }

                foreach (string domain in currentDomains)
                {
                    SiteDomain sd = site.SiteDomains.Where(d => d.Domain == domain).FirstOrDefault();
                    if (sd == null)
                    {
                        sd        = new SiteDomain();
                        sd.Domain = domain;
                        sd.Guid   = Guid.NewGuid();
                        site.SiteDomains.Add(sd);
                    }
                }

                site.FaviconUrl                = tbFaviconUrl.Text;
                site.AppleTouchIconUrl         = tbAppleTouchIconUrl.Text;
                site.FacebookAppId             = tbFacebookAppId.Text;
                site.FacebookAppSecret         = tbFacebookAppSecret.Text;
                site.RegistrationPageReference = tbRegistrationPageReference.Text;
                site.ErrorPage = tbErrorPage.Text;

                if (!site.IsValid)
                {
                    // Controls will render the error messages
                    return;
                }

                RockTransactionScope.WrapTransaction(() =>
                {
                    siteService.Save(site, CurrentPersonId);

                    if (newSite)
                    {
                        Rock.Security.Authorization.CopyAuthorization(CurrentPage.Site, site, CurrentPersonId);
                    }
                });

                SiteCache.Flush(site.Id);
            }

            NavigateToParentPage();
        }