public CacheContext(IStorageContext storageContext) { this._storageContext = storageContext; this._blockStorage = new BlockStorage(this); this._blockCache = new BlockCache ( cacheContext: this, maxFlushMemorySize: 10.MILLION(), maxCacheMemorySize: 1.MILLION() ); this._blockHeaderCache = new BlockHeaderCache ( cacheContext: this, maxFlushMemorySize: 10.MILLION(), maxCacheMemorySize: 1.MILLION() ); this._chainedBlockCache = new ChainedBlockCache ( cacheContext: this, maxFlushMemorySize: 1.MILLION(), maxCacheMemorySize: 100.MILLION() ); this._transactionCache = new TransactionCache ( cacheContext: this, maxCacheMemorySize: 1.MILLION() ); }
/// <summary> /// Creates the block config icon. /// </summary> /// <param name="block">The block.</param> /// <returns></returns> protected string CreateConfigIcon(BlockCache block) { var blockPropertyUrl = ResolveUrl(string.Format("~/BlockProperties/{0}?t=Block Properties", block.Id)); return(string.Format( "<i class=\"fa fa-th-large\"> </i> <a class='btn-minimal' href=\"javascript: Rock.controls.modal.show($(this), '{0}')\" title=\"Block Properties\"><i class=\"fa fa-cog\"></i> </a>", blockPropertyUrl)); }
/// <summary> /// Binds the custom actions configuration. /// </summary> private void BindCustomActionsConfig() { var blockId = Convert.ToInt32(PageParameter("BlockId")); var _block = BlockCache.Get(blockId); rptCustomActions.DataSource = CustomActionsConfigState; rptCustomActions.DataBind(); }
/// <summary> /// Binds the custom columns configuration. /// </summary> private void BindCustomColumnsConfig() { int blockId = Convert.ToInt32(PageParameter("BlockId")); BlockCache _block = BlockCache.Get(blockId); rptCustomGridColumns.DataSource = CustomGridColumnsConfigState.ColumnsConfig; rptCustomGridColumns.DataBind(); }
/// <summary> /// Creates the block config icon. /// </summary> /// <param name="block">The block.</param> /// <returns></returns> protected string CreateConfigIcon( BlockCache block ) { var blockPropertyUrl = ResolveUrl( string.Format( "~/BlockProperties/{0}?t=Block Properties", block.Id ) ); return string.Format( "<a class='rollover-item' href=\"javascript: Rock.controls.modal.show($(this), '{0}')\" title=\"Block Properties\"><i class=\"fa fa-cog\"></i> </a>", blockPropertyUrl ); }
public Program() { _out = new DebugLCD(GridTerminalSystem); _debug = new Debug(_out); _blockCache = new BlockCache(GridTerminalSystem, _out); _tower = new SolarPanelTower(_out, _blockCache); Runtime.UpdateFrequency = UpdateFrequency.Update100; }
/// <summary> /// Get the list of available blocks that the user can enable on the dashboard. /// </summary> /// <returns>An enumerable list of block types available.</returns> private List <DashboardBlockType> GetAvailableBlocks() { List <DashboardBlockType> blockTypes; // // Get the current configuration settings for the list of available blocks. // try { blockTypes = JsonConvert.DeserializeObject <List <DashboardBlockType> >(GetAttributeValue("AvailableBlocks")); if (blockTypes == null) { blockTypes = new List <DashboardBlockType>(); } } catch { blockTypes = new List <DashboardBlockType>(); } // // Get all the blocks the user can see. // var blocks = GetAllBlocks() .Where(b => b.IsAuthorized(Authorization.VIEW, CurrentPerson) || b.IsAuthorized(Authorization.EDIT, CurrentPerson) || b.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) .ToList(); // // Filter the block types to those the user has permissions to view. // blockTypes = blockTypes.Where(bt => blocks.Any(b => b.Id == bt.BlockId)).ToList(); // // Walk each block and either initialize the block type or load it from cache. // foreach (var block in blocks) { var blockType = blockTypes.Where(b => b.BlockId == block.Id).FirstOrDefault(); if (blockType == null) { blockType = new DashboardBlockType(); blockType.BlockCache = block; blockType.BlockId = block.Id; blockTypes.Add(blockType); } else { blockType.BlockCache = BlockCache.Read(blockType.BlockId); } } return(blockTypes); }
/// <summary> /// Saves the prayer request. /// </summary> /// <param name="answer">The answer text.</param> /// <returns> /// The response to send back to the client. /// </returns> private CallbackResponse SaveRequest(string answer) { using (var rockContext = new RockContext()) { var prayerRequestService = new PrayerRequestService(rockContext); PrayerRequest prayerRequest = null; var requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull(); if (requestGuid.HasValue) { prayerRequest = new PrayerRequestService(rockContext).Get(requestGuid.Value); } if (prayerRequest == null) { return(new CallbackResponse { Error = "We couldn't find that prayer request." }); } var canEdit = prayerRequest.RequestedByPersonAlias != null && prayerRequest.RequestedByPersonAlias.PersonId == RequestContext.CurrentPerson?.Id; if (!BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !canEdit) { return(new CallbackResponse { Error = "You are not authorized to edit prayer requests." }); } prayerRequest.Answer = answer; // // Save all changes to database. // rockContext.SaveChanges(); } if (ReturnPageGuid.HasValue) { return(new CallbackResponse { Command = "ReplacePage", CommandParameter = ReturnPageGuid.Value.ToString() }); } else { return(new CallbackResponse { Command = "PopPage", CommandParameter = "true" }); } }
/// <summary> /// Raises the <see cref="E:System.Web.UI.Control.Init" /> event. /// </summary> /// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param> protected override void OnInit(EventArgs e) { base.OnInit(e); string name = BlockCache.Get(BlockId).BlockType.Path.Replace("~", "").Replace(".ascx", ""); Id = "bid_" + BlockId; Path = name; Component = name.Replace("/", ".").Remove(0, 1); }
/// <summary> /// Builds the content to be displayed on the block. /// </summary> /// <returns>A string containing the XAML content to be displayed.</returns> private string BuildContent() { using (var rockContext = new RockContext()) { Guid? requestGuid = RequestContext.GetPageParameter(PageParameterKeys.RequestGuid).AsGuidOrNull(); PrayerRequest request = null; if (requestGuid.HasValue) { request = new PrayerRequestService(rockContext).Get(requestGuid.Value); } if (request == null) { return("<Rock:NotificationBox HeaderText=\"Not Found\" Text=\"We couldn't find that prayer request.\" NotificationType=\"Error\" />"); } var canEdit = request.RequestedByPersonAlias != null && request.RequestedByPersonAlias.PersonId == RequestContext.CurrentPerson?.Id; if (!BlockCache.IsAuthorized(Authorization.EDIT, RequestContext.CurrentPerson) && !canEdit) { return("<Rock:NotificationBox HeaderText=\"Error\" Text=\"You are not authorized to edit prayer requests.\" NotificationType=\"Error\" />"); } var mergeFields = RequestContext.GetCommonMergeFields(); mergeFields.AddOrReplace("PrayerRequest", request); var prayerRequestXaml = Template.ResolveMergeFields(mergeFields, RequestContext.CurrentPerson); return($@" <StackLayout StyleClass=""prayerdetail""> {prayerRequestXaml} <Rock:FieldContainer> <Rock:TextEditor x:Name=""tbAnswer"" IsRequired=""True"" MinimumHeightRequest=""80"" AutoSize=""TextChanges"" Placeholder=""My answer to prayer is..."" Text=""{request.Answer.ToStringSafe().EncodeXml( true )}"" /> </Rock:FieldContainer> <Rock:Validator x:Name=""vForm""> <x:Reference>tbAnswer</x:Reference> </Rock:Validator> <Rock:NotificationBox x:Name=""nbError"" NotificationType=""Warning"" /> <Button StyleClass=""btn,btn-primary,save-button"" Text=""Save"" Command=""{{Binding Callback}}""> <Button.CommandParameter> <Rock:CallbackParameters Name="":SaveAnswer"" Validator=""{{x:Reference vForm}}"" Notification=""{{x:Reference nbError}}""> <Rock:Parameter Name=""answer"" Value=""{{Binding Text, Source={{x:Reference tbAnswer}}}}"" /> </Rock:CallbackParameters> </Button.CommandParameter> </Button> <Button StyleClass=""btn,btn-link,cancel-button"" Text=""Cancel"" Command=""{{Binding PopPage}}"" /> </StackLayout>"); } }
/// <summary> /// Gets the Guid for the Block that has the specified Id /// </summary> /// <param name="id">The identifier.</param> /// <returns></returns> public override Guid?GetGuid(int id) { var cacheItem = BlockCache.Get(id); if (cacheItem != null) { return(cacheItem.Guid); } return(null); }
public HttpResponseMessage Family(string param) { try { var Session = HttpContext.Current.Session; CurrentKioskId = ( int )Session["CheckInKioskId"]; Guid blockGuid = ( Guid )Session["BlockGuid"]; List <int> CheckInGroupTypeIds = (List <int>)Session["CheckInGroupTypeIds"]; CurrentCheckInState = new CheckInState(CurrentKioskId, null, CheckInGroupTypeIds); CurrentCheckInState.CheckIn.UserEnteredSearch = true; CurrentCheckInState.CheckIn.ConfirmSingleFamily = true; CurrentCheckInState.CheckIn.SearchType = DefinedValueCache.Read(Rock.SystemGuid.DefinedValue.CHECKIN_SEARCH_TYPE_PHONE_NUMBER); CurrentCheckInState.CheckIn.SearchValue = param; var rockContext = new Rock.Data.RockContext(); var block = BlockCache.Read(blockGuid, rockContext); string workflowActivity = block.GetAttributeValue("WorkflowActivity"); Guid? workflowGuid = block.GetAttributeValue("WorkflowType").AsGuidOrNull(); List <string> errors; var workflowTypeService = new WorkflowTypeService(rockContext); var workflowService = new WorkflowService(rockContext); var workflowType = workflowTypeService.Queryable("ActivityTypes") .Where(w => w.Guid.Equals(workflowGuid.Value)) .FirstOrDefault(); var CurrentWorkflow = Rock.Model.Workflow.Activate(workflowType, CurrentCheckInState.Kiosk.Device.Name, rockContext); var activityType = workflowType.ActivityTypes.Where(a => a.Name == workflowActivity).FirstOrDefault(); if (activityType != null) { WorkflowActivity.Activate(activityType, CurrentWorkflow, rockContext); if (workflowService.Process(CurrentWorkflow, CurrentCheckInState, out errors)) { // Keep workflow active for continued processing CurrentWorkflow.CompletedDateTime = null; SaveState(Session); List <CheckInFamily> families = CurrentCheckInState.CheckIn.Families; families = families.OrderBy(f => f.Caption).ToList(); return(ControllerContext.Request.CreateResponse(HttpStatusCode.OK, families)); } } else { return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, string.Format("Workflow type does not have a '{0}' activity type", workflowActivity))); } return(ControllerContext.Request.CreateResponse(HttpStatusCode.InternalServerError, String.Join("\n", errors))); } catch (Exception ex) { ExceptionLogService.LogException(ex, HttpContext.Current); return(ControllerContext.Request.CreateResponse(HttpStatusCode.Forbidden, "Forbidden")); } }
/// <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) { int blockId = Convert.ToInt32(PageParameter("BlockId")); BlockCache _block = BlockCache.Get(blockId); var blockControlType = System.Web.Compilation.BuildManager.GetCompiledType(_block.BlockType.Path); this.ShowCustomGridColumns = typeof(Rock.Web.UI.ICustomGridColumns).IsAssignableFrom(blockControlType); this.ShowCustomGridOptions = typeof(Rock.Web.UI.ICustomGridOptions).IsAssignableFrom(blockControlType); if (!Page.IsPostBack && _block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) { if (_block.Attributes != null) { avcAdvancedAttributes.IncludedCategoryNames = new string[] { "advanced" }; avcAdvancedAttributes.AddEditControls(_block); avcAttributes.ExcludedCategoryNames = new string[] { "advanced", "customsetting" }; avcAttributes.AddEditControls(_block); } rptProperties.DataSource = GetTabs(_block.BlockType); rptProperties.DataBind(); tbBlockName.Text = _block.Name; tbCssClass.Text = _block.CssClass; cePreHtml.Text = _block.PreHtml; cePostHtml.Text = _block.PostHtml; // Hide the Cache duration block for now; tbCacheDuration.Visible = false; //tbCacheDuration.Text = _block.OutputCacheDuration.ToString(); rcwCustomGridColumns.Visible = this.ShowCustomGridColumns; tglEnableStickyHeader.Visible = this.ShowCustomGridOptions; if (this.ShowCustomGridColumns) { CustomGridColumnsConfigState = _block.GetAttributeValue(CustomGridColumnsConfig.AttributeKey).FromJsonOrNull <CustomGridColumnsConfig>() ?? new CustomGridColumnsConfig(); BindCustomColumnsConfig(); } else { CustomGridColumnsConfigState = null; } if (this.ShowCustomGridOptions) { tglEnableStickyHeader.Checked = _block.GetAttributeValue(CustomGridOptionsConfig.EnableStickyHeadersAttributeKey).AsBoolean(); } } base.OnLoad(e); }
public static void WriteBlock(this FileStream fileStream, Block block) { if (fileStream.Length < block.ThisPos) { fileStream.SetLength(block.ThisPos); } fileStream.Seek(block.ThisPos, SeekOrigin.Begin); Consts.formatter.Serialize(fileStream, block); BlockCache.TryRemoveFloatingBlock(block); // 如果是new Block(),需要在此时从floating列表移除 BlockCache.AddSunkBlock(block); // 如果是new Block(),需要在此时加入sunk字典 }
/// <summary> /// Flushes the block type attributes. /// </summary> private void FlushBlockTypeAttributes() { // Flush BlockType, Block and Entity Attributes AttributeCache.FlushEntityAttributes(); BlockTypeCache.Flush(hfBlockTypeId.Value.AsInteger()); var blockTypeCache = BlockTypeCache.Read(hfBlockTypeId.Value.AsInteger()); foreach (var blockId in new BlockService(new RockContext()).GetByBlockTypeId(hfBlockTypeId.Value.AsInteger()).Select(a => a.Id).ToList()) { BlockCache.Flush(blockId); } }
/// <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) { int blockId = Convert.ToInt32(PageParameter("BlockId")); BlockCache _block = BlockCache.Read(blockId); if (!Page.IsPostBack && _block.IsAuthorized("Administrate", CurrentPerson)) { tbBlockName.Text = _block.Name; tbCacheDuration.Text = _block.OutputCacheDuration.ToString(); } base.OnLoad(e); }
/// <summary> /// Handles the Click event of the btnDefault 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 btnDefault_Click(object sender, EventArgs e) { var bioBlock = BlockCache.Get(Rock.SystemGuid.Block.BIO.AsGuid()); List <Guid> workflowActionGuidList = bioBlock.GetAttributeValues("WorkflowActions").AsGuidList(); if (workflowActionGuidList == null || workflowActionGuidList.Count == 0) { // Add Checkr to Bio Workflow Actions bioBlock.SetAttributeValue("WorkflowActions", CheckrSystemGuid.CHECKR_WORKFLOW_TYPE); } else { //var workflowActionValues = workflowActionValue.Split( new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries ).ToList(); Guid guid = CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid(); if (!workflowActionGuidList.Any(w => w == guid)) { // Add Checkr to Bio Workflow Actions workflowActionGuidList.Add(guid); } // Remove PMM from Bio Workflow Actions guid = Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid(); workflowActionGuidList.RemoveAll(w => w == guid); bioBlock.SetAttributeValue("WorkflowActions", workflowActionGuidList.AsDelimited(",")); } bioBlock.SaveAttributeValue("WorkflowActions"); string checkrTypeName = (typeof(Rock.Checkr.Checkr)).FullName; var checkrComponent = BackgroundCheckContainer.Instance.Components.Values.FirstOrDefault(c => c.Value.TypeName == checkrTypeName); checkrComponent.Value.SetAttributeValue("Active", "True"); checkrComponent.Value.SaveAttributeValue("Active"); using (var rockContext = new RockContext()) { WorkflowTypeService workflowTypeService = new WorkflowTypeService(rockContext); // Rename PMM Workflow var pmmWorkflowAction = workflowTypeService.Get(Rock.SystemGuid.WorkflowType.PROTECTMYMINISTRY.AsGuid()); pmmWorkflowAction.Name = Checkr_CreatePages.NEW_PMM_WORKFLOW_TYPE_NAME; var checkrWorkflowAction = workflowTypeService.Get(CheckrSystemGuid.CHECKR_WORKFLOW_TYPE.AsGuid()); // Rename Checkr Workflow checkrWorkflowAction.Name = "Background Check"; rockContext.SaveChanges(); } ShowDetail(); }
public ChainingWorker(WorkerConfig workerConfig, Logger logger, IBlockchainRules rules, BlockHeaderCache blockHeaderCache, ChainedHeaderCache chainedHeaderCache, BlockCache blockCache) : base("ChainingWorker", workerConfig.initialNotify, workerConfig.minIdleTime, workerConfig.maxIdleTime, logger) { this.rules = rules; this.blockHeaderCache = blockHeaderCache; this.chainedHeaderCache = chainedHeaderCache; this.blockCache = blockCache; this.blockHeaders = new ConcurrentQueue <BlockHeader>(); this.unchainedByPrevious = new Dictionary <UInt256, Dictionary <UInt256, BlockHeader> >(); this.blockHeaderCache.OnAddition += ChainBlockHeader; this.blockCache.OnAddition += ChainBlock; }
/// <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.DialogMasterPage masterPage = this.Page.Master as Rock.Web.UI.DialogMasterPage; if (masterPage != null) { masterPage.OnSave += new EventHandler <EventArgs>(masterPage_OnSave); } try { int blockId = Convert.ToInt32(PageParameter("BlockId")); BlockCache _block = BlockCache.Read(blockId); if (_block.IsAuthorized("Administrate", CurrentPerson)) { phAttributes.Controls.Clear(); phAdvancedAttributes.Controls.Clear(); if (_block.Attributes != null) { foreach (var attributeCategory in Rock.Attribute.Helper.GetAttributeCategories(_block)) { 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"); } } catch (SystemException ex) { DisplayError(ex.Message); } base.OnInit(e); }
/// <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) { try { int?blockId = PageParameter("BlockId").AsIntegerOrNull(); if (!blockId.HasValue) { return; } var _block = BlockCache.Get(blockId.Value); Rock.Web.UI.DialogPage dialogPage = this.Page as Rock.Web.UI.DialogPage; if (dialogPage != null) { dialogPage.OnSave += new EventHandler <EventArgs>(masterPage_OnSave); dialogPage.Title = _block.BlockType.Name; dialogPage.SubTitle = string.Format("{0} / Id: {1}", _block.BlockType.Category, blockId); } if (_block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) { var blockTypeId = _block.BlockTypeId; var blockType = BlockTypeCache.Get(blockTypeId); if (blockType != null && !blockType.IsInstancePropertiesVerified) { using (var rockContext = new RockContext()) { var blockCompiledType = _block.BlockType.GetCompiledType(); int? blockEntityTypeId = EntityTypeCache.Get(typeof(Block)).Id; bool attributesUpdated = Rock.Attribute.Helper.UpdateAttributes(blockCompiledType, blockEntityTypeId, "BlockTypeId", blockTypeId.ToString(), rockContext); BlockTypeCache.Get(blockTypeId).MarkInstancePropertiesVerified(true); } } } 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); LoadCustomSettingsTabs(); }
/// <summary> /// Gets the zone for block. /// </summary> /// <param name="block">The block.</param> /// <returns></returns> protected RockZoneElement GetZoneForBlock(BlockCache block) { if (_zones.ContainsKey(block.Zone)) { return(_zones[block.Zone]); } else if (_zones.ContainsKey("Main")) { return(_zones["Main"]); } else { return(_zones.Last().Value); } }
public MobilePage GetPage(int id, string parameter = "") { var person = GetPerson(); HttpContext.Current.Items.Add("CurrentPerson", person); var pageCache = PageCache.Read(id); if (!pageCache.IsAuthorized(Authorization.VIEW, person)) { return(new MobilePage()); } string theme = pageCache.Layout.Site.Theme; string layout = pageCache.Layout.FileName; string layoutPath = PageCache.FormatPath(theme, layout); Rock.Web.UI.RockPage cmsPage = (Rock.Web.UI.RockPage)BuildManager.CreateInstanceFromVirtualPath(layoutPath, typeof(Rock.Web.UI.RockPage)); MobilePage mobilePage = new MobilePage(); mobilePage.LayoutType = pageCache.Layout.Name; mobilePage.Title = pageCache.PageTitle; mobilePage.ShowTitle = pageCache.PageDisplayTitle; foreach (var attribute in pageCache.AttributeValues) { mobilePage.Attributes.Add(attribute.Key, attribute.Value.ValueFormatted); } foreach (var block in pageCache.Blocks) { if (block.IsAuthorized(Authorization.VIEW, person)) { var blockCache = BlockCache.Read(block.Id); var control = ( RockBlock )cmsPage.TemplateControl.LoadControl(blockCache.BlockType.Path); if (control is RockBlock && control is IMobileResource) { control.SetBlock(pageCache, blockCache); var mobileResource = control as IMobileResource; var mobileBlock = mobileResource.GetMobile(parameter); mobileBlock.BlockId = blockCache.Id; mobileBlock.Zone = blockCache.Zone; mobilePage.Blocks.Add(mobileBlock); } } } HttpContext.Current.Response.Headers.Set("TTL", pageCache.OutputCacheDuration.ToString()); return(mobilePage); }
/// <summary> /// Handles the Click event of the lbProperty 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 lbProperty_Click(object sender, EventArgs e) { LinkButton lb = sender as LinkButton; if (lb != null) { CurrentTab = lb.Text; int blockId = Convert.ToInt32(PageParameter("BlockId")); BlockCache _block = BlockCache.Read(blockId); rptProperties.DataSource = GetTabs(_block.BlockType); rptProperties.DataBind(); } ShowSelectedPane(); }
/// <summary> /// Handles the ItemDataBound event of the any of the rptrBlocks controls. /// </summary> /// <param name="sender">The source of the event.</param> /// <param name="e">The <see cref="RepeaterItemEventArgs"/> instance containing the event data.</param> protected void rptrBlocks_ItemDataBound(object sender, RepeaterItemEventArgs e) { var blockInstance = e.Item.DataItem as BlockInstance; if (blockInstance != null) { BlockCache block = BlockCache.Get(blockInstance.Id); if (block != null) { var phAdminButtons = e.Item.FindControl("phAdminButtons") as PlaceHolder; var phSettings = e.Item.FindControl("phSettings") as PlaceHolder; AddAdminControls(block, phAdminButtons); AddSettingsControls(block, phSettings); } } }
public LocalClient(Logger logger, RulesEnum type, IKernel kernel, IBlockchainRules rules, CoreDaemon blockchainDaemon, BlockHeaderCache blockHeaderCache, ChainedHeaderCache chainedHeaderCache, TransactionCache transactionCache, BlockCache blockCache, NetworkPeerCache networkPeerCache) { this.shutdownToken = new CancellationTokenSource(); this.logger = logger; this.type = type; this.kernel = kernel; this.rules = rules; this.blockchainDaemon = blockchainDaemon; this.blockHeaderCache = blockHeaderCache; this.chainedHeaderCache = chainedHeaderCache; this.transactionCache = transactionCache; this.blockCache = blockCache; this.networkPeerCache = networkPeerCache; this.messageRateMeasure = new RateMeasure(); this.connectWorker = new WorkerMethod("LocalClient.ConnectWorker", ConnectWorker, true, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(1), this.logger); this.headersRequestWorker = kernel.Get <HeadersRequestWorker>( new ConstructorArgument("workerConfig", new WorkerConfig(initialNotify: true, minIdleTime: TimeSpan.FromMilliseconds(50), maxIdleTime: TimeSpan.FromSeconds(30))), new ConstructorArgument("localClient", this)); this.blockRequestWorker = kernel.Get <BlockRequestWorker>( new ConstructorArgument("workerConfig", new WorkerConfig(initialNotify: true, minIdleTime: TimeSpan.FromMilliseconds(50), maxIdleTime: TimeSpan.FromSeconds(30))), new ConstructorArgument("localClient", this)); this.statsWorker = new WorkerMethod("LocalClient.StatsWorker", StatsWorker, true, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(30), this.logger); switch (this.Type) { case RulesEnum.MainNet: Messaging.Port = 8333; Messaging.Magic = Messaging.MAGIC_MAIN; break; case RulesEnum.TestNet3: Messaging.Port = 18333; Messaging.Magic = Messaging.MAGIC_TESTNET3; break; case RulesEnum.ComparisonToolTestNet: Messaging.Port = 18444; Messaging.Magic = Messaging.MAGIC_COMPARISON_TOOL; break; } }
public MainnetSimulator() { this.random = new Random(); this.blockProvider = new MainnetBlockProvider(); // initialize kernel this.kernel = new StandardKernel(); // add logging module this.kernel.Load(new ConsoleLoggingModule()); // log startup this.logger = kernel.Get <Logger>(); this.logger.Info("Starting up: {0}".Format2(DateTime.Now)); // add storage module this.kernel.Load(new MemoryStorageModule()); // add cache module this.kernel.Load(new CoreCacheModule()); // initialize block view this.blockCache = this.kernel.Get <BlockCache>(); // add rules module this.kernel.Load(new RulesModule(RulesEnum.MainNet)); MainnetRules.IgnoreScriptErrors = true; // initialize the blockchain daemon this.kernel.Bind <CoreDaemon>().ToSelf().InSingletonScope(); this.coreDaemon = this.kernel.Get <CoreDaemon>(); // start the blockchain daemon this.coreDaemon.Start(); // wait for initial work this.coreDaemon.ForceWorkAndWait(); // verify initial state Assert.AreEqual(0, this.coreDaemon.TargetBlock.Height); //Assert.AreEqual(this.genesisBlock.Hash, this.blockchainDaemon.TargetChain.LastBlock.Hash); //Assert.AreEqual(this.genesisBlock.Hash, this.blockchainDaemon.ChainState.LastBlockHash); }
/// <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) { int blockId = Convert.ToInt32(PageParameter("BlockId")); BlockCache _block = BlockCache.Read(blockId); if (!Page.IsPostBack && _block.IsAuthorized(Authorization.ADMINISTRATE, CurrentPerson)) { rptProperties.DataSource = _tabs; rptProperties.DataBind(); tbBlockName.Text = _block.Name; tbCssClass.Text = _block.CssClass; cePreHtml.Text = _block.PreHtml; cePostHtml.Text = _block.PostHtml; tbCacheDuration.Text = _block.OutputCacheDuration.ToString(); } base.OnLoad(e); }
public override JArray GetLastTransactions() { JObject result = new JObject(); using (DBEntities db = new DBEntities(Observer.dbContextOptions.Options)) { var lastBlock = db.BlockCaches.SingleOrDefault(b => b.Currency == CurrencyCode); string lastBlockHash = ""; if (lastBlock == null) { string bestBlockHash = ((JValue)client.Invoke("getbestblockhash")).Value <string>(); JToken bestBlock = (JToken)client.Invoke("getblock", new object[] { bestBlockHash }); lastBlockHash = (string)bestBlock["previousblockhash"]; } else { lastBlockHash = lastBlock.LastSeenBlock; } object[] p = new object[] { lastBlockHash, 1, true }; result = (JObject)client.Invoke("listsinceblock", p); if (lastBlock == null) { lastBlock = new BlockCache() { Currency = CurrencyCode }; db.BlockCaches.Add(lastBlock); } lastBlock.LastSeenBlock = (string)result["lastblock"]; db.SaveChanges(); return((JArray)result["transactions"]); } }
public TrimDatabase(Func <MemoryTable> inMemoryFunc, BlockCache blockCache, int levels, string databaseFolder, int targetFileSizeL2) { _blockCache = blockCache; if (!System.IO.Directory.Exists(databaseFolder)) { System.IO.Directory.CreateDirectory(databaseFolder); } _databaseFolder = databaseFolder; _inMemoryFunc = inMemoryFunc; var unsorted = new UnsortedStorageLayer(1, _databaseFolder, _blockCache); _storageLayers.Add(unsorted); for (var i = 2; i <= levels; i++) { _storageLayers.Add(new SortedStorageLayer(i, _databaseFolder, _blockCache, targetFileSizeL2)); } _skipList = _inMemoryFunc(); }
/// <summary> /// Gets the next action with a Form attached. /// </summary> /// <param name="workflow">The workflow.</param> /// <param name="currentPerson">The current person.</param> /// <returns></returns> private WorkflowAction GetNextAction(Model.Workflow workflow, Person currentPerson) { int personId = currentPerson?.Id ?? 0; bool canEdit = BlockCache.IsAuthorized(Authorization.EDIT, currentPerson); // // Find all the activities that this person can see. // var activities = workflow.Activities .Where(a => a.IsActive && ( canEdit || (!a.AssignedGroupId.HasValue && !a.AssignedPersonAliasId.HasValue) || (a.AssignedPersonAlias != null && a.AssignedPersonAlias.PersonId == personId) || (a.AssignedGroup != null && a.AssignedGroup.Members.Any(m => m.PersonId == personId)) ) ) .OrderBy(a => a.ActivityTypeCache.Order) .ToList(); // // Find the first action that the user is authorized to work with that has a Form // attached to it. // foreach (var activity in activities) { if (canEdit || activity.ActivityTypeCache.IsAuthorized(Authorization.VIEW, currentPerson)) { foreach (var action in activity.ActiveActions) { if (action.ActionTypeCache.WorkflowForm != null && action.IsCriteriaValid) { return(action); } } } } return(null); }
public ChainStateWorker(TargetChainWorker targetChainWorker, ChainStateBuilder chainStateBuilder, Func <Chain> getTargetChain, WorkerConfig workerConfig, Logger logger, IKernel kernel, IBlockchainRules rules, BlockCache blockCache, SpentTransactionsCache spentTransactionsCache, InvalidBlockCache invalidBlockCache) : base("ChainStateWorker", workerConfig.initialNotify, workerConfig.minIdleTime, workerConfig.maxIdleTime, logger) { this.logger = logger; this.getTargetChain = getTargetChain; this.kernel = kernel; this.rules = rules; this.blockCache = blockCache; this.spentTransactionsCache = spentTransactionsCache; this.invalidBlockCache = invalidBlockCache; this.blockProcessingDurationMeasure = new DurationMeasure(); this.targetChainWorker = targetChainWorker; this.chainStateBuilder = chainStateBuilder; this.currentChain = this.chainStateBuilder.Chain.ToImmutable(); this.pruningWorker = kernel.Get <PruningWorker>( new ConstructorArgument("workerConfig", new WorkerConfig(initialNotify: false, minIdleTime: TimeSpan.FromSeconds(30), maxIdleTime: TimeSpan.FromMinutes(5))), new ConstructorArgument("getChainStateBuilder", (Func <ChainStateBuilder>)(() => this.chainStateBuilder))); }
public ChainStateBuilder(ChainBuilder chain, Utxo parentUtxo, Logger logger, IKernel kernel, IBlockchainRules rules, BlockHeaderCache blockHeaderCache, BlockCache blockCache, SpentTransactionsCache spentTransactionsCache, SpentOutputsCache spentOutputsCache) { this.logger = logger; this.sha256 = new SHA256Managed(); this.rules = rules; this.blockHeaderCache = blockHeaderCache; this.blockCache = blockCache; this.spentTransactionsCache = spentTransactionsCache; this.spentOutputsCache = spentOutputsCache; this.chainStateMonitor = new ChainStateMonitor(this.logger); this.scriptValidator = new ScriptValidator(this.logger, this.rules); this.chainStateMonitor.Subscribe(this.scriptValidator); this.chain = chain; this.chainStateBuilderStorage = kernel.Get <IChainStateBuilderStorage>(new ConstructorArgument("parentUtxo", parentUtxo.Storage)); this.spentTransactions = ImmutableList.CreateBuilder <KeyValuePair <UInt256, SpentTx> >(); this.spentOutputs = ImmutableList.CreateBuilder <KeyValuePair <TxOutputKey, TxOutput> >(); this.stats = new BuilderStats(); }
private void Init() { BC = new BlockCache(); groundMeshes = new GameObject[BOXES][]; for (int i = 0; i < groundMeshes.Length; i++) groundMeshes[i] = new GameObject[groundMeshes.Length]; UpdateLocalCoordinates(0,0); //con = new ConnectionHandler(); /*System.Random fixRand = new System.Random( 0 ); int[] nums = new int[1000]; seed_random(0); get_random_int(nums); for( int j = 0; j < 6; j++ ) print((nums[j] % 10) + 1); */ }
/// <summary> /// Initializes a new instance of the BlockCacheStream class. /// </summary> /// <param name="toWrap">The stream to wrap.</param> /// <param name="ownership">Whether to assume ownership of <c>toWrap</c>.</param> /// <param name="settings">The cache settings.</param> public BlockCacheStream(SparseStream toWrap, Ownership ownership, BlockCacheSettings settings) { if (!toWrap.CanRead) { throw new ArgumentException("The wrapped stream does not support reading", "toWrap"); } if (!toWrap.CanSeek) { throw new ArgumentException("The wrapped stream does not support seeking", "toWrap"); } _wrappedStream = toWrap; _ownWrapped = ownership; _settings = new BlockCacheSettings(settings); if (_settings.OptimumReadSize % _settings.BlockSize != 0) { throw new ArgumentException("Invalid settings, OptimumReadSize must be a multiple of BlockSize", "settings"); } _readBuffer = new byte[_settings.OptimumReadSize]; _blocksInReadBuffer = _settings.OptimumReadSize / _settings.BlockSize; int totalBlocks = (int)(_settings.ReadCacheSize / _settings.BlockSize); _cache = new BlockCache<Block>(_settings.BlockSize, totalBlocks); _stats = new BlockCacheStatistics(); _stats.FreeReadBlocks = totalBlocks; }