how to create c# exe? - c#

How to create a exe file for this C# program. I did try to create an exe file but some error occurred the error is,
'WindowsFormsApplication11.save' does not contain a definition for 'save_Load' and no extension method 'save_Load' accepting a first argument of type 'WindowsFormsApplication11.save' could be found (are you missing a using directive or an assembly reference?)
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Data.SqlClient;
using MySql.Data.MySqlClient;
namespace WindowsFormsApplication11
{
public partial class save : Form
{
public save()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string myConnection = "datasource=localhost;port=3306;username=root;Password=root";
string query = "insert into store_data.item_details (item_id,item_name,item_qty,item_price) values('" + this.id_txt.Text + "','" + this.name_txt.Text + "','" + this.qty_txt.Text + "','" + this.price_txt.Text + "');";
MySqlConnection connection = new MySqlConnection(myConnection);
MySqlCommand cmdsave = new MySqlCommand(query, connection);
MySqlDataReader dataReader;
try
{
connection.Open();
dataReader = cmdsave.ExecuteReader();
MessageBox.Show("your Data has been saved ");
while (dataReader.Read())
{
}
connection.Close();
}
catch (Exception excep)
{
MessageBox.Show(excep.Message);
}
}
}
}

You probably at one point tried to write code that executes on the form load, and then deleted the load method. The error is coming from the fact that there is still a reference to that method which no longer exists.
The solution is simply to double-click on the error in Visual Studio and delete the lines that are causing you problems, which will be the ones that reference the now nonexistent method.

You're missing an event handler, it seems, that's probably specified in the designer. Either remove the reference to it, or define it, probably something like this:
save_Load(object sender, EventArgs e) {
}

Related

.NET Framework compatibility issue with Oracle Data Access

I'm working on a C# project in Visual Studio 2012 on Windows 10 and Oracle 11g.
In order to connect my c# project I had to install Oracle Data Access Components_ODTwithODAC121024 and everything worked fine.
I updated the target .NET framework of my project to 3.5, and now I get this error:
Could not load file or assembly 'Oracle.DataAccess, Version=2.121.2.0, Culture=neutral, PublicKeyToken=89b483f429c47342' or one of its dependencies. An attempt was made to load a program with an incorrect format.
After really long search and test I think that caused by incompatibility issue.
I tried to enable .NET Framework 3.5 through Programs and Features -> Turn Windows features on or off.
I tried to read reference and importing the Oracle.DataAccess.dll from
C:\app\Samer\product\11.2.0\dbhome_1\ODP.NET\bin\2.x
and I also used the Oracle.DataAccess.dll that comes with Oracle Data Access Components
My project works fine when I disable the method that deals with oracle commands.
Here is the code:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.IO;
using Oracle.DataAccess;
using Oracle.DataAccess.Client;
using Oracle.DataAccess.Types;
namespace backup_Check_v01
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
Read_const_File();
}
//Method for Reading Constants File
public void Read_const_File()
{
string File_Path;
File_Path = #"s:\test\result";
Get_File_info(File_Path);
}
//Method for reading file information ex(File Name,Size,and creation date..etc)
public void Get_File_info(string para1)
{
FileInfo info = new FileInfo(para1);
richTextBox1.AppendText(Environment.NewLine + "File Name: " + Path.GetFileNameWithoutExtension(info.Name));
richTextBox1.AppendText(Environment.NewLine + "File Size (Bytes): " + info.Length.ToString());
richTextBox1.AppendText(Environment.NewLine + "Creation Time: " + info.CreationTime.ToString());
richTextBox1.AppendText(Environment.NewLine + "Last Access: " + info.LastAccessTime.ToString());
richTextBox1.AppendText(Environment.NewLine + " **************************** ");
search_for_string(para1);
}
public void search_for_string(string para2)
{
string keywords = "sb_0501_Thu.dmp";
string oradb = "Data Source=sb_1901;User Id=sb_1901;Password=sb00;";
StreamReader sr = new StreamReader(para2);
richTextBox1.AppendText(Environment.NewLine + sr.ReadToEnd());
if (!richTextBox1.Text.Contains(keywords))
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',0,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
else
{
OracleConnection conn = new OracleConnection(oradb);
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "insert into backup_check(REC_ID,OFFICE_CODE,DUMP_NAME,DUMP_STATUS,SYSTEM,CHECK_DATE)values(null,null,'keywords',1,'SBank',sysdate)";
int rowsupdated = cmd.ExecuteNonQuery();
if (rowsupdated == 0)
{ MessageBox.Show("NONE"); }
else
{ MessageBox.Show("Done"); }
conn.Dispose();
}
}
}
}
You refer to ODP.NET version 2.121.2.0. but it seems you have installed Oracle Client 11.2. The versions have to match with each other (at least the major version number)
Open your *.csproj file and set reference of Oracle.DataAccess like this:
<Reference Include="Oracle.DataAccess">
<SpecificVersion>False</SpecificVersion>
</Reference>
Attributes like Version=... or processorArchitecture=... are not required. Your application will load the correct Oracle.DataAccess.dll depending on selected architecture and target .NET framework

Simple C# connection to .accdb file

All I want to do is to retrieve data from tables in .accdb file.
Here is my full application:
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 WindowsFormsApplication1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
OleDbConnection myConn = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:/Microland.accdb;Persist Security Info=False;");
myConn.Open();
OleDbCommand myQuery = new OleDbCommand("select CustID from Customers WHERE CustID = 1;", myConn);
OleDbDataReader myReader = myQuery.ExecuteReader();
if(myReader.HasRows)
{
myReader.Read();
label1.Text = myReader.ToString();
}
myConn.Close();
}
}
}
I think I am missing some using at the very top or my code is somewhat broken becasue then I click the button1 the label1 text changes to System.Data.OleDb.OleDbDataReader.
Also is this the correct way to connect to access data base (.accdb) Do I need to do this walkthrough in order for it to work or this is irrelevant to what I need to do?
Thanks for any information! Very appreciated
When you call myReader.ToString() it returns a string that represents the current object. So "System.Data.OleDb.OleDbDataReader" is exactly that.
It seems like you want the label to be equal to the data that's read. I'm not familiar with this reader in particular, but refer here for documentation.
You'll need to call one of the Get*() functions.
label1.Text = myReader["CustID"] as string; // if nullable field
Or
label1.Text = (string)myReader["CustID"] // if not null

Cannot connect MS Access to C#

I am trying to create a sign-up for our movie database. I am trying to establish a connection from the MS Access that we made. But whenever I run my code, I get an error. I am using Visual Studio Express 2012 C#.
Why does my code trigger this error?
"An unhandled exception of type 'System.Data.OleDb.OleDbException'
occurred in System.Data.dll Additional information: Syntax error in
INSERT INTO statement."
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 BigScreen
{
public partial class sign_up : Form
{
private OleDbConnection connection = new OleDbConnection();
public sign_up()
{
InitializeComponent();
}
private void sign_up_Load(object sender, EventArgs e)
{
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=C:\Users\raizel\Desktop\DataBase\Movie_Database.accdb;
Persist Security Info=False;";
}
private void sign_up_FormClosed(object sender, FormClosedEventArgs e)
{
Form1 thisform = new Form1();
thisform.Show();
}
}
private void button1_Click(object sender, EventArgs e)
{
connection.Open();
OleDbCommand command = new OleDbCommand();
command.Connection = connection;
command.CommandText = "Insert into User ([firstname], [lastname], [username], [password]) values ('" + textBox2.Text + "','" + textBox5.Text + "','" + textBox4.Text + "','" + textBox1.Text + "')";
command.ExecuteNonQuery();
userID++;
MessageBox.Show("Data Saved!");
connection.Close();
}
}
}
User is a reserved word. Bracket it like this to inform the db engine that word is an object name:
Insert into [User] ...
You would be wise to switch to a parameterized query as Bradley hinted but you still need to bracket the reserved word there, too.
User is a reserved word at leat in sql server. You have here in your code some things, you are using concatenation and this is making your code in danger of sql injection, the password can be in clear text in the database you need encryption.
You need to use using in your code to be sure the connection is closed after the insert is complete. If the error throw an exception the connection remain open and you will have problem in future attempts to execute anything. Close your db and make sure you can do an action using the designer and then check your code again.
Try to move to sql server ms access is not a good database for your system.
I made this example using your structure in sql fiddle

Calling class from code behind

I am still new to ASP.net and I'm learning how to call classes. I've looked around for tutorials, but not all are specific to ASP.net 4.0 so I'm not sure if I should apply them.
Right now, I am trying to connect to my SQL database. My webconfig file has been set up with the connectionstring "dbConnectionString" and is working properly when I've tested it with GridViews. What I'd like to do now is access the database from code behind.
I've seen some ways to accomplish this, but I'd like the most efficient, resuable way. I've tried to adopt the answer listed here: How to create sql connection with c# code behind, access the sql server then conditionally redirect? however, I'm getting an error.
I am doing this with C# as a website, not a web application. Here is my code behind for Login.aspx.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using SqlComm; // Is this how I connect to my class from this page????
public partial class Login : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
}
protected void btnSubmit_Click(object sender, EventArgs e)
{
if (Page.IsValid)
{
//no code written yet
}
}
}
My class in the App_Code folder, file name SQLComm.cs:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Data;
using System.Data.SqlClient;
using System.Web;
/// <summary>
/// SQL Query class
/// </summary>
public class SqlComm
{
// Connection string
static string DatabaseConnectionString = System.Configuration.ConfigurationManager.ConnectionStrings["dbConnectionString"].ConnectionString;
// Execute sql command with no value to return
public static void SqlExecute(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
cmd.ExecuteNonQuery();
}
}
// Execute SQL query and return a value
public static object SqlReturn(string sql)
{
using (SqlConnection conn = new SqlConnection(PjSql.dbcs()))
{
conn.Open();
SqlCommand cmd = new SqlCommand(sql, conn);
object result = (object)cmd.ExecuteScalar();
return result;
}
}
// Retrieve an entire table or part of it
public static DataTable SqlDataTable(string sql)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Connection.Open();
DataTable TempTable = new DataTable();
TempTable.Load(cmd.ExecuteReader());
return TempTable;
}
}
// Execute a stored procedure with 1 parameter
// Returning a value or just executing with no returns
public static object SqlStoredProcedure1Param(string StoredProcedure, string PrmName1, object Param1)
{
using (SqlConnection conn = new SqlConnection(DatabaseConnectionString))
{
SqlCommand cmd = new SqlCommand(StoredProcedure, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter(PrmName1, Param1.ToString()));
cmd.Connection.Open();
object obj = new object();
obj = cmd.ExecuteScalar();
return obj;
}
}
}
As you can see, I haven't written any code to actually use the class yet, but the "using SQLComm;" line itself is giving me this error:
Compiler Error Message: CS0246: The type or namespace name 'SqlComm' could not be found (are you missing a using directive or an assembly reference?)
As I'm still new, I'm unsure where to go from here. I seem to have included everything contained in the answer on the page I linked above. What else and I missing?
Edit: I read this post regarding a similar issue: asp.NET 2.0 Web Site Can't Access Classes in App_Code
Could this be because I am doing a website and not a web application, so the App_Code folder is being handled differently when I FTP the files over?
using SQLComm means you want to use the namespace SqlComm, which doesn't exist. I think what you want is (somewhere in your codebehind):
DataTable dt = SqlComm.SqlDataTable(...) // call one of the static methods.
You can call it directly.
Given your class has static methods only you'll call it like this:
SqlComm.SqlReturn("select * from table");
So I believe I figured it out. I had my App_Code folder within the subdirectory of my Aspx website, instead of in the root of the server. I moved the folder to the root and now it's working.
I'd be interested in hearing any answers to my edit to my original post though. Since I'm doing this as a website instead of a web application, are there any other issues I will need to keep in mind regarding using classes like this or other issues? I've looked around but haven't seen many differences.
Thanks to everyone for you help!

removing form from c# code?

I'm extremely new to C# and programming anything except for SQL. I've gotten the below code to happen on a Form and on a button click. If I wanted to just make this run on open, how would I do that? I'm very new to C# as you can tell (just started today learning it but its pretty exciting!)
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 Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace OraTrigger
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void button1_Click(object sender, EventArgs e)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
OracleConnection conn = new OracleConnection(oradb); // C#
conn.Open();
OracleCommand cmd = new OracleCommand();
cmd.Connection = conn;
cmd.CommandText = "SELECT cast(Count(*) as varchar(20)) as trig FROM ZDMSN.TRIGGER_TEST";
//cmd.CommandType = CommandType.Text;
OracleDataReader dr = cmd.ExecuteReader();
dr.Read();
int cnt;
if (int.TryParse(dr.GetString(0), out cnt))
{
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
}
}
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
conn.Dispose();
}
}
}
If you need to run your code as a scheduled task then a command line application is more suitable.
Just create a new project and select Console Application.
Then move all of your button click code inside the Main method written for you by the Visual Studio IDE.
Rembember to set the references to the Oracle ODP.NET library and import the relevant using statements
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Oracle.DataAccess.Client; // ODP.NET Oracle managed provider
using Oracle.DataAccess.Types;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
string oradb = "Data Source=OMP1;User Id=user;Password=pass;";
using(OracleConnection conn = new OracleConnection(oradb))
using(OracleCommand cmd = new OracleCommand("SELECT Count(*) as trig FROM ZDMSN.TRIGGER_TEST", conn))
{
conn.Open();
int cnt = (int)cmd.ExecuteScalar();
if (cnt > 0)
{
System.Diagnostics.Process.Start(#"C:\testfile.bat");
cmd.CommandText = "TRUNCATE TABLE ZDMSN.TRIGGER_TEST";
cmd.ExecuteNonQuery();
}
}
}
}
}
I have also revised your code to get a single value from the database. For this case is enough to use the Command.ExecuteScalar method that returns the first column of the first row obtained from your sql command text. Because the count(*) should Always return a single row you could easily cast the return value of ExecuteScalar to your record count variable.
EDIT I have added the logic to TRUNCATE the table involved. Please pay attention that you should use the code provided here. Your code will probably fail because you have an open DataReader and when a DataReader is open you cannot execute other commands (This is true for SqlServer without Multiple Active Result Sets enabled, I really don't know if this rules applies also to the Oracle NET Provider)
Subscribe to Shown or Load event of form and move your code to that event handler.
Form.Shown Event Occurs whenever the form is first displayed.
Form.Load Event Occurs before a form is displayed for the first time.
Also I suggest to extract your code to some Data Access related class, or at least to separate method. And call that method from event handler.

Categories

Resources