0

I'm working in asp.net with c# and I decided to build a pop-up messaging module. I have done this on previous projects; however, I've never used it on a site that was also utilizing the Identity Framework or placed in my master page. I am also fairly new to C#.

The messenger appears to be working fine. However, now any kind of "submit" or "send" function found on the master page will not work properly. For example, if I try to log in as an admin, I will get my windows error messages for the field validation on the messenger. I tried taking out the RequiredFieldValidators, I was still unable to log in, instead it tried to send a message.

I then tried moving the module into a usercontrol and running it that way, still no luck. I had considered building a new masterpage for the log in page, that way I could remove the "contact" from the navigation on that page, thus eliminating the issue . However, I would prefer not to have to do this. I am sure there is a simple solution to correcting this, and my lack of experience with c# is not helping much.

Here is part of the navigation on my Site.Master, just to give an idea about what I'm doing:

    <li><a runat="server" href="#" data-toggle="modal" data-target=".pop-up-1">Contact</a></li>
                </ul>
                <asp:LoginView runat="server" ViewStateMode="Disabled">
                    <AnonymousTemplate>
                        <ul class="nav navbar-nav navbar-right">
                            <li><a runat="server" href="~/Account/Login" style="color:#f46de6">Admin</a></li>
                            <li><asp:HyperLink ID="PayPalViewCart" runat="server" NavigateUrl=<%# Link.ToPayPalViewCart() %> style="color:#f46de6">View Cart</asp:HyperLink></li>
                        </ul>
                    </AnonymousTemplate>
                    <LoggedInTemplate>
                        <ul class="nav navbar-nav navbar-right">
                            <li><a runat="server" href="~/Account/Manage" title="Manage your account" style="color:#f46de6" >Hello, Admin</a></li>
                            <li>
                                <asp:LoginStatus runat="server" LogoutAction="Redirect" LogoutText="Log off" LogoutPageUrl="~/" OnLoggingOut="Unnamed_LoggingOut" />
                            </li>
                        </ul>
                    </LoggedInTemplate>
                </asp:LoginView>
            </div>
        </div>
    </div>
    <uc1:popup1 runat="server" id="popup1" />
    <div class="container body-content">

Now here is the code behind on this page, site.Master.cs:

    public partial class SiteMaster : MasterPage
{
    private const string AntiXsrfTokenKey = "__AntiXsrfToken";
    private const string AntiXsrfUserNameKey = "__AntiXsrfUserName";
    private string _antiXsrfTokenValue;

    protected void Page_Init(object sender, EventArgs e)
    {
        // The code below helps to protect against XSRF attacks
        var requestCookie = Request.Cookies[AntiXsrfTokenKey];
        Guid requestCookieGuidValue;
        if (requestCookie != null && Guid.TryParse(requestCookie.Value, out requestCookieGuidValue))
        {
            // Use the Anti-XSRF token from the cookie
            _antiXsrfTokenValue = requestCookie.Value;
            Page.ViewStateUserKey = _antiXsrfTokenValue;
        }
        else
        {
            // Generate a new Anti-XSRF token and save to the cookie
            _antiXsrfTokenValue = Guid.NewGuid().ToString("N");
            Page.ViewStateUserKey = _antiXsrfTokenValue;

            var responseCookie = new HttpCookie(AntiXsrfTokenKey)
            {
                HttpOnly = true,
                Value = _antiXsrfTokenValue
            };
            if (FormsAuthentication.RequireSSL && Request.IsSecureConnection)
            {
                responseCookie.Secure = true;
            }
            Response.Cookies.Set(responseCookie);
        }

        Page.PreLoad += master_Page_PreLoad;
    }

    protected void master_Page_PreLoad(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            // Set Anti-XSRF token
            ViewState[AntiXsrfTokenKey] = Page.ViewStateUserKey;
            ViewState[AntiXsrfUserNameKey] = Context.User.Identity.Name ?? String.Empty;
        }
        else
        {
            // Validate the Anti-XSRF token
            if ((string)ViewState[AntiXsrfTokenKey] != _antiXsrfTokenValue
                || (string)ViewState[AntiXsrfUserNameKey] != (Context.User.Identity.Name ?? String.Empty))
            {
                throw new InvalidOperationException("Validation of Anti-XSRF token failed.");
            }
        }
    }

    protected void Page_Load(object sender, EventArgs e)
    {

    }

    protected void Unnamed_LoggingOut(object sender, LoginCancelEventArgs e)
    {
        Context.GetOwinContext().Authentication.SignOut();
    }
}

}

This is my user control for the pop-up:

    <div class="modal fade pop-up-1" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel-1" aria-hidden="true">
            <div class="modal-dialog modal-lg">
              <div class="modal-content">
                <div class="modal-header">
                  <button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
                  <h4 class="modal-title" id="myLargeModalLabel-3">Contact Us</h4>
                </div>
                <div class="modal-body">
                <table style="max-width:100%; height: auto; padding:20px">
                    <tr>
                        <td colspan="3">
                            <div style="margin:15px 0 20px 0"> Please, use the form below to contact us regarding any questions or concerns you might have:</div>
                        </td>
                    </tr>
                    <tr style="margin-bottom:10px">
                        <td style="width:150px; font-size:14px">Name:</td>
                        <td style="vertical-align:top; width:300px">
                            <asp:TextBox ID="txtName" runat="server" Width="300px" style="margin:10px"/>
                        </td>
                        <td>
                            <!--<asp:RequiredFieldValidator ID="rfvName" runat="server"
                                ControlToValidate="txtName" Display="Dynamic"
                                ErrorMessage="Name">*</asp:RequiredFieldValidator>-->
                        </td>
                    </tr>
                    <tr style="margin-bottom: 10px ">
                        <td style="font-size: 14px">Organization (optional):</td>
                        <td><asp:TextBox ID="txtOrganization" runat="server" Width="300px" style="margin:10px" /></td>
                        <td>
                        </td>
                    </tr>
                    <tr style="margin-bottom:10px">
                        <td style="font-size:14px"> Phone (optional):</td>
                        <td><asp:TextBox ID="txtPhone" runat="server" Width="300px" style="margin:10px" /></td>
                        <td>
                        </td>
                    </tr>
                    <tr style="margin-bottom:10px">
                        <td style="font-size:14px">Email:</td>
                        <td><asp:TextBox ID="txtEmail" runat="server" Width="300px" style="margin:10px" /></td>
                        <td>
                            <!--<asp:RequiredFieldValidator ID="rfvEmail" runat="server"
                                ControlToValidate="txtEmail" Display="Dynamic"
                                ErrorMessage="Email">*</asp:RequiredFieldValidator>-->
                        </td>
                    </tr>
                    <tr>
                        <td style="font-size:14px"> Message:</td>
                        <td><asp:TextBox ID="txtRequest" runat="server" TextMode="MultiLine" Width="300px" Height="60px" style="margin:10px" /></td>
                        <td>
                            <!--<asp:RequiredFieldValidator ID="rfvRequest" runat="server"
                                ControlToValidate="txtRequest" Display="Dynamic"
                                ErrorMessage="Message">*</asp:RequiredFieldValidator>-->
                        </td>
                    </tr>
                    <tr>
                        <td colspan="3">
                            <asp:Button ID="btnSubmit" runat="server" Text="Submit" OnClick="SendMail" Width="60px" />&nbsp;
                            <asp:Button ID="btnReset" runat="server" Text="Reset" OnClick="ResetEmail" Width="60px" CausesValidation="false" />
                                <!--<asp:ValidationSummary ID="ValidationSummary1" runat="server" HeaderText="Please fill out the required fields:" ShowMessageBox="true" ShowSummary="false" />-->
                        </td>
                    </tr>
                </table>
                </div>
              </div><!-- /.modal-content -->
            </div><!-- /.modal-dialog -->
          </div><!-- /.modal Contact Table-->

And last but not least, this is the code behind on the user control, and yes I know I can do this using my web.config also, and I tried that too with the same result:

     public partial class pop_up_1 : System.Web.UI.UserControl
{
    private bool IsValid;

    protected void Page_Load(object sender, EventArgs e)
    {
    }
    protected void SendMail(object sender, EventArgs e)
    {
        if (IsValid)
        {
            //create a new email message
            MailMessage mail = new MailMessage();
            mail.From = new MailAddress("");
            mail.To.Add("");
            mail.Subject = "Information Request";
            mail.IsBodyHtml = true;
            mail.Body = "Name:" + this.txtName.Text + "<br />";
            mail.Body += "Organization:" + txtOrganization.Text + "<br />";
            mail.Body += "Phone:" + txtPhone.Text + "<br />";
            mail.Body += "Email:" + txtEmail.Text + "<br />";
            mail.Body += "Request or Question:" + txtRequest.Text + "<br />";


            //Create SMTP client
            SmtpClient smtp = new SmtpClient();
            smtp.Host = "";


            //Send the email
            smtp.Send(mail);

            //Define the name and type of the client script on the page.
            String csName = "SuccessNotificationScript";
            Type csType = this.GetType();

            //Get a ClientScriptManager reference from the Page class.
            ClientScriptManager cs = Page.ClientScript;

            //Check to see if the client script is already registered.
            if (!cs.IsClientScriptBlockRegistered(csType, csName))
            {
                string csText = "<script language='javascript'>window.alert('Thank you for submitting your request');</script>";
                cs.RegisterClientScriptBlock(csType, csName, csText.ToString());
            }
            //Clear the form
            ClearForm();
        }
    }
    protected void ResetEmail(object sender, EventArgs e)
    {
        ClearForm();
    }

    protected void ClearForm()
    {
        txtName.Text = "";
        txtOrganization.Text = "";
        txtPhone.Text = "";
        txtEmail.Text = "";
        txtRequest.Text = "";
    }
}

}

Any suggestions or ideas, greatly appreciated. Thanks

here is the backend of my login page, I am using identity framework:

     public partial class Login : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        //RegisterHyperLink.NavigateUrl = "Register";
        // Enable this once you have account confirmation enabled for password reset functionality
        // ForgotPasswordHyperLink.NavigateUrl = "Forgot";
        //OpenAuthLogin.ReturnUrl = Request.QueryString["ReturnUrl"];
        var returnUrl = HttpUtility.UrlEncode(Request.QueryString["ReturnUrl"]);
        if (!String.IsNullOrEmpty(returnUrl))
        {
            //RegisterHyperLink.NavigateUrl += "?ReturnUrl=" + returnUrl;
        }
    }

    protected void LogIn(object sender, EventArgs e)
    {
        if (IsValid)
        {
            // Validate the user password
            var manager = Context.GetOwinContext().GetUserManager<ApplicationUserManager>();
            ApplicationUser user = manager.Find(Email.Text, Password.Text);
            if (user != null)
            {
                IdentityHelper.SignIn(manager, user, RememberMe.Checked);
                IdentityHelper.RedirectToReturnUrl(Request.QueryString["ReturnUrl"], Response);
            }
            else
            {
                FailureText.Text = "Invalid username or password.";
                ErrorMessage.Visible = true;
            }
        }
    }
}

}

Faron
  • 47
  • 1
  • 6
  • 1
    r u getting any errors or something. and in your C# Code i can see your mail.To.Add(""); is empty u should put your recipient email address there – Sundar Rajan Nov 17 '14 at 13:14
  • The same with smtp.Host = ""; You should insert "smtp.gmail.com" if you use gmail – Oleh Nov 17 '14 at 13:25
  • The same with smtp.Port !!! You should set it ! – Oleh Nov 17 '14 at 13:26
  • @SundarRajan No I am not receiving any errors in my code and I just deleted the private info out for the purpose of posting on this forum. It is sending mail just fine, the issue is that the user can not log in because it wants to send mail each time instead. – Faron Nov 17 '14 at 13:27
  • How to use smtp here http://stackoverflow.com/a/11700651/2703505 – Oleh Nov 17 '14 at 13:28
  • @user3731081 use FormsAuthentication.SetAuthCookie(email) and where is your login function in the code above – dazzling kumar Nov 17 '14 at 13:29
  • @user3731081 IMHO if u call the method on onclick event   it will call everytime only. better u can call one function put some condition what u need if that satisfies then call this method – Sundar Rajan Nov 17 '14 at 13:32
  • @Oleh you guys are running off topic here. The SMTP is operating just fine, my port is set in my web.config. the info is only deleted of this post for privacy reasons. My issue is that when you try to log in, the code keeps trying to send a message rather than logging in a user. I need a way to differentiate between the two submit functions, and yes the buttons and event handlers are named differently. So I don't understand why my smtp btn click is overriding login btn click – Faron Nov 17 '14 at 13:33
  • I've edited with my login page back code all though I can tell you my login fuctions work perfectly fine when I'm not trying to include the smtp send mail functions in the master page. – Faron Nov 17 '14 at 13:39

0 Answers0