473,671 Members | 2,592 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Invoke member of Userdefined Type

Hello all,

I'm hoping that someone could help me with this bit of code. I am
using reflection to dynamically call a method within an HttpHandler.
When a method returns a user defined type that implements a certain
interface, I want to call that interfaces method. The problem is that
the local varaible holding the user defined type is declared an object.
The compiler will accept the invocation of the interface method on that
object. I have a feeling that I may be getting over my head a little
bit on this one. Any hekp would be greatly appreciated. Code follows:

using System;
using System.Collecti ons;
using System.Collecti ons.Specialized ;
using System.Web;
using System.Reflecti on;
using PJC.PitchBook;
using PJC.PitchBook.C lasses;
using PJC.PitchBook.D ata;
using PJC.PitchBook.W eb.UI.Ajax;

namespace PJC.PitchBook.W eb.HttpHandlers {

public class ServerMethod:IH ttpHandler {
HttpContext _context;

HttpRequest Request {
get {return _context.Reques t;}
}
HttpResponse Response {
get {return _context.Respon se;}
}
HttpContext Context {
get {return _context;}
set {_context = value;}
}
public void ProcessRequest( HttpContext context) {
Context = context;
NameValueCollec tion qs = Request.QuerySt ring;
AJAXHandlerRequ estStruct _values;
int i,j;
int countParams=qs. Count-1; //Will use this number later
if (countParams > -1) { //Meaning there is at least 1 (function
name) at qs[0]
_values = new AJAXHandlerRequ estStruct();
_values.Args = new ArrayList();
_values.Method= qs[0]; //Function name here
for (i=1;i<countPar ams;i++) _values.Args.Ad d(qs[qs.GetKey(i)]);
//If any parameters, pick them up here
} else {
serverResponse( 204);
return;
}

MethodInfo[] myMethods =
Assembly.GetExe cutingAssembly( ).GetType("PJC. PitchBook.Web.H ttpHandlers.Ser verMethod").Get Methods();
MethodInfo theMethod;

//Get the method that matches in name and number of parameters
for (i=0;i<myMethod s.Length;i++) {
if ((myMethods[i].Name==_values. Method) &&
(myMethods[i].GetParameters( ).Length==count Params)) { //This is it!
theMethod=myMet hods[i];
Object[] args;
try {
ParameterInfo[] _params = theMethod.GetPa rameters();
int paramCount = _params.Length;
args = new Object[paramCount];

//Convert argument value to type specified by parameterInfo
object
for (j=0;j<paramCou nt;j++) args[j] =
Convert.ChangeT ype(_values.Arg s[j],_params[j].ParameterType) ;
Type RTYPE = theMethod.Retur nType;
object myResult = theMethod.Invok e(this,args);

// Test to see if return type implements interface
if (RTYPE.GetInter face("ToAJAX",f alse) != null) {
serverResponse( myResult.ToAJAX (true));
} else {
string[] myVals = new string[2];
myVals[0] = myResult.ToStri ng();
myVals[1] = string.Empty;
serverResponse( new AJAXHandlerResp onseStruct(myVa ls));
}

} catch (Exception) {
serverResponse( 204);
break;
}
break;
}
serverResponse( 204);
break;
}
return;
}
private void serverResponse (AJAXHandlerRes ponseStruct response) {
Response.Status Code = 200;
Response.Conten tEncoding = System.Text.Enc oding.UTF8;
Response.Conten tType = "text/html";
Response.Append Header("X-JSON", response.JSON);
Response.Append Header("Content-Length",
response.HTML.L ength.ToString( ));
Response.Write( response.HTML);
Response.Flush( );
Response.Close( );
}
private void serverResponse (int responseCode) {
Response.Status Code = responseCode;
Response.Conten tEncoding = System.Text.Enc oding.UTF8;
Response.Conten tType = "text/html";
Response.Append Header("X-JSON", "null");
Response.Append Header("Content-Length", "0");
Response.Write( string.Empty);
Response.Flush( );
Response.Close( );
}
public bool IsReusable {
get { return true; }
}

#region Server Methods
public PJC.PitchBook.W eb.UI.Ajax.PJCS ectionCollectio n
getSectionColle ction() {
return new PJC.PitchBook.W eb.UI.Ajax.PJCS ectionCollectio n();
}
// public AJAXHandlerResp onseStruct
getFilteredSect ionCollection(U serLevel DisplayLevel, int UserID) {
// return new
PJC.PitchBook.W eb.UI.Ajax.PJCS ectionCollectio n(DisplayLevel,
UserID).Items;
// }
// public AJAXHandlerResp onseStruct
getSearchResult sSectionCollect ion(UserLevel DisplayLevel, int UserID,
string SearchString) {
// return new
PJC.PitchBook.W eb.UI.Ajax.PJCS ectionCollectio n(DisplayLevel, UserID,
SearchString).I tems;
// }
// public AJAXHandlerResp onseStruct Expand(int id) {
// return new PJC.PitchBook.W eb.UI.Ajax.PJCS ection(id).Item s;
// }
// public AJAXHandlerResp onseStruct getCanvasCollec tion(int
CollectionID) {
// return new
PJC.PitchBook.W eb.UI.Ajax.PJCC ollection(Colle ctionID).Items;
// }
// public AJAXHandlerResp onseStruct CollectionHasVa riables(int
CollectionID) {
// PJCUser theUser = (PJCUser)Contex t.Session["User"];
// PJC.PitchBook.D ata.PJCCollecti onData _data = new
PJC.PitchBook.D ata.PJCCollecti onData(Collecti onID);
// return (_data.PageVari ableIDs.Count > 0 & theUser.UserID != 0);
// }
#endregion
}
}

Sorry about the crappy formatting.

-Tony

Feb 6 '06 #1
4 2003
> When a method returns a user defined type that implements a certain
interface, I want to call that interfaces method.The problem is that
the local varaible holding the user defined type is declared an object.
The compiler will accept the invocation of the interface method on that
object.

When you call the method using reflection (MethodInfo.Inv oke in your
snippet), only the runtime-type matters. If you want to call the
interface methods, use Activator.Creat eInstance then cast the return
value to that interface.

Hope that helps,
Thi

Feb 7 '06 #2
Thanks for the quick reply. Let me get this straight. If I can
determine the return type implements an interface, I can cast the
returned instance to the interface type, then call the interfaces
methods? I am sorry, I'm not at work and I see there are some errors in
the snippet I posted. Upen further review:

//This just creates an instance of the ReturnType of the method, using
the args[] for the method in the class contructor...Th is isn't the
intent.
Type RTYPE = theMethod.Retur nType;
if (RTYPE.GetInter face("IAJAXResp onse",false) != null) {

serverResponse( ((IAJAXResponse )Activator.Crea teInstance(RTYP E,args)).ToAJAX (true));
} else {...}

//Would this work?
Type RTYPE = theMethod.Retur nType;
object myResult = theMethod.Invok e(this,args);
// Test to see if return type implements interface
if (RTYPE.GetInter face("IAJAXResp onse",false) != null) {
serverResponse( ((IAJAXResponse )myResult).ToAJ AX(true));
} else {...}

-Tony

Feb 7 '06 #3
In this case, the call of CreateInstance is not necessary because you
already had the instance. So you could simply cast myResult to the
interface and call its ToAJAX method:
if (myResult is IAJAXResponse)
serverResponse( ((IAJAXResponse ) myResult).ToAJA X(true));

That requires IJAXResponse to be known at compile time (that is, you
added a reference to it the DLL containing it). Otherwise, you could
call:
RTYPE.Invoke("T oAJAX", BindingFlags.In vokeMethod, null, myResult, new
object[] {true});

Thi

Feb 7 '06 #4
That worked perfectly and makes sense now. Thanks Thi.

-Tony

Feb 7 '06 #5

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

10
2008
by: Charles Law | last post by:
I have a user control created on the main thread. Let's say, for arguments sake, that it has a single property that maintains a private variable. If I want to set that property from a worker thread, do I need to use UserControl1.Invoke to set it, or can I just set it? After all, it is only changing a private variable. TIA Charles
2
1656
by: parez | last post by:
Hi All! This is the first time i am tryin to write a sql server 2000 function. I need to clean up some of my stored procedures.. Can any one please give me skeleton for a userdefined function or correct my function. I get the following error. Select statements included within a function cannot return data to a client.
3
2554
by: Daniel Lidström | last post by:
Hello, I want to have a class that contains only a collection of another class. For example: public __gc class Alignment { public: Alignment(); ... };
2
2676
by: Tom | last post by:
Hi Everybod I want to update some controls in a form from another threads. I did it by passing the form to that thread and calling a delegate with Form1.Invoke, I want to have just one delegeate for all of my controls in the Form and dont define one delegate for each control. Some thing like to have a switch case in that delegate fucntion and passing control name to it.. what is the impact of this method in comparison with...
13
7413
by: Christian Westerlund | last post by:
Hi! I'm trying to use P/Invoke and a Method which takes an IntPtr where I am supposed to put an address to a method which the native method will use to communicate back to me. How do I convert a method to an IntPtr? / Christian
14
3201
by: gurry | last post by:
Suppose there's a class A. There's another class called B which looks like this: class B { private: A a; public : B() { a.~A() } }
16
2108
by: recover | last post by:
#include <string> #include <iostream> using namespace std; class TConst { private: string con; string uncon; public:
3
5267
by: =?Utf-8?B?Sm9l?= | last post by:
I know that I have posted this question before, but it is still unresolved and I don't know where to turn to next. I have code that is creating a user (works fine), then sets the account flags (works fine) and then sets the password (fails). Here is the pertinent information: Ex.InnerException.Message: Logon failure: unknown user name or bad password. Ex.Message: Exception has been thrown by the target of an invocation.
0
3048
by: =?Utf-8?B?a3Jpc2huYQ==?= | last post by:
Hi i am getting the following error while using XMLSerializer XmlSerializer ser = new XmlSerializer(typeof(Person)); ERROR: Unable to generate a temporary class (result=1). error CS0266: Cannot implicitly convert type 'XSD.BiodataGender?' to 'XSD.BiodataRace?'. An explicit conversion exists (are you missing a cast?) I am getting the above error when my xsd has multiple nillable elements of userdefined type. If I change the type of...
0
8402
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8927
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8605
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8676
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
7445
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own.... Now, this would greatly impact the work of software developers. The idea...
1
6237
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
4227
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4416
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
1816
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.