C# property not working - asp.net

Dont understand why its not working.. im using the property to set the Activelogin to true then getting the value in another page to certify that the user is has access.
namespace Ibrax_1
{
public partial class loginPage : System.Web.UI.Page
{
public bool activelogin;
public bool Activelogin
{
get
{
return activelogin;
}
set
{
activelogin = value;
}
}
.
.
.
Activelogin = true; // here in a method im setting the value to true.
and im getting value here:
namespace Ibrax_1
{
public partial class Program : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
CheckAvailablePrograms();
}
private void CheckAvailablePrograms()
{
loginPage lp = new loginPage();
if (lp.Activelogin) //here im getting the value but its false
{
am i doing anything wrong?

You're creating a new instance:
loginPage lp = new loginPage();
That new instance will have every property set to its default value. For boolean, that's false.
If you're setting it to true somewhere else, then it won't matter since you're not looking at that instance.
It's like drawing on a piece of paper and then taking another paper and wondering why there's no drawing on it. You can't expect there to be a drawing unless you're looking at the same piece of paper.
So you need to save the instance of object somewhere so you can use it again in the CheckAvailablePrograms method. As Alex Kudryashev mentioned, you could save it as a Session variable, although it's not the only way. You can read more about the Session object here if you wish: https://msdn.microsoft.com/en-us/library/ms178581.aspx

Related

Eclipse Scout callback for entering value in fields

I would like to know if there is a function that fires up when user set value in field but not if program set value in field.
so function :
user click on field 'myField and change value -> method fires up
in program : myField.setValue = SomeValue; -> method doesn't fires up.
problem is with loop detection. If your logic is that you have 4 field and try to detect if any of those fields are changed and then fire method for change some values inside those fields :
#Override
protected void execChangedValue() throws ProcessingException {
super.execChangedValue();
valueFieldsChange(this);
}
protected void valueInPriceBoxFieldsChange(AbstractValueField field) {
... calculate some values in those fields....
}
and I get :
!MESSAGE org.eclipse.scout.rt.client.ui.form.fields.AbstractValueField.setValue(AbstractValueField.java:338) Loop detection in...
So I know the method execChangedValue() are not what I am looking for. Is there similar method with explained behavior ?
Marko
Let start to say that loop detection is useful in 90% of the cases.
The warning is displayed when you are inside an execChangedValue() and you try to update the value of the same field.
If I understand your example correctly you have inside your field:
public class FirstField extends AbstractStringField {
#Override
protected void execChangedValue() throws ProcessingException {
calculateNewValues();
}
}
And the method:
public void calculateNewValues() {
//some logic to compute the new values: value1, value2, value3
getFirstField().setValue(value1);
getSecondField().setValue(value2);
getThirdField().setValue(value3);
}
At this point, you really need to be sure that when the user sets the value in the FirstField to something, you might want to change it pragmatically to something else. This might be really confusing for the user.
If you are sure that you need to update the value, there is a way to set a value without triggering execChangedValue() on the field. I have proposed a new method: setValueWithoutChangedValueTrigger(T value) on the Eclipse Scout Form: Controlling if execChangedValue() is called or not.
On the forum you will find a snippet that you can add to your field (or in a common template: AbstractMyAppStringField).
public class FirstField extends AbstractStringField {
#Override
protected void execChangedValue() throws ProcessingException {
calculateNewValues();
}
public void setValueWithoutValueChangeTrigger(String value) {
try {
setValueChangeTriggerEnabled(false);
setValue(value);
}
finally {
setValueChangeTriggerEnabled(true);
}
}
}
And you will be able to use it:
public void calculateNewValues() {
//some logic to compute the new values: value1, value2, value3
getFirstField().setValueWithoutChangedValueTrigger(value1);
getSecondField().setValueWithoutChangedValueTrigger(value2);
getThirdField().setValueWithoutChangedValueTrigger(value3);
}
I hope this helps.

C# ASP.NET - Controlling/updating a textbox.text value through a class

Newbie here, I need help with a website I'm creating.
I have a class that does some analysis on some text that is input by the user, the class then finds an appropriate answer and sends it back to the textbox. (in theory)
Problem is I don't know how I can control and access the textbox on the default.aspx page from a class, all I get is "object reference is required non static field".
I made the textbox public in the designer file yet still no joy. :(
I've also read this: How can I access the controls on my ASP.NET page from a class within the solution? , which I think is along the lines of what I'm trying to achieve but I need clarification/step by step on how to achieve this.
Hope someone can point me in the right direction.
Many thanks,
Kal
This is the code I have added to the designer.cs file:
public global::System.Web.UI.WebControls.TextBox TextBox3;
public string MyTextBoxText
{
get
{
return TextBox3.Text;
}
set
{
TextBox3.Text = value;
}
}
This is the class method i have created:
public static cleanseMe(string input)
{
string utterance = input;
string cleansedUtt = Regex.Replace(utterance, #"[!]|[.]|[?]|[,]|[']", "");
WebApplication1._Default.TextBox3.text = cleansedUtt;
}
I could just return the cleansedUtt string i know, but is it possible for me to just append this string to the said textbox from this method, within this class?
I also tried it this way, i wrote a class that takes in the name of the textbox and string to append to that textbox. it works BUT only on the default.aspx page and does not recognise the textbox names within the difference classes. The code is as follows:
public class formControl
{
public static void ModifyText(TextBox textBox, string appendthis)
{
textBox.Text += appendthis + "\r\n";
}
I would suggest you that do not access the Page Controls like TextBox in your class. It will be more useful and a good practice that whatever functionality your class does, convert them into function which accept the parameters and returns some value and then on the basis of that value you can set the controls value.
So now you have reusable function that you can use from any of the page you want. You do not need to write it for every textbox.
Here I am giving you a simple example
public class Test
{
public bool IsValid(string value)
{
// Your logic
return true;
}
}
Now you can use it simple on your page like this
Test objTest = new Test();
bool result=objTest.IsValid(TextBox1.Text);
if(result)
{
TextBox1.Text="Everything is correct";
}
else
{
TextBox1.Text="Something went wrong";
}
If you have your class in the same project (Web Project) the following will work:
public class Test
{
public Test()
{
//
// TODO: Add constructor logic here
//
}
public static void ValidateTextBox(System.Web.UI.WebControls.TextBox txt)
{
//validation logic here
if (txt != null)
txt.Text = "Modified from class";
}
}
You can use this from your webform like this:
protected void Page_Load(object sender, EventArgs e)
{
Test.ValidateTextBox(this.txt);
}
If your class is in a different (class project), you would need to add a reference to System.Web to your project.

Ajaxpro methods get global page variable to be reinitialized?

I have a problem with ajaxpro methods. In the .cs file I defined some global variable for my page, something like:
public partial class Admin : System.Web.UI.Page
{
public int localidMember = 9;
protected void Page_Load(object sender, EventArgs e)
{
AjaxPro.Utility.RegisterTypeForAjax(typeof(Admin));
if (HttpContext.Current.Session["HomeOwn_ID"] != null)
{
localidMember = Convert.ToInt32(HttpContext.Current.Session["HomeOwn_ID"].ToString());
}
}
[AjaxPro.AjaxMethod(AjaxPro.HttpSessionStateRequirement.ReadWrite)]
public string LoadInbox()
{
// I need to use the variable localidMember and expected that it will have the value that I have set to pageload.., but it didnt. The variable is reinitialized to 9... Anyone have any ideas what's going on... Thanks so much !
}
}
I think you can't do it; because, in AjaxPro, you can't deal with control properties.
AjaxMethod will have its own Context. Hence, localidMember will not be accessible inside it. You may consider passing it as a parameter.

Caliburn Micro: querying view-specific data from the VM

I'm completely new to CM and also to learn it I'm migrating an application from MVVM light to Caliburn Micro. In my original code, I had a VM which responds to some UI actions (via commands) to replace some text into a string. The position is given by the view, using the textbox selection.
So the VM has (1) a bound string property representing the textbox's text, (2) another bound string property to represent the new text to be added, and (3) needs to know selection start and length in order to replace the right portion of text with the new one.
In my original code, I had a custom DialogMessage-derived object sent in the VM command implementation with a couple of properties for selection data: when the command was issued, the message was sent, and the view received it and filled it with its textbox selection start and length; then the VM was called back and could use these data.
Which would be the best way of implementing this in CM? I'd prefer the VM to remain agnostic of the view, so I don't like too much the idea of accessing the view from it. I'd rather opt for a "message"-based mechanism like the above, but I'm not sure how I can implement it in CM: I would probably look at IResult, but most of the samples I find are related to coroutines and I'm not sure how to relate the void ReplaceText() method of the VM to the view code behind.
Could anyone point me in the right direction, and/or to some code samples about dialog-like interactions between VM 'command' methods and view? Thanks!
I'd probably look at the IResult option. You'll have access to the view so code that you would have had in the code behind can be in your Result and not in your VM.
Here is code from a ShowDialog result. I believe I grabbed it from the CM discussion group. Search the discussion group for ShowDialog for more examples. The GameLibrary sample that comes with CM also has some.
public class ShowDialog : IResult
{
private readonly Type _screenType;
private readonly string _name;
[Import]
public IWindowManager WindowManager { get; set; }
public ShowDialog(string name)
{
_name = name;
}
public ShowDialog(Type screenType)
{
_screenType = screenType;
}
public void Execute(ActionExecutionContext context)
{
var screen = !string.IsNullOrEmpty(_name)
? IoC.Get<object>(_name)
: IoC.GetInstance(_screenType, null);
Dialog = screen;
WindowManager.ShowDialog(screen);
var deactivated = screen as IDeactivate;
if (deactivated == null)
Completed(this, new ResultCompletionEventArgs());
else
{
deactivated.Deactivated += (o, e) =>
{
if (e.WasClosed)
{
Completed(this, new ResultCompletionEventArgs());
}
};
}
}
public object Dialog { get; private set; }
public event EventHandler<ResultCompletionEventArgs> Completed = delegate { };
public static ShowDialog Of<T>()
{
return new ShowDialog(typeof (T));
}
}
edit: If you extend TextBox you can bind SelectedText.
public class TextBoxEx : TextBox
{
public static readonly DependencyProperty SelectedTextProperty = DependencyProperty.Register("SelectedText", typeof(string), typeof(TextBoxEx), new PropertyMetadata("oa"));
public TextBoxEx()
{
SelectionChanged += UpdateDependencyProperty;
}
private void UpdateDependencyProperty(object sender, RoutedEventArgs e)
{
SelectedText = base.SelectedText;
}
public new string SelectedText
{
get { return GetValue(SelectedTextProperty).ToString(); }
set { SetValue(SelectedTextProperty, base.SelectedText); }
}
}
then:
<SLTest:TextBoxEx x:Name="MyTextBox2"
Grid.Row="1"
Width="200"
SelectedText="{Binding SelectedText, Mode=TwoWay}"
Text="This is some text." />

Auto wiring of Property does not work for me

In my Asp.Net project I wanna use Property Auto-wiring, e.g. for my ILogger. Basically I placed it as Property into class where I need to use it. Like below.
public class UserControlBase : UserControl
{
public ILogger CLogger { get; set; }
....
}
public partial class IPTracking : UserControlBase
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string ip = HttpContext.Current.Request.ServerVariables["REMOTE_ADDR"];
//it works
ILogger logger = ObjectFactory.GetInstance<ILogger>();
logger.LogInfo(string.Format("Client IP: {0}", ip));
//it does not work
CLogger.LogInfo(string.Format("Client IP: {0}", ip));
}
}
}
However when calling in inherited control, logger is null. I checked the container and it'a definitely set as above implementation shows. Below is setting which is called from Global.asax.
public static void SetupForIoC()
{
Debug.WriteLine("SetupForIoC");
ObjectFactory.Initialize(x =>
{
x.FillAllPropertiesOfType<ILogger>().Use<EntLibLogger>();
});
Debug.WriteLine(ObjectFactory.WhatDoIHave());
}
Thanks for any advice, tip? X.
Update:
- I didnt mentioned before, but its Asp.Net webforms 3.5.
- I can't see what I am missing. I guess it could be because the injection gets involved later in process and didnt get set in requested class.
Link to desc. of usage: http://structuremap.github.com/structuremap/ConstructorAndSetterInjection.htm#section7
Give something like this a shot.
FillAllPropertiesOfType<ILogger>().AlwaysUnique().Use(s => s.ParentType == null ? new Log4NetLogger(s.BuildStack.Current.ConcreteType) : new Log4NetLogger((s.ParentType)));
Check out another StackOverflow answer I have which discusses using StructureMap to auto wire loggers.
Where do you actually set the CLogger property on the user control? Also, if you wanted to use one logger within the page, you could have the User cotnrol do:
public ILogger CLogger
{
get
{
if (this.Page is PageBase)
return ((PageBase)this.Page).Logger;
else
return null;
}
}

Resources