Unable to Send email via .Net core 2.0 - email

I wrote the following and was running perfectly. But after updates stops running, I have already setup a mail server I had not any problem.
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using SportsStore.Data;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Security.Claims;
using System.Threading.Tasks;
namespace SportsStore.Helper
{
public class Email: IEmail
{
private SmtpClient Client;
private string MessageBody, Subject, UserEmail;
private MailAddress MailFrom, MailTo;
private MailMessage Message;
public Email(IServiceProvider service)
{
this.Client = new SmtpClient("localhost");
this.Client.Port = 25;
this.Client.UseDefaultCredentials = false;
this.Client.Credentials = new NetworkCredential("postmaster", "xxxxxxx!");
this.MailFrom = new MailAddress("xxxxx.xxxxx#yandex.com");
this.UserEmail = service.GetRequiredService<IHttpContextAccessor>().HttpContext.User.Identity.Name;
this.MailTo = new MailAddress(UserEmail);
}
public void SetMessageBody(string orderName)
{
MessageBody = String.Format("The order with id {0} has been placed and is ready to ship", orderName);
}
public string GetMessageBody()
{
return MessageBody;
}
public void SetSubject()
{
Subject = "Order Details";
}
public string GetSubject()
{
return Subject;
}
public bool SendMessageAsync()
{
this.Message = new MailMessage(this.MailFrom.ToString(), this.MailTo.ToString(), this.GetSubject(), this.GetMessageBody());
if (this.Client.SendMailAsync(this.Message).IsCompletedSuccessfully)
{
return true;
}
return false;
}
}
}
The Client.SendEmailAsync() now return false.
Any suggestion?Please give a quick answer or I have to jump to nuget packages for a package to install.

The method SendMailAsync is Async in your Send Mail in your application.
What are best practices for using SmtpClient, SendAsync and Dispose under .NET 4.0

Related

Difficulty connecting two Hololens with Unet

I am relatively new to Unity and am currently trying to build an multi-user app on Hololens. Currently, I am just trying to get two Hololens to connect over LAN using Unet. When I use one of my Hololens to host the server, my laptop can connect to it during play mode in the Unity editor. However, when I try to use my other Hololens to connect to it, it does not work and I am not sure why. Does anyone else have this problem? And if so, how do you fix it?
Thanks in advance.
Edit: some code
Here's the code for network manager
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Networking;
using System;
public class NetworkManager_Custom : NetworkManager
{
public void StartupHost()
{
setPort();
NetworkManager.singleton.StartHost();
}
public void JoinGame()
{
SetIpAddress();
setPort();
NetworkManager.singleton.StartClient();
}
private void SetIpAddress()
{
string Address = "192.168.2.80";
NetworkManager.singleton.networkAddress = Address;
}
private void setPort()
{
NetworkManager.singleton.networkPort = 9001;
}
}
Here's the code for the start-server button
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using UnityEngine.Networking;
public class ok : NetworkBehaviour, IFocusable, IInputClickHandler
{
bool hasFocus;
public NetworkManager_Custom manager;
public void OnFocusEnter()
{
hasFocus = true;
}
public void OnFocusExit()
{
hasFocus = false;
}
public void OnInputClicked(InputClickedEventData eventData)
{
manager.StartupHost();
}
}
Here's the code for joining server as client
using HoloToolkit.Unity.InputModule;
using UnityEngine;
using UnityEngine.Networking;
using UnityEngine.Networking.NetworkSystem;
public class aegf : NetworkBehaviour, IFocusable, IInputClickHandler
{
bool hasFocus;
public NetworkManager_Custom manager;
public void OnFocusEnter()
{
hasFocus = true;
}
public void OnFocusExit()
{
hasFocus = false;
}
public void OnInputClicked(InputClickedEventData eventData)
{
manager.JoinGame();
}
}
It's worth double-checking the capabilties that you've set. Ensure all three of these are selected:
InternetClient
InternetClientServer
PrivateNetworkClientServer
Ref: https://learn.microsoft.com/en-us/uwp/schemas/appxpackage/appxmanifestschema/element-capability

My program does not save or load infomation in or from data base

I created a database and three pages for a register & login form & the third is for a lottery between my usernames .
I don't have any errors but the whole thing is not using the data base,
it does not save or load from database .
This is my register form:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
public partial class _2 : System.Web.UI.Page
{
protected void btnRegister_Click(object sender, EventArgs e)
{
string strcon = "Data Source=.;uid=sa;pwd=123;database=Login_Register";
SqlConnection con = new SqlConnection(strcon);
SqlCommand com = new SqlCommand("strlogin", con);
com.CommandType = System.Data.CommandType.StoredProcedure;
SqlParameter p1 = new SqlParameter("username", txtUserName.Text.ToString());
SqlParameter p2 = new SqlParameter("email", txtEmail.Text.ToString());
SqlParameter p3 = new SqlParameter("password", txtpassword.Text.ToString());
com.Parameters.Add(p1);
com.Parameters.Add(p2);
com.Parameters.Add(p3);
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
con.Close();
com.ExecuteNonQuery();
}
private SqlDbType ToString(object text)
{
throw new NotImplementedException();
}
}
public class Label4
{
internal static object Text;
internal static bool Visible;
}
public class txtUserName
{
internal static object Text;
internal static bool Visible;
}
public class txtEmail
{
internal static object Text;
internal static bool Visible;
}
public class txtpassword
{
internal static object Text;
internal static bool Visible;
}
Look at your code
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
con.Close();
com.ExecuteNonQuery();
You are opening the connection, closing it and then executing.
it should be:
con.Open();
Label4.Text ="ثبت نام با موفقیت انجام شد".ToString();
Label4.Visible = true;
com.ExecuteNonQuery();
con.Close();//close connection after execute.
also it would be a good idea to add try/catch block around it - in case connection cannot be opened

Token Based Authentication using ASP.NET Web API 2, Owin, AspNet.Identity.MongoDB and mongocsharpdriver

+after successfully implementing Token Based Authentication using ASP.NET Web API 2, Owin, and Identity, i wished to change my implementation to use MongoDB instead of MSSQL with Entity Framework, with the help of this application here....truth be said, i dont fully understand how this should be done, but at least i know what i want my application to behave. i want to follow this IMPLEMENTATION HERE, using AspNet.Identity.MongoDB and mongocsharpdriver...and so far, here,s what I've done:
Account Controller
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using System.Web.Http;
using withMongoDB.HelperClasses.Services;
using withMongoDB.Models.Account;
namespace withMongoDB.Controllers
{
[RoutePrefix("api/Account")]
public class AccountsController : ApiController
{
AccountsService _accountsService = new AccountsService();
// POST api/Account/Register
[AllowAnonymous]
[Route("Register")]
public async Task<IHttpActionResult> Register(UserModel userModel)
{
if (!ModelState.IsValid)
{
return BadRequest(ModelState);
}
await _accountsService.Register(userModel);
return Ok();
}
private IHttpActionResult GetErrorResult(IdentityResult result)
{
if (result == null)
{
return InternalServerError();
}
if (!result.Succeeded)
{
if (result.Errors != null)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
if (ModelState.IsValid)
{
// No ModelState errors are available to send, so just return an empty BadRequest.
return BadRequest();
}
return BadRequest(ModelState);
}
return null;
}
}
}
then the register method from the controller should be taken by the accounts Service
using AspNet.Identity.MongoDB;
using Microsoft.AspNet.Identity;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using withMongoDB.Models.Account;
namespace withMongoDB.HelperClasses.Services
{
public class AccountsService
{
private readonly MongoAccountsConnectionHelper<UserProfile> _accounts;
public AccountsService()
{
_accounts = new MongoAccountsConnectionHelper<UserProfile>();
}
public async Task<IdentityResult> Register(UserModel userModel)
{
var userprofile = new UserProfile
{
UserName = userModel.UserName
};
var result = await _accounts.CreateAsync(userprofile, userModel.Password);
return result;
}
}
}
and finally the MongoAccountsConnectionHelper takes the result of the accounts service class to mongo database....
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace withMongoDB.HelperClasses
{
using AspNet.Identity.MongoDB;
//using Entities;
using MongoDB.Bson;
using MongoDB.Bson.Serialization.Conventions;
using MongoDB.Driver;
using System.Configuration;
using withMongoDB.Models.Account;
public class MongoAccountsConnectionHelper
{
private readonly MongoCollection<UserProfile> userProfileCollection;
public MongoDatabase Database { get; private set; }
public MongoAccountsConnectionHelper()
{
var pack = new ConventionPack()
{
new CamelCaseElementNameConvention(),
new EnumRepresentationConvention(BsonType.String)
};
ConventionRegistry.Register("CamelCaseConvensions", pack, t => true);
var mongoUrlBuilder = new MongoConnectionStringBuilder(ConfigurationManager.ConnectionStrings["MongoDB"].ConnectionString);
Database = new MongoClient().GetServer().GetDatabase(mongoUrlBuilder.DatabaseName);
userProfileCollection = Database.GetCollection<UserProfile>("users");
}
public MongoCollection<UserProfile> Users
{
get { return userProfileCollection; }
}
}
}
any help, tips, ideas, or opinions will be highly appreciated....{should i consider alternatives like MembershipReboot and IdentityReboot by brockallen?}
To do it smoothly, you need first to remove the dependency on "Microsoft.AspNet.Identity.EntityFramework", by providing your own user class/table (which should implements IUser as a minimum), and Also you need to implement the UserManager class (which should imeplements UserManager, and finally you need to implement the UserStore class (which should implement IUserStore as minimum) where T is the Id type in the User Table.
Once you done the above, then it is the UserStore where you can change to use MongoDB.
Hope that helps.

Error in MVVM when building

i just created a PCL called Tipcalc>core, the tutorial from witch i am building it is this one . here is
my TipViewModel.cs
using Cirrious.MvvmCross.ViewModels;
namespace TipCalc.Core
{
public class TipViewModel : MvxViewModel
{
private readonly ICalculation _calculation;
public TipViewModel(ICalculation calculation)
{
_calculation = calculation;
}
public override void Start()
{
_subTotal = 100;
_generosity = 10;
Recalcuate();
base.Start();
}
private double _subTotal;
public double SubTotal
{
get { return _subTotal; }
set { _subTotal = value; RaisePropertyChanged(() => SubTotal); Recalcuate(); }
}
private int _generosity;
public int Generosity
{
get { return _generosity; }
set { _generosity = value; RaisePropertyChanged(() => Generosity); Recalcuate(); }
}
private double _tip;
public double Tip
{
get { return _tip; }
set { _tip = value; RaisePropertyChanged(() => Tip); }
}
private void Recalcuate()
{
Tip = _calculation.TipAmount(SubTotal, Generosity);
}
}
}
The problem is that when i cuild this PCL, get the following errors:
Error 1 The type or namespace name 'ICalculation' could not be found (are you missing a using directive or an assembly reference?)
TipCalc.Core
Error 2 The type or namespace name 'ICalculation' could not be found (are you missing a using directive or an assembly reference?)
Altough my interface and class,are right there in the Services Folder,in project.
Calculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TipCalc.Core.Services
{
public class Calculation : ICalculation
{
public double TipAmount(double subTotal, int generosity)
{
return subTotal * ((double)generosity) / 100.0;
}
}
}
And ICalculation.cs
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace TipCalc.Core.Services
{
public interface ICalculation
{
double TipAmount(double subTotal, int generosity);
}
}
any help please?
You need to add using in Calculation.cs
to Use ICalculation.cs
Using TipCalc.Core.Services;

Adding Custom Filters for Dynamic Data Website (VS2010, EF4)

Trying to add some different filters (in addition to the ForeignKey filter) to a Dynamic Data Website in VS2010 using EF4. I can add the new Filter templates, but how do I specify which template will get displayed for each property in my model?
Thanks
Here are the steps for how to do this:
1) Create a new UserControl for the filter you want under DynamicData\Filters. I created a TextFilter.ascx:
<%# Control Language="C#" AutoEventWireup="true" CodeBehind="TextFilter.ascx.cs" Inherits="Test.Prototype.Web.DynamicData.DynamicData.Filters.TextFilter" %>
<asp:TextBox runat="server" ID="TextBox1" AutoPostBack="true" OnTextChanged="TextBox1_OnTextChanged" CssClass="DDFilter">
</asp:TextBox>
and the code behind:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
using System.Web.DynamicData;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Test.Prototype.Web.DynamicData.DynamicData.Filters
{
public partial class TextFilter : System.Web.DynamicData.QueryableFilterUserControl
{
private const string NullValueString = "[null]";
protected void Page_Load(object sender, EventArgs e)
{
}
public override Control FilterControl
{
get
{
return TextBox1;
}
}
protected void TextBox1_OnTextChanged(object sender, EventArgs e)
{
OnFilterChanged();
}
public override IQueryable GetQueryable(IQueryable source)
{
string selectedValue = TextBox1.Text;
if (String.IsNullOrEmpty(selectedValue))
{
return source;
}
object value = selectedValue;
if (selectedValue == NullValueString)
{
value = null;
}
if (DefaultValues != null)
{
DefaultValues[Column.Name] = value;
}
return ApplyEqualityFilter(source, Column.Name, value);
}
}
}
Then in your model, just annotate your properties with the FilterUIHint attribute pointing to the next filter and you're good to go:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
namespace Test.Model
{
public partial class Asset
{
#region Primitive Properties
public virtual int Id
{
get;
set;
}
[FilterUIHint("TextFilter")]
public virtual string Name
{
get;
set;
}
...