I have an async method whereby i want to pull some data and assign to global variable for use in another method.
Below is the method:
private async void getgoogleplususerdataSer(string access_token)
{
try
{
HttpClient client = new HttpClient();
var urlProfile = "https://www.googleapis.com/oauth2/v1/userinfo?access_token=" + access_token;
client.CancelPendingRequests();
HttpResponseMessage output = await client.GetAsync(urlProfile);
if (output.IsSuccessStatusCode)
{
string outputData = await output.Content.ReadAsStringAsync();
GoogleUserOutputData serStatus = JsonConvert.DeserializeObject<GoogleUserOutputData>(outputData);
if (serStatus != null)
{
gName = serStatus.name;
gEmail = serStatus.email;
}
}
}
catch (Exception ex)
{
//catching the exception
}
}
The variables gName and gEmail have already been declared.
I want to use the variables to register user using the following logic:
protected void RegisterGoogleUser()
{
string strCon = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string sql5 = "SELECT Email FROM Members where Email=#gEmail";
using (SqlConnection con5 = new SqlConnection(strCon))
{
using (SqlCommand cmd5 = new SqlCommand(sql5, con5))
{
con5.Open();
cmd5.Parameters.AddWithValue("#gEmail", gEmail);
Object result = cmd5.ExecuteScalar();
con5.Close();
if (result != null)
{
lblMessage.Text = "This e-mail is already registered. If you forgot your password, use forgot password link to recover it.";
return;
}
else
{
string providerName = "Google";
string conn = ConfigurationManager.ConnectionStrings["connectionString"].ConnectionString;
string query = "INSERT INTO Members(Name, Email, ProviderName)values(#gName,#gEmail,#providerName)";
using (SqlConnection connection = new SqlConnection(conn))
{
using (SqlCommand cmd1 = new SqlCommand(query, connection))
{
cmd1.Parameters.AddWithValue("#gName", gName);
cmd1.Parameters.AddWithValue("#gEmail", gEmail);
cmd1.Parameters.AddWithValue("#providerName", providerName);
connection.Open();
cmd1.ExecuteNonQuery();
Session.Add("GEmail", gEmail);
Session.Add("CurrentUserName", gName);
Response.Redirect("ExternalRegistration.aspx");
connection.Close();
}
}
}
}
}
}
Below is GoogleUserOutputData class and Google Login Method
public class GoogleUserOutputData
{
public string id { get; set; }
public string name { get; set; }
public string given_name { get; set; }
public string email { get; set; }
public string picture { get; set; }
}
protected void btnGoogleLogin_Click(object sender, System.EventArgs e)
{
var Googleurl = "https://accounts.google.com/o/oauth2/auth?response_type=code&redirect_uri=" + googleplus_redirect_url + "&scope=https://www.googleapis.com/auth/userinfo.email%20https://www.googleapis.com/auth/userinfo.profile&client_id=" + googleplus_client_id;
Session["Provider"] = "Google";
Response.Redirect(Googleurl);
}
The exception i am getting is: "The parameterized query '(#gEmail nvarchar(4000))SELECT Email FROM Members where Email=#g' expects the parameter '#gEmail', which was not supplied."
You really need to read more about how to use Asynchronous Programming.
If you call getgoogleplususerdataSer() without the await keyword, the execution of your block of code continues even before the end of the method.
So:
private async Task callingMethod()
{
getgoogleplususerdataSer();
Console.WriteLine(gName); // maybe null, runs before the end of previous method.
Console.WriteLine(gEmail); // maybe null
}
instead:
private async Task callingMethod()
{
await getgoogleplususerdataSer(); // wait for this to end, then continue.
Console.WriteLine(gName); // null
Console.WriteLine(gEmail); // null
}
Related
I am fairly new to c# and would like to know how values can be called from a file instead of statically hard coding it in the class. I know in java spring boot applications we can have it in application.properties files. In my case I have the db hostname, username and pwd stored in a file
namespace NunitTestCase
{
[TestFixture]
public class Test
{
string query = "SELECT * FROM SYSTEM.ADMIN.EMPLOYEE";
string host = "vm1.test.app.com"; //want these data in a file
int port = 5480;
string dbName = "SYSTEM";
string userName = "admin";
string password = "password";
[Test]
public void TestCase()
{
var builder = new ConnectionStringBuilder();
builder.UserName = userName;
builder.Password = password;
builder.Port = port;
builder.Host = host;
builder.Database = dbName;
using (var con = new Connection(builder.ConnectionString))
{
con.Open();
NUnit.Framework.Assert.That(con.State == ConnectionState.Open);
using (var cmd = new Command(query, con))
{
var rdr = cmd.ExecuteReader();
while (rdr.Read())
{
for (int i = 0; i < rdr.FieldCount; i++)
{
object o = null;
try
{
o = rdr.GetValue(i);
}
catch (Exception ex)
{
o = ex.Message;
}
Console.WriteLine(o);
}
}
}
con.Close();
NUnit.Framework.Assert.That(con.State == ConnectionState.Closed);
}
}
}
}
file.yaml
database:
host: "vm1.test.app.com"
port: 5480
dbName: "SYSTEM"
userName: "admin"
password: "password"
How do I make changes in my code so that instead of hardcoding, these values can be picked up from the file
Traditionally, in .net we store configuration in .json/.xml files and C# supports built-in functionality to parse it, but as far as you are using .YAML file you can install the library to parse this file:
YAMLDotNet
and use this to parse.
public class Database {
public string Host { get; set; }
public string Port { get; set; }
public string DbName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
public class Configuration
{
public Database Database { get; set; }
}
var yamlString = File.ReadAllText(#"...\file.yaml");
var deserializer = new DeserializerBuilder().WithNamingConvention(new CamelCaseNamingConvention()).Build();
var config = deserializer.Deserialize<Configuration>(yamlString);
If you don't want to use any libraries you can parse it manually, so create a class which reflects your model in YAML, something like:
Function to get the value of a property:
public string GetValueOfPropertyYaml(string yamlStr) {
return yamlStr?.Split(":")?.Skip(1)?.FirstOrDefault()?.Trim() ?? string.Empty;
}
Main code:
string[] yamlStringArray = File.ReadAllLines(#"..\file.yaml");
var config = new Database();
foreach (var yamlStr in yamlStringArray) {
if (yamlStr.Contains("host:")) {
config.Host = GetValueOfPropertyYaml(yamlStr);
}
if (yamlStr.Contains("port:"))
{
config.Port = GetValueOfPropertyYaml(yamlStr);
}
if (yamlStr.Contains("dbName:"))
{
config.DbName = GetValueOfPropertyYaml(yamlStr);
}
if (yamlStr.Contains("userName:"))
{
config.UserName = GetValueOfPropertyYaml(yamlStr);
}
if (yamlStr.Contains("password:"))
{
config.Password = GetValueOfPropertyYaml(yamlStr);
}
}
;
// use filled `config` variable below.
your model:
public class Database
{
public string Host { get; set; }
public string Port { get; set; }
public string DbName { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
}
NOTE: I highly recommend you to use library, because it was already tested and worked perfectly(my method should be tested properly)
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.
I am trying to retrieve a set of data from a MySQL database in a WebAPI application and access it through HTTP request from a mobile app. Hence I created a WebApi, a RestClient class and the class where I would show the data, this is my code.
Web API
[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
// GET: api/Blog
[HttpGet]
public IEnumerable<string> Get()
{
}
// GET: api/Blog/5
[HttpGet("{id}", Name = "GetBlogItems")]
public string Get(int id)
{
}
// POST: api/Blog
[HttpPost]
public void Post([FromBody] RetrieveDataClass value)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
}
// PUT: api/Blog/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
So, in my database, I have three rows with a telephone number of +233892929292, after the filter I have to get three rows. and I would also filter to only the topic and summary column.
RestClient Class
public class BlogRestClient<T>
{
private const string WebServiceUrl = "http://localhost:57645/api/Blog/";
public async Task<List<T>> GetAsync()
{
var httpClient = new HttpClient();
var json = await httpClient.GetStringAsync(WebServiceUrl);
var taskModels = JsonConvert.DeserializeObject<List<T>>(json);
return taskModels;
}
public async Task<bool> PostAsync(T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PostAsync(WebServiceUrl, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> PutAsync(int id, T t)
{
var httpClient = new HttpClient();
var json = JsonConvert.SerializeObject(t);
HttpContent httpContent = new StringContent(json);
httpContent.Headers.ContentType = new MediaTypeHeaderValue("application/json");
var result = await httpClient.PutAsync(WebServiceUrl + id, httpContent);
return result.IsSuccessStatusCode;
}
public async Task<bool> DeleteAsync(int id, T t)
{
var httpClient = new HttpClient();
var response = await httpClient.DeleteAsync(WebServiceUrl + id);
return response.IsSuccessStatusCode;
}
}
ModelData Class
public class ModelDataClass
{
public string Telephone ;
public string Created/Saved ;
public string TopicSaved1 ;
public string SummarySaved1 ;
public string CategoriesSaved1 ;
public string Body1 ;
public string Body2 ;
public string Body3 ;
public string Body4 ;
public ModelDataClass()
{
}
}
The Values for the strings in ModelDataClass are set in another class to post in MySQL database. Since that is not causing the problem in question, I have not included the code.
RetrieveDataClass
public class RetrieveDataClass
{
public string Topic ;
public string Summary ;
public RetrieveDataClass()
{
GetDataEvent();
AddBlog();
}
public void GetDataEvent()
{
BlogRestClient<ModelDataClass> restClient = new
BlogRestClient<ModelDataClass>();
await restClient.GetAsync();
}
public ObservableCollection<ModelDataClass> BlogItems = new
ObservableCollection<ModelDataClass>();
public void AddBlog()
{
BlogListView.ItemsSource = BlogItems;
}
}
Question1
How do I retrieve the data from, Mysql, to WebAPI accessed through the REST client class(It's for mobile so I have to use Http request)?
Question2
I would like to create a listView for each row I retrieve through the MySQL database. With the heading being the data in the topic column and the subheading is with the data in summary column.
Your application is designed with the Multitier Architecture pattern. As such, you need to ensure you have a separation of concerns.
The Web API will represent your presentation logic layer. It will parse the client's request, query for the data as required and format the returned data as needed.
The RetrieveClient can then handle the data access layer. It will manage access to the database, insert, update, delete as needed.
The key point here is to ensure that each layer talks to the other to perform actions and that you do not directly access the database in your presentation layer.
As such,
How to retrieve data?
In your Data Access Layer :
public class RetrieveDataClass
{
private IDbConnection connection;
public RetrieveDataClass(System.Data.IDbConnection connection)
{
// Setup class variables
this.connection = connection;
}
/// <summary>
/// <para>Retrieves the given record from the database</para>
/// </summary>
/// <param name="id">The identifier for the record to retrieve</param>
/// <returns></returns>
public EventDataModel GetDataEvent(int id)
{
EventDataModel data = new EventDataModel();
string sql = "SELECT id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4 WHERE id = #id";
using (IDbCommand cmd = connection.CreateCommand())
{
cmd.CommandText = sql;
cmd.CommandType = CommandType.Text;
IDbDataParameter identity = cmd.CreateParameter();
identity.ParameterName = "#id";
identity.Value = id;
identity.DbType = DbType.Int32; // TODO: Change to the matching type for id column
cmd.Parameters.Add(identity);
try
{
connection.Open();
using (IDataReader reader = cmd.ExecuteReader())
{
if (reader.Read())
{
data.id = reader.GetInt32(reader.GetOrdinal("id"));
// TODO : assign the rest of the properties to the object
}
else
{
// TODO : if method should return null when data is not found
data = null;
}
}
// TODO : Catch db exceptions
} finally
{
// Ensure connection is always closed
if (connection.State != ConnectionState.Closed) connection.Close();
}
}
// TODO : Decide if you should return null, or empty object if target cannot be found.
return data;
}
// TODO : Insert, Update, Delete methods
}
The above will get a record from the database, and return it as an object. You can use ORM libraries such as EntityFramework or NHibernate instead but they have their own learning curve.
How to return the data?
Your client will call the WebAPI, which in turn query for the data from the data access layer.
[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
// TODO : Move the connection string to configuration
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
// GET: api/Blog
/// <summary>
/// <para>Retrieves the given record from the database</para>
/// </summary>
/// <param name="id">Identifier for the required record</param>
/// <returns>JSON object with the data for the requested object</returns>
[HttpGet]
public IEnumerable<string> Get(int id)
{
IDbConnection dbConnection = System.Data.Common.DbProviderFactories.GetFactory("MySql.Data.MySqlClient");
RetrieveDataClass dal = new RetrieveDataClass(dbConnection);
EventDataModel data = dal.GetDataEvent(id);
if (data != null)
{
// Using Newtonsoft library to convert the object to JSON data
string output = Newtonsoft.Json.JsonConvert.SerializeObject(data);
// TODO : Not sure if you need IEnumerable<string> as return type
return new List<string>() { output };
} else
{
// TODO : handle a record not found - usually raises a 404
}
}
// TODO : other methods
}
There are lots of other examples online on how to access the data via API. Have a look on google and review. A few that come to mind are
https://learn.microsoft.com/en-us/aspnet/core/tutorials/first-web-api?view=aspnetcore-2.2&tabs=visual-studio
https://learn.microsoft.com/en-us/aspnet/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
i solved the problem.
WebApi
[Produces("application/json")]
[Route("api/Blog")]
public class BlogController : Controller
{
// GET: api/Blog
[HttpGet]
public List<BlogViews> Get()
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "SELECT * FROM test.blogtable where `Telephone` ='Created'";
MySqlCommand cmd = new MySqlCommand(Query, conn);
MySqlDataReader MSQLRD = cmd.ExecuteReader();
List<BlogViews> GetBlogList = new List<BlogViews>();
if (MSQLRD.HasRows)
{
while (MSQLRD.Read())
{
BlogViews BV = new BlogViews();
BV.id = (MSQLRD["id"].ToString());
BV.DisplayTopic = (MSQLRD["Topic"].ToString());
BV.DisplayMain = (MSQLRD["Summary"].ToString());
GetBlogList.Add(BV);
}
}
conn.Close();
return GetBlogList;
}
// GET: api/Blog/5
[HttpGet("{id}", Name = "GetBlogItems")]
public string Get(int id)
{
}
// POST: api/Blog
[HttpPost]
public void Post([FromBody] RetrieveDataClass value)
{
string sqlstring = "server=; port= ; user id =;Password=;Database=;";
MySqlConnection conn = new MySqlConnection(sqlstring);
try
{
conn.Open();
}
catch (MySqlException ex)
{
throw ex;
}
string Query = "INSERT INTO test.blogtable (id,Telephone,CreatedSaved,Topic,Summary,Category,Body1,Body2,Body3,Body4)values('" + value.TopicSaved1 + "','" + Value.Telephone + "','" + Value.Created/Saved + "','" + value.TopicSaved1 + "','" +value.SummarySaved1 +"','" +value.CategoriesSaved1 +"','" +value.Body1 +"','" +value.Body2 +"','" +value.Body3 +"','" +value.Body4 +"');";
MySqlCommand cmd = new MySqlCommand(Query, conn);
cmd.ExecuteReader();
conn.Close();
}
// PUT: api/Blog/5
[HttpPut("{id}")]
public void Put(int id, [FromBody]string value)
{
}
// DELETE: api/ApiWithActions/5
[HttpDelete("{id}")]
public void Delete(int id)
{
}
}
RetriveDataClass
public class RetrieveDataClass
{
public RetrieveDataClass()
{
AddBlog();
}
public class BlogViews
{
public string id { get; set; }
public string DisplayTopic { get; set; }
public string DisplayMain { get; set; }
public ImageSource BlogImageSource { get; set; }
}
public List<BlogViews> BlogList1 = new List<BlogViews>();
public async Task< List<BlogViews>> GetBlogs()
{
BlogRestClient<BlogViews> restClient = new BlogRestClient<BlogViews>();
var BlogV = await restClient.GetAsync();
return BlogV;
}
public async void AddBlog()
{
BlogList1 = await GetBlogs();
BlogListView.ItemsSource = BlogList1;
}
}
so now i get a listview ,which contains each row from the database and each item in the listview heading is DisplayTopic and subheading is DisplayMain.
I'm creating a login and user verification system using C#/.NET. This is my first time creating such a system so I need some guidance or strategies on how to go about accomplishing this. Thank you
Login Request
public class UserLoginRequest
{
public string Email { get; set; }
public string Password { get; set; }
}
Login Result
public class LoginResult
{
public int? Id { get; set; }
public string Email { get; set; }
}
Login SERVICE
public LoginResult Login(UserLoginRequest login)
{
using (SqlConnection con = new SqlConnection(connectionString))
{
con.Open();
SqlCommand cmd = con.CreateCommand();
cmd.CommandText = "User_GetByEmail";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#email", login.Email);
using (SqlDataReader reader = cmd.ExecuteReader())
{
reader.Read();
LoginResult result = new LoginResult();
string PasswordHash = "";
{
result.Id = (int)reader["Id"];
result.Email = (string)reader["Email"];
PasswordHash = (string)reader["PasswordHash"];
};
if (BCrypt.Net.BCrypt.Verify(login.Password, PasswordHash))
{
return result;
}
else
{
return null;
}
}
}
}
Login Controller
[HttpPost, Route("api/login")]
public HttpResponseMessage Login(UserLoginRequest userLogin)
{
LoginResult result = userService.Login(userLogin);
if (result != null && result.Id.HasValue)
{
return Request.CreateResponse(HttpStatusCode.OK, result);
}
else
{
return Request.CreateResponse(HttpStatusCode.BadRequest, new ErrorResponse("Invalid username or password"));
}
}
I figured it out, the problem was in my stored procedure where i did not allow enough characters to be passed into the database
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).