My web controller code:
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Web.Http.Description;
using Account;
namespace Account.Controllers
{
public class ORDER_DETAILController : ApiController
{
private restaurantEntities db = new restaurantEntities();
[HttpGet]
[Route("api/ORDER_DETAIL/PendingOrders/{id}")]
[ResponseType(typeof(ORDER_DETAIL))]
public IQueryable<Orders> PendingOrders(int id)
{
Class1 obj = new Class1();
return obj.GetOrders(id);
}
}
}
Class:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using Dapper;
namespace AccountStoredProc.Controllers
{
public class Class1
{
public IQueryable<Orders> GetOrders(int id)
{
using(SqlConnection conn = new SqlConnection("integrated security = true ; data source = RAHUL - PAVILION;"))
{
conn.open();
return conn.Query<Orders>($"select * from ORDER_DETAIL WHERE VEN_ID={id} and ORD_STATUS='PENDING' ").AsQueryable();
}
}
}
}
When I hit the below URL:
https://localhost:44331/api/ORDER_DETAIL/PendingOrders/1
I get this error:
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)
System.Data.SqlClient.SqlException
I know I already opened the connection while creating EF but how can I execute my query in GetOrders() without a SqlConnection variable called conn I am not able to execute my query without conn variable?
NOTE: connection establishment is working in normal console application and other predefined methods like get, search in account controller but in my predefined method it is not working.
Please check your connection string, especially on spaces
example format for connectiong string:
`connetionString = #"Data Source=WIN-50GP30FGO75; integrated security = true; Initial Catalog=Demodb;User ID=sa;Password=demol23";`
Related
trying to connect web API to oracle DB.
I have successfully connected with SQL server but I have no idea about oracle DB.what I have done is=> created a controller and write a get and post API method in it. and on the web.config I have added connectionStrings. I am attaching my SQL connection code.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using System.Data.SqlClient;
using System.Data;
using System.Configuration;
namespace API2.Controllers
{
public class IndexController : ApiController
{
[HttpGet]
[Route("getUsers")]
public HttpResponseMessage Get_Users()
{
DataTable dt = new DataTable();
string str_Msg = string.Empty;
string Query = string.Empty;
string consString = ConfigurationManager.ConnectionStrings["xyz"].ConnectionString;
Query = "SELECT * from xyz";
using (SqlConnection con = new SqlConnection(consString))
{
using (SqlCommand _SqlCommand = new SqlCommand(Query, con))
{
_SqlCommand.CommandType = CommandType.Text;
using (SqlDataAdapter _adapater = new SqlDataAdapter(_SqlCommand))
{
_adapater.Fill(dt);
}
Query = string.Empty;
}
}
return Request.CreateResponse(HttpStatusCode.OK, dt, Configuration.Formatters.JsonFormatter);
}
}
<connectionStrings>
<add name="xyz" connectionString="Data Source= xyz; Integrated Security=false;Initial Catalog= xyz; uid=xyz; Password=xyz;" providerName="System.Data.SqlClient" />
</connectionStrings>
I have no idea how to do the same connectivity with oracle DB. please help me with this.
thank you so much.
Referring to this
Your connection string will look like
Data Source=MyOracleDB;User Id=myUsername;Password=myPassword;Integrated Security=no;
Please help.
I have device MC3200 Zebra(motorola)(Windows Embedded version 7, build 2864). This device is connecting to network and see SQL server(ping is OK). I used it Visual Studio 2008, c#, SmartDevicePrj, .NET CF 3.5
But after start application on device will be displayed message:
Unknown connection option in connection string: initial catalog.
Some idea how to repair it?
Many thanks for your help.
using System;
using System.Linq;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlServerCe;
namespace SmartDeviceProject1
{
public partial class Form1 : Form
{
public SqlCeConnection msConn;
public string strCon = "";
public SqlCeCommand command;
public Form1()
{
InitializeComponent();
strCon = "Data Source=server007; Initial Catalog=FMPredlis; User ID=mistr; Password=heslo;";
try
{
msConn = new SqlCeConnection(strCon);
msConn.Open();
MessageBox.Show("Připojeno");
}
catch (SqlCeException ex)
{
MessageBox.Show("Chyba" + ex.Message);
msConn.Close();
}
}
}
}
I think you are mixing 2 things.
Either use The SqlConnection object, then you can connect to a SQL Server using a connection string found on this page:
https://www.connectionstrings.com/sql-server/
Or use like in your code the SqlCEConnection, then you connect to a SQL Lite (local file), and your connection string should be like on this page:
https://www.connectionstrings.com/sqlite/
But in your sample you are using SqlCEConnection to connect to a sql server, that wont work.
Grtz
Hey Members i am new to C# Language and Visual Studio Platform recently i am learning how to connect access Database with visual Studio and first time with same code i have connected with database but after some time when i compiled again then there is error given in Title.
why this is happening ?
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.OleDb;
namespace Clinic_Management_System
{
public partial class Login : Form
{
public Login()
{
InitializeComponent();
}
private void Login_Load(object sender, EventArgs e)
{
try
{
OleDbConnection connection = new OleDbConnection();
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users
\Hassan Gillani\Documents\Clinic Management System.accdb; Persist Security Info = False; ";
connection.Open();
label1.Text = "Connected to Clinic Management System Database";
connection.Close();
}
catch (Exception exp)
{
MessageBox.Show("Error " + exp);
}
}
}
}
please visit given like to view screen short
http://s33.postimg.org/5ltm4dtnj/Error.png
Using the verbatim character (#) and splitting your path in the middle in not a good idea.
Spaces counts in paths so the filename used for your connection is
C:\Users \Hassan Gillani\Documents\Clinic Management System.accdb;
If you try to use File.Exists on this string you get false as result.
Do not split your connection string in the middle of the path
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\Hassan Gillani\Documents\Clinic Management System.accdb;
Persist Security Info = False; ";
I am currently trying to connect to a database made in MS SQL Server and insert a row when a button on a form is clicked. Below is my code and an explanation of what is going wrong.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Data.SqlClient;
namespace WindowsFormsApplication10
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection myConnection = new SqlConnection("Data Source = (LocalDB)\\MSSQLLocalDB; AttachDbFilename = 'u:\\my documents\\visual studio 2015\\Projects\\WindowsFormsApplication10\\WindowsFormsApplication10\\InventoryDB.mdf'; Integrated Security = True; Connect Timeout = 30");
SqlCommand myCommand = new SqlCommand("INSERT INTO Table (Barcode, Item, Quantity) Values (123, 'Item 123', 5)", myConnection);
myConnection.Open();
myCommand.ExecuteNonQuery();
myConnection.Close();
}
}
}
I believe I have connected to the database, because in previous attempts I was getting an error at myConnection.Open(). Now I am getting an error at myCommand.ExecuteNonQuery(); which says:
SqlException was Unhandled: An Unhandled Exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll
Additional information: Incorrect syntax near the keyword 'Table'.
You can't use Table as the name for your table without qualifying it, since it's a SQL reserved word. Use [Table] instead if that is really your table name.
INSERT INTO [Table] (Barcode, Item, Quantity)...
Better yet, change the name of your table. Unless this is a copy/paste fail.
I have MYSQL database from Hosting provider net4.in and i am unable to access database.
My code is as below :
using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Data.Odbc;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
public partial class dummy : System.Web.UI.Page
{
OdbcConnection conn;
string Address = "Driver={MySql ODBC 5.1 Driver};Server=phpmyadmin7.net4india.com;Option=3;Port=3306;Stmt=;" +
"DataBase=test;Uid=demo;Pwd=demo123;";
protected void Page_Load(object sender, EventArgs e)
{
string sql = "Select * from test.testing limit 5";
DataSet rsDSet = new DataSet();
try
{
if (sql == "") throw new Exception("SQL input required");
conn = new OdbcConnection(Address);
if (conn.State == ConnectionState.Closed) conn.Open();
OdbcDataAdapter adp = new OdbcDataAdapter(sql, conn);
adp.Fill(rsDSet);
}
catch (Exception ee)
{
Response.Write(ee.ToString());
}
GridView1.DataSource = rsDSet;
GridView1.DataBind();
}
}
Pl let me know how can i connect MYSQL DB.
Thank you in advance
Are you sure your MySQL instance is hosted on a machine named phpmyadmin7? It seems unlikely. Phpmyadmin is the name of a chunk of client software, as I am sure you know.
Are you sure your hosting provider allows access from outside their data center to MySQL server instances? (Presuming you are running the sample code you provided from your own machine, which might not be the case.) Most hosting providers protect their MySQL instances from internet-wide access because it is easy to mount DDOS attacks against them otherwise.
In some hosting provider environments the MySQL authentication scheme only allows access to your MySQL instance from the particular machine upon which your web apps run.
In any case you need to have a conversation with your support crew about how to do this.