Async call of WCF using Duplex Communication to get Database change - wpf

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

Related

How to display channels in ListView using Graph API?

I’m developing a small Windows form app to test Graph API functions. I have two functionalities in the application, user's log in and get channels for specified team. I created a class that contains functions for user login and for returning channels for specified team. I have a ListView on Form in which I want to show all the channels, but when I call a function for returning channels in button event, nothing happens, nothing is displayed in the ListView. Here is the code:
public static class GraphHelper
{
public static GraphServiceClient graphClient;
public static string token;
private static string[] scopes = new string[] { "user.read" };
public static string TokenForUser = null;
public static DateTimeOffset expiration;
private const string ClientId = "599ed98d-4356-4a96-ad37-04391e9c48dc";
private const string Tenant = "common"; // Alternatively "[Enter your tenant, as obtained from the Azure portal, e.g. kko365.onmicrosoft.com]"
private const string Authority = "https://login.microsoftonline.com/" + Tenant;
// The MSAL Public client app
private static IPublicClientApplication PublicClientApp;
private static string MSGraphURL = "https://graph.microsoft.com/beta/";
private static AuthenticationResult authResult;
public static GraphServiceClient GetGraphClient(string token)
{
if (graphClient == null)
{
// Create Microsoft Graph client.
try
{
graphClient = new GraphServiceClient(
"https://graph.microsoft.com/v1.0",
new DelegateAuthenticationProvider(
async (requestMessage) =>
{
requestMessage.Headers.Authorization = new AuthenticationHeaderValue("bearer", token);
// This header has been added to identify our sample in the Microsoft Graph service. If extracting this code for your project please remove.
requestMessage.Headers.Add("SampleID", "uwp-csharp-snippets-sample");
}));
return graphClient;
}
catch (Exception ex)
{
Debug.WriteLine("Could not create a graph client: " + ex.Message);
}
}
return graphClient;
}
public static async Task<string> GetTokenForUserAsync()
{
if (TokenForUser == null || expiration <= DateTimeOffset.UtcNow.AddMinutes(10))
{
PublicClientApp = PublicClientApplicationBuilder.Create(ClientId)
.WithAuthority(Authority)
.WithRedirectUri("https://login.microsoftonline.com/common/oauth2/nativeclient")
.WithLogging((level, message, containsPii) =>
{
Debug.WriteLine($"MSAL: {level} {message} ");
}, LogLevel.Warning, enablePiiLogging: false, enableDefaultPlatformLogging: true)
.Build();
// It's good practice to not do work on the UI thread, so use ConfigureAwait(false) whenever possible.
IEnumerable<IAccount> accounts = await PublicClientApp.GetAccountsAsync().ConfigureAwait(false);
IAccount firstAccount = accounts.FirstOrDefault();
try
{
authResult = await PublicClientApp.AcquireTokenSilent(scopes, firstAccount)
.ExecuteAsync();
}
catch (MsalUiRequiredException ex)
{
// A MsalUiRequiredException happened on AcquireTokenSilentAsync. This indicates you need to call AcquireTokenAsync to acquire a token
Debug.WriteLine($"MsalUiRequiredException: {ex.Message}");
authResult = await PublicClientApp.AcquireTokenInteractive(scopes)
.ExecuteAsync()
.ConfigureAwait(false);
}
TokenForUser = authResult.AccessToken;
}
return TokenForUser;
}
public static async Task<User> GetMeAsync(string token)
{
GraphHelper.graphClient = GraphHelper.GetGraphClient(token);
try
{
// GET /me
return await GraphHelper.graphClient.Me
.Request()
.Select(u => new
{
u.DisplayName
})
.GetAsync();
}
catch (ServiceException ex)
{
Console.WriteLine($"Error getting signed-in user: {ex.Message}");
return null;
}
}
public static async Task<IEnumerable<Channel>> GetChannels(string teamId)
{
graphClient = GetGraphClient(token);
var channels = await graphClient.Teams[teamId].Channels
.Request()
.GetAsync();
return channels;
}
}
public partial class Form1 : Form
{
public static GraphServiceClient graphClient;
public static string token;
public Form1()
{
InitializeComponent();
}
private async void button1_Click(object sender, EventArgs e)
{
token = await GraphHelper.GetTokenForUserAsync();
User graphUser = await GraphHelper.GetMeAsync(token);
label2.Text = graphUser.DisplayName;
}
private async void button3_Click(object sender, EventArgs e)
{
var channels = GraphHelper.GetChannels("8557483b-a233-4710-82de-e1bdb03bb9a9").Result;
foreach (var ch in channels)
{
ListViewItem item = new ListViewItem(new string[] { ch.DisplayName, ch.Id});
listView1.Items.Add(item);
}
}
}
Does anyone how to solve this?
Try to call GraphHelper.GetChannels with await keyword on button click.
var channels = await GraphHelper.GetChannels("8557483b-a233-4710-82de-e1bdb03bb9a9");

Exception thrown: 'System.Net.WebException' in System.dll

In the button click event of below code, I'm able to send my data to post action of API Controller now.
Button Click Event of Windows Form
private void button1_Click(object sender, EventArgs e)
{
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.ContentType] = "application/json";
MyClass myClass = new MyClass();
myClass.SearchText = textBox1.Text;
myClass.CountryCode = textBox2.Text;
string serialisedData = JsonConvert.SerializeObject(myClass);
var response = client.UploadString("http://localhost:50232/api/Place/PostSimple", serialisedData);
var x= JsonConvert.DeserializeObject(response);
}
}
public class MyClass
{
public string SearchText { get; set; }
public string CountryCode { get; set; }
}
But while debugging, I'm not able to move after
GeocodingResponse geocode = GoogleMaps.Geocode.Query(geocodeRequest);
this line of PostSimple action method. and getting the exception in
var response = client.UploadString("http://localhost:50232/api/Place/PostSimple", serialisedData); of Windows form application as
Exception thrown: 'System.Net.WebException' in System.dll
Additional information: The operation has timed out
ApiController Code
[HttpPost]
public List<Place> PostSimple(MyClass value)
{
List<Place> list = new List<Place>();
var geocodeRequest = new GeocodingRequest
{
Address = value.SearchText,
Components = new GeocodingComponents()
{
Country = value.CountryCode
}
};
try
{
GeocodingResponse geocode = GoogleMaps.Geocode.Query(geocodeRequest);
if (geocode.Status == GoogleMapsApi.Entities.Geocoding.Response.Status.OK)
{
TimeZoneRequest request = new TimeZoneRequest();
request.Location = new Location(geocode.Results.First().Geometry.Location.Latitude, geocode.Results.First().Geometry.Location.Longitude);
request.Language = "en";
request.TimeStamp = DateTime.Now.AddDays(-60);
TimeZoneResponse result = GoogleMaps.TimeZone.Query(request);
var x = System.TimeZoneInfo.FindSystemTimeZoneById(result.TimeZoneName);
}
}
catch (Exception ex)
{
throw ex;
}
return list;
}
MyClass code
public class MyClass
{
public string SearchText { get; set; }
public string CountryCode { get; set; }
}
Can anyone help me to solve this issue..Thanks in Advance

How to connect to SQL Server from .Net Core without using Entity Framework?

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

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,

How do I open a TCP socket from SilverLight?

I need to know how to open a TCP socket connection from Silverlight. How is it done?
A quick google search delivers this site
Silverlight 2 and System.Net.Sockets.Socket
namespace SilverlightSocketClient
{
public partial class Page : UserControl
{
public Page()
{
InitializeComponent();
this.Loaded += PageLoaded;
}
void PageLoaded(object sender, RoutedEventArgs e)
{
var endPoint = new DnsEndPoint(Application.Current.Host.Source.DnsSafeHost, 4530);
var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
var args = new SocketAsyncEventArgs {UserToken = socket, RemoteEndPoint = endPoint};
args.Completed += OnSocketConnectCompleted;
socket.ConnectAsync(args);
}
private void OnSocketConnectCompleted(object sender, SocketAsyncEventArgs e)
{
var response = new byte[1024];
e.SetBuffer(response, 0, response.Length);
e.Completed -= OnSocketConnectCompleted;
e.Completed += OnSocketReceive;
var socket = (Socket)e.UserToken;
socket.ReceiveAsync(e);
}
private void OnSocketReceive(object sender, SocketAsyncEventArgs e)
{
StringReader sr = null;
try
{
string data = Encoding.UTF8.GetString(e.Buffer, e.Offset, e.BytesTransferred);
sr = new StringReader(data);
//Get data
if (data.Contains("Product"))
{
var xs = new XmlSerializer(typeof(Product));
var product = (Product) xs.Deserialize(sr);
Dispatcher.BeginInvoke(UpdateOrder);
}
//Get another type of data
if (data.Contains("Order"))
{
var xs = new XmlSerializer(typeof(Order));
var order = (Order)xs.Deserialize(sr);
var handler = new SomeEventHandler(UpdateOrder);
this.Dispatcher.BeginInvoke(handler, new object[]
{
order
});
}
}
catch (Exception ex)
{
//handle exception
}
finally
{
if (sr != null) sr.Close();
}
//Prepare to receive more data
var socket = (Socket)e.UserToken;
socket.ReceiveAsync(e);
}
}
}
Take a look at the Socket class in Silverlight. The MSDN documentation has a good sample.

Resources