How to send out an Email notification in selenium webdriver using java - selenium-webdriver

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,

Related

JSONArray cannot be converted to JSONObject error when used as similar code

I get this error when I did the same this to my register method, I used this on my Login and it works well, but in register I get the error that the array cannot be converted to JSONObject, I am trying to put the array to convert it to JSONObject to send it to my PHP code for the database
This is my register method
private void registerUser() {
final String phone = phonenumber.getText().toString().trim();
final String lname = lastname.getText().toString().trim();
final String fname = fullname.getText().toString().trim();
final String mname = middlename.getText().toString().trim();
final String add = address.getText().toString().trim();
final String count = country.getText().toString().trim();
//first we will do the validations
if (TextUtils.isEmpty(lname)) {
lastname.setError("Please your Last Name");
lastname.requestFocus();
return;
}
if (TextUtils.isEmpty(fname)) {
fullname.setError("Please enter your First Name");
fullname.requestFocus();
return;
}
if (TextUtils.isEmpty(add)) {
address.setError("Please enter your Address");
fullname.requestFocus();
return;
}
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_REGISTER,
new Response.Listener<String>() {
#Override
public void onResponse(String Response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(Response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
}) {
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phone);
params.put("lastname", lname);
params.put("fullname", fname);
params.put("middleinitial", mname);
params.put("country", count);
params.put("address",add);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
this code got the error of JSON Array cannot be converted while my Login Code with the same format is working
this is my login code:
private void userLogin(){
//first getting the values
final String phonenumber = etNumber.getText().toString();
//validating inputs
if (TextUtils.isEmpty(phonenumber)) {
etNumber.setError("Please enter your Number");
etNumber.requestFocus();
return;
}
//if everything is fine
StringRequest stringRequest = new StringRequest(Request.Method.POST, URLs.URL_LOGIN,
new Response.Listener<String>() {
#Override
public void onResponse(String response) {
try {
//converting response to json object
JSONObject obj = new JSONObject(response);
//if no error in response
if (!obj.getBoolean("error")) {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
//getting the user from the response
JSONObject userJson = obj.getJSONObject("user");
//creating a new user object
User user = new User(
userJson.getString("phone_number"),
userJson.getString("lastname"),
userJson.getString("fullname"),
userJson.getString("middleinitial"),
userJson.getString("country"),
userJson.getString("address")
);
//storing the user in shared preferences
SharedPrefManager.getInstance(getApplicationContext()).userLogin(user);
//starting the profile activity
finish();
startActivity(new Intent(getApplicationContext(), MainActivity.class));
} else {
Toast.makeText(getApplicationContext(), obj.getString("message"), Toast.LENGTH_SHORT).show();
}
} catch (JSONException e) {
e.printStackTrace();
}
}
},
new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Toast.makeText(getApplicationContext(), error.getMessage(), Toast.LENGTH_SHORT).show();
}
})
{
#Override
protected Map<String, String> getParams() throws AuthFailureError {
Map<String, String> params = new HashMap<>();
params.put("phone_number", phonenumber);
return params;
}
};
VolleySingleton.getInstance(this).addToRequestQueue(stringRequest);
}
and the error I got on my Logs is this:
W/System.err: org.json.JSONException: Value [] of type org.json.JSONArray cannot be converted to JSONObject
at org.json.JSON.typeMismatch(JSON.java:112)
at org.json.JSONObject.<init>(JSONObject.java:168)
at org.json.JSONObject.<init>(JSONObject.java:181)
at com.example.redwallet.Register$4.onResponse(Register.java:127)
W/System.err: at com.example.redwallet.Register$4.onResponse(Register.java:120)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:82)
at com.android.volley.toolbox.StringRequest.deliverResponse(StringRequest.java:29)
at com.android.volley.ExecutorDelivery$ResponseDeliveryRunnable.run(ExecutorDelivery.java:102)
at android.os.Handler.handleCallback(Handler.java:883)
at android.os.Handler.dispatchMessage(Handler.java:100)
at android.os.Looper.loop(Looper.java:224)
at android.app.ActivityThread.main(ActivityThread.java:7562)
at java.lang.reflect.Method.invoke(Native Method)
at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:539)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:950)

Salesforce writing Test class of Future Method - Coverage 28%

I have a class where in I am trying to call a HTTP request. I have created a Mock Test and a Test class.
My Test class is successful with 28% code coverage but it fails in recognizing the call out methods I have used in my class Below is code
My Class -
public class PD_WelcomeMaroPost {
#future(callout=true)
public static void sendEmailThroughMaro(string myInpEmail) {
string successContacts = '';
string failureContacts = '';
List<Stripe_Subscripton__c> subsToUpdate = new List<Stripe_Subscripton__c>();
//List<Case> newCase = new List<Case>();
// SQL to fetch FBO who Joined Today
list<Account> conts = new list<Account> ([SELECT Id, name, Email_FLP_com__c,
(SELECT Id FROM Stripe_Subscriptons__r WHERE Start_Date__c= TODAY
AND Status__c='active'
AND Welcome_Email__C = false LIMIT 1)from account
where ID IN (select Distributor__c from Stripe_Subscripton__c
where Start_Date__c= TODAY AND Status__c='active'
AND Welcome_Email__C = false)
AND Email_FLP_com__c != NULL LIMIT 100]);
system.debug('>>>>>>>>>>' + conts);
overallEmail myEmail = new overallEmail();
for(Account c : conts){
string resultBodyGet = '';
myEmail.email.campaign_id = 172;
myEmail.email.contact.Email = c.Email_FLP_com__c;
myEmail.email.contact.first_name = c.name;
/**MAp<String, String> tags = new Map<String, String>();
tags.put('firstName', c.name);
myEmail.email.tags = tags;**/
system.debug('#### Input JSON: ' + JSON.serialize(myEmail));
try{
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Http http = new Http();
system.debug('Sending email');
HTTPResponse response = http.send(req);
system.debug('sent email');
resultBodyGet = response.getBody();
system.debug('Output response:' + resultBodyGet);
maroResponse myMaroResponse = new maroResponse();
myMaroResponse = (maroResponse) JSON.deserialize(resultBodyGet, maroResponse.class);
system.debug('#### myMaroResponse: ' + myMaroResponse);
if(myMaroResponse.message == 'Email was sent successfully')
successContacts = successContacts + ';' + c.Email_FLP_com__c;
else
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
}
catch (exception e) {
failureContacts = failureContacts + ';' + c.Email_FLP_com__c;
system.debug('#### Exception caught: ' + e.getMessage());
}
c.Stripe_Subscriptons__r[0].Welcome_Email__c = true;
c.Stripe_Subscriptons__r[0].Welcome_Email_Sent_Date__c = system.today();
subsToUpdate.add(c.Stripe_Subscriptons__r[0]);
}
Update subsToUpdate;
}
public class maroResponse {
public string message {get;set;}
}
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
//Public Map<String, String> tags;
}
public class contactJson {
public string email;
public string first_name;
}
}
My MockTest Class- I have used this Mockclass to generate Mock response. The documentation does not have a test method thus used the same format
#isTest
Global class PD_WelcomeMaroPostMock implements HttpCalloutMock {
Global HttpResponse respond(HttpRequest req) {
// Create a fake response
//
//System.assertEquals(JSON.serialize(myEmail),req.getbody());
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
res.setBody('{"status":"success"}');
res.setStatusCode(200);
return res;
}
}
This is my Test class - This is the class I have used for the response. I have a successful insert job but my HTTP responses are failing.
#IsTest
private class PD_WelcomeMaroPost_test {
public class overallEmail {
public emailJson email = new emailJson();
}
public class emailJson {
public Integer campaign_id;
public contactJson contact = new contactJson();
}
public class contactJson {
public string email;
public string first_name;
}
#IsTest
private static void testemail() {
overallEmail myEmail = new overallEmail();
Account a = new Account();
a.Name ='Test' ;
a.Email_FLP_com__c = 'test#nextsphere.com';
insert a ;
Stripe_Subscripton__c s = new Stripe_Subscripton__c();
// insert subscription --
s.Distributor__c = a.Id;
S.Welcome_Email__c = TRUE;
S.Welcome_Email_Sent_Date__c = system.today();
s.Subscription_Id__c = 'sub_9H0LLYFZkekdMA' ;
INSERT S;
Test.setMock(HttpCalloutMock.class, new PD_WelcomeMaroPostMock());
String endpoint = 'http://api.maropost.com/accounts/1173/emails/deliver.json?auth_token=j-V4sx8ueUT7eKM8us_Cz5JqXBzoRrNS3p1lEZyPUPGcwWNoVNZpKQ';
HttpRequest req = new HttpRequest();
req.setEndpoint(endpoint);
req.setMethod('POST');
req.setHeader('Content-type', 'application/json');
req.setbody(JSON.serialize(myEmail));
Test.startTest();
PD_WelcomeMaroPost.sendEmailThroughMaro('test#nextsphere.com');
Test.stopTest();
}
}
When declaring a Mock myself, I declare it inside the test start transaction:
Test.startTest();
Test.setMock(WebServiceMock.class, new WebServiceMockImpl());
// Rest of test code here
Test.stopTest();
Also inside your test class you seem to only build the HTTP request and not send it try adding the below:
HttpResponse res = http.send(req);
if (res.getStatusCode() == 200) { } else { }

how to display files from ftp server to a local windows application gridview

i have uploaded my files to ftb server, now i want to display that files in my local windows application gridview
i want to display that files in datagridview.
public List<string> ListFiles()
{
// Get the object used to communicate with the server.
var request = (FtpWebRequest)WebRequest.Create("ftp://ipaddress/Requests/");
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential("username", "password");
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
files.Add(line.Split(new[] { ' ', '\t' }).Last());
}
}
return files;
}
}
}
following is the code on my load form.
FTPItility is my class in which listfiles is a method
FTPUtility obj = new FTPUtility();
List<string> strings = new List<string>();
dataGridViewRequest.DataSource = obj.ListFiles();
Here is the code you can use.
Here is code of FtpUtility:
public class FtpUtility
{
public string UserName { get; set; }
public string Password { get; set; }
public string Path { get; set; }
public List<string> ListFiles()
{
var request = (FtpWebRequest)WebRequest.Create(Path);
request.Method = WebRequestMethods.Ftp.ListDirectoryDetails;
request.Credentials = new NetworkCredential(UserName, Password);
List<string> files = new List<string>();
using (var response = (FtpWebResponse)request.GetResponse())
{
using (var responseStream = response.GetResponseStream())
{
var reader = new StreamReader(responseStream);
while (!reader.EndOfStream)
{
var line = reader.ReadLine();
if (string.IsNullOrWhiteSpace(line) == false)
{
var fileName = line.Split(new[] { ' ', '\t' }).Last();
if (!fileName.StartsWith("."))
files.Add(fileName);
}
}
return files;
}
}
}
}
And here is the code of form:
I have created an instance of FtpUtility and passed requiered parameters to it, then get the files and put it in a friendly list(Name, Path) and bind to grid:
private void Form1_Load(object sender, EventArgs e)
{
this.LoadFiles();
}
public void LoadFiles()
{
var ftp = new FtpUtility();
ftp.UserName = "username";
ftp.Password = "password";
ftp.Path = "ftp://address";
this.dataGridView1.DataSource = ftp.ListFiles()
.Select(x => new
{
Name = x, //Name Column
Path = ftp.Path + x //Path Column
}).ToList();
}

android app development-passing parameter to database

I am trying to connect my app to database on localhost server.I can connect to it ut the problem is how to pass the parameter from app to php script.for eg i want all names having age less than 10 so i will pass the parameter to php.below is my code for connecting to database.please provide good reference
/* */
enter code here
public class TestExternalDatabaseActivity extends Activity {
/** Called when the activity is first created. */
TextView resultView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
StrictMode.enableDefaults(); //STRICT MODE ENABLED
resultView = (TextView) findViewById(R.id.result);
getData();
}
public void getData(){
String result = "";
InputStream isr = null;
try{
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("http://localhost/tahseen0amin/php/getAllCustomers.php"); //YOUR PHP SCRIPT ADDRESS
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
isr = entity.getContent();
}
catch(Exception e){
Log.e("log_tag", "Error in http connection "+e.toString());
resultView.setText("Couldnt connect to database");
}
//convert response to string
try{
BufferedReader reader = new BufferedReader(new InputStreamReader(isr,"iso-8859-1"),8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
isr.close();
result=sb.toString();
}
catch(Exception e){
Log.e("log_tag", "Error converting result "+e.toString());
}
//parse json data
try {
String s = "";
JSONArray jArray = new JSONArray(result);
for(int i=0; i<jArray.length();i++){
JSONObject json = jArray.getJSONObject(i);
s = s +
"Name : "+json.getString("FirstName")+" "+json.getString("LastName")+"\n"+
"Age : "+json.getInt("Age")+"\n"+
"Mobile Using : "+json.getString("Mobile")+"\n\n";
}
resultView.setText(s);
} catch (Exception e) {
// TODO: handle exception
Log.e("log_tag", "Error Parsing Data "+e.toString());
}
}
}

Async call of WCF using Duplex Communication to get Database change

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

Resources