System.Web.Mvc.HtmlHelper' does not contain a definition for CheckBox - c#

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Text;
namespace secondMvc.MyControls
{
public static class CheckBoxList
{
public static MvcHtmlString CheckListBox(this HtmlHelper helper, string Name, Dictionary<Int32, string> citiesList, bool IsVertical, string cssClass)
{
StringBuilder sb = new StringBuilder();
sb.Append(string.Format("<div >"));
foreach (var item in citiesList)
{
sb.Append(helper.CheckBox(item.Value, true, new { #class = cssClass, value = item.Key }));
sb.Append(helper.Label("RadioButtonItems", item.Value));
sb.Append(" ");
if (IsVertical) sb.Append("<br>");
}
sb.Append("</div> ");
return MvcHtmlString.Create(sb.ToString());
}
}
}
System.Web.Mvc.HtmlHelper'does not contain a definition forCheckBoxand no extension method'CheckBox'accepting a first argument of type'System.Web.Mvc.HtmlHelper'` could be found (are you missing a using directive or an assembly reference?)
i change web.config like this:
<configuration>
<appSettings>
</appSettings>
<connectionStrings>
</connectionStrings>
<pages>
<namespaces>
<add namespace="secondMvc.MyControls"/>
</namespaces>
</pages>
<system.web>
<compilation>
<assemblies>
<add assembly="secondMvc.MyControls" />
</assemblies>
</compilation>
</system.web>
</configuration>
but i have same error.
any idea?

Add using System.Web.Mvc.Html to your file containing the CheckBoxList static class. It is inside this namespace that extension method such as CheckBox are defined. The web.config namespaces section is completely ignored when compiling C# code. They are used by views. And note that Razor views use the ~/Views/web.config file, not ~/web.config, so make sure you have added the secondMvc.MyControls namespace to the correct web.config if you want your custom extension method to be resolved in views.

Related

Custom config file elements in ASP.NET: `Property is not a ConfigurationElement'

I'm attempting to implement my first go-around of reading custom configuration elements from an ASP.NET web.config file. It seems pretty simple to me, yet I'm receiving a run-time `Property is not a ConfigurationElement' error. Here's my code:
The web.config file sections:
<?xml version="1.0" encoding="utf-8" ?>...
<configuration>
...
<section name="appConfig" type="ParticipationManagement.AppConfig" allowDefinition="Everywhere" allowLocation="true" requirePermission="false" />
</configSections>
...
<appConfig>
<startRecertVFC>2/15</startRecertVFC>
</appConfig>
</configuration>
The handler:
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Web;
namespace ParticipationManagement
{
public class AppConfig : ConfigurationSection
{
[ConfigurationProperty("startRecertVFC", IsRequired = false)]
public DateTime RecertVFCStart
{
get
{
string start = (string)this["startRecertVFC"];
string year = DateTime.Now.Year.ToString();
DateTime start_date;
if (DateTime.TryParse(start + "/" + year, out start_date))
{
return start_date;
}
else
{
return DateTime.Today;
}
}
set
{
this["startRecertVFC"] = value;
}
}
}
}
And my invocation in page code:
protected void Page_Init(object sender, EventArgs e)
{
...
AppConfig config = (AppConfig)System.Configuration.ConfigurationManager.GetSection("appConfig");
RecertVFCStart = config.RecertVFCStart;
}
Seems very clean and straight-forward to me, but I'm getting that troubling error at runtime and I cannot narrow it down since I have no experience with this.
Sorry in advance: I see plenty of other posts about this but all seem to address more advanced/complex issues than what I'm trying to accomplish, which is nothing more than embedding a few app-specific values in an external file...
Change your config setting like an example shown below
<?xml version="1.0"?>
<configuration>
<configSections>
<section name="appConfig" type="ParticipationManagement.AppConfig" allowDefinition="Everywhere" allowLocation="true" requirePermission="false"/>
</configSections>
<appConfig startRecertVFC="5/1/2015 8:30:52 AM" />
</configuration>
Try to make the following change in AppConfig file
string start = this["startRecertVFC"].ToString();
Let us know if this solves your problem

How to read and update value in xml file via C sharp?

I have the xml file is following manner :
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<connectionStrings>
<add name="Conn" providerName="System.Data.SqlClient"
connectionString="Data Source=machine_name; Initial Catalog=database_name; User ID=id; Password=password" />
</connectionStrings>
</configuration>
In above xml file i want to change the value of password.
Code i have tried is:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Configuration;
using System.Xml.Linq;
namespace ConsoleApplication85
{
class Program
{
static void Main(string[] args)
{
XDocument xdoc = XDocument.Load(#"filepath.xml");
var element = xdoc.Elements("Password").Single();
element.Value = "new password";
xdoc.Save(#"filepath.xml");
}
}
}
The best way to change the application configuration is through the methods of the ConfigurationManager class, not through XmlDocument methods..
See this question:
Change connection string & reload app.config at run time

Handling File Naming Convention from Configuration File

I have attempting to implement a file naming convention in my program. For example I have a configuration file such as below:
MyConfig.conf
# File naming convention for output-file
[Field1][Field3][Field2]
'FieldX' corresponds with string within the program - so for example a program would read the configuration file and format the strings as follows in the program:
Field1Value Field2Value Field3Value
Are there any preferred ways to do this kind of thing in C#?
Easiest way I can think of is to use app settings. The app settings contain the string format that you need. Then you just use that string format.
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.Configuration;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace _16852548
{
class Program
{
static void Main(string[] args)
{
NameValueCollection appSettings = ConfigurationManager.AppSettings;
string field1Value = "Filename";
string field2Value = ".";
string field3Value = "txt";
string fileFormat = appSettings["FileNameFormat"];
Console.WriteLine(string.Format(fileFormat, field1Value, field2Value, field3Value));
}
}
}
Then the config file can be:
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<appSettings>
<add key="FileNameFormat" value="{0}{2}{1}"/> <!-- follow string.Format syntax -->
</appSettings>
</configuration>

perfmon using EntLib - no instance in perfmon

We are in need to add performance monitoring to our application.
For the prototype I've created a sample project, which I'm trying to get into work.
I'm trying to use policyInjection for the performance counters, so we'll be able to turn on and off the performance monitoring in the production environment.
So far I can see the actual category in perfmon, but I cannot see any instances (see image), even I'm pretty sure the application is running and instance exists, as you can see in attached sources.
I've tried a lot of things, also googled around, but didn't find any usable solution or clue what to look for.
Application is created as consoleApplication
You can also download a zipped project for VS here:
http://dl.dropbox.com/u/19457132/stackOverflow/Mpd.Instrumentation.PerformanceCounter.zip
Here are my sources.
Program.cs
using System;
using System.Collections;
using System.Configuration.Install;
using Microsoft.Practices.EnterpriseLibrary.Common.Configuration;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection;
using Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Installers;
namespace Mpd.Instrumentation.PerformanceCounter
{
class Program
{
static void Main(string[] args)
{
//RemoveCounters();
InstallCounters();
MyCounters myCounter = PolicyInjection.Create<MyCounters>();
for (int i = 0; i < 100000000; i++)
{
myCounter.SampleMethod(i);
}
Console.ReadLine();
}
public static void InstallCounters()
{
PerformanceCountersInstaller installer = new PerformanceCountersInstaller(new SystemConfigurationSource());
IDictionary state = new Hashtable();
installer.Context = new InstallContext();
installer.Install(state);
installer.Commit(state);
Console.WriteLine("Performance counters have been successfully installed. Press enter to continue");
Console.ReadLine();
}
private static void RemoveCounters()
{
PerformanceCountersInstaller installer = new PerformanceCountersInstaller(new SystemConfigurationSource());
installer.Context = new InstallContext();
installer.Uninstall(null);
Console.WriteLine("Performance counters have been successfully removed. Press enter to continue.");
Console.ReadLine();
}
}
}
MyCounters.cs
using System;
using System.Threading;
namespace Mpd.Instrumentation.PerformanceCounter
{
public class MyCounters : IPerformanceCounter
{
public void SampleMethod(int i)
{
Console.WriteLine(i);
Thread.Sleep(50);
}
}
}
IPerformanceCounter.cs
using System;
namespace Mpd.Instrumentation.PerformanceCounter
{
public class IPerformanceCounter : MarshalByRefObject
{
}
}
And finally app.config
<?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="policyInjection" type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.Configuration.PolicyInjectionSettings, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
<section name="instrumentationConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Common.Instrumentation.Configuration.InstrumentationConfigurationSection, Microsoft.Practices.EnterpriseLibrary.Common, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="false" />
</configSections>
<policyInjection>
<policies>
<add name="SampleCountersPolicy">
<matchingRules>
<add type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.MethodSignatureMatchingRule, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
match="SampleMethod" ignoreCase="true" name="Method Signature Matching Rule" />
</matchingRules>
<handlers>
<add type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.CallHandlers.PerformanceCounterCallHandler, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
categoryName=".aaaTest" instanceName="Default" useTotalCounter="true"
incrementNumberOfCalls="true" incrementCallsPerSecond="true"
incrementAverageCallDuration="true" incrementTotalExceptions="true"
incrementExceptionsPerSecond="true" order="1" name="Performance Counter Call Handler" />
</handlers>
</add>
</policies>
</policyInjection>
<instrumentationConfiguration performanceCountersEnabled="true"
applicationInstanceName="Default" />
</configuration>
Since the SampleMethod accepts a parameter you need to add that to the matching rules configuration:
<matchingRules>
<add type="Microsoft.Practices.EnterpriseLibrary.PolicyInjection.MatchingRules.MethodSignatureMatchingRule, Microsoft.Practices.EnterpriseLibrary.PolicyInjection, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
match="SampleMethod" ignoreCase="true" name="Method Signature Matching Rule">
<parameters>
<parameter name="i" typeName="System.Int32" />
</parameters>
</add>
</matchingRules>
Without the parameter the matching rule does not match so the call handler is not invoked. If you modify the configuration you should see the instances in perfmon.

My extension method isn't registering

I'm following Pro ASP.Net MVC2 book and literally 90% of everything is new to me. I feel like a kid in a candy store! :)
Unit testing, dependancy injection, and other things are really new and very foreign to the typical CRUD applications I create.
Now I'm having trouble with a test the book asks us to design.
[Test]
public void Can_Generate_Links_To_Other_Pages()
{
// Arrange: We're going to extend the HtmlHelper class.
// It doesn't matter if the variable we use is null.
HtmlHelper html = null;
// Arrange: The helper should take a PagingInfo instance (that's
// a class we haven't yet defined) and a lambda to specify the URLs
PagingInfo pagingInfo = new PagingInfo
{
CurrentPage = 2,
TotalItems = 28,
ItemsPerPage = 10
};
Func<int, string> pageUrl = i => "Page" + i;
// Act
MvcHtmlString result = html.PageLinks(pagingInfo, pageUrl);
// Assert: Here's how it should format the links
result.ToString().ShouldEqual(#"1
<a class=""selected"" href=""Page2"">2</a>
3");
}
My html variable is a HtmlHelper variable. It seems that the extension method PageLinks() isn't correctly registered.
Where would I check for this? I realize this question might be a bit vague, but any help will be wonderful.
EDIT:
Apparantly this is where I registered the extension method. Although it doesn't seem to extend anything. At least intellisnse doesn't show it when I type it in the above code.
public static class PagingHelpers
{
public static MvcHtmlString PageLinks(this HtmlHelper html, PagingInfo pagingInfo, Func<int, string> pageUrl)
{
StringBuilder result = new StringBuilder();
for (int i = 1; i <= pagingInfo.TotalPages; i++)
{
TagBuilder tag = new TagBuilder("a"); // Construct an <a> tag
tag.MergeAttribute("href", pageUrl(i));
tag.InnerHtml = i.ToString();
if (i == pagingInfo.CurrentPage)
tag.AddCssClass("selected");
result.AppendLine(tag.ToString());
}
return MvcHtmlString.Create(result.ToString());
}
}
Also, can someone tell me how to set up Visual Studio so it just copies plain text without it's ridiculous indentation?
EDIT 2:
Woops! Forgot to type in the error:
Error 1 'System.Web.Mvc.HtmlHelper'
does not contain a definition for
'PageLinks' and no extension method
'PageLinks' accepting a first argument
of type 'System.Web.Mvc.HtmlHelper'
could be found (are you missing a
using directive or an assembly
reference?) C:\Users\Sergio\documents\visual
studio
2010\Projects\SportsStore\SportsStore.UnitTests\DisplayingPageLinks.cs 35 41 SportsStore.UnitTests
To use an extension method, you need to include the namespace in which the extension method class resides. You also need to ensure the extension method class is static and accessible to consuming code (e.g. can't be internal if it's in another assembly). Finally, be sure not to forget the this keyword on the type you're extending. If all those things are in place, you shouldn't see a problem.
You can add the namespace to all your pages in the web.config like this:
<system.web>
<pages>
<namespaces>
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="System.Linq"/>
<add namespace="System.Collections.Generic"/>
<add namespace="YourNameSpace.HtmlHelpers"/>
</namespaces>
</pages>
Use
MvcHtmlString result = PagingHelpers.PageLinks(myHelper, pagingInfo, pageUrlDelegate);
instead of
MvcHtmlString result = myHelper.PageLinks(pagingInfo, pageUrlDelegate);
You need to add in your List.cshtml above the code this line
#model SportsStore.WebUI.Models.ProductsListViewModel
You can remove this HtmlHelper html, from parameters of PageLinks method code in PagingHelpers class, and replace HtmlHelper with PagingHelpers
like this
MvcHtmlString result = PagingHelpers.PageLinks(pagingInfo, pageUrl);
HtmlHelper is not used in your example.

Categories