|
Use a SqlCommand and insert parameters into the command.
like this:
public static String GetUser(String userId)
{
SqlConnection connection = new SqlConnection();
String sqlQuery = "SELECT userName FROM Users WHERE UserId = @UserIdParameter";
SqlCommand command = new SqlCommand(sqlQuery, connection);
command.Parameters.Add(new SqlParameter("@UserIdParameter", userId));
using (SqlDataReader reader = command.ExecuteReader())
{
if (reader.HasRows)
{
return reader.GetString(0);
}
else
{
return String.Empty;
}
}
} This means that your caller can't inject sql in because they only have control over the parameter and because it's a parameter, when it the query is executed, the parameter will be validated and surrounded with quotes and any command characters will be removed to prevent injection attacks.
Read more here:
SQL Injection Attacks and Some Tips on How to Prevent Them[^]
Simon
|
|
|
|
|
Hi Simon,
Thanks for giving sample program. I'll try this one.
By the way, Can you look at the code below. That is my clsConnection where i execute my queries. Is it safe? And can you point out in my code if there is something bad code.
This is the way i used it.
E.g.
clsConnection myConn = new clsConnection();
DataTable DT = new DataTable();
string SQL = "SELECT * FROM tblUsers";
DT = myConn.ExecuteQuery(SQL);
using System;
using System.Data;
using System.Collections.Generic;
using System.Text;
using System.Data.SqlClient;
using System.Collections;
using System.Windows.Forms;
namespace Micromix.Class
{
class clsConnection
{
public SqlConnection objConnection;
SqlTransaction objTransaction;
public bool SqlConnect()
{
try
{
objConnection = new SqlConnection();
objConnection.ConnectionString = Connect.ConnString.ToString();
if (objConnection.State == ConnectionState.Closed)
objConnection.Open();
return true;
}
catch (Exception ex)
{
MessageBox.Show("Failed to connect to data source.", "Connect Failed", MessageBoxButtons.OK, MessageBoxIcon.Warning);
MessageBox.Show(ex.Message);
return false;
}
finally
{
objConnection.Close();
}
}
public DataTable ExecuteQuery(string strSQL)
{
DataTable objDataTable;
SqlDataAdapter objDataAdapter;
try
{
SqlConnect();
objDataAdapter = new SqlDataAdapter();
{
objDataTable = new DataTable();
objDataAdapter.SelectCommand = new SqlCommand(strSQL, objConnection, objTransaction);
objDataAdapter.Fill(objDataTable);
return objDataTable;
}
}
catch (Exception sqlex)
{
throw sqlex;
}
finally
{
objDataAdapter = null;
}
}
public void ExecuteNonQuery(string strSQL)
{
SqlCommand objSqlCommand;
try
{
SqlConnect();
objSqlCommand = new SqlCommand(strSQL, objConnection);
objSqlCommand.Connection.Open();
objSqlCommand.ExecuteNonQuery();
}
catch (SqlException ex)
{
throw ex;
}
finally
{
objSqlCommand = null;
}
}
public bool ExecuteNonQuery(string strSQL, SqlParameter[] sqlparams)
{
try
{
int intindex;
SqlCommand objsqlcommand = new SqlCommand(strSQL, objConnection, objTransaction);
for (intindex = 0; intindex <= sqlparams.GetUpperBound(0); intindex++)
{
objsqlcommand.Parameters.Add(sqlparams[intindex]);
}
objsqlcommand.ExecuteNonQuery();
return true;
}
catch (Exception ex)
{
throw ex;
}
}
}
}
Thanks and Regards
klaydze
if(you type your code here) {
Messagebox.Show("You help me a lot!");
}
else {
You help me = null;
}
|
|
|
|
|
Hi All
I am creating an application which takes some SQL code into a rich text box, with Syntax highlighting. I have inherited the Rich Text Box and put my word recognition code in here. The problem I have is that when ever the syntax highlighting code runs, the whole rich text box flickers annoyingly.
Does anybody know how to stop this flickering?
Thanks in advance.
oooo, the Jedi's will feel this one....
|
|
|
|
|
Here is the solution [^]
Cheers!
Nuri
|
|
|
|
|
That was just what I was needing. Cheers...
oooo, the Jedi's will feel this one....
|
|
|
|
|
Hi...
I have to call a csharp function in Java.
Can somebody give me a small example of how to do this.
Please do help me out.
Thnx.
|
|
|
|
|
Ask a question ONCE. Posting in multiple forums is guaranteed to annoy.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
I'm sorry i wasn't sure if the question was to be posted in C# section or Java section.
|
|
|
|
|
since the code you will be writing is Java the Java forum is the right one
|
|
|
|
|
On top of Tom's answer, it doesn't mater in this instance too much which you had chosen to start with. But you should have posted only once.
Panic, Chaos, Destruction.
My work here is done.
|
|
|
|
|
hi,could some one help me with my problem...
i'm trying to get the changes or modifications a specific process on my computer has made, i know how to do it in opposite side < i mean knowing what is happening now in registry ,or what files modified,but not telling who did it>... i found a program donig that but i want to do it<by the way : i'm using c# .net 2008>
can someone tell me how i can do that?
|
|
|
|
|
Hi,
I have this problem with C# socket server that's talking to a perl client. When I run the server and run the perl client with "perl client.pl commandtoexecute" the server executes the command displaying it on the server console and then crashes with this error:
Unhandled Exception: System.IO.IOException: Unable to read data from the transpo
rt connection: An existing connection was forcibly closed by the remote host. --
-> System.Net.Sockets.SocketException: An existing connection was forcibly close
d by the remote host
at System.Net.Sockets.Socket.Receive(Byte[] buffer, Int32 offset, Int32 size,
SocketFlags socketFlags)
at System.Net.Sockets.NetworkStream.Read(Byte[] buffer, Int32 offset, Int32 s
ize)
--- End of inner exception stack trace ---
I know I am not handling the error correctly, but I have no idea how do I go about fixing this. Any ideas? here is the code for the method that is handling the client connections:
public void HandleConnection()
{
int recv;
byte[] data = new byte[2048000];
TcpClient client = threadListener.AcceptTcpClient();
NetworkStream ns = client.GetStream();
connections++;
Console.WriteLine("New client accepted: {0} active connections", connections);
string welcome = "Welcome to power shell server ... ";
data = Encoding.ASCII.GetBytes(welcome);
ns.Write(data, 0, data.Length);
while (true)
{
data = new byte[2048000];
recv = ns.Read(data, 0, data.Length);
if (recv == 0)
break;
else
{
String cmd = Encoding.ASCII.GetString(data, 0, recv);
Console.WriteLine(cmd);
//Console.WriteLine(Encoding.ASCII.GetString(data, 0, recv));
//ns.Write(Encoding.UTF8.GetBytes(RunShell(cmd)), Convert.ToString((RunShell(cmd))).Length, 10000000);
// Execute incoming shell command and convert the string data to byte data using ASCII encoding.
byte[] byteData = Encoding.ASCII.GetBytes(RunShell(cmd));
// Begin sending the data to the remote device.
if (byteData.Length > 0)
ns.Write(byteData, 0, byteData.Length);
else
{
Console.Write("\nData Length is less than 0");
ns.Write(data, 0, recv);
}
}
}
ns.Close();
client.Close();
connections--;
Console.WriteLine("Client disconnected: {0} active connections", connections);
}
|
|
|
|
|
Probably you get the exception in this line:
recv = ns.Read(data, 0, data.Length);
If yes, then the remote host just disconnect you.
|
|
|
|
|
Thanks for the reply. Actually the server is crashing at:
ns.Write(byteData, 0, byteData.Length);
Because after this is executed, the client has received the data and it closes the connection - I don't know if I have to catch an exception here? I am not good with exceptions. Also, I am closing the network stream here with ns.Close() and the server is still crashing. I am confused.
|
|
|
|
|
Hi,
I have string "[Font: Name=Microsoft Sans Serif, Size=20, Units=3, GdiCharSet=1, GdiVerticalFont=False]",
how can i convert it as Font or how to assign this to a Font.
Thankyou
YPKI
|
|
|
|
|
you need to parse it using string.split and then check the NVP and assign them to a font class
|
|
|
|
|
try FontConverter class. It may help you
|
|
|
|
|
Sorry, but this string can not converted to font!
I use split function instead!
and :
Font F=new Font(params)
|
|
|
|
|
Hi All,
I have browse button to select a .hex file, this file name should always have 3 underscores and .hex as extention (for eg. TestHex_1_1_1.hex). I had written a code by using split & it works. But if foldername contains any underscore then it will not work.
This is my code.
private void btnOpenFolder1_Click(object sender, EventArgs e)
{
openFileDialog1.ShowDialog();
openFileDialog1.ValidateNames = true;
textBox1.Text = openFileDialog1.FileName;
char[] cr ={ '_' };
string[] str = textBox1.Text.Split(cr);
if (str.Length != 4 || textBox1.Text.Substring(textBox1.Text.LastIndexOf("."), 4).ToLower() != ".hex")
{
textBox1.Text = "";
MessageBox.Show("File name or file extention is not valid.");
}
hexPath = textBox1.Text;
}
Please give me any suggestion.
|
|
|
|
|
Check out System.IO.Path which has methods for getting extention from a path as well as filename from a path.
|
|
|
|
|
Hello.
I'm Reading data from an excel (CSV) file with header row and its fine.
Now I have a file with one more line in the start (above the header) and it giving me a lot of problems.
is there a way from C# to open the csv file and remove the first line?
If not as excel then maybe I'll just open it as a text file and remove it (I know whats the string I want to remove).
Whats the fasted way to remove a string from the beggining of a txt file?
Thanks.
|
|
|
|
|
polycom123 wrote: is there a way from C# to open the csv file and remove the first line?
Easy. File.ReadAllLines, to get an array of strings, then write the file over itself, skipping the lines you don't want anymore
Christian Graus
Driven to the arms of OSX by Vista.
"I am new to programming world. I have been learning c# for about past four weeks. I am quite acquainted with the fundamentals of c#. Now I have to work on a project which converts given flat files to XML using the XML serialization method" - SK64 ( but the forums have stuff like this posted every day )
|
|
|
|
|
Or better, write it into a new file, so it doesn't mess up Excel and other users?
No trees were harmed in the sending of this message; however, a significant number of electrons were slightly inconvenienced.
This message is made of fully recyclable Zeros and Ones
|
|
|
|
|
I can't do that since I need to countinu working on the same file with others.
Taht another thinh I was afried of, that if I'll read and write it will mass up my original file
Thats why I hoped that C# will have a built in function for this.
Thanks for your reply.
|
|
|
|
|
Hi christian,
Thakns for the replay.
I was hopping that C# have a built in function to work with excel and do this instead of me having to read a file with a lot of data (about 7,000 line with 10 column each).
But like I was afried, I might have no other choise other that read the whole file and write it back.
Thanks.
|
|
|
|