Ok So Here is what im attempting to do.
Add a Fileupload Control to The Registration Section of a New MVC Application.
How do i define this form as a defined control so intellisense picks it up on the vb side.
So Far i have the following.
AccountsModel.VB Code
Imports System.ComponentModel Imports System.ComponentModel.DataAnnotations Imports System.ComponentModel.DataAnnotations.Schema Imports System.Globalization Imports System.Data.Entity Imports System.Data.SqlClient Imports System.Drawing Public Class UsersContext Inherits DbContext Public Sub New() MyBase.New("DefaultConnection") End Sub Public Property UserProfiles As DbSet(Of UserProfile) End Class <Table("UserProfile")> _ Public Class UserProfile<Key()> _<DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)> _ Public Property UserId As Integer Public Property UserName As String End Class Public Class RegisterExternalLoginModel <Required()> _<Display(Name:="Email")> _ Public Property UserName As String Public Property ExternalLoginData As String End Class Public Class LocalPasswordModel <Required()> _<DataType(DataType.Password)> _<Display(Name:="Current password")> _ Public Property OldPassword As String<Required()> _<StringLength(100, ErrorMessage:="The {0} must be at least {2} characters long.", MinimumLength:=6)> _<DataType(DataType.Password)> _<Display(Name:="New password")> _ Public Property NewPassword As String<DataType(DataType.Password)> _<Display(Name:="Confirm new password")> _<Compare("NewPassword", ErrorMessage:="The new password and confirmation password do not match.")> _ Public Property ConfirmPassword As String End Class Public Class LoginModel <Required()> _<Display(Name:="Email")> _ Public Property UserName As String<Required()> _<DataType(DataType.Password)> _<Display(Name:="Password")> _ Public Property Password As String<Display(Name:="Remember me?")> _ Public Property RememberMe As Boolean End Class Public Class RegisterModel <Required()> _<Display(Name:="Email")> _ Public Property UserName As String<Required()> _<StringLength(100, ErrorMessage:="The {0} must be at least {2} characters long.", MinimumLength:=6)> _<DataType(DataType.Password)> _<Display(Name:="Password")> _ Public Property Password As String<DataType(DataType.Password)> _<Display(Name:="Confirm password")> _<Compare("Password", ErrorMessage:="The password and confirmation password do not match.")> _ Public Property ConfirmPassword As String End Class Public Class ExternalLogin Public Property Provider As String Public Property ProviderDisplayName As String Public Property ProviderUserId As String End Class
Register.aspx
<%@ Page Language="VB" MasterPageFile="~/Views/Shared/Site.Master" Inherits="System.Web.Mvc.ViewPage(Of SN.RegisterModel)" %><asp:Content ID="registerTitle" ContentPlaceHolderID="TitleContent" runat="server"> Register</asp:Content><asp:Content ID="registerContent" ContentPlaceHolderID="MainContent" runat="server"><form id="form1" runat="server"><hgroup class="title"><h1>Register.<asp:SqlDataSource ID="SqlDataSource1" runat="server" ConnectionString="<%$ ConnectionStrings:AccountManager %>" DeleteCommand="DELETE FROM [SN_Users] WHERE [id] = @id" InsertCommand="INSERT INTO [SN_Users] ([id], [email], [password]) VALUES (@id, @email, @password)" SelectCommand="SELECT * FROM [SN_Users]" UpdateCommand="UPDATE [SN_Users] SET [email] = @email, [password] = @password WHERE [id] = @id"><DeleteParameters><asp:Parameter Name="id" Type="Int32" /></DeleteParameters><InsertParameters><asp:Parameter Name="id" Type="Int32" /><asp:Parameter Name="email" Type="String" /><asp:Parameter Name="password" Type="String" /></InsertParameters><UpdateParameters><asp:Parameter Name="email" Type="String" /><asp:Parameter Name="password" Type="String" /><asp:Parameter Name="id" Type="Int32" /></UpdateParameters></asp:SqlDataSource></h1><h2>Create a new account.</h2></hgroup><% Using Html.BeginForm() %><%: Html.AntiForgeryToken() %><%: Html.ValidationSummary() %><fieldset><legend>Registration Form</legend><ol><li><%: Html.LabelFor(Function(m) m.UserName) %><%: Html.TextBoxFor(Function(m) m.UserName) %></li><li><%: Html.LabelFor(Function(m) m.Password) %><%: Html.PasswordFor(Function(m) m.Password) %></li><li><%: Html.LabelFor(Function(m) m.ConfirmPassword) %><%: Html.PasswordFor(Function(m) m.ConfirmPassword) %></li><li> Image:<asp:FileUpload id="FileUploadControl" runat="server" OnDisposed="ParseImage" /></li></ol><input type="submit" value="Register" onclick="Insert" /></fieldset><% End Using %></form></asp:Content><asp:Content ID="scriptsContent" ContentPlaceHolderID="ScriptsSection" runat="server"><%: Scripts.Render("~/bundles/jqueryval") %></asp:Content>
Modified AccountController.vb
Imports System.Diagnostics.CodeAnalysis Imports System.Security.Principal Imports System.Transactions Imports System.Web.Routing Imports DotNetOpenAuth.AspNet Imports Microsoft.Web.WebPages.OAuth Imports WebMatrix.WebData Imports System.Data.SqlClient Imports System.Security.Cryptography<Authorize()> _<InitializeSimpleMembership()> _ Public Class AccountController Inherits System.Web.Mvc.Controller ' ' GET: /Account/Login <AllowAnonymous()> _ Public Function Login(ByVal returnUrl As String) As ActionResult ViewData("ReturnUrl") = returnUrl Return View() End Function ' ' POST: /Account/Login <HttpPost()> _<AllowAnonymous()> _<ValidateAntiForgeryToken()> _ Public Function Login(ByVal model As LoginModel, ByVal returnUrl As String) As ActionResult If ModelState.IsValid AndAlso WebSecurity.Login(model.UserName, model.Password, persistCookie:=model.RememberMe) Then Return RedirectToLocal(returnUrl) End If ' If we got this far, something failed, redisplay form ModelState.AddModelError("", "The user name or password provided is incorrect.") Return View(model) End Function ' ' POST: /Account/LogOff <HttpPost()> _<ValidateAntiForgeryToken()> _ Public Function LogOff() As ActionResult WebSecurity.Logout() Return RedirectToAction("Index", "Home") End Function ' ' GET: /Account/Register <AllowAnonymous()> _ Public Function Register() As ActionResult Return View() End Function ' ' POST: /Account/Register <HttpPost()> _<AllowAnonymous()> _<ValidateAntiForgeryToken()> _ Public Function Register(ByVal model As RegisterModel) As ActionResult If ModelState.IsValid Then ' Attempt to register the user Try '---------------------------------------------------------------------------------------------------------------------' ' Custom Block For SQL Data Auth ' '---------------------------------------------------------------------------------------------------------------------' 'Add User to Backend DB for Storage and Authenticating Against the Server as Well as the User Manager Dim conn As New SqlConnection(ConfigurationManager.ConnectionStrings("AccountManager").ConnectionString) Dim cmd As New SqlCommand("adduser", conn) cmd.CommandType = CommandType.StoredProcedure cmd.Parameters.AddWithValue("email", model.UserName.ToString) cmd.Parameters.AddWithValue("pass", model.Password.ToString) cmd.Parameters.AddWithValue("image", model.Image.ToString)''''''''''''''
'This Code is For Adding the Image From FileUpload1 on the ASP.Net Side Into The Sql DB' 'And what im having trouble with' 'Add User to Built-In User Manager for Cookie Authentication WebSecurity.CreateUserAndAccount(model.UserName, model.Password) WebSecurity.Login(model.UserName, model.Password) Try conn.Open() cmd.ExecuteNonQuery() Catch ex As Exception ' Do something here Finally If conn IsNot Nothing Then conn.Close() End If '---------------------------------------------------------------------------------------------------------------------' ' End Block ' '---------------------------------------------------------------------------------------------------------------------' End Try Return RedirectToAction("Index", "Home") Catch e As MembershipCreateUserException ModelState.AddModelError("", ErrorCodeToString(e.StatusCode)) End Try End If ' If we got this far, something failed, redisplay form Return View(model) End Function ' ' POST: /Account/Disassociate <HttpPost()> _<ValidateAntiForgeryToken()> _ Public Function Disassociate(ByVal provider As String, ByVal providerUserId As String) As ActionResult ' Wrap in a transaction to prevent the user from accidentally disassociating all their accounts at one time. Dim ownerAccount = OAuthWebSecurity.GetUserName(provider, providerUserId) Dim message As ManageMessageId? = Nothing ' Only disassociate the account if the currently logged in user is the owner If ownerAccount = User.Identity.Name Then ' Use a transaction to prevent the user from deleting their last login credential Using scope As New TransactionScope(TransactionScopeOption.Required, New TransactionOptions With {.IsolationLevel = IsolationLevel.Serializable}) Dim hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)) If hasLocalAccount OrElse OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name).Count > 1 Then OAuthWebSecurity.DeleteAccount(provider, providerUserId) scope.Complete() message = ManageMessageId.RemoveLoginSuccess End If End Using End If Return RedirectToAction("Manage", New With {.Message = message}) End Function ' ' GET: /Account/Manage Public Function Manage(ByVal message As ManageMessageId?) As ActionResult ViewData("StatusMessage") = If(message = ManageMessageId.ChangePasswordSuccess, "Your password has been changed.", _ If(message = ManageMessageId.SetPasswordSuccess, "Your password has been set.", _ If(message = ManageMessageId.RemoveLoginSuccess, "The external login was removed.", _ ""))) ViewData("HasLocalPassword") = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)) ViewData("ReturnUrl") = Url.Action("Manage") Return View() End Function ' ' POST: /Account/Manage <HttpPost()> _<ValidateAntiForgeryToken()> _ Public Function Manage(ByVal model As LocalPasswordModel) As ActionResult Dim hasLocalAccount = OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)) ViewData("HasLocalPassword") = hasLocalAccount ViewData("ReturnUrl") = Url.Action("Manage") If hasLocalAccount Then If ModelState.IsValid Then ' ChangePassword will throw an exception rather than return false in certain failure scenarios. Dim changePasswordSucceeded As Boolean Try changePasswordSucceeded = WebSecurity.ChangePassword(User.Identity.Name, model.OldPassword, model.NewPassword) Catch e As Exception changePasswordSucceeded = False End Try If changePasswordSucceeded Then Return RedirectToAction("Manage", New With {.Message = ManageMessageId.ChangePasswordSuccess}) Else ModelState.AddModelError("", "The current password is incorrect or the new password is invalid.") End If End If Else ' User does not have a local password so remove any validation errors caused by a missing ' OldPassword field Dim state = ModelState("OldPassword") If state IsNot Nothing Then state.Errors.Clear() End If If ModelState.IsValid Then Try WebSecurity.CreateAccount(User.Identity.Name, model.NewPassword) Return RedirectToAction("Manage", New With {.Message = ManageMessageId.SetPasswordSuccess}) Catch e As Exception ModelState.AddModelError("", e) End Try End If End If ' If we got this far, something failed, redisplay form Return View(model) End Function ' ' POST: /Account/ExternalLogin <HttpPost()> _<AllowAnonymous()> _<ValidateAntiForgeryToken()> _ Public Function ExternalLogin(ByVal provider As String, ByVal returnUrl As String) As ActionResult Return New ExternalLoginResult(provider, Url.Action("ExternalLoginCallback", New With {.ReturnUrl = returnUrl})) End Function ' ' GET: /Account/ExternalLoginCallback <AllowAnonymous()> _ Public Function ExternalLoginCallback(ByVal returnUrl As String) As ActionResult Dim result = OAuthWebSecurity.VerifyAuthentication(Url.Action("ExternalLoginCallback", New With {.ReturnUrl = returnUrl})) If Not result.IsSuccessful Then Return RedirectToAction("ExternalLoginFailure") End If If OAuthWebSecurity.Login(result.Provider, result.ProviderUserId, createPersistentCookie:=False) Then Return RedirectToLocal(returnUrl) End If If User.Identity.IsAuthenticated Then ' If the current user is logged in add the new account OAuthWebSecurity.CreateOrUpdateAccount(result.Provider, result.ProviderUserId, User.Identity.Name) Return RedirectToLocal(returnUrl) Else ' User is new, ask for their desired membership name Dim loginData = OAuthWebSecurity.SerializeProviderUserId(result.Provider, result.ProviderUserId) ViewData("ProviderDisplayName") = OAuthWebSecurity.GetOAuthClientData(result.Provider).DisplayName ViewData("ReturnUrl") = returnUrl Return View("ExternalLoginConfirmation", New RegisterExternalLoginModel With {.UserName = result.UserName, .ExternalLoginData = loginData}) End If End Function ' ' POST: /Account/ExternalLoginConfirmation <HttpPost()> _<AllowAnonymous()> _<ValidateAntiForgeryToken()> _ Public Function ExternalLoginConfirmation(ByVal model As RegisterExternalLoginModel, ByVal returnUrl As String) As ActionResult Dim provider As String = Nothing Dim providerUserId As String = Nothing If User.Identity.IsAuthenticated OrElse Not OAuthWebSecurity.TryDeserializeProviderUserId(model.ExternalLoginData, provider, providerUserId) Then Return RedirectToAction("Manage") End If If ModelState.IsValid Then ' Insert a new user into the database Using db As New UsersContext() Dim user = db.UserProfiles.FirstOrDefault(Function(u) u.UserName.ToLower() = model.UserName.ToLower()) ' Check if user already exists If user Is Nothing Then ' Insert name into the profile table db.UserProfiles.Add(New UserProfile With {.UserName = model.UserName}) db.SaveChanges() OAuthWebSecurity.CreateOrUpdateAccount(provider, providerUserId, model.UserName) OAuthWebSecurity.Login(provider, providerUserId, createPersistentCookie:=False) Return RedirectToLocal(returnUrl) Else ModelState.AddModelError("UserName", "User name already exists. Please enter a different user name.") End If End Using End If ViewData("ProviderDisplayName") = OAuthWebSecurity.GetOAuthClientData(provider).DisplayName ViewData("ReturnUrl") = returnUrl Return View(model) End Function ' ' GET: /Account/ExternalLoginFailure <AllowAnonymous()> _ Public Function ExternalLoginFailure() As ActionResult Return View() End Function<AllowAnonymous()> _<ChildActionOnly()> _ Public Function ExternalLoginsList(ByVal returnUrl As String) As ActionResult ViewData("ReturnUrl") = returnUrl Return PartialView("_ExternalLoginsListPartial", OAuthWebSecurity.RegisteredClientData) End Function<ChildActionOnly()> _ Public Function RemoveExternalLogins() As ActionResult Dim accounts = OAuthWebSecurity.GetAccountsFromUserName(User.Identity.Name) Dim externalLogins = New List(Of ExternalLogin)() For Each account As OAuthAccount In accounts Dim clientData = OAuthWebSecurity.GetOAuthClientData(account.Provider) externalLogins.Add(New ExternalLogin With { _ .Provider = account.Provider, _ .ProviderDisplayName = clientData.DisplayName, _ .ProviderUserId = account.ProviderUserId _ }) Next ViewData("ShowRemoveButton") = externalLogins.Count > 1 OrElse OAuthWebSecurity.HasLocalAccount(WebSecurity.GetUserId(User.Identity.Name)) Return PartialView("_RemoveExternalLoginsPartial", externalLogins) End Function #Region "Helpers" Private Function RedirectToLocal(ByVal returnUrl As String) As ActionResult If Url.IsLocalUrl(returnUrl) Then Return Redirect(returnUrl) Else Return RedirectToAction("Index", "Home") End If End Function Public Enum ManageMessageId ChangePasswordSuccess SetPasswordSuccess RemoveLoginSuccess End Enum Friend Class ExternalLoginResult Inherits System.Web.Mvc.ActionResult Private ReadOnly _provider As String Private ReadOnly _returnUrl As String Public Sub New(ByVal provider As String, ByVal returnUrl As String) _provider = provider _returnUrl = returnUrl End Sub Public ReadOnly Property Provider() As String Get Return _provider End Get End Property Public ReadOnly Property ReturnUrl() As String Get Return _returnUrl End Get End Property Public Overrides Sub ExecuteResult(ByVal context As ControllerContext) OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl) End Sub End Class Public Function ErrorCodeToString(ByVal createStatus As MembershipCreateStatus) As String ' See http://go.microsoft.com/fwlink/?LinkID=177550 for ' a full list of status codes. Select Case createStatus Case MembershipCreateStatus.DuplicateUserName Return "User name already exists. Please enter a different user name." Case MembershipCreateStatus.DuplicateEmail Return "A user name for that e-mail address already exists. Please enter a different e-mail address." Case MembershipCreateStatus.InvalidPassword Return "The password provided is invalid. Please enter a valid password value." Case MembershipCreateStatus.InvalidEmail Return "The e-mail address provided is invalid. Please check the value and try again." Case MembershipCreateStatus.InvalidAnswer Return "The password retrieval answer provided is invalid. Please check the value and try again." Case MembershipCreateStatus.InvalidQuestion Return "The password retrieval question provided is invalid. Please check the value and try again." Case MembershipCreateStatus.InvalidUserName Return "The user name provided is invalid. Please check the value and try again." Case MembershipCreateStatus.ProviderError Return "The authentication provider returned an error. Please verify your entry and try again. If the problem persists, please contact your system administrator." Case MembershipCreateStatus.UserRejected Return "The user creation request has been canceled. Please verify your entry and try again. If the problem persists, please contact your system administrator." Case Else Return "An unknown error occurred. Please verify your entry and try again. If the problem persists, please contact your system administrator." End Select End Function #End Region End Class
I Have the DB Defined What im having an issue with is Referencing the Fileupload Control so i may create a function to parse the image into a byte and add it to the sql query for inserting it into the db. I Cant seem to figure out how to reference it considering
it always shows as Fileupload. and when trying to reference it under model.Fileupload1 it is not shown as a valid object. Any Help would be apprciated.