2

I'm working with JSON for a while now, but this is a problem I can't solve.

The program is written in C# and has a method called CreateWebRequest():

public void CreateWebRequest()
    {
        CurrentTime = DateTime.Now;
        target = link;
        request = WebRequest.Create(target) as HttpWebRequest;
        request.ContentType = "application/json; charset=utf-8";
        request.Method = "PUT";
        request.ServicePoint.Expect100Continue = false;
        string postData = jsonString;
        System.Console.WriteLine("POSTDATA: " + postData);
        StreamWriter requestWriter;
        using (requestWriter = new StreamWriter(request.GetRequestStream()))
        {
            requestWriter.Write(postData);
        }

    }

The other function to fetch the result is called: CreateWebResponse():

public void CreateWebResponse()
    {
        WebResponse response;

        string text;
        try
        {
            response = (HttpWebResponse)request.GetResponse();
        }

        catch (WebException e)
        {
            MessageBox.Show(e.Message);
            return;
        }

        using (var sr = new StreamReader(response.GetResponseStream()))
        {
            text = sr.ReadToEnd();
        }

        APIresult apiresult = JsonConvert.DeserializeObject<APIresult>(text); //Deserialize the text

    }

These functions work all fine, there is only one problem: the code does two requests.

When I put the same JSON in the RESTClient in mozilla FireFox the JSON works fine. It also works great when I'm only using CreateWebRequest(), but when I use both of the methods it seems the code creats a second request?

Is it possible to create only a response? Combine these two functions to one which creates directly an response?

I tried other solutions and put them just together, none of them seems to work. When I call for a response the code doesn't work properly anymore and creates two requests.

Has anyone a solution?

Thanks in advance.

The JSON function I call has several if statements and work fine according to RESTClient in Firefox. The code below shows the code which is called correct by RESTClient and twice by the C# code:

$sql = 'SELECT...';
        $result = $db->sql_query($sql);//search for member id.
        if($row = $db->sql_fetchrow($result)){//when found, the user has access.
            $member_id = $row['member_id'];
            $sql = 'SELECT ...';
            $result = $db->sql_query($sql);//search for last login today.
            if($row = $db->sql_fetchrow($result)){//if the user has logged in today update the row. 
                $row_check_in_timestamp = $row['check_in_timestamp'];
                $sql = 'UPDATE ...';//update the row with the check out timestamp
                $db->sql_query($sql);
                break;
            }else{//the user hasn't logged in yet today, log in.
                $start_session_array = array(
                    'club_id'   => (int)$club_id,
                    'member_id' => (int)$member_id,
                    'check_in_timestamp' => (int)time(),
                );
                $sql = 'INSERT ...';//check user in and add a new row in the database
                $db->sql_query($sql);
                break;
            }
        }else{
            break;
        }
Quispie
  • 948
  • 16
  • 30
  • How are you detecting that this code does two requests? Are you debugging the server and see two requests come in or are you watching over Fiddler (or other network monitoring tool)? Also, do you have any authentication mechanism not shown in this code (like basic authentication)? – TylerOhlsen Oct 29 '12 at 14:25
  • @TylerOhlsen: In the JSON is a method which writes a new row in the database at the first call and finds the previous row to update it. The first and the second time it puts a timestamp in the database and saves the diffrence. When I use the C# code it does both actions at once, while it's a if-statement(!). The authentication is all working well, with an api key, that's not a problem. – Quispie Oct 29 '12 at 14:36
  • This might not be your problem, but if you are using basic authentication, [this](http://stackoverflow.com/a/1462417/1370166) could explain why you are getting two requests. (I know this example uses WCF, but WebClient and other http request classes do the same two step authentication) – TylerOhlsen Oct 29 '12 at 14:45
  • Are those methods correctly declared as static? Do they have a legitimate reason to be static? – linkerro Oct 29 '12 at 14:57
  • @TylerOhlsen: I tried the same request with fiddler running and I see just one request, that's the weird part of this problem. – Quispie Oct 29 '12 at 15:02
  • @linkerro: The methods are static because the cardreader methods I use only can call static methods. Why can a static method be a problem for a JSON request? – Quispie Oct 29 '12 at 15:05
  • Because then you end up having problems if you have more than one thread, and the line between who is doing what and is causing what else becomes blurred. Usually statefull static methods cause more problems than they fix. – linkerro Oct 29 '12 at 15:40
  • I agree with @linkerro that statefull static methods are a bad idea. You'll probably want return the request in CreateWebRequest and take in the request as a parameter in CreateWebResponse to fix that. Are you doing anything with threading? – TylerOhlsen Oct 29 '12 at 16:26
  • Also, can you set a breakpoint in your code (both client and server side if you can) and/or watch fiddler closely to see what lines of code are actually hitting the server? – TylerOhlsen Oct 29 '12 at 16:28
  • @linkerro: I changed the methods to a non static field and works, I used this solution: [link](http://stackoverflow.com/questions/1360183/call-non-static-method-from-static-method-c-sharp). – Quispie Oct 30 '12 at 08:18
  • @TylerOhlsen: I only can set a breakpoint in the code. The only place where there's a request is here: using (requestWriter = new StreamWriter(request.GetRequestStream())). This sends an empty body and is filled by: requestWriter.Write(postData); At this point the request is already read by the code. It seems there's no second request, but why does the JSON both the IF and ELSE statement? I don't have multi threading jet, it's a tray application with multiple forms, but only one thread. – Quispie Oct 30 '12 at 08:19
  • I didn't use a breakpoint at the server but just watched the database for changes using breakpoints in the code. The new row is insert when: using (requestWriter = new StreamWriter(request.GetRequestStream())) is activated. The second timestamp is placed when requestWriter.Write(postData); starts. Only adding new StreamWriter(request.GetRequestStream())), doesn't work and new StreamWriter(request.GetRequestStream())).Write(postData); doesn't send the length, but the database input is correct when I use this line. – Quispie Oct 30 '12 at 08:45

1 Answers1

0

SOLVED: I'm sorry every one and thanks for all the responses, but I've found the problem. I had an older version as service running all the time and made the second JSON call.

I've found it by logging on the server side the calls and blocked code which call the JSON in my own code to figure this out.

Quispie
  • 948
  • 16
  • 30