protected override void MonitoringThread()
        {
            base.MonitoringThread();

            var wmiObject = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfDisk_PhysicalDisk WHERE Name != '_Total'");

            while (true)
            {
                try
                {
                    var readWriteValues = wmiObject.Get().Cast <ManagementObject>().Select(mo => new
                    {
                        Name          = Convert.ToString(mo["Name"]),
                        DiskReadTime  = Convert.ToInt32(mo["PercentDiskReadTime"]),
                        DiskWriteTime = Convert.ToInt32(mo["PercentDiskWriteTime"])
                    });

                    foreach (var item in readWriteValues)
                    {
                        CurrentValues.AddOrUpdate("DISK_READ_" + (item.Name ?? "").Replace(" ", "_"), diskItem => item.DiskReadTime,
                                                  (diskItem, val) => item.DiskReadTime);
                        CurrentValues.AddOrUpdate("DISK_WRITE_" + (item.Name ?? "").Replace(" ", "_"), diskItem => item.DiskWriteTime,
                                                  (diskItem, val) => item.DiskWriteTime);
                    }

                    Wait();
                }
                catch { }
            }
        }
예제 #2
0
 public virtual void Clear()
 {
     Bid.Trace("<comm.DbConnectionStringBuilder.Clear|API>\n");
     _connectionString    = "";
     _propertyDescriptors = null;
     CurrentValues.Clear();
 }
예제 #3
0
        /// <summary>
        /// Gets or sets the value associated with the specified key.
        /// </summary>
        /// <param name="keyword">The key of the item to get or set.</param>
        /// <returns>
        /// The value associated with the specified key. If the specified key is not found, trying to get it returns a
        /// null reference (Nothing in Visual Basic), and trying to set it creates a new element using the specified
        /// key.Passing a null (Nothing in Visual Basic) key throws an <see cref="ArgumentNullException" />. Assigning
        /// a null value removes the key/value pair.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="keyword" /> is a null reference (Nothing in Visual Basic).
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// The property is set, and the <see cref="DbConnectionStringBuilder" /> is read-only. -or-The property is set,
        /// <paramref name="keyword" /> does not exist in the collection, and the
        /// <see cref="DbConnectionStringBuilder" /> has a fixed size.
        /// </exception>
        public virtual object this[string keyword]
        {
            get
            {
                Check.NotEmpty(keyword, "keyword");

                object value;
                if (!CurrentValues.TryGetValue(keyword, out value))
                {
                    throw new ArgumentException(Strings.FormatKeywordNotSupported(keyword));
                }

                return(value);
            }
            set
            {
                Check.NotEmpty(keyword, "keyword");

                if (value == null)
                {
                    Remove(keyword);
                }
                else
                {
                    CurrentValues[keyword] = value;
                }

                _connectionString = null;
            }
        }
예제 #4
0
        } // RegisterGlobalFilters

        private void InitOnStart()
        {
            Init();

            if (_isInitialized)
            {
                return;
            }

            lock (this) {
                if (_isInitialized)
                {
                    return;
                }
                try {
                    new Log4Net().Init();
                    Log.NotifyStart();
                    var db = DbConnectionGenerator.Get(Log);
                    CurrentValues.Init(
                        db,
                        Log,
                        oLimitations => oLimitations.UpdateWebSiteCfg("Ezbob.Web")
                        );

                    DbConnectionPool.ReuseCount = CurrentValues.Instance.ConnectionPoolReuseCount;
                    AConnection.UpdateConnectionPoolMaxSize(CurrentValues.Instance.ConnectionPoolMaxSize);
                    RegisterGlobalFilters(GlobalFilters.Filters);
                }
                catch (Exception ex) {
                    Log.Error(ex);
                    throw;
                } // try
                _isInitialized = true;
            }     // lock
        }         // InitOnStart
 public HostMeasureValues(HostMeasureValues item)
 {
     foreach (var l in item.CurrentValues.Values)
     {
         CurrentValues.Add(l.HostId, l);
     }
 }
        protected override void MonitoringThread()
        {
            base.MonitoringThread();

            var wmiObject = new ManagementObjectSearcher("select * from Win32_OperatingSystem");

            while (true)
            {
                try
                {
                    var memoryInfo = wmiObject.Get().Cast <ManagementObject>().Select(mo => new
                    {
                        FreePhysicalMemory     = double.Parse(mo["FreePhysicalMemory"].ToString()),
                        TotalVisibleMemorySize = double.Parse(mo["TotalVisibleMemorySize"].ToString())
                    }).FirstOrDefault();

                    if (memoryInfo != null)
                    {
                        var percent = (int)(((memoryInfo.TotalVisibleMemorySize - memoryInfo.FreePhysicalMemory) / memoryInfo.TotalVisibleMemorySize) * 100);
                        CurrentValues.AddOrUpdate("MEMORY", memoryItem => percent, (memoryItem, val) => percent);
                    }

                    Wait();
                }
                catch { }
            }
        }
 public HostMeasureValues(List <HostLoadInfo> loads)
 {
     foreach (var l in loads)
     {
         CurrentValues.Add(l.HostId, l);
     }
 }
        protected override void MonitoringThread()
        {
            base.MonitoringThread();

            var wmiObject = new ManagementObjectSearcher("select * from Win32_PerfFormattedData_PerfOS_Processor");

            while (true)
            {
                try
                {
                    var cpuCoresInfo = wmiObject.Get().Cast <ManagementObject>().Select(mo => new
                    {
                        CoreName    = Convert.ToString(mo["Name"]),
                        LoadPercent = Convert.ToInt32(mo["PercentProcessorTime"])
                    }).ToList();

                    _cpuCount = cpuCoresInfo.Count();

                    foreach (var coreInfo in cpuCoresInfo)
                    {
                        CurrentValues.AddOrUpdate(coreInfo.CoreName, corename => coreInfo.LoadPercent, (corename, val) => coreInfo.LoadPercent);
                    }

                    Wait();
                }
                catch { }
            }
        }
예제 #9
0
 public virtual void Clear()
 {
     DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.Clear|API>");
     _connectionString    = string.Empty;
     _propertyDescriptors = null;
     CurrentValues.Clear();
 }
        /// <summary>
        ///  This can be used to add / update / remove slots.
        /// </summary>
        public async Task <List <Duty> > UpdateDuties(List <Duty> duties, bool overrideValidation)
        {
            if (!duties.Any())
            {
                throw new BusinessLayerException("Didn't provide any duties.");
            }

            await CheckForDutySlotOverlap(duties, overrideValidation);

            var dutyIds     = duties.SelectToList(duty => duty.Id);
            var savedDuties = Db.Duty.AsSingleQuery()
                              .Include(d => d.DutySlots)
                              .In(dutyIds, s => s.Id)
                              .Where(s => s.ExpiryDate == null);

            foreach (var duty in duties)
            {
                var savedDuty = await savedDuties.FirstOrDefaultAsync(s => s.Id == duty.Id);

                savedDuty.ThrowBusinessExceptionIfNull($"{nameof(Duty)} with the id: {duty.Id} could not be found. ");
                duty.Timezone.GetTimezone().ThrowBusinessExceptionIfNull($"A valid {nameof(duty.Timezone)} must be provided.");
                Db.Entry(savedDuty !).CurrentValues.SetValues(duty);
                Db.Entry(savedDuty).Property(x => x.LocationId).IsModified = false;
                Db.Entry(savedDuty).Property(x => x.ExpiryDate).IsModified = false;

                foreach (var dutySlot in duty.DutySlots)
                {
                    var savedDutySlot = await Db.DutySlot
                                        .FirstOrDefaultAsync(ds => ds.Id == dutySlot.Id && ds.ExpiryDate == null);

                    dutySlot.LocationId = duty.LocationId;
                    dutySlot.DutyId     = duty.Id;
                    dutySlot.Timezone   = duty.Timezone;
                    dutySlot.Duty       = null;
                    dutySlot.Sheriff    = null;
                    dutySlot.Location   = null;

                    if (savedDutySlot == null)
                    {
                        await Db.DutySlot.AddAsync(dutySlot);
                    }
                    else
                    {
                        Db.Entry(savedDutySlot).CurrentValues.SetValues(dutySlot);
                    }
                }
                Db.RemoveRange(savedDuty.DutySlots.Where(ds => duty.DutySlots.All(d => d.Id != ds.Id)));
            }

            await Db.SaveChangesAsync();

            var sheriffsForDuties = duties.SelectMany(d => d.DutySlots).SelectDistinctToList(ds => ds.SheriffId);
            var firstDuty         = duties.First();

            await HandleShiftAdjustmentsAndOvertime(firstDuty.LocationId, firstDuty.StartDate, firstDuty.Timezone, sheriffsForDuties);

            await Db.SaveChangesAsync();

            return(await savedDuties.ToListAsync());
        }
예제 #11
0
 /// <summary>
 /// Copy Values
 /// </summary>
 /// <param name="record"></param>
 internal void CopyValues(IRecord record)
 {
     for (int i = 0; i < CurrentValues.Count; i++)
     {
         int indexInRecord = fieldIndexInRecordByIndexInView[i];
         record.SetFieldValue(indexInRecord, CurrentValues.IsNull(i), (String)CurrentValues.GetValue(i));
     }
 }
예제 #12
0
 public TruckVariables()
 {
     Lights   = new LightValues();
     Warnings = new WarningValues();
     Current  = new CurrentValues();
     Damage   = new DamageValues();
     Constant = new ConstantValues();
 }
예제 #13
0
        public ProductDTO Edit(int id, ProductDTO entity)
        {
            _context.Entry(_context.Products.FirstOrDefault(x => x.Id == id) !).CurrentValues
            .SetValues(entity);
            var product    = _context.Products.Find(id);
            var productDto = _mapper.Map <ProductDTO>(product);

            return(productDto);
        }
예제 #14
0
        public PhotoDTO Edit(int id, PhotoDTO entity)
        {
            _context.Entry(_context.Photos.FirstOrDefault(x => x.Id == id) !).CurrentValues
            .SetValues(entity);
            var photo    = _context.Photos.Find(id);
            var photoDto = _mapper.Map <PhotoDTO>(photo);

            return(photoDto);
        }
예제 #15
0
        public CategoryDTO Edit(int id, CategoryDTO entity)
        {
            _context.Entry(_context.Categories.FirstOrDefault(x => x.Id == id) !).CurrentValues
            .SetValues(entity);
            var category    = _context.Categories.Find(id);
            var categoryDto = _mapper.Map <CategoryDTO>(category);

            return(categoryDto);
        }
 protected virtual string GetMessage()
 {
     return(string.Format("Row {0}: The row value count ({1}) does not equal the head count ({2}).\n{3}\n{4}",
                          RowIndex,
                          CurrentValues.Count,
                          HeaderNames.Count,
                          string.Join(",", HeaderNames.ToArray()),
                          string.Join(",", CurrentValues.ToArray())));
 }
예제 #17
0
        public OrderDTO Edit(int id, OrderDTO entity)
        {
            _context.Entry(_context.Orders.FirstOrDefault(x => x.Id == id) !).CurrentValues
            .SetValues(entity);
            var order    = _context.Orders.Find(id);
            var orderDto = _mapper.Map <OrderDTO>(order);

            return(orderDto);
        }
예제 #18
0
 public virtual bool Remove(string keyword)
 {
     ADP.CheckArgumentNull(keyword, "keyword");
     if (CurrentValues.Remove(keyword))
     {
         _connectionString = null;
         return(true);
     }
     return(false);
 }
 public override IEnumerable <ServerStatisticsDataItem> GetData()
 {
     return(CurrentValues.Select(data => new ServerStatisticsDataItem
     {
         Name = "CPU_" + data.Key,
         Order = GetOrderForName(data.Key, _cpuCount),
         Type = ServerStatisticsType.CPU,
         CurrentValue = data.Value,
         CurrentValueDisplay = "%"
     }));
 }
예제 #20
0
        private static void Main(string[] args)
        {
            var log = new ConsoleLog(new LegacyLog());

            ms_oLog = log;

            var oDB = new SqlConnection(log);

            CurrentValues.Init(oDB, log);

            // TestBadPeriods(oDB, ms_oLog);

            // PropertyTraverser.Traverse<B>((oInstance, oInfo) => { ms_oLog.Msg("Instance is {0}", oInstance); ms_oLog.Msg("Property name is {0}", oInfo.Name); });

            // UpdateBrokerPasswords(oDB, log);

            // TestTableSpArgument(oDB, log);

            // TestVectorSpArgument(oDB, log);

            // TestRetryerWithArguments(oDB, log);

            // TestHashPassword(oDB, log);

            // TestParsedValues(oDB, log);

            // TestUiReportExt(oDB, log);

            // TestLoanDateScore(oDB, log);

            // TestExperianLimitedCompanyData(oDB, log);

            // TestUiReport(oDB, log);

            // TestLoansIssuedReport(oDB, log);

            // TestEarnedInterest(oDB, log);

            // TestLoanIntegrity(oDB, log);

            // TestLoanStats(oDB, log);

            // TestIntervalsOperations();

            // TestInterestFreeze(oDB, log);

            // TestSpeed(oDB, log);

            // TestDataSharing(oDB, log);

            // TestAddBrokers(oDB, log);

            // TestReapproval(oDB, log);
        }
예제 #21
0
 public virtual bool Remove(string keyword)
 {
     Bid.Trace("<comm.DbConnectionStringBuilder.Remove|API> %d#, keyword='%ls'\n", ObjectID, keyword);
     ADP.CheckArgumentNull(keyword, "keyword");
     if (CurrentValues.Remove(keyword))
     {
         _connectionString    = null;
         _propertyDescriptors = null;
         return(true);
     }
     return(false);
 }
예제 #22
0
 public virtual bool Remove(string keyword)
 {
     DataCommonEventSource.Log.Trace("<comm.DbConnectionStringBuilder.Remove|API> {0}, keyword='{1}'", ObjectID, keyword);
     ADP.CheckArgumentNull(keyword, nameof(keyword));
     if (CurrentValues.Remove(keyword))
     {
         _connectionString    = null;
         _propertyDescriptors = null;
         return(true);
     }
     return(false);
 }
예제 #23
0
        }         // InitInstanceName

        private bool Init()
        {
            m_oDB = new SqlConnection(m_oEnv, m_oLog);

            if (m_oDB == null)
            {
                throw new Exception("Failed to create a DB connection.");
            }

            if (!InitInstanceName())
            {
                return(false);
            }

            m_oCfg = new Configuration(m_sInstanceName, m_oDB, m_oLog);

            m_oCfg.Init();

            var oRuntimeData = new EzServiceInstanceRuntimeData {
                Env          = m_oEnv,
                Host         = this,
                Log          = m_oLog,
                DB           = m_oDB,
                InstanceName = m_sInstanceName,
                InstanceID   = m_oCfg.InstanceID,
            };

            m_oHost = new EzServiceHost(m_oCfg, oRuntimeData);

            CurrentValues.ReloadOnTimer oOnTimer = () => {
                DbConnectionPool.ReuseCount = CurrentValues.Instance.ConnectionPoolReuseCount;
                AConnection.UpdateConnectionPoolMaxSize(CurrentValues.Instance.ConnectionPoolMaxSize);
            };

            CurrentValues.Init(m_oDB, m_oLog);
            CurrentValues.Instance.RefreshIntervalMinutes = CurrentValues.Instance.EzServiceUpdateConfiguration;

            Scanner.Register();

            ObjectFactory.Configure(x => {
                x.For <ISession>().LifecycleIs(new ThreadLocalStorageLifecycle()).Use(ctx => NHibernateManager.OpenSession());
                x.For <ISessionFactory>().Use(() => NHibernateManager.SessionFactory);
                x.AddRegistry <ServiceRegistry>();
            });

            oOnTimer();
            CurrentValues.OnReloadByTimer += oOnTimer;

            m_oCrontabDaemon = new Daemon(oRuntimeData, m_oDB, m_oLog);

            return(true);
        }         // Init
예제 #24
0
        public async Task <List <Shift> > UpdateShifts(DutyRosterService dutyRosterService, List <Shift> shifts)
        {
            var overlaps = await GetShiftConflicts(shifts);

            if (overlaps.Any())
            {
                throw new BusinessLayerException(overlaps.SelectMany(ol => ol.ConflictMessages).ToStringWithPipes());
            }

            var shiftIds    = shifts.SelectToList(s => s.Id);
            var savedShifts = Db.Shift.In(shiftIds, s => s.Id);

            if (shifts.Any(s => s.StartDate >= s.EndDate))
            {
                throw new BusinessLayerException($"{nameof(Shift)} Start date cannot come after end date.");
            }

            if (shifts.Any(s => s.Timezone.GetTimezone() == null))
            {
                throw new BusinessLayerException($"A valid {nameof(Shift.Timezone)} needs to be included in the {nameof(Shift)}.");
            }

            shifts = SplitLongShifts(shifts);

            foreach (var shift in shifts)
            {
                //Need to add shifts, because some of the shifts were split.
                if (shift.Id == 0)
                {
                    await AddShift(shift);

                    continue;
                }

                var savedShift = savedShifts.FirstOrDefault(s => s.Id == shift.Id);
                savedShift.ThrowBusinessExceptionIfNull($"{nameof(Shift)} with the id: {shift.Id} could not be found.");
                Db.Entry(savedShift !).CurrentValues.SetValues(shift);
                Db.Entry(savedShift).Property(x => x.LocationId).IsModified = false;
                Db.Entry(savedShift).Property(x => x.ExpiryDate).IsModified = false;

                savedShift.Sheriff = await Db.Sheriff.FindAsync(shift.SheriffId);

                savedShift.AnticipatedAssignment = await Db.Assignment.FindAsync(shift.AnticipatedAssignmentId);
            }
            await Db.SaveChangesAsync();

            await CalculateOvertimeHoursForShifts(shifts);

            await dutyRosterService.AdjustDutySlots(shifts);

            return(await savedShifts.ToListAsync());
        }
예제 #25
0
        public override IEnumerable <ServerStatisticsDataItem> GetData()
        {
            int i = 0;

            return(CurrentValues.Select(data => new ServerStatisticsDataItem
            {
                Name = data.Key,
                Order = (int)ItemTypeOffset.NETWORK + i++,
                Type = ServerStatisticsType.NETWORK,
                CurrentValue = data.Value,
                CurrentValueDisplay = DisplayValues.GetOrAdd(data.Key, key => "")
            }));
        }
        public override IEnumerable <ServerStatisticsDataItem> GetData()
        {
            int i = 0;

            return(CurrentValues.Select(data => new ServerStatisticsDataItem
            {
                Name = data.Key,
                Order = (int)ItemTypeOffset.DISK + i++,
                Type = ServerStatisticsType.DISK,
                CurrentValue = data.Value,
                CurrentValueDisplay = "%"
            }));
        }
예제 #27
0
        /// <summary>
        /// Removes the entry with the specified key from the <see cref="DbConnectionStringBuilder" /> instance.
        /// </summary>
        /// <param name="keyword">
        /// The key of the key/value pair to be removed from the connection string in this
        /// <see cref="DbConnectionStringBuilder" />.
        /// </param>
        /// <returns>
        /// true if the key existed within the connection string and was removed; false if the key did not exist.
        /// </returns>
        /// <exception cref="ArgumentNullException">
        /// <paramref name="keyword" /> is null (Nothing in Visual Basic)
        /// </exception>
        /// <exception cref="NotSupportedException">
        /// The <see cref="DbConnectionStringBuilder" /> is read-only, or the <see cref="DbConnectionStringBuilder" />
        /// has a fixed size.
        /// </exception>
        public virtual bool Remove(string keyword)
        {
            Check.NotEmpty(keyword, "keyword");

            if (!CurrentValues.Remove(keyword))
            {
                return(false);
            }

            _connectionString = null;

            return(true);
        }
예제 #28
0
        public static void Init()
        {
            Bootstrap.Init();
            NHibernateManager.FluentAssemblies.Add(typeof(eBayDatabaseMarketPlace).Assembly);

            new Log4Net().Init();

            var db = DbConnectionGenerator.Get(Log);

            EZBob.DatabaseLib.Library.Initialize(db.Env, db, Log);

            CurrentValues.Init(db, Log);
        }
        public override object GetDataItem(RenderContext context)
        {
            var row = context.GetDataRow <TRow>();

            if (CurrentValues.ContainsKey(row))
            {
                var rows = CurrentValues[row];
                if (rows.Count > context.RowIndex)
                {
                    return(rows[context.RowIndex]);
                }
            }
            return(null);
        }
        /// <summary>
        /// Adds the or update.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dbSet">The database set.</param>
        /// <param name="key">The key.</param>
        /// <param name="data">The data.</param>
        /// <exception cref="Exception"></exception>
        public static void AddOrUpdate <T>(this DbSet <T> dbSet, Expression <Func <T, object> > key, T data) where T : class
        {
            if (data == null)
            {
                return;
            }

            var context   = dbSet.GetContext();
            var ids       = context.Model.FindEntityType(typeof(T)).FindPrimaryKey().Properties.Select(x => x.Name);
            var t         = typeof(T);
            var keyObject = key.Compile()(data);

            PropertyInfo[] keyFields = keyObject.GetType().GetProperties().Select(p => t.GetProperty(p.Name)).ToArray();
            if (keyFields == null)
            {
                throw new Exception($"{t.FullName} does not have a KeyAttribute field. Unable to exec AddOrUpdate call.");
            }
            var keyVals  = keyFields.Select(p => p.GetValue(data));
            var entities = dbSet.AsNoTracking().ToList();
            int i        = 0;

            foreach (var keyVal in keyVals)
            {
                // ReSharper disable once PossibleNullReferenceException
                entities = entities.Where(p => p.GetType().GetProperty(keyFields[i].Name).GetValue(p).Equals(keyVal)).ToList();
                i++;
            }
            if (entities.Any())
            {
                var dbVal    = entities.FirstOrDefault();
                var keyAttrs =
                    data.GetType().GetProperties().Where(p => ids.Contains(p.Name)).ToList();
                if (keyAttrs.Any())
                {
                    foreach (var keyAttr in keyAttrs)
                    {
                        keyAttr.SetValue(data,
                                         // ReSharper disable once PossibleNullReferenceException
                                         dbVal?.GetType()
                                         .GetProperties()
                                         .FirstOrDefault(p => p.Name == keyAttr.Name)
                                         .GetValue(dbVal));
                    }
                    context.Entry(dbVal !).CurrentValues.SetValues(data);
                    context.Entry(dbVal).State = EntityState.Modified;
                    return;
                }
            }
            dbSet.Add(data);
        }
예제 #31
0
        public async Task ProcessAsync_GeneratesExpectedOutput(
            string originalContent,
            string selected,
            string value,
            CurrentValues currentValues,
            TagHelperOutput expectedTagHelperOutput)
        {
            // Arrange
            var originalAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
            };
            if (selected != null)
            {
                originalAttributes.Add("selected", selected);
            }

            var contextAttributes = new TagHelperAttributeList(originalAttributes);
            if (value != null)
            {
                contextAttributes.Add("value", value);
            }

            var tagHelperContext = new TagHelperContext(
                contextAttributes,
                items: new Dictionary<object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                expectedTagHelperOutput.TagName,
                originalAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
                {
                    // GetChildContentAsync should not be invoked since we are setting the content below.
                    Assert.True(false);
                    return Task.FromResult<TagHelperContent>(null);
                })
            {
                TagMode = TagMode.StartTagAndEndTag
            };

            output.Content.SetContent(originalContent);

            var metadataProvider = new EmptyModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);
            var viewContext = TestableHtmlGenerator.GetViewContext(
                model: null,
                htmlGenerator: htmlGenerator,
                metadataProvider: metadataProvider);
            tagHelperContext.Items[typeof(SelectTagHelper)] = currentValues;
            var tagHelper = new OptionTagHelper(htmlGenerator)
            {
                Value = value,
                ViewContext = viewContext,
            };

            // Act
            await tagHelper.ProcessAsync(tagHelperContext, output);

            // Assert
            Assert.Equal(expectedTagHelperOutput.TagName, output.TagName);
            Assert.Equal(expectedTagHelperOutput.Content.GetContent(), output.Content.GetContent());
            Assert.Equal(expectedTagHelperOutput.Attributes.Count, output.Attributes.Count);
            foreach (var attribute in output.Attributes)
            {
                Assert.Contains(attribute, expectedTagHelperOutput.Attributes);
            }
        }
예제 #32
0
        public async Task ProcessAsync_DoesNotUseViewContext_IfSelectedNotNull(
            string originalContent,
            string selected,
            string value,
            CurrentValues ignoredValues,
            TagHelperOutput ignoredOutput)
        {
            // Arrange
            var originalAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
                { "selected", selected },
            };
            var originalTagName = "not-option";

            var contextAttributes = new TagHelperAttributeList
            {
                { "label", "my-label" },
                { "selected", selected },
                { "value", value },
            };
            var originalPreContent = "original pre-content";
            var originalPostContent = "original post-content";
            var tagHelperContext = new TagHelperContext(
                contextAttributes,
                items: new Dictionary<object, object>(),
                uniqueId: "test");

            var output = new TagHelperOutput(
                originalTagName,
                originalAttributes,
                getChildContentAsync: (useCachedResult, encoder) =>
                {
                    var tagHelperContent = new DefaultTagHelperContent();
                    tagHelperContent.SetContent(originalContent);
                    return Task.FromResult<TagHelperContent>(tagHelperContent);
                })
            {
                TagMode = TagMode.StartTagAndEndTag,
            };
            output.PreContent.SetContent(originalPreContent);
            output.Content.SetContent(originalContent);
            output.PostContent.SetContent(originalPostContent);

            var metadataProvider = new EmptyModelMetadataProvider();
            var htmlGenerator = new TestableHtmlGenerator(metadataProvider);

            var tagHelper = new OptionTagHelper(htmlGenerator)
            {
                Value = value,
            };

            // Act & Assert (does not throw)
            // Tag helper would throw an NRE if it used ViewContext or Generator values.
            await tagHelper.ProcessAsync(tagHelperContext, output);
        }