I have a following code
public void ShowForm(String EName, String phoneNumber, String dnis, String mode, String callid)
{
objCallParams.EventName = EName;
objCallParams.ANI = phoneNumber;
objCallParams.DNIS = dnis;
objCallParams.Mode = mode;
objCallParams.CallId = callid;
UIThreadContext.Post(InComing_Callback, (object)objCallParams);
}
private void InComing_Callback(object objCallParams)
{
/*want to access phone number i.e.objCallParams.ANI*/
}
How do I access phoneNumber in InComing_Callback(object objCallParams) method?
If you know the type of the object you can use casting
private void InComing_Callback(object objCallParams)
{
// If you know that objCallParams will always be of the type FormParameters:
var params = (FormParameters)objCallParams;
// if you are not so sure about that
var notSoSureParams = objCallParams as FormParameters;
if (notSoSureParams != null)
{
}
}
Related
I'm trying to dynamically build set objects based on a user input document. For some reason SetValue is throwing Object does not match target type, despite that it does.
Is what im trying to achieve even possible?
private void MapProp(string prop, string invalue)
{
var currType = _userAssembly.GetType(_className);
var property = currType.GetProperty(prop, BindingFlags.Public | BindingFlags.Instance);
var value = Convert.ChangeType(invalue, property.PropertyType);
property.SetValue(styleType, value, null);
}
}
Currently its attempting to map to said object:
public class TestObject: ITestObj
{
public string PropertyA {get;set;}
public string PropertyB {get;set;}
}
Calling Code
MapProp("PropertyA", "testValue");
and the getType classname = .Assembly.TestObject
#user4550364 ,I dont know what does your _user assembly does ,so I am gonna put my sample code ,this might help you to adapt the idea to your code.This is also an example of late binding.
Class file
public class TestObject: ITestObj
{
public string PropertyA {get;set;}
public string PropertyB {get;set;}
void Print(string PropertyA,string PropertyB)
{
//Assuming that interface ITestObj has this method definition and hence implementing here.
}
}
Main code
using System.Reflection;
static void Main(string[] args)
{
Assembly executingassembly = Assembly.GetExecutingAssembly();
Type TestObjecttype = executingassembly.GetType("ur_namespace.TestObject");
object instance = Activator.CreateInstance(TestObjecttype );
string[] parameters = new string[2];
parameters[0] = "PropertyA ";
parameters[1] = "PropertyB ";
//To get properties
PropertyInfo[] properties = TestObjecttype .GetProperties();
foreach (PropertyInfo property in properties)
{
Console.WriteLine(property.PropertyType.Name+" "+property.Name);
}
MethodInfo method = customertype.GetMethod("Print");
//Object created ,now invoke using its instance
string printMethodInvoked= (string)method.Invoke(instance, parameters);
Console.WriteLine(printMethodInvoked);
Console.Read();
}
}
I have a Place data_object in the service side which contains a navigation property Roads:
public class Place : EntityData
{
...
public List<Road> Roads { get; set; }
}
And now on the client side, I want to get a Place object using its id, but the navigation property Roads just won't load. Is there any parameter or attribute I can add to make it work?
My code for it:
var roadList = await App.MobileService.GetTable<Place>()
.LookupAsync(placeId);
Since loading navigation properties in EF requires a JOIN operation in the database (which is expensive), by default they are not loaded, as you noticed. If you want them to be loaded, you need to request that from the client, by sending the $expand=<propertyName> query string parameter.
There are two ways of implementing this: in the server and in the client. If you want to do that in the server, you can implement an action filter which will modify the client request and add that query string parameter. You can do that by using the filter below:
[AttributeUsage(AttributeTargets.Method, AllowMultiple = true)]
class ExpandPropertyAttribute : ActionFilterAttribute
{
string propertyName;
public ExpandPropertyAttribute(string propertyName)
{
this.propertyName = propertyName;
}
public override void OnActionExecuting(HttpActionContext actionContext)
{
base.OnActionExecuting(actionContext);
var uriBuilder = new UriBuilder(actionContext.Request.RequestUri);
var queryParams = uriBuilder.Query.TrimStart('?').Split(new[] { '&' }, StringSplitOptions.RemoveEmptyEntries).ToList();
int expandIndex = -1;
for (var i = 0; i < queryParams.Count; i++)
{
if (queryParams[i].StartsWith("$expand", StringComparison.Ordinal))
{
expandIndex = i;
break;
}
}
if (expandIndex < 0)
{
queryParams.Add("$expand=" + this.propertyName);
}
else
{
queryParams[expandIndex] = queryParams[expandIndex] + "," + propertyName;
}
uriBuilder.Query = string.Join("&", queryParams);
actionContext.Request.RequestUri = uriBuilder.Uri;
}
}
And then you can decorate your method with that attribute:
[ExpandProperty("Roads")]
public SingleItem<Place> GetPlace(string id) {
return base.Lookup(id);
}
Another way to implement this is to change the client-side code to send that header. Currently the overload of LookupAsync (and all other CRUD operations) that takes additional query string parameters cannot be used to add the $expand parameter (or any other $-* parameter), so you need to use a handler for that. For example, this is one such a handler:
class MyExpandPropertyHandler : DelegatingHandler
{
string tableName
string propertyName;
public MyExpandPropertyHandler(string tableName, string propertyName)
{
this.tableName = tableName;
this.propertyName = propertyName;
}
protected override async Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
if (request.Method.Method == HttpMethod.Get.Method &&
request.RequestUri.PathAndQuery.StartsWith("/tables/" + tableName, StringComparison.OrdinalIgnoreCase))
{
UriBuilder builder = new UriBuilder(request.RequestUri);
string query = builder.Query;
if (!query.Contains("$expand"))
{
if (string.IsNullOrEmpty(query))
{
query = "";
}
else
{
query = query + "&";
}
query = query + "$expand=" + propertyName;
builder.Query = query.TrimStart('?');
request.RequestUri = builder.Uri;
}
}
return await base.SendAsync(request, cancellationToken);
return result;
}
}
And you'd use the handler by creating a new instance of MobileServiceClient:
var expandedClient = new MobileServiceClient(
App.MobileService.ApplicationUrl,
App.MobileService.ApplicationKey,
new MyExpandPropertyHandler("Place", "Roads"));
var roadList = await App.MobileService.GetTable<Place>()
.LookupAsync(placeId);
Hi I have to different classes with Same properties and I want to access the peoperties of my classes Dynamically.
public Class1
{
public const prop1="Some";
}
public Class2
{
public const prop1="Some";
}
And in my code I am getting my class name like this
string classname="Session["myclass"].ToString();";//Say I have Class1 now.
And I want to get the prop1 value .
Something like
string mypropvalue=classname+".prop1";//my expected result is Some
///
Type typ=Type.GetType(classname);
Please help me in getting this
Reflection
var nameOfProperty = "prop1";
var propertyInfo = Class1Object.GetType().GetProperty(nameOfProperty);
var value = propertyInfo.GetValue(myObject, null);
for static:
var nameOfProperty = "prop1";
var propertyInfo = typeof(Class1).GetProperty("prop1", BindingFlags.Static);
var value = propertyInfo.GetValue(myObject, null);
Class reference from string
EDIT (I made example):
class Program
{
static void Main(string[] args)
{
var list = Assembly.Load("ConsoleApplication4").GetTypes().ToList();
Type ty = Type.GetType(list.FirstOrDefault(t => t.Name == "Foo").ToString());
//This works too: Type ty = Type.GetType("ConsoleApplication4.Foo");
var prop1
= ty.GetProperty("Temp", BindingFlags.Static | BindingFlags.Public);
Console.WriteLine(prop1.GetValue(ty.Name, null));
Console.ReadLine();
}
}
public static class Foo
{
private static string a = "hello world";
public static string Temp
{
get
{
return a;
}
}
}
Msdn
you can use following function to get a property value fron an object dynamically:
just pass object to scan & property name
public static object GetPropValue(object src, string propName)
{
return src.GetType().GetProperty(propName).GetValue(src, null);
}
I'm trying to read an object ChatMassage from the stream and to print a message (which this object contains) with its method getMassage(). It prints a message the first time but next time it always prints the first message. What is wrong?
Here is an example of the code:
while(keepGoing){
System.out.println("Client: " + ((ChatMassage) in.readObject()).getMassage() + "\n" );
}
ChatMassage class:
public class ChatMassage implements Serializable {
String msg, recipientName = null;
String senderName = "None";
public void setMassage(String msg) {
this.msg = msg;
}
public void setRecipientName(String recName) {
recipientName = recName;
}
public String getMassage() {
return msg;
}
public String getRecipientName() {
return recipientName;
}
public void setSenderName(String name) {
senderName = name;
}
public String getSenderName() {
return senderName;
}
}
I think the problem lies in this method:
public void setMassage(String msg) {
this.msg = msg;
}
I don't know if that can be a problem, but try changing the parameter to something like "new_msg". I think it confuses the "this.msg" with "msg".
JS Code.
// this is person class constructor.
function personClass(id, name, address, phone) {
this.Id = id;
this.Name = name;
this.Address = address;
this.Phone = phone;
}
var person = new Array();
person.push(new personClass("101", $('#txtName').val(), $('#txtAddress').val(), $('#txtPhone').val());
AjaxRequest = function ("PersonInfo.asmx/AddNewPerson", "{'person[]':'" + JSON.stringify(person) + "'}", successcallback, errorcallback) {
$.ajax({
type: "POST",
url: url,
data: param,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: successcallback,
error: errorcallback
});
}
C# Code.
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public string AddProduct(Person[] person)
{
return person[0].Id;
}
public class Person
{
private string _id = String.Empty;
private string Id
{
get { return _id; }
set { _id = value; }
}
private string _name = String.Empty;
private string Name
{
get { return _name; }
set { _name = value; }
}
private string _address = String.Empty;
private string Address
{
get { return _address; }
set { _address = value; }
}
private string _phone = String.Empty;
private string Id
{
get { return _phone; }
set { _phone = value; }
}
}
Problem is that : show response error message following -:
{"Message":"Invalid web service call,
missing value for parameter:
\u0027person\u0027.","StackTrace":" at
System.Web.Script.Services.WebServiceMethodData.CallMethod(Object
target, IDictionary2 parameters)\r\n
at
System.Web.Script.Services.WebServiceMethodData.CallMethodFromRawParams(Object
target, IDictionary2 parameters)\r\n
at
System.Web.Script.Services.RestHandler.InvokeMethod(HttpContext
context, WebServiceMethodData
methodData, IDictionary`2
rawParams)\r\n at
System.Web.Script.Services.RestHandler.ExecuteWebServiceCall(HttpContext
context, WebServiceMethodData
methodData)","ExceptionType":"System.InvalidOperationException"}
Please suggest the solution.
Try:
"{'person':" + JSON.stringify(person) + "}"
It differs from your code in two places:
person instead of person[]
No quotes around person object