When trying to compile my c# windows app I am getting the following error:
The name 'GetActiveLB' does not exist in the current context
Here's the code that calls that function:
using F5LTMMaintenance;
......
private void btnLBSetA_Click(object sender, EventArgs e)
{
List<string> range = GetActiveLB();
foreach (string item in range)
{
// Do something with item
}
}
Then I have a class with the following:
namespace F5LTMMaintenance
{
public class F5LTM<T>
{
public List<T> GetActiveLB()
{
var client = new RestClient("mylb.domain.local");
var request = new RestRequest("mgmt/tm/cm/failover-status", Method.GET);
var queryResult = client.Execute<List<T>>(request).Data;
return queryResult == null ? new List<T>() : queryResult;
}
}
}
The GetActiveLB function does exist, its a public function so why am I getting this error? Any help would be appreciated.
It has to be used with an instance of F5LTM<T>.
e.g.:
var f5ltm = new F5LTM<string>();
List<string> range = f5ltm.GetActiveLB();
Alternatively, if you declare it as static like this:
public class F5LTM //not generic here
{
public static List<T> GetActiveLB<T>() //generic here and static
{
//unchanged
}
}
Usage:
List<string> range = F5LTM.GetActiveLB<string>();
Or with C# 6 using static syntax:
using static F5LTMMaintenance.F5LTM; //at top of file
List<string> range = GetActiveLB<string>();
This is as close as you can get to the code you posted.
Yes it's a public function but it's defined inside a different class than your calling event handler class. You need to create a instance of your class F5LTM<T> and on that instance call your method GetActiveLB() rather like
private void btnLBSetA_Click(object sender, EventArgs e)
{
F5LTM<Type> test = new F5LTM<Type>();
List<string> range = test.GetActiveLB();
You will need an instance of your F5LTM class (say typF5LTM), to be able to call typF5LTM.GetActiveLB(). Or you need to make GetActiveLB a static function to be able to call it without an instance like F5LTM.GetActiveLB();
As another poster pointed out, you have to call the method on the class.
F5LTM<string> listItems = new F5LTM<string>();
List<string> range = listItems.GetActiveLB();
Related
I am creating a helper class for my MVC application. This class will contain static methods that will pull information the first time the user logs into the system.
I have created two methods that will return lists like list of countries and list of languages. I don't want to execute this every time but save results of first call and return it for subsequent calls.
public static List<Languages> GetLanguages()
{
using (var db = new MCREntities())
{
var languages = db.spGetLanguages(0);
return Mapper.Map<List<Languages>>(languages);
}
}
public static List<Countries> GetCountries()
{
using (var db = new MCREntities())
{
var countries = db.spGetAllCountries("");
return Mapper.Map<List<Countries>>(countries);
}
}
Inside your class you can have static list which would hold Languages anly first time would try to access database.
private static List<Languages> _languages = null;
public static List<Languages> GetLanguages()
{
if(_languages == null){
using (var db = new MCREntities())
{
var languages = db.spGetLanguages(0);
_languages = Mapper.Map<List<Languages>>(languages);
}
}
return _languages;
}
Alternatively, you can implement cache
i would say create a class with the required properties liek
public static class CurrentSession{
List<Languages> lang{get;set;}
List<Countries> countries{get;set;}
}
and in global.asax file
protected void Application_Start()
{
//.........predefined codes
CurrentSession.lang = GetLanguages();
CurrentSession.Countries =GetCountries();
I am attempting to make an application which gets and inputted URL via textbox, retrieves the HtmlCode of that website when a button is clicked and stores both in a dictionary which is then displayed in a listbox.
However, I haven't been able to implement any of it into the user interface yet due to having an issue when trying to add an entry to the dictionary. To retrieve the HtmlCode I am calling the method GetHtml however, i am getting an error when trying to add the website and the code to the dictionary.
Code Follows
namespace HtmlCheck
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
var dict = new SortedDictionary<string, WebsiteInfo>();
var list = (from entry in dict
orderby entry.Key
select entry.Key).ToList();
}
private static void addPerson(string websiteUrl)
{
dict.Add(websiteUrl, new WebsiteInfo { WebsiteUrl = websiteUrl, HtmlCode = getHtml(websiteUrl) });
}
private static SortedDictionary<string, WebsiteInfo> dict;
public string getHtml(string websiteUrl)
{
using (WebClient client = new WebClient())
return client.DownloadString(websiteUrl);
}
}
public class WebsiteInfo
{
public string WebsiteUrl;
public string HtmlCode;
public override string ToString()
{
string formated = string.Format("{0}\n---------------------------------- \n{1}", WebsiteUrl, HtmlCode);
return formated;
}
}
}
In the method
private static void addPerson(string websiteUrl)
{
dict.Add(websiteUrl, new WebsiteInfo { WebsiteUrl = websiteUrl, HtmlCode = getHtml(websiteUrl) });
}
the HtmlCode = getHtml(websiteUrl) is throwing an error:
"An object reference is required for the non-static field, method, or property 'HtmlCheck.Program.getHtml(string)'"
So my question is, why cant I add an entry to the dictionary with this information?
Thanks for your time.
You're getting that error because addPerson() is a static method (it is called without creating an instance of the Program class), but the getHtml() method is not static (so you need an instance of the Program class to call it).
Easy fix - make it static too:
public static string getHtml(string websiteUrl)
{
...
}
For the sake of completeness, you'd have to otherwise create an instance of the Program class before calling the getHtml() method:
private static void addPerson(string websiteUrl)
{
var p = new Program();
dict.Add(websiteUrl, new WebsiteInfo { WebsiteUrl = websiteUrl, HtmlCode = p.getHtml(websiteUrl) });
}
addPerson() is a static method, which means you can call it any time, without having an instance of the class to call it on. It then tries to call getHtml(), which is non-static, which means it can only be called through a valid instance of the class.
I suggest you do some research on static methods in C# to get your head around this.
Add "static" to your method;
public static string getHtml(string websiteUrl)
I have created this helper class RichTextBoxHelper that has an extension method, and I would like to write another WriteLine method or rewrite this one (which solution is best) in order to be able to use it in the function presented under it. Thank you.
public static class RichTextBoxHelper
{
public static void WriteLine(this RichTextBox txtLog, object line)
{
txtLog.AppendText(line + Environment.NewLine);
}
}
private void selectToolStripMenuItem_Click(object sender, EventArgs e)
{
var vehicles = new List<Tuple<string, string, int>>
{
Tuple.Create("123","VW",1999),
Tuple.Create("234","Ford",2009),
Tuple.Create("567","Audi",2005),
Tuple.Create("678","Ford",2003),
Tuple.Create("789","Mazda",2003),
Tuple.Create("999","Ford",1965)
};
var fordCars = vehicles.Where(v => v.Item2 == "Ford")
.Select(v => new Car
{
VIN = v.Item1,
Make = v.Item2,
Year = v.Item3
});
foreach (var item in fordCars)
txtLog.WriteLine("Car VIN:{0} Make:{1} Year:{2}", item.VIN, item.Make, item.Year);
}
Yep, that's completely possible. It's called method overloading and it works just as well on extension method classes as normal classes.
The signature you require for your new method is:
public static void WriteLine(
this RichTextBox txtLog,
string format,
params object[] args)
{
// ...
}
Just put it in the same class as your other one and you'll be able to use both as appropriate.
Alternatively you can call your existing method in the following way:
txtLog.WriteLine(
String.Format(
"Car VIN:{0} Make:{1} Year:{2}",
item.VIN,
item.Make,
item.Year));
I think dav_i answer is correct but I prefer you to write your extension method for IsIn method something like below, because you can use it everywhere for every different kind of variables:
public static class ExtensionMethods
{
public static bool IsIn<T>(this T keyObject, params object[] collection)
{
return collection.Contains(keyObject);
}
}
usage of method is like here:
if (intValue.IsIn( 2, 3, 7 ))
{
do something...
}
if (stringVlaue.IsIn("a","b","c"))
{
do something...
}
I have a class name OFCls which has a method call getOF()
I want to use that method in another class method.
public void Display()
{
var oOF = new OFCls();
dataGridView1.DataSource = OFCls.getOF.Tables(0);
}
I get the error MyProject.OFCls.getOF() is a method which is not valid in the given context.
What should I do to call a class method! Thank you heaps
You seem to be missing brackets
public void Display()
{
var oOF = new OFCls();
dataGridView1.DataSource = OFCls.getOF().Tables[0];
}
or if it is not static
public void Display()
{
var oOF = new OFCls();
dataGridView1.DataSource = oOF .getOF().Tables[0];
}
If getOF is a method, call it:
OFCls.getOF().Tables(0);
I have created the fallowing Sample-Code:
class Program {
static void Main(string[] args) {
var x = new ActionTestClass();
x.ActionTest();
var y = x.Act.Target;
}
}
public class ActionTestClass {
public Action Act;
public void ActionTest() {
this.Act = new Action(this.ActionMethod);
}
private void ActionMethod() {
MessageBox.Show("This is a test.");
}
}
When I do this on this way, y will an object of type ActionTestClass (which is created for x). Now, when I change the line
this.Act = new Action(this.ActionMethod);
to
this.Act = new Action(() => MessageBox.Show("This is a test."));
y (the Target of the Action) will be null. Is there a way, that I can get the Target (in the sample the ActionTestClass-object) also on the way I use an Anonymous Action?
The lack of Target (iow == null) implies the delegate is either calling a static method or no environment has been captured (iow not a closure, just a 'function pointer').
the reason why you see the target as empty is because the anonymous method is not part of any class. If you open your program in reflector, it will show you the code that is generated by the compiler, here you will see the following
public void ActionTest()
{
this.Act = delegate {
Console.WriteLine("This is a test.");
};
}
You can use the following:
Act.Method.DeclaringType