localhost refused to connect Visual Studio 2013 - sql-server

I've been working on a website using ASP.NET MVC, and I have this page in the website where you can directly send the a email form to a specific email address. Before I don't have database for the form, and it's working perfectly the form is sending without any problem but when I tried to add a database for it (cause I want the information to be save at the database at the same time send it) and tried to send it I keep on having this error:
But when I go to the other page it's working properly. I'm not really sure what the problem is cause I'm new with this kind of stuffs, but maybe the problem is related to this class:
public class RegisterRepository
{
//SqlTransaction transaction = null;
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();
}
}
}
I tried repairing my IIS 8.0 Express, (SSL Enable = True), and other solutions but it still doesn't work. Please someone help me. Thank you in advance.

Related

Unable to get IAM security credentials from EC2 Instance Metadata Service error when using Aws Sdk in UWP

I'm working with Aws Sdk and I'm trying to implement a login UI using UWP. I followed this online tutorial (which is for WPF) and I tried to make it works for the Universal Windows Platform as well.
The core part of the source code is the following (please note that is 90% similar to the one posted in the tutorial. The "only difference" is that I used
InitiateAuthAsync
instead of
AdminInitiateAuthAsync
<!-- language: lang-cs -->
private readonly AmazonCognitoIdentityProviderClient _client;
private readonly string _clientId = "32fsoifj93fjsiispat";
public MainPage()
{
this.InitializeComponent();
var amazonCognitoIdentityProviderConfig = new AmazonCognitoIdentityProviderConfig();
amazonCognitoIdentityProviderConfig.ServiceURL = "https://cognito-idp.eu-central-1.amazonaws.com/";
_client = new AmazonCognitoIdentityProviderClient(amazonCognitoIdentityProviderConfig);
}
private async Task<bool> CheckPasswordAsync(string userName, string password)
{
try
{
List<HttpHeader> httpHeaders = new List<HttpHeader>();
HttpHeader httpHeader = new HttpHeader
{
HeaderName = "X-Amz-Target",
HeaderValue = "AWSCognitoIdentityProviderService.InitiateAuth"
};
httpHeaders.Add(httpHeader);
httpHeader = new HttpHeader
{
HeaderName = "Content-Type",
HeaderValue = "application/x-amz-json-1.1"
};
httpHeaders.Add(httpHeader);
var authReq = new InitiateAuthRequest()
{
ClientId = _clientId,
AuthFlow = AuthFlowType.USER_PASSWORD_AUTH,
};
authReq.AuthParameters.Add("USERNAME", userName);
authReq.AuthParameters.Add("PASSWORD", password);
var authResp = await _client.InitiateAuthAsync(authReq);
return true;
}
catch (Exception ex)
{
return false;
}
}
Please consider that it is working properly with WPF framework. I'm able to get the TokenId and RefreshToken.
But if I try to copy and paste the same code in UWP I get the exception:
'Unable to get IAM security credentials from EC2 Instance Metadata Service.'
And if I try to investigate with Fiddler I get the following error:
[Fiddler] The connection to '169.254.169.254' failed. Error: NetworkUnreachable (0x2743). System.Net.Sockets.SocketException A socket operation was attempted to an unreachable network 169.254.169.254:80
I really can't understand why it tries to connect to the '169.254.169.254' address. Googling around I found other people experiencing the same issue (for example here). Do you have any idea?

give wpf application with database to client

I have a wpf application that is connected to my database which was created in microsoft SQL server Management using this:
private SqlConnection connect()
{
con = new SqlConnection();
con.ConnectionString = "Server=LAPTOP-1B0SDCU1 ;Database=project;User ID=sa;Password=123;Trusted_Connection=true;Integrated Security=false";
return con;
}
and added my data in a table called material as such
private void insertdata(object sender, RoutedEventArgs e)
{
connect();
con.Open();
string material = materialfield.Text;
string saved = "INSERT INTO materialtable(material) VALUES ('" + material + "')";
SqlCommand com = new SqlCommand(saved, con);
com.ExecuteReader();
viewdetails();
MessageBox.Show("record is added");
}
here my server is my own computer. Now I want to give this application to my client along with the database so that they can add details into the database and those details will only be stored on their laptop, but I do not know how to. Can someone please help.

Updating Database Value in windows forms

I am trying to do a function to update a value in a SQL database, this is my table
This is the function
private void UpdateGanToDB(float entrada, string Id)
{
string string_entrada = entrada.ToString();
string conString = Properties.Settings.Default.LocalDataBaseConnectionString;
string command_string = "UPDATE Gan SET Ganan = #GetGan WHERE Id = #GetId";
SqlConnection connection = new SqlConnection(conString);
SqlCommand cmd = new SqlCommand(command_string, connection);
cmd.Parameters.AddWithValue("#GetGan", string_entrada);
cmd.Parameters.AddWithValue("#GetId", Id);
try
{
connection.Open();
int row = cmd.ExecuteNonQuery();
if (row > 0) {
MessageBox.Show("Upgrade successful");
}
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
finally
{
connection.Close();
}
}
I am getting the message "upgrade successful" but when I check the database I can't see the changes. When I run the text in the command_string with known values I can see the changes but not with my function
Edit:
I added this code to the code above
int row = cmd.ExecuteNonQuery();
if (row > 0) {
SqlCommand command = new SqlCommand("SELECT * FROM Gan ", connection);
SqlDataAdapter adapter = new SqlDataAdapter(command);
System.Data.DataTable dataTable = new System.Data.DataTable();
adapter.Fill(dataTable);
MessageBox.Show(dataTable.Rows[0]["Ganan"].ToString());
}
To see if it is updating the value and I get the excepted 200 (Original value was 0) But When I close the application and see the values in the local database I see the original value 0 I don't know why the update is not saving
EDIT2:
I found another post with a work around for this problem: Can I commit changes to actual database while debugging C# in Visual Studio?
I think your code is correct and there is no problem
If you created database via Add\NewItem\Service-Base Database
I'm not sure, but I think After running your project, one copy of your original database will be included in the debug folder in your project and the update operation and also other operations run on that, not your original database
so, if you want to see a result, you should connect to that via View\ServerExplorer
meantime, after Change your Code and rebuild your Project, your debug database will be deleted and again one copy of your original database will be included in the debug folder

Check connection to database in thread

how to check connection to database while login form is showing to user before show all tools on the login form ?
In an application, I plan to arrange the following steps:
1-Login form without any special tools except a label and background image (similar to a Splash form).
2. Behind the login form (preferably inside a thread) is the connection to the server, and the user see a label with this text: try to connect to database...
3. If a connection is established (flag == right), a series of tools will be displayed for login user.
4. If the connection to the server is not established (flag == false), a series of other tools will be displayed to user for addressing the server.
I hope I could clearly make it.
using System;
using System.Windows.Forms;
using Microsoft.Data.ConnectionUI;
using System.Reflection;
public partial class LoginForm : Form
{
public LoginForm()
{
this.DoubleBuffered = true;
InitializeComponent();
System.Threading.Thread t = new System.Threading.Thread(new System.Threading.ThreadStart(CheckConnection));
t.Start();
System.Threading.Thread.Sleep(5000);
t.Abort();
}
bool flag;
private void CheckConnection()
{
using (System.Data.SqlClient.SqlConnection connection =
new System.Data.SqlClient.SqlConnection
(connectionString))
{
try
{
connection.Open();
connection.Close();
flag = true;
}
catch
{
flag = false;
}
}
}
private void SplashScreenForm_Load(object sender, EventArgs e)
{
if (flag)
{
//Do somethings to login user
}
else
{
//Do something to create connection to database
}
}
The problem with this code is that the thread starts running before the form is displayed, and the program initially starts with a delay and immediately all the tool is displayed. Thanks for giving friends guidance.
I used Backgroundworker controller to solve this problem. It works very excellent.
Refer to https://learn.microsoft.com/en-us/dotnet/api/system.componentmodel.backgroundworker?view=netframework-4.8

Connection property has not been initialized Error (ExecuteNonQuery)

This question has been addressed all over the web and I tried a lot of things without success. The SQL EXPRESS service is setup to accept local system account but the problem still exists.
This is my connection string:
<add name="PhoneTemplateChange" providerName="System.Data.SqlClient" connectionString="Data Source=.\SQLEXPRESS;Database=PhoneTemplateChange;Integrated Security=SSPI" />
I created a class to do database operations in the constructor I have
_connectionString = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["PhoneTemplateChange"].ConnectionString;
and a method in this class to insert data
public void AddNewChangeOrder(int operation, int targetExt)
{
using (SqlConnection con = new SqlConnection(_connectionString))
{
string sql = "INSERT into [dbo].ChangeOrder (operation, targetExt, dtrequested) VALUES (#operation, #targetExt, #dtrequested)";
using (SqlCommand cmd = new SqlCommand(sql))
{
try
{
cmd.Parameters.AddWithValue("#operation", operation);
cmd.Parameters.AddWithValue("#targetExt", targetExt);
cmd.Parameters.AddWithValue("dtrequested", DateTime.Now);
//con.CreateCommand();
con.Open();
//cmd.InitializeLifetimeService();
int rows = cmd.ExecuteNonQuery();
con.Close();
}
catch (SqlException e)
{
throw new Exception(e.Message);
}
}
}
I have played around with the connection string trying all different suggestions, also the commented code in the method above is what I tried to solve the problem. Still no luck!
I also changed the connection string I get two different exceptions this way
Database=PhoneTemplateChange
The above gives the exception in the title.
And the following gives the Exception "Cannot open Database PhoneTemplatechange.mdf requested by the login. Login failed for user 'mydomain\myusername'"
Database=PhoneTemplateChange.mdf
Any ideas?
You are missing the line of code where you specify that cmd uses con as it's connection. As a result the Command (cmd) has no connection, and con isn't associated with any command at all.
Add this line before executing:
cmd.Connection - con;
Alternatively (and better IMO) change your using statement as follows:
using (SqlCommand cmd = new SqlCommand(sql, con))

Resources