473,573 Members | 2,462 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 2002
> 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
1994
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
1652
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
2550
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
2672
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...
13
7395
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
3196
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
2093
by: recover | last post by:
#include <string> #include <iostream> using namespace std; class TConst { private: string con; string uncon; public:
3
5262
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...
0
3046
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...
0
7747
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main...
0
7670
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...
0
7987
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. ...
0
8180
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that...
1
7740
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...
1
5557
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...
0
5263
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert...
0
3706
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...
0
1005
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...

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.