Koolwired.Imap - How do I delete messages? - c#

I'm trying to delete all the emails from a mailbox using the Koolwired.Imap library. I have the following code that should be marking all the messages and they, once all are marked, delete them,
_mailbox = _command.Fetch(_mailbox);
foreach (ImapMailboxMessage m in _mailbox.Messages)
{
try
{
_command.SetDeleted(m.ID, true);
}
catch (Exception e)
{
Console.WriteLine("Marking Error: " + e.Message + "(" + m.MessageID + ")");
}
}
try
{
_command.Expunge();
}
catch (Exception e)
{
Console.WriteLine("Expunge Error: " + e.Message);
}
When I run the above code i get the following errors:
Marking Error: Input string was not in a correct format.()
Marking Error: No UID found for message number3()
Marking Error: No UID found for message number1()
Marking Error: Input string was not in a correct format.()
Marking Error: Input string was not in a correct format.()
Marking Error: Input string was not in a correct format.()
I looks like there is an issue with the message UID on most of the message. After this runs about 99% of the messages are not deleted, some 2-3 are deleted. If I re-run the program, i get the same errors but a few less and another 2-3 emails are deleted.
How am I supposed to delete emails with the Koolwired.Imap library?
Are there other Imap libraries that work with c#? When i was looking this is the only one that I found.

Your code looks like it should work according to http://imapnet.codeplex.com/Thread/View.aspx?ThreadId=73377 and I see you posted out there as well. Have you tried setting up a gmail account and testing it against that just to see what happens?
As for other libraries, I have used the EAGetMail POP3 & IMAP4 component (cannot add link due to my new account: www.emailarchitect.net/eagetmail/) on previous projects and had good luck with it.

Related

Trouble opening QB

I am a long time c# developer but brand new to QBFC. I have downloaded the samples and was actually able to add an invoice to my file with it, but I am a little confused. I have trouble connecting unless QB is up and running. I was trying to follow the code in the sample, but it is difficult. I need this app to add invoices and bills to the file even if QB is not open. They only have one file so there won't be an instance where another file is already open. Also, the environment is simple as everything runs on the same computer.
My basic questions are:
How to select the correct QB file and provide credentials to allow access?
Is there a decent simple example using QBFC? Everything I have found is using XML which seems overly complicated compared to QBFC.
I cannot seem to get QB to open automatically. I have tried the code below and I get an error that states "Could not start QuickBooks".
Any pointers are greatly appreciated.
QBSessionManager qbSession = new QBSessionManager();
qbSession.OpenConnection("", "Lumber Management System");
try
{
qbSession.BeginSession("C:\\Users\\Jerry\\Documents\\QuickBooks\\Company Files\\MRJ Tecnology, LLC", ENOpenMode.omDontCare);
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + '\n' + ex.StackTrace, "Error opening QB");
}
There are a couple of things that you need in order for this to work. The first time that you request access to a company file, QuickBooks must be opened and the Admin must be logged in. The Admin will then be given a dialog to grant permission to your application to access QuickBooks. In the permission dialog, it will ask the Admin if they want to allow the application to read and modify the company file with four options:
No
Yes, prompt each time
Yes, whenever this QuickBooks company file is open
Yes, always; allow access even if QuickBooks is not running
The admin must choose the fourth option to allow your app to launch QuickBooks without running.
I would also suggest that you use OpenConnection2 instead of OpenConnection, and use a unique ID as the first parameter. You will also need to specify the connection type, which should be ENConnectionType.ctLocalQBD.
It also appears that the filename you are passing in the BeginSession call does not include the .qbw extension. Here is a basic sample:
QBSessionManager SessionManager = null;
try
{
SessionManager = new QBSessionManager();
SessionManager.OpenConnection2("UniqueAppID", "Lumber Management System", ENConnectionType.ctLocalQBD);
SessionManager.BeginSession("C:\\Users\\Jerry\\Documents\\QuickBooks\\Company Files\\MRJ Tecnology, LLC.qbw", ENOpenMode.omSingleUser);
// CODE TO SEND TO QB GOES HERE
}
catch(Exception ex)
{
MessageBox.Show("Error opening QB:" + ex.ToString());
}
finally
{
if(SessionManager != null)
{
SessionManager.EndSession();
SessionManager.CloseConnection();
}
}

How to save data to network path on .NET?

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 :)

Is it possible that SqlException is thrown and property Number == 0?

Is it possible that SqlException will be thrown when trying to execute sql procedure and property Number will be 0?
Specific situation: domain controller is not available/not responding and no real communication with sql server occurred.
No, it should not be possible that SqlException.Number is 0, except for the following cases:
Read-only routing failure
Server had severe error processing query
Processed cancellation while parsing results
Failed to create user instance
Assuming you're not using read-only routing of SQL Server 2016, then none of these cases could apply to the scenario you described.
Remaining cases are either a non-zero number from sysmessages, or a Win32 error code (which, since 0 == ERROR_SUCCESS, would also never be zero).
In practice you will see something along the lines of "Cannot create SSPI context", or "A transport-level error has occurred when sending the request to the server", or a "An existing connection was forcibly closed by the remote host", and those have nonzero Win32 error codes too.
Reference: https://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlerror.number(v=vs.110).aspx
It may be worth noting that SqlException.Number is synonym for the Number property of the first entry in its Errors array, and that array might contain more than one item.
Answering my own question. Yes, it is possible. We added aditional code to catch:
catch (SqlException ex)
{
for (int i = 0; i < ex.Errors.Count; i++)
{
this.logger.Error("Index #" + i + "\n" +
"Message: " + ex.Errors[i].Message + "\n" +
"Error Number: " + ex.Errors[i].Number + "\n" +
"LineNumber: " + ex.Errors[i].LineNumber + "\n" +
"Source: " + ex.Errors[i].Source + "\n" +
"Procedure: " + ex.Errors[i].Procedure + "\n");
}
if (ex.Number == 0)
{
this.logger.Warn("Exception was caught but ex.Number == 0! Changing to -69.");
oResults.Add("_ExitCode", "-69");
}
}
and this was logged today.
2017-01-17 08:05:08,282 [r074008903] ERROR ProcessLogger Index #0
Message: A severe error occurred on the current command. The results, if any, should be discarded.
Error Number: 0
LineNumber: 0
Source: .Net SqlClient Data Provider
Procedure:
2017-01-17 08:05:08,282 [r074008903] ERROR ProcessLogger Index #1
Message: A severe error occurred on the current command. The results, if any, should be discarded.
Error Number: 0
LineNumber: 0
Source: .Net SqlClient Data Provider
Procedure:
2017-01-17 08:05:08,283 [r074008903] WARN ProcessLogger Exception was caught but ex.Number == 0! Changing to -69.
Because in other place _ExitCode was used to determine is something was wrong in this specific situation we had false information.
It is possible.
I receive 0 when trying to connect SQL which is starting inside ubuntu container. According to this: https://learn.microsoft.com/en-us/sql/relational-databases/errors-events/database-engine-events-and-errors?view=sql-server-ver15
that is undocumented and, probably, is a bug.
Here is my situation, for example:

can't claim the PosPrinter

I have a TM-T20 Epson, I'm using this code to try to print : "Hello Printer" Message, and i keep tracking of some proprieties of the PosPrinter :
public void ImprintHelloPrinter()
{
//The Explorer
PosExplorer explorer = new PosExplorer();
////Get the device by its type LOGICAL NAME
DeviceInfo device = explorer.GetDevice(DeviceType.PosPrinter, "T20PRINTER");
//Create an instance
PosPrinter oposPrinter = (PosPrinter)explorer.CreateInstance(device);
//Opening
MessageBox.Show(#"Statue : " + oposPrinter.State.ToString());
oposPrinter.Open();
MessageBox.Show(#"Statue : " + oposPrinter.State.ToString());
//Checking if its really the printer
MessageBox.Show(#"Description : " + oposPrinter.DeviceDescription);
MessageBox.Show(#"Check Claimed : " + oposPrinter.Claimed.ToString());
oposPrinter.Claim(10000); //Here is My Exception
//Enabeling device
oposPrinter.DeviceEnabled = true;
//normal print
oposPrinter.PrintNormal(PrinterStation.Receipt, "Hello Printer");
}
Everything went OK, i checked that it is the right Printer and it opened and its not claimed, but when i try to Claim it i have the following Exception :
Method ClaimDevice threw an exception. Attempt was made to perform an illegal
or unsupported operation with the device, or an invalid parameter value was used.
Even in the Example application provided with the Microsoft Point Of Service SDK in the Sample Application Folder (C:\Program Files\Microsoft Point Of Service\SDK\Samples\Sample Application), i can find my printer, open it, but when i Claim it i have this error message :
POSControlException ErrorCode(Illegal) ExtendedErrorCode(10002) occurred:
Method ClaimDevice threw an exception. Attempt was made to perform an illegal
or unsupported operation with the device, or an invalid parameter value was
used.
Print Screen Of The Sample Application :
The error is because you have bad port configurated.
In my case, I use model FP-81 II connected to hardware NPort 5110 where I was configure port to 9100.
I hope help you.

How can I find out what is wrong with a SetupDiGetClassDev interface in C#?

How do I find out what's wrong with the device info set returned? I'm re-writing my code again and I'm still hitting the same stumbling block.
deviceInfoSet = SetupDiGetClassDevs(ref tGuid, 0, IntPtr.Zero, (uint)SetupDiFlags.DIGCF_PRESENT );
if (deviceInfoSet.ToInt32() == INVALID_DEVICE_HANDLE)
{
int errCode = Marshal.GetLastWin32Error();
errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
statusLabel.Text += "Invalid deviceinfoset returned: " + errCode + " => " + errorMessage + ".";
}
The above code doesn't cause any errors but when I use the code below:
result = true;
while (result)
{
result = SetupDiEnumDeviceInterfaces(deviceInfoSet, IntPtr.Zero, ref tGuid, Index, ref anInterface);
if (!result)
{
int errCode = Marshal.GetLastWin32Error();
errorMessage = new Win32Exception(Marshal.GetLastWin32Error()).Message;
statusLabel.Text += "\nSetDiEnumDeviceInterface Error: " + errCode + " => " + errorMessage + ".";
break;
}
Index++;
}
to try and access the device info set list, error code 259 (No more data is available) is returned. I am at a loss as to what I'm doing wrong.
Are you sure you're using the right GUID?
Check out http://blogs.msdn.com/doronh/archive/2006/02/15/532679.aspx
Edit: Everything else looks by-the-book and correct.
Edit2: Trying including DIGCF_DEVICEINTERFACE in call to SetupDiGetClassDevs, and see if that works for you. That is, both DIGCF_PRESENT and DIGCF_DEVICEINTERFACE.
Edit3: For the 64bit issue (#Thies), check out http://social.msdn.microsoft.com/Forums/en-US/windowssdk/thread/ea816aea-f718-4a0e-b013-0aa273de037f
I'm not familiar with this particular interface but it doesn't appear you are doing anything wrong. It simply appears that you are trying to read data from a device which currently has no data to offer.
Is that the case? Do you know for sure that the device is currently trying to return data to you?
I had simular problems which were due to running on 64-bit Windows. I never quite figured it out, and ended up hardcoding the device path in my code - which is not recommended.
I think it has to do with the API structures not setup correct for 64-bit.
Hope this may help lead someone else to an answer (and maybe help with my problem as well)
Please state if you are running 64-bit - and have you tried the same code on a 32-bit OS?
The problem starts with how SetupDiGetClassDevs is called.
If you are looking to get a device path, use SetupDiGetClassDevs(&GUID_DEVINTERFACE_USB_DEVICE ,,,)
SetupDiEnumDeviceInterfaces fails with error 259 if SetupDiGetClassDevs is given the wrong GUID in ClassGuid which MS Help says is A pointer to the GUID for a device setup class or a device interface class.
Include file devguid.h contains a set of GUID_DEVCLASS values. These are NOT the same as GUID_DEVINTERFACE_* values which are the one you need.
Use #include which includes ksuuids.h where you'll find GUID_DEVINTERFACE_* values.
There's a more detailed explanation on my website, with some source code that should help in correctly enumerating USB devices.
See http://pixcl.com/SetupDiEnumInterfaces_Fail.htm

Categories

Resources