|
True, but that's pretty pointless in reference to what Dave wrote. This type of declaration works best when you want to catch specific exceptions (besides the base Exception class), whether or not you declare an exception variable (I know you know that, leppie, I'm just explaining it to the poster if he manages to read it).
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Actually, it will catch the Exception. Try it...
try
{
System.IO.Directory.SetCurrentDirectory(@"Z:\testme");
}
catch
{
MessageBox.Show(@"Exception caught!");
}
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
I think I know why I thought that.
Was running a console app, and waiting for some output in the VS.NET Output console.
~leppie()
top secret xacc-ide 0.0.1
|
|
|
|
|
Hi All,
Just a simple question. I am trying to add the data in a access database (file residing on local machine.) I saw the format and worked according to it. Here is the code.
Console.WriteLine(CBoxCatagory.SelectedItem.ToString());
String sSql = "INSERT INTO MainCatagory" + "(MainCatagory)" + "VALUES("+CBoxCatagory.SelectedText+")" ;
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;" +@"Data source= C:\" + @"My Documents\db1.mdb";
conn.Open();
OleDbCommand objCommandMain = new OleDbCommand(sSql,conn);
objCommandMain.ExecuteNonQuery();
When I use the fixed or hard data in Values then statement executes fine. But when I am trying to execute with a variable of type ComboBox then it is giving me error. I also tried to use a simple string variable and see the result and it was same. Seems like there is problem in the syntax for adding values using variables.
Here is the error.
An unhandled exception of type 'System.Data.OleDb.OleDbException' occurred in system.data.dll
Can you suggest me something on this one.
Thanks,
|
|
|
|
|
OK, the first thing I notice is that you're doing a lot of unnecessary string concatenation. The second thing I see is that your CBoxCatagory.SelectedText value is not surrounded in quotes, for the sake of SQL. Try this:
tring sSql = "INSERT INTO MainCatagory (MainCatagory) VALUES('" + CBoxCatagory.SelectedText + "')";<br />
conn.ConnectionString = @"Provider=Microsoft.Jet.OLEDB.4.0;Data source=C:\My Documents\db1.mdb";<br />
...
Regards,
Alvaro
Give a man a fish, he owes you one fish. Teach a man to fish, you give up your monopoly on fisheries.
|
|
|
|
|
I tried that but it did not work. Then I replaced CBoxCatagory.SelectedText with fix text as Onemore.
It worked fine.
One more thing i observed with my database is that Table Maincatagory has 2 colums. One is maincatagory and other AutoIncrement. When I try to execute the statement with CBox it fails but it increses the AutoIncrement count.
Now does this mean that script is failing in database at insert point bcoz data coming in has wrong format. But I think the format is text so it should not fail anyways.
Any suggestions.
|
|
|
|
|
The SelectedText property of a ComboBox is the selected text in the editable portion of the box. In some cases, SelectedText can return null , especially if your ComboBox is setup with its DropDownStyle set to ComboBoxStyle.DropDownList . Use SelectedItem.ToString() instead.
This could have been easier to diagnose had you been using parameterized queries instead of string concantenations...
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
I tried that too!
In Fact, I also tried something like this.
String firstString = "ABCCD";
and then used this firstString Var in place of ComboBox var.
Thanks,
|
|
|
|
|
Like I said... Parameterized queries would have fixed this problem from day 1. Using the parameterized version, you don't have to worry about how the strings are escaped in the SQL statement and if there are any special characters in the string that you pass that will screw up the statement syntax. All of that is handled for you, automatically!
There is no reason to NOT use them!
Everything we told you will work under normal circumstances. There is something else you're not telling us, that may seem like a small detail that doesn't mean anything, but makes one hell of a difference to SQL.
RageInTheMachine9532
"...a pungent, ghastly, stinky piece of cheese!" -- The Roaming Gnome
|
|
|
|
|
Though I am kind of new to C# and I exactly dont know the syntax to use parameterized queries, I will try to learn that. Meanwhile, After your stress on nothing wrong in suggestions, I tried to use the same statement in Form Load method and to my surprise it worked. Then I copied same exact statement into Button_Click function (where I was trying previosuly ) and it worked too.
I dont get C# for this. I was always using rebuild for project before attempting any try.
Can you explain this.
|
|
|
|
|
Look at the documentation for the OleDbCommand.Parameters property. It explains it quite well and gives you examples. Using parameterized queries is highly recommended in ADO.NET because it checks for common security holes and eliminates the need to escape single and double quotes. It's also the only way to import binary data, like when using SqlDbType.Image .
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Stupid Question:
Scenario:
Need to passé Reference data to my IO engine. It opens-Sends-Closes or it Opens-Listens and sends data to User in call back when data is received, then closes. A pointer that can't be global would be perfect, but C# so ref to data would have to suffice. The ref has all the data to run the engine it self. The IOClass has the engine witch intern uses and API wrapper class for win32 IO functions.
Conundrum:
How do I get the managed ref to go through the win32 IO call back so the IO state engine will work?
Note – the Data object must be pointer for win32 and must be able to be read after the IO is complete by the managed C# code. There have been many articles on the IO functions in question, but now one has solved this as far as I have seen.
Class Guy Winslow
{
public:
WINcontrols
H: 925-606-1091
M: 925-922-0222
gdwinslow@wincontrols.com
};
|
|
|
|
|
It's a little difficult to follow your post, but I'll try...
You're saying the callback function exist in win32 then P/Invoke the callback, create a delegate of the property type in managed code, and create the delegate that points to the P/Invoke call. If you already have a delegate and the P/Invoke'd method and the delegate signatures don't quite match up (may you need to do some custom marshaling, although this case is best solved with an ICustomMarshaler implementation), then define a method which has the right signature and calls the P/Invoke'd win32 callback function.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
I think i understand what you are talking about. And I thing I am doing this. Sari for mi ignorance new to .NET. This structure my explain better:
[StructLayout(LayoutKind.Sequential)]
public unsafe struct OVERLAPPED
{
public int Internal;
public int InternalHigh;
public int offset;
public int OffsetHigh;
public int hEvent;
public Socket *socket;
}
It’s defined in my API Interface class. This needs to be LocalAlloc, and passed to the ReadFileEx function. This works fine without the Socket pointer, witch is or should be a “ref Socket” to a managed class in C#. I can’t seam to passé it into the OVERLAPPED Structure so the File IO callback can use it to get rest of data and set error info. This socket class instance is created by responses to messages it receives, vary much like Window Sockets. Except it’s our device and not network device. Note - callback must be static. So am I not understanding how you are suggesting to use the P/Invoke or is there something else you guys can suggest.
Class Guy Winslow
{
public:
WINcontrols
H: 925-606-1091
M: 925-922-0222
gdwinslow@wincontrols.com
};
|
|
|
|
|
The Socket class wouldn't work even if it wasn't pinned - it doesn't have a representation in unmanaged code. Instead, you typically declare handles as IntPtr s, and use the Marshal class methods to help with marshaling values. You rarely ever need an unsafe context, either.
In this case, however, you must pin the Socket in memory. There is a chance that the garbage collector (GC) will move the object in managed memory while the unmanaged code is using it. Unmanaged code is just that - unmanaged - so it can't track such changes. Pinning the object in memory will also give you the IntPtr you need. Try something like this, for example:
[StructLayout(LayoutKind.Sequential)]
public struct OverlappedSocket : IDisposable
{
public OverlappedSocket(long internal, long internalHigh, int offset,
int offsetHigh, Socket socket)
{
this.Internal = new IntPtr(internal);
this.InternalHigh = new IntPtr(internalHigh);
this.Offset = offset;
this.OffsetHigh = offsetHigh;
hEvent = GCHandle.Alloc(socket, GCHandleType.Pinned);
}
[MarshalAs(UnmanagedType.SysUInt)] public IntPtr Internal;
[MarshalAs(UnmanagedType.SysUInt)] public IntPtr InternalHigh;
[MarshalAs(UnmanagedType.U4)] public int Offset;
[MarshalAs(UnmanagedType.U4)] public int OffsetHigh;
[MarshalAs(UnmanagedType.SysUInt)] public GCHandle hEvent;
void IDisposable.Dispose()
{
if (hEvent.IsAllocated) hEvent.Free();
}
}
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Cool. I was playing with Marshal Attributes last night. That gets me half way there. How do I convert CGHandle back into the Socket class without duplicating it?
unsafe public static void ReadOperation(System.Int32 dwErrorCode, System.Int32 dwNumberOfBytesTransfered, ref CtrlNet_Api.OverlappedSocket lpOverlapped)
{
ref Socket socket = lpOverlapped.hEvent;
}
With my device I am getting chucks of data. So information in the Socket is being changed as Engine runes. When dune or ERRORs out. I set flag in the Socket class for Application to see status, and Trigger and Event for Calling Thread. Tried to get AddrOfPinnedObject but could not find way to cast it as Socket class.
Class Guy Winslow
{
public:
WINcontrols
H: 925-606-1091
M: 925-922-0222
gdwinslow@wincontrols.com
};
|
|
|
|
|
Again, don't use an unsafe context - you don't need it. The best examples of use for unsafe contexts is when it's faster to use pointers to iterate through characters, pixels, etc.
You don't get the Socket from the GCHandle . All the GCHandle does - the way I said to use it - is pin the Socket in memory so unmanaged code doesn't lose a reference to it in case the GC moves it (which it can do). You can still refer to the Socket in managed code just as you are now. Using the IntPtr cast operator or AddrOfPinnedObject method only gets the fixed pointer to the object for use in P/Invoke'd method calls. It doesn't change it as far as managed code is concerned.
Read about the GCHandle structure in the .NET Framework SDK.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Ok, I got it. I must be getting old. Senility is kicking in. I was looking at the documents and the answer was staring at me. So my code should look like this right:
public static void ReadOperation(System.Int32 dwErrorCode, System.Int32 dwNumberOfBytesTransfered, ref CtrlNet_Api.OverlappedSocket lpOverlapped)
{
GCHandle ghSocket = lpOverlapped.hEvent;
Socket socket = (Socket)ghSocket.Target;
}
I hope this is good for some kind of article or something using C# with Win32 OVERLAPED IO functions (USB).
Addition:
I tryed the solution and got "Additional information: Object contains non-primitive or non-blittable data." this error message. Any ideas?
Class Guy Winslow
{
public:
WINcontrols
H: 925-606-1091
M: 925-922-0222
gdwinslow@wincontrols.com
};
|
|
|
|
|
It really depends on how this is used, but again - you don't need to get the Socket back if you already have it. If you instantiated the Socket in your code (obviously you did), then you already have a reference. You only use the GCHandle for the purpose of calling unmanaged APIs. The original Socket reference that you passed to GCHandle.Alloc is still valid - all you did was pin it into memory (depending on how you used the GCHandle ) so that it wouldn't be moved by the GC while being used in unmanaged code.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
as i know, if we wanna deal with blob, we may use the image data type.
but my problem is, how can i insert the bytes to the database?
i have tried the following codes but it doesn't work
byte[] photo = GetPhoto(photoFilePath);
.
.
.
SqlCommand addPic = new SqlCommand ("INSERT INTO photoTable Values(" + photo + ")");
.
.
.
public static byte[] GetPhoto(string filePath)
{
FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
byte[] photo = br.ReadBytes((int)fs.Length);
br.Close();
fs.Close();
return photo;
}
thanks
|
|
|
|
|
Use parameterized queries, which is better to use anyway that concatentating strings together, which is error prone and can lead to security holes if you don't check user input correctly (parameterized queries have many other benefits over what you're doing, which is the old, insecure way).
SqlCeCommand addPic = conn.CreateCommand();
addPic.CommandText = "INSERT INTO photoTable (Photo) VALUES(@Photo)";
SqlCeParameter picParam = addPic.Parameters.Add("@Photo", SqlDbType.Image);
picParam.Value = GetPhoto(photoFilePath); This query is much less prone to error and makes binary data possible to work with, unlike string concatenation.
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Hi all, I am experiencing a problem and I am not sure how to go about fixing it. I have an ASP.net app that is reading from a database. I have a default database file path hardcoded into my program that the program will use if the user does not specify a database file. When executed, if the program tries to access the default database it is failing. It seems like .net is adding a "C:" to my file path where it should be "\\dir1\\dir2\\DB.mdb" Can anyone help me out so that I can access the default database on the LAN. Thanks again
|
|
|
|
|
NEVER hard code a file path. Put the filepath in the appSettings section at the bottom of the Web.config file and use ConfigurationSettings.AppSettings to get it (defaulting to a hard-coded path if you like). When you do it this way, do not escape back-slashes (that's specific to a programming language - not strings).
If you want to use a file from a share, then use "\\\\SERVER\\SHARE\\Dir1\\DB.mdb" or @"\\SERVER\SHARE\Dir1\DB.mdb" (notice the @ , which is a literal character identifier).
Many of the IO members - unless you give them a URL - will assume a local path, which is why "C:" is being prepended to your string (well, the string isn't actually changed but the behavior is the same).
If this file is in your virtual directory structure of your web application, 1) make sure it's protected from user's downloading it but so that the web application can access it, and 2) use Server.MapPath or Page.MapPath to map the virtual path (like /db/db.mdb) to a physical path (like C:\Inetpub\wwwroot\db\db.mdb).
Microsoft MVP, Visual C#
My Articles
|
|
|
|
|
Updating database with changes to dataset on Form Closing
Here is my form closing method:
private void DivFrmClosing(object sender, System.ComponentModel.CancelEventArgs e)
{
int i;
if (dataSet11.HasChanges())
i = dbUpdate(); // method to update table
...
}
Row of data gets updated only when a new row has been added(focus is lost from that row)!!
How do I get around this to accomodate update of a row even when focus is not lost from current row?
|
|
|
|
|
You have to use DataGrid.EndEdit with the appropriate cell information:
DataGridCell cur = dataGrid1.CurrentCell;
DataGridColumnStyle col = dataGrid.TableStyles[0].GridColumnStyles[cur.ColumnNumber];
dataGrid1.EndEdit(col, cur.RowNumber, false); You should add proper error checking and handling, of course. This is only an example. Read the .NET Framework SDK documentation for the classes and members used in the example for more information.
Microsoft MVP, Visual C#
My Articles
|
|
|
|