Example #1
0
        public override void Load()
        {
            Bind<IApplicationService>().ToConstant(_applicationService = Kernel.Get<ApplicationService>());
            Bind<IStorageService>().ToConstant(_storageService = Kernel.Get<StorageService>());
            Bind<ISettingsService>().ToConstant(_settingsService = Kernel.Get<SettingsService>());
            Bind<ISiteService>().ToConstant(_siteService = Kernel.Get<SiteService>());

            Bind<CuoUri>().ToSelf();
            Bind<ShellForm>().ToSelf().InSingletonScope();
            Bind<ShellController>().ToSelf().InSingletonScope();

            _shellForm = Kernel.Get<ShellForm>();
            _shellController = Kernel.Get<ShellController>();

            Bind<IShell>().ToConstant(_shellForm);
            Bind<IShellController>().ToConstant(_shellController);

            Bind<PatcherForm>().ToSelf();
            Bind<SplashScreen>().ToSelf();
            Bind<AboutControl>().ToSelf();
            Bind<SettingsControl>().ToSelf();
            Bind<NavigationControl>().ToSelf();
            Bind<EditLocalServerControl>().ToSelf();
            Bind<LocalServerListControl>().ToSelf();
            Bind<PublicServerListControl>().ToSelf();
            Bind<FavoritesServerListControl>().ToSelf();
        }
        public void all_Licence_numbers_are_7_digit_integers()
        {
            var entities = new EntitiesContext();

            var siteRepository = new EntityRepository<Site>(entities);
            var licenceRepository = new EntityRepository<Licence>(entities);
            var antennaRepository = new EntityRepository<Antenna>(entities);

            ISiteService siteService = new SiteService(siteRepository, licenceRepository, antennaRepository);

            var licences = siteService.GetLicences();
            foreach (var licence in licences)
            {
                int n;
                int.TryParse(licence.SpectrumLicence, out n);

                var s = n.ToString();
                var target = s.Length;
                //if (digitCount != 7)
                //{
                    //this.TestContext.WriteLine("\tInvalid Licence Number: " + s);
                    //throw new ApplicationException("\tInvalid Licence Number: " + s);
                //}
                Assert.AreEqual(7, target);
            }
        }
        public void Can_Validate_Station_Data()
        {
            var entities = new EntitiesContext();

            var siteRepository = new EntityRepository<Site>(entities);
            var licenceRepository = new EntityRepository<Licence>(entities);
            var antennaRepository = new EntityRepository<Antenna>(entities);

            ISiteService siteService = new SiteService(siteRepository, licenceRepository, antennaRepository);

            XNamespace ns = "http://sd.ic.gc.ca/SLDR_Schema_Definition_en";

            IEnumerable<XElement> spectrum_licences = siteService
                .GetLicences()
                .ToList()
                .Where(x => x.Antennas.Any())
                .OrderBy(x => x.SpectrumLicence)
                //.Take(3)
                .Select(x => new XElement("spectrum_licence",
                    new XElement("licence_number", x.SpectrumLicence),
                    new XElement("office_number", 7),
                    new XElement("company_code", x.CompanyCode),
                    new XElement("reference_number", x.ReferenceNumber),
                    new XElement("contact_name", x.ContactName),
                    new XElement("business_telephone", x.Phone),
                    new XElement("extension", x.PhoneExt),
                    new XElement("email_address", x.Email),
                    getStations(x)
                ));

            XDocument doc = new XDocument(new XElement("spectrum_licence_data_registry", spectrum_licences));

            foreach (XElement e in doc.Root.DescendantsAndSelf())
            {
                if (e.Name.Namespace == "")
                    e.Name = ns + e.Name.LocalName;
            }

            XmlReaderSettings sldrSettings = new XmlReaderSettings();
            sldrSettings.Schemas.Add(ns.NamespaceName, @"c:\temp\SLDR_Schema_Definition_en.xsd");
            sldrSettings.ValidationType = ValidationType.Schema;
            sldrSettings.ValidationEventHandler += new ValidationEventHandler(validationCallBack);

            //using (MemoryStream stream = new MemoryStream())
            using (FileStream stream = new FileStream(@"c:\temp\Silo_Station_Data.xml", FileMode.Create, FileAccess.ReadWrite))
            {
                StreamWriter writer = new StreamWriter(stream, Encoding.Default);
                doc.Save(writer);

                stream.Flush();
                stream.Seek(0, SeekOrigin.Begin);

                XmlReader data = XmlReader.Create(stream, sldrSettings);

                while (data.Read()) { }
            }

            Assert.IsNotNull(doc);
        }
Example #4
0
        public ActionResult Create(Site model)
        {
            if (ModelState.IsValid)
            {
                try
                {
                    var service = new SiteService(DataContext);
                    service.CreateSite(model);

                    ShowSuccess(MessageResource.CreateSuccess);

                    return RedirectToIndex();
                }
                catch (Exception e)
                {
                    LogError(e.ToString());
                    ShowError(MessageResource.CreateFailed);
                }
            }

            return View(model);
        }
        public ActionResult Create(int personId, Invitation invitation)
        {
            var person  = Repository.OfType <Person>().GetNullableById(personId);
            var seminar = SiteService.GetLatestSeminar(Site);

            if (person == null || seminar == null)
            {
                return(this.RedirectToAction <ErrorController>(a => a.Index()));
            }

            if (AddToInvitationList(seminar, person, Site, invitation.Title, invitation.FirmName))
            {
                Message = "Invitation Created Successfully";

                return(this.RedirectToAction <PersonController>(a => a.AdminEdit(person.User.Id, null, true)));
            }

            Message = "Person already on invitation list.";

            invitation.Person  = person;
            invitation.Seminar = seminar;

            return(View(invitation));
        }
Example #6
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user)
        {
            using (SiteService siteService = user.GetService<SiteService>())
            {
                // Create a statement to select sites.
                int pageSize = StatementBuilder.SUGGESTED_PAGE_LIMIT;
                StatementBuilder statementBuilder =
                    new StatementBuilder().OrderBy("id ASC").Limit(pageSize);

                // Retrieve a small amount of sites at a time, paging through until all
                // sites have been retrieved.
                int totalResultSetSize = 0;
                do
                {
                    SitePage page =
                        siteService.getSitesByStatement(statementBuilder.ToStatement());

                    // Print out some information for each site.
                    if (page.results != null)
                    {
                        totalResultSetSize = page.totalResultSetSize;
                        int i = page.startIndex;
                        foreach (Site site in page.results)
                        {
                            Console.WriteLine(
                                "{0}) Site with ID {1} and URL \"{2}\" was found.", i++,
                                site.id, site.url);
                        }
                    }

                    statementBuilder.IncreaseOffsetBy(pageSize);
                } while (statementBuilder.GetOffset() < totalResultSetSize);

                Console.WriteLine("Number of results found: {0}", totalResultSetSize);
            }
        }
Example #7
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)
        {
            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();
        }
Example #8
0
        /// <summary>
        /// There's a common use for Branch, DirectorateProject and DepartmentSubProject  etc
        /// This function will help generically retrieve a unique list of the above 3 from a specified table
        /// CAUTION!! Only use this if the table you're trying to query has the above 3 "string" columns and are spelled exactly as above!
        /// If the table doesn't have, then using this function will break your request, if not spelled the same, kindly make it spelled as
        /// above to enjoy me!
        /// LOOK at /Views/PaymentRequisition/_List and then /Views/Shared/_PRCustomSearch for usage
        /// </summary>
        /// <param name="listType"></param>
        public CustomSearchModel(string listType)
        {
            SetDefaults();

            switch (listType)
            {
            case "Users":



                break;


            case "PSPs":
            case "LinkProducts":

                using (ClientService cservice = new ClientService())
                    using (ProductService pservice = new ProductService())
                    {
                        ClientOptions  = cservice.List(true);
                        ProductOptions = pservice.List(true);
                    }

                break;


            case "Regions":

                using (PSPService pservice = new PSPService())
                {
                    PSPOptions = pservice.List(true);
                }

                break;


            case "Clients":

                using (PSPService pservice = new PSPService())
                    using (ClientService cservice = new ClientService())
                    {
                        PSPOptions    = pservice.List(true);
                        ClientOptions = cservice.List(true);
                    }

                break;


            case "SetClient":
            case "ClientKPI":
            case "ReconcileLoads":
            case "MovementReport":
            case "ReconcileInvoice":
            case "ManageTransporters":

                using (ClientService cservice = new ClientService())
                {
                    ClientOptions = cservice.List(true);
                }

                break;


            case "Disputes":
            case "Exceptions":
            case "DeliveryNotes":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                        using (DisputeReasonService drervice = new DisputeReasonService())
                        {
                            SiteOptions          = sservice.List(true);
                            ClientOptions        = cservice.List(true);
                            DisputeReasonOptions = drervice.List();
                        }

                break;


            case "ChepAudit":
            case "ClientAudit":

                using (SiteService sservice = new SiteService())
                {
                    SiteOptions = sservice.List(true);
                }

                break;


            case "DashBoard":

                using (SiteService sservice = new SiteService())
                    using (RegionService rservice = new RegionService())
                        using (ClientService cservice = new ClientService())
                            using (ProductService pservice = new ProductService())
                            {
                                SiteOptions    = sservice.List(true);
                                RegionOptions  = rservice.List(true);
                                ClientOptions  = cservice.List(true);
                                ProductOptions = pservice.List(true);
                            }

                break;


            case "AuthorisationCodes":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                        using (TransporterService tservice = new TransporterService())
                        {
                            SiteOptions        = sservice.List(true);
                            ClientOptions      = cservice.List(true);
                            TransporterOptions = tservice.List(true);
                        }

                break;


            case "Billing":

                using (PSPService pservice = new PSPService())
                    using (PSPProductService p1service = new PSPProductService())
                    {
                        PSPOptions        = pservice.List(true);
                        PSPProductOptions = p1service.List(true);
                    }

                break;


            case "ManageSites":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                        using (RegionService rservice = new RegionService())
                        {
                            SiteOptions   = sservice.List(true);
                            ClientOptions = cservice.List(true);
                            RegionOptions = rservice.List(true);
                        }

                break;


            case "ClientData":

                using (ClientService cservice = new ClientService())
                    using (VehicleService vservice = new VehicleService())
                        //using ( ClientSiteService csservice = new ClientSiteService() )
                        using (TransporterService tservice = new TransporterService())
                            using (OutstandingReasonService urservice = new OutstandingReasonService())
                            {
                                ClientOptions  = cservice.List(true);
                                VehicleOptions = vservice.List(true);
                                //ClientSiteOptions = csservice.List( true );
                                TransporterOptions       = tservice.List(true);
                                OutstandingReasonOptions = urservice.List(true);
                            }

                break;

            case "PODOutstanding":
            case "PoolingAgentData":
            case "OutstandingPallets":
            case "TopOustandingCustomers":
            case "TransporterLiableReport":

                using (ClientService cservice = new ClientService())
                    using (OutstandingReasonService urservice = new OutstandingReasonService())
                    {
                        ClientOptions            = cservice.List(true);
                        OutstandingReasonOptions = urservice.List(true);
                    }

                break;

            case "SiteAudits":

                using (SiteService sservice = new SiteService())
                    using (ClientService cservice = new ClientService())
                    {
                        SiteOptions   = sservice.List(true);
                        ClientOptions = cservice.List(true);
                    }

                break;

            case "PODPerUser":
            case "PODUploadLog":

                using (UserService uservice = new UserService())
                {
                    User1Options = uservice.List(true, RoleType.All);
                }

                break;

            case "AuthorizationCodeAudit":

                using (UserService uservice = new UserService())
                    using (TransporterService tservice = new TransporterService())
                    {
                        TransporterOptions = tservice.List(true);
                        User1Options       = uservice.List(true, RoleType.All);
                    }

                break;

            case "AuditLogPerUser":

                using (UserService uservice = new UserService())
                    using (ClientService cservice = new ClientService())
                        using (VehicleService vservice = new VehicleService())
                            using (PODCommentService pcservice = new PODCommentService())
                                using (TransporterService tservice = new TransporterService())
                                {
                                    ClientOptions      = cservice.List(true);
                                    VehicleOptions     = vservice.List(true);
                                    PODCommentOptions  = pcservice.List(true);
                                    TransporterOptions = tservice.List(true);
                                    User1Options       = uservice.List(true, RoleType.All);
                                }

                break;
            }

            using (ClientService cservice = new ClientService())
            {
                if (cservice.SelectedClient != null && ClientId == 0)
                {
                    ClientId = cservice.SelectedClient.Id;
                }
            }
        }
Example #9
0
        /// <summary>
        /// Shows the edit.
        /// </summary>
        /// <param name="siteId">The site id.</param>
        public void ShowDetail(int siteId)
        {
            pnlDetails.Visible = false;

            Site site = null;

            if (!siteId.Equals(0))
            {
                site = new SiteService(new RockContext()).Get(siteId);
                pdAuditDetails.SetEntity(site, ResolveRockUrl("~"));
            }

            if (site == null)
            {
                site = new Site {
                    Id = 0
                };
                site.SiteDomains = new List <SiteDomain>();
                site.Theme       = RockPage.Layout.Site.Theme;
                // hide the panel drawer that show created and last modified dates
                pdAuditDetails.Visible = false;
            }
            else
            {
                if (site.DefaultPageId.HasValue)
                {
                    lVisitSite.Text = string.Format(@"<a href=""{0}{1}"" target=""_blank""><span class=""label label-info"">Visit Site</span></a>", ResolveRockUrl("~/page/"), site.DefaultPageId);
                }
            }

            Guid fileTypeGuid = GetAttributeValue("DefaultFileType").AsGuid();

            imgSiteIcon.BinaryFileTypeGuid = fileTypeGuid;

            // set theme compile button
            if (!new RockTheme(site.Theme).AllowsCompile)
            {
                btnCompileTheme.Enabled = false;
                btnCompileTheme.Text    = "Theme Doesn't Support Compiling";
            }

            pnlDetails.Visible = true;
            hfSiteId.Value     = site.Id.ToString();

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

            bool readOnly = false;

            nbEditModeMessage.Text = string.Empty;
            if (!IsUserAuthorized(Authorization.EDIT))
            {
                readOnly = true;
                nbEditModeMessage.Text = EditModeMessage.ReadOnlyEditActionNotAllowed(Rock.Model.Site.FriendlyTypeName);
            }

            if (site.IsSystem)
            {
                nbEditModeMessage.Text = EditModeMessage.System(Rock.Model.Site.FriendlyTypeName);
            }

            if (readOnly)
            {
                btnEdit.Visible   = false;
                btnDelete.Visible = false;
                ShowReadonlyDetails(site);
            }
            else
            {
                btnEdit.Visible   = true;
                btnDelete.Visible = !site.IsSystem;
                if (site.Id > 0)
                {
                    ShowReadonlyDetails(site);
                }
                else
                {
                    ShowEditDetails(site);
                }
            }
        }
Example #10
0
        /// <summary>
        /// Handles the Click event of the btnEdit 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 btnEdit_Click(object sender, EventArgs e)
        {
            var site = new SiteService(new RockContext()).Get(hfSiteId.Value.AsInteger());

            ShowEditDetails(site);
        }
 public SiteController(SiteService siteService)
 {
     _siteService = siteService;
 }
Example #12
0
 public ActionResult AssembleContentsPreAction(int id)
 {
     return(Json(SiteService.AssembleContentsPreAction(id)));
 }
Example #13
0
 public ActionResult Cancel(int id)
 {
     SiteService.Cancel(id);
     return(Json(null));
 }
Example #14
0
        public void GetSitesExceptionStateTest()
        {
            SiteService siteservice = new SiteService();

            siteservice.GetSites(null);
        }
Example #15
0
 public WelcomeController(SiteService siteservice)
 {
     _siteservice = siteservice;
 }
        /// <summary>
        /// Binds the grid.
        /// </summary>
        private void BindGrid()
        {
            var htmlContentService = new HtmlContentService();
            var htmlContent        = htmlContentService.Queryable();

            string pageName = "";
            string siteName = "";
            var    htmlList = new List <HtmlApproval>();

            foreach (var content in htmlContent)
            {
                content.Block.LoadAttributes();
                var blah = content.Block.GetAttributeValue("RequireApproval");
                if (!string.IsNullOrEmpty(blah) && blah.ToLower() == "true")
                {
                    var pageService = new PageService();
                    if (content.Block.PageId != null)
                    {
                        var page = pageService.Get((int)content.Block.PageId);
                        if (page != null)
                        {
                            pageName = page.InternalName;
                            while (page.ParentPageId != null)
                            {
                                page = pageService.Get((int)page.ParentPageId);
                            }
                            var siteService = new SiteService();
                            siteName = siteService.GetByDefaultPageId(page.Id).Select(s => s.Name).FirstOrDefault();
                        }
                    }

                    var htmlApprovalClass = new HtmlApproval();
                    htmlApprovalClass.SiteName           = siteName;
                    htmlApprovalClass.PageName           = pageName;
                    htmlApprovalClass.Block              = content.Block;
                    htmlApprovalClass.BlockId            = content.BlockId;
                    htmlApprovalClass.Content            = content.Content;
                    htmlApprovalClass.Id                 = content.Id;
                    htmlApprovalClass.IsApproved         = content.IsApproved;
                    htmlApprovalClass.ApprovedByPerson   = content.ApprovedByPerson;
                    htmlApprovalClass.ApprovedByPersonId = content.ApprovedByPersonId;
                    htmlApprovalClass.ApprovedDateTime   = content.ApprovedDateTime;

                    htmlList.Add(htmlApprovalClass);
                }
            }

            // Filter by Site
            if (ddlSiteFilter.SelectedIndex > 0)
            {
                if (ddlSiteFilter.SelectedValue.ToLower() != "all")
                {
                    htmlList = htmlList.Where(h => h.SiteName == ddlSiteFilter.SelectedValue).ToList();
                }
            }

            // Filter by approved/unapproved
            if (ddlApprovedFilter.SelectedIndex > -1)
            {
                if (ddlApprovedFilter.SelectedValue.ToLower() == "unapproved")
                {
                    htmlList = htmlList.Where(a => a.IsApproved == false).ToList();
                }
                else if (ddlApprovedFilter.SelectedValue.ToLower() == "approved")
                {
                    htmlList = htmlList.Where(a => a.IsApproved == true).ToList();
                }
            }

            // Filter by the person that approved the content
            if (_canApprove)
            {
                int personId = 0;
                if (int.TryParse(gContentListFilter.GetUserPreference("Approved By"), out personId) && personId != 0)
                {
                    htmlList = htmlList.Where(a => a.ApprovedByPersonId.HasValue && a.ApprovedByPersonId.Value == personId).ToList();
                }
            }

            SortProperty sortProperty = gContentList.SortProperty;

            if (sortProperty != null)
            {
                gContentList.DataSource = htmlList.AsQueryable().Sort(sortProperty).ToList();
            }
            else
            {
                gContentList.DataSource = htmlList.OrderBy(h => h.Id).ToList();
            }

            gContentList.DataBind();
        }
Example #17
0
 /// <summary>
 /// Default constructor.
 /// </summary>
 public SiteApiController(SiteService service, ManagerLocalizer localizer)
 {
     _service   = service;
     _localizer = localizer;
 }
Example #18
0
        public ActionResult Import(HttpPostedFileBase file)
        {
            try
            {
                if (ModelState.IsValid)
                {
                    var siteService = new SiteService(DataContext);
                    siteService.Import(XDocument.Load(file.InputStream));

                    ShowSuccess(MessageResource.ImportSuccess);
                }
            }
            catch (Exception ex)
            {
                LogError(ex.ToString());
                ShowError(MessageResource.ImportFailed);
            }

            return View();
        }
Example #19
0
        public ActionResult Export(int id, string fileName)
        {
            var site = FindSite(id);
            try
            {
                if (ModelState.IsValid)
                {
                    var siteService = new SiteService(DataContext);
                    var xml = siteService.Export(site, fileName);

                    Response.AppendHeader("Content-Disposition", "attachment;filename=" + fileName);
                    Response.Write(xml);
                    Response.End();

                   // ShowSuccess(MessageResource.ExportSuccess);
                }
            }
            catch (Exception ex)
            {
                LogError(ex.ToString());
                ShowError(MessageResource.ExportFailed);
            }

            return View(site);
        }
Example #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)
        {
            var rockContext = new RockContext();
            var pageService = new PageService(rockContext);
            var siteService = new SiteService(rockContext);

            int pageId = hfPageId.Value.AsInteger();
            var page   = pageService.Get(pageId);

            if (page != null)
            {
                string errorMessage = string.Empty;
                if (!pageService.CanDelete(page, out errorMessage))
                {
                    mdDeleteWarning.Show(errorMessage, ModalAlertType.Alert);
                    return;
                }

                foreach (var site in siteService.Queryable())
                {
                    if (site.DefaultPageId == page.Id)
                    {
                        site.DefaultPageId      = null;
                        site.DefaultPageRouteId = null;
                    }

                    if (site.LoginPageId == page.Id)
                    {
                        site.LoginPageId      = null;
                        site.LoginPageRouteId = null;
                    }

                    if (site.RegistrationPageId == page.Id)
                    {
                        site.RegistrationPageId      = null;
                        site.RegistrationPageRouteId = null;
                    }
                }

                int?parentPageId = page.ParentPageId;

                pageService.Delete(page);

                rockContext.SaveChanges();

                Rock.Web.Cache.PageCache.Flush(page.Id);

                // reload page, selecting the deleted page's parent
                var qryParams = new Dictionary <string, string>();
                if (parentPageId.HasValue)
                {
                    qryParams["Page"] = parentPageId.ToString();

                    string expandedIds = this.Request.Params["ExpandedIds"];
                    if (expandedIds != null)
                    {
                        // remove the current pageId param to avoid extra treeview flash
                        var expandedIdList = expandedIds.SplitDelimitedValues().AsIntegerList();
                        expandedIdList.Remove(parentPageId.Value);

                        qryParams["ExpandedIds"] = expandedIdList.AsDelimited(",");
                    }
                }

                NavigateToPage(RockPage.Guid, qryParams);
            }
        }
Example #21
0
 public void Ready()
 {
     Site = SiteService.Query(null).FirstOrDefault();
 }
Example #22
0
        /// <summary>
        /// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
        /// </summary>
        /// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);

            List <int> expandedPageIds = new List <int>();

            RockContext rockContext = new RockContext();
            PageService pageService = new PageService(rockContext);

            if (Page.IsPostBack)
            {
                foreach (int expandedId in hfExpandedIds.Value.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries).AsIntegerList())
                {
                    if (expandedId != 0)
                    {
                        expandedPageIds.Add(expandedId);
                    }
                }
            }
            else
            {
                string pageSearch = this.PageParameter(PageParameterKey.PageSearch);

                // NOTE: using "Page" instead of "PageId" since PageId is already parameter of the current page
                int?selectedPageId = this.PageParameter(PageParameterKey.Page).AsIntegerOrNull();
                if (!string.IsNullOrWhiteSpace(pageSearch))
                {
                    foreach (var page in pageService.Queryable().Where(a => a.InternalName.IndexOf(pageSearch) >= 0))
                    {
                        var selectedPage = page;
                        while (selectedPage != null)
                        {
                            selectedPage = selectedPage.ParentPage;
                            if (selectedPage != null)
                            {
                                expandedPageIds.Add(selectedPage.Id);
                            }
                        }
                    }
                }
                else if (selectedPageId.HasValue)
                {
                    expandedPageIds.Add(selectedPageId.Value);
                    hfSelectedItemId.Value = selectedPageId.ToString();
                }
            }

            // also get any additional expanded nodes that were sent in the Post
            string postedExpandedIds = this.Request.Params["ExpandedIds"];

            if (!string.IsNullOrWhiteSpace(postedExpandedIds))
            {
                var postedExpandedIdList = postedExpandedIds.Split(',').ToList().AsIntegerList();
                foreach (var postedId in postedExpandedIdList)
                {
                    if (!expandedPageIds.Contains(postedId))
                    {
                        expandedPageIds.Add(postedId);
                    }
                }
            }

            var sb = new StringBuilder();

            sb.AppendLine("<ul id=\"treeview\">");

            var rootPagesQry = pageService.Queryable().AsNoTracking();

            string rootPage = GetAttributeValue(AttributeKey.RootPage);

            if (!string.IsNullOrEmpty(rootPage))
            {
                Guid pageGuid = rootPage.AsGuid();
                rootPagesQry = rootPagesQry.Where(a => a.ParentPage.Guid == pageGuid);
            }
            else
            {
                rootPagesQry = rootPagesQry.Where(a => a.ParentPageId == null);
            }

            // Apply the Site Type filter to the root page list.
            var siteTypeList = GetAttributeValue(AttributeKey.SiteType).SplitDelimitedValues(",").AsIntegerList();

            if (siteTypeList.Any())
            {
                var siteService = new SiteService(rockContext);

                var siteIdList = siteService.Queryable()
                                 .Where(x => siteTypeList.Contains(( int )x.SiteType))
                                 .Select(x => x.Id)
                                 .ToList();

                rootPagesQry = rootPagesQry.Where(a => siteIdList.Contains(a.Layout.Site.Id));
            }

            var rootPageList = rootPagesQry.OrderBy(a => a.Order).Select(a => a.Id).ToList();

            foreach (var pageId in rootPageList)
            {
                sb.Append(PageNode(PageCache.Get(pageId), expandedPageIds, rockContext));
            }

            sb.AppendLine("</ul>");

            lPages.Text = sb.ToString();
        }
        /// <summary>
        /// Run the code example.
        /// </summary>
        public void Run(AdManagerUser user, long siteId)
        {
            using (SiteService siteService = user.GetService <SiteService>())
            {
                // Create statement to select the site.
                StatementBuilder statementBuilder = new StatementBuilder()
                                                    .Where("id = :id")
                                                    .OrderBy("id ASC")
                                                    .Limit(1)
                                                    .AddValue("id", siteId);

                // Set default for page.
                SitePage      page    = new SitePage();
                List <string> siteIds = new List <string>();
                int           i       = 0;

                try
                {
                    do
                    {
                        // Get sites by statement.
                        page = siteService.getSitesByStatement(
                            statementBuilder.ToStatement());

                        if (page.results != null)
                        {
                            foreach (Site site in page.results)
                            {
                                Console.WriteLine(
                                    "{0}) Site with ID = '{1}', URL = '{2}', " +
                                    "and approval status = '{3}' will be submitted for approval.",
                                    i++, site.id, site.url, site.approvalStatus);
                                siteIds.Add(site.id.ToString());
                            }
                        }

                        statementBuilder.IncreaseOffsetBy(StatementBuilder.SUGGESTED_PAGE_LIMIT);
                    } while (statementBuilder.GetOffset() < page.totalResultSetSize);

                    Console.WriteLine("Number of sites to be submitted for approval: {0}",
                                      siteIds.Count);

                    if (siteIds.Count > 0)
                    {
                        // Modify statement for action.
                        statementBuilder.RemoveLimitAndOffset();

                        // Create action.
                        Google.Api.Ads.AdManager.v202202.SubmitSiteForApproval action =
                            new Google.Api.Ads.AdManager.v202202.SubmitSiteForApproval();

                        // Perform action.
                        UpdateResult result =
                            siteService.performSiteAction(action,
                                                          statementBuilder.ToStatement());

                        // Display results.
                        if (result != null && result.numChanges > 0)
                        {
                            Console.WriteLine(
                                "Number of sites that were submitted for approval: {0}",
                                result.numChanges);
                        }
                        else
                        {
                            Console.WriteLine("No sites were submitted for approval.");
                        }
                    }
                }
                catch (Exception e)
                {
                    Console.WriteLine(
                        "Failed to send sites to Marketplace. Exception says \"{0}\"",
                        e.Message);
                }
            }
        }
Example #24
0
 public CreateSiteResourceViewModel(SiteService siteService, IModalService modalService)
 {
     _siteService  = siteService;
     _modalService = modalService;
 }
Example #25
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();
                    }
                }
            }
        }
Example #26
0
 public ParticipatingLibrariesController(ServiceFacade.Controller context,
                                         SiteService siteService)
     : base(context)
 {
     _siteService = siteService ?? throw new ArgumentNullException(nameof(siteService));
 }
Example #27
0
 public CreateSiteViewModel(SiteService siteService, NavigationManager navigationManager)
 {
     _siteService       = siteService;
     _navigationManager = navigationManager;
 }
Example #28
0
        public ActionResult SimpleRemove(int id)
        {
            var result = SiteService.SimpleRemove(id);

            return(Json(result));
        }
Example #29
0
        public CoreMutation(
            SiteService siteService
            )
        {
            Name = "CoreMutation";

            //FieldAsync<SiteType>(
            //    "updateSiteName",
            //    arguments: new QueryArguments(
            //        new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "id", Description = "id of the site" },
            //        new QueryArgument<NonNullGraphType<StringGraphType>> { Name = "newName", Description = "The new name for the site" }
            //    ),
            //    resolve: async context =>
            //    {
            //        var id = context.GetArgument<Guid>("id");
            //        var newName = context.GetArgument<string>("newName");
            //        return await context.TryAsyncResolve(
            //            async c => await siteService.UpdateSiteName(id, newName)
            //        );

            //    }

            //).AuthorizeWith("AdminPolicy");

            //FieldAsync<SiteType>(
            //    "updateSite",
            //    arguments: new QueryArguments(
            //        new QueryArgument<NonNullGraphType<IdGraphType>> { Name = "id", Description = "id of the site" },
            //        new QueryArgument<NonNullGraphType<SiteUpdateInputType>> { Name = "updateSite", Description = "an object to patch site properties" }
            //    ),
            //    resolve: async context =>
            //    {
            //        var id = context.GetArgument<Guid>("id");
            //        var patch = context.GetArgument<SiteUpdateModel>("updateSite");


            //        return await context.TryAsyncResolve(
            //            async c => await siteService.UpdateSite(id, patch)
            //        );

            //    }

            //).AuthorizeWith("AdminPolicy");

            FieldAsync <SiteType>(
                "updateSiteCompanyInfo",
                arguments: new QueryArguments(
                    new QueryArgument <NonNullGraphType <IdGraphType> > {
                Name = "id", Description = "id of the site"
            },
                    new QueryArgument <NonNullGraphType <CompanyInfoUpdateType> > {
                Name = "updateSiteCompanyInfo", Description = "an object to patch site properties"
            }
                    ),
                resolve: async context =>
            {
                var id = context.GetArgument <Guid>("id");
                //var model = context.GetArgument<CompanyInfoUpdateType>("updateSiteCompanyInfo");

                var patch = context.GetArgument <Dictionary <string, object> >("updateSiteCompanyInfo");

                return(await context.TryAsyncResolve(
                           async c => await siteService.UpdateSite(id, patch)
                           ));
            }

                )
            .AuthorizeWith("AdminPolicy")
            ;
        }
Example #30
0
 public ActionResult CaptureLock(int id)
 {
     SiteService.CaptureLock(id);
     return(Json(null));
 }
Example #31
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();
            }
        }
        private async Task Refresh()
        {
            Alias         alias = null;
            Site          site;
            List <Page>   pages;
            Page          page;
            User          user = null;
            List <Module> modules;
            var           moduleid      = -1;
            var           action        = string.Empty;
            var           urlparameters = string.Empty;
            var           editmode      = false;
            var           reload        = Reload.None;
            var           lastsyncdate  = DateTime.UtcNow;
            var           runtime       = GetRuntime();

            Uri uri = new Uri(_absoluteUri);

            // get path
            var path = uri.LocalPath.Substring(1);

            // parse querystring
            var querystring = ParseQueryString(uri.Query);

            // the reload parameter is used to reload the PageState
            if (querystring.ContainsKey("reload"))
            {
                reload = Reload.Site;
            }

            if (PageState != null)
            {
                editmode     = PageState.EditMode;
                lastsyncdate = PageState.LastSyncDate;
            }

            alias = await AliasService.GetAliasAsync(path, lastsyncdate);

            SiteState.Alias = alias; // set state for services
            lastsyncdate    = alias.SyncDate;

            // process any sync events for site or page
            if (reload != Reload.Site && alias.SyncEvents.Any())
            {
                if (PageState != null && alias.SyncEvents.Exists(item => item.EntityName == EntityNames.Page && item.EntityId == PageState.Page.PageId))
                {
                    reload = Reload.Page;
                }
                if (alias.SyncEvents.Exists(item => item.EntityName == EntityNames.Site && item.EntityId == alias.SiteId))
                {
                    reload = Reload.Site;
                }
            }

            if (reload == Reload.Site || PageState == null || alias.SiteId != PageState.Alias.SiteId)
            {
                site = await SiteService.GetSiteAsync(alias.SiteId);

                reload = Reload.Site;
            }
            else
            {
                site = PageState.Site;
            }

            if (site != null)
            {
                if (PageState == null || reload == Reload.Site)
                {
                    // get user
                    var authState = await AuthenticationStateProvider.GetAuthenticationStateAsync();

                    if (authState.User.Identity.IsAuthenticated)
                    {
                        user = await UserService.GetUserAsync(authState.User.Identity.Name, site.SiteId);
                    }
                }
                else
                {
                    user = PageState.User;
                }

                // process any sync events for user
                if (reload != Reload.Site && user != null && alias.SyncEvents.Any())
                {
                    if (alias.SyncEvents.Exists(item => item.EntityName == EntityNames.User && item.EntityId == user.UserId))
                    {
                        reload = Reload.Site;
                    }
                }

                if (PageState == null || reload >= Reload.Site)
                {
                    pages = await PageService.GetPagesAsync(site.SiteId);
                }
                else
                {
                    pages = PageState.Pages;
                }

                // format path and remove alias
                path = path.Replace("//", "/");

                if (!path.EndsWith("/"))
                {
                    path += "/";
                }

                if (alias.Path != "")
                {
                    path = path.Substring(alias.Path.Length + 1);
                }

                // extract admin route elements from path
                var segments = path.Split(new[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
                int result;

                int modIdPos         = 0;
                int actionPos        = 0;
                int urlParametersPos = 0;

                for (int i = 0; i < segments.Length; i++)
                {
                    if (segments[i] == Constants.UrlParametersDelimiter)
                    {
                        urlParametersPos = i + 1;
                    }

                    if (i >= urlParametersPos && urlParametersPos != 0)
                    {
                        urlparameters += "/" + segments[i];
                    }

                    if (segments[i] == Constants.ModuleDelimiter)
                    {
                        modIdPos  = i + 1;
                        actionPos = modIdPos + 1;
                        if (actionPos > segments.Length - 1)
                        {
                            action = Constants.DefaultAction;
                        }
                        else
                        {
                            action = segments[actionPos];
                        }
                    }
                }

                // check if path has moduleid and action specification ie. pagename/moduleid/action/
                if (modIdPos > 0)
                {
                    int.TryParse(segments[modIdPos], out result);
                    moduleid = result;
                    if (actionPos > segments.Length - 1)
                    {
                        path = path.Replace(segments[modIdPos - 1] + "/" + segments[modIdPos] + "/", "");
                    }
                    else
                    {
                        path = path.Replace(segments[modIdPos - 1] + "/" + segments[modIdPos] + "/" + segments[actionPos] + "/", "");
                    }
                }

                if (urlParametersPos > 0)
                {
                    path = path.Replace(segments[urlParametersPos - 1] + urlparameters + "/", "");
                }

                // remove trailing slash so it can be used as a key for Pages
                if (path.EndsWith("/"))
                {
                    path = path.Substring(0, path.Length - 1);
                }

                if (PageState == null || reload >= Reload.Page)
                {
                    page = pages.Where(item => item.Path == path).FirstOrDefault();
                }
                else
                {
                    page = PageState.Page;
                }

                // failsafe in case router cannot locate the home page for the site
                if (page == null && path == "")
                {
                    page = pages.FirstOrDefault();
                    path = page.Path;
                }

                // check if page has changed
                if (page != null && page.Path != path)
                {
                    page     = pages.Where(item => item.Path == path).FirstOrDefault();
                    reload   = Reload.Page;
                    editmode = false;
                }

                if (page != null)
                {
                    if (PageState == null)
                    {
                        editmode = false;
                    }

                    // check if user is authorized to view page
                    if (UserSecurity.IsAuthorized(user, PermissionNames.View, page.Permissions))
                    {
                        page = await ProcessPage(page, site, user);

                        if (PageState != null && (PageState.ModuleId != moduleid || PageState.Action != action))
                        {
                            reload = Reload.Page;
                        }

                        if (PageState == null || reload >= Reload.Page)
                        {
                            modules = await ModuleService.GetModulesAsync(site.SiteId);

                            (page, modules) = ProcessModules(page, modules, moduleid, action, (!string.IsNullOrEmpty(page.DefaultContainerType)) ? page.DefaultContainerType : site.DefaultContainerType);
                        }
                        else
                        {
                            modules = PageState.Modules;
                        }

                        _pagestate = new PageState
                        {
                            Alias         = alias,
                            Site          = site,
                            Pages         = pages,
                            Page          = page,
                            User          = user,
                            Modules       = modules,
                            Uri           = new Uri(_absoluteUri, UriKind.Absolute),
                            QueryString   = querystring,
                            UrlParameters = urlparameters,
                            ModuleId      = moduleid,
                            Action        = action,
                            EditMode      = editmode,
                            LastSyncDate  = lastsyncdate,
                            Runtime       = runtime
                        };

                        OnStateChange?.Invoke(_pagestate);
                    }
                }
                else
                {
                    if (user == null)
                    {
                        // redirect to login page
                        NavigationManager.NavigateTo(Utilities.NavigateUrl(alias.Path, "login", "returnurl=" + path));
                    }
                    else
                    {
                        await LogService.Log(null, null, user.UserId, GetType().AssemblyQualifiedName, Utilities.GetTypeNameLastSegment(GetType().AssemblyQualifiedName, 1), LogFunction.Security, LogLevel.Error, null, "Page Does Not Exist Or User Is Not Authorized To View Page {Path}", path);

                        if (path != "")
                        {
                            // redirect to home page
                            NavigationManager.NavigateTo(Utilities.NavigateUrl(alias.Path, "", ""));
                        }
                    }
                }
            }
            else
            {
                // site does not exist
            }
        }
Example #33
0
        protected override async Task OnInitializedAsync()
        {
            try
            {
                _themeList = await ThemeService.GetThemesAsync();

                _aliasList = await AliasService.GetAliasesAsync();

                Site site = await SiteService.GetSiteAsync(PageState.Site.SiteId);

                if (site != null)
                {
                    _name       = site.Name;
                    _tenantList = await TenantService.GetTenantsAsync();

                    _tenant = _tenantList.Find(item => item.TenantId == site.TenantId).Name;
                    foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList())
                    {
                        _urls += alias.Name + "\n";
                    }
                    if (site.LogoFileId != null)
                    {
                        _logofileid = site.LogoFileId.Value;
                    }

                    if (site.FaviconFileId != null)
                    {
                        _faviconfileid = site.FaviconFileId.Value;
                    }

                    _themes            = ThemeService.GetThemeControls(_themeList);
                    _themetype         = site.DefaultThemeType;
                    _layouts           = ThemeService.GetLayoutControls(_themeList, _themetype);
                    _layouttype        = site.DefaultLayoutType;
                    _containers        = ThemeService.GetContainerControls(_themeList, _themetype);
                    _containertype     = site.DefaultContainerType;
                    _allowregistration = site.AllowRegistration.ToString();

                    var settings = await SettingService.GetSiteSettingsAsync(site.SiteId);

                    _smtphost     = SettingService.GetSetting(settings, "SMTPHost", string.Empty);
                    _smtpport     = SettingService.GetSetting(settings, "SMTPPort", string.Empty);
                    _smtpssl      = SettingService.GetSetting(settings, "SMTPSSL", string.Empty);
                    _smtpusername = SettingService.GetSetting(settings, "SMTPUsername", string.Empty);
                    _smtppassword = SettingService.GetSetting(settings, "SMTPPassword", string.Empty);

                    _pwaisenabled = site.PwaIsEnabled.ToString();

                    if (site.PwaAppIconFileId != null)
                    {
                        _pwaappiconfileid = site.PwaAppIconFileId.Value;
                    }

                    if (site.PwaSplashIconFileId != null)
                    {
                        _pwasplashiconfileid = site.PwaSplashIconFileId.Value;
                    }

                    _pwaisenabled = site.PwaIsEnabled.ToString();
                    if (site.PwaAppIconFileId != null)
                    {
                        _pwaappiconfileid = site.PwaAppIconFileId.Value;
                    }
                    if (site.PwaSplashIconFileId != null)
                    {
                        _pwasplashiconfileid = site.PwaSplashIconFileId.Value;
                    }

                    _createdby  = site.CreatedBy;
                    _createdon  = site.CreatedOn;
                    _modifiedby = site.ModifiedBy;
                    _modifiedon = site.ModifiedOn;
                    _deletedby  = site.DeletedBy;
                    _deletedon  = site.DeletedOn;
                    _isdeleted  = site.IsDeleted.ToString();

                    _initialized = true;
                }
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Loading Site {SiteId} {Error}", PageState.Site.SiteId, ex.Message);

                AddModuleMessage(ex.Message, MessageType.Error);
            }
        }
Example #34
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);
            }
        }
Example #35
0
        private async Task SaveSite()
        {
            try
            {
                if (_name != string.Empty && _urls != string.Empty && _themetype != "-" && (_layouts.Count == 0 || _layouttype != "-") && _containertype != "-")
                {
                    var unique = true;
                    foreach (string name in _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (_aliasList.Exists(item => item.Name == name && item.SiteId != PageState.Alias.SiteId && item.TenantId != PageState.Alias.TenantId))
                        {
                            unique = false;
                        }
                    }

                    if (unique)
                    {
                        var site = await SiteService.GetSiteAsync(PageState.Site.SiteId);

                        if (site != null)
                        {
                            site.Name       = _name;
                            site.LogoFileId = null;
                            var logofileid = _logofilemanager.GetFileId();
                            if (logofileid != -1)
                            {
                                site.LogoFileId = logofileid;
                            }

                            site.DefaultThemeType     = _themetype;
                            site.DefaultLayoutType    = (_layouttype == "-" ? string.Empty : _layouttype);
                            site.DefaultContainerType = _containertype;
                            site.AllowRegistration    = (_allowregistration == null ? true : Boolean.Parse(_allowregistration));
                            site.IsDeleted            = (_isdeleted == null ? true : Boolean.Parse(_isdeleted));

                            site.PwaIsEnabled = (_pwaisenabled == null ? true : Boolean.Parse(_pwaisenabled));

                            var pwaappiconfileid = _pwaappiconfilemanager.GetFileId();
                            if (pwaappiconfileid != -1)
                            {
                                site.PwaAppIconFileId = pwaappiconfileid;
                            }

                            var pwasplashiconfileid = _pwasplashiconfilemanager.GetFileId();
                            if (pwasplashiconfileid != -1)
                            {
                                site.PwaSplashIconFileId = pwasplashiconfileid;
                            }

                            site = await SiteService.UpdateSiteAsync(site);

                            _urls = _urls.Replace("\n", ",");
                            var names = _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);
                            foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList())
                            {
                                if (!names.Contains(alias.Name))
                                {
                                    await AliasService.DeleteAliasAsync(alias.AliasId);
                                }
                            }

                            foreach (string name in names)
                            {
                                if (!_aliasList.Exists(item => item.Name == name))
                                {
                                    Alias alias = new Alias();
                                    alias.Name     = name;
                                    alias.TenantId = site.TenantId;
                                    alias.SiteId   = site.SiteId;
                                    await AliasService.AddAliasAsync(alias);
                                }
                            }

                            var settings = await SettingService.GetSiteSettingsAsync(site.SiteId);

                            SettingService.SetSetting(settings, "SMTPHost", _smtphost);
                            SettingService.SetSetting(settings, "SMTPPort", _smtpport);
                            SettingService.SetSetting(settings, "SMTPSSL", _smtpssl);
                            SettingService.SetSetting(settings, "SMTPUsername", _smtpusername);
                            SettingService.SetSetting(settings, "SMTPPassword", _smtppassword);
                            await SettingService.UpdateSiteSettingsAsync(settings, site.SiteId);

                            await logger.LogInformation("Site Saved {Site}", site);

                            NavigationManager.NavigateTo(NavigateUrl());
                        }
                    }
                    else
                    {
                        AddModuleMessage("An Alias Specified Has Already Been Used For Another Site", MessageType.Warning);
                    }
                }
                else
                {
                    AddModuleMessage("You Must Provide A Site Name, Alias, And Default Theme/Container", MessageType.Warning);
                }
            }
            catch (Exception ex)
            {
                await logger.LogError(ex, "Error Saving Site {SiteId} {Error}", PageState.Site.SiteId, ex.Message);

                AddModuleMessage("Error Saving Site", MessageType.Error);
            }
        }
Example #36
0
        private async Task SaveSite()
        {
            try
            {
                if (_name != string.Empty && _urls != string.Empty && _themetype != "-" && (_layouts.Count == 0 || _layouttype != "-") && _containertype != "-")
                {
                    var unique = true;
                    foreach (string name in _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries))
                    {
                        if (_aliasList.Exists(item => item.Name == name && item.SiteId != _alias.SiteId && item.TenantId != _alias.TenantId))
                        {
                            unique = false;
                        }
                    }

                    if (unique)
                    {
                        SiteService.SetAlias(_alias);
                        var site = await SiteService.GetSiteAsync(_alias.SiteId);

                        if (site != null)
                        {
                            site.Name                 = _name;
                            site.LogoFileId           = null;
                            site.DefaultThemeType     = _themetype;
                            site.DefaultLayoutType    = _layouttype ?? string.Empty;
                            site.DefaultContainerType = _containertype;
                            site.IsDeleted            = (_isdeleted == null || Boolean.Parse(_isdeleted));

                            site = await SiteService.UpdateSiteAsync(site);

                            _urls = _urls.Replace("\n", ",");
                            var names = _urls.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);

                            foreach (Alias alias in _aliasList.Where(item => item.SiteId == site.SiteId && item.TenantId == site.TenantId).ToList())
                            {
                                if (!names.Contains(alias.Name))
                                {
                                    await AliasService.DeleteAliasAsync(alias.AliasId);
                                }
                            }

                            foreach (string name in names)
                            {
                                if (!_aliasList.Exists(item => item.Name == name))
                                {
                                    Alias alias = new Alias
                                    {
                                        Name     = name,
                                        TenantId = site.TenantId,
                                        SiteId   = site.SiteId
                                    };
                                    await AliasService.AddAliasAsync(alias);
                                }
                            }

                            await Log(_alias, LogLevel.Information, PermissionNames.Edit, null, "Site Saved {Site}", site);

                            NavigationManager.NavigateTo(NavigateUrl());
                        }
                    }
                    else
                    {
                        AddModuleMessage("An Alias Specified Has Already Been Used For Another Site", MessageType.Warning);
                    }
                }
                else
                {
                    AddModuleMessage("You Must Provide A Site Name, Alias, And Default Theme/Container", MessageType.Warning);
                }
            }
            catch (Exception ex)
            {
                await Log(_alias, LogLevel.Error, string.Empty, ex, "Error Saving Site {SiteId} {Error}", _alias.SiteId, ex.Message);

                AddModuleMessage("Error Saving Site", MessageType.Error);
            }
        }
Example #37
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
                }
            }
        }