private Service DoCreateService(IServiceAddress serviceAddress, ServiceType serviceType, IServiceConnector connector) { Service service = null; if (serviceType == ServiceType.Manager) { if (manager == null) { string npath = Path.Combine(basePath, "manager"); if (!Directory.Exists(npath)) Directory.CreateDirectory(npath); manager = new FileSystemManagerService(connector, basePath, npath, serviceAddress); } service = manager; } else if (serviceType == ServiceType.Root) { if (root == null) { string npath = Path.Combine(basePath, "root"); if (!Directory.Exists(npath)) Directory.CreateDirectory(npath); root = new FileSystemRootService(connector, npath); } service = root; } else if (serviceType == ServiceType.Block) { if (block == null) { string npath = Path.Combine(basePath, "block"); if (!Directory.Exists(npath)) Directory.CreateDirectory(npath); block = new FileSystemBlockService(connector, npath); } service = block; } if (service != null) { service.Started += ServiceStarted; service.Stopped += ServiceStopped; } return service; }
public void GetRewardTest() { var reward = BlockService.GetReward(); GetRewardResultTest(reward); }
protected override void OnStop() { if (configTimer != null) { configTimer.Dispose(); configTimer = null; } if (manager != null) { manager.Dispose(); manager = null; } if (root != null) { root.Dispose(); root = null; } if (block != null) { block.Dispose(); block = null; } }
public void GetFeesTest() { var fees = BlockService.GetFees(); GetFeesResultTest(fees); }
public void StopService(ServiceType serviceType) { lock (serverManagerLock) { if (serviceType == ServiceType.Manager && manager != null) { manager.Stop(); manager = null; } else if (serviceType == ServiceType.Root && root != null) { root.Stop(); root = null; } else if (serviceType == ServiceType.Block && block != null) { block.Stop(); block = null; } } }
public void GetByIdErrorTest() { var block = BlockService.GetById("ErrorId"); GetByIdErrorResultTest(block); }
public void GetHeightTest() { var height = BlockService.GetHeight(); GetHeightResultTest(height); }
/// <summary> /// Recursively saves Pages and associated Blocks, PageRoutes and PageContexts. /// </summary> /// <param name="rockContext">The rock context.</param> /// <param name="page">The current Page to save</param> /// <param name="newBlockTypes">List of BlockTypes not currently installed</param> /// <param name="parentPageId">Id of the the current Page's parent</param> /// <param name="siteId">Id of the site the current Page is being imported into</param> private void SavePages(RockContext rockContext, Page page, IEnumerable <BlockType> newBlockTypes, int parentPageId, int siteId) { rockContext = rockContext ?? new RockContext(); // find layout var layoutService = new LayoutService(rockContext); Layout layout = new Layout(); if (page.Layout != null) { layout = layoutService.GetBySiteId(siteId).Where(l => l.Name == page.Layout.Name && l.FileName == page.Layout.FileName).FirstOrDefault(); if (layout == null) { layout = new Layout(); layout.FileName = page.Layout.FileName; layout.Name = page.Layout.Name; layout.SiteId = siteId; layoutService.Add(layout); rockContext.SaveChanges(); } } else { layout = layoutService.GetBySiteId(siteId).Where(l => l.Name.Contains("Full") || l.Name.Contains("Home")).First(); } int layoutId = layout.Id; // Force shallow copies on entities so save operations are more atomic and don't get hosed // by nested object references. var pg = page.Clone(deepCopy: false); var blockTypes = newBlockTypes.ToList(); pg.ParentPageId = parentPageId; pg.LayoutId = layoutId; var pageService = new PageService(rockContext); pageService.Add(pg); rockContext.SaveChanges(); var blockService = new BlockService(rockContext); foreach (var block in page.Blocks ?? new List <Block>()) { var blockType = blockTypes.FirstOrDefault(bt => block.BlockType.Path == bt.Path); var b = block.Clone(deepCopy: false); b.PageId = pg.Id; if (blockType != null) { b.BlockTypeId = blockType.Id; } blockService.Add(b); } rockContext.SaveChanges(); var pageRouteService = new PageRouteService(rockContext); foreach (var pageRoute in page.PageRoutes ?? new List <PageRoute>()) { var pr = pageRoute.Clone(deepCopy: false); pr.PageId = pg.Id; pageRouteService.Add(pr); } rockContext.SaveChanges(); var pageContextService = new PageContextService(rockContext); foreach (var pageContext in page.PageContexts ?? new List <PageContext>()) { var pc = pageContext.Clone(deepCopy: false); pc.PageId = pg.Id; pageContextService.Add(pc); } rockContext.SaveChanges(); foreach (var p in page.Pages ?? new List <Page>()) { SavePages(rockContext, p, blockTypes, pg.Id, siteId); } }
/// <summary> /// Updates the bulk update security. /// </summary> private static void UpdateBulkUpdateSecurity() { var rockContext = new RockContext(); var authService = new Rock.Model.AuthService(rockContext); var bulkUpdateBlockType = BlockTypeCache.Get(Rock.SystemGuid.BlockType.BULK_UPDATE.AsGuid()); var bulkUpdateBlocks = new BlockService(rockContext).Queryable().Where(a => a.BlockTypeId == bulkUpdateBlockType.Id).ToList(); foreach (var bulkUpdateBlock in bulkUpdateBlocks) { var alreadyUpdated = authService.Queryable().Where(a => (a.Action == "EditConnectionStatus" || a.Action == "EditRecordStatus") && a.EntityTypeId == bulkUpdateBlock.TypeId && a.EntityId == bulkUpdateBlock.Id).Any(); if (alreadyUpdated) { // EditConnectionStatus and/or EditRecordStatus has already been set, so don't copy VIEW auth to it continue; } var groupIdAuthRules = new HashSet <int>(); var personIdAuthRules = new HashSet <int>(); var specialRoleAuthRules = new HashSet <SpecialRole>(); var authRulesToAdd = new List <AuthRule>(); Dictionary <ISecured, List <AuthRule> > parentAuthRulesList = new Dictionary <ISecured, List <AuthRule> >(); ISecured secured = bulkUpdateBlock; while (secured != null) { var entityType = secured.TypeId; List <AuthRule> authRules = Authorization.AuthRules(secured.TypeId, secured.Id, Authorization.VIEW).OrderBy(a => a.Order).ToList(); foreach (var rule in authRules) { if (rule.GroupId.HasValue) { if (!groupIdAuthRules.Contains(rule.GroupId.Value)) { groupIdAuthRules.Add(rule.GroupId.Value); authRulesToAdd.Add(rule); } } else if (rule.PersonId.HasValue) { if (!personIdAuthRules.Contains(rule.PersonId.Value)) { personIdAuthRules.Add(rule.PersonId.Value); authRulesToAdd.Add(rule); } } else if (rule.SpecialRole != SpecialRole.None) { if (!specialRoleAuthRules.Contains(rule.SpecialRole)) { specialRoleAuthRules.Add(rule.SpecialRole); authRulesToAdd.Add(rule); } } } secured = secured.ParentAuthority; } List <Auth> authsToAdd = new List <Auth>(); foreach (var auth in authRulesToAdd) { authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditConnectionStatus")); authsToAdd.Add(AddAuth(bulkUpdateBlock, auth, "EditRecordStatus")); } int authOrder = 0; authsToAdd.ForEach(a => a.Order = authOrder++); authService.AddRange(authsToAdd); Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditConnectionStatus"); Authorization.RefreshAction(bulkUpdateBlock.TypeId, bulkUpdateBlock.Id, "EditRecordStatus"); } rockContext.SaveChanges(); }
/// <summary> /// Handles the SaveClick event of the mdContentComponentConfig 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 mdContentComponentConfig_SaveClick(object sender, EventArgs e) { var rockContext = new RockContext(); var dataViewFilter = ReportingHelper.GetFilterFromControls(phFilters); if (dataViewFilter != null) { // update Guids since we are creating a new dataFilter and children and deleting the old one SetNewDataFilterGuids(dataViewFilter); if (!Page.IsValid) { return; } if (!dataViewFilter.IsValid) { // Controls will render the error messages return; } DataViewFilterService dataViewFilterService = new DataViewFilterService(rockContext); int?dataViewFilterId = hfDataFilterId.Value.AsIntegerOrNull(); if (dataViewFilterId.HasValue) { var oldDataViewFilter = dataViewFilterService.Get(dataViewFilterId.Value); DeleteDataViewFilter(oldDataViewFilter, dataViewFilterService); } dataViewFilterService.Add(dataViewFilter); } rockContext.SaveChanges(); ContentChannelService contentChannelService = new ContentChannelService(rockContext); Guid? contentChannelGuid = this.GetAttributeValue("ContentChannel").AsGuidOrNull(); ContentChannel contentChannel = null; if (contentChannelGuid.HasValue) { contentChannel = contentChannelService.Get(contentChannelGuid.Value); } if (contentChannel == null) { contentChannel = new ContentChannel(); contentChannel.ContentChannelTypeId = this.ContentChannelTypeId; contentChannelService.Add(contentChannel); } contentChannel.LoadAttributes(rockContext); avcContentChannelAttributes.GetEditValues(contentChannel); contentChannel.Name = tbComponentName.Text; rockContext.SaveChanges(); contentChannel.SaveAttributeValues(rockContext); this.SetAttributeValue("ContentChannel", contentChannel.Guid.ToString()); this.SetAttributeValue("ItemCacheDuration", nbItemCacheDuration.Text); int? contentComponentTemplateValueId = dvpContentComponentTemplate.SelectedValue.AsInteger(); Guid?contentComponentTemplateValueGuid = null; if (contentComponentTemplateValueId.HasValue) { var contentComponentTemplate = DefinedValueCache.Get(contentComponentTemplateValueId.Value); if (contentComponentTemplate != null) { contentComponentTemplateValueGuid = contentComponentTemplate.Guid; } } this.SetAttributeValue("ContentComponentTemplate", contentComponentTemplateValueGuid.ToString()); this.SetAttributeValue("AllowMultipleContentItems", cbAllowMultipleContentItems.Checked.ToString()); this.SetAttributeValue("OutputCacheDuration", nbOutputCacheDuration.Text); this.SetAttributeValue("CacheTags", cblCacheTags.SelectedValues.AsDelimited(",")); if (dataViewFilter != null) { this.SetAttributeValue("FilterId", dataViewFilter.Id.ToString()); } else { this.SetAttributeValue("FilterId", null); } this.SaveAttributeValues(); var block = new BlockService(rockContext).Get(this.BlockId); block.PreHtml = cePreHtml.Text; block.PostHtml = cePostHtml.Text; rockContext.SaveChanges(); mdContentComponentConfig.Hide(); pnlContentComponentConfig.Visible = false; RemoveCacheItem(OUTPUT_CACHE_KEY); RemoveCacheItem(ITEM_CACHE_KEY); // reload the page to make sure we have a clean load NavigateToCurrentPageReference(); }
/// <summary> /// Raises the <see cref="E:Init" /> event. /// </summary> /// <param name="e">The <see cref="EventArgs" /> instance containing the event data.</param> protected override void OnInit(EventArgs e) { Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage; if (dialogPage != null) { dialogPage.OnSave += new EventHandler <EventArgs>(masterPage_OnSave); } try { int blockId = Convert.ToInt32(PageParameter("BlockId")); Block _block = new BlockService(new RockContext()).Get(blockId); if (_block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) { var blockType = BlockTypeCache.Read(_block.BlockTypeId); if (blockType != null && !blockType.IsInstancePropertiesVerified) { System.Web.UI.Control control = Page.LoadControl(blockType.Path); if (control is RockBlock) { using (var rockContext = new RockContext()) { var rockBlock = control as RockBlock; int?blockEntityTypeId = EntityTypeCache.Read(typeof(Block)).Id; Rock.Attribute.Helper.UpdateAttributes(rockBlock.GetType(), blockEntityTypeId, "BlockTypeId", blockType.Id.ToString(), rockContext); } blockType.IsInstancePropertiesVerified = true; } } phAttributes.Controls.Clear(); phAdvancedAttributes.Controls.Clear(); _block.LoadAttributes(); if (_block.Attributes != null) { foreach (var attributeCategory in Rock.Attribute.Helper.GetAttributeCategories(_block)) { if (attributeCategory.Category != null && attributeCategory.Category.Name.Equals("customsetting", StringComparison.OrdinalIgnoreCase)) { } else if (attributeCategory.Category != null && attributeCategory.Category.Name.Equals("advanced", StringComparison.OrdinalIgnoreCase)) { Rock.Attribute.Helper.AddEditControls( string.Empty, attributeCategory.Attributes.Select(a => a.Key).ToList(), _block, phAdvancedAttributes, string.Empty, !Page.IsPostBack, new List <string>()); } else { Rock.Attribute.Helper.AddEditControls( attributeCategory.Category != null ? attributeCategory.Category.Name : string.Empty, attributeCategory.Attributes.Select(a => a.Key).ToList(), _block, phAttributes, string.Empty, !Page.IsPostBack, new List <string>()); } } } } else { DisplayError("You are not authorized to edit this block", null); } } catch (SystemException ex) { DisplayError(ex.Message, "<pre>" + HttpUtility.HtmlEncode(ex.StackTrace) + "</pre>"); } base.OnInit(e); }
public BlockRpc(BlockService service) { _service = service; }
public BlocksController(BlockService blockService, FriendsService friendsService) { this.blockService = blockService; this.friendsService = friendsService; }
//public BlockController(BlockContext context) public BlockController(BlockService service) { _service = service; }
public void GetStatusTest() { var status = BlockService.GetStatus(); GetStatusResultTest(status); }
public string GetHtmlForBlock(int blockId, int?entityTypeId = null, int?entityId = null) { RockContext rockContext = this.Service.Context as RockContext ?? new RockContext(); Block block = new BlockService(rockContext).Get(blockId); if (block != null) { block.LoadAttributes(); string liquidTemplate = block.GetAttributeValue("LiquidTemplate"); var metricCategoryPairList = Rock.Attribute.MetricCategoriesFieldAttribute.GetValueAsGuidPairs(block.GetAttributeValue("MetricCategories")); var metricGuids = metricCategoryPairList.Select(a => a.MetricGuid).ToList(); bool roundYValues = block.GetAttributeValue("RoundValues").AsBooleanOrNull() ?? true; MetricService metricService = new MetricService(rockContext); var metrics = metricService.GetByGuids(metricGuids); List <object> metricsData = new List <object>(); if (metrics.Count() == 0) { return(@"<div class='alert alert-warning'> Please select a metric in the block settings. </div>" ); } MetricValueService metricValueService = new MetricValueService(rockContext); DateTime firstDayOfYear = new DateTime(RockDateTime.Now.Year, 1, 1); DateTime currentDateTime = RockDateTime.Now; DateTime firstDayOfNextYear = new DateTime(RockDateTime.Now.Year + 1, 1, 1); foreach (var metric in metrics) { var metricYTDData = JsonConvert.DeserializeObject(metric.ToJson(), typeof(MetricYTDData)) as MetricYTDData; var qryMeasureValues = metricValueService.Queryable() .Where(a => a.MetricId == metricYTDData.Id) .Where(a => a.MetricValueDateTime >= firstDayOfYear && a.MetricValueDateTime < currentDateTime) .Where(a => a.MetricValueType == MetricValueType.Measure); //// if an entityTypeId/EntityId filter was specified, and the entityTypeId is the same as the metrics.EntityTypeId, filter the values to the specified entityId //// Note: if a Metric or it's Metric Value doesn't have a context, include it regardless of Context setting if (entityTypeId.HasValue && (metric.EntityTypeId == entityTypeId || metric.EntityTypeId == null)) { if (entityId.HasValue) { qryMeasureValues = qryMeasureValues.Where(a => a.EntityId == entityId || a.EntityId == null); } } var lastMetricValue = qryMeasureValues.OrderByDescending(a => a.MetricValueDateTime).FirstOrDefault(); if (lastMetricValue != null) { metricYTDData.LastValue = lastMetricValue.YValue.HasValue ? Math.Round(lastMetricValue.YValue.Value, roundYValues ? 0 : 2) : (decimal?)null; metricYTDData.LastValueDate = lastMetricValue.MetricValueDateTime.HasValue ? lastMetricValue.MetricValueDateTime.Value.Date : DateTime.MinValue; } decimal?sum = qryMeasureValues.Sum(a => a.YValue); metricYTDData.CumulativeValue = sum.HasValue ? Math.Round(sum.Value, roundYValues ? 0 : 2) : (decimal?)null; // figure out goal as of current date time by figuring out the slope of the goal var qryGoalValuesCurrentYear = metricValueService.Queryable() .Where(a => a.MetricId == metricYTDData.Id) .Where(a => a.MetricValueDateTime >= firstDayOfYear && a.MetricValueDateTime < firstDayOfNextYear) .Where(a => a.MetricValueType == MetricValueType.Goal); // if an entityTypeId/EntityId filter was specified, and the entityTypeId is the same as the metrics.EntityTypeId, filter the values to the specified entityId if (entityTypeId.HasValue && metric.EntityTypeId == entityTypeId) { if (entityId.HasValue) { qryGoalValuesCurrentYear = qryGoalValuesCurrentYear.Where(a => a.EntityId == entityId); } } MetricValue goalLineStartPoint = qryGoalValuesCurrentYear.Where(a => a.MetricValueDateTime <= currentDateTime).OrderByDescending(a => a.MetricValueDateTime).FirstOrDefault(); MetricValue goalLineEndPoint = qryGoalValuesCurrentYear.Where(a => a.MetricValueDateTime >= currentDateTime).FirstOrDefault(); if (goalLineStartPoint != null && goalLineEndPoint != null) { var changeInX = goalLineEndPoint.DateTimeStamp - goalLineStartPoint.DateTimeStamp; var changeInY = goalLineEndPoint.YValue - goalLineStartPoint.YValue; if (changeInX != 0) { decimal?slope = changeInY / changeInX; decimal goalValue = ((slope * (currentDateTime.ToJavascriptMilliseconds() - goalLineStartPoint.DateTimeStamp)) + goalLineStartPoint.YValue).Value; metricYTDData.GoalValue = Math.Round(goalValue, roundYValues ? 0 : 2); } } else { // if there isn't a both a start goal and end goal within the date range, there wouldn't be a goal line shown in a line chart, so don't display a goal in liquid either metricYTDData.GoalValue = null; } metricsData.Add(metricYTDData.ToLiquid()); } Dictionary <string, object> mergeValues = new Dictionary <string, object>(); mergeValues.Add("Metrics", metricsData); string resultHtml = liquidTemplate.ResolveMergeFields(mergeValues); // show liquid help for debug if (block.GetAttributeValue("EnableDebug").AsBoolean()) { resultHtml += mergeValues.lavaDebugInfo(); } return(resultHtml); } return(string.Format( @"<div class='alert alert-danger'> unable to find block_id: {0} </div>", blockId)); }
public void GetAllTest() { var blocks = BlockService.GetAll(); GetAllResultTest(blocks); }
private void SortPanelWidgets(string eventParam, string[] values) { string panelWidgetClientId = values[0]; int newIndex = int.Parse(values[1]); Panel pnlWidget = pnlDetails.ControlsOfTypeRecursive <Panel>().FirstOrDefault(a => a.ClientID == panelWidgetClientId); HiddenField hfSiteBlockId = pnlWidget.FindControl("hfSiteBlockId") as HiddenField; HiddenField hfLayoutBlockId = pnlWidget.FindControl("hfLayoutBlockId") as HiddenField; HiddenField hfPageBlockId = pnlWidget.FindControl("hfPageBlockId") as HiddenField; int?blockId = null; if (hfSiteBlockId != null) { blockId = hfSiteBlockId.Value.AsIntegerOrNull(); } else if (hfLayoutBlockId != null) { blockId = hfLayoutBlockId.Value.AsIntegerOrNull(); } else if (hfPageBlockId != null) { blockId = hfPageBlockId.Value.AsIntegerOrNull(); } if (blockId.HasValue) { var rockContext = new RockContext(); var blockService = new BlockService(rockContext); var block = blockService.Get(blockId.Value); var page = PageCache.Get(hfPageId.Value.AsInteger()); if (block != null && page != null) { List <Block> zoneBlocks = null; switch (block.BlockLocation) { case BlockLocation.Page: zoneBlocks = blockService.GetByPageAndZone(block.PageId.Value, block.Zone).ToList(); break; case BlockLocation.Layout: zoneBlocks = blockService.GetByLayoutAndZone(block.LayoutId.Value, block.Zone).ToList(); break; case BlockLocation.Site: zoneBlocks = blockService.GetBySiteAndZone(block.SiteId.Value, block.Zone).ToList(); break; } if (zoneBlocks != null) { var oldIndex = zoneBlocks.IndexOf(block); blockService.Reorder(zoneBlocks, oldIndex, newIndex); rockContext.SaveChanges(); } page.RemoveBlocks(); if (block.LayoutId.HasValue) { PageCache.RemoveLayoutBlocks(block.LayoutId.Value); } if (block.SiteId.HasValue) { PageCache.RemoveSiteBlocks(block.SiteId.Value); } ShowDetailForZone(ddlZones.SelectedValue); } } }
public void GetEpochTest() { var epoch = BlockService.GetEpoch(); GetEpochResultTest(epoch); }
public async Task <IActionResult> Get(string transactionHash) { using (var transactionService = new TransactionService(_nodeUrls)) using (var blockService = new BlockService(_nodeUrls)) { var transactionBuilder = Builders <Caladan.Models.Transaction> .Filter; var transactionFilter = transactionBuilder.Where(x => x.TransactionHash == transactionHash.ToLower()); var transactions = await _transactionRepository.FindAsync(transactionFilter, null); var transaction = transactions.FirstOrDefault(); if (transaction == null) { transaction = await transactionService.GetTransactionAsync(transactionHash); if (transaction == null) { return(Ok(new ViewModels.Transaction() { Found = false })); } } await GetTransactionReceipt(transactionHash, transactionService, _transactionRepository, _transactionReceiptRepository, transaction); ulong confirmations = 0; if (transaction.BlockNumber != 0) { var orderByBlock = Builders <Caladan.Models.Block> .Sort.Descending("block_number"); var lastBlock = await _blockRepository.GetAsync(null, orderByBlock); if (lastBlock == null || lastBlock.BlockNumber < transaction.BlockNumber) { confirmations = await blockService.GetBlockNumberFromNodeAsync() - transaction.BlockNumber + 1; } else { confirmations = lastBlock.BlockNumber - transaction.BlockNumber + 1; } } double fee = 0; if (transaction.Receipt != null) { fee = NodeServices.Helpers.ConversionHelper.ConvertWei(transaction.Receipt.GasUsed * transaction.GasPrice, 18); } var result = new ViewModels.Transaction() { BlockNumber = transaction.BlockNumber, From = transaction.From, Gas = transaction.Gas, GasPrice = (ulong)NodeServices.Helpers.ConversionHelper.ConvertWei(transaction.GasPrice, 9), GasUsed = transaction.Receipt?.GasUsed ?? 0, Fee = fee, To = transaction.To, TransactionHash = transaction.TransactionHash, Value = transaction.Value.FromHexWei(transaction.Decimals), Symbol = transaction.Symbol, BlockHash = transaction.BlockHash, ConfirmedOnFormatted = transaction.Created.ToString(), Input = transaction.Input, Nonce = transaction.Nonce, Timestamp = transaction.Timestamp, TransactionIndex = transaction.TransactionIndex, PriceBtc = transaction.PriceBtc, PriceEur = transaction.PriceEur, PriceUsd = transaction.PriceUsd, Confirmations = confirmations, Receipt = transaction.Receipt == null ? null : new ViewModels.TransactionReceipt() { BlockHash = transaction.Receipt.BlockHash, BlockNumber = transaction.Receipt.BlockNumber, ContractAddress = transaction.Receipt.ContractAddress, CumulativeGasUsed = transaction.Receipt.CumulativeGasUsed, GasUsed = transaction.Receipt.GasUsed, Logs = transaction.Receipt.Logs, TransactionHash = transaction.Receipt.TransactionHash, TransactionIndex = transaction.Receipt.TransactionIndex, From = transaction.Receipt.From, LogsBloom = transaction.Receipt.LogsBloom, Root = transaction.Receipt.Root, To = transaction.Receipt.To }, Found = true }; result.Raw = SerializeTransaction(result); if (transaction.Receipt != null) { result.ReceiptRaw = SerializeTransactionReceipt(transaction.Receipt); } return(Ok(result)); } }
public void GetNetHashTest() { var netHash = BlockService.GetNetHash(); GetNetHashResultTest(netHash); }
public OntologyUploadApp(BlockService blockService) { _blockService = blockService; }
public void StartService(ServiceType serviceType) { // Start the services, lock (serverManagerLock) { IService service = serviceFactory.CreateService(address, serviceType, connector); if (service == null) throw new ApplicationException("Unable to create service of tyoe " + serviceType); service.Start(); if (serviceType == ServiceType.Manager) manager = (ManagerService)service; else if (serviceType == ServiceType.Root) root = (RootService)service; else if (serviceType == ServiceType.Block) block = (BlockService) service; } }
/// <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) { bool newBlock = false; Rock.Model.Block block = null; using (var rockContext = new RockContext()) { BlockService blockService = new BlockService(rockContext); int blockId = hfBlockId.ValueAsInt(); if (blockId != 0) { block = blockService.Get(blockId); } if (block == null) { newBlock = true; block = new Rock.Model.Block(); blockService.Add(block); BlockLocation location = hfBlockLocation.Value.ConvertToEnum <BlockLocation>(); switch (location) { case BlockLocation.Site: block.LayoutId = null; block.PageId = null; block.SiteId = _Page.SiteId; break; case BlockLocation.Layout: block.LayoutId = _Page.LayoutId; block.PageId = null; block.SiteId = null; break; case BlockLocation.Page: block.LayoutId = null; block.PageId = _Page.Id; block.SiteId = null; break; } block.Zone = _ZoneName; Rock.Model.Block lastBlock = blockService.GetByPageAndZone(_Page.Id, _ZoneName).OrderByDescending(b => b.Order).FirstOrDefault(); var maxOrder = blockService.GetMaxOrder(block); if (lastBlock != null) { block.Order = lastBlock.Order + 1; } else { block.Order = 0; } } block.Name = tbBlockName.Text; block.BlockTypeId = Convert.ToInt32(ddlBlockType.SelectedValue); rockContext.SaveChanges(); if (newBlock) { Rock.Security.Authorization.CopyAuthorization(_Page, block, rockContext); } if (block.Layout != null) { PageCache.FlushPagesForLayout(_Page.LayoutId); } else { //_Page.RemoveBlocks(); PageCache.Remove(_Page.Id); } } PageUpdated = true; BindGrids(); pnlDetails.Visible = false; pnlLists.Visible = true; }
protected override void Dispose(bool disposing) { if (disposing) { if (manager != null) { manager.Dispose(); manager = null; } if (root != null) { root.Dispose(); root = null; } if (block != null) { block.Dispose(); block = null; } } base.Dispose(disposing); }
/// <summary> /// Builds the mobile package that can be archived for deployment. /// </summary> /// <param name="applicationId">The application identifier.</param> /// <param name="deviceType">The type of device to build for.</param> /// <param name="versionId">The version identifier to use on this package.</param> /// <returns>An update package for the specified application and device type.</returns> public static UpdatePackage BuildMobilePackage(int applicationId, DeviceType deviceType, int versionId) { var site = SiteCache.Get(applicationId); string applicationRoot = GlobalAttributesCache.Value("PublicApplicationRoot"); var additionalSettings = site.AdditionalSettings.FromJsonOrNull <AdditionalSiteSettings>(); if (additionalSettings.IsNull()) { throw new Exception("Invalid or non-existing AdditionalSettings property on site."); } // // Get all the system phone formats. // var phoneFormats = DefinedTypeCache.Get(SystemGuid.DefinedType.COMMUNICATION_PHONE_COUNTRY_CODE) .DefinedValues .Select(dv => new MobilePhoneFormat { CountryCode = dv.Value, MatchExpression = dv.GetAttributeValue("MatchRegEx"), FormatExpression = dv.GetAttributeValue("FormatRegEx") }) .ToList(); // // Get all the defined values. // var definedTypeGuids = new[] { SystemGuid.DefinedType.LOCATION_COUNTRIES, SystemGuid.DefinedType.LOCATION_ADDRESS_STATE, SystemGuid.DefinedType.PERSON_MARITAL_STATUS }; var definedValues = new List <MobileDefinedValue>(); foreach (var definedTypeGuid in definedTypeGuids) { var definedType = DefinedTypeCache.Get(definedTypeGuid); definedValues.AddRange(definedType.DefinedValues .Select(a => new MobileDefinedValue { Guid = a.Guid, DefinedTypeGuid = a.DefinedType.Guid, Value = a.Value, Description = a.Description, Attributes = GetMobileAttributeValues(a, a.Attributes.Select(b => b.Value)) })); } // // Build CSS Styles // var settings = additionalSettings.DownhillSettings; settings.Platform = DownhillPlatform.Mobile; // ensure the settings are set to mobile var cssStyles = CssUtilities.BuildFramework(settings); // append custom css but parse it for downhill variables if (additionalSettings.CssStyle.IsNotNullOrWhiteSpace()) { cssStyles += CssUtilities.ParseCss(additionalSettings.CssStyle, settings); } // Run Lava on CSS to enable color utilities cssStyles = cssStyles.ResolveMergeFields(Lava.LavaHelper.GetCommonMergeFields(null, null, new Lava.CommonMergeFieldsOptions { GetLegacyGlobalMergeFields = false })); // Get the Rock organization time zone. If not found back to the // OS time zone. If not found just use Greenwich. var timeZoneMapping = NodaTime.TimeZones.TzdbDateTimeZoneSource.Default.WindowsMapping.PrimaryMapping; var timeZoneName = timeZoneMapping.GetValueOrNull(RockDateTime.OrgTimeZoneInfo.Id) ?? timeZoneMapping.GetValueOrNull(TimeZoneInfo.Local.Id) ?? "GMT"; // // Initialize the base update package settings. // var package = new UpdatePackage { ApplicationType = additionalSettings.ShellType ?? ShellType.Blank, ApplicationVersionId = versionId, CssStyles = cssStyles, LoginPageGuid = site.LoginPageId.HasValue ? PageCache.Get(site.LoginPageId.Value)?.Guid : null, ProfileDetailsPageGuid = additionalSettings.ProfilePageId.HasValue ? PageCache.Get(additionalSettings.ProfilePageId.Value)?.Guid : null, PhoneFormats = phoneFormats, DefinedValues = definedValues, TabsOnBottomOnAndroid = additionalSettings.TabLocation == TabLocation.Bottom, HomepageRoutingLogic = additionalSettings.HomepageRoutingLogic, DoNotEnableNotificationsAtLaunch = !additionalSettings.EnableNotificationsAutomatically, TimeZone = timeZoneName, PushTokenUpdateValue = additionalSettings.PushTokenUpdateValue }; // // Setup the appearance settings. // package.AppearanceSettings.BarBackgroundColor = additionalSettings.BarBackgroundColor; package.AppearanceSettings.MenuButtonColor = additionalSettings.MenuButtonColor; package.AppearanceSettings.ActivityIndicatorColor = additionalSettings.ActivityIndicatorColor; package.AppearanceSettings.FlyoutXaml = additionalSettings.FlyoutXaml; package.AppearanceSettings.NavigationBarActionsXaml = additionalSettings.NavigationBarActionXaml; package.AppearanceSettings.LockedPhoneOrientation = additionalSettings.LockedPhoneOrientation; package.AppearanceSettings.LockedTabletOrientation = additionalSettings.LockedTabletOrientation; package.AppearanceSettings.PaletteColors.Add("text-color", additionalSettings.DownhillSettings.TextColor); package.AppearanceSettings.PaletteColors.Add("heading-color", additionalSettings.DownhillSettings.HeadingColor); package.AppearanceSettings.PaletteColors.Add("background-color", additionalSettings.DownhillSettings.BackgroundColor); package.AppearanceSettings.PaletteColors.Add("app-primary", additionalSettings.DownhillSettings.ApplicationColors.Primary); package.AppearanceSettings.PaletteColors.Add("app-secondary", additionalSettings.DownhillSettings.ApplicationColors.Secondary); package.AppearanceSettings.PaletteColors.Add("app-success", additionalSettings.DownhillSettings.ApplicationColors.Success); package.AppearanceSettings.PaletteColors.Add("app-info", additionalSettings.DownhillSettings.ApplicationColors.Info); package.AppearanceSettings.PaletteColors.Add("app-danger", additionalSettings.DownhillSettings.ApplicationColors.Danger); package.AppearanceSettings.PaletteColors.Add("app-warning", additionalSettings.DownhillSettings.ApplicationColors.Warning); package.AppearanceSettings.PaletteColors.Add("app-light", additionalSettings.DownhillSettings.ApplicationColors.Light); package.AppearanceSettings.PaletteColors.Add("app-dark", additionalSettings.DownhillSettings.ApplicationColors.Dark); package.AppearanceSettings.PaletteColors.Add("app-brand", additionalSettings.DownhillSettings.ApplicationColors.Brand); if (site.FavIconBinaryFileId.HasValue) { package.AppearanceSettings.LogoUrl = $"{applicationRoot}/GetImage.ashx?Id={site.FavIconBinaryFileId.Value}"; } // // Load all the layouts. // foreach (var layout in LayoutCache.All().Where(l => l.SiteId == site.Id)) { var mobileLayout = new MobileLayout { LayoutGuid = layout.Guid, Name = layout.Name, LayoutXaml = deviceType == DeviceType.Tablet ? layout.LayoutMobileTablet : layout.LayoutMobilePhone }; package.Layouts.Add(mobileLayout); } // // Load all the pages. // var blockIds = new List <int>(); using (var rockContext = new RockContext()) { AddPagesToUpdatePackage(package, applicationRoot, rockContext, new[] { PageCache.Get(site.DefaultPageId.Value) }); blockIds = new BlockService(rockContext).Queryable() .Where(b => b.Page != null && b.Page.Layout.SiteId == site.Id && b.BlockType.EntityTypeId.HasValue) .OrderBy(b => b.Order) .Select(b => b.Id) .ToList(); } // // Load all the blocks. // foreach (var blockId in blockIds) { var block = BlockCache.Get(blockId); var blockEntityType = block?.BlockType.EntityType.GetEntityType(); if (blockEntityType != null && typeof(Rock.Blocks.IRockMobileBlockType).IsAssignableFrom(blockEntityType)) { var additionalBlockSettings = block.AdditionalSettings.FromJsonOrNull <AdditionalBlockSettings>() ?? new AdditionalBlockSettings(); var mobileBlockEntity = (Rock.Blocks.IRockMobileBlockType)Activator.CreateInstance(blockEntityType); mobileBlockEntity.BlockCache = block; mobileBlockEntity.PageCache = block.Page; mobileBlockEntity.RequestContext = new Net.RockRequestContext(); var attributes = block.Attributes .Select(a => a.Value) .Where(a => a.Categories.Any(c => c.Name == "custommobile")); var mobileBlock = new MobileBlock { PageGuid = block.Page.Guid, Zone = block.Zone, BlockGuid = block.Guid, RequiredAbiVersion = mobileBlockEntity.RequiredMobileAbiVersion, BlockType = mobileBlockEntity.MobileBlockType, ConfigurationValues = mobileBlockEntity.GetBlockInitialization(Blocks.RockClientType.Mobile), Order = block.Order, AttributeValues = GetMobileAttributeValues(block, attributes), PreXaml = block.PreHtml, PostXaml = block.PostHtml, CssClasses = block.CssClass, CssStyles = additionalBlockSettings.CssStyles, ShowOnTablet = additionalBlockSettings.ShowOnTablet, ShowOnPhone = additionalBlockSettings.ShowOnPhone, RequiresNetwork = additionalBlockSettings.RequiresNetwork, NoNetworkContent = additionalBlockSettings.NoNetworkContent, AuthorizationRules = string.Join(",", GetOrderedExplicitAuthorizationRules(block)) }; package.Blocks.Add(mobileBlock); } } // // Load all the campuses. // foreach (var campus in CampusCache.All().Where(c => c.IsActive ?? true)) { var mobileCampus = new MobileCampus { Guid = campus.Guid, Name = campus.Name }; if (campus.Location != null) { if (campus.Location.Latitude.HasValue && campus.Location.Longitude.HasValue) { mobileCampus.Latitude = campus.Location.Latitude; mobileCampus.Longitude = campus.Location.Longitude; } if (!string.IsNullOrWhiteSpace(campus.Location.Street1)) { mobileCampus.Street1 = campus.Location.Street1; mobileCampus.City = campus.Location.City; mobileCampus.State = campus.Location.State; mobileCampus.PostalCode = campus.Location.PostalCode; } } // Get the campus time zone, If not found try the Rock // organization time zone. If not found back to the // OS time zone. If not found just use Greenwich. mobileCampus.TimeZone = timeZoneMapping.GetValueOrNull(campus.TimeZoneId ?? string.Empty) ?? timeZoneMapping.GetValueOrNull(RockDateTime.OrgTimeZoneInfo.Id) ?? timeZoneMapping.GetValueOrNull(TimeZoneInfo.Local.Id) ?? "GMT"; package.Campuses.Add(mobileCampus); } return(package); }
protected override void OnBlockLoaded(BlockService.BlockContainer container) { // Add the new container to the control list (used by the compression // thread). lock (compressionAddList) { compressionAddList.Add(container); } }
/// <summary> /// Processes the drag events. /// </summary> private void ProcessDragEvents() { string argument = Request["__EVENTARGUMENT"].ToStringSafe(); var segments = argument.Split(new[] { '|' }); // // Check for the event to add a new block. // if (segments.Length == 4 && segments[0] == "add-block") { var blockType = ComponentItemState.Where(c => c.Id == segments[1].AsInteger()).Single(); var zoneName = segments[2]; var order = segments[3].AsInteger(); int pageId = hfPageId.Value.AsInteger(); using (var rockContext = new RockContext()) { var blockService = new BlockService(rockContext); // // Generate the new block. // var block = new Block { PageId = pageId, BlockTypeId = blockType.Id, Name = blockType.Name, Zone = zoneName, Order = order }; blockService.Add(block); // // Get the current list of blocks in the zone. // var blocks = blockService.Queryable() .Where(b => b.PageId == pageId && b.Zone == zoneName) .OrderBy(a => a.Order) .ThenBy(a => a.Id) .ToList(); // // Insert the new block and then fixup all the Order values. // blocks.Insert(order, block); int index = 0; blocks.ForEach(b => b.Order = index++); rockContext.SaveChanges(); } BindZones(); } // // Check for the event to drag-reorder block. // else if (segments.Length == 4 && segments[0] == "reorder-block") { int pageId = hfPageId.Value.AsInteger(); var zoneName = segments[1]; int blockId = segments[2].AsInteger(); int newIndex = segments[3].AsInteger(); using (var rockContext = new RockContext()) { var blockService = new BlockService(rockContext); var block = blockService.Get(blockId); // // Get all blocks for this page and the destination zone except the current block. // var blocks = blockService.Queryable() .Where(b => b.PageId == pageId && b.Zone == zoneName) .Where(b => b.Id != block.Id) .OrderBy(a => a.Order) .ThenBy(a => a.Id) .ToList(); // // Insert the block in the right position and update the zone name. // blocks.Insert(newIndex, block); block.Zone = zoneName; // // Fixup the Order values of all the blocks. // int index = 0; blocks.ForEach(b => b.Order = index++); rockContext.SaveChanges(); } BindZones(); } }