2

I've been trying to put a stored procedure in the website that I'm working on right now, I'm using ASP.NET MVC. So I decided to create a class named: RegisterRepository.cs, under the Repository folder but whenever I tried to send a registration form I always get this localhost refused to connect error. I've already check the connection strings but I can't see the problem. I hope someone can help me. Thank you.

This is my RegisterRepository class:

public class RegisterRepository
{
    private SqlConnection con;
    //To Handle connection related activities
    private void connection()
    {
        string constr = ConfigurationManager.ConnectionStrings["DefaultConnection"].ToString();
        con = new SqlConnection(constr);

    }


    public bool Register(TalentInfo model)
    {
        connection();

        try
        {
            SqlCommand com = new SqlCommand("SP_INSERT_TALENT_INFO", con);
            com.CommandType = CommandType.StoredProcedure;
            com.Parameters.AddWithValue("@Talent_Name", model.Talent_Name);
            com.Parameters.AddWithValue("@Talent_Email", model.Talent_Email);
            com.Parameters.AddWithValue("@Talent_SelfPromotion", model.Talent_SelfPromotion);
            con.Open();
            int i = com.ExecuteNonQuery();
            con.Close();
            if (i >= 1)
            {
                return true;
            }
            else
            {

                return false;
            }


        }

        catch
        {
            return Register(model);
        }
        finally
        {
            con.Close();
        }

    }


}

And this is my Web.config:

<?xml version="1.0" encoding="utf-8"?>
<!--
  For more information on how to configure your ASP.NET application, please visit
  http://go.microsoft.com/fwlink/?LinkId=301880
  -->
<configuration>
  <configSections>
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
  </configSections>
  <connectionStrings>
    <add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Yes-20160608102601.mdf;Initial Catalog=aspnet-Yes-20160608102601;Integrated Security=True" providerName="System.Data.SqlClient" />
    <add name="TalentInfoEntities" connectionString="metadata=res://*/Models.TalentInfo.csdl|res://*/Models.TalentInfo.ssdl|res://*/Models.TalentInfo.msl;provider=System.Data.SqlClient;provider connection string=&quot;data source=GAYLE-PC\SQLEXPRESS;initial catalog=Yes.org;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework&quot;" providerName="System.Data.EntityClient" />
  </connectionStrings>
  <appSettings>
    <add key="webpages:Version" value="3.0.0.0" />
    <add key="webpages:Enabled" value="false" />
    <add key="ClientValidationEnabled" value="true" />
    <add key="UnobtrusiveJavaScriptEnabled" value="true" />
    <add key="EmailPassword" value="your_password" />
    <add key="reCaptchaPublicKey" value="Your site key" />
    <add key="reCaptchaPrivateKey" value="Your secret key" />
  </appSettings>
  <system.web>
    <authentication mode="None" />
    <compilation debug="true" targetFramework="4.5" />
    <httpRuntime maxRequestLength="102400" targetFramework="4.5" />
  </system.web>
  <system.webServer>
    <modules>
      <remove name="FormsAuthentication" />
    </modules>
    <security>
      <requestFiltering>
        <requestLimits maxAllowedContentLength="104857600" />
      </requestFiltering>
    </security>
  </system.webServer>
  <runtime>
    <assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
        <bindingRedirect oldVersion="0.0.0.0-6.0.0.0" newVersion="6.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Helpers" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Mvc" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-5.2.2.0" newVersion="5.2.2.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.Optimization" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="System.Web.WebPages" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
      </dependentAssembly>
      <dependentAssembly>
        <assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
        <bindingRedirect oldVersion="1.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
      </dependentAssembly>
    </assemblyBinding>
  </runtime>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

My Controller:

public class HomeController : Controller
{
    private TalentInfoEntities db = new TalentInfoEntities();

    public ActionResult Index()
    {
        return View();
    }

    public ActionResult Register()
    {
        return View();
    }

    [HttpPost]
    [ValidateAntiForgeryToken]
    public async Task<ActionResult> Register(TalentInfo model, IEnumerable<HttpPostedFileBase> files)
    {
        if (ModelState.IsValid)
        {

            RegisterRepository regRepo = new RegisterRepository();

            if (regRepo.Register(model))
            {
                List<string> paths = new List<string>();

                foreach (var file in files)
                {
                    if (file.ContentLength > 0)
                    {
                        var fileName = Path.GetFileName(file.FileName);
                        var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
                        file.SaveAs(path);
                        paths.Add(path);
                    }
                }

                var message = new MailMessage();
                foreach (var path in paths)
                {
                    var fileInfo = new FileInfo(path);
                    var memoryStream = new MemoryStream();
                    using (var stream = fileInfo.OpenRead())
                    {
                        stream.CopyTo(memoryStream);
                    }
                    memoryStream.Position = 0;
                    string fileName = fileInfo.Name;
                    message.Attachments.Add(new Attachment(memoryStream, fileName));
                }

                //Rest of business logic here
                string EncodedResponse = Request.Form["g-Recaptcha-Response"];
                bool IsCaptchaValid = (ReCaptcha.Validate(EncodedResponse) == "True" ? true : false);
                if (IsCaptchaValid)
                {

                    var body = "<p><b>Email From:</b> {0} ({1})</p><p><b>Message:<b></p><p>{2}</p>";
                    message.To.Add(new MailAddress("***"));  // replace with valid value 
                    message.From = new MailAddress("***");  // replace with valid value
                    message.Subject = "Yes.org (REGISTRATION)";
                    message.Body = string.Format(body, model.Talent_Name, model.Talent_Email, model.Talent_SelfPromotion);
                    message.IsBodyHtml = true;
                    using (var smtp = new SmtpClient())
                    {
                        var credential = new NetworkCredential
                        {
                            UserName = "***",  // replace with valid value
                            Password = "***"  // replace with valid value
                        };
                        smtp.Credentials = credential;
                        smtp.Host = "smtp.gmail.com";
                        smtp.Port = 587;
                        smtp.EnableSsl = true;
                        smtp.SendCompleted += (s, e) =>
                        {
                            //delete attached files
                            foreach (var path in paths)
                                System.IO.File.Delete(path);
                        };
                        await smtp.SendMailAsync(message);
                        ViewBag.Message = "Your message has been sent!";

                        ModelState.Clear();
                        return View("Register");
                    }
                }
                else
                {
                    TempData["recaptcha"] = "Please verify that you are not a robot!";
                }

            } return View(model);

        }

        else
        {
            return View(model);
        }
    }



}
5
  • What controller are you hitting? Does your Index page load? Commented Jun 29, 2016 at 2:30
  • @Larry I just add my controller Sir. :) Yes, It's loading. But when I'm trying to send the registration form I always get this: localhost refused to connect. Commented Jun 29, 2016 at 2:33
  • Which DB has your stored proc, DefaultConnection or TalentInfoEntities? Your connection is pointing to the former. Try ConnectionStrings["TalentInfoEntities"] Commented Jun 29, 2016 at 2:35
  • @SteveGreene It's in the TalentInfoEntities. I tried the ConnectionStrings["TalentInfoEntities"] Sir, then I got this error: System.ArgumentException: Keyword not supported: 'metadata' '{ string constr = ConfigurationManager.ConnectionStrings["TalentInfoEntities"].ToString(); con = new SqlConnection(constr) }' Commented Jun 29, 2016 at 2:47
  • Yes, you don't need the metadata for a SQL connection. Remove the garbage from that connection string: metadata=res://*/Models.TalentInfo.csdl|res://*/Models.TalentInfo.ssdl|res://*/Models.TalentInfo.msl; Commented Jun 29, 2016 at 2:48

1 Answer 1

1

Try changing your connection string to something like this:

<add name="TalentInfoEntities" connectionString="Data Source=GAYLE-PC\SQLEXPRESS;Initial Catalog=Yes.org;Integrated Security=SSPI; MultipleActiveResultSets=true" providerName="System.Data.SqlClient" />
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.