Console Application Failed to Retrieve Data With Wcf Service - c#

I am consuming wcf service into console application . I am trying to retrieve account information based on account number . But the problem is when i enter the account number and hit enter ,its only displaying account number and rest of the fields are empty.
Here is the base class.
[DataContract]
public class Current_Account_Details
{
string account_creation_date;
string account_type;
string branch_sort_code;
string account_fees;
string account_balance;
string over_draft_limit;
string account_holder_id;
[DataMember]
public string Account_Creation_Date
{
get { return account_creation_date; }
set { account_creation_date = value; }
}
[DataMember]
public string Account_Type
{
get { return account_type; }
set { account_type = value; }
}
[DataMember]
public string Branch_Sort_Code
{
get { return branch_sort_code; }
set { branch_sort_code = value; }
}
[DataMember]
public string Account_Fees
{
get { return account_fees; }
set { account_fees = value; }
}
[DataMember]
public string Account_Balance
{
get { return account_balance; }
set { account_balance = value; }
}
[DataMember]
public string Over_Draft_Limit
{
get { return over_draft_limit; }
set { over_draft_limit = value; }
}
[DataMember]
public string Account_Holder_Id
{
get { return account_holder_id; }
set { account_holder_id = value; }
}
}
}
Here is the inherited class.
[DataContract]
public class AccountBalanceRequest : Current_Account_Details
{
string account_number;
[DataMember]
public string Account_Number
{
get { return account_number; }
set { account_number = value; }
}
}
}
Here is the Interface .
[OperationContract]
AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber);
Here is my Method .
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
//use top 1 since you are only getting one record.
//let us use string interpolation, if you are working below C#6
//replace it with your previous value
var cmd = new SqlCommand($#"SELECT TOP 1
*
FROM
Current_Account_Details
WHERE
Account_Number ='{accountNumber.Account_Number}'", conn);
cmd.CommandType = CommandType.Text;
//use ExecuteReader to execute sql select
//ExecuteNonQuery is for update, delete, and insert.
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while (reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
//assuming that your datatype are string... just do the conversion...
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Account_Fees = reader["Account_Fees"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
Here is the code in Console Application .
public static void Balance()
{
MyService.HalifaxCurrentAccountServiceClient currentAccount = new MyService.HalifaxCurrentAccountServiceClient("NetTcpBinding_IHalifaxCurrentAccountService");
MyService.AccountBalanceRequest cs = new MyService.AccountBalanceRequest();
string AccountNumber;
Console.WriteLine("\nEnter your Account Number--------:");
AccountNumber = Console.ReadLine();
cs.Account_Number = AccountNumber;
// MyService.AccountBalanceRequest cs1 = currentAccount.AccountBalanceCheek(AccountNumber);
MyService.AccountBalanceRequest AccountBalance = currentAccount.AccountBalanceCheek(cs);//error on this line
Console.WriteLine("Account Number is :" + cs.Account_Number);
Console.WriteLine("Account creation date :" + cs.Account_Creation_Date);
Console.WriteLine("Account Type :" + cs.Account_Type);
Console.WriteLine("Branch_Sort_Code:" + cs.Branch_Sort_Code);
Console.WriteLine("Account_Fee:" + cs.Account_Fees);
Console.WriteLine("Account Account_Balance :" + cs.Account_Balance);
Console.WriteLine("Account Over Draft Limit :" + cs.Over_Draft_Limit);
Console.Write("--------------------------");
Console.ReadLine();
//Console.Clear();
}
Here is the screen shot of the database.click here to record
Here is the screen shot when i run the applicationClick here to see the result.In this screen shot only the account number is displaying and rest of the fields are empty

your Current_Account_Details is the base class and AccountBalanceRequest is derived class from your question posted.
If we have classes related by inheritance, the wcf service generally accepts and returns the base type. If you expect the service to accept and return inherited types, then use KnownType attribute.
So its enough if you decorate the base class with contracts and try.
[KnownType(typeof(AccountBalanceRequest))]
[DataContract]
public class Current_Account_Details
{
string account_creation_date;
string account_type;
string branch_sort_code;
string account_fees;
string account_balance;
string over_draft_limit;
string account_holder_id;
[DataMember]
public string Account_Creation_Date
{
get { return account_creation_date; }
set { account_creation_date = value; }
}
[DataMember]
public string Account_Type
{
get { return account_type; }
set { account_type = value; }
}
[DataMember]
public string Branch_Sort_Code
{
get { return branch_sort_code; }
set { branch_sort_code = value; }
}
[DataMember]
public string Account_Fees
{
get { return account_fees; }
set { account_fees = value; }
}
[DataMember]
public string Account_Balance
{
get { return account_balance; }
set { account_balance = value; }
}
[DataMember]
public string Over_Draft_Limit
{
get { return over_draft_limit; }
set { over_draft_limit = value; }
}
[DataMember]
public string Account_Holder_Id
{
get { return account_holder_id; }
set { account_holder_id = value; }
}
}
}
public class AccountBalanceRequest : Current_Account_Details
{
string account_number;
public string Account_Number
{
get { return account_number; }
set { account_number = value; }
}
}
Just check whether account number that you read from console is passed in the accountnumber variable.
var cmd = new SqlCommand("SELECT * FROM Current_Account_Details WHERE Account_Number = '" + accountNumber + "'", conn);
Edit 1: Your service is failing to retrieve records because you are passing the AccountBalanceRequest object and the changes made to the object is not reflected outside the method.
MyService.AccountBalanceRequest cs = new MyService.AccountBalanceRequest();
Change it to.
public AccountBalanceRequest AccountBalanceCheek(AccountBalanceRequest accountNumber)
{
using (SqlConnection conn = new SqlConnection(ConnectionString))
{
conn.Open();
//use top 1 since you are only getting one record.
//let us use string interpolation, if you are working below C#6
//replace it with your previous value
var cmd = new SqlCommand($#"SELECT TOP 1
*
FROM
Current_Account_Details
WHERE
Account_Number ='{accountNumber.Account_Number}'", conn));
cmd.CommandType = CommandType.Text;
//use ExecuteReader to execute sql select
//ExecuteNonQuery is for update, delete, and insert.
var reader = cmd.ExecuteReader();
//read the result of the execute command.
while(reader.Read())
{
//assuming that your property is the same as your table schema. refer to your table schema Current_Account_Details
//assuming that your datatype are string... just do the conversion...
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Account_Fee = reader["Account_Fee"].ToString();
accountNumber.Account_Balance = reader["Account_Balance"].ToString();
accountNumber.Over_Draft_Limit = reader["Over_Draft_Limit"].ToString();
}
return accountNumber;
}
}
In your console retrieve it,
MyService.AccountBalanceRequest AccountBalance =currentAccount.AccountBalanceCheek(cs);
Console.WriteLine("Your Account Number is :" + cs.Account_Number)
...

I think your problem is that you're passing a reference to the WCF service method and changing it there instead of returning. The documentation says that:
Each operation has a return value and a parameter, even if these are void. However, unlike a local method, in which you can pass references to objects from one object to another, service operations do not pass references to objects. Instead, they pass copies of the objects.
Try to change your code so the method returns the changed object. At the end of AccountBalanceCheek method instead of returning true return accountNumber.
And then in Balance method - remove if statement and change to:
....
cs = currentAccount.AccountBalanceCheek(cs);
Console.WriteLine("Your Account Number is :" + cs.Account_Number);
Console.WriteLine("Your Account Type :" + cs.Account_Balance);
....
To read more about it: Is it possible to pass parameters by reference with WCF

Related

Controller.Json() returns null

I'm only using ASP.Net and MVC, no other libraries.
The code is the following:
//ExpensesController.cs - the controller
public IActionResult getExpenses()
{
List<ExpensesViewModel> list = new List<ExpensesViewModel>();
string connectionString = "Data Source=DESKTOP-72RT825;Initial Catalog=AccountingDB;Integrated Security=True;Pooling=False";
SqlConnection sqlConnection = new SqlConnection(connectionString);
sqlConnection.Open();
SqlCommand query = new SqlCommand("Select * from Expenses", sqlConnection);
try
{
SqlDataReader reader;
reader = query.ExecuteReader();
while (reader.Read())
{
String name = reader.GetValue(0).ToString();
String value = reader.GetValue(1).ToString();
String date = reader.GetValue(2).ToString();
list.Add(new ExpensesViewModel() { Name = name, Date=date, Value = value });
Debug.Print(name + " " + " " + value);
}
}
catch (SqlException ex)
{
Debug.Print(ex.Message);
return Json(ex.Message);
}
JsonResult jsonResult = null;
try
{
jsonResult = Json(list);
}
catch(Exception ex)
{
Debug.Write(ex.Message);
}
return jsonResult;
}
//The View Model
public class ExpensesViewModel
{
public string Name;
public string Value;
public string Date;
}
The data that Json(list) returns is null, even though the list is not, I looked in the debugger, the connection to the DB is good, the data arrives, it is put into the list, but when I try and convert it to Json it fails. I've tried adding elements into the list manually, the Json function still returns null.
Change your view model to use properties, not fields:
public class ExpensesViewModel
{
public string Name { get; set; }
public string Value { get; set; }
public string Date { get; set; }
}
The reason is that the default model binder binds to properties with public getters/setters.

How to read null values out of a integer column in sql to C#?

i am trying to make a project for my school. I am trying to read a table where some null values are in an integer column. I've made it an integer but i can't get the null values into the integer.
I've already searched in stackoverflow but none of the answers i could make at my project. Can someone provide me some help, tell me where i have to put the code to make it work again. I just started as programmer.
This is my database conn string + reader:
public static List<Klant> GetAlleklanten()
{
var result = new List<Klant>();
using (var conn = new SqlConnection(ConnectionString))
{
conn.Open();
const string query = "select k.klantid, k.naam, k.adres, k.telefoonnummer, k.woonplaats, k.email, k.wachtwoord, kp.klantpasid from klant k left join klantpas kp on k.klantid = kp.klantid";
SqlCommand selectKamers = new SqlCommand(query, conn);
SqlDataReader reader = selectKamers.ExecuteReader();
while (reader.Read())
{
Klant klant = new Klant((int)reader["klantid"], (string)reader["naam"], (string)reader["adres"], (string)reader["telefoonnummer"], (string)reader["woonplaats"], (string)reader["email"], (string)reader["wachtwoord"], (int)reader["klantpasid"]);
result.Add(klant);
}
reader.Close();
}
return result;
}
klantpasid is the one that also can return a null value instead of an integer.
Here is the class where the klantpasid is in the construtor:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace FontysHotel
{
public class Klant
{
// instantie variabelen
private int klantid;
private string naam;
private string adres;
private string telefoonnummer;
private string woonplaats;
private string email;
private string wachtwoord;
private int? klantpasid;
// properties
public int Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
public string Naam
{
get
{
return naam;
}
set
{
naam = value;
}
}
public string Adres
{
get
{
return adres;
}
set
{
adres = value;
}
}
public string Telefoonnummer
{
get
{
return telefoonnummer;
}
set
{
telefoonnummer = value;
}
}
public string Woonplaats
{
get
{
return woonplaats;
}
set
{
woonplaats = value;
}
}
public string Email
{
get
{
return email;
}
set
{
email = value;
}
}
public string Wachtwoord
{
get
{
return wachtwoord;
}
set
{
wachtwoord = value;
}
}
public int? Klantpasid
{
get
{
return klantpasid;
}
set
{
klantpasid = value;
}
}
// Constructor
public Klant(int klantid, string naam, string adres, string telefoonnummer, string woonplaats, string email, string wachtwoord, int klantpasid)
{
Klantid = klantid;
Naam = naam;
Adres = adres;
Telefoonnummer = telefoonnummer;
Woonplaats = woonplaats;
Email = email;
Wachtwoord = wachtwoord;
Klantpasid = klantpasid;
}
}
}
Please provide me some help, tell me where i have to place the right code so i can continue my school project. The error i am getting now is ''' The specified conversion is invalid
'''
You can check klantid for DBNull.Value, and if it is, assign corresponding special int value; so instead of
(int)reader["klantid"]
put
reader.IsDBNull(reader.GetOrdinal("klantid")) ? -1 : Conver.ToInt32(reader["klantid"])
a better way is to declare private int klantid; as private int? klantid; (nullable int):
private int? klantid; // it can accept null now
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
then while reading from reader we can use turnary operator:
KlantId = !reader.IsDBNull(reader.GetOrdinal("klantid"))
? Conver.ToInt32(reader["klantid"])
: null;
I know a fix for you,
You change Klantpasid from int? to int
If klantpasid is null in your database, we set the value to 0 instead of null
public int Klantpasid
{
get
{
return klantpasid;
}
set
{
if( value == null){
klantpasid = 0;
}else {
klantpasid = value;
}
}
}
You can declare your property as nullable
public int? Klantid
{
get
{
return klantid;
}
set
{
klantid = value;
}
}
Check out more on documentation.
When you read your data with a DataReader, it will return DBNull.Value. Whe you want to fill your Klant.Klantpasid value (which is of type Nullable<int>), you will have to convert the value to Nullable<int> yourself. When ADO.NET was first implemented, there were no nullable values, so they introduced DBNull instead. More modern approaches like Entity Framework use nullable types instead.
You can write a helper method to help converting your read value to a nullable type:
static T? AsNullable<T>(object value) where T : struct {
switch (value) {
case T converted:
return converted;
case DBNull:
return default(T?);
default:
throw new InvalidCastException();
}
}
So instead of...
(int)reader["klantpasid"]
...you write:
AsNullable<int>(reader["klantpasid"])
And of course you change the type of your constructor parameter from int to int?.

Consuming wcf service Windows Form Application

I am consuming Wcf Service in Windows Form Application . I am trying to create user login system based on user emu type from sql database .When I enter the value 1 into textbox it should return full time employee method else value 2 into textbox it should return part time employee method but Its is not working according expectation ..
Here is Employee class code ....
[KnownType(typeof(FullTimeEmployee))]
[KnownType(typeof(PartTimeEmployee))]
[DataContract(Namespace = "http://pragimtech.com/Employee")]
public class Employee
{
private int _id;
private string _name;
private string _gender;
private DateTime _dateOfBirth;
[DataMember(Order = 1)]
public int Id
{
get { return _id; }
set { _id = value; }
}
[DataMember(Order = 2)]
public string Name
{
get { return _name; }
set { _name = value; }
}
[DataMember(Order = 3)]
public string Gender
{
get { return _gender; }
set { _gender = value; }
}
[DataMember(Order = 4)]
public DateTime DateOfBirth
{
get { return _dateOfBirth; }
set { _dateOfBirth = value; }
}
[DataMember(Order = 5)]
public EmployeeType Type { get; set; }
}
[DataContract(Name = "EmployeeType")]
public enum EmployeeType
{
[EnumMember]
FullTimeEmployee = 1,
[EnumMember]
PartTimeEmployee = 2
}
}
Here is my Full time and part time employee class inherit from Employee class...
public class FullTimeEmployee : Employee
{
public int AnnualSalary { get; set; }
}
public class PartTimeEmployee : Employee
{
public int HourlyPay { get; set; }
public int HoursWorked { get; set; }
}
Here is Method to Get Employee method to access employee based on employee type...
public Employee GetEmployee(int Id)
{
Employee employee = null;
string cs = ConfigurationManager.ConnectionStrings["DBCS"].ConnectionString;
using (SqlConnection con = new SqlConnection(cs))
{
SqlCommand cmd = new SqlCommand("spGetEmployee1", con);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter parameterId = new SqlParameter();
parameterId.ParameterName = "#EmployeeType";
parameterId.Value = Id;
cmd.Parameters.Add(parameterId);
con.Open();
SqlDataReader reader = cmd.ExecuteReader();
while (reader.Read())
{
if ((EmployeeType)reader["EmployeeType"] == EmployeeType.FullTimeEmployee)
{
return employee;
} }
else if ((EmployeeType)reader["EmployeeType"] == EmployeeType.PartTimeEmployee)
{
return employee;
}
}
}
return employee;
}
Here is my Windows Form Application ......
private void button1_Click(object sender, EventArgs e)
{
MyService.HalifaxServiceClient myservice = new MyService.HalifaxServiceClient("NetTcpBinding_IHalifaxService");
MyService.Employee employee = myservice.GetEmployee(Convert.ToInt32(txt1.Text));
MyService.FullTimeEmployee ft = new MyService.FullTimeEmployee();
if (employee == myservice.GetEmployee(Convert.ToInt32(txt1.Text).CompareTo(employee.Type)))
{
FulltimeEmployeeLinkActivites();
}
else if (employee == myservice.GetEmployee(Convert.ToInt32(txt1.Text).CompareTo(employee.Type)))
{
PartTimeEmployeeActivities();
}
else
{
label4.Text = "No infomation found";
}
}
Here is screen shot when I run the application ...
The problem I see with your if / else is that the conditional statements are exactly the same. One way that you can branch based on the type of an object is with the is keyword.
if (employee is FullTimeEmployee)
{
FulltimeEmployeeLinkActivites();
}
else if (employee is PartTimeEmployee)
{
PartTimeEmployeeActivities();
}
else
{
label4.Text = "No information found";
}
I would also add that this is not necessarily best practice, however it should get you what you are asking for.
In addition to that, your method that returns the employee instance never returns an employee of a valid type. It doesn't appear that the GetEmployee method ever instantiates an employee instance. It looks like it is always returning null. Try returning instances of the proper type. You will also need to populate the instances with the data you need.
if ((EmployeeType)reader["EmployeeType"] == EmployeeType.FullTimeEmployee)
{
return new FullTimeEmployee();
}
else if ((EmployeeType)reader["EmployeeType"] == EmployeeType.PartTimeEmployee)
{
return new PartTimeEmployee();
}
You have a confusing naming in your elements and "employee" class does not seems to be populated in your data reader.
"FullTimeEmployee" is the name one of your classes and also the name of one of your enums. So is not safe to set your condition
(EmployeeType)reader["EmployeeType"] == EmployeeType.FullTimeEmployee
I can not be sure without the code of your spGetEmployee, but if it returns values from your table with those same names it could be safer to declare
while(reader.Read())
{
employee= new employee();
employee.Id= reader.GetInt32(0);
employee.Name= reader.GetString(1);
...
employee.EmployeeType=(EmployeeType)reader.GetInt32(4);
if(employee.EmployeeType== EmployeeType.FullTimeEmployee)
{
//Do extra work for this type of employee
...
return employee;
}
}

DBNull Exception Problems

I am having an issue with my code today. Whenever I use this method to add a Product to my local DB, it throws an exception that reads "Object cannot be cast from DBNull to other types". After doing some research, I believe my issue resides with the insertCmd parameters in the AddProduct method, but I cannot seem to figure out exactly what is causing it. The program that I have created still functions correctly (it adds the product and can then be selected successfully), however it just seems to keep throwing this exception when I add the product.
Can anyone provide any insight as to where the issue might lie within my code? If you need any more information, please do not hesitate to ask. Thank you for your time and help.
public static bool AddProduct(Product product)
{
SqlConnection connect = MMABooksDB.GetConnection();
string insert = "INSERT Products " + "(ProductCode, Description, UnitPrice) " + "VALUES (#code, #description, #price)";
SqlCommand insertCmd = new SqlCommand(insert, connect);
insertCmd.Parameters.AddWithValue("#code", product.code);
insertCmd.Parameters.AddWithValue("#description", product.description);
insertCmd.Parameters.AddWithValue("#price", product.price);
try
{
connect.Open();
insertCmd.ExecuteNonQuery();
string selectStatement =
"SELECT IDENT_CURRENT('Products') FROM Products";
SqlCommand selectCommand = new SqlCommand(selectStatement, connect);
int ProductCode = Convert.ToInt32(selectCommand.ExecuteScalar());
return true;
}
catch (SqlException ex)
{
throw ex;
}
finally
{
connect.Close();
}
}
And here is the product class
public class Product
{
public string code;
public string description;
public decimal price;
public Product() { }
public Product(string code, string description, decimal price)
{
this.Code = code;
this.Description = description;
this.Price = price;
}
public string Code
{
get
{
return code;
}
set
{
code = value;
}
}
public string Description
{
get
{
return description;
}
set
{
description = value;
}
}
public decimal Price
{
get
{
return price;
}
set
{
price = value;
}
}
public string GetDisplayText()
{
return code + ", " + price.ToString("c") + ", " + description;
}
public string GetDisplayText(string sep)
{
return code + sep + price.ToString("c") + sep + description;
}
}
int ProductCode; //declare variable
object dbProductID = selectCommand.ExecuteScalar(); //get the result into object
if(dbProductID !=null || dbProductID != DBNull.Value) //check if it is null
ProductCode = 0; //assign some default value here if it has no productid
else
ProductCode = Convert.ToInt32(dbProductID);//if its has productid cast it into int
if the product is getting added I would assume the cannot convert is coming from int ProductCode = Convert.ToInt32(selectCommand.ExecuteScalar()); I would add a check to see if that scaler is returning null.

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