473,387 Members | 1,621 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

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.Collections;
using System.Collections.Specialized;
using System.Web;
using System.Reflection;
using PJC.PitchBook;
using PJC.PitchBook.Classes;
using PJC.PitchBook.Data;
using PJC.PitchBook.Web.UI.Ajax;

namespace PJC.PitchBook.Web.HttpHandlers {

public class ServerMethod:IHttpHandler {
HttpContext _context;

HttpRequest Request {
get {return _context.Request;}
}
HttpResponse Response {
get {return _context.Response;}
}
HttpContext Context {
get {return _context;}
set {_context = value;}
}
public void ProcessRequest(HttpContext context) {
Context = context;
NameValueCollection qs = Request.QueryString;
AJAXHandlerRequestStruct _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 AJAXHandlerRequestStruct();
_values.Args = new ArrayList();
_values.Method=qs[0]; //Function name here
for (i=1;i<countParams;i++) _values.Args.Add(qs[qs.GetKey(i)]);
//If any parameters, pick them up here
} else {
serverResponse(204);
return;
}

MethodInfo[] myMethods =
Assembly.GetExecutingAssembly().GetType("PJC.Pitch Book.Web.HttpHandlers.ServerMethod").GetMethods();
MethodInfo theMethod;

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

//Convert argument value to type specified by parameterInfo
object
for (j=0;j<paramCount;j++) args[j] =
Convert.ChangeType(_values.Args[j],_params[j].ParameterType);
Type RTYPE = theMethod.ReturnType;
object myResult = theMethod.Invoke(this,args);

// Test to see if return type implements interface
if (RTYPE.GetInterface("ToAJAX",false) != null) {
serverResponse(myResult.ToAJAX(true));
} else {
string[] myVals = new string[2];
myVals[0] = myResult.ToString();
myVals[1] = string.Empty;
serverResponse(new AJAXHandlerResponseStruct(myVals));
}

} catch (Exception) {
serverResponse(204);
break;
}
break;
}
serverResponse(204);
break;
}
return;
}
private void serverResponse (AJAXHandlerResponseStruct response) {
Response.StatusCode = 200;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/html";
Response.AppendHeader("X-JSON", response.JSON);
Response.AppendHeader("Content-Length",
response.HTML.Length.ToString());
Response.Write(response.HTML);
Response.Flush();
Response.Close();
}
private void serverResponse (int responseCode) {
Response.StatusCode = responseCode;
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.ContentType = "text/html";
Response.AppendHeader("X-JSON", "null");
Response.AppendHeader("Content-Length", "0");
Response.Write(string.Empty);
Response.Flush();
Response.Close();
}
public bool IsReusable {
get { return true; }
}

#region Server Methods
public PJC.PitchBook.Web.UI.Ajax.PJCSectionCollection
getSectionCollection() {
return new PJC.PitchBook.Web.UI.Ajax.PJCSectionCollection();
}
// public AJAXHandlerResponseStruct
getFilteredSectionCollection(UserLevel DisplayLevel, int UserID) {
// return new
PJC.PitchBook.Web.UI.Ajax.PJCSectionCollection(Dis playLevel,
UserID).Items;
// }
// public AJAXHandlerResponseStruct
getSearchResultsSectionCollection(UserLevel DisplayLevel, int UserID,
string SearchString) {
// return new
PJC.PitchBook.Web.UI.Ajax.PJCSectionCollection(Dis playLevel, UserID,
SearchString).Items;
// }
// public AJAXHandlerResponseStruct Expand(int id) {
// return new PJC.PitchBook.Web.UI.Ajax.PJCSection(id).Items;
// }
// public AJAXHandlerResponseStruct getCanvasCollection(int
CollectionID) {
// return new
PJC.PitchBook.Web.UI.Ajax.PJCCollection(Collection ID).Items;
// }
// public AJAXHandlerResponseStruct CollectionHasVariables(int
CollectionID) {
// PJCUser theUser = (PJCUser)Context.Session["User"];
// PJC.PitchBook.Data.PJCCollectionData _data = new
PJC.PitchBook.Data.PJCCollectionData(CollectionID) ;
// return (_data.PageVariableIDs.Count > 0 & theUser.UserID != 0);
// }
#endregion
}
}

Sorry about the crappy formatting.

-Tony

Feb 6 '06 #1
4 1987
> 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.Invoke in your
snippet), only the runtime-type matters. If you want to call the
interface methods, use Activator.CreateInstance 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...This isn't the
intent.
Type RTYPE = theMethod.ReturnType;
if (RTYPE.GetInterface("IAJAXResponse",false) != null) {

serverResponse(((IAJAXResponse)Activator.CreateIns tance(RTYPE,args)).ToAJAX(true));
} else {...}

//Would this work?
Type RTYPE = theMethod.ReturnType;
object myResult = theMethod.Invoke(this,args);
// Test to see if return type implements interface
if (RTYPE.GetInterface("IAJAXResponse",false) != null) {
serverResponse(((IAJAXResponse)myResult).ToAJAX(tr ue));
} 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).ToAJAX(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("ToAJAX", BindingFlags.InvokeMethod, 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
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...
2
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...
3
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
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...
13
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...
14
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
by: recover | last post by:
#include <string> #include <iostream> using namespace std; class TConst { private: string con; string uncon; public:
3
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...
0
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...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
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,...
0
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...
0
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,...

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.