I am trying to use the abstract class DbConnection (https://learn.microsoft.com/en-us/dotnet/api/system.data.common.dbconnection?view=netframework-4.8).
The reason why I want to use the class is because I am going to write a program where the user can choose between diffrent database types.
I have written a class named DBAdapter that implemtns DbConnection. However I cannot connect to any database with it.
using System;
using System.Data;
using System.Data.Common;
namespace DatabaseSQLiteAndPostgreSQLWPF.dao
{
class DBAdapter : DbConnection
{
public DbConnection dbConnection;
String databasePath = ""; // SQLite only (appData + "\\" + projectName + "\\" + "db")
String databaseFile = ""; // SQLite only (mydb.db)
String databaseType = ""; // new Database(DatabaseType.MySQL);
String databaseHost = ""; // localhost
String databasePort = ""; // 5432
String databaseUser = ""; // root
String databasePassword = ""; //
String databaseName = ""; // csharp
/*- Constructor ------------------------------------------------------------------------------------------- */
public DBAdapter(String dbType, String dbPath, String dbFile, String dbHost, String dbPort, String dbUser, String dbPassword, String dbName)
{
// Assign variables
this.databaseType = dbType;
this.databasePath = dbPath;
this.databaseFile = dbFile;
this.databaseHost = dbHost;
this.databasePort = dbPort;
this.databaseUser = dbUser;
this.databasePassword = dbPassword;
this.databaseName = dbName;
string connectionString = "SERVER=" + databaseHost + ";" + "DATABASE=" + databaseName + ";" +
"UID=" + databaseUser + ";" + "PASSWORD=" + databasePassword + ";";
dbConnection.ConnectionString = connectionString;
} // Constructor
public override string ConnectionString { get => throw new NotImplementedException(); set => throw new NotImplementedException(); }
public override string Database => throw new NotImplementedException();
public override string DataSource => throw new NotImplementedException();
public override string ServerVersion => throw new NotImplementedException();
public override ConnectionState State => throw new NotImplementedException();
protected override DbTransaction BeginDbTransaction(IsolationLevel isolationLevel)
{
throw new NotImplementedException();
}
/*- Open ---------------------------------------------------------------------------------- */
public override void Open()
{
this.dbConnection.Open();
}
/*- Close --------------------------------------------------------------------------------- */
public override void Close()
{
this.dbConnection.Close();
}
public override void ChangeDatabase(string databaseName)
{
throw new NotImplementedException();
}
protected override DbCommand CreateDbCommand()
{
throw new NotImplementedException();
}
}
}
Related
I am working on a class Library with .NET Framework 4.0. I have managed to pull a row using ADO.NET, but I'm unable to read individual values. I want the end result in class object. I have tried reading individual value dbReader.GetValue(dbReader.GetOrdinal("BranchCode")) but getting empty result.
Branch class:
public class Branch
{
public Branch() { }
public int BranchId { get; set; }
public string BranchCode { get; set; }
public string BranchName { get; set; }
}
DataReader class:
public void Initialize()
{
try
{
string connectionString = "xyz";
SqlConnection dbConnection = new SqlConnection(connectionString);
SqlCommand cmd = new SqlCommand("Select * from dbo.Branch", dbConnection);
dbConnection.Open();
SqlDataReader dbReader = cmd.ExecuteReader();
while (dbReader.Read())
{
var x1 = dbReader.GetValue(dbReader.GetOrdinal("BranchId"));
var x2 = dbReader.GetValue(dbReader.GetOrdinal("BranchCode"));
var x3 = dbReader.GetValue(dbReader.GetOrdinal("BranchName"));
}
var dd = "Dd";
}
catch(Exception ex)
{
throw ex;
}
}
You have a number of issues with your code.
You need to actually create the Branch objects and do something with them. For example, return List.
To read the values, the easiest way is to do (typeNameHere) dbReader["ColumnName"]
You should SELECT exactly the right columns not SELECT *
Don't catch then re-throw exceptions with throw ex; as it wipes the stakc trace.
public List<Branch> Initialize()
{
string connectionString = "xyz";
const string query = #"
Select
b.BranchId,
b.BranchCode,
b.BranchName
from dbo.Branch b;
";
using (SqlConnection dbConnection = new SqlConnection(connectionString))
using (SqlCommand cmd = new SqlCommand(query, dbConnection))
{
dbConnection.Open();
using (SqlDataReader dbReader = cmd.ExecuteReader())
{
var list = new List<Branch>();
while (dbReader.Read())
{
var b = new Branch();
b.BranchId = (int)dbReader["BranchId"];
b.BranchCode = (string)dbReader["BranchCode"];
b.BranchName = (string)dbReader["BranchName"];
list.Add(b);
}
return list;
}
}
}
How can we connect to SQL Server from .Net Core without using Entity Framework?
you can simply use the traditional way which use SqlConnection
here is an example
public class BaseDataAccess
{
protected string ConnectionString { get; set; }
public BaseDataAccess()
{
}
{
public BaseDataAccess(string connectionString)
private SqlConnection GetConnection()
this.ConnectionString = connectionString;
}
{
if (connection.State != ConnectionState.Open)
SqlConnection connection = new SqlConnection(this.ConnectionString);
connection.Open();
return connection;
SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
}
protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
{
protected SqlParameter GetParameter(string parameter, object value)
command.CommandType = commandType;
return command;
}
{
parameterObject.Direction = ParameterDirection.Input;
SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
return parameterObject;
}
SqlParameter parameterObject = new SqlParameter(parameter, type); ;
protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
{
if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)
{
}
parameterObject.Size = -1;
}
parameterObject.Direction = parameterDirection;
if (value != null)
{
parameterObject.Value = value;
}
else
{
parameterObject.Value = DBNull.Value;
}
return parameterObject;
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
int returnValue = -1;
try
{
using (SqlConnection connection = this.GetConnection())
{
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
using (DbConnection connection = this.GetConnection())
returnValue = cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);
throw;
}
return returnValue;
}
protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)
{
object returnValue = null;
try
{
{
}
DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
returnValue = cmd.ExecuteScalar();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);
throw;
return returnValue;
}
ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
DbDataReader ds;
try
{
DbConnection connection = this.GetConnection();
{
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
}
}
catch (Exception ex)
{
}
//LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
throw;
}
return ds;
}
More can be find here
Update
you have to add nuget package
Install-Package System.Data.SqlClient
that is still confusing for me... .Net Core & .Net standard vs regular .Net: How do we know which packages we can use with .Net core?
Dependencies means that what you should have installed on your machine in order to use the package or nuget will install it for you
to understand more how dependencies work in .net take a look here
Note
that if the nuget package target .net standard library mostly work on both .net core and .net standard framework
If you surprised with BaseDataAccess class format in another answer and referenced article same as me, here is well formatted example... hopefully it will save you some time
public class BaseDataAccess
{
protected string ConnectionString { get; set; }
public BaseDataAccess()
{
}
public BaseDataAccess(string connectionString)
{
this.ConnectionString = connectionString;
}
private SqlConnection GetConnection()
{
SqlConnection connection = new SqlConnection(this.ConnectionString);
if (connection.State != ConnectionState.Open)
connection.Open();
return connection;
}
protected DbCommand GetCommand(DbConnection connection, string commandText, CommandType commandType)
{
SqlCommand command = new SqlCommand(commandText, connection as SqlConnection);
command.CommandType = commandType;
return command;
}
protected SqlParameter GetParameter(string parameter, object value)
{
SqlParameter parameterObject = new SqlParameter(parameter, value != null ? value : DBNull.Value);
parameterObject.Direction = ParameterDirection.Input;
return parameterObject;
}
protected SqlParameter GetParameterOut(string parameter, SqlDbType type, object value = null, ParameterDirection parameterDirection = ParameterDirection.InputOutput)
{
SqlParameter parameterObject = new SqlParameter(parameter, type); ;
if (type == SqlDbType.NVarChar || type == SqlDbType.VarChar || type == SqlDbType.NText || type == SqlDbType.Text)
{
parameterObject.Size = -1;
}
parameterObject.Direction = parameterDirection;
if (value != null)
{
parameterObject.Value = value;
}
else
{
parameterObject.Value = DBNull.Value;
}
return parameterObject;
}
protected int ExecuteNonQuery(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
int returnValue = -1;
try
{
using (SqlConnection connection = this.GetConnection())
{
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
returnValue = cmd.ExecuteNonQuery();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteNonQuery for " + procedureName, ex, parameters);
throw;
}
return returnValue;
}
protected object ExecuteScalar(string procedureName, List<SqlParameter> parameters)
{
object returnValue = null;
try
{
using (DbConnection connection = this.GetConnection())
{
DbCommand cmd = this.GetCommand(connection, procedureName, CommandType.StoredProcedure);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
returnValue = cmd.ExecuteScalar();
}
}
catch (Exception ex)
{
//LogException("Failed to ExecuteScalar for " + procedureName, ex, parameters);
throw;
}
return returnValue;
}
protected DbDataReader GetDataReader(string procedureName, List<DbParameter> parameters, CommandType commandType = CommandType.StoredProcedure)
{
DbDataReader ds;
try
{
DbConnection connection = this.GetConnection();
{
DbCommand cmd = this.GetCommand(connection, procedureName, commandType);
if (parameters != null && parameters.Count > 0)
{
cmd.Parameters.AddRange(parameters.ToArray());
}
ds = cmd.ExecuteReader(CommandBehavior.CloseConnection);
}
}
catch (Exception ex)
{
//LogException("Failed to GetDataReader for " + procedureName, ex, parameters);
throw;
}
return ds;
}
}
Here is a solution for an ASP.NET MVC Core 3.1 project tested in Visual Studio 2019 community edition.
Create a small database in SQL Express.
Then add a few lines to appsettings.json for the connection strings:
"ConnectionStrings": {
//PROD on some server
"ProdConnection": "Server=somePRODServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;encrypt=true",
//DEV on localhost
"DevConnection": "Server=someDEVServerofYours;Database=DB_xxxxx_itemsubdb;User Id=DB_xxxxx_user;Password=xxsomepwdxx;Integrated Security=false;MultipleActiveResultSets=true;"
},
Then use code similar to the following in your controller ....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Configuration;
using System.Data.SqlClient;
using System.Data;
namespace SomeNameSpace.Controllers
{
//This Model class should be saved somewhere else in your project.
//It is placed here for simplicity.
public class XtraSimpleContent
{
public string UserName { get; set; }
public string References { get; set; }
public string CreatedTime { get; set; }
}
public class CodeNotesController : Controller
{
public IConfiguration Configuration { get; }
public string connStr = String.Empty;
public CodeNotesController(IConfiguration configuration, IWebHostEnvironment env)
{
Configuration = configuration;
if (env.IsDevelopment())
{
connStr = Configuration.GetConnectionString("DevConnection");
}
else
{
connStr = Configuration.GetConnectionString("ProdConnection");
}
}
[HttpGet]
public async Task<IActionResult> CodeActionMethodToConnectToSQLnetCore()
{
//add using System.Data.SqlClient;
// using System.Data;
//Along with the using statements, you need the system assembly reference.
//To add assembly you can do the following.
// install nuget package. Right Click on Project > Manage Nuget Packages >
// Search & install 'System.Data.SqlClient' and make sure it is compatible with the type of project (Core/Standard);
List<XtraSimpleContent> aListOfItems = new List<XtraSimpleContent>();
string commandText = #"SELECT * FROM [dbo].[ItemSubmissions]
WHERE SUBMITTEREMAIL = #SUBMITTEREMAIL
ORDER BY CreationDatetime DESC";
using (var connection = new SqlConnection(connStr))
{
await connection.OpenAsync(); //vs connection.Open();
using (var tran = connection.BeginTransaction())
{
using (var command = new SqlCommand(commandText, connection, tran))
{
try
{
command.Parameters.Add("#SUBMITTEREMAIL", SqlDbType.NVarChar);
command.Parameters["#SUBMITTEREMAIL"].Value = "me#someDomain.org";
SqlDataReader rdr = await command.ExecuteReaderAsync(); // vs also alternatives, command.ExecuteReader(); or await command.ExecuteNonQueryAsync();
while (rdr.Read())
{
var itemContent = new XtraSimpleContent();
itemContent.UserName = rdr["RCD_SUBMITTERNAME"].ToString();
itemContent.References = rdr["RCD_REFERENCES"].ToString();
itemContent.CreatedTime = rdr["CreationDatetime"].ToString();
aListOfItems.Add(itemContent);
}
await rdr.CloseAsync();
}
catch (Exception Ex)
{
await connection.CloseAsync()
string msg = Ex.Message.ToString();
tran.Rollback();
throw;
}
}
}
}
string totalinfo = string.Empty;
foreach (var itm in aListOfItems)
{
totalinfo = totalinfo + itm.UserName + itm.References + itm.CreatedTime;
}
return Content(totalinfo);
}
}
}
Test it with something like:
https://localhost:44302/CodeNotes/CodeActionMethodToConnectToSQLnetCore
With UkrGuru.SqlJson package
appsettings.json:
"ConnectionStrings": {
"SqlJsonConnection": "Server=localhost;Database=SqlJsonDemo;Integrated Security=SSPI"
}
Startup.cs
services.AddSqlJson(Configuration.GetConnectionString("SqlJsonConnection"));
DbController.cs
[ApiController]
[Route("api/[controller]")]
public class DbController : ControllerBase
{
private readonly string _prefix = "api.";
private readonly DbService _db;
public DbController(DbService db) => _db = db;
[HttpGet("{proc}")]
public async Task<string> Get(string proc, string data = null)
{
try
{
return await _db.FromProcAsync($"{_prefix}{proc}", data);
}
catch (Exception ex)
{
return await Task.FromResult($"Error: {ex.Message}");
}
}
[HttpPost("{proc}")]
public async Task<dynamic> Post(string proc, [FromBody] dynamic data = null)
{
try
{
return await _db.FromProcAsync<dynamic>($"{_prefix}{proc}",
(object)data == null ? null : data);
}
catch (Exception ex)
{
return await Task.FromResult($"Error: {ex.Message}");
}
}
}
How to send out an Email notification in selenium webdriver using java, whenever some scenario is failed/passed in between ??
Following code will allow you to send mail using JAVA. Create one function and call it after scenario of Pass/Fail in selenium webdriver code.
final String username = "YourEmail";
final String password = "YourPassword";
Properties props = new Properties();
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.starttls.enable", "true");
props.put("mail.smtp.host", "mail.example.com");
props.put("mail.smtp.port", "25");
props.put("java.net.preferIPv4Stack", "true");
Session session = Session.getInstance(props,
new javax.mail.Authenticator() {
protected PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(username, password);
}
});
try {
Message message = new MimeMessage(session);
message.setFrom(new InternetAddress("YourEmail"));
message.setRecipients(Message.RecipientType.TO,
InternetAddress.parse("Emailid to which you want to send Report"));
message.setSubject("Email Subject");
BodyPart messageBodyPart1 = new MimeBodyPart();
messageBodyPart1.setText("Body text);
//4) create new MimeBodyPart object and set DataHandler object to this object
MimeBodyPart messageBodyPart2 = new MimeBodyPart();
String filename = "File path if you want to attach in mail";//change accordingly
DataSource source = new FileDataSource(filename);
messageBodyPart2.setDataHandler(new DataHandler(source));
messageBodyPart2.setFileName(filename);
//5) create Multipart object and add MimeBodyPart objects to this object
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart1);
multipart.addBodyPart(messageBodyPart2);
//6) set the multiplart object to the message object
message.setContent(multipart );
Transport.send(message);
System.out.println("Mail Sent Successfully");
} catch (MessagingException e) {
throw new RuntimeException(e);
}
Note : Please change Host, Email details and port as per your Email system configuration.
Wrote a method in Utility class file and call it from condition where test case fails.
public static void sendEmail(string message, string testCaseName)
{
MailMessage mail = new MailMessage();
mail.To.Add("your-to-email-address-goes-here");
mail.From = new MailAddress("your-from-email-address-goes-here ");
mail.Subject = "your-mail-subject-goes-here";
mail.Body = "Test Case Name: " + testCaseName;
mail.Body += Environment.NewLine;
mail.Body += message;
SmtpClient smtp = new SmtpClient();
smtp.Host = "localhost";
smtp.Port = 25;
smtp.Send(mail);
}
You can call this method in your test case, when it should fail. User will be notified via email.
**use proper SMTP configuration
Here is my sample for sending out emails via javax.mail:
pom dependancy:
<dependency>
<groupId>javax.mail</groupId>
<artifactId>mail</artifactId>
<version>1.5.0-b01</version>
</dependency>
1. STEP (model MailMessage) you need model class of mail message:
public class MailMessage {
private String from;
private List<String> to;
private List<String> cc;
private List<String> bcc;
private String subject;
private Date sendDate;
private String flags;
private String content;
private List<File> attachments;
public MailMessage() {
}
public MailMessage(String from, String to, String subject, String content)
List<String> listTo = new ArrayList<>();
List<String> listCC = new ArrayList<>();
List<String> listBCC = new ArrayList<>();
listTo.add(to);
new MailMessage(from, listTo, listCC, listBCC, subject, content);
}
public MailMessage(String from, String to, String cc, String subject, String content) {
List<String> listTo = new ArrayList<>();
List<String> listCC = new ArrayList<>();
List<String> listBCC = new ArrayList<>();
listTo.add(to);
listCC.add(cc);
new MailMessage(from, listTo, listCC, listBCC, subject, content);
}
public MailMessage(String from, List<String> to, List<String> cc, List<String> bcc, String subject, String content) {
setFrom(from);
setTo(to);
setCc(cc);
setBcc(bcc);
setSubject(subject);
setContent(content);
}
public String getFrom() {
return from;
}
public void setFrom(String from) {
this.from = from;
}
public List<String> getTo() {
return to;
}
public void setTo(List<String> to) {
this.to = to;
}
public List<String> getCc() {
return cc;
}
public void setCc(List<String> cc) {
this.cc = cc;
}
public List<String> getBcc() {
return bcc;
}
public void setBcc(List<String> bcc) {
this.bcc = bcc;
}
public String getSubject() {
return subject;
}
public void setSubject(String subject) {
this.subject = subject;
}
public Date getSendDate() {
return sendDate;
}
public void setSendDate(Date sendDate) {
this.sendDate = sendDate;
}
public String getFlags() {
return flags;
}
public void setFlags(String flags) {
this.flags = flags;
}
public String getContent() {
return content;
}
public void setContent(String fieldMessage) {
this.content = fieldMessage;
}
public List<File> getAttachments() {
return attachments;
}
public void setAttachments(List<File> attachments) {
this.attachments = attachments;
}
public String toString() {
StringBuilder sb = new StringBuilder();
sb.append("-------------------------------------\n");
sb.append("FROM: " + getFrom() + "\n");
sb.append("TO: " + getTo() + "\n");
sb.append("Subject: " + getSubject() + "\n");
sb.append("Send Date: " + getSendDate() + "\n");
sb.append("Flags: " + getFlags() + "\n");
sb.append("Messages: " + getContent() + "\n");
sb.append("-------------------------------------\n");
return sb.toString();
}
}
2. STEP (create message, populate model)
protected MailMessage createMessage(String to, String subject, String content) {
List<String> listTo = new ArrayList<>();
List<String> listCC = new ArrayList<>();
List<String> listBCC = new ArrayList<>();
listTo.add(to);
return createMessage(listTo, listCC, listBCC, subject, content);
}
protected MailMessage createMessage(List<String> to, List<String> cc, List<String> bcc, String subject, String content) {
MailMessage mailMessage = new MailMessage();
mailMessage.setFrom(getUsername());
mailMessage.setTo(to);
mailMessage.setCc(cc);
mailMessage.setBcc(bcc);
mailMessage.setSubject(subject);
mailMessage.setContent(content);
return mailMessage;
}
3. STEP method for sending message via model (MailMessage):
public boolean sendMessage(MailMessage mailMessage) {
try {
// Create a default MimeMessage object.
MimeMessage message = new MimeMessage(getSession());
// Set From: header field of the header.
message.setFrom(new InternetAddress(mailMessage.getFrom()));
// Set To: header field of the header.
for (String fieldTo : mailMessage.getTo()) {
message.addRecipient(Message.RecipientType.TO, new InternetAddress(fieldTo));
}
for (String fieldCc : mailMessage.getCc()) {
message.addRecipient(Message.RecipientType.CC, new InternetAddress(fieldCc));
}
for (String fieldBcc : mailMessage.getBcc()) {
message.addRecipient(Message.RecipientType.BCC, new InternetAddress(fieldBcc));
}
// Set Subject: header field
message.setSubject(mailMessage.getSubject());
// Now set the actual message
message.setText(mailMessage.getContent());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(mailMessage.getContent(), "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (mailMessage.getAttachments() != null && mailMessage.getAttachments().size() > 0) {
for (File filePath : mailMessage.getAttachments()) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath.getAbsolutePath());
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
message.setContent(multipart);
// Send message
Transport.send(message);
return true;
} catch (MessagingException mex) {
mex.printStackTrace();
return false;
}
}
Hope this would help,
I am implementing and WCF Async service using WsDualHttpBinding binding for duplex communication to get database changes.
I have implemented the Service but I dont know how to call it from Client application.
Here is the code.
The below code is WCF Service
[ServiceContract()]
public interface ICustomerService
{
[OperationContract(IsOneWay = true)]
void GetAllCustomer();
}
public interface ICustomerServiceCallback
{
[OperationContract(IsOneWay = true)]
void Callback(Customer[] customers);
}
[ServiceContract(Name = "ICustomerService",
CallbackContract = typeof(CustomerServiceLibrary.ICustomerServiceCallback),
SessionMode = SessionMode.Required)]
public interface ICustomerServiceAsync
{
[OperationContract(AsyncPattern = true)]
IAsyncResult BeginGetAllCustomer(AsyncCallback callback, object asyncState);
void EndGetAllCustomer(IAsyncResult result);
}
[DataContract]
public class Customer
{
[DataMember]
public string Name
{
get;
set;
}
}
}
public class CustomerService :ICustomerService,IDisposable
{
List<Customer> Customers = null;
ICustomerServiceCallback callback;
Customer customer = null;
string constr = "Data Source=.;Initial Catalog=WPFCache;Persist Security Info=True;User ID=sa;Password=Password$2";
public CustomerService()
{
callback = OperationContext.Current.GetCallbackChannel<ICustomerServiceCallback>();
SqlDependency.Start(constr);
}
public void GetAllCustomer()
{
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand())
{
con.Open();
cmd.Connection = con;
cmd.CommandText = "GetHero";
cmd.CommandType = CommandType.StoredProcedure;
cmd.Notification = null;
// Create the associated SqlDependency
SqlDependency dep = new SqlDependency(cmd);
dep.OnChange += new OnChangeEventHandler(dep_OnChange);
SqlDataReader dr = cmd.ExecuteReader();
Customers = new List<Customer>();
while (dr.Read())
{
customer = new Customer();
customer.Name = dr.GetString(0);
Customers.Add(customer);
}
}
callback.Callback(Customers.ToArray());
}
}
void dep_OnChange(object sender, SqlNotificationEventArgs e)
{
try
{
if (e.Type == SqlNotificationType.Change)
{
GetAllCustomer();
}
}
catch (Exception ex)
{
throw ex;
}
}
public void Dispose()
{
SqlDependency.Stop(constr);
}
}
I have hosted this WCF Async Service as self hosting in a Console Application.
Here the hosting code
class Program
{
static void Main(string[] args)
{
StartService();
}
internal static ServiceHost myServiceHost = null;
internal static void StartService()
{
Uri httpbaseAddress = new Uri("http://localhost:8087/CustomerService/");
Uri[] baseAdresses = { httpbaseAddress };
myServiceHost = new ServiceHost(typeof(CustomerServiceLibrary.CustomerService));
myServiceHost.AddServiceEndpoint(typeof(CustomerServiceLibrary.ICustomerService), new WSDualHttpBinding(), httpbaseAddress);
ServiceDescription serviceDesciption = myServiceHost.Description;
foreach (ServiceEndpoint endpoint in serviceDesciption.Endpoints)
{
Console.WriteLine("Endpoint - address: {0}", endpoint.Address);
Console.WriteLine(" - binding name:\t\t{0}", endpoint.Binding.Name);
Console.WriteLine(" - contract name:\t\t{0}", endpoint.Contract.Name);
Console.WriteLine();
}
myServiceHost.Open();
Console.WriteLine("Press enter to stop.");
Console.ReadKey();
if (myServiceHost.State != CommunicationState.Closed)
myServiceHost.Close();
}
}
In client Application have crated a DuplexChannel factory instance
Here is the Code.
private void Window_Loaded(object sender, RoutedEventArgs e)
{
EndpointAddress address = new EndpointAddress(new Uri("http://localhost:8087/CustomerService"));
WSDualHttpBinding wsDualBinding = new WSDualHttpBinding();
DuplexChannelFactory<ICustomerServiceAsync> client = new DuplexChannelFactory<ICustomerServiceAsync>(new InstanceContext(this), wsDualBinding, address);
App.channel = client.CreateChannel();
}
Now My question is How I can call the
BeginGetAllCustomer
EndGetAllCustomer
Method of My service.
Help me.... A big thanks in Advance ...
You need:
InstanceContext instanceContext = new InstanceContext(YOUR_OBJECT_IMPLMENTS_CALLBACK);
and
using (App.channel as IDisposable)
{
App.channel.YOUR_METHOD_HERE();
}
from this example:
endPointAddr = "net.tcp://" + textBox2.Text + ":8000/FIXMarketDataHub";
NetTcpBinding tcpBinding = new NetTcpBinding();
tcpBinding.TransactionFlow = false;
tcpBinding.Security.Transport.ProtectionLevel = System.Net.Security.ProtectionLevel.EncryptAndSign;
tcpBinding.Security.Transport.ClientCredentialType = TcpClientCredentialType.Windows;
tcpBinding.Security.Mode = SecurityMode.None;
EndpointAddress endpointAddress = new EndpointAddress(endPointAddr);
Append("Attempt to connect to: " + endPointAddr);
InstanceContext instanceContext = new InstanceContext(??);
IMarketDataPub proxy = DuplexChannelFactory<IMarketDataPub>.CreateChannel(instanceContext,tcpBinding, endpointAddress);
using (proxy as IDisposable)
{
proxy.Subscribe();
Append("Subscribing to market data");
}
See also microsoft example
I'm quite a new C# programmer,it has been a month that ive started using C#, so far so good i might say, but im curently dealing with a simple situation , but i still dont get it to work , there is the scenario :
I've 2 forms a Parent and a Child , the parent contains a Xtragrid control and a button which opens the second form and load the textBoxes in the second form with values , the second has a button to update the values in case of any changes . but i still dont get it to work , I've the following error :
MUST DECLARE A SCALAR VARIABLE at #ID
I understood the cause of the probleme but i just cant fix it ,ive have done some researches to sort myself out but i still didnt manage to make it work
the last line
da.updatecommand.parameters.addwithvalues("ID#",ds.tables["tblLesseeYW"].Rows[LesseeYW.Position][0];
I have done it but it is not working( LesseeYW which is my binding source object but it doesnt exit in the current context nor the dataset which is understandable
: there is the code need help pleaese
// This the class ive created to retrieve all Columns from the SQl server data base
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace YoungWoman
{
public static class GetRowData
{
public static int LesseeId;
public static byte LesseePic;
public static string LesseeName;
public static string LesseeLastName;
public static string PassportNo;
public static string IDNo;
public static DateTime BirthDate;
public static string Gender;
public static string Country;
public static string City;
public static string Province;
public static string LesseePostalCode;
public static string MobileNo;
public static string HomePhoneNo;
public static string TutorName;
public static string TutorLastName;
public static string AddressTutor;
public static string AddressLessee;
public static string TutorPhoneNo;
public static string TutorEmail;
}
}
// the parent form
namespace YoungWoman
{
public partial class Lessee2 : UserControl
{
DataSet ds = new DataSet();
DataView dv ;
SqlDataAdapter daLessee = new SqlDataAdapter();
SqlDataAdapter daReservation = new SqlDataAdapter();
BindingSource LesseeYW = new BindingSource();
BindingSource ReservationCenterYW = new BindingSource();
SqlConnection conne = SqlCoonectionSEtup.GetConnection;
// the button that opens the Child Form
private void EditLesseeFrm_Click(object sender, EventArgs e)
{
Lesseefrm Lessee = new Lesseefrm(Utils.Formtype.edit, 1);
Lessee.LesseeEventHandler += new EventHandler(RefreshLesseeGrid);
GetRowData.LesseeId = Convert.ToInt32(gridView1.GetRowCellValue (gridView1.FocusedRowHandle, "LesseeId"));
GetRowData.LesseeName = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "LesseeName"));
GetRowData.LesseeLastName = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle,"LesseeLastName"));
GetRowData.PassportNo = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle,"PassportNo"));
GetRowData.Gender = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Gender"));
GetRowData.Province = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Province"));
GetRowData.BirthDate = Convert.ToDateTime(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "BirthDate"));
GetRowData.City = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "City"));
GetRowData.Country = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "Country"));
GetRowData.MobileNo = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "MobileNo"));
GetRowData.HomePhoneNo = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "HomePhoneNo"));
GetRowData.IDNo = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "IDNo"));
GetRowData.AddressLessee = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "AddressLessee"));
GetRowData.AddressTutor = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "AddressTutor"));
GetRowData.LesseePostalCode = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "LesseePostalCode"));
GetRowData.TutorName = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "TutorName"));
GetRowData.TutorLastName = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "TutorLastName"));
GetRowData.TutorPhoneNo = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "TutorPhoneNo"));
GetRowData.TutorEmail = Convert.ToString(gridView1.GetRowCellValue(gridView1.FocusedRowHandle, "TutorEmail"));
Lessee.ShowDialog();
}
( // Child LOad_form if form type == Edit )
if (formtype == Formtype.edit && Lesseeid > 0)
{
LesseeIdtextEdit.Enabled = false;
ClearBtnlayoutControlItem26.Visibility = DevExpress.XtraLayout.Utils.LayoutVisibility.Never;
SaveBtn.Text = "&Edit";
SaveBtn.Image = Resources.brush_16;
this.Text = string.Format(" Edit Lessee Information - YW Residence ");
LesseeIdtextEdit.Text = Convert.ToInt32(GetRowData.LesseeId).ToString();
txtName.Text = GetRowData.LesseeName;
txtLAstname.Text = GetRowData.LesseeLastName;
txtPassport.Text = GetRowData.PassportNo;
txtID.Text = GetRowData.IDNo;
GendercomboBoxEdit.SelectedItem = GetRowData.Gender;
DobdateEdit.DateTime = GetRowData.BirthDate;
CountrycomboBoxEdit.SelectedItem = GetRowData.Country;
txtProvince.Text = GetRowData.Province;
txtCity.Text = GetRowData.City;
txtPostalCode.Text = GetRowData.LesseePostalCode;
LesseememoEdit1.Text = GetRowData.AddressLessee;
txtMobile.Text = GetRowData.MobileNo;
txtHomePhone.Text = GetRowData.HomePhoneNo;
txtTutorName.Text = GetRowData.TutorName;
txttutorLastname.Text = GetRowData.TutorLastName;
tutorAddresstxt.Text = GetRowData.AddressTutor;
txtTutorMobile.Text = GetRowData.TutorPhoneNo;
txtEmail.Text = GetRowData.TutorEmail;
}
public event System.EventHandler LesseeEventHandler;
private void SaveBtn_Click(object sender, EventArgs e)
if (formtype == Formtype.edit && Lesseeid > 0)
{
MemoryStream ms = new MemoryStream();
PicBox1.Image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
byte[] Pic_arr = new byte[ms.Length];
ms.Position = 0;
ms.Read(Pic_arr, 0, Pic_arr.Length);
try
{
da.UpdateCommand = new SqlCommand(" UPDATE LesseeYW SET LesseePic = #image , LesseeName = #Name, LesseeLastName = #Last , PassportNo = #pass,IDNo = #Number, BirthDate =#birth ,Gender = #gender , Country =#country,LesseePostalCode = #Postal,City = #city , Province = #province,MobileNo = #Mobile,HomePhoneNo = #phone,TutorName = #tutor,TutorLastName=#Tlast,AddressTutor = #line1,AddressLessee=#line2,TutorPhoneNo = #Tphone,TutorEmail =#Temail WHERE LesseeId = #ID ", conne);
da.UpdateCommand.Parameters.AddWithValue("#image", Pic_arr);
da.UpdateCommand.Parameters.AddWithValue("#Name", txtName.Text);
da.UpdateCommand.Parameters.AddWithValue("#Last", txtLAstname.Text);
da.UpdateCommand.Parameters.AddWithValue("#pass", txtPassport.Text);
da.UpdateCommand.Parameters.AddWithValue("#Number", txtID.Text);
da.UpdateCommand.Parameters.AddWithValue("#birth", DobdateEdit.DateTime);
da.UpdateCommand.Parameters.AddWithValue("#gender", GendercomboBoxEdit.SelectedItem.ToString());
da.UpdateCommand.Parameters.AddWithValue("#country", CountrycomboBoxEdit.SelectedItem.ToString());
da.UpdateCommand.Parameters.AddWithValue("#Postal", txtPostalCode.Text);
da.UpdateCommand.Parameters.AddWithValue("#city", txtCity.Text);
da.UpdateCommand.Parameters.AddWithValue("#province", txtProvince.Text);
da.UpdateCommand.Parameters.AddWithValue("#Mobile", txtMobile.Text);
da.UpdateCommand.Parameters.AddWithValue("#phone", txtHomePhone.Text);
da.UpdateCommand.Parameters.AddWithValue("#tutor", txtTutorName.Text);
da.UpdateCommand.Parameters.AddWithValue("#Tlast", txttutorLastname.Text);
da.UpdateCommand.Parameters.AddWithValue("#line1", tutorAddresstxt.Text);
da.UpdateCommand.Parameters.AddWithValue("#line2", LesseememoEdit1.Text);
da.UpdateCommand.Parameters.AddWithValue("#Tphone", txtTutorMobile.Text);
da.UpdateCommand.Parameters.AddWithValue("#Temail", txtEmail.Text);
//da.UpdateCommand.Parameters.AddWithValue("#ID"
da.UpdateCommand.ExecuteNonQuery();
conne.Close();
MessageBox.Show("Lessee Details Updated ", "Confirmation", MessageBoxButtons.OK, MessageBoxIcon.Information);
this.Close();
}
catch (Exception Ex)
{
MessageBox.Show(Ex.Message);
}
}
at first you should program more objective. Dont declare all variables of your class as public static. You should make them private. To get acces you have to declare Properties.
Like this:
private string name;
public string Name
{
get {return name;}
set {name = value;}
}
if you have an ID you can easily make it read-only and noone from "outside" can modify it but everyone can read.
private int leeseId;
public int LeeseID
{
get{return leeseId;}
}
So you use "getter/setter" to offer your class properties. Further not all your variables should named leese... Just name it id,name,city,pic etc. In your form you create an Object from your class. You can name this object Leese.
private Leese leese = new Leese();
leese.id = ???
leese.name = ???
Much more readable.
da.updatecommand.parameters.addwithvalues("ID#",ds.tables["tblLesseeYW"].Rows[LesseeYW.Position][0];
You wrote "ID#" but it should be "#ID". And if you build your class as i descripe at top you can use property:
da.updatecommand.parameters.addwithvalues("#ID", leese.Id);
i hope that help you.