localhost connection (ASP.NET MVC) - c#

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="data source=GAYLE-PC\SQLEXPRESS;initial catalog=Yes.org;integrated security=True;MultipleActiveResultSets=True;App=EntityFramework"" 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);
}
}
}

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" />

Related

Owin identity token authentication token endpoint responds with 404

I have been trying to add token based authorisation to my application using OWIN and asp.net identity and entity framework. However when I try to get my token through the token endpoint path I get a 404 response. My OWIN startup class:
[assembly: OwinStartup(typeof(Web.Startup))]
namespace Web
{
public class Startup
{
public void Configuration(IAppBuilder app)
{
ConfigureOAuth(app);
}
public void ConfigureOAuth(IAppBuilder app)
{
Console.WriteLine("owin");
app.CreatePerOwinContext<OwinAuthDbContext>(() => new OwinAuthDbContext());
app.CreatePerOwinContext<UserManager<IdentityUser>>(CreateManager);
app.UseCors(Microsoft.Owin.Cors.CorsOptions.AllowAll);
var provider = new MyAuthorizationServerProvider();
OAuthAuthorizationServerOptions option = new OAuthAuthorizationServerOptions
{
AllowInsecureHttp = false, //have also tried with true here
TokenEndpointPath = new PathString("/token"),
AccessTokenExpireTimeSpan = TimeSpan.FromDays(1),
Provider = provider
};
app.UseOAuthAuthorizationServer(option);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
HttpConfiguration config = new HttpConfiguration();
WebApiConfig.Register(config);
}
private static UserManager<IdentityUser> CreateManager(IdentityFactoryOptions<UserManager<IdentityUser>> options, IOwinContext context)
{
var userStore = new UserStore<IdentityUser>(context.Get<OwinAuthDbContext>());
var owinManager = new UserManager<IdentityUser>(userStore);
return owinManager;
}
}
}
As you can see the token should be available under "/token", but when i call https://localhost:44373/token I get a 404 regardless of me adding headers for username, password and token_type. My OAuthAuthorizationServerProvider class:
public class MyAuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override async Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
string clientId;
string clientSecret;
if (context.TryGetBasicCredentials(out clientId, out clientSecret))
{
// validate the client Id and secret against database or from configuration file.
context.Validated();
}
else
{
context.SetError("invalid_client", "Client credentials could not be retrieved from the Authorization header");
context.Rejected();
}
}
public override async Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
UserManager<IdentityUser> userManager = context.OwinContext.GetUserManager<UserManager<IdentityUser>>();
IdentityUser user;
try
{
user = await userManager.FindAsync(context.UserName, context.Password);
}
catch
{
// Could not retrieve the user due to error.
context.SetError("server_error");
context.Rejected();
return;
}
if (user != null)
{
ClaimsIdentity identity = await userManager.CreateIdentityAsync(
user,
DefaultAuthenticationTypes.ExternalBearer);
context.Validated(identity);
}
else
{
context.SetError("invalid_grant", "Invalid User Id or password'");
context.Rejected();
}
}
}
I hope you can help.
Edit:
web.config dependent assembly:
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" culture="neutral" publicKeyToken="30ad4fe6b2a6aeed" />
<bindingRedirect oldVersion="0.0.0.0-10.0.0.0" newVersion="10.0.0.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="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.6.5135.21930" newVersion="1.6.5135.21930" />
</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.WebPages" 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.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.5.0.0" newVersion="4.5.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Web.Cors" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.1.0.0" newVersion="3.1.0.0" />
</dependentAssembly>
Please make sure you are passing in the grant_type : password too in your body and use POST to sent to http://localhost:XXXXX/token
username : userXX
password : XXXX
grant_type : password
ps : I seeing that you are missing the app.UseWebApi(config); in your Configuration function? Please make sure it is called after ConfigureOAuth(app);
Example:
public void Configuration(IAppBuilder app)
{
HttpConfiguration config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
Please try this way:
public void Configuration(IAppBuilder app)
{
var config = new HttpConfiguration();
ConfigureOAuth(app);
WebApiConfig.Register(config);
app.UseWebApi(config);
}
private void ConfigureOAuth(IAppBuilder app)
{
OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
{
AllowInsecureHttp = true,
TokenEndpointPath = new PathString("/oauth/Token"),
AccessTokenExpireTimeSpan = TimeSpan.FromMinutes(30),
Provider = new AuthorizationServerProvider()
};
//Token Generation
app.UseOAuthAuthorizationServer(OAuthServerOptions);
app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
}
AuthorizationServerProvider.cs
public class AuthorizationServerProvider : OAuthAuthorizationServerProvider
{
public override Task ValidateClientAuthentication(OAuthValidateClientAuthenticationContext context)
{
context.Validated();
return base.ValidateClientAuthentication(context);
}
public override Task GrantResourceOwnerCredentials(OAuthGrantResourceOwnerCredentialsContext context)
{
//Add parameters to token
ClaimsIdentity oAuthIdentity = new ClaimsIdentity(context.Options.AuthenticationType);
oAuthIdentity.AddClaim(new Claim(ClaimTypes.Name, context.UserName));
context.Validated(oAuthIdentity);
return base.GrantResourceOwnerCredentials(context);
}
}
Your startup class is unreachable , Try to change the value of AutomaticAppStartup in Web.config to true as following :
<configuration>
<appSettings>
.
.
<add key="owin:AutomaticAppStartup" value="true" />
<appSettings>
.
.
<configuration>

HttpStatus Ok(200) but I see a white page - Aspnet Mvc Razor

I'm developing the Asp.Net with RazorEngine. Project upload to server and run,
but giving statusCode 200(ok) and I see white page.
Note: I aslo tried two different servers.
Site Url : rest.gelecekten.net
Web.Config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<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" />-->
</appSettings>
<connectionStrings>
<add name="connectionString" connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=Restaurant;Integrated Security=False;User ID=sa;Password=123;MultipleActiveResultSets=True" providerName="System.Data.SqlClient" />
<add name="MongoServer" connectionString="mongodb://localhost:27017/Restaurant" />
</connectionStrings>
<system.web>
<globalization enableClientBasedCulture="false" uiCulture="auto" culture="auto" />
<compilation debug="true" optimizeCompilations="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" enableVersionHeader="false" />
<trace enabled="false" />
</system.web>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<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.WebPages" 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="0.0.0.0-5.2.3.0" newVersion="5.2.3.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Autofac" publicKeyToken="17863af14b0044da" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.2.1.0" newVersion="4.2.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Newtonsoft.Json" publicKeyToken="30ad4fe6b2a6aeed" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-9.0.0.0" newVersion="9.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="System.Runtime.InteropServices.RuntimeInformation" publicKeyToken="b03f5f7f11d50a3a" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-4.0.1.0" newVersion="4.0.1.0" />
</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>
<system.webServer>
<staticContent>
<clientCache cacheControlMode="UseMaxAge" cacheControlMaxAge="24.00:00:00" />
<remove fileExtension=".json" />
<mimeMap fileExtension=".json" mimeType="application/json" />
<remove fileExtension=".otf" />
<remove fileExtension=".woff" />
<remove fileExtension=".woff2" />
<mimeMap fileExtension=".otf" mimeType="application/x-font-opentype" />
<mimeMap fileExtension=".woff" mimeType="application/font-woff" />
<mimeMap fileExtension=".woff2" mimeType="application/font-woff2" />
</staticContent>
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
<remove name="DefaultAuthentication" />
<!--<remove name="OutputCache" />-->
<remove name="AnonymousIdentification" />
<remove name="RoleManager" />
</modules>
<!--<httpProtocol>
<customHeaders>
<remove name="X-Powered-By" />
</customHeaders>
</httpProtocol>-->
<urlCompression doDynamicCompression="true" doStaticCompression="true" dynamicCompressionBeforeCache="true" />
</system.webServer>
</configuration>
Global.asax
protected void InitializeApplication()
{
//Initialize dependency injection
var containerBuilder = new ContainerBuilder();
containerBuilder.RegisterControllers(typeof(MvcApplication).Assembly);
containerBuilder.RegisterModule(new AutofacWebTypesModule());
Service.DependencyRegister.Register(containerBuilder);
DependencyRegister.Register(containerBuilder);
var container = containerBuilder.Build();
DependencyResolver.SetResolver(new AutofacDependencyResolver(container));
Engine.SetContainer(container);
//View Engine Optimization
ViewEngines.Engines.Clear();
ViewEngines.Engines.Add(new ViewEngine());
var settingService = Engine.Resolve<ISettingService>();
//Start system task
if (settingService.GetSetting("system.task.enable").BoolValue)
{
TaskManager.Instance.Initialize();
TaskManager.Instance.Start();
}
//Set system setting
AntiForgeryConfig.RequireSsl = settingService.GetSetting("system.usessl").BoolValue;
SecurityHelper.EncryptKey = settingService.GetSetting("system.default.encryptionkey").Value;
//Initialize Notification
if (settingService.GetSetting("system.manage.notification").BoolValue)
InitializeNotification();
Singleton<IMetaBuilder>.Instance = new MetaBuilder();
}
private void InitializeNotification()
{
/*string connectionString = WebHelper.ConnectionString("connectionString");
SqlDependency.Start(connectionString);
NotifyEngine engine = new NotifyEngine(connectionString);
string query = "select Field1, Field2, Field3, Field4 from [dbo].Test";
engine.OnNotifyChange += delegate (SqlNotificationInfo info)
{
var testService = Engine.Resolve<ITestService>();
NotificationHub.showNotify(testService.GetLast().ToJsonString());
};
engine.RegisterSqlDependency(query, SqlNotificationInfo.Update, SqlNotificationInfo.Insert);*/
}
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
RouteConfig.RegisterRoutes(RouteTable.Routes);
InitializeApplication();
}
protected void Application_End()
{
SqlDependency.Stop(WebHelper.ConnectionString("connectionString"));
}
protected void Session_Start(object sender, EventArgs e)
{
//Request is Search Engine(GoogleBot, MsnBot vs.)
if (HttpContext.Current.Request.Browser.Crawler)
{
HttpContext.Current.Response.Redirect("http://google.com", true);
return;
}
if (CookieHelper.Exists(SessionConstant.Location))
{
var country = CookieHelper.Get(SessionConstant.Location).FromBase64().FromJsonString<Country>();
WebHelper.SetCulture(country);
}
else
{
var location = Engine.Resolve<IHelperService>().FindLocation(WebHelper.IsLocal, WebHelper.IpAddress);
var country = Engine.Resolve<ICommonService>().GetCountryByCode(location.CountryCode);
WebHelper.SetCulture(country);
CookieHelper.Set(SessionConstant.Location, country.ToJsonString().ToBase64(), 1);
}
}
protected void Session_End(object sender, EventArgs e)
{
WebHelper.ClearSession();
}
protected void Application_BeginRequest(object sender, EventArgs e)
{
if (WebHelper.IsStaticResource(this.Request))
return;
var settingService = Engine.Resolve<ISettingService>();
if (settingService.GetSetting("system.usessl").BoolValue &&
!WebHelper.IsSecureConnection &&
WebHelper.GetUri.Scheme == Uri.UriSchemeHttp)
{
//Redirect to https
var scheme = Uri.UriSchemeHttps + "://";
var authority = WebHelper.GetUri.Authority;
var url = HttpContext.Current.Request.RawUrl;
var redirectTo = scheme + authority + url;
HttpContext.Current.Response.Redirect(redirectTo);
}
}
protected void Application_EndRequest(object sender, EventArgs e)
{
}
protected void Application_AuthenticateRequest(object sender, EventArgs e)
{
}
protected void Application_Error(object sender, EventArgs e)
{
if (WebHelper.IsLocal)
return;
var exception = Server.GetLastError();
bool isAjaxRequest = new HttpRequestWrapper(this.Request).IsAjaxRequest();
if (!WebHelper.IsStaticResource(Request) && !isAjaxRequest && exception != null)
{
Response.Clear();
Server.ClearError();
Response.TrySkipIisCustomErrors = true;
//Log Error
var error = new SystemError()
{
RestaurantId = WebHelper.CurrentRestaurant.Id,
ErrorDate = DateTime.Now,
ErrorType = ErrorType.Warning,
ErrorMessage = exception.ToString(),
ErrorLocation = WebHelper.GetCurrentUrl(true),
ErrorStack = exception.StackTrace.ToString()
};
var logService = Engine.Resolve<ILogService>();
logService.Error(error);
Context.Response.Redirect("/error", true);
}
}
Views/web.config
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<system.web.webPages.razor>
<host factoryType="System.Web.Mvc.MvcWebRazorHostFactory, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<!--<pages pageBaseType="System.Web.Mvc.WebViewPage">-->
<pages pageBaseType="Restaurant.Framework.Infrastructure.WebViewPage">
<namespaces>
<clear />
<add namespace="System.Web.Mvc" />
<add namespace="System.Web.Mvc.Ajax" />
<add namespace="System.Web.Mvc.Html" />
<add namespace="System.Web.Routing" />
<add namespace="Restaurant.Manage" />
<add namespace="Restaurant.Manage.Models" />
<add namespace="Restaurant.Framework" />
<add namespace="Restaurant.Framework.Paging" />
<add namespace="Restaurant.Framework.Helpers" />
<add namespace="Restaurant.Core.Helpers" />
<add namespace="Restaurant.Core.Enums" />
<add namespace="Kendo.Mvc.UI" />
</namespaces>
</pages>
</system.web.webPages.razor>
<appSettings>
<add key="webpages:Enabled" value="false" />
</appSettings>
<system.web>
<httpHandlers>
<add path="*" verb="*" type="System.Web.HttpNotFoundHandler" />
</httpHandlers>
<pages validateRequest="false" pageParserFilterType="System.Web.Mvc.ViewTypeParserFilter, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" pageBaseType="System.Web.Mvc.ViewPage, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" userControlBaseType="System.Web.Mvc.ViewUserControl, System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<controls>
<add assembly="System.Web.Mvc, Version=5.2.3.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" namespace="System.Web.Mvc" tagPrefix="mvc" />
</controls>
</pages>
</system.web>
<system.webServer>
<validation validateIntegratedModeConfiguration="false" />
<handlers>
<remove name="BlockViewHandler" />
<add name="BlockViewHandler" path="*" verb="*" preCondition="integratedMode" type="System.Web.HttpNotFoundHandler" />
</handlers>
</system.webServer>
</configuration>
RouteConfig.cs
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
name: "Error",
url: "Error",
defaults: new { controller = "Error", action = "Index" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "NotFound",
url: "NotFound",
defaults: new { controller = "Error", action = "NotFound" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "AccessDenied",
url: "AccessDenied",
defaults: new { controller = "Error", action = "AccessDenied" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "SiteNotAvailable",
url: "SiteNotAvailable",
defaults: new { controller = "Error", action = "SiteNotAvailable" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "Notification",
url: "Notification",
defaults: new { controller = "Home", action = "Notification" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "Support",
url: "Support",
defaults: new { controller = "Home", action = "Support" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "About",
url: "About",
defaults: new { controller = "Home", action = "About" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "Contact",
url: "Contact",
defaults: new { controller = "Home", action = "Contact" },
namespaces: new[] { "Restaurant.Manage.Controllers" });
routes.MapRoute(
name: "Default",
url: "{controller}/{action}/{id}",
defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional },
namespaces: new[] { "Restaurant.Manage.Controllers" });
}

Why SQL Exception?

I'm working on this asp.net webservice using MVC5, C# to manage products, on Windows 10, using Visual Studio 2015 Community.
When I added the database connection, and ran it from index.cshtml to see the products/index page, but Visual Studio gave me this error.
SQL Exception was unhandled by user code. An exception of type
'System.Data.SqlClient.SqlException' occurred in EntityFramework.dll
but was not handled in user code
Additional information: A network-related or instance-specific error
occurred while establishing a connection to SQL Server. The server was
not found or was not accessible. Verify that the instance name is
correct and that SQL Server is configured to allow remote connections.
(provider: Named Pipes Provider, error: 40 - Could not open a
connection to SQL Server)
I'm a beginner so I researched as much as I could, and I don't see my error, how can I fix it?
EDIT: Could the error be that I don't have phpMyAdmin installed for MySQL?
II EDIT: I just realized that this new machine doesnt have my old configuration, I will install MySQL and report back. Thanks.
Thanks!
This is my Product class (model):
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Web;
namespace MVCStart.Models
{
public class Product
{
[Key]
public int ID { get; set; }
public string Description { get; set; }
public decimal Price { get; set; }
public DateTime LastBuy { get; set; }
public float Stock { get; set; }
}
}
This is my controller:
using MVCStart.Context;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace MVCStart.Controllers
{
public class ProductController : Controller
{
private StoreContext db = new StoreContext();
// GET: Product
public ActionResult Index()
{
return View(db.Products.ToList());
}
// GET: Product/Details/5
public ActionResult Details(int id)
{
return View();
}
// GET: Product/Create
public ActionResult Create()
{
return View();
}
// POST: Product/Create
[HttpPost]
public ActionResult Create(FormCollection collection)
{
try
{
// TODO: Add insert logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Product/Edit/5
public ActionResult Edit(int id)
{
return View();
}
// POST: Product/Edit/5
[HttpPost]
public ActionResult Edit(int id, FormCollection collection)
{
try
{
// TODO: Add update logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
// GET: Product/Delete/5
public ActionResult Delete(int id)
{
return View();
}
// POST: Product/Delete/5
[HttpPost]
public ActionResult Delete(int id, FormCollection collection)
{
try
{
// TODO: Add delete logic here
return RedirectToAction("Index");
}
catch
{
return View();
}
}
}
}
This is my StoreContext for database:
using MVCStart.Models;
using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Web;
namespace MVCStart.Context
{
public class StoreContext: DbContext
{
public DbSet<Product> Products { get; set; }
}
}
This is my view with html:
#model IEnumerable<MVCStart.Models.Product>
#{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
#Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
#Html.DisplayNameFor(model => model.Description)
</th>
<th>
#Html.DisplayNameFor(model => model.Price)
</th>
<th>
#Html.DisplayNameFor(model => model.LastBuy)
</th>
<th>
#Html.DisplayNameFor(model => model.Stock)
</th>
<th></th>
</tr>
#foreach (var item in Model) {
<tr>
<td>
#Html.DisplayFor(modelItem => item.Description)
</td>
<td>
#Html.DisplayFor(modelItem => item.Price)
</td>
<td>
#Html.DisplayFor(modelItem => item.LastBuy)
</td>
<td>
#Html.DisplayFor(modelItem => item.Stock)
</td>
<td>
#Html.ActionLink("Edit", "Edit", new { id=item.ID }) |
#Html.ActionLink("Details", "Details", new { id=item.ID }) |
#Html.ActionLink("Delete", "Delete", new { id=item.ID })
</td>
</tr>
}
</table>
This is my webconfig with database settings:
<?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>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="StoreContext"
connectionString="Data Source=.;Initial Catalog=Market;Integrated Security=True"
providerName="System.Data.SqlClient" />
</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" />
</appSettings>
<system.web>
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5.2" />
<httpRuntime targetFramework="4.5.2" />
</system.web>
<system.webServer>
<modules>
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-3.0.1.0" newVersion="3.0.1.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.Optimization" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="1.0.0.0-1.1.0.0" newVersion="1.1.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</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.3.0" newVersion="5.2.3.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>
</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>
<system.codedom>
<compilers>
<compiler language="c#;cs;csharp" extension=".cs" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.CSharpCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:6 /nowarn:1659;1699;1701" />
<compiler language="vb;vbs;visualbasic;vbscript" extension=".vb" type="Microsoft.CodeDom.Providers.DotNetCompilerPlatform.VBCodeProvider, Microsoft.CodeDom.Providers.DotNetCompilerPlatform, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" warningLevel="4" compilerOptions="/langversion:14 /nowarn:41008 /define:_MYTYPE=\"Web\" /optionInfer+" />
</compilers>
</system.codedom>
</configuration>
Open Server Explorer from VS via View->Server Explorer.
Open Data Connections and Delete related connection (StoreContext ) .
Then Add a new connection via right click Data Connnections .

WCF service works local , on remote server returns 404 not found

Hi I was looking for a lot of similar questions and I did not find answer, please can you help me. My wcf service work fine on my local machine, on remote serve it gives me 404. 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=169433
-->
<configuration>
<configSections>
<sectionGroup name="system.web.webPages.razor" type="System.Web.WebPages.Razor.Configuration.RazorWebSectionGroup, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35">
<section name="host" type="System.Web.WebPages.Razor.Configuration.HostSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
<section name="pages" type="System.Web.WebPages.Razor.Configuration.RazorPagesSection, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" requirePermission="false" />
</sectionGroup>
</configSections>
<appSettings>
<add key="GoogleAnalytics:PropertyID" value="" />
<add key="webpages:Version" value="3.0" />
<add key="webpages:Enabled" value="true" />
<add key="vs:EnableBrowserLink" value="false" />
</appSettings>
<system.web>
<compilation debug="true" targetFramework="4.5.1" />
<httpRuntime targetFramework="4.5.1" />
<customErrors mode="Off"/>
<securityPolicy>
<trustLevel name="Full" policyFile="internal"/>
</securityPolicy>
</system.web>
<system.web.webPages.razor>
<host factoryType="System.Web.WebPages.Razor.WebRazorHostFactory, System.Web.WebPages.Razor, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35" />
<pages pageBaseType="System.Web.WebPages.WebPage">
<namespaces>
<add namespace="System.Web.Configuration" />
<add namespace="System.Web.Optimization" />
<add namespace="System.Web.Routing" />
</namespaces>
</pages>
</system.web.webPages.razor>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="WebGrease" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-2.0.2.0" newVersion="2.0.2.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Antlr3.Runtime" publicKeyToken="eb42632606e9261f" culture="neutral" />
<bindingRedirect oldVersion="0.0.0.0-3.5.0.2" newVersion="3.5.0.2" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<location path="crossdomain.xml">
<system.webServer>
<validation validateIntegratedModeConfiguration="false"/>
<modules runAllManagedModulesForAllRequests="true" />
</system.webServer>
</location>
<system.serviceModel>
<bindings>
<webHttpBinding>
<binding maxBufferPoolSize="2147483647" maxReceivedMessageSize="2147483647" maxBufferSize="2147483647" transferMode="Streamed"></binding>
</webHttpBinding>
</bindings>
<services>
<service behaviorConfiguration="ServiceBehaviour" name="App.RozankaWeb.Service.EmailService">
<endpoint address="http:/mydomain.com/Service/EmailService.svc" behaviorConfiguration="web" binding="webHttpBinding" contract="App.RozankaWeb.Service.IEmailService" />
</service>
</services>
<behaviors>
<endpointBehaviors>
<behavior name="web">
<webHttp />
</behavior>
</endpointBehaviors>
<serviceBehaviors>
<behavior name="ServiceBehaviour">
<serviceMetadata httpGetEnabled="true" />
<serviceDebug includeExceptionDetailInFaults="false" />
</behavior>
</serviceBehaviors>
</behaviors>
<protocolMapping>
<add binding="basicHttpsBinding" scheme="https" />
</protocolMapping>
<serviceHostingEnvironment aspNetCompatibilityEnabled="true" multipleSiteBindingsEnabled="true">
<serviceActivations>
<add relativeAddress="Service/EmailService.svc" service="App.RozankaWeb.Service.EmailService"/>
</serviceActivations>
</serviceHostingEnvironment>
</system.serviceModel>
</configuration>
This is my angular controller that calls service (Works local :))
$scope.sendEmail = function (Name, emailFrom, phoneNumber, bodyOrigin) {
var emailTo = 'mymail#gmail.com';
var emailToName = "my name";
var subject = 'My subject';
var isBodyHtml = false;
var body = bodyOrigin + " " + "Kontakt telefona: " + phoneNumber;
$http.post("/Service/EmailService.svc/SendEmail", {
emailFrom: emailFrom,
emailFromName: Name,
emailTo: emailTo,
emailToName: emailToName,
subject : subject,
body : body,
isBodyHtml: isBodyHtml,
}, { timeout: 60000 })
.success(function (response) {
$scope.array = "Email sent";
})
.error(function (data, status, headers, config) {
});
And this is my service
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Mail;
using System.Net.Security;
using System.Runtime.Serialization;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel;
using System.Text;
namespace App.RozankaWeb.Service
{
public class EmailService : IEmailService
{
public void SendEmail(PostEmail postEmail)
{
MailAddress from = new MailAddress(postEmail.emailFrom, postEmail.emailFromName);
MailAddress to = new MailAddress(postEmail.emailTo, postEmail.emailToName);
MailMessage message = new MailMessage(from, to);
message.Subject = postEmail.subject;
message.Body = postEmail.body;
SmtpClient client = new SmtpClient
{
Host = "smtp.mydomain.com",
Port = 587,
UseDefaultCredentials = false,
Credentials = new NetworkCredential("mycredential#.com", "mypassword"),
DeliveryMethod = SmtpDeliveryMethod.Network,
EnableSsl = true,
Timeout = 10000
};
Console.WriteLine("Sending an e-mail message to {0} and {1}.", to.DisplayName, message.Bcc.ToString());
try
{
ServicePointManager.ServerCertificateValidationCallback = delegate(object s, X509Certificate certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
return true;
};
client.Send(message);
}
catch (Exception ex)
{
Console.WriteLine("Exception caught in CreateBccTestMessage(): {0}",
ex.ToString());
}
}
}
public class PostEmail
{
public string emailTo;
public string emailToName;
public string subject;
public string body;
public string emailFrom;
public string emailFromName;
public bool isBodyHtml;
}
}
and my Interface
{
[ServiceContract]
public interface IEmailService
{
[OperationContract]
[WebInvoke(Method = "POST", UriTemplate = "SendEmail", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.Bare)]
void SendEmail(PostEmail postEmail);
}
}
I know this is a lot of code, but please take a look at and and give me a help, I appreciate any help :)

"A network-related or instance-specific error occurred while establishing a connection to SQL Server."

I am currently stuck in a situation in which I don't know how to go about it. For the website I am working on, if I don't have a user logged in, I can access pages that require use of DB information. When I do log in though, I get the error specified in the title.
My database and website are being hosted through Azure cloud service using the free trial and I also have Role Manager enabled in the web.config (Disabling it gets rid of the error but I need it enabled for role checking). Everything works fine when I am in the localhost, so its only when my website is deployed that I am having issues.
I am new to ASP.NET, so I am still lost on some of the fundamentals of how it works.
**EDIT: ** here is my web.config file using the added code from timeiscoffee
<?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>
<!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
<section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
</configSections>
<connectionStrings>
<add name="DefaultConnection" connectionString="Data Source=(LocalDb)\v11.0;AttachDbFilename=|DataDirectory|\aspnet-Entertainist-20141207110857.mdf;Initial Catalog=aspnet-Entertainist-20141207110857;Integrated Security=True" providerName="System.Data.SqlClient" />
</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" />
</appSettings>
<system.web>
<customErrors mode="Off" />
<authentication mode="None" />
<compilation debug="true" targetFramework="4.5" />
<httpRuntime targetFramework="4.5" />
<roleManager enabled="true"
defaultProvider="SqlRoleProvider">
<providers>
<add name="SqlRoleProvider" type="System.Web.Security.SqlRoleProvider"
connectionStringName="DefaultConnection"
applicationName="Entertainist"/>
</providers>
</roleManager>
<globalization culture="en-US" uiCulture="auto:en-US" />
</system.web>
<system.webServer>
<modules runAllManagedModulesForAllRequests="true">
<remove name="FormsAuthentication" />
</modules>
</system.webServer>
<system.serviceModel>
<behaviors>
<serviceBehaviors>
<behavior name="CalculatorServiceBehavior">
<serviceAuthorization principalPermissionMode="UseAspNetRoles"
roleProviderName="SqlRoleProvider" />
</behavior>
</serviceBehaviors>
</behaviors>
</system.serviceModel>
<runtime>
<assemblyBinding xmlns="urn:schemas-microsoft-com:asm.v1">
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.OAuth" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security.Cookies" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.0.0.0-3.0.0.0" newVersion="3.0.0.0" />
</dependentAssembly>
<dependentAssembly>
<assemblyIdentity name="Microsoft.Owin.Security" publicKeyToken="31bf3856ad364e35" />
<bindingRedirect oldVersion="0.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="0.0.0.0-1.5.2.14234" newVersion="1.5.2.14234" />
</dependentAssembly>
</assemblyBinding>
</runtime>
<entityFramework>
<defaultConnectionFactory type="System.Data.Entity.Infrastructure.SqlConnectionFactory, EntityFramework" />
<providers>
<provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
</providers>
</entityFramework>
</configuration>
And here is my Configuration.cs file which sets up roles and adds seed data into the database
namespace Entertainist.Migrations
{
using Entertainist.Models;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.EntityFramework;
using System;
using System.Data.Entity;
using System.Data.Entity.Migrations;
using System.Linq;
internal sealed class Configuration : DbMigrationsConfiguration<Entertainist.Models.ApplicationDbContext>
{
public Configuration()
{
AutomaticMigrationsEnabled = true;
ContextKey = "Entertainist.Models.ApplicationDbContext";
}
protected override void Seed(Entertainist.Models.ApplicationDbContext context)
{
var UserManager = new UserManager<ApplicationUser>(new UserStore<ApplicationUser>(context));
var RoleManager = new RoleManager<IdentityRole>(new RoleStore<IdentityRole>(context));
// Create Admin Role
string roleName = "Admins";
IdentityResult roleResult;
// Check to see if Role Exists, if not create it
if (!RoleManager.RoleExists(roleName))
{
roleResult = RoleManager.Create(new IdentityRole(roleName));
}
context.Artists.AddOrUpdate(
a => a.ArtistName,
new Artist { ArtistName = "Kanye West" },
new Artist { ArtistName = "65daysofstatic"},
new Artist { ArtistName = "D'Angelo"},
new Artist { ArtistName = "Faith No More"},
new Artist { ArtistName = "Daft Punk" },
new Artist { ArtistName = "Lana Del Rey"},
new Artist { ArtistName = "The Decemberists"},
new Artist { ArtistName = "The War On Drugs"}
);
context.MusicGenres.AddOrUpdate(
g => g.GenreName,
new MusicGenre { GenreName = "Rock" },
new MusicGenre { GenreName = "Hip-Hop" },
new MusicGenre { GenreName = "Electronic" },
new MusicGenre { GenreName = "Country" },
new MusicGenre { GenreName = "Classical" },
new MusicGenre { GenreName = "Indie"},
new MusicGenre { GenreName = "Rap"},
new MusicGenre { GenreName = "Metal"},
new MusicGenre { GenreName = "Pop"}
);
context.MovieGenres.AddOrUpdate(
g => g.GenreName,
new MovieGenre { GenreName = "Adventure"},
new MovieGenre { GenreName = "Action"},
new MovieGenre { GenreName = "Anime"},
new MovieGenre { GenreName = "Bollywood"},
new MovieGenre { GenreName = "Sci-Fi"},
new MovieGenre { GenreName =" Independent"},
new MovieGenre { GenreName = "Fantasy"}
);
context.Studios.AddOrUpdate(
s => s.StudioName,
new Studio { StudioName = "Universal"},
new Studio { StudioName = "MGM"},
new Studio { StudioName = "Disney"},
new Studio { StudioName = "Bad Robot"},
new Studio { StudioName = "Studio Ghibli"},
new Studio { StudioName = "Pixar"}
);
context.Directors.AddOrUpdate(
d => d.DirectorName,
new Director { DirectorName = "Steven Spielberg"},
new Director { DirectorName = "Michael Bay"},
new Director { DirectorName = "James Cameron"},
new Director { DirectorName = "Ang Lee"},
new Director { DirectorName = "J.J. Abrams"},
new Director { DirectorName = "Hayao Miyazaki"}
);
// This method will be called after migrating to the latest version.
// You can use the DbSet<T>.AddOrUpdate() helper extension method
// to avoid creating duplicate seed data. E.g.
//
// context.People.AddOrUpdate(
// p => p.FullName,
// new Person { FullName = "Andrew Peters" },
// new Person { FullName = "Brice Lambson" },
// new Person { FullName = "Rowan Miller" }
// );
//
}
}
}
Have you extended RoleProvider to use your azure cloud service's database? if not, it might be trying to use sqlexpress which is why it would work on your local but not when deployed.
http://msdn.microsoft.com/en-us/library/aa702542(v=vs.110).aspx

Categories

Resources