public BalanceSheet(IEnumerable<OrderedBalanceChange> changes, ChainBase chain) { if (chain == null) throw new ArgumentNullException("chain"); _Chain = chain; var all = changes .Where(c => c.SpentCoins != null) //Remove line whose previous coins have not been loadedcould not be deduced .Where(c => c.MempoolEntry || chain.GetBlock(c.BlockId) != null) //Take only mempool entry, or confirmed one .Where(c => !(c.IsCoinbase && c.MempoolEntry)) //There is no such thing as a Coinbase unconfirmed, by definition a coinbase appear in a block .ToList(); var confirmed = all.Where(o => o.BlockId != null).ToDictionary(o => o.TransactionId); Dictionary<uint256, OrderedBalanceChange> unconfirmed = new Dictionary<uint256, OrderedBalanceChange>(); foreach(var item in all.Where(o => o.MempoolEntry && !confirmed.ContainsKey(o.TransactionId))) { unconfirmed.AddOrReplace(item.TransactionId, item); } _Prunable = all.Where(o => o.BlockId == null && confirmed.ContainsKey(o.TransactionId)).ToList(); _All = all.Where(o => (unconfirmed.ContainsKey(o.TransactionId) || confirmed.ContainsKey(o.TransactionId)) && !(o.BlockId == null && confirmed.ContainsKey(o.TransactionId)) ).ToList(); _Confirmed = _All.Where(o => o.BlockId != null && confirmed.ContainsKey(o.TransactionId)).ToList(); _Unconfirmed = _All.Where(o => o.BlockId == null && unconfirmed.ContainsKey(o.TransactionId)).ToList(); }
public static Script ParseScript(string s) { MemoryStream result = new MemoryStream(); if(mapOpNames.Count == 0) { mapOpNames = new Dictionary<string, OpcodeType>(Op._OpcodeByName); foreach(var kv in mapOpNames.ToArray()) { if(kv.Key.StartsWith("OP_", StringComparison.Ordinal)) { var name = kv.Key.Substring(3, kv.Key.Length - 3); mapOpNames.AddOrReplace(name, kv.Value); } } } var words = s.Split(' ', '\t', '\n'); foreach(string w in words) { if(w == "") continue; if(w.All(l => l.IsDigit()) || (w.StartsWith("-") && w.Substring(1).All(l => l.IsDigit()))) { // Number long n = long.Parse(w); Op.GetPushOp(new BigInteger(n)).WriteTo(result); } else if(w.StartsWith("0x") && HexEncoder.IsWellFormed(w.Substring(2))) { // Raw hex data, inserted NOT pushed onto stack: var raw = Encoders.Hex.DecodeData(w.Substring(2)); result.Write(raw, 0, raw.Length); } else if(w.Length >= 2 && w.StartsWith("'") && w.EndsWith("'")) { // Single-quoted string, pushed as data. NOTE: this is poor-man's // parsing, spaces/tabs/newlines in single-quoted strings won't work. var b = TestUtils.ToBytes(w.Substring(1, w.Length - 2)); Op.GetPushOp(b).WriteTo(result); } else if(mapOpNames.ContainsKey(w)) { // opcode, e.g. OP_ADD or ADD: result.WriteByte((byte)mapOpNames[w]); } else { Assert.True(false, "Invalid test"); return null; } } return new Script(result.ToArray()); }
static EquipmentSets() { CMOptions = new EquipmentSetsOptions(); SetTypes = TypeOfEquipmentSet.GetConstructableChildren(); Sets = new Dictionary<Type, EquipmentSet>(SetTypes.Length); foreach (var t in SetTypes) { Sets.AddOrReplace(t, set => set ?? t.CreateInstanceSafe<EquipmentSet>()); } }
public Dictionary <Type, ISPNode> GetChildrenTypes(ISPNode parentNode) { IEnumerable <Lazy <SPNode> > importedNodes = CompositionProvider.GetExports <SPNode>(parentNode.Descriptor.ClassType); var types = new Dictionary <Type, ISPNode>(); foreach (var lazyItem in importedNodes) { SPNode node = lazyItem.Value; node.NodeProvider = parentNode.NodeProvider; if (node.Descriptor.AdapterItemType != null) { types.AddOrReplace(node.Descriptor.AdapterItemType, node); } } return(types); }
/// <summary> /// Parses the markup. /// </summary> /// <param name="markup">The markup.</param> /// <param name="context">The context.</param> /// <returns></returns> private Dictionary <string, string> ParseMarkup(string markup, Context context) { // first run lava across the inputted markup var internalMergeFields = new Dictionary <string, object>(); // get variables defined in the lava source foreach (var scope in context.Scopes) { foreach (var item in scope) { internalMergeFields.AddOrReplace(item.Key, item.Value); } } // get merge fields loaded by the block or container if (context.Environments.Count > 0) { foreach (var item in context.Environments[0]) { internalMergeFields.AddOrReplace(item.Key, item.Value); } } var resolvedMarkup = markup.ResolveMergeFields(internalMergeFields); var parms = new Dictionary <string, string>(); parms.Add("cacheduration", "0"); parms.Add("references", string.Empty); parms.Add("disableanonymousfunction", "false"); parms.Add("url", string.Empty); var markupItems = Regex.Matches(resolvedMarkup, @"(\S*?:'[^']+')") .Cast <Match>() .Select(m => m.Value) .ToList(); foreach (var item in markupItems) { var itemParts = item.ToString().Split(new char[] { ':' }, 2); if (itemParts.Length > 1) { parms.AddOrReplace(itemParts[0].Trim().ToLower(), itemParts[1].Trim().Substring(1, itemParts[1].Length - 2)); } } return(parms); }
public void AddChannels(List <NetworkChannel> channels) { if (channels.Count == 0) { return; } lock (_syncObject) { foreach (var channel in channels) { _channels.AddOrReplace(channel.Id, channel); } _logger.LogDebug($"Added {channels.Count} channels. Total channels: {_channels.Count}"); } }
public void AddNodes(List <NetworkNode> nodesToUpdate) { if (nodesToUpdate.Count == 0) { return; } lock (_syncObject) { foreach (var networkNode in nodesToUpdate) { _nodes.AddOrReplace(networkNode.Id, networkNode); } _logger.LogDebug($"Added {nodesToUpdate.Count} nodes. Total nodes: {_nodes.Count}"); } }
static Op() { ValidOpCode = GetValidOpCode(); OpcodeByName = new Dictionary <string, OpcodeType>(); foreach (var code in Enum.GetValues(typeof(OpcodeType)).Cast <OpcodeType>().Distinct()) { var name = GetOpName(code); if (name != "OP_UNKNOWN") { OpcodeByName.AddOrReplace(name, code); } } OpcodeByName.AddOrReplace("OP_TRUE", OpcodeType.OP_1); OpcodeByName.AddOrReplace("OP_FALSE", OpcodeType.OP_0); OpcodeByName.AddOrReplace("OP_CHECKLOCKTIMEVERIFY", OpcodeType.OP_CHECKLOCKTIMEVERIFY); OpcodeByName.AddOrReplace("OP_HODL", OpcodeType.OP_CHECKLOCKTIMEVERIFY); OpcodeByName.AddOrReplace("OP_NOP2", OpcodeType.OP_CHECKLOCKTIMEVERIFY); OpcodeByName.AddOrReplace("OP_CHECKSEQUENCEVERIFY", OpcodeType.OP_CHECKSEQUENCEVERIFY); OpcodeByName.AddOrReplace("OP_NOP3", OpcodeType.OP_CHECKSEQUENCEVERIFY); foreach (var op in new[] { new object[] { "OP_0", OpcodeType.OP_0 }, new object[] { "OP_1", OpcodeType.OP_1 }, new object[] { "OP_2", OpcodeType.OP_2 }, new object[] { "OP_3", OpcodeType.OP_3 }, new object[] { "OP_4", OpcodeType.OP_4 }, new object[] { "OP_5", OpcodeType.OP_5 }, new object[] { "OP_6", OpcodeType.OP_6 }, new object[] { "OP_7", OpcodeType.OP_7 }, new object[] { "OP_8", OpcodeType.OP_8 }, new object[] { "OP_9", OpcodeType.OP_9 } }) { OpcodeByName.AddOrReplace((string)op[0], (OpcodeType)op[1]); } }
internal void AddRowAbove(object sender) { if (!(sender is Control ctrl)) { return; } var row = Grid.GetRow(ctrl); if (row == 0) { return; // cannot insert above header } var fieldsAboveInsert = _fields.Where(x => int.Parse(x.Key.Split(new[] { "__" }, StringSplitOptions.None)[1]) < row).ToArray(); var fieldsBelowInsert = _fields.Where(x => int.Parse(x.Key.Split(new[] { "__" }, StringSplitOptions.None)[1]) >= row).ToArray(); var fieldsBelowWithNewName = new Dictionary <string, INZazuWpfField>(); // now we need to move the below fields to the next row (a little like Hilberts Hotel) var layout = ((DynamicDataTable)ValueControl).LayoutGrid; layout.RowDefinitions.Add(new RowDefinition { Height = new GridLength(24) }); foreach (var field in fieldsBelowInsert.OrderBy(x => int.Parse(x.Key.Split(new[] { "__" }, StringSplitOptions.None)[1]))) { // move to next row var currentRow = Grid.GetRow(field.Value.ValueControl); Grid.SetRow(field.Value.ValueControl, currentRow + 1); // change fields index and control name (for serialization) var splits = field.Key.Split(new[] { "__" }, StringSplitOptions.None); var newKey = splits[0] + "__" + (currentRow + 1); field.Value.ValueControl.Name = newKey; fieldsBelowWithNewName.AddOrReplace(newKey, field.Value); } // ok, lets fill the fields _fields.Clear(); fieldsAboveInsert.ToList().ForEach(x => _fields.Add(x.Key, x.Value)); AddNewRow(layout, row); // this adds the new controls to the field list fieldsBelowWithNewName.ToList().ForEach(x => _fields.Add(x.Key, x.Value)); }
public void loadContentPacks() { Dictionary <string, MovieData> movieData = MovieTheater.GetMovieData(); List <MovieCharacterReaction> genericReactions = MovieTheater.GetMovieReactions(); foreach (var pack in Helper.ContentPacks.GetOwned()) { CustomMoviePack cPack = pack.ReadJsonFile <CustomMoviePack>("content.json"); foreach (var movie in cPack.Movies) { movie.LoadTexture(pack); movie._pack = pack; int y = 0; while (movieData.ContainsKey(movie.Season + "_movie_" + y)) { y++; } movie.FixedMovieID = movie.FixedMovieID == null ? movie.Season + "_movie_" + y : movie.FixedMovieID; Monitor.Log("Added " + movie.Title + " as " + movie.FixedMovieID); MovieData fixedData = movie.GetData(y); fixedData.ID = movie.FixedMovieID; movieData.AddOrReplace(fixedData.ID, fixedData); allTheMovies.AddOrReplace(movie.Id, movie); } typeof(MovieTheater).GetField("_movieData", BindingFlags.NonPublic | BindingFlags.Static).SetValue(null, movieData); foreach (var reaction in cPack.Reactions) { foreach (var r in reaction.Reactions) { if (r.Tag != null && allTheMovies.ContainsKey(r.Tag)) { r.Tag = "CMovieID:" + r.Tag; } } allTheReactions.AddOrReplace(new TranslatableMovieReactions(reaction, pack)); } } }
private bool UpdateCollateralInfo(CancellationToken cancellation = default) { List <string> addressesToCheck; lock (this.locker) { addressesToCheck = this.depositsByServerId.Keys.ToList(); } if (addressesToCheck.Count == 0) { this.logger.LogTrace("(-)[NOTHING_TO_CHECK]:true"); return(true); } var collateral = new Dictionary <string, Money>(); foreach (string addressToCheck in addressesToCheck) { if (cancellation.IsCancellationRequested) { this.logger.LogTrace("(-)[CANCELLED]:false"); return(false); } Money balance = this.addressIndexer.GetAddressBalance(addressToCheck, RequiredConfirmations); collateral.AddOrReplace(addressToCheck, balance); } if (collateral.Count != addressesToCheck.Count) { this.logger.LogTrace("(-)[INCONSISTENT_DATA]:false"); return(false); } lock (this.locker) { foreach ((string key, Money value) in collateral) { this.depositsByServerId[key] = value; } } return(true); }
protected override void PutBytesBatch(IEnumerable <Tuple <string, byte[]> > enumerable) { foreach (var data in enumerable) { if (data.Item2 == null) { _Table.Remove(data.Item1); _Removed.Add(data.Item1); _Added.Remove(data.Item1); } else { _Table.AddOrReplace(data.Item1, data.Item2); _Removed.Remove(data.Item1); _Added.Add(data.Item1); } } }
public SheetMusic(string id, Texture2D texture, string name, string description, Color color, string music, int length, IMagic magic) { if (allSheets == null) { allSheets = new Dictionary <string, SheetMusic>(); } this.magic = magic; this.length = length; this.texture = texture; this.color = color; this.music = music; this.name = name; displayName = name; sheetDescription = description; sheetMusicID = id; allSheets.AddOrReplace(id, this); }
/// <summary> /// 记录所有Selectable /// </summary> private void StoreSelectable() { Selectable[] coms = selected.GetComponentsInChildren <Selectable>(); foreach (var com in coms) { if (!com.interactable) { continue; } var c = com.name[com.name.Length - 1]; if (c == '_' || c == '=') { continue; } var path = com.transform.GetHierarchy(selected.transform); dictRef.AddOrReplace(path, com); } }
public GameObject GetSingleUI(UIType uiType) { if (_UIDict.ContainsKey(uiType) == false || _UIDict[uiType] == null) { //GameObject go = GameObject.Instantiate(Resources.Load<GameObject>(uiType.Path)) as GameObject; AssetBundle bundle = AssetManager.GetInstance().GetAsset(uiType.Path); GameObject go = GameObject.Instantiate(bundle.LoadAsset(uiType.Name)) as GameObject; if (_canvas == null) { _canvas = GameObject.Find("Canvas").transform; } go.transform.SetParent(_canvas, false); go.name = uiType.Name; _UIDict.AddOrReplace(uiType, go); return(go); } return(_UIDict[uiType]); }
/***************************************************/ public static Element ToRevitElement(this DraftingInstance draftingInstance, Document document, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null) { if (draftingInstance == null || string.IsNullOrWhiteSpace(draftingInstance.ViewName) || document == null) { return(null); } Element element = refObjects.GetValue <Element>(document, draftingInstance.BHoM_Guid); if (element != null) { return(element); } if (draftingInstance.Properties == null) { Compute.NullObjectPropertiesWarning(draftingInstance); return(null); } settings = settings.DefaultIfNull(); View view = draftingInstance.View(document); if (view == null) { return(null); } ElementType elementType = draftingInstance.Properties.ElementType(document, draftingInstance.BuiltInCategories(document), settings); element = draftingInstance.IToRevitElement(elementType, view, settings); if (element == null) { return(null); } // Copy parameters from BHoM object to Revit element element.CopyParameters(draftingInstance, settings); refObjects.AddOrReplace(draftingInstance, element); return(element); }
public GameObject GetSingleUI(UIType uiType) { if (_UIDict.ContainsKey(uiType) == false || _UIDict[uiType] == null) { GameObject UIRootCanvas = GameObject.Find("UIRootCanvas"); // GameObject UICamera = UIRootCanvas.transform.FindChild("UICamera").gameObject; GameObject go = ResourceMgr.GetGameObject(URLConst.GetUI(uiType.Name)); go.transform.SetParent(UIRootCanvas.transform); go.transform.localPosition = new Vector3(0, 0, 0); go.transform.localScale = new Vector3(1, 1, 1); Canvas canvas = go.GetComponent <Canvas>(); // Camera camera = UICamera.GetComponent<Camera>(); canvas.renderMode = RenderMode.ScreenSpaceCamera; // canvas.worldCamera = camera; _UIDict.AddOrReplace(uiType, go); return(go); } return(_UIDict[uiType]); }
/// <summary> /// 修改,新增到服务器 /// </summary> /// <param name="_msg"></param> private void SaveToServer(Message _msg) { string strNewTag = _msg["tag"] as string; string strNewShowName = _msg["name"] as string; m_currentCom.OnAffirm(m_rNewModel, m_rNewImg, strNewTag, strNewShowName); // 遍历所有的需要更新的组件 m_pMemeryRes.Clear(); m_qUpdateComp = new Queue <CompConfigData>(); code_CompConfig = new Dictionary <string, CompConfigData>(); m_pUpdateErComp = new List <CompConfigData>(); for (int i = 0; i < m_pComProperty.Count; i++) { ComProperty cpp = m_pComProperty[i]; if (cpp.m_bNeedUpdate) { CompConfigData ccd = new CompConfigData(); ccd.m_jsData = cpp.m_infoJson; ccd.m_strCode = cpp.m_strCode; m_qUpdateComp.Enqueue(ccd); code_CompConfig.AddOrReplace(ccd.m_strCode, ccd); if (cpp.m_rNewImg != null) { m_pMemeryRes.Add(cpp.m_rNewImg); } if (cpp.m_rNewModel != null) { m_pMemeryRes.Add(cpp.m_rNewModel); } } } // 先上传资源,再上传配置 UpdateRes(() => { UpdateCompConfig(() => { // 刷新列表 RefreshCom(); }); }); }
private void LoadResToMemory() { if (m_qResPaths.Count > 0) { string strPath = m_qResPaths.Dequeue() as string; ResManager.Instance.OnLoadLocalRes(strPath, (res) => { JsonData jd = new JsonData(); jd["Path"] = strPath; jd["Name"] = res.GetName(); jd["Crc"] = res.GetCrc(); m_jdFbx.Add(jd); m_pMemeryRes.Add(res); PopWaiting(); string strFileName = res.GetName(); strFileName = Utils.GetFilePrefix(strFileName); if (resName_Crc.ContainsKey(strFileName)) { Debug.LogWarning("-------------模型文件重名:" + strFileName); } resName_Crc.AddOrReplace(strFileName.ToLower(), jd); LoadResToMemory(); }); } else { string strJd = m_jdFbx.ToJson(); Utils.SaveInfo(strJd, "本地新组件AB信息"); Debug.LogWarning("加载本地文件完成"); // 上传资源到服务器 UpdateRes(() => { Debug.Log("---------资源上传完成!-------"); }); // 加载服务器组件配置 LoadCompConfig(ReadCompDataForUpdate); } }
private void OnEnable() { rectTransform = transform as RectTransform; listParent = rectTransform.GetChild(0).transform; scrollRect = rectTransform.parent.GetComponent <ScrollRect>(); viewportHeight = rectTransform.rect.size.y; itemCountChangedDisposable = Observable.EveryUpdate().Where(_ => itemCount != listParent.childCount).Subscribe(_ => ItemCountChanged()); activeItemsChangedDisposable = Observable.EveryUpdate().Where(_ => !items.Where(obj => obj != null).Select(obj => obj.transform.GetChild(0).gameObject.activeInHierarchy).SequenceEqual(previouslyActiveList)).Subscribe(_ => ActiveItemsUpdated()); scrollRect.onValueChanged.AddListener(_ => ScrollRectChanged()); if (!string.IsNullOrEmpty(scrollviewKey)) { ActiveScrollviews.AddOrReplace(scrollviewKey, this); } OnOptimizedScrollviewInitialized?.Invoke(this); }
/***************************************************/ public static Autodesk.Revit.DB.Plumbing.PipeType ToRevitElementType(this oM.MEP.System.SectionProperties.PipeSectionProperty property, Document document, IEnumerable <BuiltInCategory> categories = null, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null) { if (property == null || document == null) { return(null); } Autodesk.Revit.DB.Plumbing.PipeType elementType = refObjects.GetValue <Autodesk.Revit.DB.Plumbing.PipeType>(document, property.BHoM_Guid); if (elementType != null) { return(elementType); } settings = settings.DefaultIfNull(); elementType = property.ElementType(document, categories, settings) as Autodesk.Revit.DB.Plumbing.PipeType; if (elementType != null) { return(elementType); } List <Autodesk.Revit.DB.Plumbing.PipeType> pipeTypes = new FilteredElementCollector(document).OfClass(typeof(Autodesk.Revit.DB.Plumbing.PipeType)).Cast <Autodesk.Revit.DB.Plumbing.PipeType>().ToList(); if (property.SectionProfile.ElementProfile is BH.oM.Spatial.ShapeProfiles.TubeProfile) { elementType = pipeTypes.FirstOrDefault(x => x.FamilyName == "Pipe Types"); } if (elementType != null) { BH.Engine.Reflection.Compute.RecordNote($"Pipe is being pushed as the first type available in the Revit model, in this case {elementType.Name}."); } else { return(null); } // Copy parameters from BHoM object to Revit element elementType.CopyParameters(property, settings); refObjects.AddOrReplace(property, elementType); return(elementType); }
public static List <BH.oM.MEP.System.Pipe> PipeFromRevit(this Autodesk.Revit.DB.Plumbing.Pipe revitPipe, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null) { settings = settings.DefaultIfNull(); // Reuse a BHoM duct from refObjects if it has been converted before List <BH.oM.MEP.System.Pipe> bhomPipes = refObjects.GetValues <BH.oM.MEP.System.Pipe>(revitPipe.Id); if (bhomPipes != null) { return(bhomPipes); } else { bhomPipes = new List <BH.oM.MEP.System.Pipe>(); } List <BH.oM.Geometry.Line> queried = Query.LocationCurveMEP(revitPipe, settings); // Flow rate double flowRate = revitPipe.LookupParameterDouble(BuiltInParameter.RBS_PIPE_FLOW_PARAM); // Flow rate // Pipe section property BH.oM.MEP.System.SectionProperties.PipeSectionProperty sectionProperty = revitPipe.PipeSectionProperty(settings); for (int i = 0; i < queried.Count; i++) { BH.oM.Geometry.Line segment = queried[i]; BH.oM.MEP.System.Pipe thisSegment = new Pipe { StartPoint = segment.StartPoint(), EndPoint = segment.EndPoint(), FlowRate = flowRate, SectionProperty = sectionProperty }; //Set identifiers, parameters & custom data thisSegment.SetIdentifiers(revitPipe); thisSegment.CopyParameters(revitPipe, settings.ParameterSettings); thisSegment.SetProperties(revitPipe, settings.ParameterSettings); bhomPipes.Add(thisSegment); } refObjects.AddOrReplace(revitPipe.Id, bhomPipes); return(bhomPipes); }
/// <summary> /// Parses the markup. /// </summary> /// <param name="markup">The markup.</param> /// <returns></returns> private Dictionary <string, string> ParseMarkup(string markup) { var parms = new Dictionary <string, string>(); var markupItems = Regex.Matches(markup, @"(\S*?:'[^']+')") .Cast <Match>() .Select(m => m.Value) .ToList(); foreach (var item in markupItems) { var itemParts = item.ToString().Split(new char[] { ':' }, 2); if (itemParts.Length > 1) { parms.AddOrReplace(itemParts[0].Trim().ToLower(), itemParts[1].Trim().Substring(1, itemParts[1].Length - 2)); } } return(parms); }
public static Window WindowFromRevit(this FamilyInstance familyInstance, HostObject host = null, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null) { if (familyInstance == null) { return(null); } settings = settings.DefaultIfNull(); string refId = familyInstance.Id.ReferenceIdentifier(host); Window window = refObjects.GetValue <Window>(refId); if (window != null) { return(window); } BH.oM.Geometry.ISurface location = familyInstance.OpeningSurface(host, settings); if (location == null) { if (host == null) { BH.Engine.Reflection.Compute.RecordWarning(String.Format("Location of the window could not be retrieved from the model (possibly it has zero area or lies on a non-planar face). A window object without location has been returned. Revit ElementId: {0}", familyInstance.Id.IntegerValue)); } else { BH.Engine.Reflection.Compute.RecordWarning(String.Format("Location of the window could not be retrieved from the model (possibly it has zero area or lies on a non-planar face), the opening has been skipped. Revit ElementId: {0}", familyInstance.Id.IntegerValue)); return(null); } } window = new Window { Location = location, Name = familyInstance.FamilyTypeFullName() }; //Set identifiers, parameters & custom data window.SetIdentifiers(familyInstance); window.CopyParameters(familyInstance, settings.ParameterSettings); window.SetProperties(familyInstance, settings.ParameterSettings); refObjects.AddOrReplace(refId, window); return(window); }
/***************************************************/ /**** Public methods ****/ /***************************************************/ public static Level ToRevitLevel(this oM.Geometry.SettingOut.Level level, Document document, RevitSettings settings = null, Dictionary <Guid, List <int> > refObjects = null) { Level revitLevel = refObjects.GetValue <Level>(document, level.BHoM_Guid); if (revitLevel != null) { return(revitLevel); } settings = settings.DefaultIfNull(); List <Level> existingLevels = new FilteredElementCollector(document).OfClass(typeof(Level)).Cast <Level>().ToList(); if (existingLevels.Any(x => x.Name == level.Name)) { BH.Engine.Reflection.Compute.RecordError($"Level named {level.Name} could not be created because a level with the same name already exists in the model. BHoM_Guid: {level.BHoM_Guid}"); return(null); } double elevation = level.Elevation.FromSI(UnitType.UT_Length); if (existingLevels.Any(x => Math.Abs(x.ProjectElevation - elevation) < settings.DistanceTolerance)) { BH.Engine.Reflection.Compute.RecordError($"Level with elevation {level.Elevation} could not be created because a level with the same elevation already exists in the model. BHoM_Guid: {level.BHoM_Guid}"); return(null); } revitLevel = Level.Create(document, elevation); revitLevel.CheckIfNullPush(level); if (revitLevel == null) { return(null); } revitLevel.Name = level.Name; // Copy parameters from BHoM object to Revit element revitLevel.CopyParameters(level, settings); refObjects.AddOrReplace(level, revitLevel); return(revitLevel); }
/// <summary> /// Scores the test. /// </summary> /// <param name="assessmentResponse">The assessment response.</param> /// <returns>returns a AssessmentResults object</returns> static public AssessmentResults GetResult(Dictionary <string, int> assessmentResponse) { AssessmentResults testResults = new AssessmentResults(); var zScores = new Dictionary <Guid, double>(); var assessmentDatas = new Dictionary <Guid, Dictionary <string, string> >(); var grandTotal = assessmentResponse.Sum(a => Convert.ToDouble(a.Value)); foreach (var conflictProfileDefinedValue in constructData.Keys) { var conflictProfile = constructData[conflictProfileDefinedValue]; double totalResponse = 0; var assessmentData = new Dictionary <string, string>(); foreach (var construct in conflictProfile.Constructs) { if (assessmentResponse.ContainsKey(construct)) { totalResponse += assessmentResponse[construct]; assessmentData.AddOrReplace(construct, assessmentResponse[construct].ToString()); } } var zScore = Math.Round((totalResponse - conflictProfile.Mean) / conflictProfile.StandardDeviation, 1); zScores.AddOrReplace(conflictProfileDefinedValue, zScore); assessmentDatas.AddOrReplace(conflictProfileDefinedValue, assessmentData); } testResults.AssessmentData = new AssessmentData(); testResults.AssessmentData.SelfAware = assessmentDatas[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_SELF_AWARENESS.AsGuid()]; testResults.AssessmentData.SelfRegulate = assessmentDatas[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_SELF_REGULATING.AsGuid()]; testResults.AssessmentData.OthersAware = assessmentDatas[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_OTHERS_AWARENESS.AsGuid()]; testResults.AssessmentData.OthersRegulate = assessmentDatas[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_OTHERS_REGULATING.AsGuid()]; testResults.AssessmentData.EQ_InProblemSolving = assessmentDatas[SystemGuid.Attribute.PERSON_EQ_SCALES_PROBLEM_SOLVING.AsGuid()]; testResults.AssessmentData.EQ_UnderStress = assessmentDatas[SystemGuid.Attribute.PERSON_EQ_SCALES_UNDER_STRESS.AsGuid()]; testResults.SelfAwareConstruct = GetPercentFromScore(zScores[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_SELF_AWARENESS.AsGuid()]); testResults.SelfRegulatingConstruct = GetPercentFromScore(zScores[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_SELF_REGULATING.AsGuid()]); testResults.OtherAwarenessContruct = GetPercentFromScore(zScores[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_OTHERS_AWARENESS.AsGuid()]); testResults.OthersRegulatingConstruct = GetPercentFromScore(zScores[SystemGuid.Attribute.PERSON_EQ_CONSTRUCTS_OTHERS_REGULATING.AsGuid()]); testResults.EQ_ProblemSolvingScale = GetPercentFromScore(zScores[SystemGuid.Attribute.PERSON_EQ_SCALES_PROBLEM_SOLVING.AsGuid()]); testResults.EQ_UnderStressScale = GetPercentFromScore(zScores[SystemGuid.Attribute.PERSON_EQ_SCALES_UNDER_STRESS.AsGuid()]); return(testResults); }
/// <summary> /// invoke hooks having the given name /// hooks crashes are catched here for kernel stability reasons /// </summary> /// <param name="context">context</param> /// <param name="name">hook name</param> /// <param name="callBack">called after a hook has finished exec (param is the hook method object owner)</param> public void InvokeHooks( CommandEvaluationContext context, string name, HookTriggerMode hookTriggerMode = HookTriggerMode.EachTime, Action <object> callBack = null ) { if (context.ShellEnv.IsOptionSetted(ShellEnvironmentVar.debug_enableHookTrace)) { context.Out.Echo(context.ShellEnv.Colors.Log + "[invoke hook: " + name + "](rdc) "); } if (_hooks.TryGetValue(name, out var hookList)) { foreach (var hook in hookList) { try { var triggerStateKey = hook.Owner.ToString() + hookTriggerMode; if (HooksTriggerState.ContainsKey(triggerStateKey) && hookTriggerMode == HookTriggerMode.FirstTimeOnly) { break; } HooksTriggerState.AddOrReplace(triggerStateKey, hookTriggerMode); if (context.ShellEnv.IsOptionSetted(ShellEnvironmentVar.debug_enableHookTrace)) { context.Out.Echo(context.ShellEnv.Colors.Log + $"[hook '{hook.Name}' handled by: '{hook.Owner}.{hook.Method}'](rdc) "); } hook.Method.Invoke(hook.Owner, new object[] { context }); callBack?.Invoke(hook.Owner); } catch (Exception ex) { var m = $"hook '{hook.Owner}.{hook.Method}' has crashed: {ex.InnerException?.Message}"; context.Out.Errorln(m); context.CommandLineProcessor.LogError(m); } } } }
/// <summary> /// Queries the transaction data for a TradableAsset. /// </summary> /// <param name="query1"> The first query for the TradableAsset's transaction data. </param> /// <param name="query2"> The second query for the TradableAsset's transaction data. </param> private void QueryTransactionData(AssetTransactionQuery query1, AssetTransactionQuery query2) { query1.Query?.Invoke().OnSuccess(txData1 => { query2.Query?.Invoke().OnSuccess(txData2 => { Observable.Start(() => { query1.ProcessTransactionList(txData1, query1.AssetAddress, query1.IgnoreReceipt); query2.ProcessTransactionList(txData2, query2.AssetAddress, query2.IgnoreReceipt); }).SubscribeOnMainThread().Subscribe(_ => { addressLastUpdatedTimes.AddOrReplace(query1.AssetAddress, DateTimeUtils.GetCurrentUnixTime()); MainThreadExecutor.QueueAction(() => OnTransactionsAdded?.Invoke()); isScraping = false; }); }); }); }
/***************************************************/ public static BH.oM.Geometry.SettingOut.Grid GridFromRevit(this MultiSegmentGrid revitGrid, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null) { settings = settings.DefaultIfNull(); oM.Geometry.SettingOut.Grid grid = refObjects.GetValue <oM.Geometry.SettingOut.Grid>(revitGrid.Id); if (grid != null) { return(grid); } List <Grid> gridSegments = revitGrid.GetGridIds().Select(x => revitGrid.Document.GetElement(x) as Grid).ToList(); if (gridSegments.Count == 0) { return(null); } else if (gridSegments.Count == 1) { return(gridSegments[0].GridFromRevit(settings, refObjects)); } else { List <BH.oM.Geometry.PolyCurve> joinedGridCurves = BH.Engine.Geometry.Compute.IJoin(gridSegments.Select(x => x.Curve.IFromRevit()).ToList()); if (joinedGridCurves.Count != 1) { BH.Engine.Reflection.Compute.RecordError(String.Format("Revit grid consists of disjoint segments. Element id: {0}", revitGrid.Id)); return(null); } grid = BH.Engine.Geometry.SettingOut.Create.Grid(joinedGridCurves[0]); grid.Name = revitGrid.Name; } //Set identifiers, parameters & custom data grid.SetIdentifiers(revitGrid); grid.CopyParameters(revitGrid, settings.ParameterSettings); grid.SetProperties(revitGrid, settings.ParameterSettings); refObjects.AddOrReplace(revitGrid.Id, grid); return(grid); }
/// <summary> /// Sends and individual digest email to the specified person. /// </summary> /// <param name="systemCommunication">The system communication.</param> /// <param name="mergeObjects">The Lava merge objects.</param> /// <param name="person">The person who should receive the email.</param> /// <param name="regionalGroup">The regional group that this digest email represents.</param> private void SendDigestEmail(SystemCommunication systemCommunication, Dictionary <string, object> mergeObjects, Person person, Group regionalGroup) { mergeObjects.AddOrReplace("Person", person); var recipient = new RockEmailMessageRecipient(person, mergeObjects); var message = new RockEmailMessage(systemCommunication); message.Subject = $"'{regionalGroup.Name}' Group Attendance Digest"; message.SetRecipients(new List <RockEmailMessageRecipient> { recipient }); message.Send(out List <string> errorMessages); if (!errorMessages.Any()) { _digestsSentCount++; return; } _errors.Add($"Unable to send '{regionalGroup.Name}' digest to '{person.Email}'."); }
/// <summary> /// 资源上传入口 /// </summary> /// <param name="resourcesDic"></param> /// <param name="_cb"></param> /// <param name="errorCallBack"></param> public void OnUpdateToServer(List <IResourceNode> _pRes, Action _cb, Action <string> _eCb) { m_qUpdate = new Queue <IResourceNode>(_pRes); key_rNode.Clear(); m_pErrorNode.Clear(); for (int i = 0; i < _pRes.Count; i++) { string strKey = _pRes[i].GetCrc() + _pRes[i].GetName(); key_rNode.AddOrReplace(strKey, _pRes[i]); } if (m_qUpdate.Count > 0) { LogicUtils.Instance.OnShowWaiting(1, "资源上传中...", false, m_qUpdate.Count); UpdateToServer(_cb, _eCb); } else { _cb(); } }
private ChainedBlock SetTipNoLock(ChainedBlock block) { int height = Tip == null ? -1 : Tip.Height; foreach (var orphaned in EnumerateThisToFork(block)) { _BlocksById.Remove(orphaned.HashBlock); _BlocksByHeight.Remove(orphaned.Height); height--; } var fork = GetBlockNoLock(height); foreach (var newBlock in block.EnumerateToGenesis() .TakeWhile(c => c != fork)) { _BlocksById.AddOrReplace(newBlock.HashBlock, newBlock); _BlocksByHeight.AddOrReplace(newBlock.Height, newBlock); } _Tip = block; return(fork); }
/***************************************************/ /**** Public Methods ****/ /***************************************************/ public static BH.oM.Geometry.SettingOut.Grid GridFromRevit(this Grid revitGrid, RevitSettings settings = null, Dictionary <string, List <IBHoMObject> > refObjects = null) { settings = settings.DefaultIfNull(); oM.Geometry.SettingOut.Grid grid = refObjects.GetValue <oM.Geometry.SettingOut.Grid>(revitGrid.Id); if (grid != null) { return(grid); } grid = BH.Engine.Geometry.SettingOut.Create.Grid(revitGrid.Curve.IFromRevit()); grid.Name = revitGrid.Name; //Set identifiers, parameters & custom data grid.SetIdentifiers(revitGrid); grid.CopyParameters(revitGrid, settings.ParameterSettings); grid.SetProperties(revitGrid, settings.ParameterSettings); refObjects.AddOrReplace(revitGrid.Id, grid); return(grid); }
private void ShowDetail() { _mode = "VIEW"; pnlEdit.Visible = false; string json = GetAttributeValue( "Forms" ); if ( string.IsNullOrWhiteSpace( json ) ) { FormState = new List<AttributeForm>(); } else { FormState = JsonConvert.DeserializeObject<List<AttributeForm>>( json ); } if ( FormState.Count > 0 ) { pnlView.Visible = true; AttributeValueState = new Dictionary<int, string>(); if ( CurrentPerson != null ) { if ( CurrentPerson.Attributes == null ) { CurrentPerson.LoadAttributes(); } foreach ( var form in FormState ) { foreach ( var field in form.Fields .Where( a => a.AttributeId.HasValue && a.ShowCurrentValue == true ) ) { var attributeCache = AttributeCache.Read( field.AttributeId.Value ); if ( attributeCache != null ) { AttributeValueState.AddOrReplace( field.AttributeId.Value, CurrentPerson.GetAttributeValue( attributeCache.Key ) ); } } } } ProgressBarSteps = FormState.Count(); CurrentPageIndex = 0; ShowPage(); } else { nbMain.Title = "No Forms/Fields"; nbMain.Text = "No forms or fields have been configured. Use the Block Configuration to add new forms and fields."; nbMain.NotificationBoxType = NotificationBoxType.Warning; nbMain.Visible = true; } }
/// <summary> /// Parses the markup. /// </summary> /// <param name="markup">The markup.</param> /// <param name="context">The context.</param> /// <returns></returns> /// <exception cref="System.Exception">No parameters were found in your command. The syntax for a parameter is parmName:'' (note that you must use single quotes).</exception> private Dictionary<string, string> ParseMarkup( string markup, Context context ) { // first run lava across the inputted markup var internalMergeFields = new Dictionary<string, object>(); // get variables defined in the lava source foreach ( var scope in context.Scopes ) { foreach ( var item in scope ) { internalMergeFields.AddOrReplace( item.Key, item.Value ); } } // get merge fields loaded by the block or container foreach( var environment in context.Environments ) { foreach ( var item in environment ) { internalMergeFields.AddOrReplace( item.Key, item.Value ); } } var resolvedMarkup = markup.ResolveMergeFields( internalMergeFields ); var parms = new Dictionary<string, string>(); parms.Add( "method", "GET" ); parms.Add( "return", "results" ); parms.Add( "basicauth", "" ); parms.Add( "parameters", "" ); parms.Add( "headers", "" ); parms.Add( "responsecontenttype", "json" ); parms.Add( "body", "" ); parms.Add( "requesttype", "text/plain" ); var markupItems = Regex.Matches( resolvedMarkup, "(.*?:'[^']+')" ) .Cast<Match>() .Select( m => m.Value ) .ToList(); foreach ( var item in markupItems ) { var itemParts = item.ToString().Split( new char[] { ':' }, 2 ); if ( itemParts.Length > 1 ) { parms.AddOrReplace( itemParts[0].Trim().ToLower(), itemParts[1].Trim().Substring( 1, itemParts[1].Length - 2 ) ); } } return parms; }
/// <summary> /// Parses the markup. /// </summary> /// <param name="markup">The markup.</param> /// <param name="context">The context.</param> /// <returns></returns> /// <exception cref="System.Exception">No parameters were found in your command. The syntax for a parameter is parmName:'' (note that you must use single quotes).</exception> private Dictionary<string, string> ParseMarkup( string markup, Context context ) { // first run lava across the inputted markup var internalMergeFields = new Dictionary<string, object>(); // get variables defined in the lava source foreach ( var scope in context.Scopes ) { foreach ( var item in scope ) { internalMergeFields.AddOrReplace( item.Key, item.Value ); } } // get merge fields loaded by the block or container if ( context.Environments.Count > 0 ) { foreach ( var item in context.Environments[0] ) { internalMergeFields.AddOrReplace( item.Key, item.Value ); } } var resolvedMarkup = markup.ResolveMergeFields( internalMergeFields ); var parms = new Dictionary<string, string>(); parms.Add( "iterator", "results" ); var markupItems = Regex.Matches( resolvedMarkup, "(.*?:'[^']+')" ) .Cast<Match>() .Select( m => m.Value ) .ToList(); if ( markupItems.Count == 0 ) { throw new Exception( "No parameters were found in your command. The syntax for a parameter is parmName:'' (note that you must use single quotes)." ); } foreach ( var item in markupItems ) { var itemParts = item.ToString().Split( new char[] { ':' }, 2 ); if ( itemParts.Length > 1 ) { parms.AddOrReplace( itemParts[0].Trim().ToLower(), itemParts[1].Trim().Substring( 1, itemParts[1].Length - 2 ) ); } } return parms; }
private Dictionary<string, string> GetVariables(string filePath ) { Dictionary<string, string> overrides = new Dictionary<string, string>(); if ( File.Exists( filePath ) ) { foreach ( string line in File.ReadLines( filePath ) ) { if ( line.Replace(" ", "").Contains( "/*Custom CSS*/" ) ) { break; } char[] delimiters = new char[] { ':', ';' }; string[] variableParts = line.Split( delimiters ); if (variableParts.Length > 2 ) { overrides.AddOrReplace( variableParts[0].Replace( "@", "" ).ToLower(), variableParts[1].Trim() ); } } } return overrides; }
private static string TableHeaderCell(SmartTableColumnModel column) { var cell = new TagBuilder("th"); IDictionary<string, object> htmlAttributes = new Dictionary<string, object>(); if (!string.IsNullOrEmpty(column.field)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.field), column.field); if (!string.IsNullOrEmpty(column.horizontalAlign)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.horizontalAlign), column.horizontalAlign); if (!string.IsNullOrEmpty(column.align)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.align), column.align); if (!string.IsNullOrEmpty(column.align)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.align), column.align); if (!string.IsNullOrEmpty(column.sorter)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.sorter), column.sorter); if (!string.IsNullOrEmpty(column.formatter)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.formatter), column.formatter); if (column.radio) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.radio), column.radio.ToString().ToLower()); if (!column.switchable) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.switchable), column.switchable.ToString().ToLower()); if (!column.visible) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.visible), column.visible.ToString().ToLower()); if (column.checkbox) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.checkbox), column.checkbox.ToString().ToLower()); if (!string.IsNullOrEmpty(column.events)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.events), column.events); if (column.width != 0) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.width), column.width.ToString()); if (!string.IsNullOrEmpty(column.titleTooltip)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.titleTooltip), column.titleTooltip); if (!string.IsNullOrEmpty(column.cssClass)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.cssClass), column.cssClass); if (column.rowSpan != 0) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.rowSpan), column.rowSpan.ToString()); if (column.colspan != 0) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.colspan), column.colspan.ToString()); if (column.sortable) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.sortable), column.sortable.ToString().ToLower()); if (!column.searchable) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.searchable), column.searchable.ToString().ToLower()); if (!column.searchFormatter) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.searchFormatter), column.searchFormatter.ToString().ToLower()); if (!string.IsNullOrEmpty(column.cellStyle)) htmlAttributes.AddOrReplace(column.HtmlAttr(() => column.cellStyle), column.cellStyle); if (!string.IsNullOrEmpty(column.fieldLabel)) cell.InnerHtml = column.fieldLabel; cell.MergeAttributes(htmlAttributes.FormatHtmlAttributes()); return cell.ToString(); }
/// <summary> /// Parses the markup. /// </summary> /// <param name="markup">The markup.</param> /// <param name="context">The context.</param> /// <returns></returns> /// <exception cref="System.Exception">No parameters were found in your command. The syntax for a parameter is parmName:'' (note that you must use single quotes).</exception> private Dictionary<string, string> ParseMarkup( string markup, Context context ) { // first run lava across the inputted markup var internalMergeFields = new Dictionary<string, object>(); // get variables defined in the lava source foreach ( var scope in context.Scopes ) { foreach ( var item in scope ) { internalMergeFields.AddOrReplace( item.Key, item.Value ); } } // get merge fields loaded by the block or container if ( context.Environments.Count > 0 ) { foreach ( var item in context.Environments[0] ) { internalMergeFields.AddOrReplace( item.Key, item.Value ); } } var resolvedMarkup = markup.ResolveMergeFields( internalMergeFields ); var parms = new Dictionary<string, string>(); parms.Add( "iterator", string.Format( "{0}Items", _entityName ) ); var markupItems = Regex.Matches( resolvedMarkup, "(.*?:'[^']+')" ) .Cast<Match>() .Select( m => m.Value ) .ToList(); if ( markupItems.Count == 0 ) { throw new Exception( "No parameters were found in your command. The syntax for a parameter is parmName:'' (note that you must use single quotes)." ); } foreach ( var item in markupItems ) { var itemParts = item.ToString().Split( new char[] { ':' }, 2 ); if ( itemParts.Length > 1 ) { parms.AddOrReplace( itemParts[0].Trim().ToLower(), itemParts[1].Trim().Substring( 1, itemParts[1].Length - 2 ) ); } } // override any dynamic parameters List<string> dynamicFilters = new List<string>(); // will be used to process dynamic filters if ( parms.ContainsKey( "dynamicparameters" ) ) { var dynamicParms = parms["dynamicparameters"]; var dynamicParmList = dynamicParms.Split( ',' ) .Select( x => x.Trim() ) .Where( x => !string.IsNullOrWhiteSpace( x ) ) .ToList(); foreach ( var dynamicParm in dynamicParmList ) { if ( HttpContext.Current.Request[dynamicParm] != null ) { var dynamicParmValue = HttpContext.Current.Request[dynamicParm].ToString(); switch ( dynamicParm ) { case "id": case "limit": case "offset": case "dataview": case "expression": case "sort": case "iterator": case "checksecurity": case "includedeceased": { parms.AddOrReplace( dynamicParm, dynamicParmValue ); break; } default: { dynamicFilters.Add( dynamicParm ); break; } } } } parms.AddOrReplace( "dynamicparameters", string.Join( ",", dynamicFilters ) ); } return parms; }
/// <summary> /// Binds the registrations grid. /// </summary> private void BindRegistrationsGrid() { int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) ); var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value ); decimal cost = instance.RegistrationTemplate.Cost; if ( instance.RegistrationTemplate.SetCostOnInstance ?? false ) { cost = instance.Cost ?? 0.0m; } _instanceHasCost = cost > 0.0m; var qry = new RegistrationService( rockContext ) .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" ) .AsNoTracking() .Where( r => r.RegistrationInstanceId == instanceId.Value && !r.IsTemporary ); if ( drpRegistrationDateRange.LowerValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value ); } if ( drpRegistrationDateRange.UpperValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) ) { string pfname = tbRegistrationRegisteredByFirstName.Text; qry = qry.Where( r => r.FirstName.StartsWith( pfname ) || r.PersonAlias.Person.NickName.StartsWith( pfname ) || r.PersonAlias.Person.FirstName.StartsWith( pfname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) ) { string plname = tbRegistrationRegisteredByLastName.Text; qry = qry.Where( r => r.LastName.StartsWith( plname ) || r.PersonAlias.Person.LastName.StartsWith( plname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) ) { string rfname = tbRegistrationRegistrantFirstName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.NickName.StartsWith( rfname ) || p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) ) { string rlname = tbRegistrationRegistrantLastName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.LastName.StartsWith( rlname ) ) ); } // If filtering on payment status, need to do some sub-querying... if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null ) { // Get all the registrant costs var rCosts = new Dictionary<int, decimal>(); qry.ToList() .Select( r => new { RegistrationId = r.Id, DiscountCosts = r.Registrants.Sum( p => (decimal?)( p.DiscountedCost( r.DiscountPercentage, r.DiscountAmount) ) ) ?? 0.0m, } ).ToList() .ForEach( c => rCosts.AddOrReplace( c.RegistrationId, c.DiscountCosts ) ); var rPayments = new Dictionary<int, decimal>(); new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && rCosts.Keys.Contains( d.EntityId.Value ) ) .Select( d => new { RegistrationId = d.EntityId.Value, Payment = d.Amount } ) .ToList() .GroupBy( d => d.RegistrationId ) .Select( d => new { RegistrationId = d.Key, Payments = d.Sum( p => p.Payment ) } ) .ToList() .ForEach( p => rPayments.AddOrReplace( p.RegistrationId, p.Payments ) ); var rPmtSummary = rCosts .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new { RegistrationId = c.Key, Costs = c.Value, Payments = p.Value } ) .ToList(); var ids = new List<int>(); if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" ) { ids = rPmtSummary .Where( r => r.Costs <= r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } else { ids = rPmtSummary .Where( r => r.Costs > r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } qry = qry.Where( r => ids.Contains( r.Id ) ); } SortProperty sortProperty = gRegistrations.SortProperty; if ( sortProperty != null ) { // If sorting by Total Cost or Balance Due, the database query needs to be run first without ordering, // and then ordering needs to be done in memory since TotalCost and BalanceDue are not databae fields. if ( sortProperty.Property == "TotalCost" ) { if ( sortProperty.Direction == SortDirection.Ascending ) { gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.TotalCost ).AsQueryable() ); } else { gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.TotalCost ).AsQueryable() ); } } else if ( sortProperty.Property == "BalanceDue" ) { if ( sortProperty.Direction == SortDirection.Ascending ) { gRegistrations.SetLinqDataSource( qry.ToList().OrderBy( r => r.BalanceDue ).AsQueryable() ); } else { gRegistrations.SetLinqDataSource( qry.ToList().OrderByDescending( r => r.BalanceDue ).AsQueryable() ); } } else { gRegistrations.SetLinqDataSource( qry.Sort( sortProperty ) ); } } else { gRegistrations.SetLinqDataSource( qry.OrderByDescending( r => r.CreatedDateTime ) ); } // Get all the payments for any registrations being displayed on the current page. // This is used in the RowDataBound event but queried now so that each row does // not have to query for the data. var currentPageRegistrations = gRegistrations.DataSource as List<Registration>; if ( currentPageRegistrations != null && registrationEntityType != null ) { var registrationIds = currentPageRegistrations .Select( r => r.Id ) .ToList(); RegistrationPayments = new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && registrationIds.Contains( d.EntityId.Value ) ) .ToList(); } var discountCodeHeader = gRegistrations.Columns.GetColumnByHeaderText( "Discount Code" ); if ( discountCodeHeader != null ) { discountCodeHeader.Visible = GetAttributeValue( "DisplayDiscountCodes" ).AsBoolean(); } gRegistrations.DataBind(); } } }
/// <summary> /// Gets the filter value control. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> /// <param name="required">if set to <c>true</c> [required].</param> /// <returns></returns> public override Control FilterValueControl( Dictionary<string, ConfigurationValue> configurationValues, string id, bool required ) { var overrideConfigValues = new Dictionary<string, ConfigurationValue>(); foreach ( var keyVal in configurationValues ) { overrideConfigValues.Add( keyVal.Key, keyVal.Value ); } overrideConfigValues.AddOrReplace( ALLOW_MULTIPLE_KEY, new ConfigurationValue( "false" ) ); return base.FilterValueControl( overrideConfigValues, id, required ); }
static Op() { _ValidOpCode = GetValidOpCode(); _OpcodeByName = new Dictionary<string, OpcodeType>(); foreach(var code in Enum.GetValues(typeof(OpcodeType)).Cast<OpcodeType>().Distinct()) { var name = GetOpName(code); if(name != "OP_UNKNOWN") _OpcodeByName.AddOrReplace(name, code); } _OpcodeByName.AddOrReplace("OP_TRUE", OpcodeType.OP_1); _OpcodeByName.AddOrReplace("OP_FALSE", OpcodeType.OP_0); _OpcodeByName.AddOrReplace("OP_CHECKLOCKTIMEVERIFY", OpcodeType.OP_CHECKLOCKTIMEVERIFY); _OpcodeByName.AddOrReplace("OP_HODL", OpcodeType.OP_CHECKLOCKTIMEVERIFY); _OpcodeByName.AddOrReplace("OP_NOP2", OpcodeType.OP_CHECKLOCKTIMEVERIFY); _OpcodeByName.AddOrReplace("OP_CHECKSEQUENCEVERIFY", OpcodeType.OP_CHECKSEQUENCEVERIFY); _OpcodeByName.AddOrReplace("OP_NOP3", OpcodeType.OP_CHECKSEQUENCEVERIFY); foreach(var op in new[] { new object[]{"OP_0", OpcodeType.OP_0}, new object[]{"OP_1", OpcodeType.OP_1}, new object[]{"OP_2", OpcodeType.OP_2}, new object[]{"OP_3", OpcodeType.OP_3}, new object[]{"OP_4", OpcodeType.OP_4}, new object[]{"OP_5", OpcodeType.OP_5}, new object[]{"OP_6", OpcodeType.OP_6}, new object[]{"OP_7", OpcodeType.OP_7}, new object[]{"OP_8", OpcodeType.OP_8}, new object[]{"OP_9", OpcodeType.OP_9} }) { _OpcodeByName.AddOrReplace((string)op[0], (OpcodeType)op[1]); } }
/// <summary> /// Binds the grid. /// </summary> private void BindGrid() { int? metricId = hfMetricId.Value.AsIntegerOrNull(); if ( !metricId.HasValue ) { return; } var rockContext = new RockContext(); SortProperty sortProperty = gMetricValues.SortProperty; MetricValueService metricValueService = new MetricValueService( rockContext ); var qry = metricValueService.Queryable(); qry = qry.Where( a => a.MetricId == metricId ); var entityColumn = gMetricValues.Columns.OfType<BoundField>().FirstOrDefault( a => a.DataField == "EntityId" ); var metric = new MetricService( rockContext ).Get( metricId ?? 0 ); entityColumn.Visible = metric != null && metric.EntityTypeId.HasValue; if ( metric != null ) { _entityNameLookup = new Dictionary<int, string>(); var entityTypeCache = EntityTypeCache.Read( metric.EntityTypeId ?? 0 ); if ( entityTypeCache != null ) { entityColumn.HeaderText = entityTypeCache.FriendlyName; IQueryable<IEntity> entityQry = null; if ( entityTypeCache.GetEntityType() == typeof( Rock.Model.Group ) ) { // special case for Group since there could be a very large number (especially if you include families), so limit to GroupType.ShowInGroupList entityQry = new GroupService( rockContext ).Queryable().Where( a => a.GroupType.ShowInGroupList ); } else { Type[] modelType = { entityTypeCache.GetEntityType() }; Type genericServiceType = typeof( Rock.Data.Service<> ); Type modelServiceType = genericServiceType.MakeGenericType( modelType ); var serviceInstance = Activator.CreateInstance( modelServiceType, new object[] { rockContext } ) as IService; MethodInfo qryMethod = serviceInstance.GetType().GetMethod( "Queryable", new Type[] { } ); entityQry = qryMethod.Invoke( serviceInstance, new object[] { } ) as IQueryable<IEntity>; } if ( entityQry != null ) { var entityList = entityQry.ToList(); foreach ( var e in entityList ) { _entityNameLookup.AddOrReplace( e.Id, e.ToString() ); } } } } var drp = new DateRangePicker(); drp.DelimitedValues = gfMetricValues.GetUserPreference( "Date Range" ); if ( drp.LowerValue.HasValue ) { qry = qry.Where( a => a.MetricValueDateTime >= drp.LowerValue.Value ); } if ( drp.UpperValue.HasValue ) { DateTime upperDate = drp.UpperValue.Value.Date.AddDays( 1 ); qry = qry.Where( a => a.MetricValueDateTime < upperDate ); } var metricValueType = gfMetricValues.GetUserPreference( "Goal/Measure" ).ConvertToEnumOrNull<MetricValueType>(); if ( metricValueType.HasValue ) { qry = qry.Where( a => a.MetricValueType == metricValueType.Value ); } var entityParts = gfMetricValues.GetUserPreference( this.EntityPreferenceKey ).Split( '|' ); if ( entityParts.Length == 2 ) { if ( entityParts[0].AsInteger() == metric.EntityTypeId ) { var entityId = entityParts[1].AsIntegerOrNull(); if ( entityId.HasValue ) { qry = qry.Where( a => a.EntityId == entityId ); } } } if ( sortProperty != null ) { gMetricValues.DataSource = qry.Sort( sortProperty ).ToList(); } else { gMetricValues.DataSource = qry.OrderBy( s => s.Order ).ThenBy( s => s.MetricValueDateTime ).ThenBy( s => s.YValue ).ThenBy( s => s.XValue ).ToList(); } gMetricValues.DataBind(); }
/// <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 ); if ( !Page.IsPostBack ) { string connectionOpportunityId = PageParameter( "ConnectionOpportunityId" ); if ( !string.IsNullOrWhiteSpace( connectionOpportunityId ) ) { ShowDetail( connectionOpportunityId.AsInteger() ); } else { pnlDetails.Visible = false; } } else { nbIncorrectOpportunity.Visible = false; nbNotAllowedToEdit.Visible = false; nbInvalidGroupType.Visible = false; nbInvalidGroupTypes.Visible = false; DefaultConnectors = new Dictionary<int, int>(); foreach ( var item in lvDefaultConnectors.Items ) { var hfDefaultConnector = item.FindControl( "hfDefaultConnector" ) as HiddenField; var ddlDefaultConnector = item.FindControl( "ddlDefaultConnector" ) as RockDropDownList; if ( hfDefaultConnector != null && ddlDefaultConnector != null ) { int? campusId = hfDefaultConnector.Value.AsIntegerOrNull(); int? defaultConnectorPersonAliasId = ddlDefaultConnector.SelectedValueAsInt(); if ( campusId.HasValue && defaultConnectorPersonAliasId.HasValue ) { DefaultConnectors.AddOrReplace( campusId.Value, defaultConnectorPersonAliasId.Value ); } } } ShowOpportunityAttributes(); } }
/// <summary> /// Shows the edit details. /// </summary> /// <param name="connectionOpportunity">The connectionOpportunity.</param> private void ShowEditDetails( ConnectionOpportunity connectionOpportunity ) { if ( connectionOpportunity.Id == 0 ) { lReadOnlyTitle.Text = ActionTitle.Add( ConnectionOpportunity.FriendlyTypeName ).FormatAsHtmlTitle(); connectionOpportunity.IconCssClass = "fa fa-long-arrow-right"; hlStatus.Visible = false; } else { lReadOnlyTitle.Text = connectionOpportunity.Name.FormatAsHtmlTitle(); if ( connectionOpportunity.IsActive ) { hlStatus.Text = "Active"; hlStatus.LabelType = LabelType.Success; } else { hlStatus.Text = "Inactive"; hlStatus.LabelType = LabelType.Campus; } } lIcon.Text = string.Format( "<i class='{0}'></i>", connectionOpportunity.IconCssClass ); tbName.Text = connectionOpportunity.Name; tbPublicName.Text = connectionOpportunity.PublicName; tbIconCssClass.Text = connectionOpportunity.IconCssClass; htmlSummary.Text = connectionOpportunity.Summary; htmlDescription.Text = connectionOpportunity.Description; cbIsActive.Checked = connectionOpportunity.IsActive; tglUseAllGroupsOfGroupType.Checked = connectionOpportunity.UseAllGroupsOfType; WorkflowsState = new List<WorkflowTypeStateObj>(); foreach ( var connectionWorkflow in connectionOpportunity.ConnectionWorkflows ) { WorkflowsState.Add( new WorkflowTypeStateObj( connectionWorkflow ) ); } foreach ( var connectionWorkflow in connectionOpportunity.ConnectionType.ConnectionWorkflows ) { WorkflowsState.Add( new WorkflowTypeStateObj( connectionWorkflow ) ); } GroupsState = new List<GroupStateObj>(); foreach( var opportunityGroup in connectionOpportunity.ConnectionOpportunityGroups ) { GroupsState.Add( new GroupStateObj( opportunityGroup ) ); } ConnectorGroupsState = new List<GroupStateObj>(); foreach( var connectorGroup in connectionOpportunity.ConnectionOpportunityConnectorGroups ) { ConnectorGroupsState.Add( new GroupStateObj( connectorGroup ) ); } imgupPhoto.BinaryFileId = connectionOpportunity.PhotoId; DefaultConnectors = new Dictionary<int, int>(); foreach( var campus in connectionOpportunity.ConnectionOpportunityCampuses .Where( c => c.DefaultConnectorPersonAlias != null && c.DefaultConnectorPersonAlias.Person != null ) ) { var personAlias = campus.DefaultConnectorPersonAlias.Person.PrimaryAlias; if (personAlias != null ) { DefaultConnectors.AddOrReplace( campus.CampusId, personAlias.Id ); } } LoadDropDowns( connectionOpportunity ); ShowOpportunityAttributes(); BindGroupGrid(); BindWorkflowGrid(); BindConnectorGroupsGrid(); }
/// <summary> /// Parses the markup. /// </summary> /// <param name="markup">The markup.</param> /// <returns></returns> /// <exception cref="System.Exception">No parameters were found in your command. The syntax for a parameter is parmName:'' (note that you must use single quotes).</exception> private Dictionary<string, string> ParseMarkup( string markup ) { var parms = new Dictionary<string, string>(); var markupItems = Regex.Matches( markup, "(.*?:'[^']+')" ) .Cast<Match>() .Select( m => m.Value ) .ToList(); foreach ( var item in markupItems ) { var itemParts = item.ToString().Split( new char[] { ':' }, 2 ); if ( itemParts.Length > 1 ) { parms.AddOrReplace( itemParts[0].Trim().ToLower(), itemParts[1].Trim().Substring( 1, itemParts[1].Length - 2 ) ); } } return parms; }
/// <summary> /// Loads the chart and any visible grids /// </summary> public void LoadChartAndGrids() { pnlUpdateMessage.Visible = false; pnlResults.Visible = true; lcAmount.ShowTooltip = true; if ( this.DetailPageGuid.HasValue ) { lcAmount.ChartClick += lcAmount_ChartClick; } bcAmount.ShowTooltip = true; if ( this.DetailPageGuid.HasValue ) { bcAmount.ChartClick += lcAmount_ChartClick; } var dataSourceUrl = "~/api/FinancialTransactionDetails/GetChartData"; var dataSourceParams = new Dictionary<string, object>(); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues ); if ( dateRange.Start.HasValue ) { dataSourceParams.AddOrReplace( "startDate", dateRange.Start.Value.ToString( "o" ) ); } if ( dateRange.End.HasValue ) { dataSourceParams.AddOrReplace( "endDate", dateRange.End.Value.ToString( "o" ) ); } if ( nreAmount.LowerValue.HasValue ) { dataSourceParams.AddOrReplace( "minAmount", nreAmount.LowerValue.Value.ToString() ); } if ( nreAmount.UpperValue.HasValue ) { dataSourceParams.AddOrReplace( "maxAmount", nreAmount.UpperValue.Value.ToString() ); } var groupBy = hfGroupBy.Value.ConvertToEnumOrNull<ChartGroupBy>() ?? ChartGroupBy.Week; lcAmount.TooltipFormatter = null; switch ( groupBy ) { case ChartGroupBy.Week: { lcAmount.Options.xaxis.tickSize = new string[] { "7", "day" }; lcAmount.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = 'Weekend of <br />' + itemDate.toLocaleDateString(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue.toLocaleString() || item.series.chartData[item.dataIndex].YValueTotal.toLocaleString() || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case ChartGroupBy.Month: { lcAmount.Options.xaxis.tickSize = new string[] { "1", "month" }; lcAmount.TooltipFormatter = @" function(item) { var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = month_names[itemDate.getMonth()] + ' ' + itemDate.getFullYear(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue.toLocaleString() || item.series.chartData[item.dataIndex].YValueTotal.toLocaleString() || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case ChartGroupBy.Year: { lcAmount.Options.xaxis.tickSize = new string[] { "1", "year" }; lcAmount.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = itemDate.getFullYear(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue.toLocaleString() || item.series.chartData[item.dataIndex].YValueTotal.toLocaleString() || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; } dataSourceParams.AddOrReplace( "groupBy", hfGroupBy.Value.AsInteger() ); var selectedCurrencyTypeIds = cblCurrencyTypes.SelectedValuesAsInt; if ( selectedCurrencyTypeIds.Any() ) { dataSourceParams.AddOrReplace( "currencyTypeIds", selectedCurrencyTypeIds.AsDelimited( "," ) ); } var selectedTxnSourceIds = cblTransactionSource.SelectedValuesAsInt; if ( selectedTxnSourceIds.Any() ) { dataSourceParams.AddOrReplace( "sourceTypeIds", selectedTxnSourceIds.AsDelimited( "," ) ); } var accountIds = new List<int>(); foreach ( var cblAccounts in phAccounts.Controls.OfType<RockCheckBoxList>() ) { accountIds.AddRange( cblAccounts.SelectedValuesAsInt ); } if ( accountIds.Any() ) { dataSourceParams.AddOrReplace( "accountIds", accountIds.AsDelimited( "," ) ); } var selectedDataViewId = dvpDataView.SelectedValue.AsIntegerOrNull(); if ( selectedDataViewId.HasValue ) { dataSourceParams.AddOrReplace( "dataViewId", selectedDataViewId.Value.ToString() ); } dataSourceParams.AddOrReplace( "graphBy", hfGraphBy.Value.AsInteger() ); SaveSettingsToUserPreferences(); dataSourceUrl += "?" + dataSourceParams.Select( s => string.Format( "{0}={1}", s.Key, s.Value ) ).ToList().AsDelimited( "&" ); lcAmount.DataSourceUrl = this.ResolveUrl( dataSourceUrl ); bcAmount.TooltipFormatter = lcAmount.TooltipFormatter; bcAmount.DataSourceUrl = this.ResolveUrl( dataSourceUrl ); if ( pnlChart.Visible ) { var chartData = GetChartData(); var singleDateTime = chartData.GroupBy( a => a.DateTimeStamp ).Count() == 1; bcAmount.Visible = singleDateTime; lcAmount.Visible = !singleDateTime; if ( pnlChartAmountGrid.Visible ) { BindChartAmountGrid( chartData ); } } if ( pnlDetails.Visible ) { BindGiversGrid(); } }
/// <summary> /// Binds the registrations grid. /// </summary> private void BindRegistrationsGrid() { int? instanceId = hfRegistrationInstanceId.Value.AsIntegerOrNull(); if ( instanceId.HasValue ) { using ( var rockContext = new RockContext() ) { var registrationEntityType = EntityTypeCache.Read( typeof( Rock.Model.Registration ) ); var instance = new RegistrationInstanceService( rockContext ).Get( instanceId.Value ); _instanceHasCost = instance != null && instance.RegistrationTemplate.Cost > 0.0m; var qry = new RegistrationService( rockContext ) .Queryable( "PersonAlias.Person,Registrants.PersonAlias.Person,Registrants.Fees.RegistrationTemplateFee" ) .AsNoTracking() .Where( r => r.RegistrationInstanceId == instanceId.Value ); if ( drpRegistrationDateRange.LowerValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value >= drpRegistrationDateRange.LowerValue.Value ); } if ( drpRegistrationDateRange.UpperValue.HasValue ) { qry = qry.Where( r => r.CreatedDateTime.HasValue && r.CreatedDateTime.Value <= drpRegistrationDateRange.UpperValue.Value ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByFirstName.Text ) ) { string pfname = tbRegistrationRegisteredByFirstName.Text; qry = qry.Where( r => r.FirstName.StartsWith( pfname ) || r.PersonAlias.Person.NickName.StartsWith( pfname ) || r.PersonAlias.Person.FirstName.StartsWith( pfname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegisteredByLastName.Text ) ) { string plname = tbRegistrationRegisteredByLastName.Text; qry = qry.Where( r => r.LastName.StartsWith( plname ) || r.PersonAlias.Person.LastName.StartsWith( plname ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantFirstName.Text ) ) { string rfname = tbRegistrationRegistrantFirstName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.NickName.StartsWith( rfname ) || p.PersonAlias.Person.FirstName.StartsWith( rfname ) ) ); } if ( !string.IsNullOrWhiteSpace( tbRegistrationRegistrantLastName.Text ) ) { string rlname = tbRegistrationRegistrantLastName.Text; qry = qry.Where( r => r.Registrants.Any( p => p.PersonAlias.Person.LastName.StartsWith( rlname ) ) ); } // If filtering on payment status, need to do some sub-querying... if ( ddlRegistrationPaymentStatus.SelectedValue != "" && registrationEntityType != null ) { // Get all the registrant costs var rCosts = new Dictionary<int, decimal>(); qry .Select( r => new { RegistrationId = r.Id, Costs = r.Registrants.Sum( p => p.Cost ), Fees = r.Registrants.SelectMany( p => p.Fees ).Sum( f => f.Cost ) } ).ToList() .ForEach( c => rCosts.AddOrReplace( c.RegistrationId, c.Costs + c.Fees ) ); var rPayments = new Dictionary<int, decimal>(); new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && rCosts.Keys.Contains( d.EntityId.Value ) ) .Select( d => new { RegistrationId = d.EntityId.Value, Payment = d.Amount } ) .ToList() .GroupBy( d => d.RegistrationId ) .Select( d => new { RegistrationId = d.Key, Payments = d.Sum( p => p.Payment ) } ) .ToList() .ForEach( p => rPayments.AddOrReplace( p.RegistrationId, p.Payments ) ); var rPmtSummary = rCosts .Join( rPayments, c => c.Key, p => p.Key, ( c, p ) => new { RegistrationId = c.Key, Costs = c.Value, Payments = p.Value } ) .ToList(); var ids = new List<int>(); if ( ddlRegistrationPaymentStatus.SelectedValue == "Paid in Full" ) { ids = rPmtSummary .Where( r => r.Costs <= r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } else { ids = rPmtSummary .Where( r => r.Costs > r.Payments ) .Select( r => r.RegistrationId ) .ToList(); } qry = qry.Where( r => ids.Contains( r.Id ) ); } IOrderedQueryable<Registration> orderedQry = null; SortProperty sortProperty = gRegistrations.SortProperty; if ( sortProperty != null ) { orderedQry = qry.Sort( sortProperty ); } else { orderedQry = qry.OrderByDescending( r => r.CreatedDateTime ); } gRegistrations.SetLinqDataSource( orderedQry ); // Get all the payments for any registrations being displayed on the current page. // This is used in the RowDataBound event but queried now so that each row does // not have to query for the data. var currentPageRegistrations = gRegistrations.DataSource as List<Registration>; if ( currentPageRegistrations != null && registrationEntityType != null ) { var registrationIds = currentPageRegistrations .Select( r => r.Id ) .ToList(); RegistrationPayments = new FinancialTransactionDetailService( rockContext ) .Queryable().AsNoTracking() .Where( d => d.EntityTypeId.HasValue && d.EntityId.HasValue && d.EntityTypeId.Value == registrationEntityType.Id && registrationIds.Contains( d.EntityId.Value ) ) .ToList(); } gRegistrations.DataBind(); } } }
/// <summary> /// Shows the preview. /// </summary> /// <param name="entityTypeId">The entity type id.</param> /// <param name="filter">The filter.</param> private void BindGrid( Report report ) { if ( report != null ) { var errors = new List<string>(); if ( !report.EntityTypeId.HasValue ) { gReport.Visible = false; return; } var rockContext = new RockContext(); if ( !report.IsAuthorized( Authorization.VIEW, this.CurrentPerson ) ) { gReport.Visible = false; return; } Type entityType = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).GetEntityType(); bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ), true, rockContext ).Id; if ( isPersonDataSet ) { gReport.PersonIdField = "Id"; gReport.DataKeyNames = new string[] { "Id" }; } else { gReport.PersonIdField = null; } if ( report.EntityTypeId.HasValue ) { gReport.RowItemText = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).FriendlyName; } List<EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields( entityType ); var selectedEntityFields = new Dictionary<int, EntityField>(); var selectedAttributes = new Dictionary<int, AttributeCache>(); var selectedComponents = new Dictionary<int, ReportField>(); // if there is a selectField, keep it to preserve which items are checked var selectField = gReport.Columns.OfType<SelectField>().FirstOrDefault(); gReport.Columns.Clear(); int columnIndex = 0; if ( !string.IsNullOrWhiteSpace( gReport.PersonIdField ) ) { // if we already had a selectField, use it (to preserve checkbox state) gReport.Columns.Add( selectField ?? new SelectField() ); columnIndex++; } var reportFieldSortExpressions = new Dictionary<Guid, string>(); foreach ( var reportField in report.ReportFields.OrderBy( a => a.ColumnOrder ) ) { columnIndex++; if ( reportField.ReportFieldType == ReportFieldType.Property ) { var entityField = entityFields.FirstOrDefault( a => a.Name == reportField.Selection ); if ( entityField != null ) { selectedEntityFields.Add( columnIndex, entityField ); BoundField boundField; if ( entityField.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid() ) ) { boundField = new DefinedValueField(); } else { boundField = Grid.GetGridField( entityField.PropertyType ); } boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex ); boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? entityField.Title : reportField.ColumnHeaderText; boundField.SortExpression = boundField.DataField; reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression ); boundField.Visible = reportField.ShowInGrid; gReport.Columns.Add( boundField ); } } else if ( reportField.ReportFieldType == ReportFieldType.Attribute ) { Guid? attributeGuid = reportField.Selection.AsGuidOrNull(); if ( attributeGuid.HasValue ) { var attribute = AttributeCache.Read( attributeGuid.Value, rockContext ); if ( attribute != null ) { selectedAttributes.Add( columnIndex, attribute ); BoundField boundField; if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.BOOLEAN.AsGuid() ) ) { boundField = new BoolField(); } else { boundField = new BoundField(); } boundField.DataField = string.Format( "Attribute_{0}_{1}", attribute.Id, columnIndex ); boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? attribute.Name : reportField.ColumnHeaderText; boundField.SortExpression = boundField.DataField; reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression ); if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.INTEGER.AsGuid() ) || attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) || attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid() ) ) { boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right; boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Right; } boundField.Visible = reportField.ShowInGrid; // NOTE: Additional formatting for attributes is done in the gReport_RowDataBound event gReport.Columns.Add( boundField ); } } } else if ( reportField.ReportFieldType == ReportFieldType.DataSelectComponent ) { selectedComponents.Add( columnIndex, reportField ); DataSelectComponent selectComponent = DataSelectContainer.GetComponent( reportField.DataSelectComponentEntityType.Name ); if ( selectComponent != null ) { DataControlField columnField = selectComponent.GetGridField( entityType, reportField.Selection ); if ( columnField is BoundField ) { ( columnField as BoundField ).DataField = string.Format( "Data_{0}_{1}", selectComponent.ColumnPropertyName, columnIndex ); columnField.SortExpression = ( columnField as BoundField ).DataField; } columnField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText; if ( columnField.SortExpression != null ) { reportFieldSortExpressions.AddOrReplace( reportField.Guid, columnField.SortExpression ); } columnField.Visible = reportField.ShowInGrid; gReport.Columns.Add( columnField ); } } } // if no fields are specified, show the default fields (Previewable/All) for the EntityType var dataColumns = gReport.Columns.OfType<object>().Where( a => a.GetType() != typeof( SelectField ) ); if ( dataColumns.Count() == 0 ) { // show either the Previewable Columns or all (if there are no previewable columns) bool showAllColumns = !entityFields.Any( a => a.FieldKind == FieldKind.Property && a.IsPreviewable ); foreach ( var entityField in entityFields.Where( a => a.FieldKind == FieldKind.Property ) ) { columnIndex++; selectedEntityFields.Add( columnIndex, entityField ); BoundField boundField; if ( entityField.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid() ) ) { boundField = new DefinedValueField(); } else { boundField = Grid.GetGridField( entityField.PropertyType ); } boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex ); boundField.HeaderText = entityField.Name; boundField.SortExpression = boundField.DataField; boundField.Visible = showAllColumns || entityField.IsPreviewable; gReport.Columns.Add( boundField ); } } try { gReport.Visible = true; gReport.ExportFilename = report.Name; SortProperty sortProperty = gReport.SortProperty; if ( sortProperty == null ) { var reportSort = new SortProperty(); var sortColumns = new Dictionary<string, SortDirection>(); foreach ( var reportField in report.ReportFields.Where( a => a.SortOrder.HasValue ).OrderBy( a => a.SortOrder.Value ) ) { if ( reportFieldSortExpressions.ContainsKey( reportField.Guid ) ) { var sortField = reportFieldSortExpressions[reportField.Guid]; if ( !string.IsNullOrWhiteSpace( sortField ) ) { sortColumns.Add( sortField, reportField.SortDirection ); } } } if ( sortColumns.Any() ) { reportSort.Property = sortColumns.Select( a => a.Key + ( a.Value == SortDirection.Descending ? " desc" : string.Empty ) ).ToList().AsDelimited( "," ); sortProperty = reportSort; } } gReport.DataSource = report.GetDataSource( entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, GetAttributeValue( "DatabaseTimeout" ).AsIntegerOrNull() ?? 180, out errors ); gReport.DataBind(); } catch ( Exception ex ) { Exception exception = ex; this.LogException( ex ); while ( exception != null ) { if ( exception is System.Data.SqlClient.SqlException ) { // if there was a SQL Server Timeout, have the warning be a friendly message about that. if ( ( exception as System.Data.SqlClient.SqlException ).Number == -2 ) { nbEditModeMessage.NotificationBoxType = NotificationBoxType.Warning; nbEditModeMessage.Text = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block."; return; } else { errors.Add( exception.Message ); exception = exception.InnerException; } } else { errors.Add( exception.Message ); exception = exception.InnerException; } } } if ( errors.Any() ) { nbEditModeMessage.NotificationBoxType = NotificationBoxType.Warning; nbEditModeMessage.Text = "INFO: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited( "<br/>" ); } } }
/// <summary> /// Loads the chart. /// </summary> public void LoadChart() { lcAttendance.ShowTooltip = true; if ( this.DetailPageGuid.HasValue ) { lcAttendance.ChartClick += lcAttendance_ChartClick; } var dataSourceUrl = "~/api/Attendances/GetChartData"; var dataSourceParams = new Dictionary<string, object>(); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues ); if ( dateRange.Start.HasValue ) { dataSourceParams.AddOrReplace( "startDate", dateRange.Start.Value.ToString( "o" ) ); } if ( dateRange.End.HasValue ) { dataSourceParams.AddOrReplace( "endDate", dateRange.End.Value.ToString( "o" ) ); } var groupBy = hfGroupBy.Value.ConvertToEnumOrNull<AttendanceGroupBy>() ?? AttendanceGroupBy.Week; lcAttendance.TooltipFormatter = null; switch ( groupBy ) { case AttendanceGroupBy.Week: { lcAttendance.Options.xaxis.tickSize = new string[] { "7", "day" }; lcAttendance.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = 'Weekend of <br />' + itemDate.toLocaleDateString(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case AttendanceGroupBy.Month: { lcAttendance.Options.xaxis.tickSize = new string[] { "1", "month" }; lcAttendance.TooltipFormatter = @" function(item) { var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = month_names[itemDate.getMonth()] + ' ' + itemDate.getFullYear(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case AttendanceGroupBy.Year: { lcAttendance.Options.xaxis.tickSize = new string[] { "1", "year" }; lcAttendance.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = itemDate.getFullYear(); var seriesLabel = item.series.label; var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; } dataSourceParams.AddOrReplace( "groupBy", hfGroupBy.Value.AsInteger() ); dataSourceParams.AddOrReplace( "graphBy", hfGraphBy.Value.AsInteger() ); dataSourceParams.AddOrReplace( "campusIds", cpCampuses.SelectedCampusIds.AsDelimited( "," ) ); dataSourceParams.AddOrReplace( "groupIds", GetSelectedGroupIds().AsDelimited( "," ) ); SaveSettingsToUserPreferences(); dataSourceUrl += "?" + dataSourceParams.Select( s => string.Format( "{0}={1}", s.Key, s.Value ) ).ToList().AsDelimited( "&" ); lcAttendance.DataSourceUrl = this.ResolveUrl( dataSourceUrl ); if ( pnlGrid.Visible ) { BindGrid(); } }
/// <summary> /// Loads all of the configured blocks for the current page into the control tree /// </summary> /// <param name="e"></param> protected override void OnInit( EventArgs e ) { // Add the ScriptManager to each page _scriptManager = ScriptManager.GetCurrent( this.Page ); if ( _scriptManager == null ) { _scriptManager = new AjaxControlToolkit.ToolkitScriptManager { ID = "sManager" }; Page.Trace.Warn( "Adding script manager" ); Page.Form.Controls.AddAt( 0, _scriptManager ); } // enable history on the ScriptManager _scriptManager.EnableHistory = true; // TODO: Delete this line, only used for testing _scriptManager.AsyncPostBackTimeout = 180; // wire up navigation event _scriptManager.Navigate += new EventHandler<HistoryEventArgs>( scriptManager_Navigate ); // add ckeditor (doesn't like to be added during an async postback) _scriptManager.Scripts.Add( new ScriptReference( ResolveRockUrl( "~/Scripts/ckeditor/ckeditor.js", true ) ) ); // Add library and UI bundles during init, that way theme developers will only // need to worry about registering any custom scripts or script bundles they need _scriptManager.Scripts.Add( new ScriptReference( "~/Bundles/WebFormsJs" ) ); _scriptManager.Scripts.Add( new ScriptReference( "~/Scripts/Bundles/RockLibs" ) ); _scriptManager.Scripts.Add( new ScriptReference( "~/Scripts/Bundles/RockUi" ) ); _scriptManager.Scripts.Add( new ScriptReference( "~/Scripts/Bundles/RockValidation" ) ); // add Google Maps API (doesn't like to be added during an async postback ) var googleAPIKey = GlobalAttributesCache.Read().GetValue( "GoogleAPIKey" ); string keyParameter = string.IsNullOrWhiteSpace(googleAPIKey) ? "" : string.Format("key={0}&", googleAPIKey); _scriptManager.Scripts.Add( new ScriptReference( string.Format( "https://maps.googleapis.com/maps/api/js?{0}sensor=false&libraries=drawing", keyParameter ) ) ); // Recurse the page controls to find the rock page title and zone controls Page.Trace.Warn( "Recursing layout to find zones" ); Zones = new Dictionary<string, KeyValuePair<string, Zone>>(); FindRockControls( this.Controls ); // Add a Rock version meta tag Page.Trace.Warn( "Adding Rock metatag" ); string version = typeof( Rock.Web.UI.RockPage ).Assembly.GetName().Version.ToString(); HtmlMeta rockVersion = new HtmlMeta(); rockVersion.Attributes.Add( "name", "generator" ); rockVersion.Attributes.Add( "content", string.Format( "Rock v{0}", version ) ); AddMetaTag( this.Page, rockVersion ); // If the logout parameter was entered, delete the user's forms authentication cookie and redirect them // back to the same page. Page.Trace.Warn( "Checking for logout request" ); if ( PageParameter( "logout" ) != string.Empty ) { if ( CurrentUser != null ) { var transaction = new Rock.Transactions.UserLastActivityTransaction(); transaction.UserId = CurrentUser.Id; transaction.LastActivityDate = RockDateTime.Now; transaction.IsOnLine = false; Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } FormsAuthentication.SignOut(); // After logging out check to see if an anonymous user is allowed to view the current page. If so // redirect back to the current page, otherwise redirect to the site's default page if ( _pageCache != null ) { if ( _pageCache.IsAuthorized( Authorization.VIEW, null ) ) { // Remove the 'logout' queryparam before redirecting var pageReference = new PageReference( PageReference.PageId, PageReference.RouteId, PageReference.Parameters ); foreach ( string key in PageReference.QueryString ) { if ( !key.Equals( "logout", StringComparison.OrdinalIgnoreCase ) ) { pageReference.Parameters.Add( key, PageReference.QueryString[key] ); } } Response.Redirect( pageReference.BuildUrl(), false ); Context.ApplicationInstance.CompleteRequest(); } else { _pageCache.Layout.Site.RedirectToDefaultPage(); } return; } else { CurrentPerson = null; CurrentUser = null; } } var rockContext = new RockContext(); // If the impersonated query key was included then set the current person Page.Trace.Warn( "Checking for person impersanation" ); string impersonatedPersonKey = PageParameter( "rckipid" ); if ( !String.IsNullOrEmpty( impersonatedPersonKey ) ) { Rock.Model.PersonService personService = new Model.PersonService( rockContext ); Rock.Model.Person impersonatedPerson = personService.GetByEncryptedKey( impersonatedPersonKey ); if ( impersonatedPerson != null ) { Rock.Security.Authorization.SetAuthCookie( "rckipid=" + impersonatedPerson.EncryptedKey, false, true ); CurrentUser = impersonatedPerson.GetImpersonatedUser(); } } // Get current user/person info Page.Trace.Warn( "Getting CurrentUser" ); Rock.Model.UserLogin user = CurrentUser; // If there is a logged in user, see if it has an associated Person Record. If so, set the UserName to // the person's full name (which is then cached in the Session state for future page requests) if ( user != null ) { Page.Trace.Warn( "Setting CurrentPerson" ); UserName = user.UserName; int? personId = user.PersonId; if ( personId.HasValue ) { string personNameKey = "PersonName_" + personId.Value.ToString(); if ( Session[personNameKey] != null ) { UserName = Session[personNameKey].ToString(); } else { Rock.Model.PersonService personService = new Model.PersonService( rockContext ); Rock.Model.Person person = personService.Get( personId.Value ); if ( person != null ) { UserName = person.FullName; CurrentPerson = person; } Session[personNameKey] = UserName; } } } // If a PageInstance exists if ( _pageCache != null ) { BrowserTitle = _pageCache.BrowserTitle; PageTitle = _pageCache.PageTitle; PageIcon = _pageCache.IconCssClass; // If there's a master page, update it's reference to Current Page if ( this.Master is RockMasterPage ) { ( (RockMasterPage)this.Master ).SetPage( _pageCache ); } // check if page should have been loaded via ssl Page.Trace.Warn( "Checking for SSL request" ); if ( !Request.IsSecureConnection && _pageCache.RequiresEncryption ) { string redirectUrl = Request.Url.ToString().Replace( "http:", "https:" ); Response.Redirect( redirectUrl, false ); Context.ApplicationInstance.CompleteRequest(); return; } // Verify that the current user is allowed to view the page. Page.Trace.Warn( "Checking if user is authorized" ); if ( !_pageCache.IsAuthorized( Authorization.VIEW, CurrentPerson ) ) { if ( user == null ) { // If not authorized, and the user hasn't logged in yet, redirect to the login page Page.Trace.Warn( "Redirecting to login page" ); var site = _pageCache.Layout.Site; if ( site.LoginPageId.HasValue ) { site.RedirectToLoginPage( true ); } else { FormsAuthentication.RedirectToLoginPage(); } } else { // If not authorized, and the user has logged in, redirect to error page Page.Trace.Warn( "Redirecting to error page" ); Response.Redirect( "~/error.aspx?type=security", false ); Context.ApplicationInstance.CompleteRequest(); } } else { // Set current models (context) Page.Trace.Warn( "Checking for Context" ); ModelContext = new Dictionary<string, Data.KeyEntity>(); try { // first search cookies, but pageContext can replace it GetCookieContext( GetContextCookieName( false ) ); // Site GetCookieContext( GetContextCookieName( true ) ); // Page (will replace any site values) foreach ( var pageContext in _pageCache.PageContexts ) { int? contextId = PageParameter( pageContext.Value ).AsIntegerOrNull(); if ( contextId.HasValue ) { ModelContext.AddOrReplace( pageContext.Key, new Data.KeyEntity( contextId.Value ) ); } } char[] delim = new char[1] { ',' }; foreach ( string param in PageParameter( "context", true ).Split( delim, StringSplitOptions.RemoveEmptyEntries ) ) { string contextItem = Rock.Security.Encryption.DecryptString( param ); string[] parts = contextItem.Split( '|' ); if ( parts.Length == 2 ) { ModelContext.AddOrReplace( parts[0], new Data.KeyEntity( parts[1] ) ); } } } catch { // intentionally ignore exception } // set viewstate on/off this.EnableViewState = _pageCache.EnableViewState; // Cache object used for block output caching Page.Trace.Warn( "Getting memory cache" ); ObjectCache cache = MemoryCache.Default; Page.Trace.Warn( "Checking if user can administer" ); bool canAdministratePage = _pageCache.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ); // Create a javascript object to store information about the current page for client side scripts to use Page.Trace.Warn( "Creating JS objects" ); string script = string.Format( @" Rock.settings.initialize({{ siteId: {0}, layoutId: {1}, pageId: {2}, layout: '{3}', baseUrl: '{4}' }});", _pageCache.Layout.SiteId, _pageCache.LayoutId, _pageCache.Id, _pageCache.Layout.FileName, ResolveUrl( "~" ) ); ScriptManager.RegisterStartupScript( this.Page, this.GetType(), "rock-js-object", script, true ); AddTriggerPanel(); // Add config elements if ( _pageCache.IncludeAdminFooter ) { Page.Trace.Warn( "Adding popup controls (footer elements)" ); AddPopupControls(); Page.Trace.Warn( "Adding zone elements" ); AddZoneElements( canAdministratePage ); } // Initialize the list of breadcrumbs for the current page (and blocks on the page) Page.Trace.Warn( "Setting breadcrumbs" ); PageReference.BreadCrumbs = new List<BreadCrumb>(); // If the page is configured to display in the breadcrumbs... string bcName = _pageCache.BreadCrumbText; if ( bcName != string.Empty ) { PageReference.BreadCrumbs.Add( new BreadCrumb( bcName, PageReference.BuildUrl() ) ); } // Add the Google Analytics Code script if a code was specified for the site if ( !string.IsNullOrWhiteSpace( _pageCache.Layout.Site.GoogleAnalyticsCode ) ) { AddGoogleAnalytics( _pageCache.Layout.Site.GoogleAnalyticsCode ); } // Flag indicating if user has rights to administer one or more of the blocks on page bool canAdministrateBlock = false; // Load the blocks and insert them into page zones Page.Trace.Warn( "Loading Blocks" ); foreach ( Rock.Web.Cache.BlockCache block in _pageCache.Blocks ) { Page.Trace.Warn( string.Format( "\tLoading '{0}' block", block.Name ) ); // Get current user's permissions for the block instance Page.Trace.Warn( "\tChecking permission" ); bool canAdministrate = block.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ); bool canEdit = block.IsAuthorized( Authorization.EDIT, CurrentPerson ); bool canView = block.IsAuthorized( Authorization.VIEW, CurrentPerson ); if ( canAdministrate || canEdit ) { canAdministrateBlock = true; } // Make sure user has access to view block instance if ( canAdministrate || canEdit || canView ) { // Create block wrapper control (implements INamingContainer so child control IDs are unique for // each block instance Page.Trace.Warn( "\tAdding block wrapper html" ); HtmlGenericContainer blockWrapper = new HtmlGenericContainer( "div" ); blockWrapper.ID = string.Format( "bid_{0}", block.Id ); blockWrapper.Attributes.Add( "data-zone-location", block.BlockLocation.ToString() ); blockWrapper.ClientIDMode = ClientIDMode.Static; FindZone( block.Zone ).Controls.Add( blockWrapper ); string blockTypeCss = block.BlockType != null ? block.BlockType.Name : ""; var parts = blockTypeCss.Split( new char[] { '>' } ); if ( parts.Length > 1 ) { blockTypeCss = parts[parts.Length - 1].Trim(); } blockTypeCss = blockTypeCss.Replace( ' ', '-' ).ToLower(); blockWrapper.Attributes.Add( "class", "block-instance " + blockTypeCss + ( string.IsNullOrWhiteSpace( block.CssClass ) ? "" : " " + block.CssClass.Trim() ) + ( canAdministrate || canEdit ? " can-configure " : "" ) ); // Check to see if block is configured to use a "Cache Duration' string blockCacheKey = string.Format( "Rock:BlockOutput:{0}", block.Id ); if ( block.OutputCacheDuration > 0 && cache.Contains( blockCacheKey ) ) { // If the current block exists in our custom output cache, add the cached output instead of adding the control blockWrapper.Controls.Add( new LiteralControl( cache[blockCacheKey] as string ) ); } else { // Load the control and add to the control tree Page.Trace.Warn( "\tLoading control" ); Control control; try { control = TemplateControl.LoadControl( block.BlockType.Path ); control.ClientIDMode = ClientIDMode.AutoID; } catch ( Exception ex ) { NotificationBox nbBlockLoad = new NotificationBox(); nbBlockLoad.ID = string.Format( "nbBlockLoad_{0}", block.Id ); nbBlockLoad.CssClass = "system-error"; nbBlockLoad.NotificationBoxType = NotificationBoxType.Danger; nbBlockLoad.Text = string.Format( "Error Loading Block: {0}", block.Name ); nbBlockLoad.Details = string.Format( "{0}<pre>{1}</pre>", ex.Message, ex.StackTrace ); nbBlockLoad.Dismissable = true; control = nbBlockLoad; if ( this.IsPostBack ) { // throw an error on PostBack so that the ErrorPage gets shown (vs nothing happening) throw ex; } } RockBlock blockControl = null; // Check to see if the control was a PartialCachingControl or not Page.Trace.Warn( "\tChecking block for partial caching" ); if ( control is RockBlock ) blockControl = control as RockBlock; else { if ( control is PartialCachingControl && ( (PartialCachingControl)control ).CachedControl != null ) { blockControl = (RockBlock)( (PartialCachingControl)control ).CachedControl; } } // If the current control is a block, set it's properties if ( blockControl != null ) { Page.Trace.Warn( "\tSetting block properties" ); blockControl.SetBlock( block ); // Add any breadcrumbs to current page reference that the block creates Page.Trace.Warn( "\tAdding any breadcrumbs from block" ); if ( block.BlockLocation == BlockLocation.Page ) { blockControl.GetBreadCrumbs( PageReference ).ForEach( c => PageReference.BreadCrumbs.Add( c ) ); } // If the blocktype's security actions have not yet been loaded, load them now if ( !block.BlockType.CheckedSecurityActions ) { Page.Trace.Warn( "\tAdding additional security actions for blcok" ); block.BlockType.SecurityActions = new Dictionary<string, string>(); foreach ( var action in blockControl.GetSecurityActionAttributes() ) { if ( block.BlockType.SecurityActions.ContainsKey( action.Key ) ) { block.BlockType.SecurityActions[action.Key] = action.Value; } else { block.BlockType.SecurityActions.Add( action.Key, action.Value ); } } block.BlockType.CheckedSecurityActions = true; } // If the block's AttributeProperty values have not yet been verified verify them. // (This provides a mechanism for block developers to define the needed block // attributes in code and have them automatically added to the database) Page.Trace.Warn( "\tChecking if block attributes need refresh" ); if ( !block.BlockType.IsInstancePropertiesVerified ) { Page.Trace.Warn( "\tCreating block attributes" ); blockControl.CreateAttributes( rockContext ); block.BlockType.IsInstancePropertiesVerified = true; } // Add the block configuration scripts and icons if user is authorized if ( _pageCache.IncludeAdminFooter ) { Page.Trace.Warn( "\tAdding block configuration tools" ); AddBlockConfig( blockWrapper, blockControl, block, canAdministrate, canEdit ); } } Page.Trace.Warn( "\tAdding block to control tree" ); HtmlGenericContainer blockContent = new HtmlGenericContainer( "div" ); blockContent.Attributes.Add( "class", "block-content" ); blockWrapper.Controls.Add( blockContent ); // Add the block blockContent.Controls.Add( control ); } } } // Make the last crumb for this page the active one Page.Trace.Warn( "Setting active breadcrumb" ); if ( PageReference.BreadCrumbs.Any() ) { PageReference.BreadCrumbs.Last().Active = true; } Page.Trace.Warn( "Getting parent page references" ); var pageReferences = PageReference.GetParentPageReferences( this, _pageCache, PageReference ); pageReferences.Add( PageReference ); PageReference.SavePageReferences( pageReferences ); // Update breadcrumbs Page.Trace.Warn( "Updating breadcrumbs" ); BreadCrumbs = new List<BreadCrumb>(); foreach ( var pageReference in pageReferences ) { pageReference.BreadCrumbs.ForEach( c => BreadCrumbs.Add( c ) ); } // Add the page admin footer if the user is authorized to edit the page if ( _pageCache.IncludeAdminFooter && ( canAdministratePage || canAdministrateBlock ) ) { // Add the page admin script AddScriptLink( Page, "~/Scripts/Bundles/RockAdmin", false ); Page.Trace.Warn( "Adding admin footer to page" ); HtmlGenericControl adminFooter = new HtmlGenericControl( "div" ); adminFooter.ID = "cms-admin-footer"; adminFooter.ClientIDMode = System.Web.UI.ClientIDMode.Static; this.Form.Controls.Add( adminFooter ); phLoadTime = new PlaceHolder(); adminFooter.Controls.Add( phLoadTime ); HtmlGenericControl buttonBar = new HtmlGenericControl( "div" ); adminFooter.Controls.Add( buttonBar ); buttonBar.Attributes.Add( "class", "button-bar" ); // RockBlock Config HtmlGenericControl aBlockConfig = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aBlockConfig ); aBlockConfig.Attributes.Add( "class", "btn block-config" ); aBlockConfig.Attributes.Add( "href", "javascript: Rock.admin.pageAdmin.showBlockConfig();" ); aBlockConfig.Attributes.Add( "Title", "Block Configuration" ); HtmlGenericControl iBlockConfig = new HtmlGenericControl( "i" ); aBlockConfig.Controls.Add( iBlockConfig ); iBlockConfig.Attributes.Add( "class", "fa fa-th-large" ); if ( canAdministratePage ) { // RockPage Properties HtmlGenericControl aAttributes = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aAttributes ); aAttributes.ID = "aPageProperties"; aAttributes.ClientIDMode = System.Web.UI.ClientIDMode.Static; aAttributes.Attributes.Add( "class", "btn properties" ); aAttributes.Attributes.Add( "height", "500px" ); aAttributes.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( string.Format( "~/PageProperties/{0}?t=Page Properties", _pageCache.Id ) ) + "')" ); aAttributes.Attributes.Add( "Title", "Page Properties" ); HtmlGenericControl iAttributes = new HtmlGenericControl( "i" ); aAttributes.Controls.Add( iAttributes ); iAttributes.Attributes.Add( "class", "fa fa-cog" ); // Child Pages HtmlGenericControl aChildPages = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aChildPages ); aChildPages.ID = "aChildPages"; aChildPages.ClientIDMode = System.Web.UI.ClientIDMode.Static; aChildPages.Attributes.Add( "class", "btn page-child-pages" ); aChildPages.Attributes.Add( "height", "500px" ); aChildPages.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( string.Format( "~/pages/{0}?t=Child Pages&pb=&sb=Done", _pageCache.Id ) ) + "')" ); aChildPages.Attributes.Add( "Title", "Child Pages" ); HtmlGenericControl iChildPages = new HtmlGenericControl( "i" ); aChildPages.Controls.Add( iChildPages ); iChildPages.Attributes.Add( "class", "fa fa-sitemap" ); // RockPage Zones HtmlGenericControl aPageZones = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aPageZones ); aPageZones.Attributes.Add( "class", "btn page-zones" ); aPageZones.Attributes.Add( "href", "javascript: Rock.admin.pageAdmin.showPageZones();" ); aPageZones.Attributes.Add( "Title", "Page Zones" ); HtmlGenericControl iPageZones = new HtmlGenericControl( "i" ); aPageZones.Controls.Add( iPageZones ); iPageZones.Attributes.Add( "class", "fa fa-columns" ); // RockPage Security HtmlGenericControl aPageSecurity = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aPageSecurity ); aPageSecurity.ID = "aPageSecurity"; aPageSecurity.ClientIDMode = System.Web.UI.ClientIDMode.Static; aPageSecurity.Attributes.Add( "class", "btn page-security" ); aPageSecurity.Attributes.Add( "height", "500px" ); aPageSecurity.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( string.Format( "~/Secure/{0}/{1}?t=Page Security&pb=&sb=Done", EntityTypeCache.Read( typeof( Rock.Model.Page ) ).Id, _pageCache.Id ) ) + "')" ); aPageSecurity.Attributes.Add( "Title", "Page Security" ); HtmlGenericControl iPageSecurity = new HtmlGenericControl( "i" ); aPageSecurity.Controls.Add( iPageSecurity ); iPageSecurity.Attributes.Add( "class", "fa fa-lock" ); // System Info HtmlGenericControl aSystemInfo = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aSystemInfo ); aSystemInfo.ID = "aSystemInfo"; aSystemInfo.ClientIDMode = System.Web.UI.ClientIDMode.Static; aSystemInfo.Attributes.Add( "class", "btn system-info" ); aSystemInfo.Attributes.Add( "height", "500px" ); aSystemInfo.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( "~/SystemInfo?t=System Information&pb=&sb=Done" ) + "')" ); aSystemInfo.Attributes.Add( "Title", "Rock Information" ); HtmlGenericControl iSystemInfo = new HtmlGenericControl( "i" ); aSystemInfo.Controls.Add( iSystemInfo ); iSystemInfo.Attributes.Add( "class", "fa fa-info-circle" ); } } // Check to see if page output should be cached. The RockRouteHandler // saves the PageCacheData information for the current page to memorycache // so it should always exist if ( _pageCache.OutputCacheDuration > 0 ) { Response.Cache.SetCacheability( System.Web.HttpCacheability.Public ); Response.Cache.SetExpires( RockDateTime.Now.AddSeconds( _pageCache.OutputCacheDuration ) ); Response.Cache.SetValidUntilExpires( true ); } } string pageTitle = BrowserTitle; string siteTitle = _pageCache.Layout.Site.Name; string seperator = pageTitle.Trim() != string.Empty && siteTitle.Trim() != string.Empty ? " | " : ""; base.Title = pageTitle + seperator + siteTitle; if ( !string.IsNullOrWhiteSpace( _pageCache.Description ) ) { HtmlMeta metaTag = new HtmlMeta(); metaTag.Attributes.Add( "name", "description" ); metaTag.Attributes.Add( "content", _pageCache.Description.Trim() ); AddMetaTag( this.Page, metaTag ); } if ( !string.IsNullOrWhiteSpace( _pageCache.KeyWords ) ) { HtmlMeta metaTag = new HtmlMeta(); metaTag.Attributes.Add( "name", "keywords" ); metaTag.Attributes.Add( "content", _pageCache.KeyWords.Trim() ); AddMetaTag( this.Page, metaTag ); } if ( !string.IsNullOrWhiteSpace( _pageCache.HeaderContent ) ) { Page.Header.Controls.Add( new LiteralControl( _pageCache.HeaderContent ) ); } } }
/// <summary> /// Filters the value control. /// </summary> /// <param name="configurationValues">The configuration values.</param> /// <param name="id">The identifier.</param> /// <param name="required">if set to <c>true</c> [required].</param> /// <param name="filterMode">The filter mode.</param> /// <returns></returns> public override Control FilterValueControl( Dictionary<string, ConfigurationValue> configurationValues, string id, bool required, FilterMode filterMode ) { bool allowMultiple = configurationValues != null && configurationValues.ContainsKey( ALLOW_MULTIPLE_KEY ) && configurationValues[ALLOW_MULTIPLE_KEY].Value.AsBoolean(); var overrideConfigValues = new Dictionary<string, ConfigurationValue>(); foreach ( var keyVal in configurationValues ) { overrideConfigValues.Add( keyVal.Key, keyVal.Value ); } overrideConfigValues.AddOrReplace( ALLOW_MULTIPLE_KEY, new ConfigurationValue( ( true ).ToString() ) ); return base.FilterValueControl( overrideConfigValues, id, required, filterMode ); }
private static Script CombineMultisig(Script scriptPubKey, Transaction transaction, int n, byte[][] sigs1, byte[][] sigs2) { // Combine all the signatures we've got: List<TransactionSignature> allsigs = new List<TransactionSignature>(); foreach(var v in sigs1) { if(TransactionSignature.IsValid(v)) { allsigs.Add(new TransactionSignature(v)); } } foreach(var v in sigs2) { if(TransactionSignature.IsValid(v)) { allsigs.Add(new TransactionSignature(v)); } } var multiSigParams = PayToMultiSigTemplate.Instance.ExtractScriptPubKeyParameters(scriptPubKey); if(multiSigParams == null) throw new InvalidOperationException("The scriptPubKey is not a valid multi sig"); Dictionary<PubKey, TransactionSignature> sigs = new Dictionary<PubKey, TransactionSignature>(); foreach(var sig in allsigs) { foreach(var pubkey in multiSigParams.PubKeys) { if(sigs.ContainsKey(pubkey)) continue; // Already got a sig for this pubkey ScriptEvaluationContext eval = new ScriptEvaluationContext(); if(eval.CheckSig(sig.ToBytes(), pubkey.ToBytes(), scriptPubKey, transaction, n)) { sigs.AddOrReplace(pubkey, sig); } } } // Now build a merged CScript: int nSigsHave = 0; Script result = new Script(OpcodeType.OP_0); // pop-one-too-many workaround foreach(var pubkey in multiSigParams.PubKeys) { if(sigs.ContainsKey(pubkey)) { result += Op.GetPushOp(sigs[pubkey].ToBytes()); nSigsHave++; } if(nSigsHave >= multiSigParams.SignatureCount) break; } // Fill any missing with OP_0: for(int i = nSigsHave ; i < multiSigParams.SignatureCount ; i++) result += OpcodeType.OP_0; return result; }
//Do not get all entries, but only the one you can generate with spent/unspent. public AccountEntry[] GetInChain(Chain chain, bool value) { Dictionary<OutPoint, AccountEntry> entries = new Dictionary<OutPoint, AccountEntry>(); foreach(var entry in AccountEntries) { if(entry.Block == null) continue; if(chain.Contains(entry.Block, false) == value) { if(entry.Reason == AccountEntryReason.Income && _Unspent.ContainsKey(entry.Spendable.OutPoint)) entries.AddOrReplace(entry.Spendable.OutPoint, entry); if(entry.Reason == AccountEntryReason.ChainBlockChanged && !_Unspent.ContainsKey(entry.Spendable.OutPoint)) entries.AddOrReplace(entry.Spendable.OutPoint, entry); } } return entries.Values.ToArray(); }
/// <summary> /// Loads the chart and any visible grids /// </summary> public void LoadChartAndGrids() { pnlUpdateMessage.Visible = false; pnlResults.Visible = true; lcAttendance.ShowTooltip = true; if ( this.DetailPageGuid.HasValue ) { lcAttendance.ChartClick += lcAttendance_ChartClick; } bcAttendance.ShowTooltip = true; if ( this.DetailPageGuid.HasValue ) { bcAttendance.ChartClick += lcAttendance_ChartClick; } var lineChartDataSourceUrl = "~/api/Attendances/GetChartData"; var dataSourceParams = new Dictionary<string, object>(); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues ); if ( !dateRange.Start.HasValue || !dateRange.End.HasValue ) { nbDateRangeWarning.Visible = true; return; } nbDateRangeWarning.Visible = false; if ( dateRange.Start.HasValue ) { dataSourceParams.AddOrReplace( "startDate", dateRange.Start.Value.ToString( "o" ) ); } if ( dateRange.End.HasValue ) { dataSourceParams.AddOrReplace( "endDate", dateRange.End.Value.ToString( "o" ) ); } var groupBy = hfGroupBy.Value.ConvertToEnumOrNull<ChartGroupBy>() ?? ChartGroupBy.Week; lcAttendance.TooltipFormatter = null; switch ( groupBy ) { case ChartGroupBy.Week: { lcAttendance.Options.xaxis.tickSize = new string[] { "7", "day" }; lcAttendance.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = 'Weekend of <br />' + itemDate.toLocaleDateString(); var seriesLabel = item.series.label || ( item.series.labels ? item.series.labels[item.dataIndex] : null ); var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case ChartGroupBy.Month: { lcAttendance.Options.xaxis.tickSize = new string[] { "1", "month" }; lcAttendance.TooltipFormatter = @" function(item) { var month_names = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = month_names[itemDate.getMonth()] + ' ' + itemDate.getFullYear(); var seriesLabel = item.series.label || ( item.series.labels ? item.series.labels[item.dataIndex] : null ); var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; case ChartGroupBy.Year: { lcAttendance.Options.xaxis.tickSize = new string[] { "1", "year" }; lcAttendance.TooltipFormatter = @" function(item) { var itemDate = new Date(item.series.chartData[item.dataIndex].DateTimeStamp); var dateText = itemDate.getFullYear(); var seriesLabel = item.series.label || ( item.series.labels ? item.series.labels[item.dataIndex] : null ); var pointValue = item.series.chartData[item.dataIndex].YValue || item.series.chartData[item.dataIndex].YValueTotal || '-'; return dateText + '<br />' + seriesLabel + ': ' + pointValue; } "; } break; } string groupByTextPlural = groupBy.ConvertToString().ToLower().Pluralize(); lPatternXFor.Text = string.Format( " {0} for the selected date range", groupByTextPlural ); lPatternAndMissedXBetween.Text = string.Format( " {0} between", groupByTextPlural ); var selectedDataViewId = dvpDataView.SelectedValue.AsIntegerOrNull(); if ( selectedDataViewId.HasValue ) { dataSourceParams.AddOrReplace( "dataViewId", selectedDataViewId.Value.ToString() ); } dataSourceParams.AddOrReplace( "groupBy", hfGroupBy.Value.AsInteger() ); dataSourceParams.AddOrReplace( "graphBy", hfGraphBy.Value.AsInteger() ); var selectedCampusValues = clbCampuses.SelectedValues; string campusIdsValue = selectedCampusValues.AsDelimited( "," ); dataSourceParams.AddOrReplace( "campusIds", campusIdsValue ); var selectedGroupIds = GetSelectedGroupIds(); if ( selectedGroupIds.Any() ) { dataSourceParams.AddOrReplace( "groupIds", selectedGroupIds.AsDelimited( "," ) ); } else { // set the value to 0 to indicate that no groups where selected (and so that Rest Endpoint doesn't 404) dataSourceParams.AddOrReplace( "groupIds", 0 ); } SaveSettingsToUserPreferences(); lineChartDataSourceUrl += "?" + dataSourceParams.Select( s => string.Format( "{0}={1}", s.Key, s.Value ) ).ToList().AsDelimited( "&" ); // if no Groups are selected show a warning since no data will show up nbGroupsWarning.Visible = false; if ( !selectedGroupIds.Any() ) { nbGroupsWarning.Visible = true; return; } lcAttendance.DataSourceUrl = this.ResolveUrl( lineChartDataSourceUrl ); bcAttendance.TooltipFormatter = lcAttendance.TooltipFormatter; bcAttendance.DataSourceUrl = this.ResolveUrl( lineChartDataSourceUrl ); var chartData = this.GetAttendanceChartData(); var singleDateTime = chartData.GroupBy(a => a.DateTimeStamp).Count() == 1; bcAttendance.Visible = singleDateTime; lcAttendance.Visible = !singleDateTime; if ( pnlChartAttendanceGrid.Visible ) { BindChartAttendanceGrid( chartData ); } if ( pnlShowByAttendees.Visible ) { BindAttendeesGrid(); } }
/// <summary> /// Binds the grid. /// </summary> private void ShowView() { nbContentError.Visible = false; upnlContent.Update(); var pageRef = CurrentPageReference; pageRef.Parameters.AddOrReplace( "Page", "PageNum" ); Dictionary<string, object> linkedPages = new Dictionary<string, object>(); linkedPages.Add( "DetailPage", LinkedPageRoute( "DetailPage" ) ); var errorMessages = new List<string>(); List<ContentChannelItem> content; try { content = GetContent( errorMessages ) ?? new List<ContentChannelItem>(); } catch (Exception ex) { this.LogException( ex ); Exception exception = ex; while ( exception != null ) { errorMessages.Add( exception.Message ); exception = exception.InnerException; } content = new List<ContentChannelItem>(); } if (errorMessages.Any()) { nbContentError.Text = "ERROR: There was a problem getting content...<br/> "; nbContentError.NotificationBoxType = NotificationBoxType.Danger; nbContentError.Details = errorMessages.AsDelimited( "<br/>" ); nbContentError.Visible = true; } var pagination = new Pagination(); pagination.ItemCount = content.Count(); pagination.PageSize = GetAttributeValue( "Count" ).AsInteger(); pagination.CurrentPage = PageParameter( "Page" ).AsIntegerOrNull() ?? 1; pagination.UrlTemplate = pageRef.BuildUrl(); var currentPageContent = pagination.GetCurrentPageItems( content ); var commonMergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson ); // Merge content and attribute fields if block is configured to do so. if ( GetAttributeValue( "MergeContent" ).AsBoolean() ) { var itemMergeFields = new Dictionary<string, object>(); if ( CurrentPerson != null ) { // TODO: When support for "Person" is not supported anymore (should use "CurrentPerson" instead), remove this line itemMergeFields.Add( "Person", CurrentPerson ); } commonMergeFields.ToList().ForEach( d => itemMergeFields.Add( d.Key, d.Value ) ); foreach ( var item in currentPageContent ) { itemMergeFields.AddOrReplace( "Item", item ); var enabledCommands = GetAttributeValue( "EnabledLavaCommands" ); item.Content = item.Content.ResolveMergeFields( itemMergeFields, enabledCommands ); foreach ( var attributeValue in item.AttributeValues ) { attributeValue.Value.Value = attributeValue.Value.Value.ResolveMergeFields( itemMergeFields, enabledCommands ); } } } var mergeFields = Rock.Lava.LavaHelper.GetCommonMergeFields( this.RockPage, this.CurrentPerson ); mergeFields.Add( "Pagination", pagination ); mergeFields.Add( "LinkedPages", linkedPages ); mergeFields.Add( "Items", currentPageContent ); mergeFields.Add( "RockVersion", Rock.VersionInfo.VersionInfo.GetRockProductVersionNumber() ); // enable showing debug info if ( GetAttributeValue( "EnableDebug" ).AsBoolean() && IsUserAuthorized( Authorization.EDIT ) ) { mergeFields["Items"] = currentPageContent.Take( 5 ).ToList(); lDebug.Visible = true; lDebug.Text = mergeFields.lavaDebugInfo(); mergeFields["Items"] = currentPageContent; } else { lDebug.Visible = false; lDebug.Text = string.Empty; } // TODO: When support for "Person" is not supported anymore (should use "CurrentPerson" instead), remove this line mergeFields.AddOrIgnore( "Person", CurrentPerson ); // set page title if ( GetAttributeValue( "SetPageTitle" ).AsBoolean() && content.Count > 0 ) { if ( string.IsNullOrWhiteSpace( PageParameter( "Item" ) ) ) { // set title to channel name string channelName = content.Select( c => c.ContentChannel.Name ).FirstOrDefault(); RockPage.BrowserTitle = String.Format( "{0} | {1}", channelName, RockPage.Site.Name ); RockPage.PageTitle = channelName; RockPage.Header.Title = String.Format( "{0} | {1}", channelName, RockPage.Site.Name ); } else { string itemTitle = content.Select( c => c.Title ).FirstOrDefault(); RockPage.PageTitle = itemTitle; RockPage.BrowserTitle = String.Format( "{0} | {1}", itemTitle, RockPage.Site.Name ); RockPage.Header.Title = String.Format( "{0} | {1}", itemTitle, RockPage.Site.Name ); } var pageBreadCrumb = RockPage.PageReference.BreadCrumbs.FirstOrDefault(); if ( pageBreadCrumb != null ) { pageBreadCrumb.Name = RockPage.PageTitle; } } // set rss auto discover link if ( GetAttributeValue( "RssAutodiscover" ).AsBoolean() && content.Count > 0 ) { //<link rel="alternate" type="application/rss+xml" title="RSS Feed for petefreitag.com" href="/rss/" /> HtmlLink rssLink = new HtmlLink(); rssLink.Attributes.Add("type", "application/rss+xml"); rssLink.Attributes.Add("rel", "alternate"); rssLink.Attributes.Add("title", content.Select(c => c.ContentChannel.Name).FirstOrDefault()); var context = HttpContext.Current; string channelRssUrl = string.Format( "{0}://{1}{2}{3}{4}", context.Request.Url.Scheme, context.Request.Url.Host, context.Request.Url.Port == 80 ? string.Empty : ":" + context.Request.Url.Port, RockPage.ResolveRockUrl( "~/GetChannelFeed.ashx?ChannelId="), content.Select(c => c.ContentChannelId).FirstOrDefault()); rssLink.Attributes.Add( "href", channelRssUrl ); RockPage.Header.Controls.Add( rssLink ); } // set description meta tag string metaDescriptionAttributeValue = GetAttributeValue("MetaDescriptionAttribute"); if ( !string.IsNullOrWhiteSpace( metaDescriptionAttributeValue ) && content.Count > 0 ) { string attributeValue = GetMetaValueFromAttribute(metaDescriptionAttributeValue, content); if ( !string.IsNullOrWhiteSpace( attributeValue ) ) { // remove default meta description RockPage.Header.Description = attributeValue.SanitizeHtml( true ); } } // add meta images string metaImageAttributeValue = GetAttributeValue( "MetaImageAttribute" ); if ( !string.IsNullOrWhiteSpace( metaImageAttributeValue ) && content.Count > 0 ) { string attributeValue = GetMetaValueFromAttribute( metaImageAttributeValue, content ); if ( !string.IsNullOrWhiteSpace( attributeValue ) ) { HtmlMeta metaDescription = new HtmlMeta(); metaDescription.Name = "og:image"; metaDescription.Content = string.Format( "{0}://{1}/GetImage.ashx?guid={2}", Request.Url.Scheme, Request.Url.Authority, attributeValue ); RockPage.Header.Controls.Add( metaDescription ); HtmlLink imageLink = new HtmlLink(); imageLink.Attributes.Add( "rel", "image_src" ); imageLink.Attributes.Add( "href", string.Format( "{0}://{1}/GetImage.ashx?guid={2}", Request.Url.Scheme, Request.Url.Authority, attributeValue )); RockPage.Header.Controls.Add( imageLink ); } } var template = GetTemplate(); if ( template.InstanceAssigns.ContainsKey( "EnabledCommands" ) ) { template.InstanceAssigns["EnabledCommands"] = GetAttributeValue( "EnabledLavaCommands" ); } else // this should never happen { template.InstanceAssigns.Add( "EnabledCommands", GetAttributeValue( "EnabledLavaCommands" ) ); } phContent.Controls.Add( new LiteralControl( template.Render( Hash.FromDictionary( mergeFields ) ) ) ); }
/// <summary> /// Loads all of the configured blocks for the current page into the control tree /// </summary> /// <param name="e"></param> protected override void OnInit( EventArgs e ) { var slDebugTimings = new StringBuilder(); var stopwatchInitEvents = Stopwatch.StartNew(); bool showDebugTimings = this.PageParameter( "ShowDebugTimings" ).AsBoolean(); bool canAdministratePage = false; if ( showDebugTimings ) { TimeSpan tsDuration = RockDateTime.Now.Subtract( (DateTime)Context.Items["Request_Start_Time"] ); slDebugTimings.AppendFormat( "OnInit [{0}ms] @ {1} \n", stopwatchInitEvents.Elapsed.TotalMilliseconds, tsDuration.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // Add the ScriptManager to each page _scriptManager = ScriptManager.GetCurrent( this.Page ); if ( _scriptManager == null ) { _scriptManager = new ScriptManager { ID = "sManager" }; Page.Trace.Warn( "Adding script manager" ); Page.Form.Controls.AddAt( 0, _scriptManager ); } // enable history on the ScriptManager _scriptManager.EnableHistory = true; // TODO: Delete this line, only used for testing _scriptManager.AsyncPostBackTimeout = 180; // wire up navigation event _scriptManager.Navigate += new EventHandler<HistoryEventArgs>( scriptManager_Navigate ); // Add library and UI bundles during init, that way theme developers will only // need to worry about registering any custom scripts or script bundles they need _scriptManager.Scripts.Add( new ScriptReference( "~/Bundles/WebFormsJs" ) ); _scriptManager.Scripts.Add( new ScriptReference( "~/Scripts/Bundles/RockLibs" ) ); _scriptManager.Scripts.Add( new ScriptReference( "~/Scripts/Bundles/RockUi" ) ); _scriptManager.Scripts.Add( new ScriptReference( "~/Scripts/Bundles/RockValidation" ) ); // Recurse the page controls to find the rock page title and zone controls Page.Trace.Warn( "Recursing layout to find zones" ); Zones = new Dictionary<string, KeyValuePair<string, Zone>>(); FindRockControls( this.Controls ); // Add a Rock version meta tag Page.Trace.Warn( "Adding Rock metatag" ); string version = typeof( Rock.Web.UI.RockPage ).Assembly.GetName().Version.ToString(); HtmlMeta rockVersion = new HtmlMeta(); rockVersion.Attributes.Add( "name", "generator" ); rockVersion.Attributes.Add( "content", string.Format( "Rock v{0}", version ) ); AddMetaTag( this.Page, rockVersion ); if ( showDebugTimings ) { slDebugTimings.AppendFormat( "CheckingForLogout [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // If the logout parameter was entered, delete the user's forms authentication cookie and redirect them // back to the same page. Page.Trace.Warn( "Checking for logout request" ); if ( PageParameter( "logout" ) != string.Empty ) { if ( CurrentUser != null ) { var transaction = new Rock.Transactions.UserLastActivityTransaction(); transaction.UserId = CurrentUser.Id; transaction.LastActivityDate = RockDateTime.Now; transaction.IsOnLine = false; Rock.Transactions.RockQueue.TransactionQueue.Enqueue( transaction ); } FormsAuthentication.SignOut(); // After logging out check to see if an anonymous user is allowed to view the current page. If so // redirect back to the current page, otherwise redirect to the site's default page if ( _pageCache != null ) { if ( _pageCache.IsAuthorized( Authorization.VIEW, null ) ) { // Remove the 'logout' queryparam before redirecting var pageReference = new PageReference( PageReference.PageId, PageReference.RouteId, PageReference.Parameters ); foreach ( string key in PageReference.QueryString ) { if ( !key.Equals( "logout", StringComparison.OrdinalIgnoreCase ) ) { pageReference.Parameters.Add( key, PageReference.QueryString[key] ); } } Response.Redirect( pageReference.BuildUrl(), false ); Context.ApplicationInstance.CompleteRequest(); } else { _pageCache.Layout.Site.RedirectToDefaultPage(); } return; } else { CurrentPerson = null; CurrentUser = null; } } var rockContext = new RockContext(); if ( showDebugTimings ) { slDebugTimings.AppendFormat( "CreateRockContext [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // If the impersonated query key was included then set the current person Page.Trace.Warn( "Checking for person impersanation" ); string impersonatedPersonKey = PageParameter( "rckipid" ); if ( !String.IsNullOrEmpty( impersonatedPersonKey ) ) { Rock.Model.PersonService personService = new Model.PersonService( rockContext ); Rock.Model.Person impersonatedPerson = personService.GetByEncryptedKey( impersonatedPersonKey ); if ( impersonatedPerson == null ) { impersonatedPerson = personService.GetByUrlEncodedKey( impersonatedPersonKey ); } if ( impersonatedPerson != null ) { Rock.Security.Authorization.SetAuthCookie( "rckipid=" + impersonatedPerson.EncryptedKey, false, true ); CurrentUser = impersonatedPerson.GetImpersonatedUser(); } } // Get current user/person info Page.Trace.Warn( "Getting CurrentUser" ); Rock.Model.UserLogin user = CurrentUser; if ( showDebugTimings ) { slDebugTimings.AppendFormat( "GetCurrentUser [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // If there is a logged in user, see if it has an associated Person Record. If so, set the UserName to // the person's full name (which is then cached in the Session state for future page requests) if ( user != null ) { Page.Trace.Warn( "Setting CurrentPerson" ); UserName = user.UserName; int? personId = user.PersonId; if ( personId.HasValue ) { string personNameKey = "PersonName_" + personId.Value.ToString(); if ( Session[personNameKey] != null ) { UserName = Session[personNameKey].ToString(); } else { Rock.Model.PersonService personService = new Model.PersonService( rockContext ); Rock.Model.Person person = personService.Get( personId.Value ); if ( person != null ) { UserName = person.FullName; CurrentPerson = person; } Session[personNameKey] = UserName; } } if ( showDebugTimings ) { slDebugTimings.AppendFormat( "GetCurrentPerson [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // check that they aren't required to change their password if ( user.IsPasswordChangeRequired == true && Site.ChangePasswordPageReference != null ) { // don't redirect if this is the change password page if ( Site.ChangePasswordPageReference.PageId != this.PageId ) { Site.RedirectToChangePasswordPage( true, true ); } } } // If a PageInstance exists if ( _pageCache != null ) { BrowserTitle = _pageCache.BrowserTitle; PageTitle = _pageCache.PageTitle; PageIcon = _pageCache.IconCssClass; BodyCssClass = _pageCache.BodyCssClass; // If there's a master page, update its reference to Current Page if ( this.Master is RockMasterPage ) { ( (RockMasterPage)this.Master ).SetPage( _pageCache ); } // Add CSS class to body if ( !string.IsNullOrWhiteSpace( this.BodyCssClass ) ) { // attempt to find the body tag var body = (HtmlGenericControl)this.Master.FindControl( "body" ); if ( body != null ) { body.Attributes.Add( "class", this.BodyCssClass ); } } // check if page should have been loaded via ssl Page.Trace.Warn( "Checking for SSL request" ); if ( !Request.IsSecureConnection && (_pageCache.RequiresEncryption || Site.RequiresEncryption) ) { string redirectUrl = Request.Url.ToString().Replace( "http:", "https:" ); Response.Redirect( redirectUrl, false ); Context.ApplicationInstance.CompleteRequest(); return; } // Verify that the current user is allowed to view the page. Page.Trace.Warn( "Checking if user is authorized" ); var isCurrentPersonAuthorized = _pageCache.IsAuthorized( Authorization.VIEW, CurrentPerson ); if ( showDebugTimings ) { slDebugTimings.AppendFormat( "isCurrentPersonAuthorized [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } if ( !isCurrentPersonAuthorized ) { if ( user == null ) { // If not authorized, and the user hasn't logged in yet, redirect to the login page Page.Trace.Warn( "Redirecting to login page" ); var site = _pageCache.Layout.Site; if ( site.LoginPageId.HasValue ) { site.RedirectToLoginPage( true ); } else { FormsAuthentication.RedirectToLoginPage(); } } else { // If not authorized, and the user has logged in, redirect to error page Page.Trace.Warn( "Redirecting to error page" ); Response.Redirect( "~/Error.aspx?type=security", false ); Context.ApplicationInstance.CompleteRequest(); } } else { // Set current models (context) Page.Trace.Warn( "Checking for Context" ); ModelContext = new Dictionary<string, Data.KeyEntity>(); try { char[] delim = new char[1] { ',' }; // Check to see if a context from query string should be saved to a cookie first foreach ( string param in PageParameter( "SetContext", true ).Split( delim, StringSplitOptions.RemoveEmptyEntries ) ) { string[] parts = param.Split( '|' ); if ( parts.Length == 2 ) { var contextModelEntityType = EntityTypeCache.Read( parts[0], false, rockContext ); int? contextId = parts[1].AsIntegerOrNull(); if ( contextModelEntityType != null && contextId.HasValue ) { var contextModelType = contextModelEntityType.GetEntityType(); var contextDbContext = Reflection.GetDbContextForEntityType( contextModelType ); if ( contextDbContext != null ) { var contextService = Reflection.GetServiceForEntityType( contextModelType, contextDbContext ); if ( contextService != null ) { MethodInfo getMethod = contextService.GetType().GetMethod( "Get", new Type[] { typeof( int ) } ); if ( getMethod != null ) { var getResult = getMethod.Invoke( contextService, new object[] { contextId.Value } ); var contextEntity = getResult as IEntity; if ( contextEntity != null ) { SetContextCookie( contextEntity, false, false ); } } } } } } } if ( showDebugTimings ) { slDebugTimings.AppendFormat( "Set Page Context(s) [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // first search the cookies for any saved context, but pageContext can replace it GetCookieContext( GetContextCookieName( false ) ); // Site GetCookieContext( GetContextCookieName( true ) ); // Page (will replace any site values) // check for page context foreach ( var pageContext in _pageCache.PageContexts ) { int? contextId = PageParameter( pageContext.Value ).AsIntegerOrNull(); if ( contextId.HasValue ) { ModelContext.AddOrReplace( pageContext.Key, new Data.KeyEntity( contextId.Value ) ); } } // check for any encrypted contextkeys specified in query string foreach ( string param in PageParameter( "context", true ).Split( delim, StringSplitOptions.RemoveEmptyEntries ) ) { string contextItem = Rock.Security.Encryption.DecryptString( param ); string[] parts = contextItem.Split( '|' ); if ( parts.Length == 2 ) { ModelContext.AddOrReplace( parts[0], new Data.KeyEntity( parts[1] ) ); } } if ( showDebugTimings ) { slDebugTimings.AppendFormat( "Check Page Context(s) [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } } catch { // intentionally ignore exception } // set viewstate on/off this.EnableViewState = _pageCache.EnableViewState; Page.Trace.Warn( "Checking if user can administer" ); canAdministratePage = _pageCache.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ); if ( showDebugTimings ) { slDebugTimings.AppendFormat( "canAdministratePage [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // Create a javascript object to store information about the current page for client side scripts to use Page.Trace.Warn( "Creating JS objects" ); if ( !ClientScript.IsStartupScriptRegistered( "rock-js-object" ) ) { string script = string.Format( @" Rock.settings.initialize({{ siteId: {0}, layoutId: {1}, pageId: {2}, layout: '{3}', baseUrl: '{4}' }});", _pageCache.Layout.SiteId, _pageCache.LayoutId, _pageCache.Id, _pageCache.Layout.FileName, ResolveUrl( "~" ) ); ClientScript.RegisterStartupScript( this.Page.GetType(), "rock-js-object", script, true ); } AddTriggerPanel(); // Add config elements if ( _pageCache.IncludeAdminFooter ) { Page.Trace.Warn( "Adding popup controls (footer elements)" ); AddPopupControls(); Page.Trace.Warn( "Adding zone elements" ); AddZoneElements( canAdministratePage ); } // Initialize the list of breadcrumbs for the current page (and blocks on the page) Page.Trace.Warn( "Setting breadcrumbs" ); PageReference.BreadCrumbs = new List<BreadCrumb>(); // If the page is configured to display in the breadcrumbs... string bcName = _pageCache.BreadCrumbText; if ( bcName != string.Empty ) { PageReference.BreadCrumbs.Add( new BreadCrumb( bcName, PageReference.BuildUrl() ) ); } // Add the Google Analytics Code script if a code was specified for the site if ( !string.IsNullOrWhiteSpace( _pageCache.Layout.Site.GoogleAnalyticsCode ) ) { AddGoogleAnalytics( _pageCache.Layout.Site.GoogleAnalyticsCode ); } // Flag indicating if user has rights to administer one or more of the blocks on page bool canAdministrateBlockOnPage = false; if ( showDebugTimings ) { slDebugTimings.AppendFormat( "start loading blocks [{0}ms]\n", stopwatchInitEvents.Elapsed.TotalMilliseconds ); stopwatchInitEvents.Restart(); } // Load the blocks and insert them into page zones Page.Trace.Warn( "Loading Blocks" ); var pageBlocks = _pageCache.Blocks; foreach ( Rock.Web.Cache.BlockCache block in pageBlocks ) { var stopwatchBlockInit= Stopwatch.StartNew(); Page.Trace.Warn( string.Format( "\tLoading '{0}' block", block.Name ) ); // Get current user's permissions for the block instance Page.Trace.Warn( "\tChecking permission" ); bool canAdministrate = block.IsAuthorized( Authorization.ADMINISTRATE, CurrentPerson ); bool canEdit = block.IsAuthorized( Authorization.EDIT, CurrentPerson ); bool canView = block.IsAuthorized( Authorization.VIEW, CurrentPerson ); // Make sure user has access to view block instance if ( canAdministrate || canEdit || canView ) { // Load the control and add to the control tree Page.Trace.Warn( "\tLoading control" ); Control control = null; // Check to see if block is configured to use a "Cache Duration' if ( block.OutputCacheDuration > 0 ) { // Cache object used for block output caching Page.Trace.Warn( "Getting memory cache" ); RockMemoryCache cache = RockMemoryCache.Default; string blockCacheKey = string.Format( "Rock:BlockOutput:{0}", block.Id ); if ( cache.Contains( blockCacheKey ) ) { // If the current block exists in our custom output cache, add the cached output instead of adding the control control = new LiteralControl( cache[blockCacheKey] as string ); } } if ( control == null ) { try { control = TemplateControl.LoadControl( block.BlockType.Path ); control.ClientIDMode = ClientIDMode.AutoID; } catch ( Exception ex ) { NotificationBox nbBlockLoad = new NotificationBox(); nbBlockLoad.ID = string.Format( "nbBlockLoad_{0}", block.Id ); nbBlockLoad.CssClass = "system-error"; nbBlockLoad.NotificationBoxType = NotificationBoxType.Danger; nbBlockLoad.Text = string.Format( "Error Loading Block: {0}", block.Name ); nbBlockLoad.Details = string.Format( "{0}<pre>{1}</pre>", HttpUtility.HtmlEncode( ex.Message ), HttpUtility.HtmlEncode( ex.StackTrace ) ); nbBlockLoad.Dismissable = true; control = nbBlockLoad; if ( this.IsPostBack ) { // throw an error on PostBack so that the ErrorPage gets shown (vs nothing happening) throw; } } } if ( control != null ) { if ( canAdministrate || ( canEdit && control is RockBlockCustomSettings ) ) { canAdministrateBlockOnPage = true; } // If the current control is a block, set its properties var blockControl = control as RockBlock; if ( blockControl != null ) { Page.Trace.Warn( "\tSetting block properties" ); blockControl.SetBlock( _pageCache, block, canEdit, canAdministrate ); control = new RockBlockWrapper( blockControl ); // Add any breadcrumbs to current page reference that the block creates Page.Trace.Warn( "\tAdding any breadcrumbs from block" ); if ( block.BlockLocation == BlockLocation.Page ) { blockControl.GetBreadCrumbs( PageReference ).ForEach( c => PageReference.BreadCrumbs.Add( c ) ); } // If the blocktype's security actions have not yet been loaded, load them now block.BlockType.SetSecurityActions( blockControl ); // If the block's AttributeProperty values have not yet been verified verify them. // (This provides a mechanism for block developers to define the needed block // attributes in code and have them automatically added to the database) Page.Trace.Warn( "\tChecking if block attributes need refresh" ); if ( !block.BlockType.IsInstancePropertiesVerified ) { Page.Trace.Warn( "\tCreating block attributes" ); if ( blockControl.CreateAttributes( rockContext ) ) { // If attributes were updated, update the block attributes for all blocks in page of same type pageBlocks .Where( b => b.BlockTypeId == block.BlockTypeId ) .ToList() .ForEach( b => b.ReloadAttributeValues() ); } block.BlockType.IsInstancePropertiesVerified = true; } } } FindZone( block.Zone ).Controls.Add( control ); if ( control is RockBlockWrapper ) { ( (RockBlockWrapper)control ).EnsureBlockControls(); } if ( showDebugTimings ) { stopwatchBlockInit.Stop(); slDebugTimings.AppendFormat( "create/init block {0} <span class='label label-{2}'>[{1}ms]</span>\n", block.Name, stopwatchBlockInit.Elapsed.TotalMilliseconds, stopwatchBlockInit.Elapsed.TotalMilliseconds > 500 ? "danger" : "info"); } } } // Make the last crumb for this page the active one Page.Trace.Warn( "Setting active breadcrumb" ); if ( PageReference.BreadCrumbs.Any() ) { PageReference.BreadCrumbs.Last().Active = true; } Page.Trace.Warn( "Getting parent page references" ); var pageReferences = PageReference.GetParentPageReferences( this, _pageCache, PageReference ); pageReferences.Add( PageReference ); PageReference.SavePageReferences( pageReferences ); // Update breadcrumbs Page.Trace.Warn( "Updating breadcrumbs" ); BreadCrumbs = new List<BreadCrumb>(); foreach ( var pageReference in pageReferences ) { pageReference.BreadCrumbs.ForEach( c => BreadCrumbs.Add( c ) ); } // Add the page admin footer if the user is authorized to edit the page if ( _pageCache.IncludeAdminFooter && ( canAdministratePage || canAdministrateBlockOnPage ) ) { // Add the page admin script AddScriptLink( Page, "~/Scripts/Bundles/RockAdmin", false ); Page.Trace.Warn( "Adding admin footer to page" ); HtmlGenericControl adminFooter = new HtmlGenericControl( "div" ); adminFooter.ID = "cms-admin-footer"; adminFooter.ClientIDMode = System.Web.UI.ClientIDMode.Static; this.Form.Controls.Add( adminFooter ); phLoadStats = new PlaceHolder(); adminFooter.Controls.Add( phLoadStats ); HtmlGenericControl buttonBar = new HtmlGenericControl( "div" ); adminFooter.Controls.Add( buttonBar ); buttonBar.Attributes.Add( "class", "button-bar" ); // RockBlock Config HtmlGenericControl aBlockConfig = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aBlockConfig ); aBlockConfig.Attributes.Add( "class", "btn block-config" ); aBlockConfig.Attributes.Add( "href", "javascript: Rock.admin.pageAdmin.showBlockConfig();" ); aBlockConfig.Attributes.Add( "Title", "Block Configuration" ); HtmlGenericControl iBlockConfig = new HtmlGenericControl( "i" ); aBlockConfig.Controls.Add( iBlockConfig ); iBlockConfig.Attributes.Add( "class", "fa fa-th-large" ); if ( canAdministratePage ) { // RockPage Properties HtmlGenericControl aAttributes = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aAttributes ); aAttributes.ID = "aPageProperties"; aAttributes.ClientIDMode = System.Web.UI.ClientIDMode.Static; aAttributes.Attributes.Add( "class", "btn properties" ); aAttributes.Attributes.Add( "height", "500px" ); aAttributes.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( string.Format( "~/PageProperties/{0}?t=Page Properties", _pageCache.Id ) ) + "')" ); aAttributes.Attributes.Add( "Title", "Page Properties" ); HtmlGenericControl iAttributes = new HtmlGenericControl( "i" ); aAttributes.Controls.Add( iAttributes ); iAttributes.Attributes.Add( "class", "fa fa-cog" ); // Child Pages HtmlGenericControl aChildPages = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aChildPages ); aChildPages.ID = "aChildPages"; aChildPages.ClientIDMode = System.Web.UI.ClientIDMode.Static; aChildPages.Attributes.Add( "class", "btn page-child-pages" ); aChildPages.Attributes.Add( "height", "500px" ); aChildPages.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( string.Format( "~/pages/{0}?t=Child Pages&pb=&sb=Done", _pageCache.Id ) ) + "')" ); aChildPages.Attributes.Add( "Title", "Child Pages" ); HtmlGenericControl iChildPages = new HtmlGenericControl( "i" ); aChildPages.Controls.Add( iChildPages ); iChildPages.Attributes.Add( "class", "fa fa-sitemap" ); // RockPage Zones HtmlGenericControl aPageZones = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aPageZones ); aPageZones.Attributes.Add( "class", "btn page-zones" ); aPageZones.Attributes.Add( "href", "javascript: Rock.admin.pageAdmin.showPageZones();" ); aPageZones.Attributes.Add( "Title", "Page Zones" ); HtmlGenericControl iPageZones = new HtmlGenericControl( "i" ); aPageZones.Controls.Add( iPageZones ); iPageZones.Attributes.Add( "class", "fa fa-columns" ); // RockPage Security HtmlGenericControl aPageSecurity = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aPageSecurity ); aPageSecurity.ID = "aPageSecurity"; aPageSecurity.ClientIDMode = System.Web.UI.ClientIDMode.Static; aPageSecurity.Attributes.Add( "class", "btn page-security" ); aPageSecurity.Attributes.Add( "height", "500px" ); aPageSecurity.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( string.Format( "~/Secure/{0}/{1}?t=Page Security&pb=&sb=Done", EntityTypeCache.Read( typeof( Rock.Model.Page ) ).Id, _pageCache.Id ) ) + "')" ); aPageSecurity.Attributes.Add( "Title", "Page Security" ); HtmlGenericControl iPageSecurity = new HtmlGenericControl( "i" ); aPageSecurity.Controls.Add( iPageSecurity ); iPageSecurity.Attributes.Add( "class", "fa fa-lock" ); // System Info HtmlGenericControl aSystemInfo = new HtmlGenericControl( "a" ); buttonBar.Controls.Add( aSystemInfo ); aSystemInfo.ID = "aSystemInfo"; aSystemInfo.ClientIDMode = System.Web.UI.ClientIDMode.Static; aSystemInfo.Attributes.Add( "class", "btn system-info" ); aSystemInfo.Attributes.Add( "height", "500px" ); aSystemInfo.Attributes.Add( "href", "javascript: Rock.controls.modal.show($(this), '" + ResolveUrl( "~/SystemInfo?t=System Information&pb=&sb=Done" ) + "')" ); aSystemInfo.Attributes.Add( "Title", "Rock Information" ); HtmlGenericControl iSystemInfo = new HtmlGenericControl( "i" ); aSystemInfo.Controls.Add( iSystemInfo ); iSystemInfo.Attributes.Add( "class", "fa fa-info-circle" ); } } // Check to see if page output should be cached. The RockRouteHandler // saves the PageCacheData information for the current page to memorycache // so it should always exist if ( _pageCache.OutputCacheDuration > 0 ) { Response.Cache.SetCacheability( System.Web.HttpCacheability.Public ); Response.Cache.SetExpires( RockDateTime.Now.AddSeconds( _pageCache.OutputCacheDuration ) ); Response.Cache.SetValidUntilExpires( true ); } // create a page view transaction if enabled if ( !Page.IsPostBack && _pageCache != null ) { if ( _pageCache.Layout.Site.EnablePageViews ) { PageViewTransaction transaction = new PageViewTransaction(); transaction.DateViewed = RockDateTime.Now; transaction.PageId = _pageCache.Id; transaction.SiteId = _pageCache.Layout.Site.Id; if ( CurrentPersonAlias != null ) { transaction.PersonAliasId = CurrentPersonAlias.Id; } transaction.IPAddress = GetClientIpAddress(); transaction.UserAgent = Request.UserAgent ?? ""; transaction.Url = Request.Url.ToString(); transaction.PageTitle = _pageCache.PageTitle; var sessionId = Session["RockSessionID"]; if ( sessionId != null ) { transaction.SessionId = sessionId.ToString(); } RockQueue.TransactionQueue.Enqueue( transaction ); } } } stopwatchInitEvents.Restart(); string pageTitle = BrowserTitle ?? string.Empty; string siteTitle = _pageCache.Layout.Site.Name; string seperator = pageTitle.Trim() != string.Empty && siteTitle.Trim() != string.Empty ? " | " : ""; base.Title = pageTitle + seperator + siteTitle; if ( !string.IsNullOrWhiteSpace( _pageCache.Description ) ) { HtmlMeta metaTag = new HtmlMeta(); metaTag.Attributes.Add( "name", "description" ); metaTag.Attributes.Add( "content", _pageCache.Description.Trim() ); AddMetaTag( this.Page, metaTag ); } if ( !string.IsNullOrWhiteSpace( _pageCache.KeyWords ) ) { HtmlMeta metaTag = new HtmlMeta(); metaTag.Attributes.Add( "name", "keywords" ); metaTag.Attributes.Add( "content", _pageCache.KeyWords.Trim() ); AddMetaTag( this.Page, metaTag ); } if (!string.IsNullOrWhiteSpace( _pageCache.Layout.Site.PageHeaderContent )) { Page.Header.Controls.Add( new LiteralControl( _pageCache.Layout.Site.PageHeaderContent ) ); } if ( !string.IsNullOrWhiteSpace( _pageCache.HeaderContent ) ) { Page.Header.Controls.Add( new LiteralControl( _pageCache.HeaderContent ) ); } if ( !_pageCache.AllowIndexing || !_pageCache.Layout.Site.AllowIndexing ) { Page.Header.Controls.Add( new LiteralControl( "<meta name=\"robots\" content=\"noindex, nofollow\"/>" ) ); } if ( showDebugTimings ) { TimeSpan tsDuration = RockDateTime.Now.Subtract( (DateTime)Context.Items["Request_Start_Time"] ); slDebugTimings.AppendFormat( "done oninit [{0}ms] @ {1} \n", stopwatchInitEvents.Elapsed.TotalMilliseconds, tsDuration.TotalMilliseconds ); stopwatchInitEvents.Restart(); } if ( showDebugTimings && canAdministratePage ) { Page.Form.Controls.Add( new Label { ID="lblShowDebugTimings", Text = string.Format( "<pre>{0}</pre>", slDebugTimings.ToString() ) } ); } } }
/// <summary> /// Shows the preview. /// </summary> /// <param name="report">The report.</param> /// <param name="gReport">The g report.</param> /// <param name="currentPerson">The current person.</param> /// <param name="databaseTimeoutSeconds">The database timeout seconds.</param> /// <param name="errorMessage">The error message.</param> public static void BindGrid( Report report, Grid gReport, Person currentPerson, int? databaseTimeoutSeconds, out string errorMessage ) { errorMessage = null; if ( report != null ) { var errors = new List<string>(); if ( !report.EntityTypeId.HasValue ) { gReport.Visible = false; return; } var rockContext = new RockContext(); if ( !report.IsAuthorized( Authorization.VIEW, currentPerson ) ) { gReport.Visible = false; return; } Type entityType = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).GetEntityType(); if ( entityType == null ) { errorMessage = string.Format( "Unable to determine entityType for {0}", report.EntityType ); return; } gReport.EntityTypeId = report.EntityTypeId; bool isPersonDataSet = report.EntityTypeId == EntityTypeCache.Read( typeof( Rock.Model.Person ), true, rockContext ).Id; if ( isPersonDataSet ) { gReport.PersonIdField = "Id"; gReport.DataKeyNames = new string[] { "Id" }; } else { gReport.PersonIdField = null; } if ( report.EntityTypeId.HasValue ) { gReport.RowItemText = EntityTypeCache.Read( report.EntityTypeId.Value, rockContext ).FriendlyName; } List<EntityField> entityFields = Rock.Reporting.EntityHelper.GetEntityFields( entityType, true, false ); var selectedEntityFields = new Dictionary<int, EntityField>(); var selectedAttributes = new Dictionary<int, AttributeCache>(); var selectedComponents = new Dictionary<int, ReportField>(); // if there is a selectField, keep it to preserve which items are checked var selectField = gReport.Columns.OfType<SelectField>().FirstOrDefault(); gReport.Columns.Clear(); int columnIndex = 0; if ( !string.IsNullOrWhiteSpace( gReport.PersonIdField ) ) { // if we already had a selectField, use it (to preserve checkbox state) gReport.Columns.Add( selectField ?? new SelectField() ); columnIndex++; } var reportFieldSortExpressions = new Dictionary<Guid, string>(); foreach ( var reportField in report.ReportFields.OrderBy( a => a.ColumnOrder ) ) { columnIndex++; if ( reportField.ReportFieldType == ReportFieldType.Property ) { var entityField = entityFields.FirstOrDefault( a => a.Name == reportField.Selection ); if ( entityField != null ) { selectedEntityFields.Add( columnIndex, entityField ); BoundField boundField = entityField.GetBoundFieldType(); boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex ); boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? entityField.Title : reportField.ColumnHeaderText; boundField.SortExpression = boundField.DataField; reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression ); boundField.Visible = reportField.ShowInGrid; gReport.Columns.Add( boundField ); } } else if ( reportField.ReportFieldType == ReportFieldType.Attribute ) { Guid? attributeGuid = reportField.Selection.AsGuidOrNull(); if ( attributeGuid.HasValue ) { var attribute = AttributeCache.Read( attributeGuid.Value, rockContext ); if ( attribute != null ) { selectedAttributes.Add( columnIndex, attribute ); BoundField boundField; if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.BOOLEAN.AsGuid() ) ) { boundField = new BoolField(); } else if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DEFINED_VALUE.AsGuid() ) ) { boundField = new DefinedValueField(); } else { boundField = new CallbackField(); boundField.HtmlEncode = false; ( boundField as CallbackField ).OnFormatDataValue += (sender, e) => { string resultHtml = null; if (e.DataValue != null) { bool condensed = true; resultHtml = attribute.FieldType.Field.FormatValueAsHtml( gReport, e.DataValue.ToString(), attribute.QualifierValues, condensed ); } e.FormattedValue = resultHtml ?? string.Empty; }; } boundField.DataField = string.Format( "Attribute_{0}_{1}", attribute.Id, columnIndex ); boundField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? attribute.Name : reportField.ColumnHeaderText; boundField.SortExpression = boundField.DataField; reportFieldSortExpressions.AddOrReplace( reportField.Guid, boundField.SortExpression ); if ( attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.INTEGER.AsGuid() ) || attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.DATE.AsGuid() ) || attribute.FieldType.Guid.Equals( Rock.SystemGuid.FieldType.FILTER_DATE.AsGuid() ) ) { boundField.HeaderStyle.HorizontalAlign = HorizontalAlign.Right; boundField.ItemStyle.HorizontalAlign = HorizontalAlign.Right; } boundField.Visible = reportField.ShowInGrid; gReport.Columns.Add( boundField ); } } } else if ( reportField.ReportFieldType == ReportFieldType.DataSelectComponent ) { selectedComponents.Add( columnIndex, reportField ); DataSelectComponent selectComponent = DataSelectContainer.GetComponent( reportField.DataSelectComponentEntityType.Name ); if ( selectComponent != null ) { try { DataControlField columnField = selectComponent.GetGridField( entityType, reportField.Selection ?? string.Empty ); if ( columnField is BoundField ) { ( columnField as BoundField ).DataField = string.Format( "Data_{0}_{1}", selectComponent.ColumnPropertyName, columnIndex ); var customSortProperties = selectComponent.SortProperties( reportField.Selection ?? string.Empty ); bool sortReversed = selectComponent.SortReversed( reportField.Selection ?? string.Empty ); if ( customSortProperties != null ) { if ( customSortProperties == string.Empty ) { // disable sorting if customSortExpression set to string.empty columnField.SortExpression = string.Empty; } else { columnField.SortExpression = customSortProperties.Split( ',' ).Select( a => string.Format( "Sort_{0}_{1}", a, columnIndex ) ).ToList().AsDelimited( "," ); } } else { // use default sorting if customSortExpression was null columnField.SortExpression = ( columnField as BoundField ).DataField; } if ( sortReversed == true && !string.IsNullOrWhiteSpace( columnField.SortExpression ) ) { columnField.SortExpression = columnField.SortExpression + " DESC"; } } columnField.HeaderText = string.IsNullOrWhiteSpace( reportField.ColumnHeaderText ) ? selectComponent.ColumnHeaderText : reportField.ColumnHeaderText; if ( !string.IsNullOrEmpty( columnField.SortExpression ) ) { reportFieldSortExpressions.AddOrReplace( reportField.Guid, columnField.SortExpression ); } columnField.Visible = reportField.ShowInGrid; gReport.Columns.Add( columnField ); } catch ( Exception ex ) { ExceptionLogService.LogException( ex, HttpContext.Current ); errors.Add( string.Format( "{0} - {1}", selectComponent, ex.Message ) ); } } } } // if no fields are specified, show the default fields (Previewable/All) for the EntityType var dataColumns = gReport.Columns.OfType<object>().Where( a => a.GetType() != typeof( SelectField ) ); if ( dataColumns.Count() == 0 ) { // show either the Previewable Columns or all (if there are no previewable columns) bool showAllColumns = !entityFields.Any( a => a.FieldKind == FieldKind.Property && a.IsPreviewable ); foreach ( var entityField in entityFields.Where( a => a.FieldKind == FieldKind.Property ) ) { columnIndex++; selectedEntityFields.Add( columnIndex, entityField ); BoundField boundField = entityField.GetBoundFieldType(); boundField.DataField = string.Format( "Entity_{0}_{1}", entityField.Name, columnIndex ); boundField.HeaderText = entityField.Name; boundField.SortExpression = boundField.DataField; boundField.Visible = showAllColumns || entityField.IsPreviewable; gReport.Columns.Add( boundField ); } } try { gReport.Visible = true; gReport.ExportFilename = report.Name; SortProperty sortProperty = gReport.SortProperty; if ( sortProperty == null ) { var reportSort = new SortProperty(); var sortColumns = new Dictionary<string, SortDirection>(); foreach ( var reportField in report.ReportFields.Where( a => a.SortOrder.HasValue ).OrderBy( a => a.SortOrder.Value ) ) { if ( reportFieldSortExpressions.ContainsKey( reportField.Guid ) ) { var sortField = reportFieldSortExpressions[reportField.Guid]; if ( !string.IsNullOrWhiteSpace( sortField ) ) { sortColumns.Add( sortField, reportField.SortDirection ); } } } if ( sortColumns.Any() ) { reportSort.Property = sortColumns.Select( a => a.Key + ( a.Value == SortDirection.Descending ? " desc" : string.Empty ) ).ToList().AsDelimited( "," ); sortProperty = reportSort; } } var qryErrors = new List<string>(); dynamic qry = report.GetQueryable( entityType, selectedEntityFields, selectedAttributes, selectedComponents, sortProperty, databaseTimeoutSeconds ?? 180, out qryErrors ); errors.AddRange( qryErrors ); gReport.SetLinqDataSource( qry ); gReport.DataBind(); } catch ( Exception ex ) { Exception exception = ex; ExceptionLogService.LogException( ex, HttpContext.Current ); while ( exception != null ) { if ( exception is System.Data.SqlClient.SqlException ) { // if there was a SQL Server Timeout, have the warning be a friendly message about that. if ( ( exception as System.Data.SqlClient.SqlException ).Number == -2 ) { errorMessage = "This report did not complete in a timely manner. You can try again or adjust the timeout setting of this block."; return; } else { errors.Add( exception.Message ); exception = exception.InnerException; } } else { errors.Add( exception.Message ); exception = exception.InnerException; } } } if ( errors.Any() ) { errorMessage = "WARNING: There was a problem with one or more of the report's data components...<br/><br/> " + errors.AsDelimited( "<br/>" ); } } }
/// <summary> /// Loads the chart. /// </summary> public void LoadChart() { lcAttendance.ShowTooltip = true; if ( this.DetailPageGuid.HasValue ) { lcAttendance.ChartClick += lcAttendance_ChartClick; } lcAttendance.Options.SetChartStyle( this.GetAttributeValue( "ChartStyle" ).AsGuidOrNull() ); var dataSourceUrl = "~/api/Attendances/GetChartData"; var dataSourceParams = new Dictionary<string, object>(); var dateRange = SlidingDateRangePicker.CalculateDateRangeFromDelimitedValues( drpSlidingDateRange.DelimitedValues ); if ( dateRange.Start.HasValue ) { dataSourceParams.AddOrReplace( "startDate", dateRange.Start.Value.ToString( "o" ) ); } if ( dateRange.End.HasValue ) { dataSourceParams.AddOrReplace( "endDate", dateRange.End.Value.ToString( "o" ) ); } dataSourceParams.AddOrReplace( "groupBy", hfGroupBy.Value.AsInteger() ); dataSourceParams.AddOrReplace( "graphBy", hfGraphBy.Value.AsInteger() ); dataSourceParams.AddOrReplace( "campusIds", cpCampuses.SelectedCampusIds.AsDelimited( "," ) ); SaveSettingsToUserPreferences(); dataSourceUrl += "?" + dataSourceParams.Select( s => string.Format( "{0}={1}", s.Key, s.Value ) ).ToList().AsDelimited( "&" ); lcAttendance.DataSourceUrl = this.ResolveUrl( dataSourceUrl ); if ( pnlGrid.Visible ) { BindGrid(); } }
public BlockAndValidity(Dictionary<uint256, int> blockToHeightMap, Dictionary<uint256, Block> hashHeaderMap, Block block, bool connects, bool throwsException, uint256 hashChainTipAfterBlock, int heightAfterBlock, String blockName) : base(blockName) { if(connects && throwsException) throw new InvalidOperationException("A block cannot connect if an exception was thrown while adding it."); this.block = block; this.blockHash = block.GetHash(); this.connects = connects; this.throwsException = throwsException; this.hashChainTipAfterBlock = hashChainTipAfterBlock; this.heightAfterBlock = heightAfterBlock; // Keep track of the set of blocks indexed by hash hashHeaderMap.AddOrReplace(block.GetHash(), block.Clone()); // Double-check that we are always marking any given block at the same height int height = 0; ; if(blockToHeightMap.TryGetValue(hashChainTipAfterBlock, out height)) Assert.True(height == heightAfterBlock); else blockToHeightMap.Add(hashChainTipAfterBlock, heightAfterBlock); }