PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0
Showing posts with label wcf. Show all posts
Showing posts with label wcf. Show all posts

Sunday, October 23, 2022

[FIXED] How to send class equals implementation to client using a WCF Web Server

 October 23, 2022     c#, datamember, java-client, wcf, webserver     No comments   

Issue

I'm developing an aplication in java (JSF) which communicates whith an WCF web server. I developed the webserver using c#, and I'm havin trouble to send the equals implementation of an complex object to the java client. For example, consider this c# class:

[DataContract(Namespace = "http://mywebservice.com/Entidades")]
    public class Record{private Int64 id;
    [DataMember]
    public Int64 Id
    {
        get { return id; }
        set { id = value; }
    }

    public override bool Equals(Object obj)
    {
          if(obj is Record){
               Record rec = obj as Record;
               return rec.Id == this.Id;
         }
         return false;
    }

}

First tryed to put the [DataMember] in the equals, but I discovered that I can't do that. How is the right way to send this implementation of the "equals" of this complex type to the java client?

Thanks in advance


Solution

That doesn't make sense.
Web services transfer data, not code.

You need to implement equals() in you Java objects in source.



Answered By - SLaks
Answer Checked By - Gilberto Lyons (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, October 20, 2022

[FIXED] how to WCF dynamic DataMember?

 October 20, 2022     datacontract, datamember, json, wcf     No comments   

Issue

example: a Customer class have 100 data member(id, name, age, address...etc) to be serialization to JSON.

In Config file such as Web.config, can set a output list to serialize JSON ouptut.

If output only id and name, then JSON only have id and name.

My Question: Can support dynamic DataMember in a DataContract ?


Solution

You mean optional datamembers, I guess so, check this question Surely you'll have to have null values for the ones you dont want to send over the wire. Another, more dirtier, solution would be to use a dictionary as a datamember and have the fields you want to send as elements there. There may be type conversion issues, but maybe it serves you better.

Edit:

You probably want to go with a dictioray serialized as an associative array en js, as this question specifies. Check the answers and the links in there. That should get you going. But still I'd go with optional datamembers since it's more of a "contract" thing. Other than that a better description of what you want to do will help.



Answered By - Carlos Grappa
Answer Checked By - Clifford M. (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

[FIXED] Why is using [DataMember(EmitDefaultValue = false)] not recommended?

 October 20, 2022     datacontract, datamember, msdn, wcf     No comments   

Issue

In WCF you can define a contract using the [DataContract] and [DataMember] attributes, like this:

[DataContract]
public class Sample 
{
    [DataMember(EmitDefaultValue = false, IsRequired = false)]
    public string Test { get; set; }
}

This article on the MSDN states that using EmitDefaultValue = false is not recommended:

snippet

However, i like to use this, because the XML that is generated using this construction is cleaner. Not specifying this setting results in:

<Sample>
    <Test xsi:nil="true"/>
</Sample>

while using the setting the element is ommited when there is no value:

<Sample>
</Sample>

I'm curious to what the reasoning behind that statement is. Specifically since both snipptes of XML look equivalent to me (and both last part can be deserialized correctly for this contract).

What is the reasoning behind this statement?


Solution

The reason is at the bottom of the article that you link to. The short version is:

  • When the EmitDefaultValue is set to false, it is represented in the schema as an annotation specific to Windows Communication Foundation (WCF). There is no interoperable way to represent this information. In particular, the "default" attribute in the schema is not used for this purpose, the minOccurs attribute is affected only by the IsRequired setting, and the nillable attribute is affected only by the type of the data member.

  • The actual default value to use is not present in the schema. It is up to the receiving endpoint to appropriately interpret a missing element.



Answered By - Shiraz Bhaiji
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, August 4, 2022

[FIXED] How to prevent that a channel exception make a WCF service stop working?

 August 04, 2022     .net, channel, exception, timeout, wcf     No comments   

Issue

I created a WCF singleton service with netNamedPipeBinding. When a channel exception occurs, it leaves a channel in a faulty state, and all subsequent operations throws exceptions. How can I prevent this? I want that a TimeoutException, or any of the other common exceptions, to make only one operation fail, and not to make the service unresponsive.


Solution

There is another way. You can instantiate the client proxy for each request instead of using a single instance for more than one request. This way if the channel enters a faulty state, it is discarded anyway.

This is a bit tricky because you shouldn't dispose a channel, besides it being IDisposable.

It won't work:

using(var channel = channelFactory.CreateChannel())
{
    return channel.ServiceMethod(parameter);
}

Instead you should:

public static class Service<T>
{
    public static ChannelFactory<T> _channelFactory = new ChannelFactory<T>("");

    public static TResult Use<TResult>(Func<T, TResult> func)
    {
        TResult output;
        var channel = (IClientChannel)_channelFactory.CreateChannel();
        bool success = false;
        try
        {
            output = func((T)proxy);
            channel.Close();
            success = true;
        }
        finally
        {
            if (!success)
            {
                proxy.Abort();
            }
        }
        return output;
    }
}

return Service<IService>.Use(channel =>
{
    return channel.ServiceMethod(parameter);
});


Answered By - Jader Dias
Answer Checked By - Dawn Plyler (PHPFixing Volunteer)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg

Thursday, May 19, 2022

[FIXED] How can convert AsyncTask to Retrofit for get data from WCF Webservice in Android

 May 19, 2022     android, android-asynctask, json, wcf, web-services     No comments   

Issue

I have a WCF webservice that returns SQL Server database data in JSON format, Now i'm using AsyncTask for get this data in Android by this code :

public class FetchInfo extends AsyncTask {

private String year = "94";
private String month = "1";
private String requested_column = "";
private String kodemelli = "";

public FetchInfo(String year, String month,String requested_column, String kodemelli) {
    this.year = year;
    this.month = month;
    this.requested_column = requested_column;
    this.kodemelli = kodemelli;
}
@Override
protected String doInBackground(Object[] params) {
    try {
        System.out.println("guru");
        DefaultHttpClient httpClient=new DefaultHttpClient();

        //Connect to the server
        HttpGet httpGet=new HttpGet("http://SERVERIP:8005/Service1.svc/checkLogin1?year="+year+"&month="+month+"&requested_column="+requested_column+"&kode_melli="+kodemelli);
        //Get the response

        String result = "";
        HttpResponse httpResponse = httpClient.execute(httpGet);
        HttpEntity httpEntity = httpResponse.getEntity();
        InputStream stream=httpEntity.getContent();
        result = convertStreamToString(stream);
        //Convert the stream to readable format
        if (result.contains("\"error\"") || result.contains("\"server error\"")){
            Main.result = "0";
            MainFish.result = "0";
        }else {
            Main.result = result;
            MainFish.result = result;
        }

    } catch (Exception e) {
        Main.result = "error";
        MainFish.result = "error";
    }

    return "";
}
public static String convertStreamToString(InputStream is)
{
    BufferedReader reader = new BufferedReader(new InputStreamReader(is));
    StringBuilder sb = new StringBuilder();

    String line = null;
    try {
        while ((line = reader.readLine()) != null) {
            sb.append(line + "\n");
        }
    }
    catch (IOException e) {
        e.printStackTrace();
    }
    finally {
        try {
            is.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    return sb.toString();
}
}

By this ,when the requests is more than for example 10 request, the response time is very long. From this topic How to speed up fetching of data from server using JSON? I realized that I should to use Retrofit instead AsyncTask to make my program work.

Now my question is how can convert AsyncTask class to a Retrofit?


Solution

Ok so first you will not use an async task with retrofit. Retrofit takes care of the async part. First you need do define a rest adapter.

Here is a default rest adapter with your parameters in it.

public class ApiClient {

private static ApiInterface sApiInterface;

public static ApiInterface getApiClient(Context context) {

//build the rest adapter
if (sApiInterface == null) {
    final RestAdapter restAdapter = new RestAdapter.Builder()
            .setEndpoint("http://SERVERIP:8005")
            .build();
    sApiInterface = restAdapter.create(ApiInterface.class);
}
return sApiInterface;
}


public interface ApiInterface {
// /Service1.svc/checkLogin1?year="+year+"&month="+month+"&requested_column="+requested_column+"&kode_melli="+kodemelli
@GET("/Service1.svc/checkLogin1")
void getYourObject(
    @Query("year") String year,       
    @Query("month") String month,    
    @Query("requested_column") String requested_column,
    @Query("kode_melli") String kodemelli,
    RetrofitCallback<YourObjectModel> callback);

}

After you have a rest adapter you need a model to put the data in. Use jsonschema2pojo to convert valid JSON to a POJO model. Here is an example of one of my json responses and its model.

{
"id": "37",
"title": "",
"short_name": "",
"short_description": "",
"full_description": "",
"url": "http:\/\/\/shows\/programname",
"Image": {
    "url": "https:\/\/s3.amazonaws.com\/image\/original\/b2mWDPX.jpg",
    "url_sm": "https:\/\/s3.amazonaws.com\/image\/small\/b2mWDPX.jpg",
},
"image": "b2mWDPX.jpg",
"hosts": [{
    "id": "651",
    "display_name": "",
    "username": "",
    "Image": {
        "url": "https:\/\/s3.amazonaws.com\/image\/original\/selfie.jpg",
        "url_sm": "https:\/\/s3.amazonaws.com\/image\/small\/selfie.jpg",
    }
}],
"airtimes": [{
    "start": "11:00:00",
    "end": "13:30:00",
    "weekday": "6"
}],
"categories": [{
    "id": "84",
    "title": "Bluegrass",
    "short_name": "bluegrass"
}],
"meta": []
}

I get this model. And a few others to go with it.

public class Program {
@Expose
private doublea.models.Airtime Airtime;
@Expose
private String id;
@Expose
private String title;
@SerializedName("short_name")
@Expose
private String shortName;
@SerializedName("full_description")
@Expose
private String fullDescription;
@SerializedName("short_description")
@Expose
private String shortDescription;
@Expose
private doublea.models.Image Image;
@SerializedName("image")
@Expose
private String imageName;
@Expose
private List<Host> hosts = new ArrayList<Host>();
@Expose
private List<Category> categories = new ArrayList<Category>();
@Expose
private List<Airtime> airtimes = new ArrayList<Airtime>();

/** Getters and Setters */

public Program() {
}

Then make sure you take care of failure cases.

public class RetrofitCallback<S> implements Callback<S> {
private static final String TAG = RetrofitCallback.class.getSimpleName();


@Override
public void success(S s, Response response) {

}

@Override
public void failure(RetrofitError error) {
    Log.e(TAG, "Failed to make http request for: " + error.getUrl());
    Response errorResponse = error.getResponse();
    if (errorResponse != null) {
        Log.e(TAG, errorResponse.getReason());
        if (errorResponse.getStatus() == 500) {
            Log.e(TAG, "Handle Server Errors Here");
        }
    }
}
}

And finally making the api call.

private void executeProgramApiCall(String year, String month, String requested_column, String kodemelli) {
ApiClient.getApiClient(this).getProgram(year, month, requested_column, kodemelli, new RetrofitCallback<Program>() {

    @Override
    public void success(YourObjectModel program, Response response) {
        super.success(YourObjectModel , response);
        //TODO: Do something here with your ObjectMadel
    }
});
}

I would highly recommend taking a look at the retrofit documentation in case you need anything special like headers or request interceptors.



Answered By - doubleA
Answer Checked By - Robin (PHPFixing Admin)
Read More
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Older Posts Home

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
All Comments
Atom
All Comments

Copyright © PHPFixing