Enumeration values for FaxJob.SetStatus method - c#

Using Windows Fax Service, I am trying to cancel a fax from the Windows Fax Console. According to this worthless documentation I need to pass in a value JC_Delete which appears that it is some enumeration, however, the documentation fails to leave out what it is or how to get it.
I found another MSDN article stating in the last sentence that these JC values are just constants which the user defines. Finally, I found a forum post stating that it's just an enumeration in a C++ header file and the Microsoft guy showed the enumeration consisting of:
JC_UNKNOWN = 0
JC_DELETE = 1
JC_PAUSE = 2
JC_RESUME = 3
JC_RESTART = JC_RESUME
I just tried plugging in numbers, 0 or 1 since the method calls for an int and then I receive an exception
COM error:
the handle is invalid. (Exception from HRESULT: 0x80070006 (E_HANDLE))
Here is my bit of code. I am able to get the FaxJob object just fine. It's just calling the SetStatus() method that bombs.
var job = this.getFaxJobsInQueue().Where(j => j.JobId == JobId).Single();
job.SetStatus(1);

Arg!! Found the problem! It was very simple! I forgot to connect to the fax console. Apparently that is what the handle is invalid was indicating. My problem was in the method that returned all the jobs connected and disconnected. Once I had the FaxJob object, I was suppose to connect again. Here is my updated code:
var job = this.getFaxJobsInQueue().Where(j => j.JobId == JobId).Single();
this.objFaxServer.Connect(faxServerConnectionString);
job.SetStatus(1);
this.objFaxServer.Disconnect();

Related

Message read by OnEntryWritten are coming with parameters not set

I'm using the OnEntryWritten event in order to get events from the event log when they are fired.
The problem I started to see today is that some messages come with parameters unset.
For example:
The Windows Filtering Platform has permitted a bind to a local port. Application Information: Process ID:9852 Application Name:\device\harddiskvolume7\program files (x86)\google\chrome\application\chrome.exe Network Information: Source Address::: Source Port:51714 Protocol:17 Filter Information: Filter Run-Time ID:0 Layer Name:%%14608 Layer Run-Time ID:38
You can see the %%14608 parameter. This comes with a value if I see the same log in the Event Viewer.
I'm running a windows service as LocalSystem, so I don't know if this is a permission issue or this technology is not useful at all.
I have tried the rest offered on C# and they also don't meet my requirements.
UPDATE: this is the code I'm using to read the events.
1) First I subscribe to the corresponding Event log:
private void Subscribe()
{
_eventLog.EnableRaisingEvents = true;
var callbackFunction = new EntryWrittenEventHandler(OnEntryWritten);
_eventLog.EntryWritten += callbackFunction;
// Save a reference for callbackFunction
_eventHandler = callbackFunction;
}
2) Then on the callback method, I read data from the message:
public void OnEntryWritten(Object source, EntryWrittenEventArgs entryArgs)
{
// When overwrite policy is enabled, this will trigger for all elements when it starts writing new ones
try
{
var entry = entryArgs.Entry;
var timeWritten = entry.TimeWritten;
// This comes with %% values depending on the log
string message = entry.Message;
}
catch(Exception ex)
{
...
}
}
3) The event log variable is simply initialized as:
var eventLog = EventLog.GetEventLogs().FirstOrDefault(el => el.Log.Equals(logName, StringComparison.OrdinalIgnoreCase));
I need some help on this, honestly I don't know what else to try.
UPDATE
I'm adding some images here so everybody can understand the situation a little bit better. To be honest, it looks like there's no solution but to implement a dictionary and replace manually the required values, which appear to be always constants.
This is what I see on the Event Viewer for a given Event ID:
This is what I see on my program when I read that entry:
You can clearly see that the following values:
"Machine key." (Key type)
"Read persisted key from file." (Operation)
Are coming unmapped in the ReplacementStrings and the Message properties as: %%2499 and %%2458
This is the message value I get on the program:
"Key file operation.\r\n\r\nSubject:\r\n\tSecurity ID:\t\tS-1-5-18\r\n\tAccount Name:\t\tMyAccount$\r\n\tAccount Domain:\t\tWORKGROUP\r\n\tLogon ID:\t\t0x3e7\r\n\r\nProcess Information:\r\n\tProcess ID:\t\t6644\r\n\tProcess Creation Time:\t2019-04-03T12:17:24.587994400Z\r\n\r\nCryptographic Parameters:\r\n\tProvider Name:\tMicrosoft Software Key Storage Provider\r\n\tAlgorithm Name:\tUNKNOWN\r\n\tKey Name:\t816339d2-c476-4f1e-bc40-954f0aa0f851\r\n\tKey Type:\t%%2499\r\n\r\nKey File Operation Information:\r\n\tFile Path:\tC:\ProgramData\Microsoft\Crypto\Keys\6d55a45fd69327293e9ed3e7930f4565_5663a8bb-2d1d-4c0d-90c1-624beddabe9c\r\n\tOperation:\t%%2458\r\n\tReturn Code:\t0x0"
What can be done here? There also nothing in entry.Data that might help me out to obtain both values.
No, I believe you're mistaken, sorry that this answer is too late. I found a similar event that was raised by chrome and evaluated if there's anything missed by the event handler. There wasn't anything missed. The message I got in my console output exactly matched what I saw in my Event Viewer.
A better solution would be to
Use entry.Data to get the complete data instead of entry.Message
entry.Data will return a byte[] which you can convert to a string. Here's the link to all properties that an entry will have.

How to get ExpandEnvironmentVariables to return custom variables?

I have added a custom environment variable and I'm unable to get it to return in the ExpandEnvironmentVariables.
These 2 calls work fine:
string s = Environment.GetEnvironmentVariable("TEST", EnvironmentVariableTarget.Machine);
// s = "D:\Temp2"
string path = Environment.ExpandEnvironmentVariables(#"%windir%\Temp1");
// path = "C:\Windows\Temp1"
However, this call returns the same input string:
var path = Environment.ExpandEnvironmentVariables(#"%TEST%\Temp1");
// path = "%TEST%\\Temp1"
I expect to get D:\Temp2\Temp1
What am I missing to correctly get the custom EnvironmentVariable in this last call?
Hans and Evk were correct in their comments. Since no one wanted to add an answer I'll close this question out.
For whatever reason ExpandEnvironmentVariables will not get any keys which were added after an application started. I also tested this with a running Windows Service. It was only after I restarted the service that new keys were found and populated.
This behavior is not documented in the Microsoft Documentation.

Issues with using Managed WiFi (NativeWiFi API)

I am trying to create and connect to a WLAN profile using Native WiFi (https://managedwifi.codeplex.com/). I am able to view all the Network BSS List and their parameters. However, when I am trying to create/overwrite a WLAN profile, I get the below mentioned error message (Error#1):
An unhandled exception of type 'System.ComponentModel.Win32Exception' occurred in ManagedWifi.dll.
Additional information: The network connection profile is corrupted
However, when I created a profile normally from "Network and Sharing Center" of the Windows 7 control panel and then tried to connect using the ManagedWiFi, I get another error message(Error#2):
An unhandled exception of type 'System.ArgumentException' occurred in mscorlib.dll
Additional information: Type 'NativeWifi.Wlan+WlanReasonCode' cannot be marshaled as an unmanaged structure; no meaningful size or offset can be computed.
I noticed that this error occurs even if I try to connect/disconnect to a WLAN profile from the "Network and Sharing Center", with the windows application running in the background.
Here is the sample code that I am using:
Dim profileName As String = GlobalVariables.ssidname ' Provides the selected SSID name from the Network BSS List
Dim hexval As String = StringToHex(GlobalVariables.ssidname) ' Function to get the hexadecimal value for a provided string
Dim key As String = TextBox1.Text ' Security key from the textbook provided
Dim profileXml As String = String.Format("<?xml version=""1.0""?><WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1""><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><MSM><security><authEncryption><authentication>open</authentication><encryption>WEP</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>networkKey</keyType><protected>false</protected><keyMaterial>{2}</keyMaterial></sharedKey><keyIndex>0</keyIndex></security></MSM></WLANProfile>", 'GlobalVariables.ssidname, hexval, TextBox1.Text)
wlanIface.SetProfile(Wlan.WlanProfileFlags.AllUser, profileXml, True) 'Error#1 occurs here
wlanIface.Connect(Wlan.WlanConnectionMode.Profile, Wlan.Dot11BssType.Any, profileName) 'Error#2 occurs here
From the forum "Type Native Wifi.Wlan + WlanReasonCode cannot be marshaled error", the issue (Error#2) seems to be within the WlanAPI.cs, where there is a line of code that checks for the size of the return code. This is the line:
int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanReasonCode));
if (notifyData.dataSize >= expectedSize)
{
Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
if (wlanIface != null)
wlanIface.OnWlanReason(notifyData, reasonCode);
}
Changing the above code to the below seems to fix the issue.
//int expectedSize = Marshal.SizeOf(typeof(Wlan.WlanReasonCode));
if (notifyData.dataSize >= 0)
{
Wlan.WlanReasonCode reasonCode = (Wlan.WlanReasonCode)Marshal.ReadInt32(notifyData.dataPtr);
if (wlanIface != null)
wlanIface.OnWlanReason(notifyData, reasonCode);
}
However, I am not sure on how to add this fix to my solution. I installed the ManagedWiFi from the NuGet Package Manager. Hence, not sure how to change the WlanApi.cs file. Any help regarding the above mentioned two issues are much appreciated.
The issue (Error#1) is now resolved. The profilexml file format was different for me. Here is the profilexml after I changed it.
Dim profileXml As String = String.Format("<?xml version=""1.0""?><WLANProfile xmlns=""http://www.microsoft.com/networking/WLAN/profile/v1""><name>{0}</name><SSIDConfig><SSID><hex>{1}</hex><name>{0}</name></SSID></SSIDConfig><connectionType>ESS</connectionType><connectionMode>auto</connectionMode><MSM><security><authEncryption><authentication>WPA2PSK</authentication><encryption>AES</encryption><useOneX>false</useOneX></authEncryption><sharedKey><keyType>passPhrase</keyType><protected>false</protected><keyMaterial>{2}</keyMaterial></sharedKey></security></MSM></WLANProfile>", GlobalVariables.ssidname, hexval, TextBox1.Text)
Also the second issue (Error#2) was resolved when I uninstalled ManagedWiFi package from my solution and added the whole ManagedWiFi project to the solution. Then I made the change in WlanApi.cs as mentioned in SimpleWiFi Or Type Native Wifi.Wlan + WlanReasonCode cannot be marshaled error.
I had a simpler task (read the SSID of the connected network), which was throwing the same error.
I solved it by switching to using SimpleWiFi entirely and ignore the ManagedWifi package.
Glancing at the source code, it looks like SW is a fixed reimplementation of some of the functionality in MW.

What does it indicate when RasGetConnectStatus returns a value of 6?

I'm trying to query the RasStatus of a connection. When I call the RasGetConnectStatus method, it returns 6. I've not found that particular return value in any of the documentation that I've read.
Here are some of the pages that I've looked at:
http://www.cs.scranton.edu/~beidler/Ada/win32/win32-raserror.html
http://msdn.microsoft.com/en-us/library/aa920162.aspx
http://msdn.microsoft.com/en-us/library/bb530704(v=vs.85).aspx
I'm using C# and .net 4.0
Edit: The code that actually calls follows:
uint result;
RASCONNSTATUS rasconnstatus; // http://pinvoke.net/default.aspx/Structures/RASCONNSTATUS.html
// _handle is previously set to the hwnd of the ras connection
result = RASAPI.RasGetConnectStatus(_handle, out rasconnstatus);
return rasconnstatus;
When this returns, result == 6 and rasconnstatus.rasconnstate == 0
What I need to find out is why result == 6.
The easiest way to look up Win32 error codes is by looking at the header files directly in the Windows SDK. Most of them are in the WinError.h file in the include folder wherever you installed the Windows SDK. For the RAS specific errors (the result would be between 600 and 900) those are in the RasError.h file.
In the case of your result being 6, it's indicating ERROR_INVALID_HANDLE; which in RAS that means it didn't like the connection handle you passed to the function. In your code sample, that would be _handle.
By the way, you may want to look at using the DotRas project on CodePlex, it's a .NET wrapper around the RAS API. The particular method you're interested in would be RasConnection.GetConnectionStatus, it returns the data from that structure.
foreach (RasConnection conn in RasConnection.GetActiveConnections())
{
RasConnectionStatus status = conn.GetConnectionStatus();
// Do something useful.
}
The WinError.h file is also available online here: http://msdn.microsoft.com/en-us/library/ms819772.aspx
Hope that helps!
Here you should find your answer http://msdn.microsoft.com/en-us/library/aa920538.aspx this is the enum values of RASCONNSTATE returned by RasGetConnectStatus. The value 6 should equal to RASCS_AuthNotify and you will find this description:
An authentication event has occurred. If dwError is zero, this event will be immediately followed by one of the more specific authentication states following. If dwError is nonzero, authentication has failed, and the error value indicates why.
Maybe is related with some firewall rules that block the connection.
update the link is from windows mobile 6.5 documentation.
for the windows one this link.

IDataRecord.IsDBNull causes an System.OverflowException (Arithmetic Overflow)

I have a OdbcDataReader that gets data from a database and returns a set of records.
The code that executes the query looks as follows:
OdbcDataReader reader = command.ExecuteReader();
while (reader.Read())
{
yield return reader.AsMovexProduct();
}
The method returns an IEnumerable of a custom type (MovexProduct). The convertion from an IDataRecord to my custom type MovexProduct happens in an extension-method that looks like this (abbrev.):
public static MovexProduct AsMovexProduct(this IDataRecord record)
{
var movexProduct = new MovexProduct
{
ItemNumber = record.GetString(0).Trim(),
Name = record.GetString(1).Trim(),
Category = record.GetString(2).Trim(),
ItemType = record.GetString(3).Trim()
};
if (!record.IsDBNull(4))
movexProduct.Status1 = int.Parse(record.GetString(4).Trim());
// Additional properties with IsDBNull checks follow here.
return movexProduct;
}
As soon as I hit the if (!record.IsDBNull(4)) I get an OverflowException with the exception message "Arithmetic operation resulted in an overflow."
StackTrace:
System.OverflowException was unhandled by user code
Message=Arithmetic operation resulted in an overflow.
Source=System.Data
StackTrace:
at System.Data.Odbc.OdbcDataReader.GetSqlType(Int32 i)
at System.Data.Odbc.OdbcDataReader.GetValue(Int32 i)
at System.Data.Odbc.OdbcDataReader.IsDBNull(Int32 i)
at JulaAil.DataService.Movex.Data.ExtensionMethods.AsMovexProduct(IDataRecord record) [...]
I've never encountered this problem before and I cannot figure out why I get it. I have verified that the record exists and that it contains data and that the indexes I provide are correct. I should also mention that I get the same exception if I change the if-statemnt to this: if (record.GetString(4) != null). What does work is encapsulating the property-assignment in a try {} catch (NullReferenceException) {} block - but that can lead to performance-loss (can it not?).
I am running the x64 version of Visual Studio and I'm using a 64-bit odbc driver.
Has anyone else come across this? Any suggestions as to how I could solve / get around this issue?
Many thanks!
For any one experiencing the same issue, the way I solved this was to switch from the Odbc* classes to their OleDb* counterparts. This of course demands that your data driver has support for OleDb connections.
Which DB are you trying to talk to? If it uses some "private" column types that can cause problems. That doesn't apply to SQL Server of course :-)
Also check that you are compiling and running as x64 (Process Explorer will show you thsi and even plain tack manager shows it). devenv.exe will still be x86 but your actual binary should run as x64. The reason I mention is that crossing 32/64 bit boundary is notorious for breaking 3rd party ODBC drivers.

Categories

Resources