Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8230757
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 7, 20262026-06-07T17:14:23+00:00 2026-06-07T17:14:23+00:00

I m testing how to retrieve data from SQL Server in Web Service. I

  • 0

I m testing how to retrieve data from SQL Server in Web Service. I m using SQL Server 2008 R2, asp.net web service application project template in VS 2010.

Let’s say I have a table that has 4 columns and w/o any constaints(for the sake of conversation).

  • FirstName
  • LastName
  • Email
  • University

I want to be able to get all the values of my SQL table if a user inputs value for FirstName. Later I would change FirstName to NTID or some meaningful column.Right now my web service just returns single value let’s say LastName if a user types in FirstName.

Being a new to web services, I m trying to learn as much as I can and would greatly appreciate your time and effort in helping me out. TIA.

Where/how do I make changes at my code below

Here’s is my Data helper class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;

namespace EmployeeRecs
{
    public class DataHelper
    {
        //create new method to get Employee record based on First Name
        public static string GetEmployee(string firstName)
        {
            string LastName = "";

            //Create Connection
            SqlConnection con = new SqlConnection (@"Data Source=myDBServer;Initial Catalog=MyDataBase;Integrated Security=true;");

            //Sql Command
            SqlCommand cmd = new SqlCommand("Select LastName from Employees where FirstName ='" + firstName.ToUpper() + "'", con);

            //Open Connection
            con.Open();

            //To Read From SQL Server
            SqlDataReader dr = cmd.ExecuteReader();

                while (dr.Read())
                {
                    LastName = dr["LastName"].ToString();
                }

            //Close Connection
                dr.Close();
                con.Close();

            return LastName;


        }

    }
}

And here’s my asmx.cs class

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;

namespace EmployeeRecs
{
    /// <summary>
    /// Summary description for Service1
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.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
    {

               //Create new web method to get Employee last name
        [WebMethod]
        public string GetEmployee(string firstName)
        {
            return DataHelper.GetEmployee(firstName);

        }
    }
}
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-07T17:14:25+00:00Added an answer on June 7, 2026 at 5:14 pm

    Besides the SQL injection, a few things:

    Create a DataContract and create a model for the data you want to return

    [DataContract]
    public class Employee
    {
        [DataMember]
        public int NTID { get; set; }
    
        [DataMember]
        public string LastName { get; set; }
    
        [DataMember]
        public int FirstName { get; set; }
    }
    

    Fill that model with your SQL Query results and return it from your service

        //create new method to get Employee record based on First Name
        public static List<Employee> GetEmployee(string firstName)
        {
            //Create Connection
            SqlConnection con = new SqlConnection (@"Data Source=myDBServer;Initial Catalog=MyDataBase;Integrated Security=true;");
    
            //Sql Command
            SqlCommand cmd = new SqlCommand("Select NTID, LastName, FirstName from Employees where FirstName ='" + firstName.ToUpper() + "'", con);
    
            //Open Connection
            con.Open();
    
            List<Employee> employees = new List<Employee>();
    
            //To Read From SQL Server
            SqlDataReader dr = cmd.ExecuteReader();
    
            while (dr.Read())
            {
                var employee = new Employee { 
                           NTID = dr["NTID"].ToString();
                           LastName = dr["LastName"].ToString();
                           FirstName = dr["FirstName"].ToString();
                        };
                employees.Add(employee);
            }
            //Close Connection
            dr.Close();
            con.Close();
            return employees;
    }
    

    Expose it:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Web;
    using System.Web.Services;
    
    namespace EmployeeRecs
    {
        /// <summary>
        /// Summary description for Service1
        /// </summary>
        [WebService(Namespace = "http://tempuri.org/")]
        [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
        [System.ComponentModel.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
        {
    
                   //Create new web method to get Employee last name
            [WebMethod]
            public List<Employee> GetEmployee(string firstName)
            {
                return DataHelper.GetEmployee(firstName);
    
            }
        }
    }
    

    Full Code from OP for posterity:

    This might be useful to other folks struggling with the same situation. So I m posting my code for the solution:
    Create a new WCF PRoject in VS 2010, I used .net version 3.5 and selected WCF Service Library under WCF template.

    Here’s my code under IService1.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Runtime.Serialization; 
    using System.ServiceModel; 
    using System.Text; 
    
    namespace WcfServiceLibrary1 
    { 
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together. 
        [ServiceContract] 
        public interface IService1 
        { 
            [OperationContract] 
            List<Employee> GetEmployee(string firstName); 
    
    
            [OperationContract] 
            CompositeType GetDataUsingDataContract(CompositeType composite); 
    
            // TODO: Add your service operations here 
        } 
    
    
        //Custon Data contract 
    
        [DataContract] 
        public class Employee 
        { 
            [DataMember] 
            public string FirstName { get; set; } 
    
            [DataMember] 
            public string LastName { get; set; } 
    
            [DataMember] 
            public string Email { get; set; } 
    
            [DataMember] 
            public string University { get; set; } 
    
        }  
    
    
    
        // Use a data contract as illustrated in the sample below to add composite types to service operations 
        [DataContract] 
        public class CompositeType 
        { 
            bool boolValue = true; 
            string stringValue = "Hello "; 
    
            [DataMember] 
            public bool BoolValue 
            { 
                get { return boolValue; } 
                set { boolValue = value; } 
            } 
    
            [DataMember] 
            public string StringValue 
            { 
                get { return stringValue; } 
                set { stringValue = value; } 
            } 
        } 
    } 
    

    And here’s my code under Service1.cs

    using System; 
    using System.Collections.Generic; 
    using System.Linq; 
    using System.Runtime.Serialization; 
    using System.ServiceModel; 
    using System.Text; 
    using System.Data; 
    using System.Data.SqlClient; 
    
    namespace WcfServiceLibrary1 
    { 
        // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in both code and config file together. 
        public class Service1 : IService1 
        { 
            public List<Employee> GetEmployee(string firstName)  
    
            { 
                //Create Connection  
                SqlConnection con = new SqlConnection(@"Data Source=gsops4;Initial Catalog=MultiTabDataAnalysis;Integrated Security=true;"); 
    
                //Sql Command  
                SqlCommand cmd = new SqlCommand("Select LastName, FirstName, Email, University from Employees where FirstName ='" + firstName.ToUpper() + "'", con); 
    
                //Open Connection  
                con.Open(); 
    
                List<Employee> employees = new List<Employee>(); 
    
                //To Read From SQL Server  
                SqlDataReader dr = cmd.ExecuteReader();  
    
    
                while (dr.Read())  
            {  
                var employee = new Employee {   
    
                           FirstName = dr["FirstName"].ToString(),  
                           LastName = dr["LastName"].ToString(), 
                           Email = dr["Email"].ToString(), 
                           University = dr["University"].ToString() 
    
    
    
                        };  
                employees.Add(employee);  
            }  
            //Close Connection  
            dr.Close();  
            con.Close();  
            return employees; 
    
            } 
    
            public CompositeType GetDataUsingDataContract(CompositeType composite) 
            { 
                if (composite == null) 
                { 
                    throw new ArgumentNullException("composite"); 
                } 
                if (composite.BoolValue) 
                { 
                    composite.StringValue += "Suffix"; 
                } 
                return composite; 
            } 
        } 
    } 
    
    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I want to analyze an SQL Server stored procedure from .NET code to retrieve
In my ASP.Net MVC application I am using IoC to facilitate unit testing. The
I have a .NET 3.5 Windows Service. I'm testing with a small application that
I need to call a web and retrieve the resulting data from the model
I use an asynchronous process to retrieve data from a long running SQL query.
I'm using Dojo toolkit to get data from an external JSON source (a web
from 1 week if my gps app fail to retrieve signal (eg: testing in
When sql server is receiving two queries (SELECT * From the_Same_Table), at exactly the
I am trying to retrieve data from mysql then display it on android listview.
I am trying to retrieve some data using a combination of jQuery and CakePHP.

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.