public async Task <IActionResult> CreateTag([FromBody] TagSettings tag, CancellationToken cancellationToken)
        {
            if (!ModelState.IsValid)
            {
                return(BadRequest(ModelState)); // 400
            }

            try {
                var result = await _historian.CreateTag(User, tag, cancellationToken).ConfigureAwait(false);

                return(CreatedAtRoute("GetTagById", new { id = result.Id }, result.ToTagDefinitionExtendedDto())); // 201
            }
            catch (ArgumentException) {
                return(BadRequest()); // 400
            }
            catch (OperationCanceledException) {
                return(StatusCode(204)); // 204
            }
            catch (SecurityException) {
                return(Forbid()); // 403
            }
            catch (NotSupportedException) {
                return(BadRequest()); // 400
            }
            catch (NotImplementedException) {
                return(BadRequest()); // 400
            }
        }
Exemple #2
0
        /// <summary>
        /// Run the code example.
        /// </summary>
        /// <param name="user">The Dfa user object running the code example.
        /// </param>
        public override void Run(DfaUser user)
        {
            // Create PlacementRemoteService instance.
            PlacementRemoteService service = (PlacementRemoteService)user.GetService(
                DfaService.v1_20.PlacementRemoteService);
            string placementName = _T("INSERT_PLACEMENT_NAME_HERE");
            long   dfaSiteId     = long.Parse(_T("INSERT_DFA_SITE_ID_HERE"));
            long   campaignId    = long.Parse(_T("INSERT_CAMPAIGN_ID_HERE"));
            int    pricingType   = int.Parse(_T("INSERT_PRICING_TYPE_HERE"));
            int    placementType = int.Parse(_T("INSERT_PLACEMENT_TYPE_HERE"));
            long   sizeId        = long.Parse(_T("INSERT_SIZE_ID_HERE"));

            // Create placement structure.
            Placement placement = new Placement();

            placement.id         = 0;
            placement.name       = placementName;
            placement.campaignId = campaignId;
            placement.dfaSiteId  = dfaSiteId;
            placement.sizeId     = sizeId;

            // Set pricing schedule for placement.
            PricingSchedule pricingSchedule = new PricingSchedule();

            pricingSchedule.startDate   = DateTime.Now;
            pricingSchedule.endDate     = DateTime.Now.AddMonths(1);
            pricingSchedule.pricingType = pricingType;
            placement.pricingSchedule   = pricingSchedule;

            // Set placement type.
            placement.placementType = placementType;

            try {
                // Set placement tag settings.
                TagSettings          tagSettings         = new TagSettings();
                PlacementTagOption[] placementTagOptions = service.getRegularPlacementTagOptions();
                int[] tagTypes = new int[placementTagOptions.Length];

                for (int i = 0; i < placementTagOptions.Length; i++)
                {
                    tagTypes[i] = (int)placementTagOptions[i].id;
                }

                tagSettings.tagTypes  = tagTypes;
                placement.tagSettings = tagSettings;

                // Create the placement.
                PlacementSaveResult placementSaveResult = service.savePlacement(placement);

                // Display new placment id.
                Console.WriteLine("Placment with id \"{0}\" was created.", placementSaveResult.id);
            } catch (Exception ex) {
                Console.WriteLine("Failed to create placement. Exception says \"{0}\"", ex.Message);
            }
        }
Exemple #3
0
        /// <summary>
        /// Creates a new <see cref="RedisTagDefinition"/> object.
        /// </summary>
        /// <param name="historian">The owning historian.</param>
        /// <param name="id">The tag ID.</param>
        /// <param name="settings">The tag settings.</param>
        /// <param name="metadata">The metadata for the tag.</param>
        /// <param name="initialTagValues">The initial tag values, used to prime the exception and compression filters for the tag.</param>
        /// <param name="changeHistory">The change history for the tag.</param>
        private RedisTagDefinition(RedisHistorian historian, string id, TagSettings settings, TagMetadata metadata, InitialTagValues initialTagValues, IEnumerable <TagChangeHistoryEntry> changeHistory) : base(historian, id, settings, metadata, CreateTagSecurity(), initialTagValues, changeHistory)
        {
            _historian           = historian ?? throw new ArgumentNullException(nameof(historian));
            _tagDefinitionKey    = _historian.GetKeyForTagDefinition(Id);
            _snapshotKey         = _historian.GetKeyForSnapshotData(Id);
            _archiveKey          = _historian.GetKeyForRawData(Id);
            _archiveCandidateKey = _historian.GetKeyForArchiveCandidateData(Id);

            _archiveCandidateValue = new ArchiveCandidateValue(initialTagValues?.LastExceptionValue, initialTagValues?.CompressionAngleMinimum ?? Double.NaN, initialTagValues?.CompressionAngleMaximum ?? Double.NaN);

            Updated += TagUpdated;
        }
        /// <summary>
        /// 输出标签选择器(用于不能直接根据内容项获取标签的情况,例如:设置相关标签)
        /// </summary>
        /// <param name="htmlHelper"></param>
        /// <param name="tagInputName">表单项名称</param>
        /// <param name="selectedTagNames">选中的标签组</param>
        /// <param name="tenantTypeId">标签租户类型Id</param>
        /// <param name="ownerId">标签拥有者Id(可优先从该拥有者的标签中获取,并提供下拉列表选择)</param>
        /// <param name="topNumber">默认下拉列表中最多显示多少条数据</param>
        /// <returns></returns>
        public static MvcHtmlString TagSelector(this HtmlHelper htmlHelper, string tagInputName, IEnumerable <string> selectedTagNames, string tenantTypeId = null, long?ownerId = null, int topNumber = 50)
        {
            TagService           tagService    = new TagService(tenantTypeId);
            IEnumerable <string> ownerTagNames = new List <string>();

            if (ownerId.HasValue && ownerId.Value > 0)
            {
                ownerTagNames = tagService.GetTopOwnerTags(ownerId.Value, topNumber, tenantTypeId).Select(n => n.Key.TagName);
            }
            TagSettings tagSettings = DIContainer.Resolve <ITagSettingsManager>().Get();

            return(htmlHelper.EditorForModel("TagSelector", new { tagInputName = tagInputName, ownerId = ownerId, selectedTagNames = string.Join(",", selectedTagNames), ownerTagNames = ownerTagNames, tagSettings = tagSettings }));
        }
Exemple #5
0
        public ActionResult _SetPhotoTag(long photoId)
        {
            string tags = Request.Form.Get <string>("tags", null);
            ISettingsManager <TagSettings> tagSettingsManager = DIContainer.Resolve <ISettingsManager <TagSettings> >();
            TagSettings tagSettings = tagSettingsManager.Get();

            if (tags != null && tags.Split(new char[] { ',', ',' }, StringSplitOptions.RemoveEmptyEntries).Count() > tagSettings.MaxTagsCount)
            {
                return(Json(new StatusMessageData(StatusMessageType.Error, "由于标签超过设置,所以贴标签失败")));
            }

            Photo photo = photoService.GetPhoto(photoId);

            tagService.ClearTagsFromItem(photoId, photo.UserId);
            tagService.AddTagsToItem(tags, photo.UserId, photo.PhotoId);

            return(Json(new StatusMessageData(StatusMessageType.Success, "贴标签成功")));
        }
Exemple #6
0
        private string StartTag(TagSettings thisTagSettings, string[] startTagComponents)
        {
            string text = "";

            if (thisTagSettings.StartHtmlObject != null)
            {
                if (thisTagSettings.StartHtmlObject is string)
                {
                    text = (string)thisTagSettings.StartHtmlObject;
                }

                else if (thisTagSettings.StartHtmlObject is StartTagHandlerDelegate)
                {
                    text = ((StartTagHandlerDelegate)thisTagSettings.StartHtmlObject)(startTagComponents);
                }
            }

            return(text);
        }
Exemple #7
0
        private string EndTag(TagSettings thisTagSettings, string endTagInnerText)
        {
            string text = "";

            if (thisTagSettings.EndHtmlObject != null)
            {
                if (thisTagSettings.EndHtmlObject is string)
                {
                    text = endTagInnerText + (string)thisTagSettings.EndHtmlObject;
                }

                else if (thisTagSettings.EndHtmlObject is EndTagHandlerDelegate)
                {
                    text = ((EndTagHandlerDelegate)thisTagSettings.EndHtmlObject)(endTagInnerText);
                }
            }

            else
            {
                text = endTagInnerText;
            }

            return(text);
        }
Exemple #8
0
        protected override Task <TagDefinition> CreateTag(ClaimsPrincipal claimsIdentity, TagSettings tag, CancellationToken cancellationToken)
        {
            var result = new InMemoryTagDefinition(this, null, tag, new TagMetadata(DateTime.UtcNow, claimsIdentity?.Identity?.Name));

            _tags[result.Id] = result;

            return(Task.FromResult <TagDefinition>(result));
        }
Exemple #9
0
 /// <summary>
 /// Updates a tag.
 /// </summary>
 /// <param name="identity">The identity of the caller.</param>
 /// <param name="tag">The tag to update.</param>
 /// <param name="update">The updated tag definition.</param>
 /// <param name="description">A description of the change.</param>
 /// <param name="cancellationToken">The cancellation token for the request.</param>
 /// <returns>
 /// The updated tag definition.
 /// </returns>
 protected virtual Task <TagDefinition> UpdateTag(ClaimsPrincipal identity, TagDefinition tag, TagSettings update, string description, CancellationToken cancellationToken)
 {
     tag.Update(update, identity, description);
     return(Task.FromResult(tag));
 }
Exemple #10
0
 /// <summary>
 /// Updates a tag.
 /// </summary>
 /// <param name="identity">The identity of the caller.</param>
 /// <param name="tag">The tag to update.</param>
 /// <param name="update">The updated tag definition.</param>
 /// <param name="description">A description of the change.</param>
 /// <param name="cancellationToken">The cancellation token for the request.</param>
 /// <returns>
 /// The updated tag definition.
 /// </returns>
 async Task <TagDefinition> IHistorian.UpdateTag(ClaimsPrincipal identity, TagDefinition tag, TagSettings update, string description, CancellationToken cancellationToken)
 {
     ThrowIfDisposed();
     if (tag.Historian != this)
     {
         throw new ArgumentException(Resources.Error_CannotOperateOnTagsOwnedByAnotherHistorian, nameof(tag));
     }
     return(await UpdateTag(identity, tag, update, description, cancellationToken).ConfigureAwait(false));
 }
Exemple #11
0
 /// <summary>
 /// Creates a new tag.
 /// </summary>
 /// <param name="identity">The identity of the caller.</param>
 /// <param name="tag">The tag definition.</param>
 /// <param name="cancellationToken">The cancellation token for the request.</param>
 /// <returns>
 /// The new tag definition.
 /// </returns>
 protected abstract Task <TagDefinition> CreateTag(ClaimsPrincipal identity, TagSettings tag, CancellationToken cancellationToken);
Exemple #12
0
 /// <summary>
 /// Creates a new tag.
 /// </summary>
 /// <param name="identity">The identity of the caller.</param>
 /// <param name="tag">The tag definition.</param>
 /// <param name="cancellationToken">The cancellation token for the request.</param>
 /// <returns>
 /// The new tag definition.
 /// </returns>
 async Task <TagDefinition> IHistorian.CreateTag(ClaimsPrincipal identity, TagSettings tag, CancellationToken cancellationToken)
 {
     ThrowIfDisposed();
     return(await CreateTag(identity, tag, cancellationToken).ConfigureAwait(false));
 }
        private string EndTag(TagSettings thisTagSettings,string endTagInnerText)
        {
            string text = "";

            if( thisTagSettings.EndHtmlObject != null )
            {
                if( thisTagSettings.EndHtmlObject is string )
                    text = endTagInnerText + (string)thisTagSettings.EndHtmlObject;

                else if( thisTagSettings.EndHtmlObject is EndTagHandlerDelegate )
                    text = ((EndTagHandlerDelegate)thisTagSettings.EndHtmlObject)(endTagInnerText);
            }

            else
                text = endTagInnerText;

            return text;
        }
Exemple #14
0
        /// <summary>
        /// Updates a tag.
        /// </summary>
        /// <param name="identity">The identity of the caller.</param>
        /// <param name="tag">The tag to update.</param>
        /// <param name="update">The updated tag definition.</param>
        /// <param name="description">The change description</param>
        /// <param name="cancellationToken">The cancellation token for the request.</param>
        /// <returns>
        /// The updated tag definition.
        /// </returns>
        protected override Task <TagDefinition> UpdateTag(ClaimsPrincipal identity, TagDefinition tag, TagSettings update, string description, CancellationToken cancellationToken)
        {
            if (tag == null)
            {
                throw new ArgumentNullException(nameof(tag));
            }
            if (update == null)
            {
                throw new ArgumentNullException(nameof(update));
            }

            if (!_tags.ContainsKey(tag.Id))
            {
                throw new ArgumentException(Resources.Error_InvalidTagId, nameof(tag));
            }

            return(base.UpdateTag(identity, tag, update, description, cancellationToken));
        }
Exemple #15
0
        protected override Task <TagDefinition> UpdateTag(ClaimsPrincipal identity, TagDefinition tag, TagSettings update, string description, CancellationToken cancellationToken)
        {
            if (!_tags.ContainsKey(tag.Id))
            {
                throw new ArgumentException("Tag is not registered.", nameof(tag));
            }

            return(base.UpdateTag(identity, tag, update, description, cancellationToken));
        }
Exemple #16
0
 public void Save(TagSettings tagSettings)
 {
     repository.Save(tagSettings);
 }
        private string StartTag(TagSettings thisTagSettings,string[] startTagComponents)
        {
            string text = "";

            if( thisTagSettings.StartHtmlObject != null )
            {
                if( thisTagSettings.StartHtmlObject is string )
                    text = (string)thisTagSettings.StartHtmlObject;

                else if( thisTagSettings.StartHtmlObject is StartTagHandlerDelegate )
                    text = ((StartTagHandlerDelegate)thisTagSettings.StartHtmlObject)(startTagComponents);
            }

            return text;
        }
Exemple #18
0
        /// <summary>
        /// Loads a tag definition from the Redis database.
        /// </summary>
        /// <param name="historian">The Redis historian to load the tag from.</param>
        /// <param name="tagId">The ID of the tag to load.</param>
        /// <param name="cancellationToken">The cancellation token for the request.</param>
        /// <returns>
        /// A task that will return the loaded tag definition.
        /// </returns>
        internal static async Task <RedisTagDefinition> Load(RedisHistorian historian, string tagId, CancellationToken cancellationToken)
        {
            var values = await historian.Connection.GetDatabase().HashGetAllAsync(historian.GetKeyForTagDefinition(tagId)).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            string      name        = null;
            string      description = null;
            string      units       = null;
            TagDataType dataType    = default(TagDataType);
            string      stateSet    = null;

            bool exceptionFilterEnabled = false;
            TagValueFilterDeviationType exceptionFilterLimitType = default(TagValueFilterDeviationType);
            double   exceptionFilterLimit      = 0;
            TimeSpan exceptionFilterWindowSize = default(TimeSpan);

            bool compressionFilterEnabled = false;
            TagValueFilterDeviationType compressionFilterLimitType = default(TagValueFilterDeviationType);
            double   compressionFilterLimit      = 0;
            TimeSpan compressionFilterWindowSize = default(TimeSpan);

            DateTime createdAt  = DateTime.MinValue;
            string   creator    = null;
            DateTime modifiedAt = DateTime.MinValue;
            string   modifiedBy = null;

            foreach (var item in values)
            {
                switch (item.Name.ToString())
                {
                case "NAME":
                    name = item.Value;
                    break;

                case "DESC":
                    description = item.Value;
                    break;

                case "UNITS":
                    units = item.Value;
                    break;

                case "TYPE":
                    dataType = (TagDataType)((int)item.Value);
                    break;

                case "SSET":
                    stateSet = item.Value;
                    break;

                case "EXC_ENABLED":
                    exceptionFilterEnabled = Convert.ToBoolean((int)item.Value);
                    break;

                case "EXC_LIMIT_TYPE":
                    exceptionFilterLimitType = (TagValueFilterDeviationType)((int)item.Value);
                    break;

                case "EXC_LIMIT":
                    exceptionFilterLimit = (double)item.Value;
                    break;

                case "EXC_WINDOW":
                    exceptionFilterWindowSize = TimeSpan.Parse(item.Value);
                    break;

                case "COM_ENABLED":
                    compressionFilterEnabled = Convert.ToBoolean((int)item.Value);
                    break;

                case "COM_LIMIT_TYPE":
                    compressionFilterLimitType = (TagValueFilterDeviationType)((int)item.Value);
                    break;

                case "COM_LIMIT":
                    compressionFilterLimit = (double)item.Value;
                    break;

                case "COM_WINDOW":
                    compressionFilterWindowSize = TimeSpan.Parse(item.Value);
                    break;

                case "MD_CREATEDAT":
                    createdAt = new DateTime((long)item.Value, DateTimeKind.Utc);
                    break;

                case "MD_CREATEDBY":
                    creator = item.Value;
                    break;

                case "MD_MODIFIEDAT":
                    modifiedAt = new DateTime((long)item.Value, DateTimeKind.Utc);
                    break;

                case "MD_MODIFIEDBY":
                    modifiedBy = item.Value;
                    break;
                }
            }

            if (String.IsNullOrWhiteSpace(name))
            {
                name = tagId;
            }

            var settings = new TagSettings()
            {
                Name                    = name,
                Description             = description,
                Units                   = units,
                DataType                = dataType,
                StateSet                = stateSet,
                ExceptionFilterSettings = new TagValueFilterSettingsUpdate()
                {
                    IsEnabled  = exceptionFilterEnabled,
                    LimitType  = exceptionFilterLimitType,
                    Limit      = exceptionFilterLimit,
                    WindowSize = exceptionFilterWindowSize
                },
                CompressionFilterSettings = new TagValueFilterSettingsUpdate()
                {
                    IsEnabled  = compressionFilterEnabled,
                    LimitType  = compressionFilterLimitType,
                    Limit      = compressionFilterLimit,
                    WindowSize = compressionFilterWindowSize
                }
            };

            var metadata = new TagMetadata(createdAt, creator, modifiedAt, modifiedBy);

            var snapshotTask         = LoadSnapshotValue(historian, tagId, cancellationToken);
            var lastArchivedTask     = LoadLastArchivedValue(historian, tagId, cancellationToken);
            var archiveCandidateTask = LoadArchiveCandidateValue(historian, tagId, cancellationToken);

            await Task.WhenAll(snapshotTask, lastArchivedTask, archiveCandidateTask).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            var initialValues = new InitialTagValues(snapshotTask.Result, lastArchivedTask.Result, archiveCandidateTask.Result.Value, archiveCandidateTask.Result.CompressionAngleMinimum, archiveCandidateTask.Result.CompressionAngleMaximum);

            var result = new RedisTagDefinition(historian,
                                                tagId,
                                                settings,
                                                metadata,
                                                initialValues,
                                                null);

            return(result);
        }
Exemple #19
0
        /// <summary>
        /// Creates a new <see cref="RedisTagDefinition"/>.
        /// </summary>
        /// <param name="historian">The historian for the tag.</param>
        /// <param name="settings">The tag settings.</param>
        /// <param name="creator">The tag's creator.</param>
        /// <param name="cancellationToken">The cancellation token for the request.</param>
        /// <returns>
        /// A task that will create a new <see cref="RedisTagDefinition"/> and save it to the
        /// historian's Redis server.
        /// </returns>
        internal static async Task <RedisTagDefinition> Create(RedisHistorian historian, TagSettings settings, ClaimsPrincipal creator, CancellationToken cancellationToken)
        {
            var now    = DateTime.UtcNow;
            var result = new RedisTagDefinition(historian, null, settings, new TagMetadata(DateTime.UtcNow, creator?.Identity.Name), null, new[] { TagChangeHistoryEntry.Created(creator) });
            var key    = historian.GetKeyForTagIdsList();

            await Task.WhenAny(Task.WhenAll(result.Save(cancellationToken), historian.Connection.GetDatabase().ListRightPushAsync(key, result.Id)), Task.Delay(-1, cancellationToken)).ConfigureAwait(false);

            cancellationToken.ThrowIfCancellationRequested();

            return(result);
        }
Exemple #20
0
 /// <summary>
 /// Creates a new <see cref="InMemoryTagDefinition"/> object.
 /// </summary>
 /// <param name="historian">The owning historian.</param>
 /// <param name="id">The tag ID.</param>
 /// <param name="tagSettings">The tag settings.</param>
 /// <param name="metadata">The tag metadata.</param>
 /// <exception cref="ArgumentNullException"><paramref name="historian"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="tagSettings"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="metadata"/> is <see langword="null"/>.</exception>
 /// <exception cref="ValidationException"><paramref name="tagSettings"/> is not valid.</exception>
 internal InMemoryTagDefinition(InMemoryHistorian historian, string id, TagSettings tagSettings, TagMetadata metadata) : base(historian, id, tagSettings, metadata, CreateTagSecurity(), null, null)
 {
     _historian = historian ?? throw new ArgumentNullException(nameof(historian));
 }
Exemple #21
0
        /// <summary>
        /// Creates a new tag.
        /// </summary>
        /// <param name="identity">The identity of the caller.</param>
        /// <param name="tag">The tag definition.</param>
        /// <param name="cancellationToken">The cancellation token for the request.</param>
        /// <returns>
        /// The new tag definition.
        /// </returns>
        protected override async Task <TagDefinition> CreateTag(ClaimsPrincipal identity, TagSettings tag, CancellationToken cancellationToken)
        {
            var tagDefinition = await RedisTagDefinition.Create(this, tag, identity, cancellationToken).ConfigureAwait(false);

            _tags[tagDefinition.Id] = tagDefinition;

            return(tagDefinition);
        }
 /// <summary>
 /// Creates a new <see cref="ElasticsearchTagDefinition"/> object.
 /// </summary>
 /// <param name="historian">The owning historian.</param>
 /// <param name="id">The tag ID.</param>
 /// <param name="settings">The tag settings.</param>
 /// <param name="metadata">The tag metadata.</param>
 /// <param name="security">The tag security configuration.</param>
 /// <param name="initialTagValues">The initial tag values, to use with the exception and compression filters.</param>
 /// <param name="changeHistory">The change history information for the tag.</param>
 /// <exception cref="ArgumentNullException"><paramref name="historian"/> is <see langword="null"/>.</exception>
 /// <exception cref="ArgumentNullException"><paramref name="security"/> is <see langword="null"/>.</exception>
 internal ElasticsearchTagDefinition(ElasticsearchHistorian historian, Guid id, TagSettings settings, TagMetadata metadata, TagSecurity security, InitialTagValues initialTagValues, IEnumerable <TagChangeHistoryEntry> changeHistory) : base(historian, id.ToString(), settings, metadata, security, initialTagValues, changeHistory)
 {
     _historian = historian ?? throw new ArgumentNullException(nameof(historian));
     IdAsGuid   = id;
 }
Exemple #23
0
        private string ProcessText(ref string text)
        {
            int startTagPos = text.IndexOf('<');

            if (startTagPos < 0)  // no more tags so get out
            {
                string savedText = text;
                text = "";
                return(savedText);
            }

            int endTagPos = text.IndexOf('>', startTagPos + 1);

            if (endTagPos < 0)
            {
                throw new Exception("Invalid tag construction around: " + text.Substring(startTagPos));
            }

            string beforeTagText   = text.Substring(0, startTagPos);
            string fullTag         = text.Substring(startTagPos, endTagPos - startTagPos + 1);
            string fullTagContents = fullTag.Substring(1, fullTag.Length - 2).Trim();
            string afterTagText    = text.Substring(endTagPos + 1);

            string[] fullTagComponents = Regex.Split(fullTagContents, @"\s+");

            string tag        = fullTagComponents[0];
            bool   tagIsBlank = String.IsNullOrWhiteSpace(tag);

            if (tagIsBlank && !_inBlockTag)
            {
                throw new Exception("Empty tag around: " + text.Substring(startTagPos));
            }

            bool isEndTag = (!tagIsBlank && tag[0] == '/');

            // processing end tags
            if (isEndTag)
            {
                tag = tag.Substring(1);

                if (_tagStack.Count == 0)
                {
                    throw new Exception("End tag without a start tag around: " + text.Substring(startTagPos));
                }

                // if in a block, ignore ending tags unless they are ending the block tag
                if (_inBlockTag && !_tagStack.Peek().Equals(tag))
                {
                    string blockHtml = beforeTagText + fullTag + ProcessText(ref afterTagText);

                    text = afterTagText;

                    return(blockHtml);
                }

                string lastStartTag = _tagStack.Pop();

                if (!lastStartTag.Equals(tag))
                {
                    throw new Exception(String.Format("End tag </{0}> does not match the last start tag <{1}> around: {2}", tag, lastStartTag, text.Substring(startTagPos)));
                }

                _inBlockTag = false;

                text = afterTagText;
                return(beforeTagText);
            }


            // processing start tags

            // tags are ignored while in a block
            if (_inBlockTag)
            {
                text = text.Substring(startTagPos + 1);
                return(beforeTagText + "<" + ProcessText(ref text));
            }

            if (!_tagSettings.ContainsKey(tag))
            {
                throw new Exception("Invalid tag around: " + text.Substring(startTagPos));
            }

            // see if this is a block tag
            if (_blockTags.ContainsKey(MakeTag(tag, true)))
            {
                _inBlockTag = true;
            }

            TagSettings thisTagSettings = _tagSettings[tag];

            if (!thisTagSettings.IsPairedTag)  // check that the tag ends correctly
            {
                if (fullTagComponents.Length == 1 || !fullTagComponents[fullTagComponents.Length - 1].Equals("/"))
                {
                    throw new Exception(String.Format("The tag {0} is not paired and must end with / around: {1}", tag, text.Substring(startTagPos)));
                }
            }

            int numTagComponents = fullTagComponents.Length - 1 - (thisTagSettings.IsPairedTag ? 0 : 1);

            string[] tagComponents = new string[numTagComponents];
            Array.Copy(fullTagComponents, 1, tagComponents, 0, numTagComponents);

            if (numTagComponents < thisTagSettings.MinTagComponents)
            {
                throw new Exception(String.Format("The tag {0} must have at least {1} argument{2} around: {3}",
                                                  tag, thisTagSettings.MinTagComponents, (thisTagSettings.MinTagComponents == 1) ? "" : "s", text.Substring(startTagPos)));
            }

            if (numTagComponents > thisTagSettings.MaxTagComponents)
            {
                throw new Exception(String.Format("The tag {0} must have at most {1} argument{2} around: {3}",
                                                  tag, thisTagSettings.MaxTagComponents, (thisTagSettings.MaxTagComponents == 1) ? "" : "s", text.Substring(startTagPos)));
            }

            string startOutput = StartTag(thisTagSettings, tagComponents);
            string endOutput   = "";

            if (thisTagSettings.IsPairedTag)
            {
                _tagStack.Push(tag);

                string innerText = ProcessText(ref afterTagText);
                endOutput = EndTag(thisTagSettings, innerText);
            }

            string html = beforeTagText + startOutput + endOutput + ProcessText(ref afterTagText);

            text = afterTagText;
            return(html);
        }
Exemple #24
0
        /// <summary>
        /// Gets the <see cref="ResourceGroupCostResult"/> instance.
        /// </summary>
        /// <param name="cost"><see cref="ResourceGroupCost"/> instance.</param>
        /// <param name="groups">List of <see cref="ResourceGroup"/> instances.</param>
        /// <param name="tagSettings"><see cref="TagSettings"/> instance.</param>
        /// <returns>Returns the <see cref="ResourceGroupCostResult"/> instance.</returns>
        public static ResourceGroupCostResult GetResourceGroupCostResult(ResourceGroupCost cost, IEnumerable <ResourceGroup> groups, TagSettings tagSettings)
        {
            var group = groups.SingleOrDefault(p => p.Name.IsEquivalentTo(cost.ResourceGroupName));
            var tags  = group?.Tags;

            var result = new ResourceGroupCostResult()
            {
                ResourceGroupName = cost.ResourceGroupName,
                Cost            = Convert.ToDecimal(cost.Cost),
                OwnerEmails     = tags?.SingleOrDefault(p => p.Key.IsEquivalentTo(tagSettings.OwnerEmailsKey)).Value,
                TotalSpendLimit = tags?.SingleOrDefault(p => p.Key.IsEquivalentTo(tagSettings.TotalSpendLimitKey)).Value,
                DailySpendLimit = tags?.SingleOrDefault(p => p.Key.IsEquivalentTo(tagSettings.DailySpendLimitKey)).Value,
                OverspendAction = tags?.SingleOrDefault(p => p.Key.IsEquivalentTo(tagSettings.OverspendActionKey)).Value,
                DateStart       = cost.DateStart,
                DateEnd         = cost.DateEnd
            };

            return(result);
        }