Parth Doshi
Parth Doshi

Reputation: 4208

Web Service code not returning array of String

I want to return an array of Strings in the form "abc#xyz#ghi#tru" (where # is delimiter) from my web service method . However i m not able to do it . Here is my current web service code :

using System;
using System.Collections;
using System.ComponentModel;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Data.SqlClient;

namespace WebService10
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [ToolboxItem(false)]
    // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment
 the following line. 
    // [System.Web.Script.Services.ScriptService]
    public class Service1 : System.Web.Services.WebService
    {
        String[] result=new String[40];
        String[] result2 = new String[40];

        [WebMethod]
        public String[] getData()
        {
            SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
            try
            {
                myConnection.Open();

                SqlCommand myCommand = new SqlCommand();
                myCommand.Connection = myConnection;
                myCommand.CommandText = "select count(*) from names where name =@name";

                SqlDataReader myReader = myCommand.ExecuteReader();

                //while
                for(int i=0;i<40;i++)
                {
                    if (myReader.Read())
                    {
                         result[i]= myReader["name"].ToString();
                         result2[i] = result[i] + "#";
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            finally
            {
                myConnection.Close();
            }

            return result2;
        }
    }
}

Can anyone tell me what's wrong with my code ?

Upvotes: 0

Views: 3721

Answers (3)

Denis Mitropolskiy
Denis Mitropolskiy

Reputation: 71

First, your query returns only number instead of set of rows. So you should use sql like this:

select name from names

Second, to return array you could use List instead of pre-defined arrays: I would be use the following approach:

var result = new List<string>();
while(myReader.Read())
{
  result.Add(reader["name"].ToString() + "#");
}

return result.ToArray();

Or if you want to return a string:

return string.Join("#", result.ToArray())

Upvotes: 1

Emond
Emond

Reputation: 50672

Try this:

I changed the query (BTW: the query still doesn't make much sense but I do not know what you really want), the resulting type and the loop.

You forgot to pass the parameter to the query too.

Also: change the exception handling; writing to the console on the server side is not a good idea.

public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    public String getData(string nameFilter)
    {
        String result = "";

        SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
        try
        {
            myConnection.Open();

            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText = "select name from names where name =@name";
            myCommand.Parameters.AddWithValue("@name", nameFilter);
            SqlDataReader myReader = myCommand.ExecuteReader();

            while(myReader.Read())
            {
                if(result.Length > 0)
                {
                    result += "#";
                }
                result += myReader["name"].ToString();
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            myConnection.Close();
        }

        return result;
    }
}

EDIT

I'd prefer a different approach:

public class Service1 : System.Web.Services.WebService
{

    [WebMethod]
    public String[] getData(string nameFilter)
    {
        var names = new List<string>();
        SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
        try
        {
            myConnection.Open();

            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText = "select name from names where name = @name";
            myCommand.Parameters.AddWithValue("@name", nameFilter);
            SqlDataReader myReader = myCommand.ExecuteReader();

            while(myReader.Read())
            {
                names.Add(myReader["name"].ToString());
            }
        }
        catch (Exception ex)
        {
            //Console.WriteLine(ex.Message);
        }
        finally
        {
            myConnection.Close();
        }

        return names.ToArray();
    }
}

Upvotes: 2

kleinohad
kleinohad

Reputation: 5912

 [WebMethod]
    public string getData()//changed to return string
    {

        SqlConnection myConnection = new SqlConnection(@"Data Source=.\SQLEXPRESS;Initial Catalog=student;User ID=sa;Password=123");
        try
        {
            myConnection.Open();

            SqlCommand myCommand = new SqlCommand();
            myCommand.Connection = myConnection;
            myCommand.CommandText = "select name from names";//you can make it select distinct

            SqlDataReader myReader = myCommand.ExecuteReader();
            string toReturn = "";
            while(myReader.Read())
            {
                if (myReader.Read())
                {
                     toReturn += myReader["name"].ToString() + "#";
                }
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }
        finally
        {
            myConnection.Close();
        }

        return toReturn; //# as delimiter
    }

Upvotes: 2

Related Questions