I have the following c# code in a WPF app:
var command = new OleDbCommand($"CREATE INDEX idx{index.ColumnName} ON {tableConfig.Name}({index.ColumnName})", _targetCon);
try
{
command.ExecuteNonQuery();
}
catch (Exception ex1) { _serilog.WriteError(METHOD_NAME, "Trouble adding index onto Access column", ex1); }
My problem is that when stepping through the code in the VS debugger, the line "command.ExecuteNonQuery();" is throwing an exception. At the time of the exception, the value of _targetCon.ConnectionString is "Provider=Microsoft.Jet.OleDb.4.0;Data Source=C:\AccessDatabases\APMS\unit3.mdb;" and the value of the _targetCon.DataSource is: C:\AccessDatabases\APMS\unit3.mdb This is the correct path. However, the value of ex2.Message is "Could not find file 'C:\Git_RB\AccessMigration\AccessLauncher\AccessLauncher.WPF\bin\Debug\Unit3.mdb'"
If I run the app outside of VS then I find that it's still trying to find the file in the database in the same folder as the exe:
Why is the command object ignoring the properties of its connection object and looking in the wrong path?
Check the actual value of the SQL statement that you are using. It might contain another table name than the one you expect, e.g. due to string truncation.
Related
I'm really struggling with saving data to my local network NAS (a Synology DS214 if that matters).
I need to store some files in my network folders after creating them in another part of my program, but I haven't been able to handle the authentication/permissions properly.
My code atm is this:
WrapperImpersonationContext WIContext =
new WrapperImpersonationContext("\\\\DiskStation", "admin", "admin");
try
{
WIContext.Enter();
// code to select the final path simplified.
string fileName = "file.txt";
string originalPath = Environment.GetFolderPath(
Environment.SpecialFolder.MyDocuments);
originalPath= Path.Combine(new string[] {originalPath, fileName});
string finalPath = "\\\\DiskStation\\Virtual\\DestFolder";
if (!Directory.Exists(finalPath))
{
// This goes well for whatever reason
Directory.CreateDirectory(finalPath);
}
finalPath = Path.Combine(new string[] {finalPath, fileName});
// This fails for wrong username/password
File.Move(originalPath, finalPath);
} catch (Exception ex)
{
// Exception showing simplified here
MessageBox.Show(ex.ToString());
throw;
} finally
{
WIContext.Leave();
}
The code used for the WrapperImpersonationContext I found here:
WindowsImpersonationContext made easy
As written in my code when I try to move the file I get an UnauthorizedAccessException: Access to the path is denied. I also tried to create a new file in the network folder with the same results.
While looking at the Michiel Vanotegem's code linked above, I discovered that I get an authentication error calling the LogonUser function (error code 1326 that gets me a Win32Exception (0x80004005): The user name or password is incorrect).
I tried to use the WNetUseConnection function looking at this and this pages but while I get no error from the function (after substituting it in the Michiel code), when I try to move the file I get the same UnauthorizedAccessException: Access to the path is denied.
I also tried to fiddle with the domain passed to the Impersonation Wrapper but I couldn't seem to make it work. I feel like I'm missing something... Can someone kindly point me to the right direction or help me with this issue?
Ty all who contributes in advance.
Edit 15/12/2017 11:52: I discovered that if I try to rerun the LogonUser function immediately after the first error I get a different exception (error 87 Win32Exception (0x80004005): The parameter is incorrect)
I followed on #LennartStoop suggestion, so I enclosed my code in a using block instead of a try finally using the code I borrowed from this answer:
using (NetworkConnection netConn =
new NetworkConnection("\\\\DiskStation", new NetworkCredential("admin", "admin")))
{
// My code here
}
Using this I've been able to establish a connection the network folder and perform all the IO operation I needed so ty very much for the tip Lennart :)
Simply put i added a new form to my program to see the data directly instead of just manipulating though SQL. well when i add the data set. and it does work in the designer perfectly but when i go to build it it erros out
Severity Code Description Project File Line
Error CS0426 The type name 'Db12DataSet' does not exist in the type 'AllianceERP' AllianceERP C:\Users\dhelm.ALLMATINC.001\Documents\Visual Studio 2013\Projects\AllianceERP\AllianceERP\Form2.Designer.cs 230
the line it is referencing is private AllianceERP.Db12DataSet db12DataSet;
with redline under db12DataSet
and i think that the problem is that db12data set isnt in that location but is in another location ? My connection string is right and tested #
connection.ConnectionString = #"Provider=Microsoft.ACE.OLEDB.12.0;Data Source=S:\Documents\2015\Db12.accdb";
Where have I gone wrong or is my thinking just off?
I've encountered a problem when I try to retrieve the valid states of all features within an MSI package using the Microsoft.Deployment.WindowsInstaller.Installer class.
I want to copy the ValidStates property of each FeatureInfo within a Session. However when doing so I get a "Handle is in an invalid state." exception.
If I print each of these values out using Console.WriteLine() or step through the code in Visual Studio there is no exception.
I am at a loss as to what is preventing me from doing this.
Thanks in advance!
My Code:
var featureDictionary = new Dictionary<string, string[]>();
if (string.IsNullOrWhiteSpace(mPath))
return featureDictionary;
try
{
Installer.SetInternalUI(InstallUIOptions.Silent);
using (var session = Installer.OpenPackage(mPath, true))
{
foreach (var feature in session.Features)
{
try
{
var states = feature.ValidStates.Select((state) => state.ToString());
featureDictionary.Add(feature.Name, states.ToArray());
}
catch (InstallerException ex)
{
Debug.WriteLine(ex.Message);
}
}
}
}
catch (InstallerException) { }
return featureDictionary;
The basic problem appears to be that you are opening the MSI as a file. Since you haven't posted its declaration, or how it is set, I'm assuming that mpath means it's a path to the file. Your OpenPackage method parameters seem to indicate this too. You're getting that error because you are trying to open the MSI file as a file during the actual install, and failing.
The way to get hold of the database for the running install is to use Session.Database.
You can't open the running MSI as a file during the install perhaps for the same reason you can't run an MSI file that you have open with Orca, a simple file sharing violation. When you step through with Visual Studio you're simply accessing the static file and getting default values and the file isn't being used for an install. The other issue is that there can only be one Session object per process (as the OpenPackage docs say) and you are attempting to get a second one while there is already a Session object associated with the handle of the install.
As a custom action it needs to be sequenced after CostFinalize.
Windows Installer conditional expressions such as !feature-state will tell you what state the feature is in, because it's usually better to avoid code where Windows Installer will just give you the answer.
I'm still new in c# Please help me. I was trying to save images in database, for that i did this as suggested in my researches:
byte[] img = ImageToByte(pbxBarcode.Image);
byte[] img2 = ImageToByte(pbxLogo.Image);
cmd.CommandText = "Update table set Image=(?),logo=(?) where ID=" + id + "";
cmd.Parameters.Add("#barcode", OdbcType.Image).Value = img;
cmd.Parameters.Add("#logo", OdbcType.Image).Value = img2;
cmd.ExecuteNonQuery();
the first data entered will be saved as intended but the program freezes(?) . with that, i mean no EventHandler will fire but objects are still functional, textboxes still accepts input, etc. then if i browse away of the form then return, the error appears in Program.cs saying "Parameter is not Valid". I provided a screenshot.
also note that if i only provided one odbcParameter.. all if working fine.. I also tried using two Update statements.. even created two functions for each, updatebarcode(id), updatelogo(id) but still no luck. I hope you can help me. tnx
If you using sql server you can use SqlCommand. Here is documentatio with example. From documentation: The Microsoft .NET Framework Data Provider for SQL Server does not support the question mark (?) placeholder for passing parameters to a SQL Statement or a stored procedure called by a command of CommandType.Text
So what you may want to use:
cmd.CommandText = "Update table set Image=(#barcode),logo=(#logo) where ID=#imageID";
cmd.Parameters.Add("#barcode", SqlDbType.Image).Value = img;
cmd.Parameters.Add("#logo", SqlDbType.Image).Value = img2;
cmd.Parameters.Add("#imageID", SqlDbType.Int).Value = id;
Also like others mentioned you getting exception in Program.cs because you didn't handled exception anywhere else.
If you do something like this:
try
{
cmd.ExecuteNonQuery();
}
catch(Exception exc) //<==
{
}
Visual Studio will break at the place where arrow shows. At this point you can analyse exc and you will see error message and stack trace (the thing Jon Skeet was talking about)
I Got it .. I think found the error here on the button click event. not sure why:
pbxLogo.Image.Dispose(); //here..
pbxLogo.Image = pbxSelectLogo.Image;
but i remove that line and it just worked.. hehe
this is the exception:
System.ArgumentException: Parameter is not valid.
at System.Drawing.Image.get_FrameDimensionsList()
at System.Drawing.ImageAnimator.CanAnimate(Image image)
at System.Drawing.ImageAnimator.ImageInfo..ctor(Image image)
at System.Drawing.ImageAnimator.Animate(Image image, EventHandler onFrameChangedHandler)
at System.Windows.Forms.PictureBox.Animate(Boolean animate)
at System.Windows.Forms.PictureBox.Animate()
at System.Windows.Forms.PictureBox.InstallNewImage(Image value, ImageInstallationType installationType)
at System.Windows.Forms.PictureBox.set_Image(Image value)
at xxxxx.BarcodeGenerator.btnStOk_Click(Object sender, EventArgs e) in C:\xxxxx\xxxxx\BarcodeGenerator.cs:line 459
what does this mean?
I have a List<string> that I would like to populate via a text file that is set as a project resource. I have looked all over on a way to do this but haven't yet found one that doesn't cause my program to crash.
If I manually populate the list...
_names.Add("Sam");
_names.Add("John");
_names.Add("Mike");
...everything works. My text file has each name on a separate line, no commas or anything. When I try to read in the names, the program crashes, no matter which route I take. This is the most recent way I've tried, though there are many others:
using (var reader = new StreamReader(Properties.Resources.sampleNamesMale))
{
string line;
while ((line = reader.ReadLine()) != null)
{
_names.Add(line);
}
}
Also, I can't isolate the reason for the crash because every time it does, the error just mentions ViewModelLocator, which is entirely irrelevant to this issue.
Does anybody have any ideas about how to fix this? I would certainly appreciate any advice.
Update: Try-catch yields no results. This is the error I get:
XamlParseException occurred - 'The invocation of the constructor on type 'AoW.ViewModels.ViewModelLocator' that matches the specified binding constraints threw an exception.' Line number '13' and line position '10'.
It points at InitializeComponent() in my main window's constructor.
Update 2: The real exception is this:
"ArgumentException occurred - Illegal characters in path." It points at the using (var reader.... line.
Use a StringReader instead of a StreamReader:
using (var reader = new StringReader(Properties.Resources.sampleNamesMale))
You are getting that error because StreamReader(string) expects a file path. If you are providing the actual text in Properties.Resources.sampleNamesMale, you have to use a StringReader.
The only way you could get the exception:
ArgumentException occurred - Illegal characters in path.
is if the path returned by Properties.Resources.sampleNamesMale was literally invalid:
using (var reader = new StreamReader(Properties.Resources.sampleNamesMale))
After second update the answer is very easy: display in debugger what is a path to your file and make it correct. Probably it contains spaces in the end or not escaped \