Sending email from controller - asp.net-mvc-3

How make a sending email from controller? I have email address in database, so I get this email from base and send special text message to this email. I don't need use a View.

Here we go:
Your code:
System.Net.Mail.MailMessage message = new System.Net.Mail.MailMessage();
message.From = new System.Net.Mail.MailAddress("yourname#yourdomain.com");
message.To.Add(new System.Net.Mail.MailAddress("receiver#receiverdomain.com"));
message.IsBodyHtml = true;
message.BodyEncoding = Encoding.UTF8;
message.Subject = "subject";
message.Body = "hello receiver";
System.Net.Mail.SmtpClient client = new System.Net.Mail.SmtpClient();
client.Send(message);
And your web.config:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<system.net>
<mailSettings>
<smtp from="yourname#yourdomain.com" deliveryMethod="Network">
<network host="smtp.yourprovider.com" port="587" userName="yourname#yourdomain.com" password="yourpass" enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
...

You could use MvcMailer. Or if you want to implement it manually you could use the SmtpClient class to send emails.

Related

How do I open an internally created pdf in Xamarin.Android via a FileProvider in the default system pdf app?

I created a .pdf file in the private local directory I got via (I try to work with the minimum of permissions):
string targetBaseDir = Environment.GetFolderPath(
Environment.SpecialFolder.Personal,
Environment.SpecialFolderOption.Create
);
The official Android documentation suggests that file should be shared via a FileProvider.
I also tried to get some code to start an intent, and I'm currently at:
var fileUri = Android.Net.Uri.Parse(filePath);
var intent = new Intent();
intent.SetFlags(ActivityFlags.ClearTop);
intent.SetFlags(ActivityFlags.NewTask);
intent.SetAction(Intent.ActionView);
intent.SetType("application/pdf");
intent.PutExtra(Intent.ExtraStream, fileUri);
intent.AddFlags(ActivityFlags.GrantReadUriPermission);
Android.App.Application.Context.StartActivity(intent);
This starts the share dialog for a pdf file but while the Adobe Pdf reader gets opened it shows an empty view and not my pdf file.
You need to wrap your URI with FileProvider. Since android uri will give you file:// while FileProvider will give you content://, which you actually need:
public static Android.Net.Uri WrapFileWithUri(Context context,Java.IO.File file)
{
Android.Net.Uri result;
if (Build.VERSION.SdkInt < (BuildVersionCodes)24)
{
result = Android.Net.Uri.FromFile(file);
}
else
{
result = FileProvider.GetUriForFile(context, context.ApplicationContext.PackageName + ".provider", file);
}
return result;
}
File can be createed this way:
var file = new Java.IO.File(filePath);
Then you can open it:
public static void View(Context context, string path, string mimeType)
{
Intent viewIntent = new Intent(Intent.ActionView);
Java.IO.File document = new Java.IO.File(path);
viewIntent.SetDataAndType(UriResolver.WrapFileWithUri(context,document),mimeType);
viewIntent.SetFlags(ActivityFlags.NewTask);
viewIntent.AddFlags(ActivityFlags.GrantReadUriPermission);
context.StartActivity(Intent.CreateChooser(viewIntent, "your text"));
}
Be aware, that this line
viewIntent.SetDataAndType(UriResolver.WrapFileWithUri(context,document),mimeType);
does not equal to SetData and SetType separate commands.
And yes, you need to add FileProvider to your manifest:
<provider android:name="android.support.v4.content.FileProvider" android:authorities="${applicationId}.provider" android:exported="false" android:grantUriPermissions="true">
<meta-data android:name="android.support.FILE_PROVIDER_PATHS" android:resource="#xml/provider_paths" />
</provider>
Also you need to create Resources\xml folder with provider_paths.xml file:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
<external-path name="external_files" path="."/>
<files-path name="internal_files" path="." />
</paths>

Sending Email Using SMTP Bluehost Server

I use ASP.NET WEB API and I want to send an email from my application from an email created by https://www.bluehost.com/
Here is the configuration in the web.config file:
<system.net>
<mailSettings>
<smtp deliveryMethod="Network" from="example#domain.com">
<network host="mail.domain.com"
port="465"
userName="example#domain.com"
password="*****"
enableSsl="true" />
</smtp>
</mailSettings>
</system.net>
Here is my code:
SmtpClient smtpClient = new SmtpClient();
smtpClient.Timeout = 120000;
MailMessage mail = new MailMessage("fromMailAddress#domain.com", "toMailAddress#gmail.com");
mail.Body = "Here is the body of my email";
mail.IsBodyHtml = true;
smtpClient.Send(mail);
I am receiving the following error:
Network Error (tcp_error)
A communication error occurred: "Operation timed out"
The Web Server may be down, too busy, or experiencing other problems preventing it from responding to requests. You may wish to try again at a later time.
Note that I have tried configuring SMTP directly in the above code, but still it didn't work.
I had tested from host smtp.gmail.com and it worked fine, so I guess the issue is from the new host.
Any help is much appreciated.
Please try this below code segment.
SmtpClient smtpClient = new SmtpClient();
smtpClient.Port = 465; // can check port for ssl - 587 and non ssl - 25
smtpClient.Host = "mail.domain.com";
smtpClient.EnableSsl = true;
smtpClient.Timeout = 10000;
smtpClient.DeliveryMethod = SmtpDeliveryMethod.Network;
smtpClient.UseDefaultCredentials = false;
smtpClient.Credentials = new System.Net.NetworkCredential("example#domain.com","password");
MailMessage mail = new MailMessage("donotreply#domain.com", "sendtomyemail#domain.com", "test", "test");
mail.BodyEncoding = UTF8Encoding.UTF8;
mail.DeliveryNotificationOptions = DeliveryNotificationOptions.OnFailure;
smtpClient.Send(mail);
For SMTP, I used port 26 and mail.company.com. My host server is bluehost.

Send Very big string data in HTTPPost request

I have a requirement to encode the file data into base64 encoding and upload the file, This works completely fine if the file size is less than 2-3KB when i try sending relatively big files it throws 403 error(Remote Server returned an error: (403) Forbidden), There is no issue with authentication it is successfully established.
Below is the code snippet I am using to make request
Public Shared Function PostData() As String
Dim sReturnValue As String = String.Empty
Dim sUrl As String = http://localhost:50562/API/UploadFile/UploadSingleFile
Dim oRequest As HttpWebRequest
Dim oResponse As HttpWebResponse
oRequest = TryCast(WebRequest.Create(sUrl), HttpWebRequest)
oRequest.AllowWriteStreamBuffering = True
oRequest.Method = "POST"
oRequest.ContentType = "text/json"
oRequest.Headers.Add("Accept-Language", "en-us")
If m_bPassKeyInHeader = True Then
oRequest.Headers.Add("APIKey", m_sAPIKey)
End If
If i_sData IsNot Nothing AndAlso i_sData.Length > 0 Then
Using oWriter As New StreamWriter(oRequest.GetRequestStream())
oWriter.Write(i_sData)
End Using
End If
Try
oResponse = oRequest.GetResponse()
Catch ex As Exception
End Try
Using oReader As New StreamReader(oResponse.GetResponseStream())
sReturnValue = oReader.ReadToEnd()
End Using
Return sReturnValue
I am not sending the file as multipart/formdata as my requirement needs the file data to be encoded, what change should i make to get this working.
Try increasing your maxRequestLength and maxAllowedContentLength in the web.config:
<system.web>
<httpRuntime targetFramework="4.6.2" maxRequestLength="1048576" />
</system.web>
...
<system.webServer>
<security>
<requestFiltering>
<requestLimits maxAllowedContentLength="1073741824" />
</requestFiltering>
</security>
</system.webServer>
Which gets priority, maxRequestLength or maxAllowedContentLength?

Send Push notifications (Toasts) with launch parameters in Windows 8.1

I have a WinJS project which has a BackgroundTask in Runtime Component that triggers when Push Notification is sent (Raw notifications) from my own webservice.
And that Background service creates a local toasts and show it in action notification center.
public static void ShowNotification(int notificationId, string ToastTitle, int messageType, string messageDetails)
{
string messageText = String.Empty;
ToastTemplateType toastTemplate = ToastTemplateType.ToastText04;
XmlDocument toastXml = ToastNotificationManager.GetTemplateContent(toastTemplate);
XmlNodeList toastTextElements = toastXml.GetElementsByTagName("text");
toastTextElements[0].AppendChild(toastXml.CreateTextNode(ToastTitle));//Toast notification title
toastTextElements[1].AppendChild(toastXml.CreateTextNode(messageText));
toastTextElements[2].AppendChild(toastXml.CreateTextNode(messageDetails));
var launchAttribute = toastXml.CreateAttribute("launch");
IXmlNode toastNode = toastXml.SelectSingleNode("/toast");
((XmlElement)toastNode).SetAttribute("duration", "short");
toastNode.Attributes.SetNamedItem(launchAttribute);
//Launch params
var toastNavigationUriString = messageDetails;
var toastElement = ((XmlElement)toastXml.SelectSingleNode("/toast"));
toastElement.SetAttribute("launch", toastNavigationUriString);
ToastNotification toast = new ToastNotification(toastXml);
toast.Tag = notificationId.ToString();
toast.ExpirationTime = DateTimeOffset.UtcNow.AddDays(3);
if (true)
{
toast.SuppressPopup = false;//to send notification directly to action center without displaying a popup on phone.
}
ToastNotificationManager.CreateToastNotifier().Show(toast);
}
And I was handling those toasts like this in JS:
WinJS.Application.addEventListener("activated", onActivatedHandler, true);
function onActivatedHandler(args) {
if (args.detail.kind === Windows.ApplicationModel.Activation.ActivationKind.launch) {
messageDetails = args.detail.arguments;
PhonegapService.setNotificationMessage(messageDetails, function () {
window.location.href = "index.html";
});
}
}
XML format that is used in this case on my webservice is:
string rawMessage = "<?xml version=\"1.0\" encoding=\"utf-8\"?>" +
"<root>" +
"<Value1>" + "Hello" + "<Value1>" +
"<Value2>" + "Raw" + "<Value2>" +
"</root>";
Now there is slightly change in Push Notifications. I want to send push notifications (Toasts) directly from my webservice rather than sending Raw messages.
My questions are:
How to attach launch params and message on my toast notification in web-service similar like we did while creating local toasts.
When toasts are received how to handle click events and get the useful messages attached with that notification.
XML in this case would be like this:
string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
string toast2 = string.Format(#"<toast>
<visual>
<binding template=""ToastText04"">
<text id=""1"">{0}</text>
<launch></launch>
</binding>
</visual>
</toast>",message);
string xml = toast1 + toast2;
Update 1
I used the following XML on my web-service. But I'm getting notification in an unusual format than I expected:
string toast1 = "<?xml version=\"1.0\" encoding=\"utf-8\"?> ";
string message = "some json";
string toast2 = string.Format(#"<toast launch= ""{0}"">
<visual version=""1"">
<binding template=""ToastText02"">
<text id=""1"">{1}</text>
<text id=""2"">{2}</text>
</binding>
</visual>
</toast>", message, "Alert", "Test");
You need to create an XML with the same structure as the following (with or without the custom audio):
<toast launch=\"$param\">
<audio src=\"ms-appx:///Assets/Sounds/$sound.wav\"/>
<visual>
<binding template=\"ToastText04\">
<text id=\"1\">$title</text>
<text id=\"2\">$msg</text>
</binding>
</visual>
</toast>
Notice that launch is a member of the <toast> tag.
You can handle click events the same as before when the app is activated, you get the string that is the value of launch.

Oracle managed data access TNS no listener

Below is my config file
<configuration>
<configSections>
<section name="Oracle.ManagedDataAccess.Client"
type="OracleInternal.Common.ODPMSectionHandler, Oracle.ManagedDataAccess" />
</configSections>
<startup>
<supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
</startup>
<connectionStrings>
<add name="DBNAME" connectionString="User Id=USERNAME; Password=PASSWORD; Data Source=DEV01" providerName="Oracle.ManagedDataAccess.Client"/>
</connectionStrings>
<oracle.manageddataaccess.client>
<version number="4.121.1.0">
<dataSources>
<dataSource alias="DEV01" descriptor="(DESCRIPTION = (ADDRESS_LIST = (ADDRESS = (PROTOCOL = TCP)(HOST = HOST)(PORT = PORT))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = dev01.local.junk)))" />
</dataSources>
</version>
</oracle.manageddataaccess.client>
</configuration>
I also have the descriptor in my tnsnames.ora. I am able to tnsping dev01 and it makes the connection just fine. I can also put the descriptor directly in for the connection string hard coded for data soruce and it connects to the DB just fine. There is something wrong and the tnsnames doesnt seem to work otherwise. I feel its something in my config file but cannot seem to figure it out.
EDIT:
Its read from code by
if (_configReader != null)
{
_connectionString =
_configReader.ConnectionStringsSection.ConnectionStrings["DBNAME"].ConnectionString;
}
OracleConnection connection = new OracleConnection(_connectionString);
connection.Open();
which returns the connectionstring from above
it looks like in your descriptor you don't close all of your parentheses. I don't think you need the address_list in there either... try using
(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = HOST)(PORT = PORT))(CONNECT_DATA = (SERVER = DEDICATED)(SERVICE_NAME = dev01.local.junk)))
EDIT:
Finally found the problem. First, your section name for the manageddataaccess HAS to be lowercase, or else it won't match.
Second, I'm not sure what your _configReader is, but I simply used a System.Configuration.Configuration object and it worked, like this:
// Get the application configuration file.
System.Configuration.Configuration config =
ConfigurationManager.OpenExeConfiguration(
ConfigurationUserLevel.None);
if (config != null)
{
ConnectionStringSettings settings = new ConnectionStringSettings("DEV01", config.ConnectionStrings.ConnectionStrings["DBNAME"].ToString());
OracleConnection connection = new OracleConnection(settings.ConnectionString);
connection.Open();
}
The only changes I made to your config file were change the section name value to lowercase.

Resources