An unhandled exception in the designer - visual-studio-2019

I've created a project in Visual Studio 2019 which has several user controls in a form called Home.
All goes right until today. After rebuilding my project Home form shows an error saying
The control system.windows.forms.form has thrown an unhandled exception in the designer and has been desabled.
Exception :
An attempt to attach an auto-named database for file c:\program files(x86)\Microsoft Visual Studio\2019\Enterprise\common7\ide\database\pharmacy.mdf failed. A database with the same name exists, or specified file cannot be opened, or it is located on unc share.
I checked the connection code, and it looks ok. But still the error isn't solved.
Code:
SqlConnection con = new SqlConnection(#"Data Source=LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True");
con.Open()
String str = "Select max(id) from supp;";
SqlCommand cmd = new SqlCommand(str, con);
SqlDataReader dr = cmd.ExecuteReader();
if (dr.Read())
{
String val = dr[0].ToString();
if (val == "")
{
.....
}
private void button1_Click(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection(#"Data Source= (LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True");
con.Open();
try
{
String str = "Insert into supp(name,email,mobile,addr,s_code) values('" + Sup_Name.Text + "','" + Sup_Email.Text + "','" + Sup_Mobile.Text + "','" + Sup_Add.Text + "','" + Sup_Code.Text + "');";
SqlCommand cmd = new SqlCommand(str, con);
cmd.ExecuteNonQuery();
String str1 = "select max(ID) from supp;";
SqlCommand cmd1 = new SqlCommand(str1, con);
SqlDataReader dr = cmd1.ExecuteReader();
if (dr.Read())
{
MessageBox.Show("Inserted Supplier Data SuccessFully..");
using (SqlConnection con1 = new SqlConnection(#"Data Source=(LocalDB)\MSSQLLocalDB;AttachDbFilename=D:\Final Project BCA\PharmacyManagementSystemCSharp\Database\pharmacy.mdf;Integrated Security=True"))
{
String str2 = "Select * from supp";
SqlCommand cmd2 = new SqlCommand(str2, con1);
SqlDataAdapter sda = new SqlDataAdapter(cmd2);
DataTable dt = new DataTable();
sda.Fill(dt);
SupplierDataGV.DataSource = new BindingSource(dt, null);
}
Sup_Name.Text = "";
Sup_Code.Text = "";
Sup_Email.Text = "";
Sup_Mobile.Text = "";
Sup_Add.Text = "";
}
}
catch (SqlException ex)
{
MessageBox.Show(ex.Message);
}
}

Related

getting the System.Threading.Tasks.Task`1[System.Int32] error

i am trying to convert my code to a sync but when i run it
i get in one of my vars the value "System.Threading.Tasks.Task`1[System.Int32]" instead of the expected ans
i have read most of the same questions asked in this topic but none of them helped me solved the problem
i tried to use properly the await but its isn't helped
public async Task<int> userloginAsync(string name,string pass)
{
using (SqlConnection con = new SqlConnection(#"/////:P//////"))
{
using (SqlCommand cmd = new SqlCommand("UserLoginPro"))
{
cmd.Connection = con;
cmd.CommandText = "SELECT count(id) FROM user_table where name =#name and password =#password; ";
cmd.Parameters.AddWithValue("#name", name);
cmd.Parameters.AddWithValue("#password", pass);
await con.OpenAsync();
var ans1 = await cmd.ExecuteScalarAsync();
var ans = ans1.ToString();
con.Close();
int res = Convert.ToInt32(ans);
con.Close();
return res;
}
}
}
its should query the mssql if there is an match to inputs(username and password)
and if there is return 1
if not 0
(in the DB there is unique usernames so it can be only one )

com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near '{'

I am new to java.We have a few tabled valued parameter used in one of our stored procedure when we try with below code then we are getting following error.
com.microsoft.sqlserver.jdbc.SQLServerException: Incorrect syntax near
'{'.
import java.sql.*;
import com.microsoft.sqlserver.jdbc.SQLServerDataTable; import
com.microsoft.sqlserver.jdbc.SQLServerPreparedStatement;
public class DB_SP_Call {
Connection conn = null;
Statement stmt = null;
String dbserver="10.42..:1198";
String db="t1c";
String USER="t1c";
String PWD="t1c";
String sql; static final String JDBC_DRIVER = "com.microsoft.sqlserver.jdbc.SQLServerDriver"; public void
runSP(){
String DB_URL = "jdbc:sqlserver://"+dbserver+";databaseName="+db; try{
Class.forName(JDBC_DRIVER);
//STEP 3: Open a connection
System.out.println("Connecting to database...");
conn = DriverManager.getConnection(DB_URL,USER,PWD);
System.out.println("Creating statement...");
stmt = conn.createStatement();
//SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement)conn.prepareStatement("{call exec
t1c.scnTargetingBYO
#InstrID=?,#CAS=?,#PageNum=?,#PageSize=?,#SortField=?,#TotalRecNum=?
output,#OutputFirmFund=?,#Download=?,#FirmContactData=?,#FirmList=?,#CustTagList=?,#LocationList=?,#Orientation=?,#InvTypeIDList=?,#InvStyleIDList=?,#AdvisoryList=?,#SocialyResposible=?,#TurnoverList=?,#SecurityActivity=?,#InstWithUpside=?,#MarketCapPass=?,#PNI=?,#EventFirmMet=?,#EventType=?,#CorpParticipant=?,#SectorList=?,#GeoIDList=?,#MarketCapStr=?,#HoldType=?,#ActThreshold=?,#SavedDataFlag=?
output,#DisplayGroupFlag=?,#PerPeerFlag=?,#UserId=?,#AccountID=?}");
SQLServerPreparedStatement pstmt = (SQLServerPreparedStatement)conn.prepareStatement("{ call exec
t1c.scnTargetingBYO
?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?
}");
pstmt.setInt(1, 264998);
pstmt.setString(2, "P");
pstmt.setInt(3,0);
pstmt.setInt(4, 100);
pstmt.setString(5, "Pos DESC");
pstmt.setInt(6, 2308);
pstmt.setInt(7,0);
pstmt.setInt(8, 0);
pstmt.setInt(9, 0);
SQLServerDataTable p10 = new SQLServerDataTable();
p10.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p10.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
pstmt.setStructured(10, "t1c.InvIDTabType", p10);
SQLServerDataTable p11 = new SQLServerDataTable();
p11.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p11.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
pstmt.setStructured(11, "t1c.InvIDTabType", p11);
SQLServerDataTable p12 = new SQLServerDataTable();
p12.addColumnMetadata("LocationID",java.sql.Types.NUMERIC);
p12.addColumnMetadata("LocationTypeID",java.sql.Types.NUMERIC);
Object[] row= new Object[2];
row[0]=new Integer(10006);
row[1]=new Integer(5);
p12.addRow(row);
pstmt.setStructured(12, "t1c.LocationList", p12);
pstmt.setInt(13,1);
SQLServerDataTable p14 = new SQLServerDataTable();
p14.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p14.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
p14.addColumnMetadata("Lev",java.sql.Types.NUMERIC);
Object[] row1= new Object[3];
row1[0]=new Integer(200);
row1[1]=null;
row1[2]=new Integer(2);
p14.addRow(row1);
Object[] row2= new Object[3];
row2[0]=new Integer(600);
row2[1]=null;
row2[2]=new Integer(1);
p14.addRow(row2);
Object[] row3= new Object[3];
row3[0]=new Integer(100);
row3[1]=null;
row3[2]=new Integer(2);
p14.addRow(row3);
Object[] row4= new Object[3];
row4[0]=new Integer(500);
row4[1]=null;
row4[2]=new Integer(1);
p14.addRow(row4);
Object[] row5= new Object[3];
row5[0]=new Integer(300);
row5[1]=null;
row5[2]=new Integer(2);
p14.addRow(row5);
pstmt.setStructured(14, "t1c.InvIDTabType2", p14);
SQLServerDataTable p15 = new SQLServerDataTable();
p15.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p15.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
p15.addColumnMetadata("Lev",java.sql.Types.NUMERIC);
pstmt.setStructured(15, "t1c.InvIDTabType2", p15);
pstmt.setInt(16,0);
pstmt.setString(17,"NULL");
SQLServerDataTable p18 = new SQLServerDataTable();
p18.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p18.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
pstmt.setStructured(18, "t1c.InvIDTabType", p18);
pstmt.setInt(19,0);
pstmt.setInt(20,0);
pstmt.setInt(21,0);
pstmt.setInt(22,0);
pstmt.setInt(23,3);
SQLServerDataTable p24 = new SQLServerDataTable();
p24.addColumnMetadata("EventID",java.sql.Types.NUMERIC);
p24.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p24.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
pstmt.setStructured(24, "cms.EvtLinkTabType", p24);
SQLServerDataTable p25 = new SQLServerDataTable();
p25.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p25.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
pstmt.setStructured(25, "t1c.InvIDTabType", p25);
SQLServerDataTable p26 = new SQLServerDataTable();
p26.addColumnMetadata("Type",java.sql.Types.VARCHAR);
p26.addColumnMetadata("ID",java.sql.Types.NUMERIC);
p26.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p26.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
p26.addColumnMetadata("ID3",java.sql.Types.NUMERIC);
p26.addColumnMetadata("ID4",java.sql.Types.NUMERIC);
p26.addColumnMetadata("ID5",java.sql.Types.NUMERIC);
p26.addColumnMetadata("ID6",java.sql.Types.NUMERIC);
p26.addColumnMetadata("ID7",java.sql.Types.NUMERIC);
pstmt.setStructured(26, "t1c.InvSpecialIDTabType2", p26);
SQLServerDataTable p27 = new SQLServerDataTable();
p27.addColumnMetadata("Type",java.sql.Types.VARCHAR);
p27.addColumnMetadata("ID",java.sql.Types.NUMERIC);
p27.addColumnMetadata("ID1",java.sql.Types.NUMERIC);
p27.addColumnMetadata("ID2",java.sql.Types.NUMERIC);
p27.addColumnMetadata("ID3",java.sql.Types.NUMERIC);
p27.addColumnMetadata("ID4",java.sql.Types.NUMERIC);
p27.addColumnMetadata("ID5",java.sql.Types.NUMERIC);
p27.addColumnMetadata("ID6",java.sql.Types.NUMERIC);
p27.addColumnMetadata("ID7",java.sql.Types.NUMERIC);
pstmt.setStructured(27, "t1c.InvSpecialIDTabType2", p27);
pstmt.setString(28,"NULL");
pstmt.setInt(29,1);
SQLServerDataTable p30 = new SQLServerDataTable();
p30.addColumnMetadata("Category", java.sql.Types.VARCHAR);
p30.addColumnMetadata("ActType", java.sql.Types.NUMERIC);
p30.addColumnMetadata("Threshold", java.sql.Types.VARCHAR);
p30.addColumnMetadata("Min", java.sql.Types.NUMERIC);
p30.addColumnMetadata("Max", java.sql.Types.NUMERIC);
Object[] row6= new Object[5];
row6[0]=new String("O");
row6[1]=new Integer(0);
row6[2]=new String("S");
row6[3]=new Integer(1);
row6[4]=null;
p30.addRow(row6);
Object[] row7= new Object[5];
row7[0]=new String("F");
row7[1]=null;
row7[2]=new String("E");
row7[3]=new Integer(5);
row7[4]=null;
p30.addRow(row7);
pstmt.setStructured(30, "t1c.InvActThresholdTabType", p30);
pstmt.setInt(31,2);
pstmt.setInt(32,2946);
pstmt.setInt(33,0);
pstmt.setInt(34,234568);
pstmt.setInt(35,21022);
ResultSet rs = pstmt.executeQuery();
//ResultSet rs = pstmt.execute();
ResultSetMetaData metaData = rs.getMetaData();
//System.out.println("Hi, fetching resultset.........");
System.out.println(metaData.getColumnCount());
while(rs.next()){
int intdata = rs.getInt("LgcyInvestorID");
System.out.println(intdata);
}
}catch(Exception e){ e.printStackTrace();
}finally{
//finally block used to close resources
try{
if(stmt!=null)
stmt.close();
}
catch(SQLException se2)
{
}// nothing we can do
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}//end finally try
}
}
public static void main(String[] args) {
DB_SP_Call dbcall= new DB_SP_Call();
dbcall.runSP(); }
}
Request experts to please help in this regard.

Oledbcommand with date in the where clause

I am using oledbconnection to read dbf files. I am trying to search all data from a specific dbf database. I am doing it well when there is no date in where clause. But when I am using date as a where I am having zero result.
String constr = #"Provider=VFPOLEDB.1;Data Source=" + Directory.GetParent(cashierPath).FullName +
";Exclusive=false;Nulls=false";
DataTable dt = new DataTable();
OleDbConnection con= new OleDbConnection(constr);
con.Open();
using (OleDbCommand cmd = con.CreateCommand())
{
cmd.CommandText = "select id from " + Path.GetFileName(cashierPath) + " where todate=#todate";
cmd.Parameters.AddRange(new OleDbParameter[]
{
new OleDbParameter("#todate", "2016-07-21")
});
using(OleDbDataReader reader = cmd.ExecuteReader())
{
if (reader.HasRows)
{
reader.Read();
String data = reader.GetString(0);
MessageBox.Show(data);
}
}
}
I don't really know what the problem.

Stored procedure error with ADO.NET

I have a situation here. My stored procedure works exactly fine the way I want in SQL Server.
However, I'm unable to implement the same in ADO.NET.
Here is my stored procedure:
Create Procedure bridge_Type(
#EmpID INT,
#Name varchar(50),
#Mob2 numeric(10,0),
#Email varchar(50),
#Type varchar(50)
)
AS
DECLARE #TYPEID int
Set NOCOUNT OFF
BEGIN TRANSACTION
INSERT INTO dbo.EmpType VALUES (#Type)
SET #TYPEID = SCOPE_IDENTITY()
IF ##ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
Insert into dbo.Emp VALUES (#EmpID, #Name, #Mob2, #Email, #TYPEID)
IF ##ERROR <> 0
BEGIN
ROLLBACK
RETURN
END
COMMIT
Here is my ADO.NET connections for simple registration process.
public void InsertInfo()
{
String empdb = #"Data Source=USER-PC\SQLEXPRESS;Initial Catalog=EmployeeDB;Integrated Security=True";
SqlConnection conn = new SqlConnection(empdb);
SqlCommand cmd = new SqlCommand("bridge_Type", conn);
cmd.CommandType = CommandType.StoredProcedure;
try
{
conn.Open();
/*cmd.Parameters.Add(new SqlParameter("#EmpID", TextBox1.Text));
cmd.Parameters.Add(new SqlParameter("#Name", TextBox2.Text));
cmd.Parameters.Add(new SqlParameter("#Mob2", TextBox3.Text));
cmd.Parameters.Add(new SqlParameter("#Email", TextBox4.Text));
cmd.Parameters.Add(new SqlParameter("#Emptype", dropdown1.SelectedValue));
cmd.Parameters.Add(new SqlParameter("#Emptype", SqlDbType.VarChar, 50));
cmd.Parameters("#Emptype").Value = dropdown1.SelectedValue; */
cmd.Parameters.Add(new SqlParameter("#EmpID", SqlDbType.Int));
cmd.Parameters["#EmpID"].Value = Convert.ToInt32(TextBox1.Text);
cmd.Parameters.Add(new SqlParameter("#Name", SqlDbType.VarChar, 50));
cmd.Parameters["#Name"].Value = TextBox2.Text;
cmd.Parameters.Add(new SqlParameter("#Mob2", SqlDbType.Int));
cmd.Parameters["#Mob2"].Value = TextBox3.Text;
cmd.Parameters.Add(new SqlParameter("#Email", SqlDbType.VarChar, 50));
cmd.Parameters["#Email"].Value = TextBox4.Text;
cmd.Parameters.Add(new SqlParameter("#Emptype", SqlDbType.VarChar, 50));
cmd.Parameters["#Emptype"].Value = dropdown1.SelectedValue;
cmd.ExecuteNonQuery();
}
catch (System.Data.SqlClient.SqlException ex)
{
string msg = "Insert Error:";
msg += ex.Message;
throw new Exception(msg);
}
finally
{
if (conn != null)
{
conn.Close();
}
}
}
protected void Button1_Click(object sender, EventArgs e)
{
InsertInfo();
}
It looks like you missed a conversion to an int in your #Mob2 parameter:
cmd.Parameters.Add(new SqlParameter("#Mob2", SqlDbType.Int));
cmd.Parameters["#Mob2"].Value = Convert.ToInt32(TextBox3.Text);
EDIT:
Thanks to David for seeing this. The last parameter you are adding is called #Emptype, but the stored proc is expecting it to be named #Type.

How to handle SQL Query CommandTimeout in C# 2.0

I have got below code in c#.
SqlConnection conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;");
conn.Open();
if (conn != null)
{
//create command
SqlCommand cmd = new SqlCommand("dbo.GETTridionLinkData", conn);
cmd.Parameters.AddWithValue("#PageID", "637518");
cmd.CommandType = CommandType.StoredProcedure;
cmd.CommandTimeout = 500;
StringBuilder sbXML = new StringBuilder();
//Adding Root node
sbXML.Append("<TridionLinks>");
//Reading all the values of Stored procedure return
using (XmlReader reader = cmd.ExecuteXmlReader())
{
while (reader.Read())
{
sbXML.Append(reader.ReadOuterXml().Replace("//", "/"));
}
}
//Closing the root node tag
sbXML.Append("</TridionLinks>");
XmlDocument xDoc = new XmlDocument();
//Loading string xml in XML Document
xDoc.LoadXml(sbXML.ToString());
}
In above code you can see that, I have set the cmd.CommandTimeout = 500;, now I want to give user an error message if the timeout is more than this or you can say database is down.
Please suggest!!
Please refer to
How to catch SQLServer timeout exceptions
The question has already been answered..
To improve coding, you can use
try{
using (sqlconnection Conn = new SqlConnection("Data Source=MANOJ-PC\\SQLEXPRESS;Initial Catalog=master;Integrated Security=False;User Id=sa;Password=Manoj;"){
...
}
}catch(sqlException ex){
if (ex.Number == -2) {
//return your message to the control or display the error
}
}
well just an example..

Resources