Could not generate emails getting error - wpf

System.Net.Mail.SmtpException: Failure sending mail. ---> System.Net.WebException: The remote name could not be resolved: 'mailrelay'
at System.Net.ServicePoint.GetConnection(PooledStream PooledStream, Object owner, Boolean async, IPAddress& address, Socket& abortSocket, Socket& abortSocket6)
at System.Net.PooledStream.Activate(Object owningObject, Boolean async, GeneralAsyncDelegate asyncCallback)
at System.Net.PooledStream.Activate(Object owningObject, GeneralAsyncDelegate asyncCallback)
at System.Net.ConnectionPool.GetConnection(Object owningObject, GeneralAsyncDelegate asyncCallback, Int32 creationTimeout)
at System.Net.Mail.SmtpConnection.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpTransport.GetConnection(ServicePoint servicePoint)
at System.Net.Mail.SmtpClient.GetConnection()
at System.Net.Mail.SmtpClient.Send(MailMessage message)
--- End of inner exception stack trace ---
at System.Net.Mail.SmtpClient.Send(MailMessage message)
at EmailSender.PerformDelivery(IMessage message)
below is my code
mail = new MailMessage();
string[] toAddresses = email.To.EmailAddress.Split(new char[] { ';' });
foreach (string toAddress in toAddresses)
{
if (!string.IsNullOrEmpty(toAddress.Trim()))
{
mail.To.Add(new MailAddress(toAddress));
}
}
string[] ccAddresses = email.CcEmail.Split(new char[] { ';' });
foreach (string ccAddress in ccAddresses)
{
if (!string.IsNullOrEmpty(ccAddress.Trim()))
{
mail.CC.Add(new MailAddress(ccAddress));
}
}
string[] bccAddresses = email.BccEmail.Split(new char[] { ';' });
foreach (string bccAddress in bccAddresses)
{
if (!string.IsNullOrEmpty(bccAddress.Trim()))
{
mail.Bcc.Add(new MailAddress(bccAddress));
}
}
mail.From = new MailAddress(email.From.EmailAddress,email.From.FullName);
mail.Subject = email.Subject;
mail.Body = email.Body;
if (email.Body.Contains("<html>"))
{
mail.IsBodyHtml = true;
}
if (!email.ExcludeAttachment && !string.IsNullOrEmpty(email.AttachmentPath))
mail.Attachments.Add(new Attachment(email.AttachmentPath));
client = new SmtpClient();
client.Host = ConfigurationSettings.AppSettings["SmtpServer"].ToString();
client.Send(mail);

It looks like ConfigurationSettings.AppSettings["SmtpServer"].ToString() is returning "mailrelay"
Check your AppSettings (normally in web.config), find the SmtpServer setting and change it to a machine name, ip address or domain name that is a mail relay that will accept emails from your app (most mail relays are secured to prevent spammers using them).
If "mailrelay" does work on your dev machine, ping it and find out what IP address it is resolving to. It needs to resolve to a machine that your other environment can see too. If it's a local test machine, then chances are that a production server in a hosting environment can't access it.

Related

Getting socket error while accessing azure cognitive search index

I have created an index in the azure portal and I am trying to access the index in my code to get the data. Everytime I do it I get a {System.Net.Sockets.SocketException (11001): No such host is known at System.Net.Http.ConnectHelper.ConnectAsync(String host, Int32 port, CancellationToken cancellationToken)}.
Is there anything I can do for this?
Below is my code
static void Main(string[] args)
{
Index();
}
public static DocumentSearchResult<SearchResult> Index()
{
IConfigurationBuilder builder = new ConfigurationBuilder().AddJsonFile("appsettings.json");
IConfigurationRoot configuration = builder.Build();
string serviceName = configuration["SearchServiceName"];
string key = configuration["SearchServiceQueryApiKey"];
//Creating search client
SearchServiceClient serviceClient = new SearchServiceClient(serviceName, new SearchCredentials(key));
SearchIndexClient indexClient = new SearchIndexClient(serviceName, "cognitivesearchpoc", new SearchCredentials(key));
SearchParameters parameters;
DocumentSearchResult<SearchResult> results;
parameters = new SearchParameters() { Select = new[] { "*" } };
return indexClient.Documents.Search<SearchResult>("*");
}
The error message is telling you that the host name to which you’re trying to connect is incorrect. Use just the host name portion of your service endpoint as the service name. In your case, that’s just “devglobalsearch” without the DNS suffix.

How to retrieve data using JDBC

I have been trying with the following code.
The connection is being made. But the resultSet is coming as empty (not null), whereas there are a couple of entries (2 fields each) in the database for the same.
It does not enter the while condition. I'm new to JDBC, please help!
My code is:
import java.sql.*;
public class JDBCTest123
{
public static void main(String[] args)
{
System.out.println("oracle Connect Example.");
Connection conn = null;
String url = "jdbc:oracle:thin:#127.0.0.1:1521:XE";
String driver = "oracle.jdbc.driver.OracleDriver";
String userName = "system";
String password = "mumpymamai";
Statement stmt = null;
String query = "select * from table1";
try
{
Class.forName(driver);
conn = DriverManager.getConnection(url, userName, password);
stmt = conn.createStatement();
System.out.println("Connected to the database");
ResultSet rs = stmt.executeQuery(query);
while (rs.next())
{
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
}
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e)
{
e.printStackTrace();
}
}
}
And the output is:
oracle Connect Example.
Connected to the database
Disconnected from database
So few suggestions. I recommend to you use PreparedStatements which are more faster and safer.
PreparedStatement ps = null;
conn = DriverManager.getConnection(url, userName, password);
ps = conn.prepareStatement(query);
ResultSet rs = ps.executeQuery();
while (rs.next())
{
// do some work
}
Second suggestion, call close() method in finally block, because application may crash and then your connection won't be closed. Finally block guarantees that will be always called.
Third suggestion if it doesn't work without Exception, probably you have empty table.

Find group membership using System.DirectoryServices.AccountManagement

I'm trying to authenticate a user against Active Directory using the types in the AccountManagement namespace/assembly in my .NET 4 application (VisualStudio 2010). Here is the code I have:
private Boolean ValidateUser(String domainName, String userName, String password)
{
var ou = String.Format(CultureInfo.InvariantCulture,
"LDAP://{0}.mydomain.com/dc={0},dc=mydomain,dc=com",
domainName);
var domain = String.Format(CultureInfo.InvariantCulture,
"{0}.mydomain.com",
domainName);
using (var context = new PrincipalContext(ContextType.Domain,
domain,
ou))
{
if (context.ValidateCredentials(userName, password))
{
var userPrincipal = UserPrincipal.FindByIdentity(context,
IdentityType.SamAccountName,
userName);
return userPrincipal.IsMemberOf(context, IdentityType.Name, "GroupName");
}
return false;
}
}
The code runs great until the statement where I call FindByIdentity. This call results in the following exception:
System.DirectoryServices.AccountManagement.PrincipalOperationException was caught
Message=Unknown error (0x80005000)
Source=System.DirectoryServices.AccountManagement
ErrorCode=-2147463168
StackTrace:
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.DoDomainInit()
at System.DirectoryServices.AccountManagement.PrincipalContext.Initialize()
at System.DirectoryServices.AccountManagement.PrincipalContext.get_QueryCtx()
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithTypeHelper(PrincipalContext context, Type principalType, Nullable`1 identityType, String identityValue, DateTime refDate)
at System.DirectoryServices.AccountManagement.Principal.FindByIdentityWithType(PrincipalContext context, Type principalType, IdentityType identityType, String identityValue)
at System.DirectoryServices.AccountManagement.UserPrincipal.FindByIdentity(PrincipalContext context, IdentityType identityType, String identityValue)
at Dominos.Pulse.Server.Security.DirectoryServices.ActiveDirectoryAuthenticationProvider.ValidateUser(String domainName, String userName, String password)
InnerException: System.Runtime.InteropServices.COMException
Message=Unknown error (0x80005000)
Source=System.DirectoryServices
ErrorCode=-2147463168
StackTrace:
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_SchemaEntry()
at System.DirectoryServices.AccountManagement.ADStoreCtx.IsContainer(DirectoryEntry de)
at System.DirectoryServices.AccountManagement.ADStoreCtx..ctor(DirectoryEntry ctxBase, Boolean ownCtxBase, String username, String password, ContextOptions options)
at System.DirectoryServices.AccountManagement.PrincipalContext.CreateContextFromDirectoryEntry(DirectoryEntry entry)
at System.DirectoryServices.AccountManagement.PrincipalContext.DoLDAPDirectoryInit()
InnerException:
Clearly I have something configured wrong. If not, perhaps I'm simply going about this the wrong way.
My goal is to simply authenticate the user against A/D then make sure that they are the member of a specific group (or groups). What am I doing wrong?
Can you try to dine OU like this :
var ou = String.Format(CultureInfo.InvariantCulture,
"dc={0},dc=mydomain,dc=com",
domainName);
The root context is just not need to validate credentials.

How to call 2 CXF dynamic clients?

A try to call two CXF-2.5.0 dynamic clients fails with:
org.apache.cxf.interceptor.Fault: Marshalling Error: net.webservicex.GetWeather is not known to this context
package my.test;
import javax.xml.namespace.QName;
import org.apache.cxf.endpoint.Client;
import org.apache.cxf.jaxws.endpoint.dynamic.JaxWsDynamicClientFactory;
public class TwoDynClients {
public static void main(String[] args) throws Exception {
JaxWsDynamicClientFactory dcf = JaxWsDynamicClientFactory.newInstance();
Client clientA = dcf.createClient("http://www.webservicex.net/stockquote.asmx?WSDL");
Object[] resultA = clientA.invoke(new QName("http://www.webserviceX.NET/", "GetQuote"), "GOOG");
System.out.println("resultA: " + resultA[0]);
Client clientB = dcf.createClient("http://www.webservicex.net/GlobalWeather.asmx?wsdl");
Object[] resultB = clientB.invoke(new QName("http://www.webserviceX.NET", "GetWeather"), new Object[] {"Stuttgart", "Germany"} );
System.out.println("resultB: " + resultB[0]);
}
}
The output of snippet above is:
29.12.2011 9:37:12 org.apache.cxf.jaxb.JAXBUtils logGeneratedClassNames
INFO: Created classes: net.webservicex.GetQuote, net.webservicex.GetQuoteResponse, net.webservicex.ObjectFactory
resultA: <StockQuotes><Stock><Symbol>GOOG</Symbol><Last>639.70</Last><Date>12/28/2011</Date><Time>4:00pm</Time><Change>0.00</Change><Open>N/A</Open><High>N/A</High><Low>N/A</Low><Volume>0</Volume><MktCap>207.2B</MktCap><PreviousClose>639.70</PreviousClose><PercentageChange>0.00%</PercentageChange><AnnRange>473.02 - 645.00</AnnRange><Earns>29.337</Earns><P-E>21.81</P-E><Name>Google Inc.</Name></Stock></StockQuotes>
29.12.2011 9:37:22 org.apache.cxf.jaxb.JAXBUtils logGeneratedClassNames
INFO: Created classes: net.webservicex.GetCitiesByCountry, net.webservicex.GetCitiesByCountryResponse, net.webservicex.GetWeather, net.webservicex.GetWeatherResponse, net.webservicex.ObjectFactory
29.12.2011 9:37:24 org.apache.cxf.phase.PhaseInterceptorChain doDefaultLogging
WARNING: Interceptor for {http://www.webserviceX.NET}GlobalWeather#{http://www.webserviceX.NET}GetWeather has thrown exception, unwinding now
org.apache.cxf.interceptor.Fault: Marshalling Error: net.webservicex.GetWeather is not known to this context
at org.apache.cxf.jaxb.JAXBEncoderDecoder.marshall(JAXBEncoderDecoder.java:261)
When order of clients is changed the second fails.
Is it OK to use one JaxWsDynamicClientFactory to create both clients?
Answer from Daniel Kulp is here How to call 2 CXF dynamic clients?
ClassLoader cl = Thread.currentThread().getContextClassloader();
JaxWsDynamicClientFactory dcf =
JaxWsDynamicClientFactory.newInstance();
Client clientA = dcf.createClient(".....");
Thread.currentThread().setContextClassloader(cl);
dcf = JaxWsDynamicClientFactory.newInstance();
Client clientB = dcf.createClient(".....");

Error in SQL Server to WCF development

I am testing a DB that have two tables (Satellite and Channel) to be exposed as I need using WCF. fortunately, I tried everything I know and online for more that I week now and I can't solve the problem.
This is the service contract IService.cs
[ServiceContract]
public interface IService
{
[OperationContract]
List<Satalite> SelectSatalite(int satNum);
[OperationContract]
List<Satalite> SataliteList();
[OperationContract]
List<Channel> ChannelList(int satNum);
[OperationContract]
String Sat(int satNum);
}
And this is the Service.svc.cs file
public class Service : IService
{
DataDbDataContext DbObj = new DataDbDataContext();
public List<Satalite> SataliteList()
{
var satList = from r in DbObj.Satalites
select r;
return satList.ToList();
}
public List<Satalite> SelectSatalite(int satNum)
{
var satList = from r in DbObj.Satalites
where r.SateliteID == satNum
select r;
return satList.ToList();
}
public List<Channel> ChannelList(int satNum)
{
var channels = from r in DbObj.Channels
where r.SateliteID == satNum
select r;
return channels.ToList();
}
public String Sat(int satNum)
{
Satalite satObj = new Satalite();
satObj = DbObj.Satalites.Single(p => p.SateliteID == satNum);
return satObj.Name;
}
}
Whenever I try to run the first three I got an error when testing them using wcftestclient.exe, the last one works with no issues.
The underlying connection was closed: The connection was closed
unexpectedly.
Server stack trace:
at System.ServiceModel.Channels.HttpChannelUtilities.ProcessGetResponseWebException(WebException
webException, HttpWebRequest request, HttpAbortReason abortReason)
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout)
at System.ServiceModel.Channels.RequestChannel.Request(Message message,
TimeSpan timeout)
at System.ServiceModel.Dispatcher.RequestChannelBinder.Request(Message
message, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannel.Call(String action,
Boolean oneway, ProxyOperationRuntime operation, Object[] ins,
Object[] outs, TimeSpan timeout)
at System.ServiceModel.Channels.ServiceChannelProxy.InvokeService(IMethodCallMessage
methodCall, ProxyOperationRuntime operation)
at System.ServiceModel.Channels.ServiceChannelProxy.Invoke(IMessage
message)
Exception rethrown at [0]:
at System.Runtime.Remoting.Proxies.RealProxy.HandleReturnMessage(IMessage
reqMsg, IMessage retMsg)
at System.Runtime.Remoting.Proxies.RealProxy.PrivateInvoke(MessageData&
msgData, Int32 type) at IService.SelectSatalite(Int32 satNum)
at ServiceClient.SelectSatalite(Int32 satNum)
Inner Exception: The underlying connection was closed: The connection
was closed unexpectedly.
at System.Net.HttpWebRequest.GetResponse()
at System.ServiceModel.Channels.HttpChannelFactory.HttpRequestChannel.HttpChannelRequest.WaitForReply(TimeSpan
timeout)
What I understand is that the error happens for the custom classes which are the DB tables, if I used a known type by the .net compiler (ex. int or string) it will work with no problems. Fortunately, I didn't find a solution.
The error appears to be one of two reasons:
a timeout since you're returning too much data, e.g. the selection of the data from the database takes too long for the service method to complete in time
or:
the message size is too large, because you're selecting too much data, and thus the WCF communication aborts before the whole data has been returned
My solution:
don't select all data from the tables! Return only as much data as you can really handle / display, e.g. 10 rows, 20 rows or a maximum of 100 rows....
Try this - if you change your method to:
public List<Satalite> SataliteList(int count)
{
var satList = (from r in DbObj.Satalites
select r).Take(count);
return satList.ToList();
}
Can you call this from the WCF Test Client with e.g. count = 10 or count = 50 ??
Adjusting timeout settings on server and client side will help you.
Server Side adjust the SendTimeout attribute of binding element and on client side adjust the RecieveTimeout attribute of binding element.
Thanks,

Resources