Database not working after publishing website on IIS - C# Web Services - c#

Hope you're doing well!
I will try to be brief,
I made a web service called "Contacts.asmx" that have this code:
[WebMethod]
public DataTable GetContacts()
{
string constr = ConfigurationManager.ConnectionStrings["constr"].ConnectionString;
using (SqlConnection con = new SqlConnection(constr))
{
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Customers"))
{
using (SqlDataAdapter sda = new SqlDataAdapter())
{
cmd.Connection = con;
sda.SelectCommand = cmd;
using (DataTable dt = new DataTable())
{
dt.TableName = "Customers";
sda.Fill(dt);
return dt;
}
}
}
}
and and I have this code in my web.config
<add name="constr" connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=C:\Users\user\Desktop\InternetApp\Folder\database.mdf;Integrated Security=True;Connect Timeout=30" providerName="System.Data.SqlClient"/>
Seems to be working fine and i'm getting the XML when i click invoke.
But after publishing website on IIS : http://localhost/Contacts, i'm having this problem:
What should i do?

Related

Do I really need to explicitely open a connection when ExecuteNonQuery()

I was trying to create shortest possible code to execute "non query" commands. Is it possible somehow to instruct to implicitly open the connection without using conn.Open()
public static int ExecuteNonSelect(string nonSelect)
{
string conString = #"Data Source=...";
int affected;
using (SqlConnection conn = new SqlConnection(conString))
{
using (SqlCommand cmd = new SqlCommand(nonSelect, conn))
{
conn.Open();
affected = cmd.ExecuteNonQuery();
conn.Close();
}
}
return affected;
}
In case of the SqlDataAdapter() class this was not needed:
public static DataTable ExecuteSelect(string selectQuery)
{
string constring = #"Data Source=...";
DataTable dt = new DataTable();
using (SqlConnection conn = new SqlConnection(constring))
{
using (SqlDataAdapter da = new SqlDataAdapter(selectQuery, conn))
{
da.Fill(dt); // calls ExecuteReader internally
}
}
return dt;
}

c# local Cannot open database requested by the login. The login failed. Login failed for user MicrosoftAccount\(email)

Doesnt connect to database, its throw exception.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
SqlCommand cmd;
SqlDataAdapter da;
DataTable dt;
DataSet ds = new DataSet();
private void CashForm_Load(object sender, EventArgs e)
{
con.Open();
da = new SqlDataAdapter("Select * FROM PhoneBook ORDER BY SLNo desc", con);
dt = new DataTable();
da.Fill(dt);
dataGridView1.DataSource = dt;
dataGridView1.Columns[0].Width = 10;
con.Close();
comboBox1.Items.Clear();
con.Open();
cmd = con.CreateCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "SELECT Name FROM PhoneBook order by SLNo asc";
cmd.ExecuteNonQuery();
dt = new DataTable();
SqlDataAdapter da1 = new SqlDataAdapter(cmd);
da1.Fill(dt);
foreach (DataRow dr in dt.Rows)
{
comboBox1.Items.Add(dr["Name"].ToString());
}
con.Close();
here is my connection string:
<add name="CafeteriaDBConnectionString"
connectionString="Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True"
First of all, place your connection string in single location. As on connection string inside code and second in configuration file.
SqlConnection con = new SqlConnection("Data Source=.;InitialCatalog=CAFETERIADB; Integrated Security=True;");
To make it working first test your connection string.
Save notepad file as name.udl
double click and provide appropriate values if local server (pc name \SQLEXPRESS) or (.\SQLEXPRESS)
Click test and again open same udl file in notepad
copy the connection string it will be some thing like below but exclude provider part
Password=;Persist Security Info=True;User ID=;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS
SqlConnection con = new SqlConnection("Password=***;Persist Security Info=True;User ID=***;Initial Catalog=CafeteriaDB;Data Source=.\SQLEXPRESS;")
I hope this will helps you.
I don't think in your code you are referring to the connection string you set up in config file. Instead, you hard-coded a new connection in the first line of your code.
If you are sure the connection string in config file works fine, you can put it into your code directly.
Change your first line code as:
SqlConnection con = new SqlConnection("Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\CafeteriaDB.mdf;Integrated Security=True");
Or you can refer to connection string in config file.
string connectionString = DatabaseHelper.CafeteriaDBConnectionString;
SqlConnection con = new SqlConnection(connectionString);

How to display and loop record from database to label one by one with timer

I am developing windows form project with C# where I need to display record from access database to label, but it should not show entire record at a time rather it should show record from database one at a time and so on looping one by one with timer say 5 seconds. Any kind of suggestion will be helpful and will be highly appreciable.
Below is the code I was trying but gave up:
private void BindLabel()
{
string constring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
Persist Security Info=True;Jet OLEDB:Database Password=abc123";
using (OleDbConnection con = new OleDbConnection(constring))
{
using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
{
cmd.CommandType = CommandType.Text;
using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
{
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
//label1
// Please guide me, any suggestion will be higly helpful and appreciable.
}
}
}
}
}
Make DataTable global to form and then use timer
DataTable dtReminders = null;
int i = 0;
private void BindLabel()
{
string constring = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=|DataDirectory|\\LicensedDB.accdb;
Persist Security Info=True;Jet OLEDB:Database Password=abc123";
using (OleDbConnection con = new OleDbConnection(constring))
{
using (OleDbCommand cmd = new OleDbCommand("SELECT TaskDetails FROM TaskReminder ", con))
{
cmd.CommandType = CommandType.Text;
using (OleDbDataAdapter sda = new OleDbDataAdapter(cmd))
{
sda.Fill(dtReminders);
if(dtReminders.Rows.Count > 0)
timer.Start();
}
}
}
}
In timer tick event add below lines
if(i >= dtReminders.Rows.Count)
i = 0;
if(dtReminders.Rows[i]["columnName"] != null)
lblRemider.Text = dtReminders.Rows[i]["columnName"].ToString();
i++;

Creating social website in asp.net

I'm creating a social Networking Website for that I used "Social Networking Website in ASP.NET - Open Source" from
http://www.c-sharpcorner.com/UploadFile/rahul4_saxena/social-networking-website-in-Asp-Net-open-source-project/
When I tried to run the project on my Visual Studio 2012 edition it is showing error like below,
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)
Source Error:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
/// <summary>
/// Summary description for DataBaseClass
/// </summary>
public class DataBaseClass
{
SqlDataAdapter da;
SqlConnection con;
SqlCommand cmd = new SqlCommand();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
public DataBaseClass()
{
//
// TODO: Add constructor logic here
//
}
public void ConnectDataBaseToInsert(string Query)
{
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
}
public DataSet ConnectDataBaseReturnDS(string Query)
{
ds = new DataSet();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(ds);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return ds;
}
public DataTable ConnectDataBaseReturnDT(string Query)
{
dt = new DataTable();
con = new SqlConnection(#"Data Source=Veena-SQLServer2008; Initial Catalog=RNetworkingWebApplication;");
cmd.CommandText = Query;
cmd.Connection = con;
da = new SqlDataAdapter(cmd);
da.Fill(dt);
con.Open();
cmd.ExecuteNonQuery();
con.Close();
return dt;
}
}
Visual studio pointing the error here da.Fill(dt).
I have spent 2 days to debug this error but still I couldn't. Please help me.
It is very simple. Your code is not able to connect to the database. Open Server Explorer in Visual Studio and connect to your database to confirm you are able to connect. And then get your connection string right.
And you do have a database, right?

Executing an INSERT command using ASP.net

I am using Visual Studio 2010 to create a simple Website for a college assignment. I am trying to create a contact form that submits the users name, email and message to my database table Messages.
I have created the relevant web service and I know that it is working when I try to GET data from the Table. I am just a little confused as to how I can INSERT data into the table.
Below is the code to my web service. The method I am concerned with is addMessage() I call the method when a button is clicked that is located on the contact.aspx page.
public class Customers : System.Web.Services.WebService {
[WebMethod]
public DataSet getCustomers() {
SqlConnection conn;
SqlDataAdapter myDataAdapter;
DataSet myDataSet;
string cmdString = "Select * From Customers";
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
myDataAdapter = new SqlDataAdapter(cmdString, conn);
myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet, "Customers");
return myDataSet;
}
[WebMethod]
public void addMessage(String n, String e, String m)
{
SqlConnection conn;
SqlDataAdapter myDataAdapter;
SqlCommand myCommand = new SqlCommand("INSERT INTO Messages VALUES("+n+","+e+","+m+")");
conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True");
//UNSURE WHAT TO DO FROM THIS POINT... CAN I USE myDataAdapter to execute a query?
}
}
Appreciate any help you guys might have! Thanks
[WebMethod]
public void addMessage(String n, String e, String m)
{
string sql = "INSERT INTO Messages VALUES(#n, #e, #m)";
using (var conn = new SqlConnection("Data Source=localhost\\SQLEXPRESS;AttachDbFilename=C:\\Users\\n00093500\\Desktop\\MMCA2\\APP_DATA\\NORTHWIND.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True"))
using (var cmd = new SqlCommand(sql, conn))
{
//change these three lines to use actual database column types, lengths
//I'll pretend "e" is a date column just to show an example of how that might look
cmd.Parameters.Add("#n", SqlDbType.NVarChar, 50).Value = n;
cmd.Parameters.Add("#e", SqlDbType.DateTime).Value = DateTime.Parse(e);
cmd.Parameters.Add("#m", SqlDbType.NVarChar, 50).Value = m;
conn.Open();
cmd.ExecuteNonQuery();
}
}

Categories