...is inaccessible due to its protection level c#/asp.net - c#

I have an application with a separate class, that i'm instantiating in the code behind-file (in Page_Load). In the class there's some methods that I want to be able to call from the code behind-file, but by some reason it doesn't work (SecretNumber.MakeGuess(int) is inaccessible due to it's protection level). The class as well as the methods are public so what can be the reason?
// Default.asx.cs
...
protected void btnCheckNr_Click(object sender, EventArgs e)
{
if (!Page.IsValid){
return;
}
else{
var guessedNr = int.Parse(inputBox.Text);
var result = SecretNumber.MakeGuess(guessedNr); <- inaccessible due to...
}
}
// SecretNumber.cs
public class SecretNumber {
enum Outcome {
Indefinite,
Low,
High,
Correct,
NoMoreGuesses,
PreviousGuess
};
// Other code goes here...
public Outcome MakeGuess(int guess) {
// Other code here
}
}

It is because your Outcome enumeration is private. Also in the code you have, MakeGuess needs to be marked as static to be used the way you have it written.

You're calling the method as though it is static, yet it is not a static method. How did your code even compile??
To clarify, that is not the cause of accessibility issue and others have posted the solution for that. But the aforementioned way you call the method is also a glaring problem (unless you just put a typo by not showing that is in fact static when posting your code).

Outcome is needed to be declared public and I can't tell if you've had the class initialized in which case it either would need to be or declared static.

You have to public Static Class SecretNumber instead of public Class SecretNumber

Related

Method overriding or interception

In my project, I have many DLL assemblies referenced. One of those DLL's contains the bool method that I want to change. I do not have the original source for the DLL and using a Reflector to decompile a project seems impractical. All I want to do is intercept or override this method or method call so that I can change it's return value to match my own method outside of said DLL.
Any such way to do this? Thanks!
Edit:
Here is an example:
public virtual bool isOwner()
{
return false;
}
Essentially, I just want to change getOwner to return true;
If the class is public and the method is marked as virtual, then you can simply override it with this syntax:
public MyClass : TheClass
{
public override ReturnType MethodName(Arguments)
{
//class the base class implementation if needed
//base.MethodName(Arguments)
//do your own stuff and return whatever is needed
}
}
Hope this helps
EDIT: A word of caution though, this won't replace the calling code within the DLL. It will only work if you instantiate the derived class yourself and call it from your code.
Is there a general way to do what you want, built into .NET?
Yes, and no.
If you want every usage of class X' method Y to be replaced by some other code, then no, there is nothing built into .NET class system or compiler that will do this.
If you can inherit from class X, overriding method Y, and then ensure that all places where class X is used, your new class is used instead, then yes, that is the proper way to do this.
This is easily done:
public class YourFixedClass : TheProblematicClass
{
public override string YourProblematicMethod()
{
// probably call the problematic method through base.
// and fix the return value, or fix the parameters
// or don't call it at all, re-doing whatever it does
}
}
Or, if you can make a new class that implements all the same interfaces, wrapping (delegating) all the methods and properties of the original (problematic) class, then that might be doable, but this requires all actual usage of the class to go through the interfaces.
As this:
public class Wrapper : IInterface1, IInterface2
{
private readonly YourProblematicClass _C;
public Wrapper(YourProblematicClass c)
{
_C = c;
}
public string YourProblematicMetho()
{
// probably call the problematic method through _C.
// and fix the return value, or fix the parameters
// or don't call it at all, re-doing whatever it does
}
}
If, on the other hand, you don't have control of where all the code is that calls the class/method, then no, you can't do any of this.
So what else is there? Well, there is always the debugger interfaces. You can make a program that is somehow the debugger of itself, patching in the right code upon demand, but this is likely to be extraordinary difficult to get right.
In short, no, there is no way to do what you want. You need to find a different way to accomplish this.
Have you thought about changing the original assembly in the first place? I understand that you don't have the source code for it, but is that because:
You lost it
You didn't make it
In point 1, I would really work towards recreating the source code, either through a decompiler or similar, and get a new project going to fix that.
In point 2, have you thought about contacting the people that made it and asking them for help?
Uhm Ok you can do something like this:
public class MyNameClass : MyDllname.MyClassName
{
public bool isOwner()
{
return !base.isOwner();
}
}
Then you have override the method and you can use all the other methods in the DLL simply using an istance(if there aren't static) of the MyNameClass
You can use "new" modifier.
See example on http://msdn.microsoft.com/en-us/library/435f1dw2.aspx
Or this:
class Program
{
static void Main(string[] args)
{
Console.WriteLine(new ClassA().IsEvenDayToday()); // Result: true
Console.WriteLine(new ClassB().IsEvenDayToday()); // Result: false
Console.ReadKey();
}
}
public class ClassA : ClassB
{
public new bool IsEvenDayToday()
{
return DateTime.Now.Day % 2 == 0;
}
}
public class ClassB
{
public bool IsEvenDayToday()
{
return DateTime.Now.Day % 2 != 0;
}
}

Attribute to generate compilerwarning for a method in class

I have a class, where I use the singleton-pattern. The class looks like
public class MessageAccess
{
private static MessageAccess instance;
public static MessageAccess Instance
{
get { return instance ?? (instance = new MessageAccess()); }
}
private MessageAccess()
{
}
public void Initialize(string data)
{
//...
isInitialized = true;
}
private bool isInitialized;
public void ReadData1()
{
// This Method can always be called
}
public void ReadData2()
{
// This Method can only be called, if Initialize was called. Otherwise an exception will be thrown
}
}
Is it possible to generate a compiler-warning if the Method Initialize is never called
While I understand your point of view, I don't think such warning would be as handy as you think. I'm afraid .NET framework doesn't cater for this type of warnings for a couple of well defined reasons (please refer to this link: http://blogs.msdn.com/b/csharpfaq/archive/2004/03/19/why-doesn-t-c-warn-about-unused-methods.aspx).
One might think that the lack of this feature is a missed opportunity, but it's not quite the case. Your class, MessageAccess, is public and will be compiled into (let's say) a dll. Even if you had this warning while compiling your dll, you wouldn't want it to appear while compiling some external code using that dll's Initialize method (which is also public). You basically can't guarantee that no other code will ever use that method, and this is one of the better reasons not to have this warning.
If the class is not used from outside the assembly, you can make it internal. In this case, Code Analysis will generate a warning "Avoid uncalled private code", if the method is not called.

Need a pattern to call Verify method for every instance method pattern

I have the following code:
class Foo
{
public Foo()
{
Size = true;
}
private bool _size;
protected bool Size
{
get { _size; }
set { _size = value; }
}
}
class CrazyFoo : Foo
{
public void First()
{
if (!Size)
return;
}
public void Second()
{
if (!Size)
return;
}
public void Finished()
{
if (!Size)
return;
}
}
What is the best way to implement this sort of pattern, as it drives me nuts to type
if(!Size) return;
perhaps I can do it with attributes or AOP?
What is the best and simplest way?
Thanks
If you have the same guard statement at the beginning of too many methods, you can create a method called executeWithGuard:
private void executeWithGuard(Action method)
{
if (HeadSize) method();
}
Then you could do this:
public void ScreenFirstShot()
{
executeWithGuard(() =>
{
// code here
});
}
public void ScreenSecondShot()
{
ExecuteWithGuard(() =>
{
// code here
});
}
public void CrazyUp()
{
ExecuteWithGuard(() =>
{
// code here
});
}
There's no less code doing this... in fact, there's probably more code, but it does allow you to not have to do a find/replace if your guard condition ever changes. I'd only suggest it as a last resort, though. It's very possible that your real problem is that you're doing your validation too far down the call tree. If you can do it at a higher level, you may save yourself from all of this validation.
ALSO
Have a look at the null object patttern. This pattern can be used in some special cases to prevent or simplify state checking.
ALSO (rev 2)
It's hard to know what your intent is since the question focuses on a specific solution, but if you're executing these methods sequentially, you can look at using the strategy pattern, and putting the check in your base strategy class.
From a "pattern" standpoint, though, this doesn't seem onerous to me. It seems perfectly reasonable to me to type:
if(!Size)
return;
You're explicitly handling the cases you want. In your case, this check is pretty specific to what you are working with, from what I can tell (from your original + edits). I'd personally choose a more obvious name, since it does seem a little strange (even in your original), and not completely obvious what's happening.
Even with AOP, you'd be adding some other information here on each method, to make sure your aspect was handled.
Maybe just use one method and an Enum with the values First, Second, Finished etc.? It's hard to tell because, apart from that one check, you don't say what is common. AOP could be a solution, but maybe not, since aspects are usually more general in their conceptional nature.
BTW, maybe choose a different naming for your samples in the future, this may offend some people. (Edited to match new naming)

How does one access a control from a static method?

I have an application in C# .NET which has a MainForm and a few classes.
One of these classes receives incoming data messages from a network. I need to get these message's text appended into a multi-line textbox on the MainForm.
I can send the message to a method in the MainForm by making the method static, but then the static method cannot access the MainForm's controls.
TheIncomingDataClass.cs
namespace TheApplicationName
{
class TheIncomingDataClass
{
public void IncomingMessage(IncomingMessageType message)
{
TheApplicationName.MainForm.ReceiveMSG(message);
}
MainForm.cs
public static void ReceiveMSG(string message)
{
txtDisplayMessages.AppendText(message); //This line causes compile error
}
The compile error:
An object reference is required for the nonstatic field, method, or
property 'TheApplicationName.MainForm.txtDisplayMessages'
A static method doesn't have access to members like txtDisplayMessages because it is not a part of that instance. I suggest you do some reading on the concepts of static methods and whatnot, because that is a fairly language agnostic concept. That method would best be served by removing the static modifier, because it doesn't need to be static - it appears that it would need to be called by that particular instance of that object.
To continue the way you've been doing it, your "TheIncomingDataClass" should have a reference to the MainForm object with which it should interface. When you create an instance of this class (presumably from an instance method of MainForm), you will need to pass in a reference to this MainForm object.
class TheIncomingDataClass{
MainForm form;
public TheIncomingDataClass(MainForm form){
this.form = form;
}
}
class MainForm : Form{
MainForm(){
new TheIncomingDataClass(this);
}
}
However, as suggested by Bugs, you probably would be better off making this an event on TheIncomingDataClass and subscribing to it from MainForm.
class IncomingMessageEventArgs : EventArgs{
IncomingMessageType message;
public IncomingMessageType Message{get{return message;}}
public IncomingMessageEventArgs(IncomingMessageType message){
this.message = message;
}
}
class TheIncomingDataClass{
public event EventHandler<IncomingMessageEventArgs> MessageReceived;
protected virtual void OnMessageReceived(IncomingMessageEventArgs e){
if(MessageReceived != null)
MessageReceived(this, e);
}
public void IncomingMessage(IncomingMessageType message){
OnMessageReceived(new IncomingMessageEventArgs(message));
}
}
class MainForm : Form{
MainForm(){
new TheIncomingDataClass().MessageReceived +=
(s, e)=>txtDisplayMessages.AppendText(e.Message.ToString());
}
}
Its possible to pass in a reference to the current form like this:
public static void ReceiveMSG(string message, MainForm mainform)
{
mainform.txtDisplayMessages.AppendText(message);
}
Although as suggested an event is probably a better way of doing it.
raise an event from class which the form can subscribe to.
Just remove the static modifier, you don't need it for your purposes. Read about statics here.
You can solve this problem by removing the static keyword.
When you see "static", think: without an instance of this type.
When you call a non-static method, you must explicitly use some instance. The method can access that instance using the "this" keyword.
When you call a static method, there is no instance - you have abandoned the boundaries of OO and are now in a structural or functional programming context. If you want an instance of something, you need to bring it in as a parameter.
I think you might be taking the wrong approach on this. It sounds like you are trying to push messages to a client from an external process. There are ways to do this, but it will get complicated. My suggestion would be to have the client poll whatever process has the data periodically - maybe every 10 seconds depending on your needs. This is going to be a heck of a lot easier than pushing from server to client.
Ok here goes.
Static methods can access only static members. Your ReceiveMSG method is static. txtDisplayMessages is not and hence you cant access it.
Why does your method need to be static? Needless to say, if you remove the static keyword that will fix your problem.
Just make ReceiveMSG part of a class, create an instance of the class and then call the method on the instance.
I think you should post the kind the solution you are expecting.
Seeing as you are new to C# I will keep this as simple as possible. You should have a Program.cs file that has a single method Main (this would have been generated by Visual Studio). You will need to make it look like the following:
class Program
{
public static readonly MainForm MainForm;
static void Main()
{
Application.EnableVisualStyles();
MainForm = new MainForm(); // These two lines
Application.Run(MainForm); // are the important ones.
}
}
Now in your incoming message you will have a way to access that form.
public void IncomingMessage(IncomingMessageType message)
{
Program.MainForm.RecieveMSG(message);
}
That method in the form would then be a instance (not static) method. E.g.
public void RecieveMSG(IncomingMessageType message) // NB: No static
{
txtDisplayMessages.Text = message.Text; // Or whatever.
}
There are better ways to do it - but as a beginner I think this would be the best approach.
The difference between static and instance (instance is when you don't say static) is huge. To get to an instance method, field or property (which are collectively called members in C#) you need to have the containing instance. So:
Person p = new Person(); // You now have an instance.
p.Name = "Fred"; // You are using an instance property.
Static are the opposite, they are the same anywhere in your application (more technically within the same AppDomain - but if you are a beginner you won't need to worry about that for a while). You don't need an instance to get to them (props to codewidgets "Static methods can access only static members"). For example:
// Where Planet is a class and People is a static property.
// Somewhat confusingly the Add method is an instance - best left for the student :).
Planet.People.Add(new Person("Fred"));
Hopefully that gives you a good indication of what static and instance is and where to use them. The most important thing though is to try and avoid static members as best as you can - they can cause maintenance nightmares.
Microsoft has a whole write-up on the important concepts in regard to this.
private void FormMain_Load(object sender, EventArgs e)
{
TheIncomingDataClass.SetupControl(textBox1);
}
public class TheIncomingDataClass
{
public static TextBox textbox = new TextBox();
public static void SetupControl(TextBox txt)
{
textbox = txt;
}
public void IncomingMessage(string message)
{
textbox.Text = message;
}
}

Is it possible for a function to only be called from within another function?

In C# is it possible to create a function that can only be called from within another function?
e.g., can you do something like this?
private void a()
{
b();
c();
...do something else
private void b()
{
..do something but can only be called from a()
}
private void c()
{
..do something but can only be called from a()
}
}
The reason I want to do this is that function b() and c() split some implentation details of a() and they are just cleaner and easier to read in their own scope. However, these functions are of no use to the class as a() does some handling after they are called which must take place.
Use an anonymous nested function maybe?
I wouldn't worry about taking explicit steps to ensure b() and c() are only called by a().
It makes sense to worry about the public methods you expose on a class, since you're providing an interface to the outside world, potentially to people who don't have access to the source code of your class (or at the very least don't want to worry about the implementation details of your class).
Inside your class, though, you should feel free to have whatever private methods you want for whatever reasons you want. Code re-use is one reason to create a new private method, but creating multiple smaller, single-use methods to break up a larger one is also a perfectly valid (and common) reason.
Beyond that, for future maintainers of your code a simple comment like:
//this method should only be called by a()
private void b()
{
...
}
is going to be far more understandable than most of the other solutions presented here.
Using a delegate you can do:
public voidMyFunction()
{
Func<string> myFunction=(s)=>Console.WriteLine(s);
foreach(string str in myStringList)
{
myFunction(str);
}
}
The short answer is no; however, you can create an anonymous delegate or lambda expression as your internal b() method.
You could use the StackFrame class to check at runtime who's the caller of the function:
public class MyClass
{
public static void A()
{
B();
}
public static void B()
{
var stackTrace = new StackTrace();
if (stackTrace.FrameCount < 1 || stackTrace.GetFrame(1).GetMethod() != typeof(MyClass).GetMethod("A"))
throw new InvalidOperationException("Not called from A()");
}
}
But that is
1) Only at runtime
2) Slow
3) A really dirty hack
Well you could use reflection and just get the calling method name and throw an exception if it were anything other than A.
http://www.csharp-examples.net/reflection-calling-method-name/
But if b and c are private they can only be called from within that class anyway, and if you're the only one that is writing the class, then i fail to see the problem. So it seems to me its not a coding problem but rather one of policy.
I'd just document the intent in the method headers/comments.
Similar Question Here - Note the comments on the answer
Not exactly but you could implement both within their own class. Mark b() as private.
To gain the effect of only a() calling b(), either do as Andrew noted already, by putting a() and b() in a class and marking b() appropriately. If you're working inside of an assembly that you control totally, you could use internal instead of private if a() and b() will be in different classes, but in the same assembly. Then user code cannot call it (from outside of your assembly, that is, from their application program) and you can control via policy the writing of your assembly.
You can also create something like this:
internal abstract class SecretFunctionWrapper
{
private void MySecretFunction()
{
...
}
protected void FunctionWhichCalls()
{
...
MySecretFunction();
}
}
public MyRealClass : SecretFunctionWrapper
{
...
}
This will work only for one function. You can also try nested private class like this:
public class A
{
private static class Wrapped
{
private static void A()
{
secred code
}
public static void B()
{
A();
}
}
public void UsingA()
{
Wrapped.B();
}
}
i dont know but maybe Code by Contracts may help but this is not supported natively
Maybe easier to use #region in this case
You could use the internal keyword and put both those functions inside the same class, while leaving other other functions in a different class:
http://msdn.microsoft.com/en-us/library/7c5ka91b.aspx

Categories