The function below is found in a class called page.cs
public static List<string> MyFunction()
{
var retList = new List<string>();
retList.Add("xzy");
retList.Add("abc");
return retList;
}
On page load how to call the function and check if the list contains
xzy and abc?
protected void Page_Load(object sender, EventArgs e)
{
//call MyFunction()
}
You don't really show enough code for us to see your problem. As I read it, you have a class Page in a file named page.cs and it looks like this in part:
public class Page {
public static List<string> MyFunction()
{
var retList = new List<string>
{
"xyz",
"abc",
};
return retList;
}
protected void Page_Load(object sender, EventArgs e)
{
var list = MyFunction();
}
}
(Note that I've simplified your initialization of the list - my code is equivalent to yours)
The code I show compiles. Assuming that MyFunction and Page_Load are in the same class, then you can directly call MyFunction from Page_Load (static functions can be called from instance function (within the same class)).
If they are not in the same class, let's say that MyFunction was a static function in another class (say OtherClass). Then Page_Load could call it in the way #joelcoehoorn describes:
OtherClass.MyFunction();
The reverse is not true. A static function cannot directly call an instance function (one without the static keyword) in the same class. You'll get an error complaining that you need an instance. For example, if MyFunction wanted to call Page_Load, it would need to do something like this:
var page = new Page();
//possibly do something with page
page.PageLoad(new object(), EventArgs.Empty);
//possibly do more stuff with page
If this doesn't answer your question, you need to add more to your question. In particular:
Show the class declarations around your method definitions. It's not clear (but it is important) which class(es) have which methods
Show us the code you have and any error messages you get (compile time and runtime)
Also note that I don't believe you should be getting Non-invocable member 'page' cannot be used like a method. if you did what #joelcoehoorn describes.
You have to reference the function using the type name. However, a file named page.cs likely had a class named Page, which will conflict with the base ASP.Net Page class. Therefore you must either fully-qualify the name (MyNamespace.Page.MyFunction()) or change the name of the class.
Related
I am trying to add some new features to a C# application- in particular, trying to replicate some of its behavior, but inside a web browser, rather than in the application, as it currently is.
I am trying to call a method that has been defined in the Browser.cs class from inside a method in the MainWindow.cs class.
The method is defined in Browser.cs with:
public partial class Browser : Form{
public Browser(){
...
}
public void Browser_Load(object sender, EventArgs e){
webKitBrowser1.Navigate("https://google.com");
}
...
}
I am then trying to call it from MainWindow.cs as follows:
public partial class MainWindow : Window{
...
public MainWindow(){
...
Browser mBrowser = new Browser();
Object sender = new Object();
EventArgs e = new EventArgs();
mBrowser.Browser_Load(sender, e);
...
}
...
}
But, I'm getting a compile error that says:
A local or parameter named 'e' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
What does this mean? I've never come across this error before- I am using the variable inside the same scope as where it has been declared- what does it mean by 'enclosing local scope'? Is that because I'm using e inside the parenthesis for the method call to mBrowser.Browser_Load(sender, e)?
Surely, since the call to this method is inside the same scope as where I've defined e, it shouldn't be an issue of scope?
I did try performing the call with:
mBrowser.Browser_Load(sender, EventArgs e);
but this gave me a compile error saying:
'EventArgs' is a type, which is not valid in the given context.
Can anyone point out what I'm doing wrong here, and what I should be doing to be able to call this method correctly?
The error is pretty clear, you have already defined e named variable in your scope, (Probably in the part of code that you haven't shown).
But more importantly, you shouldn't be calling the Load event like that, instead extract the functionality in a separate method and call the method from your Load event and other places.
Like:
public void SomeMethodToBeCalledOnLoad()
{
webKitBrowser1.Navigate("https://google.com");
}
public void Browser_Load(object sender, EventArgs e)
{
SomeMethodToBeCalledOnLoad();
}
public MainWindow(){
...
Browser mBrowser = new Browser();
Object sender = new Object();
EventArgs e = new EventArgs();
SomeMethodToBeCalledOnLoad();//here
...
}
You already have a variable named e in the scope.
try to call your method like this
mBrowser.Browser_Load(this, EventArgs.Empty);
and the error should go.
I have a method that should return the domain name of the current user in a label.text. I call the method in the load event of the form but nothing comes up, no errors in the code either. Maybe im starting the object wrong? It works if i put the method code in the load event directly.
public partial class Main Form
{
public Main()
{
InitializeComponent();
}
public string getCurrentDomain()
{
return domainNameValue.Text = Environment.UserDomainName;
}
public void Main_Load(object sender, EventArgs e)
{
Main main = new Main();
main.getCurrentDomain();
}
}
I think your problem is in the Main_Load function you are creating a new form instead of changing the current form, The correct code is:
public void Main_Load(object sender, EventArgs e)
{
this.getCurrentDomain();
}
Or if you wnat to have another form just show it using main.show()
The problem is because you are creating new instance of Main class in your Main_Load method. So, the method getCurrentDomain() change label text of the instance that you are creating not the label in the form where Main_Load is executed.
Also the body of method getCurrentDomain() violates the Principle of least astonishment because that method is generating side effect which changes text of a label. But the name of method suggest only that the current domain name is being returned.
You could use
public string getCurrentDomain() // Method: Get current domain
{
domainNameValue.Text = Environment.UserDomainName;
return Environment.UserDomainName;
}
I have an ASP.net solution, which contains a project InvestTracking where I am calling a function GetInvestPeriod() from the PageLoad event.
I have another project InvestTrackingBL which contains the function GetInvestPeriod().
protected void Page_Load(object sender, EventArgs e)
{
GetInvestPeriod();
}
public class InvestTrackingBL
{
protected void GetInvestPeriod()
{
}
}
I am getting an error in my main project:
'The name GetInvestPeriod does not exist in the current context'.
What am I missing here?
You can't just use the function like that.
You either need an instance of InvestTrackingBL or call the static method on it:
//If it's an instance member
var investTrackingBL = new InvestTrackingBL();
investTrackingBL.GetInvestPeriod();
//or if it's static
InvestTrackingBL.GetInvestPeriod();
And following your update. Methods that are protected cannot be called by other classes, only derived classes, you need to make it public or internal.
I'm trying to find the assembly of a page request during runtime. I have used the code at Get current System.Web.UI.Page from HttpContext? which work for most calls, but there is an issue.
If in my aspx.cs I instantiate a class variable at the top of my class HttpContext.Current.CurrentHandler is null.
Example
I have one DLL named Business.dll with the function to get the Page type as per the above SO question.
In my page, default.asp in FrontEnd.dll I have the following call:
public partial class FrontEnd: Page
{
private readonly Type _t = Business.GetPageType();
The above code return HttpContext.Current.CurrentHandler as null and HttpContext.Current.ApplicationInstance return HttpApplication as the type, and hence System.Web as the assembly.
If I however write it like this:
public partial class FrontEnd: Page
{
readonly Type _t;
protected override void OnInit(EventArgs e)
{
_t = Business.GetPageType();
it works just fine, and I get a reference to CurrentHandler and the page. I could of course refactor all places and move the variable initialization to OnInit, but this requires convention in the app and a higher degree of maintenance.
Using Assembly.GetEntryAssembly() return null for the example and Assembly.GetExecutingAssembly() return Business.dll, so I cannot use them either.
Is there possible another way to find the type/dll, perhaps using the Request Url to find the type/dll which it originates from?
[Update]
So far I have this code, as all my dll's are signed with a known key (not including the extra methods for checking the signing key):
StackTrace stackTrace = new StackTrace();
StackFrame[] stackFrames = stackTrace.GetFrames();
Assembly firstAssembly = null;
foreach (StackFrame stackFrame in stackFrames)
{
var method = stackFrame.GetMethod();
Type t = method.DeclaringType;
if (t != null && t.Assembly.Is(SignedBy.Me))
{
firstAssembly = t.Assembly;
}
}
if( firstPzlAssembly != null)
{
return firstPzlAssembly;
}
While it works, it seems wrong and will have a potential performance hit if called often.
When you do it this way:
private readonly Type _t = Business.GetPageType();
it is actually compiled into a field initialization within the constructor.
It means that the object (your page) is not constructed yet. It does not exist yet, it is "being born". You are just within the constructor at this stage.
Until your object (the page) is constructed, ASP.NET infrastructure cannot assign it to an HttpContext.Current.CurrentHandler static property. Well, because the handler (your page) does not exist yet and id being constructed.
So you cannot do what you want.
What you can do is to create a PageBase class, override OnInit method and add this code there:
public abstract class PageBase
{
protected Type PageType { get; private set; }
protected override void OnInit(EventArgs e)
{
PageType = Business.GetPageType();
}
}
and now just derive your pages from this base class:
public partial class FrontEnd: PageBase { .... }
(or specify PageBase as a base class directly in ASPX file, whatever you do.
One option, is to define a single base page, with the OnInit function setup as required, and then ensure that all your other pages inherit from that.
For example:
public class CustomBasePage: Page
{
readonly Type _t;
protected override void OnInit(EventArgs e)
{
_t = Business.GetPageType();
}
}
Then alter all your pages to inherit from this instead of the normal Page class:
public partial class FrontEnd: CustomBasePage
This means you only need to define your logic once and places a minimal overhead on the rest of the applications pages.
If any page need to override OnInit for another reason, it just needs to include a call to base.OnInit(); which isn't too onerous.
You'll need to ensure that your Business.GetPageType(); return what you expect. I'm not clear on exactly what it is doing and whether it will return the FrontEnd or CustomBasePage class, (nor which of those would be acceptable to your application logic).
I have a C# Windows Form that contains a function called automation. I then have a C# console application that I am trying to use to call the function of the Windows Form. I have created the reference and have gotten this far:
Form1 FormInstance = new Form1();
FormInstance.automation += new EventHandler(?);
My question is, I have tried to add something where my question mark is but I continue getting an error. If I set it up like this:
FormInstance.automation += new EventHandler(NewHandler);
I get "NewHandler" does not exist in the current context.
And if I create
public void NewHandler(object sender, EventArgs e)
I get An object reference is required for the non-static field, method, or property.
I can not figure out what I am doing wrong.
It is supposed to be object.NewHandler, where object may be this if this occurs within the context of a member method. You can be forgiven for tripping this up because most member references can be implicit but this one has to be explicit.
At a high level it works something like this:
public static void Main(string[] args)
{
Form x = new Form();
x.Method = new EventHandler(MyHandler);
}
public static void MyHandler(object sender, EventArgs e)
{
// Stuff
}
It looks like you haven't marked your method with the static keyword (if invoking this via a static method like a console main). You also need to make sure you're assigning the appropriate delegate to the event; i.e. automation in your method needs to be able to accept an EventHandler delegate.
The simplest way is to make your event handler method static
public static void NewHandler(object sender, EventArgs e)