This question is like Cannot access Public method in Web Control's Page_Load event
However since you are not allowed to ask questions inside someone else's question I'm making a new question.
I have the following layout:
namepspace
{
public partial class
{
protected void Page_Load
{
}
class Employee
{
public static bool employeeType
{
}
}
}
If I want to access employeeType in Page_Load, how can I access it?
This
protected void Page_Load
{
// We can access whitout creating a instance since it is static
Employee.employeeType
}
Doesn't work? Also, what exactly is employeeType? If it is a function:
protected void Page_Load
{
Employee.employeeType();
}
But then you are missing the parenthesis and the return type on the declaration. You should declare like this, preferably starting with uppercase (call it with uppercase also):
class Employee
{
public static void EmployeeType()
{
}
....
}
Edit
So, it is a static property. Then:
protected void Page_Load
{
bool type = Employee.EmployeeType;
}
class Employee
{
public static bool EmployeeType
{
get { return true; } // Your logic here...
}
....
}
Related
Picture a case like this:
I have a controller action (or service method) where I need to call three methods in a consecutive order, each method has a single responsibility.
public return_type MyMethod(_params_) {
// .. some code
Method_1 (...);
Method_2 (...);
Method_3 (...);
// ... some more code
}
A developer can make the mistake of calling Method_2 before Method_1, or at least we can say that nothing forces him to follow this order, or to get an exception when the order isn't followed.
Now we can call Method_2 inside Method_1, and Method_3 inside Method_2, but that doesn't seem right when each method handles a completely different responsibility.
Is there a design pattern for this situation? Or any "clean" way to handle this?
This is exactly what facade pattern do.
Try to extract the three methods to another class, and make them private. Expose a single method MyMethod that calls the other methods in the desired order. Clients should use Facade.MyMethod
More details: https://en.m.wikipedia.org/wiki/Facade_pattern
I suppose you should leave control of execution for yourself and give possibility just to set what should be executed.
public interface IMethodsExecutor
{
void Execute();
void ShouldRunMethod1();
void ShouldRunMethod2();
void ShouldRunMethod3();
}
public class MethodsExecutor: IMethodsExecutor
{
private bool _runMethod1;
private bool _runMethod2;
private bool _runMethod3;
public MethodsExecutor()
{
_runMethod1 = false;
_runMethod2 = false;
_runMethod3 = false;
}
public void ShouldRunMethod1()
{
_runMethod1 = true;
}
public void ShouldRunMethod2()
{
_runMethod2 = true;
}
public void ShouldRunMethod3()
{
_runMethod3 = true;
}
private void Method1()
{
}
private void Method2()
{
}
private void Method3()
{
}
public void Execute()
{
if (_runMethod1)
{
Method1();
}
if (_runMethod2)
{
Method2();
}
if (_runMethod3)
{
Method3();
}
}
}
So that the usage will be:
IMethodsExecutor methodsExecutor = new MethodsExecutor();
methodsExecutor.ShouldRunMethod1();
methodsExecutor.ShouldRunMethod3();
methodsExecutor.Execute();
I am seeing a strange problem in my C# code. I have something like this:
public static class ErrorHandler {
public static int ErrorIgnoreCount = 0;
public static void IncrementIgnoreCount() {
ErrorIgnoreCount++;
}
public static void DecrementIgnoreCount() {
ErrorIgnoreCount--;
}
public static void DoHandleError() {
// actual error handling code here
}
public static void HandleError() {
if (ErrorIgnoreCount == 0) {
DoHandleError();
}
}
}
public class SomeClass {
public void DoSomething() {
ErrorHandler.IncrementIgnoreCount();
CodeThatIsSupposedToGenerateErrors(); // some method; not shown
ErrorHandler.DecrementIgnoreCount();
}
}
The problem is that the compiler often decides that the order of the three calls in the DoSomething() method is not important. For example, the decrement may happen before the increment. The result is that when the code that is supposed to generate errors is run, the error handling code fires, which I don't want.
How can I prevent that?
Add Trace or Logs to your code in IncrementIgnoreCount, DecrementIgnoreCount and HandleError function.
That will help you to view real call order.
I have a class Lot with a function AddPiece(piece).
I also have a Page with a button btnPanel that on click fires the function
public void btnPanel_OnClick(object sender, EventArgs e){}
I want to call the btnPanel_OnClick from the Addpiece function but when I try to do it it does not show in the intlliSense and I get this compilation error "The name 'btnPanel_OnClick' does not exist in the current context". Both classes are in the same namespace. Is this possible?
Here is what I have:
namespace GraphicW_Array
{
public partial class Board : System.Web.UI.Page
{
public void btnPanel_OnClick(object sender, EventArgs e)
{
...code...
}
}
}
and
namespace GraphicW_Array
{
public class Lot
{
public void addPiece(int piece)
{
lotPresent[lotLoad] = piece;
lotLoad++;
}
}
}
I think the answer is yes you can but you probably don't want to. To call the method you need and instance of your page class so you could do
namespace GraphicW_Array
{
public class Lot
{
public void addPiece(int piece)
{
lotPresent[lotLoad] = piece;
lotLoad++;
var myPage = new Board();
myPage.btnPanel_OnClick(null,EventArgs.Empty);
}
}
}
But what would that actually do? I have no idea because you haven't posted the code but i suspect it won't do anything useful for you.
What are you actually trying to achieve?
Maybe this is want you want
namespace GraphicW_Array
{
public class Lot
{
public void addPiece(int piece, Board myPAge)
{
lotPresent[lotLoad] = piece;
lotLoad++;
myPage.btnPanel_OnClick(null,EventArgs.Empty);
}
}
}
Then in your page you can call it like this:
var myLot = new Lot();
myLot.addPiece(4,this);
Yes, this is possible.
Ensure your Lot class has a reference to the Board class in order to be able to call it, or define an event on it that the Board class can subscribe to and that will call this mathod when the event fires.
If you don't use the sender and e parameters, just pass a null and EventArgs.Empty.
You can call page's event by passing either null(if sender and EventArgs is not mandatory) but below is the better way to go.
It is not wise and not good practice to call a event from a class, however you can create another method with arguments in your class and then call it with desired parameters when it is needed.
This is can be accomplished as below:
Say you have below event
public void btnPanel_OnClick(object sender, EventArgs e)
{
//Do some common tasks to do here
}
Rearrange it as below:
public void btnPanel_OnClick(object sender, EventArgs e)
{
Lot lot = new Lot();
lot.CommonFunction(arg1, arg2); // Pass required data
}
public class Lot
{
public void AFunction()
{
//Do something
//...
CommonFunction(arg1, arg2); // Pass required data
//...
//Do something
}
public void CommonFunction(string arg1, string arg2)
{
// Do some common tasks to do here
}
}
I've searched Google all day and can't find the correct answer to my issue, hoping someone here can help me.
So, in the "Main" form I have the method to show a form that needs to be centered directly above the parent form (frmMain). Normally I would call ShowDialog(this) to see the parent, but for some reason I have to set the loadNewsFeedItem to static in order to see the method from the flpNewsFeedHeader : Label derrived class (below). The OnClick event triggers the method loadNewsFeedItem().
When I call this to set the parent, I'm getting the message "Keyword 'this' is not valid in a static property, static method, or static field initializer"
namespace NewsFeeds
{
public partial class FrmMain : Form
{
public static void loadNewsFeedItem()
{
frmNewsFeedView frmFeedView = new frmNewsFeedView(FrmFuncs.selFeedID);
frmFeedView.ShowDialog(this); // Error occurs on this line, when calling this via a static method
}
}
}
public class flpNewsFeedHeader : Label
{
private int FeedID = 0;
public int theFeedID
{
get { return FeedID; }
set { FeedID = value; }
}
protected override void OnClick(EventArgs e)
{
FrmFuncs.selFeedID = FeedID;
Thread thrShowFeed = new Thread(new ThreadStart(FrmMain.loadNewsFeedItem));
thrShowFeed.Start();
}
}
Can someone please give me a corrected code example or a hint as to how to get the loadNewsFeedItem() to be visible without setting the accessor to static, or how to work around this in a static accessor?
Thanks in advance!
Chris
Edit: used ActiveForm for owner.
public partial class FrmMain : Form
{
public static void loadNewsFeedItem(Form owner)
{
frmNewsFeedView frmFeedView = new frmNewsFeedView(FrmFuncs.selFeedID);
frmFeedView.ShowDialog(owner);
}
}
}
public class flpNewsFeedHeader : Label
{
private int FeedID = 0;
public int theFeedID
{
get { return FeedID; }
set { FeedID = value; }
}
protected override void OnClick(EventArgs e)
{
FrmFuncs.selFeedID = FeedID;
// Shouldn't need a new thread. Already on the GUI thread.
FrmMain.loadNewsFeedItem (System.Windows.Forms.Form.ActiveForm);
}
}
may be you mean this:
frmFeedView.Owner = System.Windows.Forms.Form.ActiveForm;
frmFeedView.ShowDialog();
In a static method, this is meaningless. One option is to skip the parameter
frmFeedView.ShowDialog();
The other option is to setup a static variable as shown below (but beware, it can have side effects if you try to open multiple instances of FrmMain)
public partial class FrmMain : Form
{
private static FrmMain staticInstance;
public FrmMain()
{
staticInstance = this;
InitializeComponent();
...
}
public static void loadNewsFeedItem()
{
frmNewsFeedView frmFeedView = new frmNewsFeedView(FrmFuncs.selFeedID);
frmFeedView.ShowDialog(staticInstance );
}
In one of my previous questions I explained about a form class that contain form field objects to save data in a user profile object (using profile provider).
The code is here bellow. Basically what I would like to accomplish is to pass as a parameter to my form field objects the field of the Profile object that they should interact in order to save the data later on.
You can see that in the following line:
//LastNameFormLine is an control that was added to my form page.
//The ProfileField parameter stores the field of the UserProfile object that is being manipulated by this control
LastNameFormLine.ProfileField = "UserProfile.LastName";
I was reading about reflection to be able to save this value in the UserProfileVisitor class, but I came across this concept of delegate in C# which I am not sure yet if I fully grasp.
Is it possible to delegate the ProfileField to a property on my UserProfile class? Or should I forget about it and go with reflection?
What would you suggest?
public partial class UserProfileForm : CustomIntranetWebappUserControl
{
protected override void OnInit(EventArgs e)
{
//AutoEventWireup is set to false
Load += Page_Load;
CancelLinkButton.Click += CancelButtonClickEvent;
SaveLinkButton.Click += SaveButtonClickEvent;
base.OnInit(e);
}
private void SaveButtonClickEvent(object sender, EventArgs e)
{
VisitFormFields();
}
private void VisitFormFields()
{
var userProfileVisitor = new UserProfileVisitor();
foreach (var control in Controls)
{
if (control is FormFieldUserControl)
{
var formField = (FormFieldUserControl) control;
formField.Visit(userProfileVisitor);
}
}
userProfileVisitor.Save();
}
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
BindText();
}
}
private void BindText()
{
LastNameFormLine.LabelText = string.Format("{0}:", HomePage.Localize("Last Name"));
LastNameFormLine.InputValue = UserProfile.LastName;
LastNameFormLine.IsMandatoryField = true;
LastNameFormLine.IsMultilineField = false;
LastNameFormLine.ProfileField = "UserProfile.LastName";
//... the rest of this method is exactly like the 4 lines above.
}
}
public abstract class FormFieldUserControl : CustomIntranetWebappUserControl
{
public string ProfileField { get; set; }
public abstract void Visit(UserProfileVisitor userProfileVisitor);
}
public partial class FormLineTextBox : FormFieldUserControl
{
//... irrelevant code removed...
public override void Visit(UserProfileVisitor userProfileVisitor)
{
if (userProfileVisitor == null)
{
Log.Error("UserProfileVisitor not defined for the field: " + ProfileField);
return;
}
userProfileVisitor.Visit(this);
}
}
public class UserProfileVisitor
{
public void Visit(FormLineTextBox formLine)
{
// The value of formLine.ProfileField is null!!!
Log.Debug(string.Format("Saving form field type {1} with profile field [{0}] and value {2}", formLine.ProfileField, formLine.GetType().Name, formLine.InputValue));
}
// ... removing irrelevant code...
public void Save()
{
Log.Debug("Triggering the save operation...");
}
}
Delegates are not for properties. However, Reflection is slow, may have issues with code security and it's not typesafe and may lead to runtime instead of compile-time problems on naming errors due to the late-bound nature.
That said, you may want to use getter and/or setter methods and use delegates on those.