How to read custom data type - c#

I was created this return from WCF and may i know how could i read the data specifically ??
[DataContract]
public class UserData
{
[DataMember]
public int userID { get; set; }
[DataMember]
public string name { get; set; }
[DataMember]
public string email { get; set; }
[DataMember]
public string contact { get; set; }
[DataMember]
public string status { get; set; }
}
This is WCF side and returning from WCF, i want to read this from Window phone. may i know is there some example ? Thank you for reply
Update
The code in phone part where i want to use the data
private Service1Client _serviceClient;
public Login()
{
InitializeComponent();
_serviceClient = new Service1Client();
_serviceClient.LoginUserCompleted += new EventHandler<LoginUserCompletedEventArgs>(_serviceClient_LoginUserCompleted);
}
private void loginBtn_Click(object sender, RoutedEventArgs e)
{
_serviceClient.LoginUserAsync(txtEmail.Text, txtPassword.Password);
}
private void _serviceClient_LoginUserCompleted(object sender, LoginUserCompletedEventArgs e)
{
if (e.Error == null && e.Result != null)
{
(App.Current as App).MyUserID = 16;
MessageBox.Show("Welcome " + e.Result + "!");
//ContentPanel.Visibility = Visibility.Collapsed;
//Data.Visibility = Visibility.Visible;
//Testing.ItemsSource = e.Result;
Wondering how could i make this few line of code to read the data accordingly, make it into list or can be extract specific data and currently this few lines of codes giving me this answer ::
WCFReference.UserData
}
else
{
MessageBox.Show(e.Error.InnerException.Message + " Couldn't Login, Please try again =D");
}
}

If you are using the SOAP protocol you could either build an WSDL to describe the webservice or you could create the custom class right on the client based on your knowledge of the webservice.
If you are using the REST protocol (Which would be the best alternative for an WP7 Application) you have to create the class on the client based on your knowledge because there are no such thing as WSDL that can describe an REST webservice.
Here is an start for you.
public class UserData
{
public int userID { get; set; }
public string name { get; set; }
public string email { get; set; }
public string contact { get; set; }
public string status { get; set; }
}
Now you just have to parse the response from the webservice request as an UserData class and whoala you are all set.
And as some people pointed out, you can use the webservice as an service reference if you prefer that but sometimes it just messes things up.

You can consume exposed web services by creating service reference (proxy).
Check out following URLs
BLOG
POST
MSDN
LINK

Related

how to pass a object which contains List<object> to web service method in C#?

I want to pass one JBSearchRequest object which contains List<JBCredential> to my asp.net web service. I am able to call this web service from SOAP UI and some other tools but when I'm trying to send request from my C# client code is giving problem.
My Web service class is
public List<JBCredential> JBCredentials{ get; set; }
public string codes { get; set; }
public string db { get; set; }
public string locale { get; set; }
public string location { get; set; }
public string mode { get; set; }
public string postcode { get; set; }
I've tried the following
test.JBSearchRequest s = new test.JBSearchRequest();
test.JBCredential jb = new test.JBCredential();
jb.code = "LNK";
jb.Username = "";
jb.Password = "";
/
s.query = "java";
s.mode = "mock_search";
s.JBCredentials.Add(jb);//I'm not getting add method
so I've tried like this
s.JBCredentials[0].code = jb.code;
s.JBCredentials[0].Password = jb.Password;
s.JBCredentials[0].Username = jb.Username;
and also I tried
List<JBCredential> ad=new List<JBCredential>();
ad.Add(jb);
s.JBCredentials=ad;
Please help me how to pass object which contains list when we are consuming web service.

JSON ASP.NET Deserialization failing, getting null

From Javascript I send my object via string like so, data is what facebook FQL query returns:
var propData = new Object();
propData.d = data;
var jString = JSON.stringify(propData);
$('#<%=Hidden1.ClientID%>').val(jString);
$('#UpdatePanelTrigger').click();
Then, I receive this string on server side, display this JSON string in a label (which looks ok to me) and try to Deserialize it, code below.
public class Friends
{
public IList<Dictionary<string,string>> data {get; set;}
}
protected void UpdateTrigger_Click(object sender, EventArgs e)
{
JSON_out.Text = Hidden1.Value;
Friends fbookFriends = new System.Web.Script.Serialization.JavaScriptDerializer().Deserialize<Friends>(JSON_out.Text);
obj_check.Text = new System.Web.Script.Serialization.JavaScriptSErializer().Serialize(fbookFriends);
//The result of above line is {"data":null}
}
I don't understand why Deserializer refuses to convert this string to JSON.
Any help, would be greatly appreciated.
I.N.
PS: If it helps, My JSON string received on server, looks like this:
{"d":[{"uid":"XXXXXXXX","name":"Bro Number1","pic_square":"https://fbcdn-profile-a.akamaihd.net/beautiful_avatar.jpg"},{"uid":"XXXXX2","name":...
To be able to deserialize your json string in question your Friends class should be something like that
public class Friend
{
public string uid { get; set; }
public string name { get; set; }
public string pic_square { get; set; }
}
public class Friends
{
public List<Friend> d { get; set; }
}
But your comments says you have some top level fields like data (//The result of above line is {"data":null})

Web Service Exception: "The formatter threw an exception while trying to deserialise the message"

Got a question. I get this error and I know it is due to the fact that int32 has a number limit of 2147483647. But I don't know why I am getting this error when the value in question (a telephone number of 11 digits) is defined as a string in our SQL database, a string in our web service and a string in our web application.
I assume it is something to do with the way the service serialises and deserialises data over a connection, but I was wanting to know if there is a way to force Number to use only the string instead of parsing it when deserialisation happens. Or even get it to parse as int64.
Here is the error exception. I removed the namespace and service name. It is the property Number that is causing the problem.
There was an error deserializing the object of type .".ClientPhone[]. The value '07721545554' cannot be parsed as the type 'Int32'."
And here is the code for the service and the service interface.
[DataContract]
public class ClientPhone
{
[DataMember]
public int? ClientNumberID { get; set; }
[DataMember]
public int? RefID { get; set; }
[DataMember]
public string Number { get; set; }
[DataMember]
public string NumberType { get; set; }
[DataMember]
public bool? PrimaryNumber { get; set; }
}
public partial class ClientNumberEntity
{
public int ClientNumbersID { get; set; }
public Nullable<int> RefID { get; set; }
public string ClientNumberType { get; set; }
public string ClientNumber { get; set; }
public Nullable<bool> PrimaryNumber { get; set; }
public virtual ClientDataEntity ClientData { get; set; }
}
public List<ClientPhone> GetClientsPhoneByReference(int _reference)
{
OurDatabaseEntities context = new OurDatabaseEntities();
var phoneEntity = (from c in context.ClientNumberEntities
where c.RefID == _reference
select c).ToList();
if (phoneEntity != null)
{
return TranslateClientPhoneEntityToPhoneNumberList(phoneEntity);
}
else
throw new Exception("Unable to get phone data");
}
private List<ClientPhone> TranslateClientPhoneEntityToPhoneNumberList(List<ClientNumberEntity> numberEntities)
{
List<ClientPhone> phoneList = new List<ClientPhone>();
foreach (ClientNumberEntity numberEntity in numberEntities)
{
ClientPhone phoneListMember = new ClientPhone();
phoneListMember.ClientNumberID = numberEntity.ClientNumbersID;
phoneListMember.RefID = numberEntity.RefID;
phoneListMember.Number = numberEntity.ClientNumber;
phoneListMember.NumberType = numberEntity.ClientNumberType;
phoneListMember.PrimaryNumber = numberEntity.PrimaryNumber;
phoneList.Add(phoneListMember);
}
return phoneList;
}
Any advice on a solution would be greatly appreciated! Thanks :)
Got a solution, albeit it's more stupidity on my end.
I didn't realise that my .EDMX entity diagram hadn't been updated with the new values from the database (I had to manually delete the entity and re-add it to force changes).
After re-compiling and updating the service reference, it worked.

Using C# Properties and JSON

I have this issue where I'm sending a request for a JSON Feed. The issue is that the feed has a dynamic header (i.e. when I send a request for "testinput1" the header response will be testinput1.
Therefore I need to make my RootObject dynamic, but I'm not sure how, could you please help me?
I've entered the troublesome part of the code below
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
textBlock1.Text = "Details Loaded.";
short_description.Text = feed.testinput1.short_description; // can I make testinput1 a constant? its based on code below
});
public class Event
{
public string description { get; set; }
public string datetime { get; set; }
}
public class TrackCode
{
public string short_description { get; set; }
public List<Event> events { get; set; }
}
public class RootObject
{
public string tracker;
public TrackCode testinput1// This needs to be based on user input each time
{
get; // Can I do something here to make sure that the "testinput1" changes each time?
set; // And create a constant that can be referred to?
}
}
Hopefully I can do something like this:
short_description.Text = feed.trackcode.short_description; // this is a constant
public class RootObject
{
public string tracker = "AB123456789NZ"; // This is the variable that changes
public TrackCode trackcode // this becomes a constant
{
get { return tracker; } // uses tracking number as value for JSON when it retrieves it
set { tracker = value;}
}
}
Where have I gone wrong? Thankyou!

C#.NET WebService returning object

I am creating a Web Service using ASP.NET C#. I am sending various data types from the webservice so I use the following structure.
public enum WS_ServiceResponseResult
{
Success,
Failure,
}
public class WS_ServiceResponse
{
public WS_ServiceResponseResult result { get; set; }
public object data { get; set; }
}
public class WS_User
{
public long id{ get; set; }
public string name{ get; set; }
}
Webservice Sample Method
[WebMethod(EnableSession = true)]
public WS_ServiceResponse LogIn(string username, string pasword)
{
WS_ServiceResponse osr = new WS_ServiceResponse();
long userID = UserController.checkLogin(username, pasword);
if (userID != 0)
{
osr.result = WS_ServiceResponseResult.Success;
osr.data = new WS_User() { id = userID, name = username };
}
else
{
osr.result = WS_ServiceResponseResult.Failure;
osr.data = "Invalid username/password!";
}
return osr;
}
I am using two client types, javascript and C#.NET Windows Form. When I call from javascript I get no problem and the osr.data is filled with WS_User. So i can use osr.data.id easily. But when I use from C#.NET (proxy is generated using "Add Web Reference") I can successfully call but when the result arrives I get a Soap Exception
{System.Web.Services.Protocols.SoapException:
System.Web.Services.Protocols.SoapException:
Server was unable to process request.
---> System.InvalidOperationException: There was an error generating the XML
document. ... ...
What am I missing? I Guess object is not well defined and causing the problems. What are the workarounds?
Thanks
Maksud
Addition:
If add the following dummy method, then it works nicely. Hope it helps, to get the solution.
[WebMethod]
public WS_User Dummy()
{
return new WS_User();
}
I had a similar Problem returning an "object" (multiple classes possible)
Here is a sample code:
[Serializable()]
[XmlRoot(ElementName="Object")]
public sealed class XMLObject
{
private Object _Object;
[XmlElement(Type=typeof(App.Projekte.Projekt), ElementName="Projekt")]
[XmlElement(Type=typeof(App.Projekte.Task), ElementName="Task")]
[XmlElement(Type=typeof(App.Projekte.Mitarbeiter), ElementName="Mitarbeiter")]
public Object Object
{
get
{
return _Object;
}
set
{
_Object = value;
}
}
}
I think you should change your code this way:
[XmlRoot(ElementName="ServiceResponse")]
public class WS_ServiceResponse
{
public WS_ServiceResponseResult result { get; set; }
[XmlElement(Type=typeof(WS_User), ElementName="WS_User")]
[XmlElement(Type=typeof(string), ElementName="Text")]
public object data { get; set; }
}

Categories

Resources