Complete newbie in VS and C#, I am trying to setup a web service, starting by something very simple. I managed to write a class that will (hopefully) return an item’s name, given the item’s code. Now I want to implement this so that it can be called from the web, but I do not know how to retrieve the parameter. The idea is to have http://myurl.com?ProdRef=XYZ, and return the name of product XYZ.
Please don’t shoot, this is my first try with C# and VS !
Edit: working code (for whom it may help)
Class code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for Class1
/// </summary>
class Product
{
public string ProdRef {get; set; }
public string ProdName{get; set; }
public static string GetLabel(string ProdRef)
{
//
// create a new SqlConnection object with the appropriate connection string
SqlConnection sqlConn = new SqlConnection("Data Source=ssss;Initial Catalog=ccccc;Persist Security Info=True;User ID=uuu;Password=pppp;Network Library=dbmssocn");
// open the connection
sqlConn.Open();
// create the command object
SqlCommand sqlComm = new SqlCommand("select libelle from dbo.vwArticlesPerm WHERE Ref = '" + ProdRef + "'", sqlConn);
string strResult = (string)sqlComm.ExecuteScalar();
// close the connection
sqlConn.Close();
return strResult;
}
}
Web service code:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Services;
/// <summary>
/// Summary description for WebService
/// </summary>
[WebService(Namespace = "http://xxxxx.lu/clientwebserv")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
// 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 WebService : System.Web.Services.WebService {
public WebService () {
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetName(string prName) {
return Product.GetLabel(prName);
}
}
I think you should define GetName in this way
When a client app loads your WSDL, xml returned shows that
GetNamefunction wants a string in input and gives back a string. That’s all.Next: don’t build queries manually joining strings, int, dates, use Parameters.
If you want to use
GetLabel, you must addpublicto its declaration or you won’t be able to see it outside its class!Another advise I give you is to use
using(...)when instantiating classes that implementsIDisposableinterface: when execution exits fromusingblock classes are disposed, so you can avoid memory waste and some headache 🙂