I want to create and consume a WCF Service in Silverlight. I have created a service that returns this model from a database:
namespace SilverlightWithWCFService.Web
{
[DataContract]
public class Customer
{
[DataMember]
public string CustomerName { get; set; }
[DataMember]
public string CompanyName { get; set; }
[DataMember]
public string ContactName { get; set; }
}
}
The service looks like this:
namespace SilverlightWithWCFService.Web
{
[ServiceContract(Namespace = "")]
[AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
public class SampleService
{
[OperationContract]
public List<Customer> CustomerList()
{
var custList = new List<Customer>();
// populate custList
return custList;
}
}
}
}
In my Silverlight application, I added a Service Reference. This method calls the service operation:
public Page()
{
InitializeComponent();
SampleServiceClient client = new SampleServiceClient();
client.CustomerListCompleted += new EventHandler<CustomerListCompletedEventArgs>(client_CustomerListCompleted);
client.CustomerListAsync();
}
void client_CustomerListCompleted(object sender, CustomerListCompletedEventArgs e)
{
CustomerGrid.ItemsSource = e.Result;
}
So my question is: I don't know how the Silverlight work with WCF. Do I have to serialize something on WCF side and deserialize the return value on client side? If so, what code is missing? (Where?)
UPDATE:
I think based on some online questions. Should I deserialize the returned e.Result in the completed event code?
Do I have to serialize something on WCF side and deserialize the return value on client side?
No, when you consume the webservice the underlying code will do all that for you.
Don't get hung up on it being Silverlight. Just think of Silverlight as the same as a console application. Whatever one has to do in the console app to consume the webservices, one will have to do in Silverlight. The only difference is that you will need to handle the calls in an async manner, but that is separate from the consuming of the webservice which your question pertains.
Note there was a competing technology to do all the updates of the webservice during a compile. That was called RIA services and that is a different animal all together.
I would recommend you use WCF web services, but update the size of the send/receive buffers for you will max those out easily on any true data transfers.
I have a working C# Web Service running on IIS on a dedicated server. There is a method that gets Session object(DataContract) and its tested and working on Windows clients. However now I'm developing a "Xamarin.Mac" application and I need to connect to server , but I'm facing a specific error.
[DataContract]
public class Session{
[DataMember]
public string Email { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string ComputerHash { get; set; }
[DataMember]
public string Ip { get; set; }
}
This is the Session class I'm trying to send.
[OperationContract]
bool Login ( Session session );
And this is the method I'm calling.
But when I'm debugging, I checked that my Session object is filled and the values are set. But server gets the Session object but all fields of the object are set to null. Thus it gives me null exception.
Interestingly non-complex objects are being sent without any problem, but these complex types are giving me headaches.
What I might be missing here?
That depends on how you're making the request. You need to "post" the data to the server. The data needs to be defined in the body of the message, not as parameters in the request url.
Here: Recommended ServiceStack API Structure and here: https://github.com/ServiceStack/ServiceStack/wiki/Physical-project-structure are recommendations for how to structure your projects for C# clients to reuse DTOs.
Apparently this is done by including a dll of the DTO assembly. I have searched the web for one example, just Hello World that uses a separate assembly DTO for a C# client in ServiceStack. Perhaps I should be able to break this out myself but so far it has not proven that easy.
Almost all client descriptions are for generic and non-typed JSON or other non-DTO based clients. No one appears interested in typed C# clients like I am (even the ServiceStack documentation I have found). So I thought this would be a good question even if I figure it out myself in the end.
To be clear, I have built and run the Hello World example server. I have also used a browser to attach to the server and interact with it. I have also created a client empty project that can call
JsonServiceClient client = new JsonServiceClient(myURL);
Then I tried to copy over my DTO definition without the assembly DLL as I don't have one. I get ResponseStatus is undefined.
Clearly there is something missing (it appears to be defined in ServiceStack.Interfaces.dll) and if I could create a dll of the DTO I think it would resolve all references.
Can anyone give insight into how to create the DTO assembly for the simple Hello World?
Edited to add code:
using ServiceStack.ServiceClient.Web;
namespace TestServiceStack
{
class HelloClient
{ public class HelloResponse
{
public string Result { get; set; }
public ResponseStatus ResponseStatus { get; set; } //Where Exceptions get auto-serialized
}
//Request DTO
public class Hello
{
public string Name { get; set; }
}
HelloResponse response = client.Get(new Hello { Name = "World!" });
}
}
Where the ResponceStatus is undefined.
I was able to find the missing symbol ResponseStatus by adding:
using ServiceStack.ServiceInterface.ServiceModel;
Here is the full code that built. Keep in mind that I found out something else in the process. Once this built it then failed because I was using a DTO from a .NET 4.0 environment in a .NET 3.5 environment. But that is an unrelated issue. Also note that this test code does nothing with the response, it is just an example to get the build working.
using ServiceStack.ServiceClient;
using ServiceStack.ServiceInterface;
using ServiceStack.Text;
using ServiceStack.Service;
using ServiceStack.ServiceHost;
using ServiceStack.WebHost;
using ServiceStack;
using ServiceStack.ServiceClient.Web;
using RestTestRoot; // This is the name of my DTO assembly. You will need to insert your own here.
using ServiceStack.ServiceInterface.ServiceModel;
namespace WebApplicationRoot
{
class HelloClient
{
JsonServiceClient hello_client;
//Request DTO
public class Hello
{
public string Name { get; set; }
}
//Response DTO
public class HelloResponse
{
public string Result { get; set; }
public ResponseStatus ResponseStatus { get; set; } //Where Exceptions get auto-serialized
}
//Can be called via any endpoint or format, see: http://mono.servicestack.net/ServiceStack.Hello/
public class HelloService : Service
{
public object Any(Hello request)
{
return new HelloResponse { Result = "Hello, " + request.Name };
}
}
//REST Resource DTO
[Route("/todos")]
[Route("/todos/{Ids}")]
public class Todos : IReturn<List<Todo>>
{
public long[] Ids { get; set; }
public Todos(params long[] ids)
{
this.Ids = ids;
}
}
[Route("/todos", "POST")]
[Route("/todos/{Id}", "PUT")]
public class Todo : IReturn<Todo>
{
public long Id { get; set; }
public string Content { get; set; }
public int Order { get; set; }
public bool Done { get; set; }
}
public HelloClient(){
// ServiceStack gateway = new ServiceStack.ClientGateway(
// location.protocol + "//" + location.host + '/ServiceStack.Examples.Host.Web/ServiceStack/');
hello_client = new JsonServiceClient("http://tradetree2.dnsapi.info:8080/");
hello_client.Get<HelloResponse>("/hello/MyTestWorld!");
}
}
}
I am looking for new wcf rest web service in asp.net 4.0 using vs2010.
here is my code for passing url:
"homewizard/Service1.svc/monthlytips/country_state=US_IL_N/tip_code=NoInformation/feature=ACC,FAHD,WHG,FP,WA,DY,DWSH,GD,REF,STV,OVN,MW,CPTR,ATT,ROOF,RG,BSMT,FDN,SPX,GAR,EGF,PLB,DOOR,WIND,WS,LWN,DKG,PF,BBQ,WSD,OWF,DWY,OLIT,HL,SPTC,CF,WF,CPTS,DVB,FURW,FURL,FURU,MAT,BATH,KITC,CLST,LITE,SD,COD,FE,EMS,PC,SS,MED,EAUD,ENR,GARR,INR,MGR,TAXR,TELR,CGD,DOOR,WIND,WS/dwelling_type=1/tip_priority=1/month=3/tip_knowledge_level=1/tipbr_ensav=0/tipbr_safe=0/tipbr_avoid=1/tipbr_comfort=1/tipbr_value=1/tipbr_appear=1/tipbr_green=0/tipbr_money=0/tipbr_space=1/tipbr_allergy=2/tipbr_elderly=2/tipbr_children=2/tip_location_temp=0/tip_location_humidity=0"
output:Bad Request - Invalid URL HTTP Error 400. The request URL is invalid.
my web config is: httpRuntime maxUrlLength="1024"
but it's working my local host not in server pc.
thanks in advance.
To be honest your issue is that that's not a restfull URL, the url should just be the location of the resource you are dealing with, the body of the request should contain the details of the request (as xml or json for example). It will both solve your problem and result in less code to manage the parameters via deserialization into a request object server side, not to mention clear up that url.
UPDATE
Are you sure thats a GET and not a PUT, what is the call meant to do?
If it is a GET I'd do something like the following...
Service Interface
[WebGet(UriTemplate = "monthlytips")]
AppropriateReturnType MonthlyTips(MonthlyTip monthlytip);
DTO Object
public class MonthlyTip
{
public string CountryState { get; set; }
public string TipCode { get; set; }
public List<string> Feature { get; set; }
public int DwellingType { get; set; }
public int TipPriority { get; set; }
...
...
}
Thats off the top of my head so it might need a little refining and you'll need to implement the interface, finish the DTO and so on but that's the approach you should take.
I got an Employee class and each employee has a list of applied leaves. Is it possible to have the list AppliedLeave as a [DataMember] in WCF?
[DataContract]
public class Employee
{
[DataMember]
public string UserID { get; set; }
[DataMember]
public int EmployeeNumber { get; set; }
[ForeignKey("EmployeeUserID")]
[DataMember]
public List<Leave> AppliedLeave
{
get { return _appliedLeaves; }
set { _appliedLeaves = value; }
}
private List<Leave> _appliedLeaves = new List<Leave>();
...
}
Is there any other way to do this?
thank you for your consideration of this matter
I extend my Question
This is my Leave Class:
[DataContract]
public class Leave
{
[Key()]
[DataMember]
public Guid LeaveId { get; set; }
[DataMember]
public string LeaveType { get; set; }
[DataMember]
public DateTime StartDate { get; set; }
[DataMember]
public string EmployeeUserID { get; set; }
}
this shows ServiceContract ---->
[ServiceContract]
public interface IEmployeeService
{
[OperationContract]
Employee GetEmployeeByUserId(string userId);
[OperationContract]
void AssignSupervisor(string userId, string supervisorUserId);
[OperationContract]
void DeleteEmployeeByUserId(string userId);
....
}
In Client application,
EmployeeServiceClient employeeService = new EmployeeServiceClient();
Employee employee = employeeService.GetEmployeeByUserId(id);
But when Employee gathered from the service its shows Null for leaves,
Can somebody help me? what have I done wrong here?
Yes, it is possible to return generics from WCF service operations.
But by default they are casted to Array on client side. This can be customized while proxy generation.
WCF: Serialization and Generics
Also you have to decorate the service with all the types to which generics can be resolved, using KnownTypeAttribute.
Known Types and the Generic Resolver
I also found my server side list would always arrive at the client as a null pointer. After browsing around a lot for this problem it strikes me it is nearly always denied at first ("your code should work")
Found the issue.. I had configured my solution using one "WCF Service" project and one "Winforms app" project with a generated service reference. Both interface and implementation of Service1 were in the WCF service project, as expected. But any list member returned null.
When I put my IService1.cs = the interface only = in a separate class library instead, reference the class library on both sides (using) and generate the service reference again, my list does work ! The generated code on the client side looks much simpler.
I did not need any special attributes, change service reference configuration, or interface references for this.
You could use IList<T> instead of List<T>.