Sending Mail in vb.net - gmail-imap

Imports System.Net
Imports System.Net.Mail
Public Class forgetpass
Inherits System.Web.UI.Page
Dim randomCode As String
Public Shared toUser As String
Private Sub btnsend_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles btnsend.Click
Dim from, pass, messageBody As String
Dim rand As Random = New Random()
randomCode = (rand.Next(999999)).ToString()
Dim message As MailMessage = New MailMessage
toUser = txtMail.Text
from = "Mymail#gmail.com"
pass = "MyPassword"
messageBody = "Your reset code is " + randomCode
message.To.Add(toUser)
message.From = New MailAddress(from)
message.Body = messageBody
message.Subject = "Password Resetting Code"
Dim smpt As SmtpClient = New SmtpClient("smpt.gmail.com")
smpt.EnableSsl = True
smpt.Port = 587
smpt.DeliveryMethod = SmtpDeliveryMethod.Network
smpt.Credentials = New NetworkCredential(from, pass)
Try
smpt.Send(message)
MsgBox("Check the email and enter the code")
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
This is my code to provide a random 6 digit code for resetting the password.
But the problem is while running the exception occurs that's shown below.
Exception
So anybody have an idea about that

Related

Is it possible to create a message using Microsoft Graph with a different sent/received date?

I'm working on an application that needs to be able to insert messages into an O365 mailbox with particular dates (similar to a mail migration). I created a version using IMAP with MailKit, and that was a simple matter of setting the date property on the message object:
MimeMessage message = new MimeMessage();
message.From.Add(new MailboxAddress(NameGenerator.AnyName(), EmailAddressGenerator.AnyEmailAddress()));
message.To.Add(new MailboxAddress(m_O365UserID));
message.Subject = StringGenerator.AnyStringOfSizeAndCase(NumberGenerator.RandomNumberBetween(20, 100), CaseType.TitleCase);
BodyBuilder builder = new BodyBuilder
{
HtmlBody = LipsumGenerator.GenerateHtml(NumberGenerator.RandomNumberBetween(3, 10))
};
message.Body = builder.ToMessageBody();
DateTime t = DateTimeGenerator.AnyDateBetween(m_startDate, DateTime.Now);
t = t.Add(DateTimeGenerator.AnyTime());
DateTimeOffset dto = new DateTimeOffset(t);
message.Date = dto;
I was also able to do this in the past with EWS, but I needed to set some extended properties to do it, like this:
ExtendedPropertyDefinition deliveryTime = new Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0E06, MapiPropertyType.SystemTime);
ExtendedPropertyDefinition clientSubmitTime = new Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(0x0039, MapiPropertyType.SystemTime);
ExtendedPropertyDefinition flags = new Microsoft.Exchange.WebServices.Data.ExtendedPropertyDefinition(3591, MapiPropertyType.Integer);
EmailMessage m = new EmailMessage(m_exchangeService);
m.From = EmailAddressGenerator.AnyEmailAddress();
m.ToRecipients.Add(m_emailAddress);
DateTime t = DateTimeGenerator.AnyDateBetween(startDate, DateTime.Now);
t = t.Add(DateTimeGenerator.AnyTime());
m.SetExtendedProperty(deliveryTime, t);
m.SetExtendedProperty(clientSubmitTime, t);
m.SetExtendedProperty(flags, 1);
Both of these approaches can backdate a message to any point that I need. In this case I'm just populating a mailbox with test data to validate the API calls. Trying to do the same thing in graph like this:
Microsoft.Graph.Message message = new Microsoft.Graph.Message();
message.From = new Recipient { EmailAddress = new EmailAddress { Address = EmailAddressGenerator.AnyEmailAddress(), Name = NameGenerator.AnyName() } };
message.ToRecipients = new List<Recipient>();
message.ToRecipients.Append(new Recipient { EmailAddress = new EmailAddress { Address = m_O365UserID } });
message.Subject = StringGenerator.AnyStringOfSizeAndCase(NumberGenerator.RandomNumberBetween(20, 100), CaseType.TitleCase);
DateTime t = DateTimeGenerator.AnyDateBetween(m_startDate, DateTime.Now);
t = t.Add(DateTimeGenerator.AnyTime());
DateTimeOffset dto = new DateTimeOffset(t);
message.ReceivedDateTime = dto;
message.SentDateTime = dto;
message.CreatedDateTime = dto;
message.LastModifiedDateTime = dto;
timestamps the message as of the submission time. I thought I needed to set the same Mapi properties on the message as with EWS, but so far I haven't found a way to do that. I looked into extended properties as outlined here, which says they can be referenced by a type and MAPI property tag. This page says that extended properties can be created on new objects:
To create one or more extended properties in a new resource instance, use the same REST request as creating the instance, and include the properties of the new resource instance and extended property in the request body.
I tried that like this:
Dictionary<string, object> extendedProperties = new Dictionary<string, object>();
extendedProperties.Add("SystemTime 0x0E06",dto.DateTime);
extendedProperties.Add("SystemTime 0x0039", dto.DateTime);
extendedProperties.Add("Integer 0x3591",1);
message.Body = new ItemBody { ContentType = BodyType.Html, Content = LipsumGenerator.GenerateHtml(NumberGenerator.RandomNumberBetween(3, 10)), AdditionalData=extendedProperties};
Which throws an exception:
The property 'SystemTime 0x0E06' does not exist on type 'Microsoft.OutlookServices.ItemBody'. Make sure to only use property names that are defined by the type or mark the type as open type.
I also can't directly create anything on message.SingleValueExtendedProperties, and the same exception happens if I omit SystemTime and just try to set the property with the hex value. I'd like to be able to support Graph for this application-is there any way that anyone knows of to create messages with custom send/receive dates? If I was able to do it in EWS, I'd expect that the newer API should be able to do the same thing.
Edit
#Glen's answer works. I'd tried the same thing, but still had a second definition of the property that I was trying to add to the message body, which was what actually caused the exception. The only other thing to add to his answer is that the time format for the property needs to be in a very specific format, so you can format a standard DateTimeOffset to a mapi compatible time like this:
string mapiTime = $"{dto.UtcDateTime.Year}-{dto.UtcDateTime.Month.ToString("D2")}-{dto.UtcDateTime.Day.ToString("D2")}T{dto.UtcDateTime.TimeOfDay.ToString()}.0{dto.Offset.Hours.ToString("D2")}:00";
message.SingleValueExtendedProperties = new MessageSingleValueExtendedPropertiesCollectionPage()
{
new SingleValueLegacyExtendedProperty {Id = "Integer 0x0E07",Value = "1" },
new SingleValueLegacyExtendedProperty {Id = "SystemTime 0x0039", Value = mapiTime },
new SingleValueLegacyExtendedProperty {Id = "SystemTime 0x0E06",Value = mapiTime }
};
You should be able to do something like
Microsoft.Graph.Message message = new Microsoft.Graph.Message();
message.From = new Recipient { EmailAddress = new EmailAddress { Address = "blah#blah.com", Name = "blah" } };
message.ToRecipients = new List<Recipient>() { new Recipient { EmailAddress = new EmailAddress { Address = "ToBalh#blah.com" } } };
message.Subject = "Blah";
message.SingleValueExtendedProperties = new MessageSingleValueExtendedPropertiesCollectionPage()
{
new SingleValueLegacyExtendedProperty {Id = "Integer 0x0E07",Value = "1" },
new SingleValueLegacyExtendedProperty {Id = "SystemTime 0x0039", Value = "2020-05-12T10:10:47.2048+10:00" },
new SingleValueLegacyExtendedProperty {Id = "SystemTime 0x0E06",Value = "2020-05-12T10:10:47.2048+10:00" }
};
var SaveMessage = graphClient.Me.MailFolders["Inbox"].Messages.Request().AddAsync(message).Result;
works for me okay

Logging of Access control logs in VB .NET

I'm new to VB .NET, I want to write a method that saves a new entry to the database every time someone tries to log in no matter if it is a successful or failed attempt.
Also I need to capture the IP address of the machine where the attempt is performed.
Any advice of where to start
I dont believe capturing ip can be done locally without a library for it, but if you dont mind an api call you can use ip-api.com
'Query location data
Dim Req As HttpWebRequest
Dim Ret As HttpWebResponse = Nothing
Dim SR As StreamReader
Req = DirectCast(WebRequest.Create("http://ip-api.com/json"), HttpWebRequest)
Ret = DirectCast(Req.GetResponse(), HttpWebResponse)
SR = New StreamReader(Ret.GetResponseStream())
Dim Raw As String = Nothing
Raw = SR.ReadToEnd()
Dim JavaScriptSerialization As New JavaScriptSerializer()
Dim ipdata_object As New IPData()
ipdata_object = JavaScriptSerialization.Deserialize(Raw, ipdata_object.GetType)
dim ip_address as string = ipdata_object.query.tostring()
IPData Class
'IP Data API Deserialization classes for http://ip-api.com/json API response
<Serializable>
Class IPData
Public asinfo As String
Public city As String
Public country As String
Public countryCode As String
Public isp As String
Public lat As String
Public lon As String
Public org As String
Public query As String
Public region As String
Public regionName As String
Public status As String
Public timezone As String
Public zip As String
End Class
As for logging, depending on what you want to use, Mysql, CSV, Flatfile, etc
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'SAVE FUNCTION
Dim LogString as String = "User " + Username + " Attempted to login from " + ip_address + " Successfully/Failed"
My.Computer.FileSystem.WriteAllText("C://testfile.txt", inputString, True)
End Sub
You can try something like this for mysql database
Imports MySql.Data.MySqlClient
Imports System.Data.Sql
Imports System
Imports System.Data
Public Class LoginForm
'These variables store information regarding the sql connection string, and the sql class callers.
Dim connectionString As String = "Server=localhost; User Id=admin; Password=pass; Database=access_logs"
Dim SQLConnection As MySqlConnection = New MySqlConnection
Private Sub LoginButton_Click(sender As Object, e As EventArgs) Handles LoginButton.Click
Dim username As String = "usernametextbox.text"
Dim ip_address As String = ipfetchfunction()
Dim status As String = Nothing
If username.ToString() = "valid" And Password.ToString() = "valid" Then
status = "authorized"
Else
status = "failed"
End If
LogAttempt(username, ip_address, status)
End Sub
Public Function LogAttempt(user_name As String, ip_address As String, login_status As String) As Boolean
SQLConnection = New MySqlConnection()
SQLConnection.ConnectionString = connectionString
Dim sqlCommand As New MySqlCommand
Dim str_logSql As String
Try
str_logSql = "insert into access_log (username, user_ip, login_status) values ('" + user_name + "','" + ip_address + "','" + login_status + "')"
'MsgBox(str_logSql) uncomment for debugging
sqlCommand.Connection = SQLConnection
sqlCommand.CommandText = str_logSql
sqlCommand.ExecuteNonQuery()
Return True
Catch ex As Exception
Return False
'MessageBox.Show(ex.ToString()) Uncomment for debugging
End Try
End Function
End Class

Is this the correct approach to customizing the ASP.Net MVC 4 template Login

While the MVC4 template provided by Microsoft is useful, I feel there are a few scenarios that should be covered to help out users trying to log in.
Allow the user to log in with their email address instead of their user name (they can still choose to use their user name). The former is generally easier to remember.
If they don't have a local account and try to use one, check if they have previously used an external provider (such as google) to log in and let them know to use it instead.
If they have registered an account locally but have not yet confirmed their email, let them know. The current template just warns that the username or password is wrong.
Maybe I'm over-thinking it, but I want to provide the user every opportunity to successfully log in and use the site. Here is the code I wrote to add these functions. I wrote it in VB, but am including C# tag since the majority of MVC user's here seem to favor it and VB is easy to read. Is this the correct approach to add these options? Are there any glaring errors with this code, aside from the fact I can probably refactor it? Thank you.
<HttpPost()> _
<AllowAnonymous()> _
<ValidateAntiForgeryToken()> _
Public Function Login(ByVal model As LoginModel, ByVal returnUrl As String) As ActionResult
If ModelState.IsValid Then
If IsEmail(model.UserName) Then
'the username is an email address
Dim username = GetUserNamebyEmail(model.UserName)
If username IsNot Nothing Then
If WebSecurity.Login(username, model.Password, persistCookie:=model.RememberMe) Then
Return RedirectToLocal(returnUrl)
End If
'check if there is a local account
Dim localID = GetUserIDbyEmail(model.UserName)
If localID Is Nothing Then
'no local account means the username is wrong
ModelState.AddModelError("", "The user name or password provided is incorrect.")
Else
If Not OAuthWebSecurity.HasLocalAccount(localID) Then
'registered via external provider
ModelState.AddModelError("", "Please login with the External Provider you have previously used.")
Else
If Not WebSecurity.IsConfirmed(model.UserName) Then
'has a local account, but hasn't confirmed email
ModelState.AddModelError("", "You have not yet confirmed your email.")
Else
'password is wrong
ModelState.AddModelError("", "The user name or password provided is incorrect.")
End If
End If
End If
Else
ModelState.AddModelError("", "The email you entered is incorrect.")
End If
Else
'must be the regular user name, so log in as normal
If WebSecurity.Login(model.UserName, model.Password, persistCookie:=model.RememberMe) Then
Return RedirectToLocal(returnUrl)
End If
'check if there is a local account
Dim localID = GetUserIDbyUserName(model.UserName)
If localID Is Nothing Then
'no local account means the username is wrong
ModelState.AddModelError("", "The user name or password provided is incorrect.")
Else
If Not OAuthWebSecurity.HasLocalAccount(localID) Then
'registered via external provider
ModelState.AddModelError("", "Please login with the External Provider you have previously used.")
Else
If Not WebSecurity.IsConfirmed(model.UserName) Then
'has a local account, but hasn't confirmed email
ModelState.AddModelError("", "You have not yet confirmed your email.")
Else
'password is wrong
ModelState.AddModelError("", "The user name or password provided is incorrect.")
End If
End If
End If
End If
End If
Return View(model)
End Function
'check if input is an email address
Public Function IsEmail(ByVal input As String) As Boolean
Return Regex.IsMatch(input, "\A(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*#(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?)\Z")
End Function
Public Function GetUserNamebyEmail(ByVal email As String) As String
Dim username As String = Nothing
Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString)
Dim cmd As SqlCommand = New SqlCommand("select username from user_info where Email = #Email", conn)
cmd.Parameters.Add(New SqlParameter("#Email", System.Data.SqlDbType.NVarChar))
cmd.Parameters("#Email").Value = email
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
Try
While reader.Read
username = reader(0)
End While
Finally
reader.Close()
End Try
conn.Close()
Return username
End Function
Public Function GetUserIDbyEmail(ByVal email As String) As Integer?
Dim userID As Integer?
Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString)
Dim cmd As SqlCommand = New SqlCommand("select UserID from user_info where Email = #Email", conn)
cmd.Parameters.Add(New SqlParameter("#Email", System.Data.SqlDbType.NVarChar))
cmd.Parameters("#Email").Value = email
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
Try
While reader.Read
userID = reader(0)
End While
Finally
reader.Close()
End Try
conn.Close()
Return userID
End Function
Public Function GetUserIDbyUserName(ByVal username As String) As Integer?
Dim userID As Integer?
Dim conn As SqlConnection = New SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings("DefaultConnection").ConnectionString)
Dim cmd As SqlCommand = New SqlCommand("select UserID from user_info where UserName = #username", conn)
cmd.Parameters.Add(New SqlParameter("#username", System.Data.SqlDbType.NVarChar))
cmd.Parameters("#username").Value = username
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
Try
While reader.Read
userID = reader(0)
End While
Finally
reader.Close()
End Try
conn.Close()
Return userID
End Function

StackOverFlowException was unhandled in CustomAuthorize AuthorizeAttribute

I have a custom authorize program called CustomAuthorize that inherits AuthorizeAttribute that simply restricts access to certain controllers and resources based on various factors specific to the user. However, I get an error on the following line:
The line:
Protected Overrides Function AuthorizeCore(httpContext As
HttpContextBase) As Boolean
The error:
An unhandled exception of type 'System.StackOverflowException'
occurred in MyBlog.DLL
Here's my whole code:
Public Class CustomAuthorize
Inherits AuthorizeAttribute
Protected Overrides Function AuthorizeCore(httpContext As HttpContextBase) As Boolean
Dim authorized = AuthorizeCore(httpContext)
' if user is not authorized, restrict access
If (authorized = False) Then
Return False
End If
' get user name
Dim username = httpContext.User.Identity.Name
' get user
Dim user = Membership.GetUser(username, True)
' get user's profile
Dim db As UserProfileDbContext = New UserProfileDbContext
Dim profile = db.UserProfiles.Where(Function(x) x.UserId = user.ProviderUserKey).Single
' TODO: if user doesn't have a profile, return false
' get route
Dim routeData = httpContext.Request.RequestContext.RouteData
' get controller
Dim controller = routeData.Values("controller").ToString
' get id
Dim id = routeData.Values("id").ToString
' if no id is set, check to see if the user owns the requested entity (company or blog)
If String.IsNullOrEmpty(id) = True Then
If controller.ToLower = "blog" Or controller.ToLower = "article" Then
If profile.IsCompanyOwner Or profile.IsBlogOwner = True Then
' if user is owner of a blog with no specified id, then it will default to their own blog
Return True
End If
End If
Else
' if controller = blog
' check for blog id
If controller.ToLower = "blog" Then
' check to see if the user owns the company to which the blog belongs
If profile.IsCompanyOwner Then
' get company from blog id
Dim db1 As BlogDbContext = New BlogDbContext
Dim blog = db1.Blogs.Where(Function(b) b.BlogId = id).Single()
If blog.CompanyId = profile.CompanyId Then
Return True
End If
ElseIf profile.IsBlogOwner Then
' if user's blog id is the blog being requested, grant access
If profile.BlogId = id Then
Return True
End If
End If
End If
' if controller = article
' check for article blog id
If controller.ToLower = "article" Then
Dim db2 As ArticleDbContext = New ArticleDbContext
Dim article = db2.Articles.Where(Function(a) a.ArticleId = id).Single
Dim articleBlogId = article.BlogId
' check to see if the user owns the company to which the blog belongs
If profile.IsCompanyOwner Then
' get company from blog id
Dim db1 As BlogDbContext = New BlogDbContext
Dim blog = db1.Blogs.Where(Function(b) b.BlogId = articleBlogId).Single()
If blog.CompanyId = profile.CompanyId Then
Return True
End If
ElseIf profile.IsBlogOwner Then
' if user's blog id is the blog being requested, grant access
If profile.BlogId = articleBlogId Then
Return True
End If
End If
End If
End If
' if we got this far, then the user shouldn't have access
Return False
End Function
Protected Overrides Sub HandleUnauthorizedRequest(filterContext As AuthorizationContext)
Dim result = New ViewResult()
result.ViewName = "Error"
result.ViewBag.ErrorMessage = "oops, you are not allowed"
filterContext.Result = result
End Sub
End Class
How can I fix this error? Thank you.
I think you want to call the MyBase.AuthorizeCore.
So you want to change this line
Dim authorized = AuthorizeCore(httpContext)
to
Dim authorized = MyBase.AuthorizeCore(httpContext)
The first line of your function is Dim authorized = AuthorizeCore(httpContext)
This line will call your method again, and the first line of that new call will do the same, ad infinitum. This causes a StackOverflowException.

Grails: save is not working

i have created new domain in grails and from a controller i've tried to save but nothing get saved in the database.. the code is as follow
controller
def register={
String name = params.name
String email = params.email
String pass = params.password
boolean signedIn = params.signedIn
System.out.println(name + " " + email +" "+ pass+" " + signedIn)
def rUser = new Registered(params)
rUser.signedIn = signedIn
System.out.println(rUser)
rUser.save(flush:true)
}
domain
class Registered {
String name;
String email;
String password;
boolean signedIn =false;
static constraints = {
}
}
and i'm trying to save by this url
http://localhost:8080/egypths/apps/register?name=hegab&email=eio#gmail.com&password=tom&signedIn=false
so what am i doing wrong ... putting in mind that there's no error in the stack trace
I would start by wrapping this in an integration test that would look like this:
import groovy.util.GroovyTestCase
import org.junit.Test
public class RegisterControllerTests extends GroovyTestCase {
#Test
void saveAction() {
def controller = new RegisterController() //or whatever the controller name is
controller.params.name = "SomethingUnique"
controller.params.email = "example#example.com"
controller.params.password = "password"
controller.params.signedIn = "false"
controller.register()
def registered = Registered.findByName("SomethingUnique")
assert "example#example.com" == registered.email
assert "password" == registered.password
assert false == registered.signedIn
}
}
Then I would start by making your controller action as simple as possible:
def register={
String name = params.name
String email = params.email
String pass = params.password
boolean signedIn = params.signedIn
def rUser = new Registered()
rUser.name = name
rUser.email = email
rUser.password = pass
rUser.signedIn = signedIn
rUser.save(flush:true, failOnError:true) //I would remove the failOnError after you identify the issue.
}
This way you can quickly repeat your test and figure out where your problem is. Adding the failOnError:true to the save call will cause an exception to be thrown if it doesn't pass validation. If this simple example works start working back towards a more elegant solution to identify where you're issue resides.

Resources