I've followed an example from MS (Get started with EWS Managed API).
It works fine to send a message with EmailMessage.Send, but with EmailMessage.SendAndSaveCopy it just saves a copy of the e-mail in sent folder with the drafts icon. No exception is throwed.
Any ideas anyone?
try
{
ServicePointManager.ServerCertificateValidationCallback = CertificateValidationCallBack;
ExchangeService service = new ExchangeService(ExchangeVersion.Exchange2007_SP1);
service.Credentials = new WebCredentials("nicholas", "XXXXXXX", "mydomain");
service.TraceEnabled = true;
service.TraceFlags = TraceFlags.All;
string exchangeUrl = "https://XXXXXXXX.local/EWS/Exchange.asmx";
service.Url = new Uri(exchangeUrl);
EmailMessage email = new EmailMessage(service);
email.ToRecipients.Add("xx#xxxxxx.se");
email.Subject = "HelloWorld";
email.Body = new MessageBody("This is the first email I've sent by using the EWS Managed API");
email.SendAndSaveCopy(WellKnownFolderName.SentItems);
// email.Send(); // SEND WORKS
}
catch (Exception ex)
{
}
no need email.SendAndSaveCopy(WellKnownFolderName.SentItems);
use email.SendAndSaveCopy();
https://msdn.microsoft.com/en-us/library/dd634557(v=exchg.80).aspx
Related
I am trying to develop an mobile application using asp.net web api and xamarin forms. Getting errors in web api Project:ExpiredProviderToken
I am facing problem to the send the push notification in ios using Apns service.
public partial class AppDelegate : global::Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
public override bool FinishedLaunching(UIApplication app, NSDictionary options)
{
if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
{
var notificationSettings = UIUserNotificationSettings.GetSettingsForTypes(
UIUserNotificationType.Alert | UIUserNotificationType.Badge | UIUserNotificationType.Sound, null
);
UIApplication.SharedApplication.RegisterUserNotificationSettings(notificationSettings);
UIApplication.SharedApplication.RegisterForRemoteNotifications();
}
else
{
UIRemoteNotificationType notificationTypes = UIRemoteNotificationType.Alert | UIRemoteNotificationType.Badge | UIRemoteNotificationType.Sound;
UIApplication.SharedApplication.RegisterForRemoteNotificationTypes(notificationTypes);
}
global::Xamarin.Forms.Forms.SetFlags("CollectionView_Experimental");
global::Xamarin.Forms.Forms.Init();
LoadApplication(new App());
return base.FinishedLaunching(app, options);
}
public override void RegisteredForRemoteNotifications(UIApplication application, NSData deviceToken)
{
var IosDeviceToken = UIDevice.CurrentDevice.IdentifierForVendor.ToString();
if (!string.IsNullOrWhiteSpace(IosDeviceToken))
{
IosDeviceToken = IosDeviceToken.Trim('<').Trim('>');
var model = new IosDevice { IosDeviceId = IosDeviceToken };
string url = "http://notificationdemo.project-demo.info:8075/DeviceToken/Addtoken";
HttpClient client = new HttpClient();
string jsonData = JsonConvert.SerializeObject(model);
StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = client.PostAsync(url, content);
var result = response.Result.StatusCode;
}
}
public override void FailedToRegisterForRemoteNotifications(UIApplication application, NSError error)
{
var model = new IosDevice { IosDeviceId = error.LocalizedDescription };
string url = "http://notificationdemo.project-demo.info:8075/DeviceToken/Addtoken";
HttpClient client = new HttpClient();
string jsonData = JsonConvert.SerializeObject(model);
StringContent content = new StringContent(jsonData, Encoding.UTF8, "application/json");
var response = client.PostAsync(url, content);
var result = response.Result.StatusCode;
//new UIAlertView("Error registering push notifications", error.LocalizedDescription, null, "OK", null).Show();
}
}
Below code is web api project
public void SendIOSNotification()
{
var options = new ApnsJwtOptions()
{
BundleId = "com.itpathsolutions.xamarin",
CertFilePath = #"D:\XamarinForms\demoapp\demoapp\demoapp.iOS\AuthKey_B95M9X635C.p8",
KeyId = "B95M9X635C",
TeamId = "M36758127B"
};
var apns = ApnsClient.CreateUsingJwt(new HttpClient(new WinHttpHandler()), options);
var push = new ApplePush(ApplePushType.Alert)
.AddBadge(1)
.AddSound("sound.caf")
.AddCustomProperty("category", "", true)
.AddCustomProperty("alert", "Good Morning iOS", true)
.AddCustomProperty("Id", "47474", true)
.AddCustomProperty("CreatedDate", DateTime.Now.ToString(), true)
.AddCustomProperty("url", "www.google.com", true)
.AddCustomProperty("content-available", "1", true)
.AddToken("CE227D98-4D25-43A6-AEF0-870DB1028772");
try
{
var response = apns.SendAsync(push).Result;
if (response.IsSuccessful)
{
Console.WriteLine("An alert push has been successfully sent!");
}
else
{
switch (response.Reason)
{
case ApnsResponseReason.BadCertificateEnvironment:
break;
// TODO: process other reasons we might be interested in
default:
throw new ArgumentOutOfRangeException(nameof(response.Reason), response.Reason, null);
}
Console.WriteLine("Failed to send a push, APNs reported an error: " + response.ReasonString);
}
}
catch (TaskCanceledException)
{
Console.WriteLine("Failed to send a push: HTTP request timed out.");
throw;
}
catch (HttpRequestException ex)
{
Console.WriteLine("Failed to send a push. HTTP request failed: " + ex);
throw;
}
}
The problem is related to server side .
Check the apple docs .
For security, APNs requires you to refresh your token regularly. Refresh your token no more than once every 20 minutes and no less than once every 60 minutes. APNs rejects any request whose token contains a timestamp that is more than one hour old. Similarly, APNs reports an error if you recreate your tokens more than once every 20 minutes.
On your provider server, set up a recurring task to recreate your token with a current timestamp. Encrypt the token again and attach it to subsequent notification requests.
The docs clear indicates that On your provider server, set up a recurring task to recreate your token with a current timestamp. Encrypt the token again and attach it to subsequent notification requests.
Also check the similar thread : iOS sending push with APNs Auth Key: suddenly "403 Forbidden: {"reason":"InvalidProviderToken"}" .
i am sending email using hotmail or outlook email with smtp : smtp-mail.outlook.com in asp.net mvc. it works fine local but when try to send live it gives this error "value cannot be null. parameter name innerstream". please suggest any solution. Thanks in adavace.
below is my code which work perfect on local..
------------------------------------Here is my code -------------------------
public static string SendMail(string from,string SenderName,string[] recipient, string subject,string body, string _smtp,string _autEmail,string _autPass, string ReplyTo = "")
{
try
{
ComponentInfo.SetLicense("EN-2020Apr13-bFAW7hA9RPNwz2EimPfupBFO+Zvn7eAJFmwMDry8bw3XBOwrbN8zT5uOUMlwhwErECColZkcu0J9Nnp+k91PYjA+yVw==A");
MailMessage message = new MailMessage();
message.From.Add(new MailAddress(from, SenderName));
foreach(var to in recipient)
{
message.To.Add(new MailAddress(to.Trim()));
}
if (!string.IsNullOrEmpty(ReplyTo))
{
message.To.Add(new MailAddress(ReplyTo.Trim()));
}
message.Subject = subject;
message.BodyHtml = body;
RemoteCertificateValidationCallback validationDelegate =
(object sender,
X509Certificate certificate,
X509Chain chain,
SslPolicyErrors errors) =>
{
if (errors == SslPolicyErrors.None || errors == SslPolicyErrors.RemoteCertificateNameMismatch)
{
return true;
}
else
{
return false;
}
};
// Create new SmtpClient and specify host, port, security and certificate validation callback.
using (SmtpClient smtp = new SmtpClient(
_smtp,
465,
ConnectionSecurity.Auto,
validationDelegate))
{
smtp.Connect();
smtp.Authenticate(_autEmail, _autPass, SmtpAuthentication.Login);
smtp.SendMessage(message);
return "1";
}
}
catch (Exception ex)
{
return ex.Message;
}
}
This is a fairly long piece of code but I am getting nowhere with this and cannot see any issues, although I am new to using notification hubs. I am trying to register for targeted notifications (the logged on user) using the notification hub in Azure. After the registration, a test notification is sent.
The issue I am having is that sometimes the notification is sent to the device, and sometimes it is not. It mostly isn't but occasionally when I step through the code on the server, i will get the notification on the emulator come through. Once when I deployed the app to my phone the notification came though on the emulator! I cannot discover a pattern.
My Controller class looks like this;
private NotificationHelper hub;
public RegisterController()
{
hub = NotificationHelper.Instance;
}
public async Task<RegistrationDescription> Post([FromBody]JObject registrationCall)
{
var obj = await hub.Post(registrationCall);
return obj;
}
And the helper class (which is used elsewhere so is not directly in the controller) looks like this;
public static NotificationHelper Instance = new NotificationHelper();
public NotificationHubClient Hub { get; set; }
// Create the client in the constructor.
public NotificationHelper()
{
var cn = "<my-cn>";
Hub = NotificationHubClient.CreateClientFromConnectionString(cn, "<my-hub>");
}
public async Task<RegistrationDescription> Post([FromBody] JObject registrationCall)
{
// Get the registration info that we need from the request.
var platform = registrationCall["platform"].ToString();
var installationId = registrationCall["instId"].ToString();
var channelUri = registrationCall["channelUri"] != null
? registrationCall["channelUri"].ToString()
: null;
var deviceToken = registrationCall["deviceToken"] != null
? registrationCall["deviceToken"].ToString()
: null;
var userName = HttpContext.Current.User.Identity.Name;
// Get registrations for the current installation ID.
var regsForInstId = await Hub.GetRegistrationsByTagAsync(installationId, 100);
var updated = false;
var firstRegistration = true;
RegistrationDescription registration = null;
// Check for existing registrations.
foreach (var registrationDescription in regsForInstId)
{
if (firstRegistration)
{
// Update the tags.
registrationDescription.Tags = new HashSet<string>() {installationId, userName};
// We need to handle each platform separately.
switch (platform)
{
case "windows":
var winReg = registrationDescription as MpnsRegistrationDescription;
winReg.ChannelUri = new Uri(channelUri);
registration = await Hub.UpdateRegistrationAsync(winReg);
break;
case "ios":
var iosReg = registrationDescription as AppleRegistrationDescription;
iosReg.DeviceToken = deviceToken;
registration = await Hub.UpdateRegistrationAsync(iosReg);
break;
}
updated = true;
firstRegistration = false;
}
else
{
// We shouldn't have any extra registrations; delete if we do.
await Hub.DeleteRegistrationAsync(registrationDescription);
}
}
// Create a new registration.
if (!updated)
{
switch (platform)
{
case "windows":
registration = await Hub.CreateMpnsNativeRegistrationAsync(channelUri,
new string[] {installationId, userName});
break;
case "ios":
registration = await Hub.CreateAppleNativeRegistrationAsync(deviceToken,
new string[] {installationId, userName});
break;
}
}
// Send out a test notification.
await SendNotification(string.Format("Test notification for {0}", userName), userName);
return registration;
And finally, my SendNotification method is here;
internal async Task SendNotification(string notificationText, string tag)
{
try
{
var toast = PrepareToastPayload("<my-hub>", notificationText);
// Send a notification to the logged-in user on both platforms.
await NotificationHelper.Instance.Hub.SendMpnsNativeNotificationAsync(toast, tag);
//await hubClient.SendAppleNativeNotificationAsync(alert, tag);
}
catch (ArgumentException ex)
{
// This is expected when an APNS registration doesn't exist.
Console.WriteLine(ex.Message);
}
}
I suspect the issue is in my phone client code, which is here and SubscribeToService is called immediately after WebAPI login;
public void SubscribeToService()
{
_channel = HttpNotificationChannel.Find("mychannel");
if (_channel == null)
{
_channel = new HttpNotificationChannel("mychannel");
_channel.Open();
_channel.BindToShellToast();
}
_channel.ChannelUriUpdated += async (o, args) =>
{
var hub = new NotificationHub("<my-hub>", "<my-cn>");
await hub.RegisterNativeAsync(args.ChannelUri.ToString());
await RegisterForMessageNotificationsAsync();
};
}
public async Task RegisterForMessageNotificationsAsync()
{
using (var client = GetNewHttpClient(true))
{
// Get the info that we need to request registration.
var installationId = LocalStorageManager.GetInstallationId(); // a new Guid
var registration = new Dictionary<string, string>()
{
{"platform", "windows"},
{"instId", installationId},
{"channelUri", _channel.ChannelUri.ToString()}
};
var request = new HttpRequestMessage(HttpMethod.Post, new Uri(ApiUrl + "api/Register/RegisterForNotifications"));
request.Content = new StringContent(JsonConvert.SerializeObject(registration), Encoding.UTF8, "application/json");
string message;
try
{
HttpResponseMessage response = await client.SendAsync(request);
message = await response.Content.ReadAsStringAsync();
}
catch (Exception ex)
{
message = ex.Message;
}
_registrationId = message;
}
}
Any help would be greatly appriciated as I have been stuck on this now for days! I know this is a lot of code to paste up here but it is all relevant.
Thanks,
EDIT: The SubscribeToService() method is called when the user logs in and authenticates with the WebAPI. The method is here;
public async Task<User> SendSubmitLogonAsync(LogonObject lo)
{
_logonObject = lo;
using (var client = GetNewHttpClient(false))
{
var logonString = String.Format("grant_type=password&username={0}&password={1}", lo.username, lo.password);
var sc = new StringContent(logonString, Encoding.UTF8);
var response = await client.PostAsync("Token", sc);
if (response.IsSuccessStatusCode)
{
_logonResponse = await response.Content.ReadAsAsync<TokenResponseModel>();
var userInfo = await GetUserInfoAsync();
if (_channel == null)
SubscribeToService();
else
await RegisterForMessageNotificationsAsync();
return userInfo;
}
// ...
}
}
I have solved the issue. There are tons of fairly poorly organised howto's for azure notification hubs and only one of them has this note toward the bottom;
NOTE:
You will not receive the notification when you are still in the app.
To receive a toast notification while the app is active, you must
handle the ShellToastNotificationReceived event.
This is why I was experiencing intermittent results, as i assumed you would still get a notification if you were in the app. And this little note is pretty well hidden.
Have you used proper tag / tag expressions while register/send the message. Also, Where are you storing the id back from the notification hub. It should be used when you update the channel uri (it will expire).
I would suggest to start from scratch.
Ref: http://msdn.microsoft.com/en-us/library/dn530749.aspx
I want to develop Office Outlook Plug-in to upload email message attachments if it exceeds for example 20 MB to OneDrive or SharePoint Online and add links for attachments to the message body while sending.
I need some guide to start, just show me the way and I'll walk it.
Update:
I've developed a part but once code reach clientContext.ExecuteQuery(); outlook crash.
private void ApplicationOnItemSend(object item, ref bool cancel)
{
var mailItem = item as Outlook.MailItem;
//Upload to SharePoint
foreach (Outlook.Attachment attachment in mailItem.Attachments)
{
if (IsAttachmentExceedLimit(attachment))
{
byte[] attachmentData = null;
// this is a standard attached object
attachmentData = attachment.PropertyAccessor.GetProperty(PrAttachDataBin) as byte[];
MemoryStream theMemStream = new MemoryStream();
theMemStream.Write(attachmentData, 0, attachmentData.Length);
theMemStream.Position = 0;
try
{
//Upload attachment to SharePoint Online
bool overwrite = Settings.Default.Overwrite;
using (ClientContext clientContext = ClaimClientContext.GetAuthenticatedContext(Settings.Default.SharePointSiteUrl))
{
var web = clientContext.Web;
var list = web.Lists.GetByTitle(Settings.Default.SharePointFolder);
var newFileFromComputer = new FileCreationInformation
{
Content = attachmentData,
Url = attachment.FileName
};
var uploadedFile = list.RootFolder.Files.Add(newFileFromComputer);
clientContext.Load(uploadedFile);
clientContext.RequestTimeout = 360000000;
clientContext.ExecuteQuery();
}
//Add Link for attachment
mailItem.HTMLBody += Settings.Default.SharePointSiteUrl + Settings.Default.SharePointFolder +
attachment.FileName + Environment.NewLine;
//Delete attachement from mail message
mailItem.Attachments.Remove(attachment.Index);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
}
}
Note:
I don't have any experience in VSTO.
I cannot connect to my server using HttpClient when Posting, it works fine with get, and works fine with post to other servers (such as google), any ideas?
I am NOT using android.
The server responds fine when accessing it by browser.
As it is probably a server config issue, i do not have full access to the server, it is a hosted webserver, however i have access to the cpanel
private static String GetURL(String inUrl, String post) {
String inputLine = "";
try {
if (!inUrl.contains("http")) {
throw new Exception("Invalid URL");
} else {
DefaultHttpClient client = new DefaultHttpClient();
HttpPost httpPost = new HttpPost(inUrl);
httpPost.addHeader("Accept-Charset", "UTF-8");
httpPost.addHeader("Content-Type", "application/x-www-form-urlencoded");
//create post
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(1);
nameValuePairs.add(new BasicNameValuePair("req", post));
httpPost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = client.execute(httpPost);
BufferedReader in = new BufferedReader(new InputStreamReader(response.getEntity().getContent()));
inputLine = in.readLine();
in.close();
}
}catch (Exception ex) {
inputLine = "" + Comms.ERROR_COULD_NOT_REACH_SERVER;
Log.writeLog("Could Not Reach Server: \"" + inUrl + "\"");
ex.printStackTrace();
}
return inputLine;
}
org.apache.http.NoHttpResponseException: The target server failed to respond
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:95)
at org.apache.http.impl.conn.DefaultHttpResponseParser.parseHead(DefaultHttpResponseParser.java:62)
at org.apache.http.impl.io.AbstractMessageParser.parse(AbstractMessageParser.java:254)
at org.apache.http.impl.AbstractHttpClientConnection.receiveResponseHeader(AbstractHttpClientConnection.java:289)
at org.apache.http.impl.conn.DefaultClientConnection.receiveResponseHeader(DefaultClientConnection.java:252)
at org.apache.http.impl.conn.ManagedClientConnectionImpl.receiveResponseHeader(ManagedClientConnectionImpl.java:191)
at org.apache.http.protocol.HttpRequestExecutor.doReceiveResponse(HttpRequestExecutor.java:300)
at org.apache.http.protocol.HttpRequestExecutor.execute(HttpRequestExecutor.java:127)
at org.apache.http.impl.client.DefaultRequestDirector.tryExecute(DefaultRequestDirector.java:715)
at org.apache.http.impl.client.DefaultRequestDirector.execute(DefaultRequestDirector.java:520)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:906)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:805)
at org.apache.http.impl.client.AbstractHttpClient.execute(AbstractHttpClient.java:784)
at Comms.GetURL(Comms.java:87)
at Comms.sendCommand(Comms.java:64)
at Comms.main(Comms.java:43)