Passing lot of parameters into Web Service - c#

I have a web service in ASP.NET a simple one but the web method takes 5 parameters. Is there any other way to pass the parameters? like array or list?. I would like to limit it to 3.
I tried SetMethod(string param) and dint work.
Thanks.

Why don't you create a Class that has those parameters as it's properties, then you would pass an instance of the class as a parameter to the web method.
Changing something like this..
[WebMethod]
public void SomeMethod(string param1, string param2, string param3)
{
//some code
}
to something like this...
[WebMethod]
public void SomeMethod(SomeClass myClass)
{
//some code
}
public class SomeClass
{
public string Param1 { get; set; }
public string Param2 { get; set; }
public string Param3 { get; set; }
}
and you would use it like so...
SomeClass myClass = new SomeClass();
myClass.Param1 = "some data";
myClass.Param2 = "more data";
myClass.Param3 = "even more";
// make the webservice call
someObject.SomeMethod(myClass);

List<Student> list = new List<Student>();
[WebMethod]
public string InsertUserDetails(Student userInfo)
{
list.Add(userInfo);
//string Message;
SqlConnection con = new SqlConnection("Data Source=.;Initial Catalog=Sample;Integrated Security=True");
con.Open();
foreach (Student s in list)
{
SqlCommand cmd = new SqlCommand("insert into userdetail(username,password,country,email) values(#UserName,#Password,#Country,#Email)", con);
cmd.Parameters.AddWithValue("#UserName", userInfo.UserName);
cmd.Parameters.AddWithValue("#Password", userInfo.Password);
cmd.Parameters.AddWithValue("#Country", userInfo.Country);
cmd.Parameters.AddWithValue("#Email", userInfo.Email);
int result = cmd.ExecuteNonQuery();
}
//if (result == 1)
//{
// Message = userInfo.UserName + " Details inserted successfully";
//}
//else
//{
// Message = userInfo.UserName + " Details not inserted successfully";
//}
//con.Close();
// return Message;
return "done";
}
you can do like this>>>>>>>>>>>>>

Related

How to get many field on the Query of webservice

I am making a web service get data from sql server. I need to get many fields from the sql server, but I can only get one field, which is the Currancy Name
namespace WebApplication2
{
public class DataHelper
{
public static string GetCurrency(string currencyCode)
{
string currencyName = "";
SqlConnection con = new SqlConnection(#"Data Source=WEB3\SHAREPOINT;Initial Catalog=WSS_Search_WEB3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select PO_NUMBER,PO_STATUS from View_1 where PO_HEADER_ID ='" + currencyCode.ToUpper() + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
currencyName = dr["PO_NUMBER"].ToString();
}
dr.Close();
con.Close();
return currencyName;
}
}
}
I need to get the PO_Number & PO Status from the Query
As I understand you need to return not only PO_NUMBER, but also PO_STATUS, and as I understand you want to return both values.
I suggest you make model that represent what you want to return.
So for that we make a model class call it for instance POModel:
public class POModel
{
public string currencyName { get; set; } // PO_Number
public string statusName { get; set; } // PO_Status
}
Than fetch the values from SQL as you did and return object in stead of string.
Here would you final code looks like, of course naming and all the stuff you can change the way if fits best:
public class DataHelper
{
public static POModel GetCurrency(string currencyCode)
{
//string currencyName = "";
var poModel = new POModel();
SqlConnection con = new SqlConnection(#"Data Source=WEB3\SHAREPOINT;Initial Catalog=WSS_Search_WEB3;Integrated Security=True");
SqlCommand cmd = new SqlCommand("select PO_NUMBER,PO_STATUS from View_1 where PO_HEADER_ID ='" + currencyCode.ToUpper() + "'", con);
con.Open();
SqlDataReader dr = cmd.ExecuteReader();
while (dr.Read())
{
poModel.currencyName = dr["PO_NUMBER"].ToString();
poModel.statusName = dr["PO_STATUS"].ToString();
}
dr.Close();
con.Close();
//return currencyName;
return poModel;
}
}
public class POModel
{
public string currencyName { get; set; }
public string statusName { get; set; }
}
One option is to return an array that contains the two values. Notice string[]:
public static string[] GetCurrency(string currencyCode)
Similar to how you declared string currencyName = "";, instead make an array variable:
string[] poData = new string[2];
Since this looks like it should return a single row, I would not loop. Just do a Read():
dr.Read();
poData[0] = dr["PO_NUMBER"].ToString(); //poData[] will have to be declared in your method
poData[1] = dr["PO_STATUS"].ToString();
....
return poData;

Is there a way i can reuse this code in C#

Is there a way i can reuse this codes in executing SQL transaction, i want to make it a method so i can put parameters to execute other stored procedures,
can you guys help me to design a good coding structure?
try {
using (SqlConnection con = new SqlConnection(connectionString))
{
using (SqlCommand cmd = new SqlCommand("InsertUser2Sp", con) {
CommandType = CommandType.StoredProcedure
}) {
cmd.Parameters.AddWithValue("#UserID", useridStr);
cmd.Parameters.AddWithValue("#Firstname", firstnStr);
cmd.Parameters.AddWithValue("#Middlename", middleNstr);
cmd.Parameters.AddWithValue("#Lastname", lastnStr);
cmd.Parameters.AddWithValue("#UserAge", ageInt);
cmd.Parameters.AddWithValue("#HomeAddress", homeaddStr);
con.Open();
cmd.ExecuteNonQuery();
}
}
} catch (Exception ex) {
MessageBox.Show("Could not connect to database. Check settings. " + ex.Message, "Connection Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
MessageBox.Show(ex.Message);
}
}
I will share a generic method here . All you need to do is to build an object with the same property names (including cases) same with the parameters in your SP.
protected internal string GetSingleValue_String(String spname, Object entity)
{
Object res = new Object();
String conString = String.Empty;
using (SqlConnection con = new SqlConnection(ConnectionString))
{
con.Open();
SqlCommand cmd = new SqlCommand(spname, con);
cmd.CommandType = CommandType.StoredProcedure;
if (entity != null)
{
SqlCommandBuilder.DeriveParameters(cmd);
PropertyInfo entitymember = default(PropertyInfo);
foreach (SqlParameter _param in cmd.Parameters)
{
if (_param.Direction == ParameterDirection.Input)
{
entitymember = entity.GetType().GetProperty(_param.ParameterName.Replace("#", ""));
var entityValue = entitymember.GetValue(entity, null);
String _paramvalue = entityValue != null ? entityValue.ToString() : null;
_param.Value = (string.IsNullOrEmpty(_paramvalue) || _paramvalue == string.Empty ? null : _paramvalue);
}
}
}
res = cmd.ExecuteScalar();
cmd.Connection.Close();
entity = null;
cmd = null;
if(res==null)
res = "";
else if (String.IsNullOrEmpty(res.ToString()))
res = "";
return res.ToString();
}
}
So in your example, create a new class that have the same definition as your SP parameters.
class NewClass()
{
public string UserID { get; set; }
public string Firstname { get; set; }
public string Middlename { get; set; }
public string Lastname { get; set; }
public string UserAge { get; set; }
public string HomeAddress { get; set; }
}
And will call the method like this.
var newClass = new NewClass
{
UserID = "UserId",
Firstname = "Firstname",
Middlename = "Middlename",
Lastname = "Lastname",
UserAge = "UserAge",
HomeAddress = "HomeAddress"
}
var res = GetSingleValue_String("InsertUser2Sp", newClass);
Don'd mind the return type.

Return Object in C#

I'm trying to return an object in C#. In JavaScript, I would do this:
function myFunction () {
var myObj = { firstName: "John", lastName: "Smith", age: 20};
return myObj;
}
Everything I'm reading about returning an object within C# is much different than this so it's throwing me for a loop.
What I want to do is run a query to SQL to get some user info and return the users Role, Full Name, Email, etc...
Here is my current C# Code:
public static string getUserRole(string connectionString, string userId)
{
string role;
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCom = new SqlCommand();
SqlDataReader reader;
sqlCom.CommandText = "SELECT Role FROM myDatabase.Table WHERE Email = '" + userId + "'";
sqlCom.CommandType = CommandType.Text;
sqlCom.Connection = sqlCon;
sqlCon.Open();
reader = sqlCom.ExecuteReader();
if (reader.Read())
{
role = reader.GetString(0);
sqlCon.Close();
return role;
}
else
{
return "An error has occurred";
}
}
I'm assuming I need to do something like the following but it doesn't work:
public static string getUserRole(string connectionString, string userId)
{
string role;
string fullName;
string email;
SqlConnection sqlCon = new SqlConnection(connectionString);
SqlCommand sqlCom = new SqlCommand();
SqlDataReader reader;
sqlCom.CommandText = "SELECT Role FROM myDatabase.Table WHERE Email = '" + userId + "'";
sqlCom.CommandType = CommandType.Text;
sqlCom.Connection = sqlCon;
sqlCon.Open();
reader = sqlCom.ExecuteReader();
if (reader.Read())
{
public class myObject
{
role = reader.GetString(0);
fullName = reader.GetString(1);
email = reader.GetString(2);
}
sqlCon.Close();
return myObject;
}
else
{
return "An error has occurred";
}
}
I'm probably way off but from what I'm reading, object within c# are basically classes. So that makes sense. I need to create a class that defines my properties. Is this correct? I've ready lots of posts and watched some youtube videos but none are 'clicking'
Thanks in advance for any helpful input.
public class UserInfo
{
public string role;
public string fullName;
public string email;
public string ErrorCode;
}
and then change signatures to
public static UserInfo getUserRole(string connectionString, string userId)
and then change
if (reader.Read())
{
public class myObject
{
role = reader.GetString(0);
fullName = reader.GetString(1);
email = reader.GetString(2);
}
sqlCon.Close();
return myObject;
}
else
{
return "An error has occurred";
}
to create an object of UserInfo and return that. Like,
UserInfo info = new UserInfo();
if (reader.Read())
{
info.role = reader.GetString(0);
info.fullName = reader.GetString(1);
info.email = reader.GetString(2);
sqlCon.Close();
}
else
{
info.ErrorCode = "An error has occurred";
}
return info;
Note: Not the best way to do it, but should get you going. Just to give you an idea.

combine two methods returning two different values

Hi I have got two methods are returning two different return type of values like int and string and I am executing query inside the method with passing different variables like the below
METHOD 1
private string SelectTransactionHistory(int transactionId, ContextObject contextObject)
{
SqlConnection con;
SqlCommand cmd;
con = new SqlConnection(contextObject.ConnectionString);
con.Open();
string returnvalue = string.Empty;
string selecteQuery = "SELECT Comments
From dbo.TransactionHistory
WHERE TransactionID = '" + transactionId + "'";
cmd = new SqlCommand(selecteQuery, con);
returnvalue = (string)cmd.ExecuteScalar();
con.Close();
return returnvalue;
}
METHOD 2
private int SelectTransactionHistoryID(string comment, ContextObject contextObject)
{
SqlConnection con;
SqlCommand cmd;
con = new SqlConnection(contextObject.ConnectionString);
con.Open();
string query = "SELECT TransactionID
From dbo.TransactionHistory
WHERE Comments = '" + comment + "'";
cmd = new SqlCommand(query, con);
int returnvalue = (int)cmd.ExecuteScalar();
con.Close();
return returnvalue;
}
I am calling these methods in another method like this
int transactionId = SelectTransactionHistoryID(comment, GetContext());
string commentsreturnValue = SelectTransactionHistory(transactionId, GetContext());
how can i combine these two methods to make more generic type..
Would any one have any suggestions on how to do this..
Many Thanks.....
You could create a method to execute any query using ado.net, for sample:
private static T ExecuteQuery<T>(ContextObject contextObject, string query)
{
T result;
using (SqlConnection con = con = new SqlConnection(contextObject.ConnectionString))
{
try
{
con.Open();
using (SqlCommand cmd = cmd = new SqlCommand(query, con))
{
result = (T)cmd.ExecuteScalar();
}
}
catch
{
result = null;
}
finally
{
con.Close();
}
}
returnr result;
}
And pass a query that return a single value (in sql we use TOP 1), something like this:
var resultComment = ExecuteQuery<string>("SELECT TOP 1 Comments From dbo.TransactionHistory WHERE TransactionID = '" + transactionId + "'");
var resultTransactionId = ExecuteQuery<int>("SELECT TOP 1 TransactionID From dbo.TransactionHistory WHERE Comments = '" + comment + "'")
I have all of my infrastructure classes setup to utilize Dapper. However you can replace the dapper extension method with a regular method.
Base Service:
public interface IService
{
T Execute<T>(Func<IDbConnection, T> query);
void Execute(Action<IDbConnection> query);
}
public sealed class Service : IService
{
private readonly string _connectionString;
public Service(string connectionString)
{
_connectionString = connectionString;
}
private IDbConnection CreateConnection()
{
var connection = new SqlConnection(_connectionString);
connection.Open();
return connection;
}
public T Execute<T>(Func<IDbConnection, T> query)
{
using (var connection = CreateConnection())
{
return query(connection);
}
}
public void Execute(Action<IDbConnection> query)
{
using (var connection = CreateConnection())
{
query(connection);
}
}
}
DTO:
public class TransactionHistory
{
public int TransactionID { get; set; }
public string Comments { get; set; }
}
Service:
public interface ITransactionHistoryService
{
IEnumerable<TransactionHistory> GetByTransactionId(int transactionId);
IEnumerable<TransactionHistory> GetByComment(string comment);
}
public sealed class TransactionHistoryService : ITransactionHistoryService
{
// Note SELECT * is frowned upon. Replace with actual column names.
private const string GetByTransactionIdQuery =
"SELECT * FROM dbo.TransactionHistory WHERE TransactionID = #TransactionId";
private const string GetByCommentQuery =
"SELECT * FROM dbo.TransactionHistory WHERE Comments = #Comment";
private readonly IService _service;
public TransactionHistoryService(IService service)
{
_service = service;
}
public IEnumerable<TransactionHistory> GetByTransactionId(int transactionId)
{
var result = _service.Execute(c =>
c.Query<TransactionHistory>(GetByTransactionIdQuery,
new { TransactionId = transactionId }));
return result;
}
public IEnumerable<TransactionHistory> GetByComment(string comment)
{
var result = _service.Execute(c =>
c.Query<TransactionHistory>(GetByCommentQuery,
new { Comment = comment }));
return result;
}
}
You can create a single function as follows- (Not tested)
private string[] SelectTransactionHistory(int transactionId, ContextObject contextObject)
{
string[] returnValues;
SqlConnection con;
SqlCommand cmd;
SqlDataReader reader;
con = new SqlConnection(contextObject.ConnectionString);
con.Open();
string returnvalue = string.Empty;
string selecteQuery = "SELECT TransactionID, Comments From dbo.TransactionHistory WHERE TransactionID = '" + transactionId + "'";
cmd = new SqlCommand(selecteQuery, con);
reader = cmd.ExecuteReader();
while(reader.Read())
{
returnValues[0] = reader["TransactionID"].ToString();
returnValues[1] = reader["Comments"].ToString();
}
con.Close();
return returnValues;
}
And then call it as follows-
string[] TransactionHistory = SelectTransactionHistory(transactionId, GetContext());
int transactionId = Convert.ToInt32(TransactionHistory[0]);
string commentsreturnValue = TransactionHistory[1];
The above code is not tested. But you can get an idea.

Three-tier architecture implementation in Windows form application

I am trying to insert data into a database using a three-tier architecture, but I am stuck and I cannot proceed further.
This is my code
First is UI part:
public void assignField()
{
string maritalCondition = "";
string sex = "";
assignObj.Registered_Date = dateTimePicker1_Date.Value;
assignObj.First_Name = txt_FirstName.Text;
if (comboBox2_MaritalStatus.SelectedIndex == 0)
{
maritalCondition = "Single";
}
else
maritalCondition = "Married";
assignObj.Marital_Status = maritalCondition;
if (RadioButton_Male.Checked == true)
sex = "Male";
else
sex = "Female";
assignObj.Gender = sex;
this.txt_Age.Text = Convert.ToInt32(age).ToString();
}
private void btnRegister_Click(object sender, EventArgs e)
{
assignField();
}
Next is the middle tier:
public class CustomerDataType
{
private DateTime registered_Date;
private string first_Name;
private int age;
private string marital_Status;
private string gender;
public DateTime Registered_Date
{
get { return registered_Date; }
set { registered_Date = value; }
}
public string First_Name
{
get { return first_Name; }
set { first_Name = value; }
}
public int Age
{
get { return age; }
set { age = value; }
}
public string Marital_Status
{
get { return marital_Status; }
set { marital_Status = value; }
}
public string Gender
{
get { return gender; }
set { gender = value; }
}
public void insertInfo()
{
CustomerDataAccess insertObj = new CustomerDataAccess(Registered_Date, First_Name, Age, Marital_Status, Gender);
insertObj.insertCustomerInfo();
}
}
and last is the data access tier:
public class CustomerDataAccess
{
public CustomerDataAccess(DateTime Registered_Date, string First_Name, int Age, string Marital_Status, string Gender)
{
this.registrationDate = Registered_Date;
this.fName = First_Name;
this.userAge = Age;
this.marriageStatus = Marital_Status;
this.userGender = Gender;
}
SqlConnection con;
SqlCommand cmd;
DateTime registrationDate;
string fName = "";
int userAge;
string marriageStatus;
string userGender;
public void insertCustomerInfo()
{
try
{
con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True");
con.Open();
cmd = con.CreateCommand();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add("#Registered_Date", SqlDbType.DateTime);
cmd.Parameters["#Registered_Date"].Value = registrationDate;
cmd.Parameters.Add("#First_Name", SqlDbType.VarChar);
cmd.Parameters["#First_Name"].Value = fName;
cmd.Parameters.Add("#Age", SqlDbType.Int.ToString());
cmd.Parameters["#Age"].Value = userAge;
cmd.Parameters.Add("#Marital_Status", SqlDbType.VarChar);
cmd.Parameters["#Marital_Status"].Value = marriageStatus;
cmd.Parameters.Add("#Gender", SqlDbType.VarChar);
cmd.Parameters["#Gender"].Value = userGender;
cmd.ExecuteNonQuery();
con.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
Here with the stored procedure, there is no problem and and from SQL Server I can insert data into table easily. But from windows form, it does not insert data in table. Plz help me.
I'll do something like below
UI
CustomerHandler custHandler = new CustomerHandler();
// create Customer object and pass to insert method
if (custHandler.InsertCustomer(new Customer(){
FirstName = txt_FirstName.Text, Registered_Date =dateTimePicker1_Date.Value,
//decalare other parameters....
))
{
// insert Success, show message or update label with succcess message
}
In my BL
public class CustomerHandler
{
// in BL you may have to call several DAL methods to perform one Task
// here i have added validation and insert
// in case of validation fail method return false
public bool InsertCustomer(Customer customer)
{
if (CustomerDataAccess.Validate(customer))
{
CustomerDataAccess.insertCustomer(customer);
return true;
}
return false;
}
}
In MY DAL
// this is the class you going to use to transfer data across the layers
public class Customer
{
public DateTime Registered_Date { get; set; }
public string FirstName { get; set; }
//so on...
}
public class CustomerDataAccess
{
public static void insertCustomer(Customer customer)
{
using (var con = new SqlConnection("Data Source=LAKHE-PC;Initial Catalog=Sahakari;Integrated Security=True"))
using (var cmd = con.CreateCommand())
{
con.Open();
cmd.CommandText = "sp_registerCust";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#Registered_Date", customer.Registered_Date);
cmd.Parameters.AddWithValue("#FirstName", customer.FirstName);
// so on...
cmd.ExecuteNonQuery();
}
}
internal static bool Validate(Customer customer)
{
// some validations before insert
}
}
Your middle tier consists of classes holding the values you require in properties. Instead of writing the data access manually, try using the Entity Framework (EF) which does that for you.
Here (at MSDN) you can find a quickstart example which shows you how you can use it.
Instead of mapping the fields manually and executing a query, the Entity Framework does that which means you just have to assign the values to the object's properties and call SaveChanges() - the SQL code is created and executed automatically by the EF.
For further reading, there is also a lot to find here (at Stackoverflow).

Categories