how can i call method in web page from class library - asp.net

I have a page sample.aspx. In this file page I use ajax to call a handler which in class library. I do some job in class lib. After doing this, I want to call method from sample.cs.
For example:
addstudent.aspx page calls ajax request to addstudent.ashx (this code is in handler.cs). I am adding student with params, and after adding students I want to call a method which is in addstudent.cs for example public afteraddingstudent(){}
How can I call after adding student in class lib?

Make your afteraddingstudent method as public static and after that you can call this method in handler as
public static void afteraddingstudent()
{
}
Handler,
WebApplication1.addstudent.afteraddingstudent();

//in my Handler class lib,it is separated project
public class gnric : IHttpHandler, IRequiresSessionState
{
public enum DBAction
{
INSERT = 0,
UPDATE = 1,
DELETE = 2
}
public class DatabaseEventArgs : EventArgs
{
private DBAction prmAction;
private int prmID;
public DatabaseEventArgs(DBAction Action, int ID)
{
this.prmAction = Action;
this.prmID = ID;
}
public int ID
{
get { return prmID; }
}
public DBAction Action
{
get { return prmAction; }
}
}
public delegate void DBChangeEventHandler(object sender, DatabaseEventArgs e);
[Category("DB"), Description(" when a record is Inserted, Updated, or Deleted.")]
public event DBChangeEventHandler DBChange;
protected virtual void OnDBChange(DatabaseEventArgs e)
{
if (DBChange != null)
DBChange(this, e);
}
public void ProcessRequest(HttpContext context)
{
//DO SOME DBJOBS
OnDBChange(new DatabaseEventArgs(DBAction.UPDATE, 22));
//in my apsx file
protected void LNA_DBChange(object sender,HandlerClass.gnric.DatabaseEventArgs e) //how can I bind this method
{
EasySQL DBA = new EasySQL();
DBA.cmd("INSERT INTO TEST ALAN VALUES(3)");
}

Related

Unable to cast object of type 'ASP.masterpage_mpname_master' to type 'ITest'

I am developing a web application. I have created an interface ITest
public interface ITest
{
void Add();
}
& a usercontrol which implements ITest
public partial class WebUserControl1 : System.Web.UI.UserControl, ITest
{
public void Add()
{
throw new NotImplementedException();
}
}
On my webpage i have placed usercontrol. but, when i typecast the usercontrol to type IType it throws an Exception(System.InvalidCastException)
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
// WebUserControl11.Add();
foreach (var uCnt in this.Page.FindControlsOfType<UserControl>())
{
if (uCnt.Visible)
{
((ITest)uCnt).Add(); //Error : Casting Exception
}
else
{
}
}
}
}
I can call Add method directly but, I want to call it using ITest Interface
I'm not sure how the FindControlsOfType method implemented but suppose that you need to retrieve controls those implement ITest interface instead of all UserControl instances.

JSF custom panel with button - action not invoked

I have built a custom component button, but somehow the action is not invoked. When debugging the getAction-Method within the component and invoking the supplied MethodeExpression the Bean-Method is called as expected. But due to some reason, the Expression is not invoked when pressing the button in the browser.
Is there some kind of additional Interface necessary to pass the action to the embedded button-component?
Any help is very appreciated since I am stuck at this issue for some days now
MyClass:
public class MyClass extends UIPanel implements SystemEventListener
{
private UIForm form;
private HtmlCommandButton buttonOk;
public MyClass()
{
FacesContext context = getFacesContext();
UIViewRoot root = context.getViewRoot();
root.subscribeToViewEvent(PostAddToViewEvent.class, this);
}
#Override
public void processEvent(SystemEvent event)
{
this.form = new UIForm();
this.buttonOk = new HtmlCommandButton();
this.buttonOk.setId("okButtonId");
this.buttonOk.setActionExpression(getAction());
this.buttonOk.setValue("OK");
this.form.getChildren().add(this.buttonOk);
getChildren().add(this.form);
}
private enum PropertyKeys
{
action, text, titel
}
public MethodExpression getAction()
{
return (MethodExpression) getStateHelper().eval(PropertyKeys.action);
}
public void setAction(MethodExpression actionExpression)
{
getStateHelper().put(PropertyKeys.action, actionExpression);
}
public String getText()
{
return (String) getStateHelper().eval(PropertyKeys.text);
}
public void setText(String text)
{
getStateHelper().put(PropertyKeys.text, text);
}
public String getTitel()
{
return (String) getStateHelper().eval(PropertyKeys.titel);
}
public void setTitel(String titel)
{
getStateHelper().put(PropertyKeys.titel, titel);
}
#Override
public void encodeAll(FacesContext context) throws IOException
{
ResponseWriter writer = context.getResponseWriter();
writer.startElement(HTML.DIV_ELEM, this);
writer.writeText(getText(), null);
this.form.encodeAll(context);
writer.endElement(HTML.DIV_ELEM);
}
#Override
public void encodeChildren(FacesContext context) throws IOException
{
}
#Override
public boolean isListenerForSource(Object source)
{
return (source instanceof MyClass);
}
}
MyClassHandler:
public class MyClassHandler extends ComponentHandler
{
public MyClassHandler(ComponentConfig config)
{
super(config);
}
#SuppressWarnings("rawtypes")
#Override
protected MetaRuleset createMetaRuleset(Class type)
{
return super.createMetaRuleset(type).addRule(new MethodRule("action", String.class, new Class[] { ActionEvent.class }));
}
}
myView Method:
...
public String myMethod()
{
System.err.println("myMethod");
return "/some/path/yadayada.xhtml";
}
...
MyView.xhtml
<myTag action="#{myView.myMethod}" id="id1" titel="bla" text="bleh" />
Exdending UICommand is enough, since you only want one action to be executed.
You have to provide two additional MethodExpressions via the tag-attributes and within the decode-method you can check which button has been pressed and redirect the particular MethodExpression to the standard-action provided by UICommand. This way, you dont have to worry about the legacy-interface ActionSource, or how Events are broadcasted.
public void decode(FacesContext contex)
{
Map<String,String> map = context.getExternalContext.getRequestParameterMap();
// your rendered buttons need a name you check for
final boolean okPressed = map.containsKey( getClientId + ":ok" );
final boolean cancelPressed = map.containsKey( getClientId + ":cancel" );
if(okPressed || cancelPressed)
{
MethodExpression exp = null;
if(okPressed)
{
exp = getActionOk();
}
else
{
exp = getActionCancel();
}
// redirect to standard action
setActionExpression(exp);
queueEvent(new ActionEvent(this));
}
}
In order to make use of of this you need two attributes (actionOk and actionCancel) which use Method Expressions (setter and getter). Those have to be configured by a ComponentHandler as you did for the action-attribute.

Create a log everytime When methods in an interface class are called

I want to update a log file(txt) everytime when methods in a an interface class are called?
Is there any way to do this other than writing code in every method to create log?
Here's my 30 mins. you'll have to implement the logging code somewhere so you have to create another abstraction for your code. thus an abstract class is needed. i think. this is very quick and dirty.
public interface IService<T>
{
List<T> GetAll();
bool Add(T obj);
}
then you'll need the abstract class where you'll need to implement your logging routine
public abstract class Service<T> : IService<T>
{
private void log()
{
/// TODO : do log routine here
}
public bool Add(T obj)
{
try
{
log();
return AddWithLogging(obj);
}
finally
{
log();
}
}
public List<T> GetAll()
{
try
{
log();
return GetAllWithLog();
}
finally
{
log();
}
}
protected abstract List<T> GetAllWithLog();
protected abstract bool AddWithLogging(T obj);
}
as for your concrete classes
public class EmployeeService : Service<Employee>
{
protected override List<Employee> GetAllWithLog()
{
return new List<Employee>() { new Employee() { Id = 0, Name = "test" } };
}
protected override bool AddWithLogging(Employee obj)
{
/// TODO : do add logic here
return true;
}
}
public class CompanyService : Service<Company>
{
protected override List<Company> GetAllWithLog()
{
return new List<Company>() { new Company() { Id = 0, Name = "test" } };
}
protected override bool AddWithLogging(Company obj)
{
/// TODO : do add logic here
return true;
}
}
public class Employee
{
public int Id {get;set;}
public string Name { get; set;}
}
public class Company
{
public int Id { get; set; }
public string Name { get; set; }
}
then on your implementation you can just..
static void Main(string[] args)
{
IService<Employee> employee = new EmployeeService();
List<Employee> employees = employee.GetAll();
foreach (var item in employees)
{
Console.WriteLine(item.Name);
}
IService<Company> company = new CompanyService();
List<Company> companies = company.GetAll();
foreach (var item in companies)
{
Console.WriteLine(item.Name);
}
Console.ReadLine();
}
hope this helps!
I think you would have to use Aspect Oriented Programming to achieve that. Read http://www.sharpcrafters.com/aop.net
I think you meant class (instead of interface)
Two options I can think of:
Implementing INotifyPropertyChanged which is in lines of writing code in every method
or
to adopt on of the AOP frameworks in the article http://www.codeproject.com/KB/cs/AOP_Frameworks_Rating.aspx if that is not a major leap

MVMLight Messaging and Silverlight

I am trying to get a sample to work using MVVM Light and the Messaging Class. In the sample, I have a test project created from the MVVM Template for Silveright 4. I have added a button on the main page. When the button is clicked, it updates a property on the ViewModel. When the property is updated, I want to show a messagebox with the new value.
The key line of code is:
Messenger.Default.Register(this, new Action(ShowMessage));
I can get this to work in WPF, but not silverlight. It should call ShowMessage with the string parameter when the property changes, but it does not. If I use:
Messenger.Default.Send("Hello MVVM");
This works and the string is sent as a message to ShowMessage.
However, the message does not get sent if the property changes, even though the property was created with the MVVMINPC snippet and has the following line:
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
This should have the same effect as Messager.Default.Send but it seems to be ignored. ThePropertyChangedEvent is indeed raised, but the messanger part seems to be disconnected.
Am I doing something wrong? Here is the full MainViewModel:
public class MainViewModel : ViewModelBase
{
public RelayCommand MyRelayCommand { get; set; }
public const string MyPropertyPropertyName = "MyProperty";
private string _myProperty = "test";
public string MyProperty
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
var oldValue = _myProperty;
_myProperty = value;
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
}
}
public void DoSomething()
{
//Messenger.Default.Send("Hello MVVM"); //Works
this.MyProperty = "Hello World"; //Doesn't work.
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Messenger.Default.Register(this, new Action<string>(ShowMessage));
MyRelayCommand = new RelayCommand(new Action(DoSomething));
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainViewModel_PropertyChanged);
}
void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MessageBox.Show(e.PropertyName);
}
}public class MainViewModel : ViewModelBase
{
public RelayCommand MyRelayCommand { get; set; }
public const string MyPropertyPropertyName = "MyProperty";
private string _myProperty = "test";
public string MyProperty
{
get
{
return _myProperty;
}
set
{
if (_myProperty == value)
{
return;
}
var oldValue = _myProperty;
_myProperty = value;
RaisePropertyChanged(MyPropertyPropertyName, oldValue, value, true);
}
}
public void DoSomething()
{
//Messenger.Default.Send("Hello MVVM"); //Works
this.MyProperty = "Hello World"; //Doesn't work.
}
public void ShowMessage(string message)
{
MessageBox.Show(message);
}
/// <summary>
/// Initializes a new instance of the MainViewModel class.
/// </summary>
public MainViewModel()
{
Messenger.Default.Register(this, new Action<string>(ShowMessage));
MyRelayCommand = new RelayCommand(new Action(DoSomething));
this.PropertyChanged += new System.ComponentModel.PropertyChangedEventHandler(MainViewModel_PropertyChanged);
}
void MainViewModel_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e)
{
MessageBox.Show(e.PropertyName);
}
}v
OK, I found that the Register line should look like this:
Messenger.Default.Register(this, new Action<PropertyChangedMessage<string>>(ShowMessage));
The point being there are different types of messages, and you have to register the PropertyChangedMessage type to recieve property changed messages.
Then also, the Action that recieves the message needs to take the correct parameter, like this:
public void ShowMessage(PropertyChangedMessage<string> e)
{
MessageBox.Show(e.NewValue.ToString());
}

Retrieving Custom Attribute on a web page class (.net)

I've create a custom attribute for my web pages... In the base page class I've created I'm trying to pull if that attribute has been set. Unfortunately it does not come back as part of the GetCustomAttributes function. Only if I explicitly use the typeof(myclass) to create the class. I have a feeling it's due to how asp.net classes are generated. Anyone have any suggestions on how to get this to work?
namespace SecuritySample.SecurityCode
{
[AttributeUsage(AttributeTargets.All, Inherited = false, AllowMultiple = true)]
public sealed class MHCSecurityAttribute : Attribute
{
private string _permissionSet;
private bool _viewable;
public MHCSecurityAttribute(string permission, bool viewable)
{
_permissionSet = permission;
_viewable = viewable;
}
public string PermissionSetRequired
{
get { return _permissionSet; }
}
public bool Viewable
{
get { return _viewable; }
}
}
}
AdminOnly class
using System;
using SecuritySample.SecurityCode;
namespace SecuritySample
{
[MHCSecurityAttribute("testpermission", false)]
public partial class AdminOnlyPage : BasePage, IMHCSecurityControl
{
protected void Page_Load(object sender, EventArgs e)
{
}
public void DisableControl()
{
Server.Transfer("Error.aspx");
}
public void EnableControl()
{
}
}
}
BasePage class
using System.Web.UI.WebControls;
namespace SecuritySample.SecurityCode
{
public class BasePage : Page
{
private string _user;
protected override void OnLoadComplete(EventArgs e)
{
base.OnLoadComplete(e);
_user = string.Empty;
if (Session.Contents["loggedInUser"] != null)
_user = Session["loggedInUser"].ToString();
// perform security check
// check page level
if (this is IMHCSecurityControl)
{
System.Reflection.MemberInfo info = this.GetType();
object[] attributes = info.GetCustomAttributes(false);
bool authorized = false;
if ((attributes != null) && (attributes.Length > 0))
{
foreach(MHCSecurityAttribute a in attributes)
{
if ((MHCSecurityCheck.IsAuthorized(_user, a.PermissionSetRequired)))
{
((IMHCSecurityControl) this).EnableControl();
authorized = true;
break;
}
}
if (!authorized)
((IMHCSecurityControl)this).DisableControl();
}
}
}
}
}
You have set the AttributeUsage.Inherited member to false. When set to false the attribute is not inherited by classes that inherit from your class (which is how Pages/Controls work in ASP.NET). This is why when you explicitly use typeof(your class name) the attribute is found.

Resources