I am creating a system with C# and Windows Forms, and when I tried to implement an interface to generate the base model with the methods for any database that I implement in the system I get an error when trying to pass parameters to the child class of the interface.
I have the following interface:
It is responsible for generating the contract with all the classes that will inherit it.
public interface iDatabase
{
void createConnection();
void CreateUser();
}
and the class DbService:
which is responsible for containing the contract's fixation and allow me not to generate dependency on the project's dependencies, this way I can change the database at any time, I just need to send a new database class as parameter for it to work...
public class DbService
{
private iDatabase _database;
public DbService(iDatabase databaseService)
{
this._database = databaseService;
}
public void connect()
{
this._database.createConnection();
}
public void insertUser()
{
this._database.CreateUser();
}
}
and the dependency's class of SQL Server: this class is responsible for implementing SQL Server specific rules.
namespace TravelCompany.app.repository
{
internal class SqlServerService : iDatabase
{
SqlConnection sqlCon = null;
private string strCon = "Data Source=DESKTOP-UD6EQCL;Initial Catalog=immigration;Integrated Security=True";
private string strSql = string.Empty;
SqlDataAdapter adapt;
SqlCommand command;
public void createConnection()
{
try
{
sqlCon = new SqlConnection(strCon);
sqlCon.Open();
MessageBox.Show("Connection Open !");
}
catch (Exception e)
{
MessageBox.Show("Error to connect Database!", e.Message);
}
}
public void CreateUser()
{
try
{
strSql = "INSERT INTO users (full_name, email, password, cpf, birthday, cep, street, neighborhood, city, uf, complement, passport_number, stack, xp, seniority) VALUES (#full_name, #email, #password, #cpf, #birthday, #cep, #street, #neighborhood, #city, #uf, #complement, #passport_number, #stack, #xp, #seniority)";
command = new SqlCommand(strSql, sqlCon);
command.Parameters.AddWithValue("#full_name", full_name);
command.Parameters.AddWithValue("#email", email);
command.Parameters.AddWithValue("#password", password);
command.Parameters.AddWithValue("#cpf", cpf);
command.Parameters.AddWithValue("#birthday", birthday);
command.Parameters.AddWithValue("#cep", cep);
command.Parameters.AddWithValue("#street", street);
command.Parameters.AddWithValue("#neighborhood", neighborhood);
command.Parameters.AddWithValue("#city", city);
command.Parameters.AddWithValue("#uf", uf);
command.Parameters.AddWithValue("#complement", complement);
command.Parameters.AddWithValue("#passport_number", passport_number);
command.Parameters.AddWithValue("#stack", stack);
command.Parameters.AddWithValue("#xp", xp);
command.Parameters.AddWithValue("#seniority", seniority);
command.ExecuteNonQuery();
MessageBox.Show("User created successfully!");
}
catch (Exception e)
{
MessageBox.Show("Error to create user!", e.Message);
}
throw new NotImplementedException();
}
}
}
and every time that i try to pass values to the public void CreateUser() of public class SqlServerService i receive an error message:
ERROR: 'iDatabase.CreateUser']1 'SqlServerService' does not implement interface member
The method databaseService.connect(); is working!
the problem is with the 'create user' function of SqlServerService...
but the error appears only when I try to pass parameters to the SqlServerService class methods, and I don't know why this happens because I am implementing the interface method with the same name, can someone help?
I would like to solve this error problem and be able to use the create user function of the SqlServerService class with the implementation of the interface
solved the problem, I basically had to pass the same parameters to all the other methods, so the code looks like this:
class SqlServerService
namespace TravelCompany.app.repository
{
internal class SqlServerService : iDatabase
{
SqlConnection sqlCon = null;
private string strCon = "Data Source=DESKTOP-UD6EQCL;Initial Catalog=immigration;Integrated Security=True";
private string strSql = string.Empty;
SqlDataAdapter adapt;
SqlCommand command;
public void createConnection()
{
try
{
sqlCon = new SqlConnection(strCon);
sqlCon.Open();
MessageBox.Show("Connection Open !");
}
catch (Exception e)
{
MessageBox.Show("Error to connect Database!", e.Message);
}
}
public void CreateUser(string userName, string userBirthday, string userCpf, string userCep, string userStreet, string userNeighborhood, string userCity, string userUf, string userComplement, string userEmail, string userPassport, string stack, string xp, string seniority)
{
MessageBox.Show("User created!");
//try
//{
// strSql = "INSERT INTO users (full_name, email, password, cpf, birthday, cep, street, neighborhood, city, uf, complement, passport_number, stack, xp, seniority) VALUES (#full_name, #email, #password, #cpf, #birthday, #cep, #street, #neighborhood, #city, #uf, #complement, #passport_number, #stack, #xp, #seniority)";
// command = new SqlCommand(strSql, sqlCon);
// command.Parameters.AddWithValue("#full_name", userName);
// command.Parameters.AddWithValue("#email", userEmail);
// command.Parameters.AddWithValue("#password", userPassword);
// command.Parameters.AddWithValue("#cpf", userCpf);
// command.Parameters.AddWithValue("#birthday", userBirthday);
// command.Parameters.AddWithValue("#cep", userCep);
// command.Parameters.AddWithValue("#street", userStreet);
// command.Parameters.AddWithValue("#neighborhood", userNeighborhood);
// command.Parameters.AddWithValue("#city", userCity);
// command.Parameters.AddWithValue("#uf", userUf);
// command.Parameters.AddWithValue("#complement", userComplement);
// command.Parameters.AddWithValue("#passport_number", userPassport);
// command.Parameters.AddWithValue("#stack", userStack);
// command.Parameters.AddWithValue("#xp", userXp);
// command.Parameters.AddWithValue("#seniority", userSeniority);
// command.ExecuteNonQuery();
// MessageBox.Show("User created successfully!");
// }
// catch (Exception e)
// {
// MessageBox.Show("Error to create user!", e.Message);
// }
//throw new NotImplementedException();
}
}
}
interface:
public interface iDatabase
{
void createConnection();
void CreateUser(string userName, string userBirthday, string userCpf, string userCep, string userStreet, string userNeighborhood, string userCity, string userUf, string userComplement, string userEmail, string userPassport, string stack, string xp,
string seniority);
}
and the class DbService:
public void insertUser(string userName, string userBirthday, string userCpf, string userCep, string userStreet, string userNeighborhood, string userCity, string userUf, string userComplement, string userEmail, string userPassport, string stack, string xp, string seniority)
{
this._database.CreateUser(userName, userBirthday, userCpf, userCep, userStreet, userNeighborhood, userCity, userUf, userComplement, userEmail, userPassport, stack, xp, seniority);
}
For a reason that i dont know, i have to pass the parameters to all the classes.
I am following a guide on WCF on C# using visual studio 2010. I thought I was doing everything correct, till I built the solution and I am meet with this error. Can someone tell me what to do and how to fix it? Also why its happening? I am fairly new to this, so any help will be greatly appericated.
This is my code. The error appears in the first line, in Service1 : IService1. I do see the note but I tried changing service1 to say "Hello" but no luck.
namespace WCFData
{
// 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
{
SqlConnection conn;
SqlCommand comm;
SqlConnectionStringBuilder connStringBuilder;
void ConnectToDB()
{
connStringBuilder = new SqlConnectionStringBuilder();
connStringBuilder.DataSource = "NATHAN-PC\\SQLEXPRESS";
connStringBuilder.InitialCatalog = "WCF";
connStringBuilder.Encrypt = true;
connStringBuilder.TrustServerCertificate = true;
connStringBuilder.ConnectTimeout = 30;
connStringBuilder.MultipleActiveResultSets = true;
connStringBuilder.IntegratedSecurity = true;
conn = new SqlConnection(connStringBuilder.ToString());
conn = conn.CreateCommand();
}
public string GetData(int value)
{
return string.Format("You entered: {0}", value);
}
public CompositeType GetDataUsingDataContract(CompositeType composite)
{
if (composite == null)
{
throw new ArgumentNullException("composite");
}
if (composite.BoolValue)
{
composite.StringValue += "Suffix";
}
return composite;
}
public int InsertPerson(Person p)
{
try
{
comm.CommandText = "INSERT INTO Person Values(#Id, #Name, #age)";
comm.Parameters.AddWithValue("Id", p.Id);
comm.Parameters.AddWithValue("Name", p.Name);
comm.Parameters.AddWithValue("Age", p.Age);
comm.CommandType = CommandType.Text;
conn.Open();
return comm.ExecuteNonQuery();
}
catch (Exception)
{
throw;
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
}
}
You can right click on the interface IService1 and select "Implement Interface."
This will add the appropriate methods to your class.
Then check if you are misspelling their signatures in your code.
I want to implement factory pattern Architecture. I have created Interface with parameterized function.
1) Step 1 :
public interface IDatabase
{
bool Create(string userId,string password,string host,string dbName);
bool Delete(string userId, string password, string host, string dbName);
}
Step 2:
This interface is Implemented in below class:-
public class IntialDBSetup : IDatabase
{
public bool Create(string userId, string password, string host, string dbName)
{
SqlConnection con = new SqlConnection("Data Source=" + host + ";uid=" + userId + ";pwd=" + password + "");
try
{
string strCreatecmd = "create database " + dbName + "";
SqlCommand cmd = new SqlCommand(strCreatecmd, con);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
var file = new System.IO.FileInfo(System.Web.HttpContext.Current.Server.MapPath(ConfigurationManager.AppSettings["ScriptLocation"]));
string strscript = file.OpenText().ReadToEnd();
string strupdatescript = strscript.Replace("[OWpress]", dbName);
var server = new Microsoft.SqlServer.Management.Smo.Server(new Microsoft.SqlServer.Management.Common.ServerConnection(con));
server.ConnectionContext.ExecuteNonQuery(strupdatescript);
con.Close();
return true;
}
catch (Exception ex)
{
return false;
}
}
public bool Delete(string userId, string password, string host, string dbName)
{
throw new NotImplementedException();
}
}
Step 3:
created factory class
public class DBFactory
{
public static IDatabase DbSetup(string DbType, string userId, string password, string host, string dbName)
{
try
{
if (DbType == DBTypeEnum.IntialDB.ToString())
{
return new IntialDBSetup();
}
}
catch (Exception ex)
{
throw new ArgumentException("DB Type Does not exist in our Record");
}
return null;
}
}
Here I want to pass some parameter to my class, Hgow can I get this?
Add a constructor to your class.
If DBFactory and IntialDBSetup are in the same assembly then that constructor can be marked internal (preventing code outside the assembly creating instances directly).
If the factory method was a static member of IntialDBSetup then the constructor can be private preventing direct creation even in the same assembly.
Am using CLR Trigger to pass the values to WCF,everything works fine but when try to pass the constant value its not pass thru WCF even its not throwing any exception.
CLR Trigger
public partial class Triggers
{
public static EndpointAddress endpoint = new EndpointAddress(new Uri("http://localhost:8000/services/myservice"));
public static WSHttpBinding httpBinding = new WSHttpBinding();
public static ServiceClient.ServiceReference1.ServiceContractClient myclient = new ServiceClient.ServiceReference1.ServiceContractClient(httpBinding, endpoint);
public delegate void MyDelagate(String crudType);
[SqlProcedure()]
[Microsoft.SqlServer.Server.SqlTrigger(Name = "WCFTrigger",
Target = "tbCR", Event = "FOR UPDATE, INSERT")]
public static void Trigger1()
{
SqlCommand cmd;
SqlTriggerContext myContext = SqlContext.TriggerContext;
SqlPipe pipe = SqlContext.Pipe;
SqlDataReader reader;
if(myContext.TriggerAction== TriggerAction.Insert)
{
using (SqlConnection conn = new SqlConnection(#"context connection=true"))
{
conn.Open();
cmd = new SqlCommand(#"SELECT * FROM tbCR", conn);
reader = cmd.ExecuteReader();
reader.Read();
//get the insert value's here
string Name;
Name = reader[1].ToString();
reader.Dispose();
myclient.InsertOccured(Name);
}
}
}
}
}
Interface
namespace SampleService
{
[ServiceContract]
interface IServiceContract
{
[OperationContract]
void UpdateOccured();
[OperationContract]
void InsertOccured(String Name);
}
}
Contract
namespace SampleService
{
class MyService : IServiceContract
{
public void InsertOccured(string Name)
{
Console.WriteLine("Insert Occured",Name);
}
}
}
every time i insert record ,WCF shows "Insert Occured" only but i was expecting "Insert Occured, Test".
Can you please guide me what i suppose to do to get the constant value from SLQ Tirgger.
In your service operation implementation is looks like you need to add the string parameter to your Console.WriteLine() string template. In other words:
Console.WriteLine("Insert Occured, {0}",Name);
You can find more about Console.WriteLine and composite formatting here:
http://msdn.microsoft.com/en-us/library/828t9b9h.aspx