Web service in ASP.NET

kormos

Member
Licensed User
Longtime User
I would like to have some help about this library. I am an ASP.NET programmer and I have made a web service. I try to use it through basic4android but for some reason I can not make it work. I would like to have some help if it is possible. I want to call a web method using the following parameters:

Web Service URL : http://localhost:999/Contacts.asmx
Web Method : Contacts_Select
Parameter : ContactID

Can someone tell me how to access this web method using a POST request from the web service and store the output of the web method in a string variable.

Thanks in advance.
 

kormos

Member
Licensed User
Longtime User
I have used various ways that I found in the forum but nothing worked. I probably make some kind of mistake in my code.

I will show you 2 different approaches that I tried to access the service but both of them does not work for some reason.

The first method

B4X:
'Activity module
Sub Process_Globals
   'These global variables will be declared once when the application starts.
   'These variables can be accessed from all modules.

End Sub

Sub Globals
   'These global variables will be redeclared each time the activity is created.
   'These variables can only be accessed from this module.

End Sub

Sub Activity_Create(FirstTime As Boolean)
   Dim url As String
   Dim myHttpRequest As HttpRequest
   url = "http://localhost:999/Contacts.asmx/Contacts_Select"
   Dim str() As Byte
   Dim form As String
   form = "ContactID=2"
   str = form.GetBytes("UTF8")
   myhttprequest.InitializePost2(url,str)
   myHttpRequest.Timeout = 5000
   If sock.Execute(myHttpRequest,1) = False Then 
      'Something went wrong
      Return
   End If
End Sub

Sub Activity_Resume

End Sub

Sub Activity_Pause (UserClosed As Boolean)

End Sub

The second Method

B4X:
 'Activity module
Sub Process_Globals
   Dim PostUrl As String
   PostUrl = "http://localhost:999/Contacts.asmx/Contacts_Select"
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
   HttpUtils.CallbackActivity = "Main"
   HttpUtils.CallbackJobDoneSub = "JobDone"
   HttpUtils.CallbackUrlDoneSub = "UrlDone"
   
   HttpUtils.PostString("POST Job1", PostUrl, "ContactID=2")
End Sub

Sub Activity_Resume
   'Check whether a job has finished while the activity was paused.
   If HttpUtils.Complete = True Then JobDone(HttpUtils.Job)
End Sub

Sub UrlDone(Url As String)
   Log(Url & " done")
End Sub

Sub JobDone (Job As String)
   Select Job
      Case "POST Job1"
         If HttpUtils.IsSuccess(PostUrl) Then
            Log(HttpUtils.GetString("http://localhost:999/Contacts.asmx/Contacts_Select"))
         End If
   End Select
   HttpUtils.Complete = False 'Turn off the complete flag so we won't handle it again if the activity is resumed.
End Sub

For the first method I do not know how to access the returned data and for the second the HttpUtils.IsSuccess(PostUrl) returns false.

I want to find the right way to call a service because most of the projects that I am going to develop will use services to collect data.
 
Upvote 0

kormos

Member
Licensed User
Longtime User
The service is hosted in my computer. I have installed the IIS. Is this the reason that it does not work? Should I put it on a public server?
 
Upvote 0

kormos

Member
Licensed User
Longtime User
This was the problem. I placed the service on a public web server and the service works. I just want to ask a question about the UrlDone event. When does it executed and what is the reason that we use it?

I also would like to know how to identify if an error occures during the service request. When I had it on my computer, there was not any message. This means that the HttpUtils library informed me somehow but how can I get informed about the error?

Thanks for your help.
 
Upvote 0

kormos

Member
Licensed User
Longtime User
Erel thanks you very much. You are perfect. Before I start using the basic4android I was trying to make the same program using rhomobile. I spent more than 2 weeks trying to access my web service without solving my problem. Using basic4android I made it in no time with your help.

Thanks you.
 
Upvote 0

ttsolution

Member
Licensed User
Longtime User
how to call asmx webservice with parameters and return a datatable

Hi everyone, i am new to b4a. Iam seeking your help for the followings matters

I have a asmx web service method as follow

Method name: getstaff(mdeparthmentid) as datatable

How can i call this method to get a list of staff of a department then show in a list view?

many for your help

Jonh,
 
Upvote 0

kanaida

Active Member
Licensed User
Longtime User
I've taken the easier route :)

add a .ashx http handler to give back more simple info back to your android app. Instead of getting back a nasty xml data table, convert it to something easier to parse like a text file. Use a unique delimiter character that doesn't appear in your data to separate columns. (the example below is just a single column table pretty much)

B4X:
<%@ WebHandler Language="VB" Class="mobile" %>

Imports System
Imports System.Web
Imports System.Xml
Imports System.Xml.Linq
Imports System.Data

Public Class mobile : Implements IHttpHandler
    Dim QM As New lib_FoxPro.QueryManager
    
    Public Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
        context.Response.ContentType = "text/plain"
        Dim Action = context.Request.Params("a")
        Dim Company = context.Request.Params("c")
        Select Case Action
    Case 1
                Dim SQL As String = "SELECT pat_code from pat_tab where NOT pat_disc ='Y' order by pat_code"
                Dim DT = QM.GetTable(Company, SQL)
                Dim L As New List(Of String)
                For Each R As Datarow In DT.Rows
                    L.Add(R("pat_code").trim)
                Next
                Dim Result = Strings.Join(L.ToArray, vbLf)
                context.Response.Write(Result)
End Select

End Sub
 
Public ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property

End Class

Then I just call:
B4X:
Dim job1 As HttpJob
   job1.Initialize("GetStyles", Me)
   job1.Download("http://ws.somewhere.com/SomeWebService/mobile.ashx?a=1&c=1137")

Then i take that text i saved to a text file (cache lol) and load it:
B4X:
Dim StyleList As List = File.ReadList(File.DirInternal,"styles.txt")

Then For each line.... do stuff().

For multiple columns, just regex.split() using your delimiter and remember the position of the columns. If you have the web service already working just write the wrapper. I just went raw sql in my example since I had no web service in the back end that was already written.

If you want to get fancy, Gzip the text before sending it to the mobile device, then UnGzip before processing. That = >CPU Usage but < Network Usage + >Speed (depends on amount of data)
 
Last edited:
Upvote 0

AbbasMohammed

Member
Licensed User
Longtime User
Help on (Hellow world) method

Dear Erel,
iam trying to access the web service below without any success.the web service is (in vb.net 2008) :

Imports System.Web.Services
Imports System.Web.Services.Protocols
Imports System.ComponentModel

' To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line.
' <System.Web.Script.Services.ScriptService()> _
<System.Web.Services.WebService(Namespace:="http://tempuri.org/")> _
<System.Web.Services.WebServiceBinding(ConformsTo:=WsiProfiles.BasicProfile1_1)> _
<ToolboxItem(False)> _
Public Class WebService1
Inherits System.Web.Services.WebService

<WebMethod()> _
Public Function HelloWorld() As String
Return "Hello World"
End Function

End Class


and the b4a code is :

job2.Initialize("Job2", Me)

job2.PostString("http://yamiyami.no-ip.biz/WebService1.asmx/HelloWorld"," ")

and the log is:

** Activity (main) Create, isFirst = true **


** Activity (main) Resume **


** Service (httputils2service) Create **


** Service (httputils2service) Start **


<html>



<head>

<title>Runtime Error</title>

<style>

body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;}

p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}

b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}

H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }

H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }

pre {font-family:"Lucida Console";font-size: .9em}

.marker {font-weight: bold; color: black;text-decoration: none;}

.version {color: gray;}

.error {margin-bottom: 10px;}

.expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }

</style>

</head>



<body bgcolor="white">



<span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>



<h2> <i>Runtime Error</i> </h2></span>





<font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">



<b> Description: </b>An application error occurred on the server. The current custom error settings for this application prevent the details of the application error from being viewed remotely (for security reasons). It could, however, be viewed by browsers running on the local server machine.

<br><br>



<b>Details:</b> To enable the details of this specific error message to be viewable on remote machines, please create a &lt;customErrors&gt; tag within a &quot;web.config&quot; configuration file located in the root directory of the current web application. This &lt;customErrors&gt; tag should then have its &quot;mode&quot; attribute set to &quot;Off&quot;.<br><br>



<table width=100% bgcolor="#ffffcc">

<tr>

<td>

<code><pre>



&lt;!-- Web.Config Configuration File --&gt;



&lt;configuration&gt;

&lt;system.web&gt;

&lt;customErrors mode=&quot;Off&quot;/&gt;

&lt;/system.web&gt;

&lt;/configuration&gt;</pre></code>



</td>

</tr>

</table>



<br>



<b>Notes:</b> The current error page you are seeing can be replaced by a custom error page by modifying the &quot;defaultRedirect&quot; attribute of the application's &lt;customErrors&gt; configuration tag to point to a custom error page URL.<br><br>



<table width=100% bgcolor="#ffffcc">

<tr>

<td>

<code><pre>



&lt;!-- Web.Config Configuration File --&gt;



&lt;configuration&gt;

&lt;system.web&gt;

&lt;customErrors mode=&quot;RemoteOnly&quot; defaultRedirect=&quot;mycustompage.htm&quot;/&gt;

&lt;/system.web&gt;

&lt;/configuration&gt;</pre></code>



</td>

</tr>

</table>



<br>



</body>

</html>

JobName = Job2, Success = false
Error: Internal Server Error

:sign0105:
 
Upvote 0

AbbasMohammed

Member
Licensed User
Longtime User
:sign0144:
Dear Erel,
Iam new in this field and it would be easier for me to use the same method you have used in (CelsiusToFahrenheit) as shown below, so i wonder if i changed the web service to WCF can i make similer( HttpUtility.poststring )method

Sub Process_Globals
Dim PostUrl As String
PostUrl = "http://www.w3schools.com/webservices/tempconvert.asmx/CelsiusToFahrenheit"
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
HttpUtils.CallbackActivity = "Main"
HttpUtils.CallbackJobDoneSub = "JobDone"
HttpUtils.PostString("POST Job1", PostUrl, "Celsius=123")
End Sub

Sub Activity_Resume
'Check whether a job has finished while the activity was paused.
If HttpUtils.Complete = True Then JobDone(HttpUtils.Job)
End Sub

Sub JobDone (Job As String)
If HttpUtils.IsSuccess(PostUrl) Then
Msgbox(HttpUtils.GetString(PostUrl), "")
Else
ToastMessageShow("Error sending request", True)
End If
HttpUtils.Complete = False 'Turn off the complete flag so we won't handle it again if the activity is resumed.
End Sub
 
Upvote 0

AbbasMohammed

Member
Licensed User
Longtime User
Dear Erel,
in another thread (which i found more suitable to my subject) i have post my example their and i am trying to get the capital for Spain country, so i think your reply will be very helpful there.
Note: the thread title is ( SOAP textbox info )
 
Upvote 0
Top