How do I change the SMTP Client, User and Password dynamically in MVC Mailer? - smtpclient

In the step by step guide at:
https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide
It is stated that the .net mail lib is used (System.Net.Mail).
In medical transactions, there is a need to change servers based on country region and record if the mail message was sent with status.
.net mail lib will do this but I have trouble understanding where to put the following code pieces when Using MVC Mailer:
.net Mail Lib-->
SmtpClient client = new SmtpClient(server, port);
client.credentials = CredentialCache.DefaultNetworkCredentials;
MVC Mailer-->
public ActionResult SendWelcomeMessage()
{
UserMailer.SmtpClient(server, port);
UserMailer.credentials = CredentialCache.DefaultNetworkCredentials;
UserMailer.Welcome().SendAsync();
return RedirectToAction("Index");
}
static bool mailSent = false;
private static void SendCompletedCallback(object sender, AsyncCompletedEventArgs e)
{
// Get the unique identifier for this asynchronous operation.
String token = (string) e.UserState;
if (e.Cancelled)
{
Console.WriteLine("[{0}] Send canceled.", token);
}
if (e.Error != null)
{
Console.WriteLine("[{0}] {1}", token, e.Error.ToString());
} else
{
Console.WriteLine("Message sent.");
}
mailSent = true;
}
if MailSent is false, then write to Critical Log Error.
I am not sure where the client setting for .net setting should go.
Should they go in the controller as I have done above or in the Mailer method.
Thanks for any advice.
Regards,
Vic

I had the same need.
To do so, i have created a custom mail sender class :
Public Class CustomMailSender
Inherits System.Net.Mail.SmtpClient
Implements ISmtpClient
Public Sub Init(senderEmail As String, password As String)
Me.Credentials = New System.Net.NetworkCredential(senderEmail, password)
End Sub
Public Overloads Sub SendAsync(mail As MailMessage) Implements ISmtpClient.SendAsync
MyBase.SendAsync(mail, Nothing)
End Sub
Public Overloads Sub SendAsync(mail As MailMessage, userToken As Object) Implements ISmtpClient.SendAsync
MyBase.SendAsync(mail, userToken)
End Sub
Public Overloads Sub Send(mail As MailMessage) Implements ISmtpClient.Send
MyBase.Send(mail)
End Sub
Public Shadows Event SendCompleted(sender As Object, e As System.ComponentModel.AsyncCompletedEventArgs) Implements ISmtpClient.SendCompleted
End Class
Then inside your email controller, you use it like that
Public Class EmailController
Inherits MailerBase
Public Sub New()
MyBase.New()
Me.CustomMailSender = New CustomMailSender
End Sub
Public Property CustomMailSender As CustomMailSender
Public Sub Sample()
Dim mvcMailMessage As MvcMailMessage = Populate(Sub(i)
i.ViewName = "Sample"
i.To.Add("some1#somewhere.org")
i.Subject = "Boo!"
End Sub)
mvcMailMessage.Send(Me.CustomMailSender)
End Sub
End Class
Yeah, i know that's VB, but i'm a VB guy ! :>
Hope this helps :)

Related

How to create new record from web service in ADF?

I have created a class and published it as web service. I have created a web method like this:
public void addNewRow(MyObject cob) {
MyAppModule myAppModule = new MyAppModule();
try {
ViewObjectImpl vo = myAppModule.getMyVewObject1();
================> vo object is now null
Row r = vo.createRow();
r.setAttribute("Param1", cob.getParam1());
r.setAttribute("Param2", cob.getParam2());
vo.executeQuery();
getTransaction().commit();
} catch (Exception e) {
e.printStackTrace();
}
}
As I have written in code, myAppModule.getMyVewObject1() returns a null object. I do not understand why! As far as I know AppModule has to initialize the object by itself when I call "getMyVewObject1()" but maybe I am wrong, or maybe this is not the way it should be for web methods. Has anyone ever faced this issue? Any help would be very appreciated.
You can check nice tutorial: Building and Using Web Services with JDeveloper
It gives you general idea about how you should build your webservices with ADF.
Another approach is when you need to call existing Application Module from some bean that doesn't have needed environment (servlet, etc), then you can initialize it like this:
String appModuleName = "org.my.package.name.model.AppModule";
String appModuleConfig = "AppModuleLocal";
ApplicationModule am = Configuration.createRootApplicationModule(appModuleName, appModuleConfig);
Don't forget to release it:
Configuration.releaseRootApplicationModule(am, true);
And why you shouldn't really do it like this.
And even more...
Better aproach is to get access to binding layer and do call from there.
Here is a nice article.
Per Our PM : If you don't use it in the context of an ADF application then the following code should be used (sample code is from a project I am involved in). Note the release of the AM at the end of the request
#WebService(serviceName = "LightViewerSoapService")
public class LightViewerSoapService {
private final String amDef = " oracle.demo.lightbox.model.viewer.soap.services.LightBoxViewerService";
private final String config = "LightBoxViewerServiceLocal";
LightBoxViewerServiceImpl service;
public LightViewerSoapService() {
super();
}
#WebMethod
public List<Presentations> getAllUserPresentations(#WebParam(name = "userId") Long userId){
ArrayList<Presentations> al = new ArrayList<Presentations>();
service = (LightBoxViewerServiceImpl)getApplicationModule(amDef,config);
ViewObject vo = service.findViewObject("UserOwnedPresentations");
VariableValueManager vm = vo.ensureVariableManager();
vm.setVariableValue("userIdVariable", userId.toString());
vo.applyViewCriteria(vo.getViewCriteriaManager().getViewCriteria("byUserIdViewCriteria"));
Row rw = vo.first();
if(rw != null){
Presentations p = createPresentationFromRow(rw);
al.add(p);
while(vo.hasNext()){
rw = vo.next();
p = createPresentationFromRow(rw);
al.add(p);
}
}
releaseAm((ApplicationModule)service);
return al;
}
Have a look here too:
http://www.youtube.com/watch?v=jDBd3JuroMQ

Is it possible / good idea to use Akka for multithreading in a Glassfish EAR?

Context:
This is a client server app. At the moment the EJB looks like:
public class ServerSideJob {
#WebMethod(operationName = "launchJob")
public String launchJob(#WebParam(name = "idUser") String idUser, #WebParam(name = "name") String name, #WebParam(name = "param") Object param) {
Runnable controller = new JobController(screenName, fof, mm, job);
new Thread(controller).start();
return "job launched";
}
}
The job is launching several other threads.
At this point, I'd like to add the possibility for the client to interrupt the job. Interrupting a thread from "the outside" is quite a dirty affair (I'd have to add many more calls per op to a db just for that), and this prompts me to switch to Akka for the multithreading.
Problem: I am not sure how / if I can merge the Akka logic with the code of the EJB above. How do I call the top actor of my hierarchy from my launchJob function? (ok, surely a noob question...)
public class ServerSideJob {
#WebMethod(operationName = "launchJob")
public String launchJob(#WebParam(name = "idUser") String idUser, #WebParam(name = "name") String name, #WebParam(name = "param") Object param) {
//how do I call my Akka actor here?
return "job launched";
}
}
That was indeed a noob question. I did not know how to do that because, following the "hello world" example on akka.io, the app was launched without an ActorSystem so I ignored it. An ActorSystem is simply what you need:
One class for the ActorSystem, to be launched at the start up at the app:
#Singleton
#Startup
// initialize at deployment time instead of first invocation
public class SharedActorSystem {
ActorSystem system;
#PostConstruct
void loadConfiguration() {
system = ActorSystem.create("systemJobs");
}
public ActorSystem getSystem() {
return system;
}
}
And the class with the server side job:
public class ServerSideJob {
#EJB
SharedActorSystem sharedActorSystem;
#WebMethod(operationName = "launchJob")
public String launchJob(#WebParam(name = "idUser") String idUser) {
//getting the ActorSystem
ActorSystem system = sharedActorSystem.getSystem();
final ActorRef myActor = system.actorOf(Props.create(MyActor.class));
MsgLaunchActor msg = new MsgLaunchActor(idUser);
myActor.tell(msg, ActorRef.noSender());
return "job launched";
}
}

phpunit mock web service(not WSDL)

I have a small problem which I think is quite simple to solve for experienced PHPUnit users.
I'm working with ZF2.
I'm working with a web service that returns plain text(CSV). I'd like to unit test the service that I've created.
I currently have a working configuration which is not the right way to do it I think.. I'm using mocks now when I'm unit testing my models and I have seen that PHPUnit has a special mock for web services, but that only supports WSDL.
Beneath you'll find my code and I hope someone can help me out with some explanation about the best practice for this situation.
The docs and the topics out here did not help me out (yet).
Thanks in advance!
The test itself:
public function testCanSearchSteeringWheels()
{
// Create the entry and fill it with the data that should be retrieved from the web service
$steeringWheelEntity = new SteeringWheelEntity();
$steeringWheelEntity->setId('170633')
->setName('Nice steering wheel one')
->setGrossPrice(100)
->setNetPrice(75);
// Setup the http client which whill make the final call to the web service
$httpClient = new Client();
$httpClient->setOptions(array(
'maxredirects' => 5,
'timeout' => 60,
))
->setAuth($this->config['supplier_name']['api']['username'], $this->config['supplier_name']['api']['password'])
;
$steeringWheelService = new SteeringWheelService($httpClient, new Request(), $this->config['supplier_name']);
// Search for a steering wheel by id code
$searchResult = $steeringWheelService->search('ID=5221552658987');
$this->assertEquals($steeringWheelEntity, $searchResult[0]);
}
The SteeringWheelEntity
namespace SupplierName\Entity;
class SteeringWheelEntity
{
// vars
// exchange array method
// getters methods
// setters methods
}
The SteeringWheelService
namespace SupplierName\Service;
use SupplierName\Entity\SteeringWheelEntity;
class SteeringWheelService extends AbstractWebService
{
/**
* search()
*
* #param string $param
* #return array
*/
public function search($param)
{
$this->appendUrl('ww0800?3,' . $param);
$response = $this->dispatch();
$parsedBody = $this->parse($response->getBody());
$entities = array();
foreach ($parsedBody as $data)
{
$steeringWheel = new SteeringWheelEntity();
// Fill SteeringWheelEntity with data
$entities[] = $steeringWheel;
}
return $entities;
}
}
The AbstractWebService
use \Zend\Http\Client;
use \Zend\Http\Request;
class AbstractWebService
{
private $httpClient;
private $request;
private $response;
protected $config;
private $url;
public function __construct(Client $httpClient, Request $request, Array $config)
{
$this->url = $config['api']['url'];
$this->httpClient = $httpClient;
$this->request = $request;
$this->config = $config;
}
protected function setUrl($url)
{
$this->url = $url;
return $this->url;
}
protected function appendUrl($string)
{
$this->url .= $string;
}
protected function getUrl()
{
return $this->url;
}
public function dispatch()
{
$this->request->setUri($this->getUrl());
$this->response = $this->httpClient->dispatch($this->request);
if (!$this->response->isSuccess()) {
throw new \Exception('HTTP error #' . $this->response->getStatusCode() . ' when connecting to ' . $this->getUrl() . '.');
}
return $this->response;
}
public function parse()
{
// Parse the content
}
}
Rather than using a mock for a web service. Could you just mock the \Zend\Http\Request and \Zend\Http\Client objects as they are doing the work for you? This way you have control over what the Zend objects return to you versus having to try to mock the web service.
That would be how I would go about testing the services.

Create a webservice

How do I create a webservice using Mono For Android? It seems like everything is about consuming a webservice, and not really about creating one.
I've tried using this: http://www.mono-project.com/Writing_a_WebService
But System.Web.Services.WebService doesn't exist. System.ServiceModel hasn't been translated yet either. Does anyone have clues on how to create a webservice on Mono For Android?
Thanks
I have now tried to implement the following code and tried to run it in the emulator, but the request I make either through my browser or through a REST client, never reaches the HandleRequest.
protected override void OnCreate(Bundle bundle) {
base.OnCreate(bundle);
// Set our view from the "main" layout resource
SetContentView(Resource.Layout.Main);
var startBtn = FindViewById<Button>(Resource.Id.StartBtn);
stopBtn.Clickable = false;
startBtn.Click += SetupListener;
}
private void SetupListener(object sender, EventArgs e) {
_httpListener = new HttpListener();
_httpListener.Prefixes.Add("http://*:9876/");
_httpListener.Start();
_httpListener.BeginGetContext(HandleRequest, _httpListener);
}
private void HandleRequest(IAsyncResult result) {
var context = _httpListener.EndGetContext(result);
var response = "<html>Hello World</html>";
var buffer = Encoding.UTF8.GetBytes(response);
context.Response.ContentLength64 = buffer.Length;
context.Response.OutputStream.Write(buffer, 0, buffer.Length);
context.Response.OutputStream.Close();
_httpListener.BeginGetContext(HandleRequest, _httpListener);
}
I have tried making request like the following: http:// localhost:9876/ , http:// 10.1.1.190:9876/ and http:// 10.0.2.2:9876/ but none of them actually reaches into the application.

How to send additional fields to soap handler along with soapMessage?

I am logging RequestXML for a webservice client using SoapHandler as follows
public boolean handleMessage(SOAPMessageContext smc) {
logToSystemOut(smc);
return true;
}
private void logToSystemOut(SOAPMessageContext smc) {
Boolean outboundProperty = (Boolean)
smc.get (MessageContext.MESSAGE_OUTBOUND_PROPERTY);
if (outboundProperty.booleanValue()) {
out.println("\nOutbound message:");
} else {
out.println("\nInbound message:");
}
SOAPMessage message = smc.getMessage();
try {
message.writeTo(out);
out.println("");
} catch (Exception e) {
out.println("Exception in handler: " + e);
}
}
Got a new requirenment to add this xml to DB along with some extra values(which are not present in the xml). Is there any way I can pass few additional fields to above soap handler (in handleMessage method)?
Please note that changing the xml/WSDL or adding this to SOAP message header is not an option for me as it is owned by other interface. Any other solution?
Thanks!
You can cast your service class to a class of type "BindingProvider". In this form you can use it to assign it objects which you can access later from your SOAPHandler. Another useful usage is that you also can change the endPoint URL this way.
Before calling the service you do:
MySoapServicePortType service = new MySoapService().getMySoapServicePort();
BindingProvider bp = (BindingProvider)service;
MyTransferObject t = new MyTransferObject();
bp.getRequestContext().put("myTransferObject", t);
TypeResponse response = service.doRequest();
SOAPMessage message = t.getRequestMessage(message);
From your logging function you do:
private void logToSystemOut(SOAPMessageContext smc) {
...
MyTransferObject t = (MyTransferObject) messageContext.get("myTransferObject");
if (outboundProperty.booleanValue())
t.setRequestMessage(message);
else
t.setResponseMessage(message);
...
}