Pass a list of objects to a web service - c#

I have a DataObjects class that contains a UserEmail object that contains an int (EmailID) and a string (EmailAddress).
Within a C# .net application, if I want to display a list of email addresses - I create and populate a list of UserEmail objects.
List<DataObjects.UserEmails> myUserEmailsList = new List<DataObjects.UserEmails>();
And use it as a datasource for whatever control I happen to be using.
I need to pass that list to a web service. I can't see how to do this. If the other party writes a web service with a method that takes a list as a parameter - fine, I can call the web service and pass my list. But how will they be able to extract the data from the list - without having access to the classes that created the objects in the list?
Is there a way of looping through a list of objects without knowing what the data structure of the object is?

When you are consuming their web service, you have to conform to their data structures. You take your UserEmail object data, and would convert it to the object their service is expecting.
If you're using a service where it's just needing the data as get or post data, you'll have to use whatever keys they are requiring. So they might take the email address using a key of "email" instead of your property name of "EmailAddress"

here a sample to pass list object to your webservice
<%#WebService Language="c#" class="CustomObjectArrayWS"%>
using System;
using System.Collections;
using System.Web.Services;
using System.Xml.Serialization;
public class CustomObjectArrayWS
{
[WebMethodAttribute]
[XmlInclude(typeof(Address))]
public ArrayList GetAddresses ()
{
ArrayList al = new ArrayList();
Address addr1 = new Address("John Smith", "New York",12345);
Address addr2 = new Address("John Stalk", "San Fransisco", 12345);
al.Add(addr1);
al.Add(addr2);
return al;
}
}
// Custom class to be added to the collection to be passed in //and out of the service
public class Address
{
public string name;
public string city;
public int zip;
// Default ctor needed by XmlSerializer
public Address()
{
}
public Address(string _name, string _city, int _zip )
{
this.name = _name;
this.city = _city;
this.zip = _zip;
}
}
see http://www.programmersheaven.com/2/XML-Webservice-FAQ-Pass-Array-Of-Custom-Objects

Related

How to fetch value from an ExtensionDataObject of a wcf reponse

I have a WCF service which returns ExtensionDataObject during runtime as attached snapshot:
Im struck with fetching value for these objects. Could anyone please help here:
Have tried with below code using reflection, which throws Parameter count missing exception
List<System.Runtime.Serialization.ExtensionDataObject> extData = temp.Select(x => x.ExtensionData).ToList();
var GetCountry = extData.GetType().GetProperties();
string Country = string.Empty;
foreach (var property in GetCountry)
{
string name = property.Name;
object value = property.GetValue(extData, null);
if (name == "Country")
Country = value.ToString();
}
The Extensiondataobject field is generated to control the data contract incompatibility between the server and the client, so it will return a field named extensiondataobject. In other words, your client data contract implements the IExtensionDataObject interface.
[DataContract(Namespace="abcd")]
public class Product: IExtensibleDataObject
{
[DataMember]
public int ID { get; set; }
[DataMember]
public string Name { get; set; }
public ExtensionDataObject ExtensionData { get ; set ; }
}
If we capture this request through Fiddle, you can even see all the data directly.
In a word, you only need to add the Country property to the Data class of X object. It will be deserialized automatically. This class should be your client-side data contract class, instead of the server-side data class.
Finally, it seems that the value of these fields is null. We should ensure that the server and client data contracts have the same namespace. It cannot be the default value(http://tempuri.org). As I defined above, this namespace attribute should be consistent with the server-side value.
Feel free to let me know if there is anything I can help with.

How can I pass DataTable to view as JSON/XML code?

I am new to the .NET environment and trying to write a simple MVC application to read student data and display it to the end user. I have connected to a database using SQLOLEDB, the code of which I have pasted below. The data obtained from the query was stored in a variable of the type DataTable. Now I want to see the content of the query result in the form of a JSON output for which I have a faintest idea that I have to create a new controller. But I am not able to proceed beyond this point.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data.SqlClient;
using System.Data;
namespace Database.model
{
public class student
{
public int id { get; set; }
public string name { get; set; }
private string age { get; set; }
public DataTable GETSQLServerData()
{
//Connect
var _connectionobject = new SqlConnection();
_connectionobject.ConnectionString = #"Provider=SQLOLEDB;Data Source=PHYSICS\SQLEXPRESS;Persist Security Info=true;Initial Catalog=master;Integrated Security=True; provider = SQLOLEDB;";
_connectionobject.Open();
//Command
var _commandObject = new SqlCommand();
_commandObject.CommandText = "select * from dbo.tblStudent";
//Execute
_commandObject.ExecuteReader();
//Data
var _dataReader = _commandObject.ExecuteReader();
DataTable obj2 = new DataTable();
obj2.Load(_dataReader);
_connectionobject.Close();
return obj2;
}
}
}
I would be really grateful if anyone could help me in this regard
You can convert the datatable object into a POCO object
How do I convert a datatable into a POCO object in Asp.Net MVC?
then return that POCO object back to the browser.
The best practice would be to create a class that will hold the student data and return that class object instead of the data table like so.
// you student model class
public class Student
{
// public properties of student...
}
In your data access class populate this student object list and return to the MVC action method.
//then in your MVC action method
IEnumerable<Student> students = GETSQLServerData();
return this.Json(students , JsonRequestBehavior.AllowGet);
A few points about your code:
1- Avoid using sql statement in your C# code, switch to stored
procedure.
2- Use Data Model layer and create Student class to define student
model.
3- Use Data acccess layer to call SQL Stored proc
4- Inject dependencies to avoid tightly coupled classes.
Hope this helps!

Can I consume JSON without defining the fields before in C# code?

I am working on a REST API for a project using Visual Studio 2013 with C# and ASP.NET, and I need some guidance.
When the webpage performs a POST, I am passing along a number of fields as a JSON object. By defining a data transfer object in my C# code, I can easily read the values from the JSON, but only if I define all the fields (with the same name).
Here is my current (working) code:
public class AgencyPostDTO
{
public string AgencyName { get; set; }
public string Address1 { get; set; }
public string Address2 { get; set; }
public string City { get; set; }
public string State { get; set; }
public string ZIP { get; set; }
}
// POST: api/Agency
public string Post(AgencyPostDTO Agency)
{
int success;
success = SQLUpdateAgency(Agency);
if (success < 1)
{
return "Failed";
}
else
{
return "Success";
}
}
So far no problems. I need to pass the data over to a second function, where I will perform some data processing (including converting the data into XML) and send the data/XML to MS SQL using a stored procedure:
public int SQLUpdateAgency(AgencyPostDTO Agency)
{
string xml = Agency.SerializeObject();
... code to call SQL stored procedure ommitted here
}
Now to my problem. I would prefer if I did not have to define the parameters of the data transfer object AgencyPostDTO in the code, and instead the code would just read the incoming JSON and pass it along to the next function, where I create the XML containing everything passed along.
As it works now, if the JSON contains for example an email address field, it will be dropped unless I define it in AgencyPostDTO.
So why do I want to do this? For future ease of maintenance. The users may come and say they want to add additional fields to the web form. I can then simply have our SQL expert add that column to the table, give me the name of it and I add an input field to the HTML form and make sure it is included in the JSON sent over. That way we never have to touch the already written, tested and working code. The new field is simply passed though the whole process.
Can this be done? If so, any suggestions on how?
If you used JSON.NET to handle the deserialisation of your objects then that has support for dynamic properties. Once you'd read your JSON string, you could convert it to a JArray or JObject and from there by using the .Children() call to get a list of all properties to convert it to any XML object you needed.
Have a look here:
Deserialize json object into dynamic object using Json.net

How to pass an object of custom class containing a custom list to a web service?

I have to implement a simple conventional web service in VS2008 C#, which would receive an Order class object, which contains a list of Product class objects. The problem arises when I create an instance of an Order class object on the client. It is declared in the proxy and does not contain any methods, thus I have no opportunity to add Products, as List of Products is now simply a System.Array.
One method which works fine is to manually serialize into XML on the client and de-serialize in the web service. This way I would be using same class declaration which I isolated into a DLL shared between web service and client application. However, I am being told that it is possible to avoid using a shared DLL and manual serialization althogether, but I just don't understand how, i.e. how do I need to declare/define Order class and where in order for it to have methods on the client?
Currently the classes are defined as follows in the shared DLL:
namespace MyNS
{
[Serializable]
public class ProductInfo {
public Int32 ProductID;
public Int32 Quantity;
public decimal CurrPrice;
public VE_ProductInfo() {
ProductID = 0;
Quantity = 0;
CPrice = 0;
}
public ProductInfo(Int32 pId, Int32 quant, decimal cprice)
{
ProductID = pId;
Quantity = quant;
CPrice = cprice;
}
}
[Serializable]
public class OrderInfo
{
public Int32 CustomerId = 0;
public OrderInfo () {
Items = new List<ProductInfo>();
}
[XmlArray]
public List<ProductInfo> Items {get; set;}
public string SpecialInstructions;
public void AddProduct(ProductInfo pi)
{
Items.Add(pi);
}
}
}
This class is then used in a web service method as follows:
public bool CreateOrder(OrderInfo Order) {
// some code
}
And it is called as follows from the client:
WebService.MyWebService s;
WebService.OrderInfo o = new WebService.OrderInfo();
o.CustomerId = 1;
o.Items.Add(new ProductInfo(2, 4));
o.Items.Add(new ProductInfo(1, 2, 3.95m));
checkBox1.Checked = s.CreateOrder(o);
If you provide a default constructor and field initializers for the classes shared between the application and web service, then you can put the classes in a separate library project that both projects reference. When you add the web service reference to the application, it will generate a few proxy classes that match the data "shape" of your object, sans methods. You can delete those classes (I don't remember exactly where they are located) and add a using statement to the web service proxy class file itself to import your shared classes and they will work appropriately.
If your web service is a WCF one and you created a proxy for it by adding a web reference you should be able to change it by editing the refernce in Visual Studio. Right Click on it and select "Configure Service Reference" then choose a Collection type of List.

One property not saving when using web service

I have this object:
public class Announcement
{
public int Id { get; set; }
public DateTime DateSent { get; set; }
private IList<string> _recipients;
public IList<string> Recipients
{
get { return _recipients; }
set { _recipients = value; }
}
public string RecipientsString
{
get { return String.Join("\n", _recipients); }
set { _recipients = value.Split('\n').ToList(); }
}
}
I can populate this object with the DateSent and RecipientString (a string of email addresses separated by \n) and save it to the database with no problems.
Now I want to move this to a web service so we can use it across multiple apps.
I created the exact same object in the webservice, and testing locally (on the service) everything works as expected.
But if I populate the object on the client and pass it to the service to be saved, the RecipientString is always empty (not null). The DateSent is fine.
I'm guessing the data is getting lost in serialization, but I don't know why, or how to solve this. I thought also, it could have something to do with the # in the email address, but I've ruled that out. Any suggestions?
This happens because de WSDL that is generated to describe your service can't describe the function that is used in your get and set functions. I suggest you keep RecipientsString as a common property, and create a private method GetRecipients on your class that processes the RecipientsString value and returns the list you need.
Use RecipientsString without backing field.

Categories