MySql Query Sent by Email - mysql

I have a simple query that select some fields from a few different tables and I need it to run once a month. I know i can schedule a monthly "job" with the CREATE EVENT, however, is it possible to have that information emailed to some addresses after the query runs? That way i don't need to log into the server and look at the new file?

I think that Mysql doesn't support Email sending.
In this case, you can develop an auxiliary program that sends the file created, and execute it with - scheduled task, Cron ...(It depends on the Operating System of the server you're using).
The auxiliary program can be like this code adding the file/s you want to attach (attachFiles variable).
public class EmailAttachmentSender {
public static void sendEmailWithAttachments(String host, String port,
final String userName, final String password, String toAddress,
String subject, String message, String[] attachFiles)
throws AddressException, MessagingException {
// sets SMTP server properties
Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", port);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
properties.put("mail.user", userName);
properties.put("mail.password", password);
// creates a new session with an authenticator
Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, password);
}
};
Session session = Session.getInstance(properties, auth);
// creates a new e-mail message
Message msg = new MimeMessage(session);
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
// creates message part
MimeBodyPart messageBodyPart = new MimeBodyPart();
messageBodyPart.setContent(message, "text/html");
// creates multi-part
Multipart multipart = new MimeMultipart();
multipart.addBodyPart(messageBodyPart);
// adds attachments
if (attachFiles != null && attachFiles.length > 0) {
for (String filePath : attachFiles) {
MimeBodyPart attachPart = new MimeBodyPart();
try {
attachPart.attachFile(filePath);
} catch (IOException ex) {
ex.printStackTrace();
}
multipart.addBodyPart(attachPart);
}
}
// sets the multi-part as e-mail's content
msg.setContent(multipart);
// sends the e-mail
Transport.send(msg);
}
/**
* Test sending e-mail with attachments
*/
public static void main(String[] args) {
// SMTP info
String host = "smtp.gmail.com";
String port = "587";
String mailFrom = "your-email-address";
String password = "your-email-password";
// message info
String mailTo = "your-friend-email";
String subject = "New email with attachments";
String message = "I have some attachments for you.";
// attachments
String[] attachFiles = new String[3];
attachFiles[0] = "e:/Test/Picture.png";
attachFiles[1] = "e:/Test/Music.mp3";
attachFiles[2] = "e:/Test/Video.mp4";
try {
sendEmailWithAttachments(host, port, mailFrom, password, mailTo,
subject, message, attachFiles);
System.out.println("Email sent.");
} catch (Exception ex) {
System.out.println("Could not send email.");
ex.printStackTrace();
}
}

Mysql does not support that functionality.
You can use a cron job (Quartz) to schedule a job every month,
where you can fetch the data and shoot an email containing your data.
Refer the below link for quartz job :
http://www.mkyong.com/java/example-to-run-multiple-jobs-in-quartz/

is it possible to have that information emailed to some addresses
after the query runs?
If you are looking for a MySQL built in solution then probably NO. This particular should be handled in application end.
So, if you are scheduling the query as cron job in linux (OR) batch job in windows then you can configure cron (or) batch to send an email to list of recipients once the query finishes.
How to configure cron to send mail can be checked HERE

I haven't done this myself but I see no reason why it shouldn't work: create a UDF (user defined function) that takes the e-mail parameters and sends out the e-mail. You can write UDFs e.g. in C++ and have so all necesssary libraries at hand.

Related

Random System.Net.Mail.SmtpFailedRecipientsException exception - relay account office365

We have an application that runs on a Windows Server 2008 machine. It sends emails out using an office365 smtp relay account. However, all the emails are not sent successfully. We randomly get these two exceptions on emails being sent out on the smtp.Send call:
System.Net.Mail.SmtpFailedRecipientsException: Unable to send to all recipients. ---> System.Net.Mail.SmtpFailedRecipientException: Mailbox unavailable. The server response was: 5.7.64 TenantAttribution; Relay Access Denied
System.Net.Mail.SmtpFailedRecipientException: Insufficient system storage. The server response was: 4.5.3 Too many recipients
Thus far, we haven't been able to figure out why this is happening. Any ideas are appreciated.
The email code uses System.Net.Mail namespace - .Net framework 4.0.
We pass in the username and password for the NetworkCredential.
public void Send(string from, string[] to, string[] cc, string[] bcc, string subject, string body, string[] attachmentArr, Boolean isBodyHtml, string smtpServerName, int port = 25, bool enableSsl = true, string userName = null, string password = null, string domain = null, int timeoutMilliSec = 100000)
{
MailMessage objEmail = new MailMessage();
try
{
foreach (string toItem in to)
{
objEmail.To.Add(toItem);
}
if (cc != null)
{
foreach (string toItem in cc)
{
objEmail.CC.Add(toItem);
}
}
if (bcc != null)
{
foreach (string toItem in bcc)
{
objEmail.Bcc.Add(toItem);
}
}
objEmail.From = new MailAddress(from);
objEmail.Subject = subject;
objEmail.Body = body;
objEmail.IsBodyHtml = isBodyHtml;
objEmail.Priority = MailPriority.High;
if (attachmentArr != null)
{
foreach (String s1 in attachmentArr)
{
objEmail.Attachments.Add(new Attachment(s1));
}
}
using (SmtpClient smtp = new SmtpClient(smtpServerName))
{
if (string.IsNullOrEmpty(userName) == false && string.IsNullOrEmpty(password) == false)
{
NetworkCredential credential = (string.IsNullOrEmpty(domain)) ? new NetworkCredential(userName, password) : new NetworkCredential(userName, password, domain);
smtp.Credentials = credential;
}
smtp.Timeout = timeoutMilliSec;
smtp.Port = port;
smtp.EnableSsl = enableSsl;
smtp.Send(objEmail);
}
}
catch (Exception ex)
{
throw ex;
}
finally
{
if (attachmentArr != null && objEmail.Attachments != null)
{
foreach (Attachment a1 in objEmail.Attachments)
{
a1.Dispose();
}
}
}
}
We finally found what was going on - Email throttling.
Office365 has a Throttling limit of 30 messages per minute for SMTP client submission https://technet.microsoft.com/en-us/library/dn554323%28v=exchg.150%29.aspx#summary
The solution was to send less than 30 messages per minute. I think it is affected by other messages (sent by Outlook) showing up to be sent by the server too. We pushed ours down to almost a five second delay between messages. We have not seen the error reoccur since.

System.web name space does not exist error

I am trying to use Gmail API for windows phone 8.1 app.This is the code which I got from https://developers.google.com/gmail/api/quickstart/quickstart-cs
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Web;
using System.Web.Compilation;
using System.Text;
using System.Text.RegularExpressions;
using System.Web.Routing;
using System.Web.SessionState;
using Newtonsoft.Json;
// TODO(class) Reorder, this gets messy with alt+shift+F10
using Google.Apis.Auth.OAuth2;
using Google.Apis.Services;
using Google.Apis.Util;
using Google.Apis.Gmail;
using Google.Apis.Gmail.v1;
using Google.Apis.Gmail.v1.Data;
using Google.Apis.Oauth2;
using Google.Apis.Oauth2.v2;
using Google.Apis.Oauth2.v2.Data;
using Google.Apis.Plus.v1;
using Google.Apis.Auth.OAuth2.Responses;
using Google.Apis.Auth.OAuth2.Flows;
using System.Threading;
namespace GmailQuickstart
{
/// <summary>
/// This is a minimal implementation of GMail demonstrating:
/// - Using the Google+ Sign-In button to get an OAuth 2.0 refresh token.
/// - Exchanging the refresh token for an access token.
/// - Making GMail API requests with the access token, including
/// getting a list GMail threads.
/// - Disconnecting the app from the user's Google account and revoking
/// tokens.
/// </summary>
/// #author class#google.com (Gus Class)
public class Signin : IHttpHandler, IRequiresSessionState, IRouteHandler
{
// These come from the APIs console:
// https://code.google.com/apis/console
public static ClientSecrets secrets = new ClientSecrets()
{
ClientId = "YOUR_CLIENT_ID",
ClientSecret = "YOUR_CLIENT_SECRET"
};
// Configuration that you probably don't need to change.
static public string APP_NAME = "GMail .NET Quickstart";
// Stores token response info such as the access token and refresh token.
private TokenResponse token;
// Used to peform API calls against Google APIs.
private PlusService ps = null;
private GmailService gs = null;
/// <summary>Processes the request based on the path.</summary>
/// <param name="context">Contains the request and response.</param>
public void ProcessRequest(HttpContext context)
{
// Redirect base path to signin.
if (context.Request.Path.EndsWith("/"))
{
context.Response.RedirectPermanent("signin.ashx");
}
// This is reached when the root document is passed. Return HTML
// using index.html as a template.
if (context.Request.Path.EndsWith("/signin.ashx"))
{
String state = (String)context.Session["state"];
// Store a random string in the session for verifying
// the responses in our OAuth2 flow.
if (state == null)
{
Random random = new Random((int)DateTime.Now.Ticks);
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 13; i++)
{
builder.Append(Convert.ToChar(
Convert.ToInt32(Math.Floor(
26 * random.NextDouble() + 65))));
}
state = builder.ToString();
context.Session["state"] = state;
}
// Render the templated HTML.
String templatedHTML = File.ReadAllText(
context.Server.MapPath("index.html"));
templatedHTML = Regex.Replace(templatedHTML,
"[{]{2}\\s*APPLICATION_NAME\\s*[}]{2}", APP_NAME);
templatedHTML = Regex.Replace(templatedHTML,
"[{]{2}\\s*CLIENT_ID\\s*[}]{2}", secrets.ClientId);
templatedHTML = Regex.Replace(templatedHTML,
"[{]{2}\\s*STATE\\s*[}]{2}", state);
context.Response.ContentType = "text/html";
context.Response.Write(templatedHTML);
return;
}
if (context.Session["authState"] == null)
{
// The connect action exchanges a code from the sign-in button,
// verifies it, and creates OAuth2 credentials.
if (context.Request.Path.Contains("/connect"))
{
// Get the code from the request POST body.
StreamReader sr = new StreamReader(
context.Request.InputStream);
string code = sr.ReadToEnd();
string state = context.Request["state"];
// Test that the request state matches the session state.
if (!state.Equals(context.Session["state"]))
{
context.Response.StatusCode = 401;
return;
}
// Use the code exchange flow to get an access and refresh token.
IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets,
Scopes = new string[] { PlusService.Scope.PlusLogin, GmailService.Scope.GmailReadonly}
});
token = flow.ExchangeCodeForTokenAsync("", code, "postmessage",
CancellationToken.None).Result;
// Create an authorization state from the returned token.
context.Session["authState"] = token;
// Get tokeninfo for the access token if you want to verify.
Oauth2Service service = new Oauth2Service(
new Google.Apis.Services.BaseClientService.Initializer());
Oauth2Service.TokeninfoRequest request = service.Tokeninfo();
request.AccessToken = token.AccessToken;
Tokeninfo info = request.Execute();
string gplus_id = info.UserId;
}
else
{
// No cached state and we are not connecting.
context.Response.StatusCode = 400;
return;
}
}
else if (context.Request.Path.Contains("/connect"))
{
// The user is already connected and credentials are cached.
context.Response.ContentType = "application/json";
context.Response.StatusCode = 200;
context.Response.Write(JsonConvert.SerializeObject("Current user is already connected."));
return;
}
else
{
// Register the authenticator and construct the Plus service
// for performing API calls on behalf of the user.
token = (TokenResponse)context.Session["authState"];
IAuthorizationCodeFlow flow =
new GoogleAuthorizationCodeFlow(new GoogleAuthorizationCodeFlow.Initializer
{
ClientSecrets = secrets,
Scopes = new string[] { PlusService.Scope.PlusLogin, GmailService.Scope.GmailReadonly }
});
UserCredential credential = new UserCredential(flow, "me", token);
bool success = credential.RefreshTokenAsync(CancellationToken.None).Result;
token = credential.Token;
ps = new PlusService(
new Google.Apis.Services.BaseClientService.Initializer()
{
ApplicationName = ".NET Quickstart",
HttpClientInitializer = credential
});
gs = new GmailService(
new Google.Apis.Services.BaseClientService.Initializer()
{
ApplicationName = ".NET Quickstart",
HttpClientInitializer = credential
});
}
// Perform an authenticated API request to retrieve the list of
// people that the user has made visible to the app.
if (context.Request.Path.Contains("/mail"))
{
// List the GMail threads for the current user.
IList<Google.Apis.Gmail.v1.Data.Thread> threadFeed =
gs.Users.Threads.List("me").Execute().Threads;
string jsonContent =
Newtonsoft.Json.JsonConvert.SerializeObject(threadFeed);
context.Response.ContentType = "application/json";
context.Response.Write(jsonContent);
return;
}
// Disconnect the user from the application by revoking the tokens
// and removing all locally stored data associated with the user.
if (context.Request.Path.Contains("/disconnect"))
{
// Perform a get request to the token endpoint to revoke the
// refresh token.
token = (TokenResponse)context.Session["authState"];
string tokenToRevoke = (token.RefreshToken != null) ?
token.RefreshToken : token.AccessToken;
WebRequest request = WebRequest.Create(
"https://accounts.google.com/o/oauth2/revoke?token=" +
token);
WebResponse response = request.GetResponse();
// Remove the cached credentials.
context.Session["authState"] = null;
// You could reset the state in the session but you must also
// reset the state on the client.
// context.Session["state"] = null;
context.Response.Write(
response.GetResponseStream().ToString().ToCharArray());
return;
}
}
/// <summary>
/// Implements IRouteHandler interface for mapping routes to this
/// IHttpHandler.
/// </summary>
/// <param name="requestContext">Information about the request.
/// </param>
/// <returns></returns>
public IHttpHandler GetHttpHandler(RequestContext
requestContext)
{
var page = BuildManager.CreateInstanceFromVirtualPath
("~/signin.ashx", typeof(IHttpHandler)) as IHttpHandler;
return page;
}
public bool IsReusable { get { return false; } }
}
}
So I keep getting this error System.web,System.Web.Compilation namespaces are not available.So What can I do to fix this?
The error is correct. System.Web is not available to Windows Phone apps (either Silverlight or Runtime). If the Gmail API depends on it then it is probably designed for the full .Net Framework and not for Windows Phone. Instead you'll need to connect directly to the Gmail web API. It looks like google has docs for it at https://developers.google.com/gmail/api/v1/reference/
See .NET API for Windows Phone for .Net classes available in WP8 Silverlight apps.

Send Email using gmail SMTP throwing AuthenticationFailedException

I am sending mail using smtp from my web site to gmail.its work well localy. But did't work in remote server
i am previously using this code:
public boolean sendMail(String subject, String bodyContent,String emailAddress){
boolean isMailsent=false;
final String SMTP_HOST= getText("email.smtp.host");
final String SOCKET_FACTORY_PORT= getText("email.socket.factory.port");
final String SMTP=getText("email.smtp.port");
final String MAIL_USER_EMAIL_ADDRESS=getText("email.username");
final String MAIL_USER_PASSWORD= getText("email.password");
final String EMAIL_FROMNAME= getText("email.fromname");
try{
Properties props = new Properties();
props.put("mail.smtp.host", SMTP_HOST);
props.put("mail.smtp.socketFactory.port",SOCKET_FACTORY_PORT);
props.put("mail.smtp.socketFactory.class","javax.net.ssl.SSLSocketFactory");
props.put("mail.smtp.auth", "true");
props.put("mail.smtp.port", SMTP);
Authenticator auth = new SMTPAuthenticator(MAIL_USER_EMAIL_ADDRESS, MAIL_USER_PASSWORD);
Session session = Session.getInstance(props, auth);
Message message = new MimeMessage(session);
InternetAddress from = new InternetAddress(MAIL_USER_EMAIL_ADDRESS,EMAIL_FROMNAME);
message.setFrom(from);
message.setRecipients(Message.RecipientType.TO, InternetAddress.parse(emailAddress));
message.setSubject(subject);
message.setContent(bodyContent,"text/html" );
Transport.send(message);
isMailsent=true;
}catch(Exception e){
LOGGER.error(e);
}
return isMailsent;
}
how to fix it please give me best example
You need to provide the correct GMail credentials to authenticate.

wp8 Handle raw push notification in more than one pages

I am developing a wp8 application and the need is the above:
My server sends some raw push notifications that i can handle in my mainpage successful. But i have more pages so i need my app continue to get and handle notifications when the user is on the other pages.
As far i have tried to add the same code as i have put in the main page to handle notifications
string channelName = "test";
pushChannel = HttpNotificationChannel.Find(channelName);
if (pushChannel == null)
{
pushChannel = new HttpNotificationChannel(channelName);
// Register for all the events before attempting to open the channel.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
//pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.Open();
// Bind this new channel for toast events.
//pushChannel.BindToShellToast();
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
}
else
{
// The channel was already open, so just register for all the events.
pushChannel.ChannelUriUpdated += new EventHandler<NotificationChannelUriEventArgs>(PushChannel_ChannelUriUpdated);
pushChannel.ErrorOccurred += new EventHandler<NotificationChannelErrorEventArgs>(PushChannel_ErrorOccurred);
// Register for this notification only if you need to receive the notifications while your application is running.
// pushChannel.ShellToastNotificationReceived += new EventHandler<NotificationEventArgs>(PushChannel_ShellToastNotificationReceived);
pushChannel.HttpNotificationReceived += new EventHandler<HttpNotificationEventArgs>(PushChannel_HttpNotificationReceived);
System.Threading.Thread.Sleep(3000);
channel = pushChannel.ChannelUri.ToString();
cSettings.device_notify_id = channel;
// Display the URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
}
and the handlers methods
void PushChannel_ChannelUriUpdated(object sender, NotificationChannelUriEventArgs e)
{
Dispatcher.BeginInvoke(() =>
{
cSettings.device_notify_id = e.ChannelUri.ToString();
// Display the new URI for testing purposes. Normally, the URI would be passed back to your web service at this point.
});
}
void PushChannel_ErrorOccurred(object sender, NotificationChannelErrorEventArgs e)
{
cSettings set = new cSettings();
set.LogEx(new Exception((String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))));
// Error handling logic for your particular application would be here.
Dispatcher.BeginInvoke(() =>
MessageBox.Show(String.Format("A push notification {0} error occurred. {1} ({2}) {3}",
e.ErrorType, e.Message, e.ErrorCode, e.ErrorAdditionalData))
);
}
void PushChannel_HttpNotificationReceived(object sender, HttpNotificationEventArgs e)
{
string message;
VibrationDevice vibr = VibrationDevice.GetDefault();
vibr.Vibrate(TimeSpan.FromSeconds(3));
using (System.IO.StreamReader reader = new System.IO.StreamReader(e.Notification.Body))
{
message = reader.ReadToEnd();
}
cSettings set = new cSettings();
string n_type = "";
string n_header = "";
//var obj = set.parse_stringfromnotify(message, ref n_type, ref n_header);
Dispatcher.BeginInvoke(() => nofication_received_action(message, n_type, ""));
}
private void nofication_received_action(string n_header, string n_type, object data)
{
MessageBoxResult result;
CallSrvData cdata = new CallSrvData();
Exception ex = null;
WP_MemberData m;
WP_MemberRules wpmr;
cSettings set;
MemberRules mr;
Microsoft.Phone.Shell.ShellToast toast = new Microsoft.Phone.Shell.ShellToast();
Rules c_rules;
Notify.data = data;
Notify.msg_box_text = String.Format("{0}", n_header);
//dose k data sth forma
toast = new Microsoft.Phone.Shell.ShellToast();
toast.Content = "Invitation received";
toast.Title = "Title : ";
//SetProperty(toast, "Sound", new Uri("/data/alert.mp3", UriKind.Relative));
toast.NavigationUri = new Uri("/forms/Notify.xaml?type=0", UriKind.Relative);
toast.Show();
}
When the app is in background and i successfully get the notification and navigate to Notify.xaml the mechanism works fine, but when i go back or i press start button to leave from Notify.xaml and i resend a notification nothing happens. I have tried to add the same code and in Notify.xaml but again nothing happen when i send notification. In comparison with android where you just register listeners once in your app and then you can receive notification in in any page even the app is "closed" who can i succeed something like that or can i succeed something like that?
Thx a lot for your contribution.
I have found that i can create all the notification functionality in a class which will initialize on app.cs or any time is needed.

System.Net.WebException: The request failed with HTTP status 400: Bad Request. calling a webservice dynamically

Iam calling a web service through my web service dynamically. I stored serviceName, MethodToCall, and array of parameters in my database table and execute these two methods to call a dynamic service url with .asmx extention and its method without adding its reference in my app. It works fine.
Following code is here.
public string ShowThirdParty(String strURL, String[] Params, String MethodToCall, String ServiceName)
{
String Result = String.Empty;
//Specify service Url without ?wsdl suffix.
//Reference urls for code help
///http://www.codeproject.com/KB/webservices/webservice_.aspx?msg=3197985#xx3197985xx
//http://www.codeproject.com/KB/cpp/CallWebServicesDynamic.aspx
//String WSUrl = "http://localhost/ThirdParty/WebService.asmx";
String WSUrl = strURL;
//Specify service name
String WSName = ServiceName;
//Specify method name to be called
String WSMethodName = MethodToCall;
//Parameters passed to the method
String[] WSMethodArguments = Params;
//WSMethodArguments[0] = "20500";
//Create and Call Service Wrapper
Object WSResults = CallWebService(WSUrl, WSName, WSMethodName, WSMethodArguments);
if (WSResults != null)
{
//Decode Results
if (WSResults is DataSet)
{
Result += ("Result: \r\n" + ((DataSet)WSResults).GetXml());
}
else if (WSResults is Boolean)
{
bool BooleanResult = (Boolean)WSResults;
if(BooleanResult)
Result += "Result: \r\n" + "Success";
else
Result += "Result: \r\n" + "Failure";
}
else if (WSResults.GetType().IsArray)
{
Object[] oa = (Object[])WSResults;
//Retrieve a property value withour reflection...
PropertyDescriptor descriptor1 = TypeDescriptor.GetProperties(oa[0]).Find("locationID", true);
foreach (Object oae in oa)
{
Result += ("Result: " + descriptor1.GetValue(oae).ToString() + "\r\n");
}
}
else
{
Result += ("Result: \r\n" + WSResults.ToString());
}
}
return Result;
}
public Object CallWebService(string webServiceAsmxUrl,
string serviceName, string methodName, string[] args)
{
try
{
System.Net.WebClient client = new System.Net.WebClient();
Uri objURI = new Uri(webServiceAsmxUrl);
//bool isProxy = client.Proxy.IsBypassed(objURI);
//objURI = client.Proxy.GetProxy(objURI);
//-Connect To the web service
// System.IO.Stream stream = client.OpenRead(webServiceAsmxUrl + "?wsdl");
string ccc = webServiceAsmxUrl + "?wsdl";// Connect To the web service System.IO.
//string wsdlContents = client.DownloadString(ccc);
string wsdlContents = client.DownloadString(ccc);
XmlDocument wsdlDoc = new XmlDocument();
wsdlDoc.InnerXml = wsdlContents;
System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(new XmlNodeReader(wsdlDoc));
//Read the WSDL file describing a service.
// System.Web.Services.Description.ServiceDescription description = System.Web.Services.Description.ServiceDescription.Read(stream);
//Load the DOM
//--Initialize a service description importer.
ServiceDescriptionImporter importer = new ServiceDescriptionImporter();
importer.ProtocolName = "Soap12"; //Use SOAP 1.2.
importer.AddServiceDescription(description, null, null);
//--Generate a proxy client.
importer.Style = ServiceDescriptionImportStyle.Client;
//--Generate properties to represent primitive values.
importer.CodeGenerationOptions = System.Xml.Serialization.CodeGenerationOptions.GenerateProperties;
//Initialize a Code-DOM tree into which we will import the service.
CodeNamespace codenamespace = new CodeNamespace();
CodeCompileUnit codeunit = new CodeCompileUnit();
codeunit.Namespaces.Add(codenamespace);
//Import the service into the Code-DOM tree.
//This creates proxy code that uses the service.
ServiceDescriptionImportWarnings warning = importer.Import(codenamespace, codeunit);
if (warning == 0)
{
//--Generate the proxy code
CodeDomProvider provider = CodeDomProvider.CreateProvider("CSharp");
//--Compile the assembly proxy with the
// appropriate references
string[] assemblyReferences = new string[] {
"System.dll",
"System.Web.Services.dll",
"System.Web.dll",
"System.Xml.dll",
"System.Data.dll"};
//--Add parameters
CompilerParameters parms = new CompilerParameters(assemblyReferences);
parms.GenerateInMemory = true; //(Thanks for this line nikolas)
CompilerResults results = provider.CompileAssemblyFromDom(parms, codeunit);
//--Check For Errors
if (results.Errors.Count > 0)
{
foreach (CompilerError oops in results.Errors)
{
System.Diagnostics.Debug.WriteLine("========Compiler error============");
System.Diagnostics.Debug.WriteLine(oops.ErrorText);
}
throw new Exception("Compile Error Occured calling WebService.");
}
//--Finally, Invoke the web service method
Object wsvcClass = results.CompiledAssembly.CreateInstance(serviceName);
MethodInfo mi = wsvcClass.GetType().GetMethod(methodName);
return mi.Invoke(wsvcClass, args);
}
else
{
return null;
}
}
catch (Exception ex)
{
throw ex;
}
}
Now the problem arraize when i have two different client servers. and calling a service from one server to the service deployed on other server. Follwing two kind of error log occurs. Cant find the exact reson for cope up this problem.
System.Net.WebException: The request failed with HTTP status 400: Bad Request.
at System.Web.Services.Protocols.SoapHttpClientProtocol.ReadResponse(SoapClientMessage message, WebResponse response, Stream responseStream, Boolean asyncCall)
at System.Web.Services.Protocols.SoapHttpClientProtocol.Invoke(String methodName, Object[] parameters)
at MarkUsageHistoryInSTJH.InsertUpdateIssueItemAditionalDetail(String csvBarcode, String csvName, String csvPMGSRN, String csvGLN, String csvMobile, String csvPhone, String csvAddressLine1, String csvAddressLine2, String csvAddressLine3, String csvIsHospital)
and
System.Net.Sockets.SocketException (0x80004005):
A connection attempt failed because the connected party did not properly respond after a period of time, or established connection failed because connected host has failed to respond 172.17.13.7:80
at System.Net.Sockets.Socket.DoConnect(EndPoint endPointSnapshot, SocketAddress socketAddress)
at System.Net.ServicePoint.ConnectSocketInternal(Boolean connectFailure, Socket s4, Socket s6, Socket& socket, IPAddress& address, ConnectSocketState state, IAsyncResult asyncResult, Int32 timeout, Exception& exception)
Please Carry Out Following Steps :
1) First of all try to access your service by adding reference of it.
It it works fine then we can say that there is no problem related to accessibility and permission.
2) If its not work then there is a problem with connection.
-->So Check Configuration in your service and try to set timeout for your web service.
(http://social.msdn.microsoft.com/Forums/vstudio/en-US/ed89ae3c-e5f8-401b-bcc7-
333579a9f0fe/webservice-client-timeout)
3)Now try after setting the timeout.
it operation completes successfully after above change that means now you can check with your web client method(dymamic calling).
4) If still problem persists then this might be network latency issue. Check the n/w latency between your client and server.
it will helps you.