Change WebService address at runtime - C #

2

I'm developing an application that should connect to a number of Web services depending on the user's location.

For example :

  

If the user is in the city " A " he will connect to the Web service: 192.168.1.1:8010 if he goes to the city " B ", 192.168.1.1:8020 , in the city " C " 192.168.1.1:8030 , and so on.

     

The address is always the same, what changes is the port.

Simple thing, right ?! Yeah, but I can not make it run at any time!

  

When I change the URL parameter of the Web service at runtime the server only returns null , returning to the original value the communication resets. The same thing if the change is made before the compilation, that is, compile for the city " A ", works in the city " A ", B ", works in the city" B ".

The application was originally developed for Windows CE using VS2008 and CF3.5, but even in VS2013 with .Net Framework 4.0 the "problem" is repeated.

Has anyone ever been through this?

I created a new application just to test the exchange of the server, it follows the code:

WebReference.WSR testeWS = new WebReference.WSR();

private void btn_Troca_URL_Click(object sender, EventArgs e)
{
    if (URL_01)
    {
        testeWS.Url = "http://192.168.1.1:8010/WSR.apw";
        URL_01 = false;
    }
    else
    {
        testeWS.Url = "http://192.168.1.1:8020/WSR.apw";
        URL_01 = true;
    }
}

In this case the original URL (compiled) is "http://192.168.1.1:8010/WSR.apw" and for this URL everything works normally, when I click the button and change to the URL "http://192.168.1.1:8020/WSR.apw" , I only have null as a response. By clicking back and returning to the original URL, everything works again.

If the code is compiled for the URL "http://192.168.1.1:8020/WSR.apw" the "problem" is reversed.

Remembering that the "URL Behavior" property is set to Dynamic.

    
asked by anonymous 19.05.2014 / 16:44

1 answer

1
  • I recommend not adding the reference (Web Service) in your project. This way you will have more control in the code on how to consume this web service.

  • Use WebRequest or a library like RestSharp :

  • Using RestSharp

    //MEU EndPoint
    var endPointRM = "{minha url WS}"
    
    
    var client = new RestClient();
    var request = new RestRequest(endPointRM, Method.POST);
    request.AddParameter("matricula", matricula);
    var usuario = client.Execute<UsuarioRM>(request).Data;
    
    if (usuario != null)
        return new Dictionary<string, object> { { "Nome", usuario.Nome.Trim() }, { "Email", usuario.Email.Trim() } };
    return null;
    

    Using WebRequest

    var response = GetResponseWS(matricula.ToString());
    if (response ==  null)
        return null;
    var usr = ConvertFromStream(response.GetResponseStream());
    
    if (usr != null)
        return new Dictionary<string, object> { { "Nome", usr.Nome.Trim() }, { "Email", usr.Email.Trim() } };
    return null;
    

    And the auxiliary methods:

    private HttpWebResponse GetResponseWS(string matricula)
    {
        byte[] buffer = Encoding.ASCII.GetBytes(GetSoapEnvelope(matricula));
        //Initialization, webrequest
        HttpWebRequest WebReq =
        (HttpWebRequest)WebRequest.Create(endPointRM);
    
        //Set the method/action type
        WebReq.Method = "POST";
    
        //We use form contentType
        WebReq.ContentType = "text/xml; charset=utf-8";
    
        //The length of the buffer
        WebReq.ContentLength = buffer.Length;
    
        //We open a stream for writing the post  data
        Stream MyPostData = WebReq.GetRequestStream();
    
        //Now we write, and after wards, we close. Closing is always important!
        MyPostData.Write(buffer, 0, buffer.Length);
        MyPostData.Close();
    
        //Get the response handle, we have no true response yet!
        WebResponse resp;
        try
        {
            resp = WebReq.GetResponse();
            return (HttpWebResponse)resp;
        }
        catch (WebException wex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(wex);
            return null;
        }
        catch (Exception ex)
        {
            Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            return null;
        }
    }
    
    private string GetSoapEnvelope(string matricula)
    {
        return string.Format(@"<?xml version=""1.0"" encoding=""utf-8""?>
    <soap:Envelope xmlns:xsi=""http://www.w3.org/2001/XMLSchema-instance"" xmlns:xsd=""http://www.w3.org/2001/XMLSchema"" xmlns:soap=""http://schemas.xmlsoap.org/soap/envelope/"">
    <soap:Body>
    <ConsultarInformacoesFuncionarioRmPorMatriculaPorColigada xmlns=""http://www.aec.com.br/"">
    <matricula>{0}</matricula>
    <codColigada>{1}</codColigada>
    <token>{2}</token>
    </ConsultarInformacoesFuncionarioRmPorMatriculaPorColigada>
    </soap:Body>
    </soap:Envelope>", matricula, 3, ConfigurationManager.AppSettings["tokenWS"]);
    }
    
    private UsuarioWS ConvertFromStream(Stream stream)
    {
        var ds = new DataSet();
        ds.ReadXml(new StreamReader(stream), XmlReadMode.ReadSchema);
    
        return new UsuarioWS
        {
            Nome = ds.Tables[0].Rows[0]["NOME"].ToString()
            ,
            Email = ds.Tables[0].Rows[0]["EMAIL"].ToString()
        };
    }
    
        
    26.06.2014 / 23:21