Download the free trial version
Basic4android Video
Features
Tutorials and manuals
Showcase
Screenshots

Go Back   Android Development Forum - Basic4android > Basic4android > Basic4android Getting started & Tutorials
Documentation Wiki Register Members List Windows Mobile Search Today's Posts Mark Forums Read

Basic4android Getting started & Tutorials Android development starts here. Please do not post questions in this sub-forum.

Connect Android to MS SQL Server Tutorial

Reply
 
LinkBack Thread Tools Display Modes
  #1 (permalink)  
Old 12-11-2011, 01:31 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,859
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default Connect Android to MS SQL Server Tutorial

This tutorial is a follow up to the previous tutorial that explained how to connect to a MySQL database using a PHP web service. This time we will use an ASP.NET web service to connect to a Microsoft SQL Server.

Android cannot directly connect to the database server. Instead we will use HttpUtils to connect to a simple ASP.NET script that will issue the query and return the result as a JSON string.

There are several possible solutions for the web service implementation:
1. Pre-set the possible queries in the ASP script and then choose one of the queries by setting a parameter in the Http request.
2. Pass the query as-is to the database.

While the second solution is more flexible and doesn't require any changes to the ASP.NET script, it can also be more vulnerable to security attacks. For example a hacker can send a "DROP TABLE" query and erase all the data.
Making the database user a "read-only" user will protect this attack.

In this tutorial I will post the ASP.NET script that handles any query and passes it directly to the server. You can of course modify it and make it support only a set of queries.

ASP.NET code:
Code:
<%@ Page Language="C#"%>
<%@ Import Namespace=
"System.Collections.Generic" %>
<%@ Import Namespace=
"System.Data" %>
<%@ Import Namespace=
"System.Data.SqlClient" %>
<%@ Import Namespace=
"System.IO" %>
<%@ Import Namespace=
"System.Web.Script.Serialization" %>

<!DOCTYPE html 
PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat=
"server">
    protected void Page_Load(
object sender, EventArgs ec)
    {
        using (SqlConnection cn = new SqlConnection(
"Database=Test1; User Id=UserName; password=Password")) //change as needed
        {
            using (StreamReader sr = new StreamReader(Request.InputStream, Encoding.UTF8))
            {
                Response.ContentType = 
"text/plain";
                
string c;
                c = Request.QueryString[
"query"]; //for debugging with the browser 
                //you can set the query by adding the query parameter  
For ex: <a href="http://127.0.0.1/test.aspx?query=select" target="_blank">http://127.0.0.1/test.aspx?query=select</a> * from table1
                
if (c == null)
                    c = sr.ReadToEnd();
                
try
                {
                    SqlCommand cmd = new SqlCommand(c, cn);
                    cn.Open();
                    SqlDataReader rdr = cmd.ExecuteReader(CommandBehavior.CloseConnection);
                    
List<Dictionary<stringobject>> list = new List<Dictionary<stringobject>>();
                    
while (rdr.Read())
                    {
                        Dictionary<
stringobject> d = new Dictionary<stringobject>(rdr.FieldCount);
                        
for (int i =0;i < rdr.FieldCount;i++)
                        {
                            d[rdr.GetName(i)] = rdr.GetValue(i);
                        }
                        
list.Add(d);
                    }
                    JavaScriptSerializer j = new JavaScriptSerializer();
                    Response.Write(j.Serialize(
list.ToArray()));
                    
                } 
catch (Exception e)
                {
                    Response.TrySkipIisCustomErrors = 
true;
                    Response.StatusCode = 
500;
                    Response.Write(
"Error occurred. Query=" + c + "\n");
                    Response.Write(e.ToString());
                    
                }
                Response.End();
            }
        }
    }
</script>
This code depends on System.Web.Extensions.dll.
To use this code you should save it as a file with aspx extension and modify the connection string with your values.
You may need to put System.Web.Extensions.dll in the bin folder (you will get a compilation error when the script runs if it is required and missing).


Before trying to connect from the Basic4android program, it is recommended to test that the script is working by calling it from the browser. It will be easier to read the error message this way. To help with debugging you can send the query as a GET parameter (later it will be sent as the payload).
Code:
http://www.example.com/test1.aspx?query=select * from table_1


Now for Basic4android program:
Code:
Sub Process_Globals
    
Dim ServerUrl As String
    ServerUrl = 
"http://www.example.com/test1.aspx"
End Sub

Sub Globals

End Sub

Sub Activity_Create(FirstTime As Boolean)
    
If FirstTime Then
        HttpUtils.CallbackActivity = 
"Main"
        HttpUtils.CallbackJobDoneSub = 
"JobDone"
    
End If
        
    HttpUtils.PostString(
"Job1", ServerUrl, "SELECT col1, col2 FROM Table_1")
End Sub

Sub Activity_Resume
    
If HttpUtils.Complete = True Then JobDone(HttpUtils.Job)
End Sub

Sub Activity_Pause (UserClosed As Boolean)
    
End Sub

Sub JobDone (Job As String)
    
If HttpUtils.IsSuccess(ServerUrl) Then
        
Dim parser As JSONParser
        
Dim response As String
        response = HttpUtils.GetString(ServerUrl)
        parser.Initialize(response)
        
Dim rows As List
        rows = parser.NextArray
        
        
'work with result
        'rows is a List. Each item is a Map with the columns names as keys and the db values as the values.
        For i = 0 To rows.Size - 1
            
Log("Rows #" & i)
            
Dim m As Map
            m = rows.Get(i)
            
Log("col1=" & m.Get("col1")) 'log the values of col1 and col2
            Log("col2=" & m.Get("col2"))
        
Next
    
End If
    HttpUtils.Complete = 
False
End Sub
This is the main activity code. Calling HttpUtils.PostString sends the request. When the request completes, Sub JobDone will be executed. After parsing the response with JSON parser we get a List. Each item in the list represents a row in the results set. Each item is a Map with the column names as keys and the db values as values.

When running the example, make sure to check the logs. Errors will be posted there.

The logs after a successful run:
Code:
** Activity (main) Resume **
** Service (httputilsservice) Create **
** Service (httputilsservice) Start **
Rows #
0
col1=
23
col2=asdasd
Rows #
1
col1=
12323
col2=dwqd
Rows #
2
col1=
0
col2=
1
Rows #
3
col1=
0
col2=
1
** Service (httputilsservice) Destroy **
Attached Files
File Type: zip MsSQL.zip (8.3 KB, 901 views)
Reply With Quote
  #2 (permalink)  
Old 12-19-2011, 02:38 PM
Junior Member
 
Join Date: Oct 2011
Posts: 29
Default asp

can this be done using ASP (not .net)?
Thanx
Reply With Quote
  #3 (permalink)  
Old 12-19-2011, 03:18 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,859
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

If you can access the server from ASP then you should be able to create a similar ASP script that passes the query to the server and returns the result. I'm not familiar with ASP at all so I don't really know.
Reply With Quote
  #4 (permalink)  
Old 01-12-2012, 08:41 PM
Newbie
 
Join Date: Dec 2011
Posts: 2
Default Undeclared variable 'httputils'

Yes to classic asp. aspjson - JSON for ASP - Google Project Hosting

I am getting a compile error. Any idea what is wrong? All I've done is copy it down and made no changes.

Compiling code. Error
Error parsing program.
Error description: Undeclared variable 'httputils' is used before it was assigned any value.
Occurred on line: 13
HttpUtils.CallbackActivity = "Main"
Reply With Quote
  #5 (permalink)  
Old 01-13-2012, 05:31 AM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,859
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

This project requires HttpUtils (a code module and a service). It is included in the attached example.
Reply With Quote
  #6 (permalink)  
Old 01-26-2012, 06:24 AM
Junior Member
 
Join Date: Jul 2009
Posts: 43
Default HttpUtils cant run in Another Activity

HttpUtils run correct if in main activity.

if you write same code second activity, Http Job never done.

I cant find why this was.
Reply With Quote
  #7 (permalink)  
Old 01-26-2012, 12:00 PM
Erel's Avatar
Administrator
 
Join Date: Apr 2007
Posts: 25,859
Awards Showcase
Basic4ppc Founder 
Total Awards: 1
Default

You should change this line with the name of the second activity:
Code:
HttpUtils.CallbackActivity = "Main"
Reply With Quote
  #8 (permalink)  
Old 01-30-2012, 03:22 PM
Junior Member
 
Join Date: Jan 2012
Posts: 26
Default

Hi, I'm having some issues with this demo ... I'm essentially cutting and pasting code to my own project. The demo will compile - my code won't.

The error I'm getting is:

Error parsing program.
Error description: Unknown type: jsonparser
Are you missing a library reference?
Occurred on line: 34
Dim parser As JSONParser

both parser and JSONParser are RED in my source code (they are not in the demo's source code).

I looked at my source code in a text editor and the demo source code.

In the demo source code (text) it has:

Library1=core
Library2=http
Library3=json

In mine? It only has

Library1=core

I have added the two HTTP modules to my project already.

Any help? I guess I COULD just copy and paste those lines in a text editor, but I'd rather understand the big picture.

Thank you!
Reply With Quote
  #9 (permalink)  
Old 01-30-2012, 03:30 PM
Junior Member
 
Join Date: Jan 2012
Posts: 26
Default

I figured it out ... I had to CHECK the boxes next to HTTP and JSON in the LIBRARIES tab ...

I'll get this yet!
Reply With Quote
  #10 (permalink)  
Old 02-02-2012, 07:47 PM
Junior Member
 
Join Date: Jan 2012
Location: Laguna Hills Mall
Posts: 17
Default

I am using the HttpUtilsService and trying to change the original code so instead of sending a query statement like:

http://192.168.1.103:81/test.aspx?query=select * from status

now I can send tokens like this:

http://192.168.1.103:81/test.aspx?qu...mer&name=smith

Any ideas, on how to change and add more parameters?


UPDATE:
Never mind... found my solution.....

My issue was in my ASP.NET website... in order to read my new parameter names, I need to use :

sRequestType = Request.Params["key1"];

and not

sRequestType = Request.QueryString["key1"];



Robert J.

Last edited by RobertJurado : 02-03-2012 at 02:11 PM. Reason: found a solution
Reply With Quote
Reply


Currently Active Users Viewing This Thread: 1 (0 members and 1 guests)
 
Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Trackbacks are Off
Pingbacks are Off
Refbacks are On

Similar Threads
Thread Thread Starter Forum Replies Last Post
Connect Android to MySQL Database Tutorial Erel Basic4android Getting started & Tutorials 269 04-30-2013 07:40 PM
B4AServer - Simple way to connect Android devices to a desktop server Erel Basic4android Updates and Questions 18 03-02-2012 05:11 AM
I can't connect to Mysql in my own server ruy Basic4android Updates and Questions 1 03-31-2011 08:07 PM
connect to mysql server from device encolo Questions (Windows Mobile) 5 08-30-2010 04:50 PM
with basi4ppc (device) can we connect to SQL SERVER (situated on a pc) ? gecomail Questions (Windows Mobile) 2 11-24-2008 08:52 PM


All times are GMT. The time now is 08:43 AM.


Powered by vBulletin® Version 3.6.12
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.
Search Engine Friendly URLs by vBSEO 3.3.0