Hi,
How to call WCF Service from MVC web api and bind the service model into MVC model? Can you please help ?????
[DataContract]
public class Employee
{
[DataMember]
public int Id { get; set; }
[DataMember]
public string Name { get; set; }
[DataMember]
public int Age { get; set; }
}
This is the employee class
EndpointAddress endpointAddress = new EndpointAddress(ConfigurationManager.AppSettings["ServiceKey"]);
string endpointConfigurationName = "SampleSerVice";
ClassProxy obj = new ClassProxy(endpointConfigurationName, endpointAddress);
var result = obj.GetEmployeeName();
result returns the list of employee, but how to bind this to MVC Model
First of all you need to create WCF Service.
After that you will had to add the ServiceBase Reference in your project.
and then go to the link which is provided by the WCFService.
and then Add the Service by giving Proper name.
After that you need to add the endpoints of the WCF Service which you can find in the Appconfig in the Project where you have added the ServiceBase Reference.
Copy the binding name=" " and End points from the AppConfig and paste it in the Web Config.
You can Access the WCF Service and to use the Service You need to create the instance of it and then whatever models or methods you need to access it.
Related
Sorry for the (maybe) trivial question but, I'm trying to consume a web service where the entities and my data model classes are named different.
I want to keep my model .Net Class name and use a Json Attribute name to map, serializer/deserializer, with the corresponding web service entity.
For example:
Web Service Entity:
"People"
My Model Class:
"Employee"
What I've already do:
[JsonObject(Title="People")]
public class Employee
{
[JsonProperty("DifferentPropertyName")]
string propertyName1 { get; set; }
}
But the json serializer/Deserializer continues to use the .Net class name and I need to set the jsonObject Title.
There is a way to achieve it?
EDIT
I'm working on a Xamarin Forms app, using Simple.OData.Client to consume an OData Service
Thanks
DataContractAttribute may be your solution.
public class RichFilter
{
public Trolo item { get; set; }
}
[DataContract(Name = "item")]
public class Trolo
{
public string connector { get; set; }
}
If you serialize a RichFilter object, here is the output :
{"item":{"connector":"AND"}}
Hello im trying to create a login using wcf but somehow looks like my program dont work as I wanted ;(
public class UserService : IUserService
{
[DataMember]
public string Login { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Type { get; set; }
[DataMember]
public int ID { get; set; }
public List<UserInfo> GetUserInformation()
{
QuizDBEntities contex = new QuizDBEntities();
var UserInfo = from a in contex.UserInfoes select a;
return UserInfo.ToList();
}
}
I created
protected void Button1_Click(object sender, EventArgs e)
{
string username = TextBox1.Text;
string password = TextBox2.Text;
UserService vs = new UserService();
List<UserInfo> alfa = new List<UserInfo>();
}
I used few foreach/if loop but every time I do something wrong and my list act like its empty ( I tried grindwiev and did get all data ;( ) Anyone can help me and give hint how can I compare List to login/password ?
A WCF service isn't actually a service until it's hosted somewhere (IIS, self-hosted, etc). Simply adding the attributes [ServiceContract] and [OperationContract] do not magically make it a service.
SOAP Web services like WCF are not directly accessed by the client - the client goes through a proxy to interact with the service. This proxy can be generated automatically by Visual Studio through either Add Service Reference or the command line svcutil.exe. An easy way to do this is to create a new WCF Service Application - this will be hosted in IIS. There are different (and in my opinion better) ways to host the service, but for simplicity and sake of illustration we'll go with this one.
So let's assume you have a WCF service application up and running, and it has the code you posted above. You could then choose Add Service Reference in the VS Solution Explorer to add a service reference to your service. This will generate a proxy for you to use. The name of the proxy is usually UserServiceClient (i.e., Visual Studio adds Client to the end).
To call a method in your service with this proxy, you would do this:
UserServiceClient proxy = new UserServiceClient();
List<UserInfo> users = proxy.GetUserInformation;
This would give you a list of all the users in your database. You would probably want to either markup the UserInfo entity as a DataContract, or create a new class that has the properties in it as a DataContract - your current code doesn't do anything to set the properties it has in it, and services themselves don't do anything with properties (not to mention your code isn't setting any values for them anyway).
Now for your other question - "how can I compare List to login/password"? In a nutshell, you can't. Your List<UserInfo> is a list of UserInfo objects, and you're attempting to compare a string to this list. That won't work.
What you could do, however, is create another method in your service that would accept a username and a password and return that user's information if it is found. It might look something like below, but first let's make a DataContract to hold the UserInfo (basically moving the DataMembers from the service to a separate class:
[DataContract]
public class UserInformation
{
[DataMember]
public string Login { get; set; }
[DataMember]
public string Password { get; set; }
[DataMember]
public string Type { get; set; }
[DataMember]
public int ID { get; set; }
}
public UserInformation GetUser(string userName, string password)
{
UserInformation user = new UserInformation();
using (QuizDBEntities context = new QuizDBEntities())
{
user = (from a in context.UserInfoes
where a.UserName == userName && a.Password == password
select new UserInformation() {
Login = a.UserName,
Password = a.Password,
Type = a.Type,
ID = a.ID}).SingleOrDefault();
}
return user;
}
The UserInformation class contains the DataMembers you originally had in your service. The LINQ query selects the user that has the matching UserName and Password and populates the UserInformation class (property names are conjecture as I don't know what your UserInfo entity looks like). The SingleOrDefault() at the end selects one matching result, or if no match is found returns the default value - which in this case will be null.
You could then use it like this:
UserServiceClient proxy = new UserServiceClient();
UserInformation user = proxy.GetUser("someName", "somePassword");
proxy.Close();
if (user == null)
{
// No match was found, so do something
}
else
{
// Match was found, so proceed with what you were doing
}
All of the above is primarily for illustration purposes, but you should be able to adapt to your program's needs. I would also suggest Googling for some good tutorials on how to create and host a WCF service.
I'm new to wcf services development. I have the following problem:
I'm creating wcf-service with URI template like this:
[OperationContract, WebGet(UriTemplate = "/EmpDetails/command/?command=SaveDetails&id={id}&data{empid:{EmpID},EmpName:{EmpName},EmpAge:{EmpAge}}"
How can I access these values to save details?
another thing is i want this URL to be used to save details.
http://12.154.21.23:8888/EmpDetails/command/?command=SaveDetails&data={empid:Test,EmpName:TestName,EmpAge:26}
You need to create a class somewhere in service:
[DataContract]
public class Data
{
[DataMember]
public int EmpID {get;set;}
[DataMember]
public string EmpName{get;set;}
[DataMember]
public string EmpAge {get;set;}
}
Next, add this to your wcf service interface:
[OperationContract]
[WebGet(UriTemplate = "/EmpDetails/command/?command=SaveDetails&id={id}&data{EmpID:{EmpID},EmpName:{EmpName},EmpAge:{EmpAge}}")]
void SaveDetails(int id, Data data);
and finally, add code below to class implementing wcf service interface:
public void SaveDetails(int id, Data data)
{
//do smt
}
Apparently my education has failed me, because I didn't realize that methods in C# cannot be serialized. (Good to know.)
I am trying to create a WCF service that returns a simple class I created. The problem is that this simple class contains methods that I want to expose, and the caller of my service won't have any access to them (assuming they won't have a .dll containing the class declaration).
public class Simple
{
public string Message { get; set; }
private const string _Hidden = "Underpants";
public string Hidden
{
get { return _Hidden; }
}
public string GetHidden()
{
return _Hidden;
}
}
I set up a WCF service (let's call it MyService) to return an instance of my Simple class. To my frustration, I'm only getting a partial build of my class back.
public void CallService()
{
using (var client = new MyService.Serviceclient())
{
Simple result = client.GetSimple();
string message = result.Message; // this works.
string hidden = result.Hidden; // this doesn't.
string fail = result.GetHidden(); // Underpants remains elusive.
}
}
Is there any type of workaround where I'm able to set up a property or method on my class that will be accessible to whomever calls my service? How does one handle constants or other methods that are set up in a class that only exists in a service?
Typically you would create three different projects.
1. Service project
2. Client project
3. Data project
The Data project contains only the data classes - no application code. The methods and constants in these data classes should be independent of the Service/Client projects.
The Data project is included as a reference in both the Service and Client projects so that serialization and deserialization happen against the same binary - and you get to retain your constants/methods/etc.
The downside here is that all your clients will either have to be .NET apps, or you will have to provide different data libraries for each platform you wish to support.
As far as I know the only things that can be returned in a WCF service are primitives or a class with public properties that have a get method on them. From a high level WCF exists to allow you to specify a contract between the client and the server that it in theory transportation agnostic (ie you can swap out an HTTP endpoint for a netTcp endpoint and the service will function the same way from a contractual level).
The question to answer then is what data are you trying to pass back in this service call. If it's an object called simple with the data points of Message and Hidden then I would advise creating a data class called Simple that has those values as properties:
[DataContract]
public class Simple
{
[DataMember]
public string Hidden { get; set; }
[DataMember]
public string Message { get; set; }
}
When the client receives the response back Message and Hidden will be populated with whatever you have set their values to on the server side.
The DataMember attribute can only be used on properties and fields. This means that a WCF response can only serialize these types.
If you really want to only use the const in your WCF contract You could convert it to a field and place the DataMember attribute on it:
public class Simple
{
[DataMember]
public string Message { get; set; }
[DataMember]
public const string Hidden = "Underpants";
}
To be able to do this the field must be accessible (public).
Add the DataMember attribute to your property. To do so, you must have both a get and a set defined.
[DataMember]
public string Hidden
{
get { return _Hidden; }
set { }
}
technically you could do
public class thingToSerialize{
public Func<ArgType1,ArgType2...,ReturnType> myFunction{get;set;}
}
and then assign it a lambda that takes the arguments and returns the return type
before serializing
Scenario: An entity from data model is passed into a WCF Web Service with various information, saved into a database and then returned back with the object fully populated with additional information.
public class Request
{
public virtual Guid RequestID { get; set; }
public virtual string RequestType { get; set; }
public virtual System.DateTime CreatedDate { get; set; }
//More properties here populated from DB
}
[OperationContract]
Request CreateRequest(Request input);
In this example, the RequestID and CreatedDate are populated only when the record is inserted into the database, and therefore should not be visible during the initial request. They should be visible when the object is returned however.
The current approach that we are going with is to create two classes (RequestInput, RequestOutput) in our web service implementation project which inherit from the entity.
We will then add [DataMember] attributes on various properties that are required and [IgnoreDataMember] on those that should be ignored.
Is this the correct approach?
I wouldn't say it is a correct or incorrect way. But it is more usual to use names something along the line of
[DataContract]
Request{...}
and
[DataContract]
Response{...}
the Request and Response should ideally be decoupled from the model representation you are using in the client and the server - ie you have a facade or adaptor that maps them to your model from your service code.
this is along the lines of how I would do it - but this is very subjective dependant on size of entities etc - you may want to involve an auto-mapper somehow.
// higher level code
var entity = new Entity { properties we know before call };
// pass down to service layer
var response = service.CreateRequest(new Request { Prop1 = entity.Prop1... } );
entity.RequestID = response.RequestId;
entity.CreatedDate = response.CreatedDate;