I have WSDL file which contains:
<wsdl:port name="NotificationConsumerSoapJms"
binding="tns_NotificationConsumer:NotificationConsumerSoapJmsBinding">
<jms:address destinationStyle="topic"
jndiConnectionFactoryName="ConnectionFactory"
jndiDestinationName="dynamicTopics/test.DefaultTopic">
<jms:JMSNamingProperty name="java.naming.factory.initial"
value="org.apache.activemq.jndi.ActiveMQInitialContextFactory" />
<jms:JMSNamingProperty name="java.naming.provider.url"
value="tcp://localhost:61616" />
</jms:address>
</wsdl:port>
And here is JMS client which was generated by CXF:
URL wsdlURL = EfaNbiWebService.WSDL_LOCATION;
if (args.length > 0 && args[0] != null && !"".equals(args[0])) {
File wsdlFile = new File(args[0]);
try {
if (wsdlFile.exists()) {
wsdlURL = wsdlFile.toURI().toURL();
} else {
wsdlURL = new URL(args[0]);
}
} catch (MalformedURLException e) {
e.printStackTrace();
}
}
EfaNbiWebService ss = new EfaNbiWebService(wsdlURL, SERVICE_NAME);
NotificationConsumer port = ss.getNotificationConsumerSoapJms();
{
System.out.println("Invoking notify...");
org.tmforum.mtop.fmw.xsd.hdr.v1.Header _notify_mtopHeader = null;
org.tmforum.mtop.fmw.xsd.notmsg.v1.Notify _notify_mtopBody = null;
port.notify(_notify_mtopHeader, _notify_mtopBody);
}
As you see, the topic name is store in WSDL file. So how to change topic name programmatically?
I found the solution:
JMSConfiguration jmsConfig = new JMSConfiguration();
ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory("tcp://" + activeMQServer + ":61616");
jmsConfig.setConnectionFactory(connectionFactory);
jmsConfig.setTargetDestination("dynamicTopics/Test.Notification_" + topic);
jmsConfig.setReconnectOnException(false);
//jmsConfig.se
jmsConfig.setPubSubDomain(true);
jmsConfig.setUseJms11(true);
jmsConfig.setTransactionManager(new JmsTransactionManager(connectionFactory));
JMSConfigFeature jmsConfigFeature = new JMSConfigFeature();
jmsConfigFeature.setJmsConfig(jmsConfig);
String address = "jms:jndi:dynamicTopics/Test.Notification_" + topic + "?jndiInitialContextFactory=org.apache.activemq.jndi.ActiveMQInitialContextFactory&jndiConnectionFactoryName=ConnectionFactory&jndiURL=tcp://" + activeMQServer + ":61616";
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
// And specify the transport ID with SOAP over JMS specification
factory.setTransportId(JMSSpecConstants.SOAP_JMS_SPECIFICATION_TRANSPORTID);
factory.setServiceClass(NotificationConsumer.class);
factory.getFeatures().add(jmsConfigFeature);
factory.setAddress(address);
NotificationConsumer client = (NotificationConsumer)factory.create();
Have a nice day, guys :)
Related
Ive gone through many posts, but none seem to work.
I have an MVC application hosted in Azure as an app service and sending of mails is not working. It works on my local.
I have my SMTP details stored in my Web.Config:
Web.Config
<appSettings>
<!--To Send Mail-->
<add key="MailServerSMTP" value="mail.appname.com" />
<add key="MailServerSMTP_UserName" value="alerts#appname.com" />
<add key="MailServerSMTP_Password" value="Password" />
</appSettings>
Below is my sending function:
Email sending function
public void SendMessage(string subject, string messageBody, string fromAddress, string toAddress, string ccAddress, string sFileName, string sFileName2)
{
try
{
MailMessage message = new MailMessage();
SmtpClient client = new SmtpClient();
//Thread T1 = new Thread(delegate ()
//{
//Set the sender's address
message.From = new MailAddress(fromAddress);
//Allow multiple "To" addresses to be separated by a semi-colon
if ((toAddress.Trim().Length > 0))
{
foreach (string addr in toAddress.Split(';'))
{
message.To.Add(new MailAddress(addr));
}
}
//Allow multiple "Cc" addresses to be separated by a semi-colon
if ((ccAddress.Trim().Length > 0))
{
foreach (string addr in ccAddress.Split(';'))
{
message.CC.Add(new MailAddress(addr));
}
}
//Set the subject and message body text
if (!string.IsNullOrEmpty(sFileName))
{
Attachment obAttachement = new Attachment(sFileName);
message.Attachments.Add(obAttachement);
}
if (!string.IsNullOrEmpty(sFileName2))
{
Attachment obAttachement = new Attachment(sFileName2);
message.Attachments.Add(obAttachement);
}
message.Subject = subject;
message.Body = messageBody;
message.IsBodyHtml = true;
string path = System.AppDomain.CurrentDomain.BaseDirectory;
path = path.Replace("bin\\Debug\\", "Content\\img");
//if (path.Substring(path.Length - 6) != "Images")
//{
// path = path + "Images";
//}
if (path.GetLast(6) != "Content\\img")
{
path = path + "Content\\img";
}
Attachment ImageAttachment = new Attachment(path + "\\SystemicLogic_Transparent.png");
// Set the ContentId of the attachment, used in body HTML
ImageAttachment.ContentId = "SystemicLogic_Transparent.png";
// Add an image as file attachment
message.Attachments.Add(ImageAttachment);
message.Body = messageBody;
//Set the SMTP server to be used to send the message
//client.Host = "smtp.jumpstartcom.co.za"
string sSMTP_Username = ConfigurationManager.AppSettings["MailServerSMTP_UserName"].ToString();
string sSMTP_Password = ConfigurationManager.AppSettings["MailServerSMTP_Password"].ToString();
string appname = ConfigurationManager.AppSettings["MailServerSMTP"];
client.Credentials = new System.Net.NetworkCredential(sSMTP_Username, sSMTP_Password);
client.Host = appname;
client.Port = 587;
//client.EnableSsl = true;
//Send the e-mail message
//client.SendAsync(message, null);
client.Send(message);
//});
//T1.Start();
}
catch (Exception ex)
{
}
}
I have tried enabling SSL and using port 25. I have tried setting the port to 465 and 587 and emails are not coming through though.
Is there a specific port that needs to be used, or something I am doing wrong ?
Thanks for any help in advance!
Currently I Am Using ADFS Login. i am Getting Response From Adfs Server. But I Can't get Any Information From Response Saml.What Can I Do getting Information Is it Right?
<br /><br />
<samlp:Response Consent="urn:oasis:names:tc:SAML:2.0:consent:unspecified"
Destination="https://demo.apps.com/adfsauthlogin/login"
ID="_cbb5174b-36b4-4e75-9d8a-7f2d47ccb9bc" IssueInstant="2018-01-08T06:09:16.122Z" Version="2.0"
xmlns:samlp="urn:oasis:names:tc:SAML:2.0:protocol">
<Issuer xmlns="urn:oasis:names:tc:SAML:2.0:assertion">http://adfs.Sample.com/adfs/services/trust</Issuer>
<samlp:Status><samlp:StatusCode Value="urn:oasis:names:tc:SAML:2.0:status:Success"/></samlp:Status>
<EncryptedAssertion xmlns="urn:oasis:names:tc:SAML:2.0:assertion">
<xenc:EncryptedData Type="http://www.w3.org/2001/04/xmlenc#Element"
xmlns:xenc="http://www.w3.org/2001/04/xmlenc#"><xenc:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#aes256-cbc"/>
<KeyInfo xmlns="http://www.w3.org/2000/09/xmldsig#">
<e:EncryptedKey xmlns:e="http://www.w3.org/2001/04/xmlenc#">
<e:EncryptionMethod Algorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"><DigestMethod Algorithm="http://www.w3.org/2000/09/xmldsig#sha1"/></e:EncryptionMethod>
<KeyInfo>
<ds:X509Data xmlns:ds="http://www.w3.org/2000/09/xmldsig#">
<ds:X509IssuerSerial>
<ds:X509IssuerName>CN=ADFS Encryption - demo.apps.com</ds:X509IssuerName>
<ds:X509SerialNumber>33157209971584938906555805034885884694</ds:X509SerialNumber>
</ds:X509IssuerSerial>
</ds:X509Data>
</KeyInfo>
<e:CipherData>
<e:CipherValue> ==- Value -== </e:CipherValue>
</e:CipherData>
</e:EncryptedKey>
</KeyInfo>
<xenc:CipherData>
<xenc:CipherValue> ==- Value -== </xenc:CipherValue>
</xenc:CipherData>
</xenc:EncryptedData>
</EncryptedAssertion>
</samlp:Response>
I was facing the same issue today and I found the solution to my problem from this thread How to Decrypt EncryptedAssertion using System.Cryptography
I did little tweaking to this to work for ADFS SAMLResponse.
Here is my solution....
private void DecryptSamlAssertion(XmlDocument xmlDocument, X509Certificate2 cert)
{
EncryptedXmlWithPreconfiguredAsymmetricKey encXml = new EncryptedXmlWithPreconfiguredAsymmetricKey(xmlDocument, cert);
if (xmlDocument.GetElementsByTagName("EncryptedAssertion").Count > 0)
{
var encryptedAssertion = xmlDocument.GetElementsByTagName("EncryptedAssertion")[0];
xmlDocument.DocumentElement.ReplaceChild(encryptedAssertion.FirstChild, encryptedAssertion);
while (xmlDocument.GetElementsByTagName("xenc:EncryptedData").Count > 0)
{
XmlElement encryptedDataElement = xmlDocument.GetElementsByTagName("xenc:EncryptedData")[0] as XmlElement;
EncryptedData encryptedData = new EncryptedData();
encryptedData.LoadXml(encryptedDataElement);
SymmetricAlgorithm symmKey = encXml.GetDecryptionKey(encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
symmKey.IV = encXml.GetDecryptionIV(encryptedData, encryptedData.EncryptionMethod.KeyAlgorithm);
symmKey.Padding = encXml.Padding;
symmKey.Mode = encXml.Mode;
byte[] decryptedData = encXml.DecryptData(encryptedData, symmKey);
encXml.ReplaceData(encryptedDataElement, decryptedData);
}
}
}
public class EncryptedXmlWithPreconfiguredAsymmetricKey : EncryptedXml
{
public readonly X509Certificate2 _encryptionCert;
public EncryptedXmlWithPreconfiguredAsymmetricKey(XmlDocument xmlDoc, X509Certificate2 encryptionCert) : base(xmlDoc)
{
_encryptionCert = encryptionCert;
}
public override SymmetricAlgorithm GetDecryptionKey(EncryptedData encryptedData, string symmetricAlgorithmUri)
{
if (encryptedData == null)
throw new ArgumentNullException("encryptedData");
if (encryptedData.KeyInfo == null)
return null;
IEnumerator keyInfoEnum = encryptedData.KeyInfo.GetEnumerator();
KeyInfoRetrievalMethod kiRetrievalMethod;
KeyInfoName kiName;
KeyInfoEncryptedKey kiEncKey;
EncryptedKey ek = null;
while (keyInfoEnum.MoveNext())
{
kiName = keyInfoEnum.Current as KeyInfoName;
kiRetrievalMethod = keyInfoEnum.Current as KeyInfoRetrievalMethod;
kiEncKey = keyInfoEnum.Current as KeyInfoEncryptedKey;
if (kiEncKey != null)
{
ek = kiEncKey.EncryptedKey;
break;
}
}
// if we have an EncryptedKey, decrypt to get the symmetric key
if (ek != null)
{
// now process the EncryptedKey, loop recursively
// If the Uri is not provided by the application, try to get it from the EncryptionMethod
if (symmetricAlgorithmUri == null)
{
if (encryptedData.EncryptionMethod == null)
throw new CryptographicException("Cryptography_Xml_MissingAlgorithm");
symmetricAlgorithmUri = encryptedData.EncryptionMethod.KeyAlgorithm;
}
byte[] key = ek.CipherData.CipherValue;
if (key == null)
throw new CryptographicException("Cryptography_Xml_MissingDecryptionKey");
// Ignore any information about the asymmetric key in the XML, and just use our predefined certificate
var rsaKey = (RSA)_encryptionCert.PrivateKey;
byte[] symkey = DecryptKey(key, rsaKey, true);
SymmetricAlgorithm symAlg = (SymmetricAlgorithm)CryptoConfig.CreateFromName(symmetricAlgorithmUri);
symAlg.Key = symkey;
return symAlg;
}
return null;
}
}
How can I get the all HTTP request headers, method, the suffix of the connection, and all parameters that I added to the request?
Try something like this (I ran this code on a background thread, which I why I use UiApplication.invokeLater() to display results):
try {
ConnectionFactory factory = new ConnectionFactory(); // for OS 5.0+
factory.setPreferredTransportTypes(new int[] {
TransportInfo.TRANSPORT_TCP_WIFI,
TransportInfo.TRANSPORT_TCP_CELLULAR
});
// For OS < 5.0
//HttpConnection conn = (HttpConnection) Connector.open("http://www.google.com;interface=wifi");
HttpConnection conn = (HttpConnection) factory.getConnection("http://www.google.com").getConnection();
conn.setRequestProperty("sessionId", "ABCDEF0123456789");
final StringBuffer results = new StringBuffer();
String key = "";
int index = 0;
// loop over all the header fields, and record their values
while (key != null) {
key = conn.getHeaderFieldKey(index);
if (key != null) {
String value = conn.getHeaderField(key);
results.append(key + " = " + value + "\n\n");
}
index++;
}
results.append("method = " + conn.getRequestMethod() + "\n\n");
// we (should) know which request properties we've set, so we ask
// for them by name here
String sessionId = conn.getRequestProperty("sessionId");
results.append("sessionId = " + sessionId + "\n\n");
String url = conn.getURL();
results.append("URL = " + url);
// show the result on screen (UI thread)
UiApplication.getUiApplication().invokeLater(new Runnable() {
public void run() {
textField.setText(results.toString());
}
});
} catch (IOException e) {
e.printStackTrace();
}
Ok - I have a WCF Service which reads an excel file from a certain location and strips the data into an object. What I need is the ability to allow users of my program to Upload an excel sheet to the file location that my Service uses.
Alternitivley I could pass the Uploaded excel sheet to the service directly.
Can anyone help with this. My service code is:
public List<ImportFile> ImportExcelData(string FileName)
{
//string dataSource = Location + FileName;
string dataSource = Location;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
var data = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
var sheetName = data.Rows[0]["TABLE_NAME"].ToString();
OleDbCommand cmd = new OleDbCommand("SELECT * FROM [" + sheetName + "] WHERE Status = '4'", con);
OleDbDataAdapter oleda = new OleDbDataAdapter();
oleda.SelectCommand = cmd;
DataSet ds = new DataSet();
oleda.Fill(ds, "Employees");
DataTable dt = ds.Tables[0];
var _impFiles = new List<ImportFile>();
foreach (DataRow row in dt.Rows)
{
var _import = new ImportFile();
_import.PurchaseOrder = row[4].ToString();
try
{
var ord = row[8].ToString();
DateTime dati = Convert.ToDateTime(ord);
_import.ShipDate = dati;
}
catch (Exception)
{
_import.ShipDate = null;
}
ImportFile additionalData = new ImportFile();
additionalData = GetAdditionalData(_import.PurchaseOrder);
_import.NavOrderNo = additionalData.NavOrderNo;
_import.IsInstall = additionalData.IsInstall;
_import.SalesOrderId = additionalData.SalesOrderId;
_import.ActivityID = additionalData.ActivityID;
_import.Subject = additionalData.Subject ;
_import.IsMatched = (_import.ShipDate != null & _import.NavOrderNo != "" & _import.NavOrderNo != null & _import.ShipDate > DateTime.Parse("01/01/1999") ? true : false);
_import.UpdatedShipToField = false;
_import.UpdatedShipToFieldFailed = false;
_import.CreateNote = false;
_import.CreateNoteFailed = false;
_import.CompleteTask = false;
_import.CompleteTaskFailed = false;
_import.FullyCompleted = 0;
_import.NotCompleted = false;
_impFiles.Add(_import);
}
oleda.Dispose();
con.Close();
//File.Delete(dataSource);
return _impFiles;
}
You will want to modify your service to accept a Stream instead of a filename, then you can save if off to a file (or parse it directly from the Stream, although I don't know how to do that).
Then in your Silverlight app you could do something like this:
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var fileStream = dialog.File.OpenRead();
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// don't forget to close the stream
fileStream.Close();
};
proxy.ImportExcelDataAsync(fileStream);
}
}
You could also have your WCF service accept a byte[] and do something like this.
private void Button_Click(object sender, RoutedEventArgs ev)
{
var dialog = new OpenFileDialog();
dialog.Filter = "Excel Files (*.xls;*.xlsx;*.xlsm)|*.xls;*.xlsx;*.xlsm|All Files (*.*)|*.*";
if (dialog.ShowDialog() == true)
{
var length = dialog.File.Length;
var fileContents = new byte[length];
using (var fileStream = dialog.File.OpenRead())
{
if (length > Int32.MaxValue)
{
throw new Exception("Are you sure you want to load > 2GB into memory. There may be better options");
}
fileStream.Read(fileContents, 0, (int)length);
}
var proxy = new WcfService();
proxy.ImportExcelDataCompleted += (s, e) =>
{
MessageBox.Show("Import Data is at e.Result");
// no need to close any streams this way
};
proxy.ImportExcelDataAsync(fileContents);
}
}
Update
Your service could look like this:
public List<ImportFile> ImportExcelData(Stream uploadedFile)
{
var tempFile = HttpContext.Current.Server.MapPath("~/uploadedFiles/" + Path.GetRandomFileName());
try
{
using (var tempStream = File.OpenWrite(tempFile))
{
uploadedFile.CopyTo(tempStream);
}
//string dataSource = Location + FileName;
string dataSource = tempFile;
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() +
";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
con.Open();
}
finally
{
if (File.Exists(tempFile))
File.Delete(tempFile);
}
}
Thanks Bendewey that was great. Had to amend it slightly -
My Service:
var tempFile = #"c:\temp\" + Path.GetRandomFileName();
try
{
int length = 256;
int bytesRead = 0;
Byte[] buffer = new Byte[length];
// write the required bytes
using (FileStream fs = new FileStream(tempFile, FileMode.Create))
{
do
{
bytesRead = uploadedFile.Read(buffer, 0, length);
fs.Write(buffer, 0, bytesRead);
}
while (bytesRead == length);
}
uploadedFile.Dispose();
string conStr = "Provider=Microsoft.Jet.OLEDB.4.0;" + "Data Source=" + dataSource.ToString() + ";Extended Properties=Excel 8.0;";
var con = new OleDbConnection(conStr);
Thanks Again for your help
"java:comp/env/jdbc/MY_SQL_DS" does not work. I get a Naming Exception: NameNotFoundException. neither works "MY_SQL_DS" alone.name exception again.
I created another JNDI for a Mail Session named "MY_MailSession" and reference it like (javax.mail.Session) ctx.lookup( "MY_MailSession" ) which works...
what is the convention to refer the JDBC DataSource then?
I solved it the following way:
hope this helps others having the same issue/problem afterwards...
protected Connection getConnection() {
try {
if (connection == null || connection.isClosed()) {
if (dataSource == null) {
// impliziter Initial Context von WebLogic ApplicationServer Environment
java.util.Hashtable environment = new java.util.Hashtable();
environment.put(Context.INITIAL_CONTEXT_FACTORY, "weblogic.jndi.WLInitialContextFactory");
Context wlsic = new InitialContext(environment);
showJndiContext( wlsic, "", "");
// logischer JNDI Rootcontext der Serverkomponente, kann mehrfach verwendet werden
Context ctx = (Context) wlsic.lookup("java:comp/env");
showJndiContext( ctx, "", "");
// weiter mit Resourcenpfad
dataSource = (DataSource) ctx.lookup("MY_SQL_DS");
}
connection = dataSource.getConnection();
}
}
catch (NamingException ne) {
ne.printStackTrace();
log.error(ne);
}
catch (SQLException sqlEx) {
sqlEx.printStackTrace();
log.error(sqlEx.getMessage());
}
return connection;
}
public static void showJndiContext(Context ctx, String name, String space) {
if (null == name)
name = "";
if (null == space)
space = "";
try {
NamingEnumeration en = ctx.list(name);
while (en.hasMoreElements()) {
String delim = (null != name && 0 < name.length()) ? "/" : "";
NameClassPair nc = (NameClassPair) en.next();
System.out.println(space + name + delim + nc);
if (40 > space.length())
showJndiContext(ctx, nc.getName(), " " + space);
}
}
catch (javax.naming.NamingException ex) {
//System.out.println( ex );
}
}