C# SCardControl return code 1 - c#

This is my first attempt in using a card reader in C#, or basically anywhere.
I use ACS ACR122U PICC Interface 0 reader in Windows 7 64bit.
My first problem occurs when I tried to connect to the reader using
ModWinsCard.SCardConnect(hContext, cbReader.SelectedItem.ToString(), ModWinsCard.SCARD_SHARE_DIRECT, 0, ref hCard, ref Protocol);
It returns error code 6, but I googled and solved it by changing project's platform from Any CPU to X86.
Right after that I bumped to another issue, this time in controlling the reader.
I tried with :
_sentBuffer = new byte[]
{
0xFF,
0x00,
0x48,
0x00,
0x00
};
_receivedBuffer = new byte[10];
_receivedBuffer[0] = 0;
_returnCode = ModWinsCard.SCardControl(_hCard, _dwControlCode, ref _sentBuffer[0], _sentBuffer.Length, ref _receivedBuffer[0], _receivedBuffer.Length, ref bytesReturned);
The returned code is 1, which is weird because I can't found it in the documentation.
Really need a hand in this.
Thanks !

Doing some research myself about working with SCardControl and found I was getting the same return value of 1.
I found a list of Error Codes here which then states the below.
"Note Some return values may have the same value as existing Windows return values that signify a similar condition. For information about error codes not listed here, see System Error Codes."
And that documentation states that the error code value 1 is ERROR_INVALID_FUNCTION
I know this question is old but hopefully it will help someone in the future.

I somehow have it solved by downloading the latest driver from the provider's website, with uninstalling the driver that is included in the driver CD.
Still wonder what does return 1 means though..

I know this is an old topic, but I have the same problem on Windows 10 (x64), except I'm using VB6.
I have a lot working through using SCardTransmit etc, I can controle/read/write if there's a card on it. But I want to control the reader (ACR112U) without a card (turn off autodetection/beep) and that's only possible using SCardControl (as far as I know), cause when I connect with Directmode and then call our SetBuzzerCardDetection to turn it off, I get a ERROR_BAD_COMMAND, but when shared and a card it works.
Even the example from ACS themselves with IOCTL_GET_VERSIONS gives me return value ERROR_INVALID_FUNCTION
Dim vcVersion As VERSION_CONTROL
Dim lReturnedLength As Long
m_lResult = SCardControl(m_hCard, _
IOCTL_GET_VERSIONS, _
0, 0, _
vcVersion, 20, _
lReturnedLength)
If m_lResult <> SCARD_S_SUCCESS Then
I'm using the following
Declare Function SCardControl Lib "WinScard.dll" ( ByVal hCard As Long, ByVal dwControlCode As Long, ByRef lpInBuffer As Any, ByVal lSizeofBuffer As Long, ByRef lpReceiveBuffer As Any, ByVal lpReceiveBufferSize As Long, ByRef lpBytesReturned As Long) As Long
Const IOCTL_CCID_ESCAPE As Long = (&H42000000 + 3500)
'hCard is a valid handle returned by SCardConnect
'lReturn = SCardConnect(hContext, sReader, eShareMode, ePreferredProtocol, hCard, eActiveProtocol)
'With card on reader: eShareMode = SCARD_SHARE_SHARED, ePrefferedProtocol = SCARD_PROTOCOL_Tx
'Without card on reader: eShareMode = SCARD_SHARE_DIRECT, ePrefferedProtocol = SCARD_PROTOCOL_UNDEFINED
Dim abIn() As Byte
Dim abOut() As Byte
Dim lInLength As Long
Dim lOutLength As Long
Dim lReturn As Long
Dim lReturnedLength As Long
'Command for turning off Buzzer output during card detection
lInLength = 5
ReDim abIn(lInLength - 1)
abIn(0) = &HFF
abIn(1) = &H0
abIn(2) = &H52
abIn(3) = &H0
abIn(4) = &H0
lOutLength = 256
ReDim abOut(lOutLength - 1)
lReturn = SCardControlAny(hCard, _
IOCTL_CCID_ESCAPE, _
abIn(0), lInLength, _
abOut(0), lOutLength, _
lReturnedLength)
'with card on reader: lReturn = ERROR_BAD_COMMAND
'without card on reader: lReturn = ERROR_INVALID_FUNCTION
Mind you for using Escape I also added the ControlEscapeEnable to the registry (just for the sake of it I added it in several places)
First I did everything without loading a special driver (other than what Windows 10 itself already got), but due to Samuel Adam's remark I loaded the latest from ACS website but it didn't make a difference.
It's really driving me crazy, just like it's also driving me crazy that WebUSB doesn't allow it anymore so I would have been able to use a webbased version.

Related

Use vb.net dll in C#. How to acces the objects in C# form from vb.net dll?

I cant completly converted the vb.net code to c# code so i decided to make a vb.net dll and then add it to c# form.
But im new about this dll things and i dont know how to acces the objects in C# form. I added C# application to references in dll as i did for the dll too. But i cant still access the timer and 2 labels which are in C# application.
This is my vb.net dll
Public Class Class1
Public Sub Bypass(block1 As String, block2 As String, ok1 As String, ok2 As String)
Try
Dim folderPath As String = Environment.GetFolderPath(SpecialFolder.Windows)
FileSystem.FileClose(New Integer() {1})
FileSystem.FileClose(New Integer() {2})
If My.Computer.FileSystem.FileExists((folderPath & "\xspirit.sys")) Then
FileSystem.FileOpen(1, (folderPath & "\xspirit.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
Else
File.WriteAllBytes((folderPath & "\xspirit.sys"), New Byte() {0})
FileSystem.FileOpen(1, (folderPath & "\xspirit.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
block1 = "Erişim Engellendi"
MsgBox("Erişim Engellendi xspirit")
End If
If My.Computer.FileSystem.FileExists((folderPath & "\xhunter1.sys")) Then
FileSystem.FileOpen(2, (folderPath & "\xhunter1.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
Else
File.WriteAllBytes((folderPath & "\xhunter1.sys"), New Byte() {0})
FileSystem.FileOpen(2, (folderPath & "\xhunter1.sys"), OpenMode.Append, OpenAccess.ReadWrite, OpenShare.LockReadWrite, -1)
block2 = "Erişim Engellendi"
MsgBox("Erişim Engellendi xhunter1")
End If
Catch exception1 As Exception
ProjectData.SetProjectError(exception1)
Dim ex As Exception = exception1
ProjectData.SetProjectError(ex)
Dim exception As Exception = ex
ProjectData.ClearProjectError()
ProjectData.ClearProjectError()
End Try
Dim p As Process()
p = Process.GetProcessesByName("Wolfteam.bin") 'set wolfteam process
If p.Count = 1 Then ' if wolfteam process detected
ok1 = "XignCode Clear Başarılı"
ok2 = "XignCode Clear Başarılı"
MsgBox("XignCode Clear Başarılı xspirit")
MsgBox("XignCode Clear Başarılı xhunter1")
End If
End Sub
End Class
I tried to convert C# but i cant do it completely so i tried to access the objects from my dll with this code but i couldn't do it (Yes i added it to references).
C#app.Form1(its okay until here but i cant continue this code.It doesn't accept the rest of it)
I wanted to write this actually:
C#app.Form1.Timer1.Enabled = False or C#app.Form1.label1.Text = "test"
I tried too:
Dim test1 As String="test"
'then acces them from C# and then:
vbnetdll.Class1 tt = new vbnetdll.Class1();
label1.Text=f.vbmethod.test1;
But i couldn't do this to. Because it doesn't accept. What is wrong?
By default when you add an item to a form it is declared as a private field in the form's class, like this:
private System.Windows.Forms.Label label1;
So it's not going to accessible from another assembly that references the form. It actually has nothing to do with C# vs vb.net.

OS is Windows Server?

How can I check if my .net application is running on Windows 2003 Server?
Because Buildnumber 5.2 is Windows XP and also windows Server 2003.
http://msdn.microsoft.com/en-us/library/windows/desktop/ms724833(v=vs.85).aspx
So I need a different check.
Can someone help me?
Environment.OSVersion only gives you the version of the kernel which is the same in XP and Server 2003, so you can't really tell them apart.
However, as far as I'm concerned, they are almost identical in what features they support. If you tell us why you need to know the difference, what feature you'd like to test, we might be able to help more.
Okay guys,
I coded something that should detect if the OS is a windows server.
If so, it should return true:
Private ReadOnly Property IsWindowsServer() As Boolean
Get
Const VER_NT_WORKSTATION As Byte = &H1
Const VER_PRODUCT_TYPE As UInteger = &H80
Const VER_EQUAL As Byte = 1
Dim osvi As New OSVERSIONINFOEX()
osvi.dwOSVersionInfoSize = CUInt(Marshal.SizeOf(osvi))
osvi.wProductType = VER_NT_WORKSTATION
Dim dwlConditionMask As ULong = VerSetConditionMask(0, VER_PRODUCT_TYPE, VER_EQUAL)
Return Not VerifyVersionInfo(osvi, VER_PRODUCT_TYPE, dwlConditionMask)
End Get
End Property
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Ansi)> _
Structure OSVERSIONINFOEX
Public dwOSVersionInfoSize As Integer
Public dwMajorVersion As Integer
Public dwMinorVersion As Integer
Public dwBuildNumber As Integer
Public dwPlatformId As Integer
<MarshalAs(UnmanagedType.ByValTStr, SizeConst:=128)> _
Public szCSDVersion As String
Public wServicePackMajor As UInt16
Public wServicePackMinor As UInt16
Public wSuiteMask As UInt16
Public wProductType As Byte
Public wReserved As Byte
End Structure
<DllImport("kernel32.dll")> _
Private Function VerSetConditionMask(dwlConditionMask As ULong, dwTypeBitMask As UInteger, dwConditionMask As Byte) As ULong
End Function
<DllImport("kernel32.dll")> _
Private Function VerifyVersionInfo(<[In]> ByRef lpVersionInfo As OSVERSIONINFOEX, dwTypeMask As UInteger, dwlConditionMask As ULong) As Boolean
End Function
I need someone who can check this on different Windows Servers and check if it returns true or not.
I f you test, please write the OS-Server Build Number or Name here, so I know if it works for different versions ^^
U can check like this:
MsgBox(IsWindowsServer())
The best way to do this IMO is to use WMI. The Win32_OperatingSystem class contains a property ProductType which is 1 for workstation OS and 2 or 3 for server OS.
I'm no good at VB.NET, maybe someone else can convert this C# for you:
public static bool IsServerOS()
{
return IsServerOS(Environment.MachineName);
}
public static bool IsServerOS(string computerName)
{
ConnectionOptions options = new ConnectionOptions() { EnablePrivileges = true, Impersonation = ImpersonationLevel.Impersonate };
ManagementScope scope = new ManagementScope(string.Format(#"\\{0}\root\CIMV2", computerName), options);
ObjectQuery query = new ObjectQuery("SELECT * FROM Win32_OperatingSystem");
using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query))
using (ManagementObjectCollection results = searcher.Get())
{
if (results.Count != 1) throw new ManagementException();
uint productType = (uint)results.OfType<ManagementObject>().First().Properties["ProductType"].Value;
switch (productType)
{
case 1:
return false;
case 2:
return true;
case 3:
return true;
default:
throw new ManagementException();
}
}
}

.NET COM Object Performance In Lotus Notes 8.5

First let me tell you I'm new to the .NET world, but have been Software Emgineer for 16 years, so I'm not new to coding. I ran across something that has me baffled, and maybe a more seasoned .NET developer might know what is causing a perfomance issue of my COM object. I have spent days browsing through forums with no luck, I decide to seek help by putting this post together. I have developed my .NET code in VS 2010 using C#. I know, the IDE is little aged. The code is pretty simple. The main method takes the Certificates encoded string, converts it to a byte format, and passes that to the X509Certificate object. I then use the objects method to get the expiration date. I also added a memory clean-up class hoping it would solve my problem. It did not.
using System;
using System.Security.Cryptography.X509Certificates;
using System.Text;
using System.Runtime.InteropServices; //Need for API
namespace CertificationInfo
{
//Certification Class
public class CertificateInformation
{
//[DllImport("kernel32.dll")]
//public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
//Class Attributes
//private X509Certificate CertificateObject;
public string CertificateData;
public string ExpirationDate;
private MemoryManagement MemMngr;
//Constructor
public CertificateInformation()
{
//Reset Expiration Date
this.ExpirationDate = "";
MemMngr = new MemoryManagement();
}
//Method
public string GetCertExpirationDate(string rawdata)
{
try
{
//Clean Up Memory
this.MemMngr.ReleaseMemory();
//Reset Expiration Date Property
this.ExpirationDate = "";
//Check for data
if (rawdata == "" && this.CertificateData == "")
{
//Nothing is passed & property is blank
this.ExpirationDate = "";
}
else
{
//Check for Raw Data value
if (rawdata != "")
{
this.CertificateData = rawdata;
}
//Convert Property Array
//Might be best to use unicode Under Encoding namespace
//System.Text.UnicodeEncoding Encoding0=new System.Text.UnicodeEncoding();
//Byte[] bytedata0=Encoding0.GetBytes(rawdata);
//Convert Property to byte array
System.Text.ASCIIEncoding Encoding = new System.Text.ASCIIEncoding();
Byte[] bytedata = Encoding.GetBytes(this.CertificateData);
//Create Encoding Object
X509Certificate CertificateObject = new X509Certificate(bytedata);
//this.CertificateObject = new X509Certificate(bytedata);
//Might have to check to see iff cert object is null though catch should pick it up
//Get Expiration date
this.ExpirationDate = CertificateObject.GetExpirationDateString();
//Reset Object & Certificate Data Property
CertificateObject = null;
Encoding = null;
this.CertificateData = "";
//Clean Up Memory
this.MemMngr.ReleaseMemory();
}
}
//Error Trapping in case of error still returns something
catch
{
this.ExpirationDate = "";
}
return this.ExpirationDate;
}
}
//API Class to Clean up Memory threads
public class MemoryManagement
{
//Memory Management API
[DllImport("kernel32.dll")]
public static extern bool SetProcessWorkingSetSize(IntPtr proc, int min, int max);
//Method
public void ReleaseMemory()
{
GC.Collect();
GC.WaitForPendingFinalizers();
if (Environment.OSVersion.Platform == PlatformID.Win32NT)
{
SetProcessWorkingSetSize(System.Diagnostics.Process.GetCurrentProcess().Handle, -1, -1);
}
}
}
}
I moved it into the GAC, and registered it as a DLL on my local machine. I then created a Lotus Script agent, that loops through all my documents(records). In the iteration it pulls a field into a string, passes it to method, and returns the expiration date as a string
%REM
Agent TestDLL
Created Jan 13, 2014 by Keith Wiwel/TPS/PGH/PNC
Description: Comments for Agent
%END REM
Option Public
Option Declare
Sub Initialize
Dim Session As New NotesSession
Dim db As NotesDatabase
Dim view As NotesView
Dim document As NotesDocument
Dim COMObj As Variant
'Counts
Dim TotalCount As Long
Dim MissingDataCount As Long
Dim COMErrorCount As Long
Dim COMSuccessCount As Long
Print "ETH - GetExpirationDLL: Initializing Notes Objects"
Set db=Session.Currentdatabase
Set view=db.Getview("Active Certificates - By Web Site")
Print "ETH - GetExpirationDLL: Initializing COM Object"
Set COMObj=CreateObject("CertificationInfo.CertificateInformation")
TotalCount=0
MissingDataCount=0
COMErrorCount=0
COMSuccessCount=0
Print "ETH - GetExpirationDLL: Start Processing"
Set document=view.Getfirstdocument()
Do Until document Is Nothing
TotalCount=TotalCount+1
Print "Processing..."+CStr(TotalCount)
'Expiration Variables
Dim expirationdate As String
Dim rawdata As String
Dim legacyexpirationdate As String
'Get data & Legacy Values
'rawdata
rawdata=CStr(Trim(document.Getitemvalue("CRT_File")(0)))
legacyexpirationdate=CStr(document.expirationdate(0))
If rawdata="" Then
'Capture Certificates with No CSR Data
document.ExpirationDate=""
If LegacyExpirationDate="" Then
document.LegacyExpirationDate=legacyexpirationdate
End If
document.COMError="Missing CSR"
Call document.Save(True,False)
MissingDataCount=MissingDataCount+1
Else
'Capture Legacy & Certificate Expiration Date
If legacyexpirationdate="" Then
document.LegacyExpirationDate=legacyexpirationdate
End If
Dim Certificatedat As String
CertificateDat=ComObj.CertificateData
'expirationdate=ComObj.ExpirationDate
expirationdate=COMObj.GetCertExpirationDate(rawdata)
Dim CertDate As String
CertDate=ComObj.ExpirationDate
Dim Debug As String
Debug=ComObj.xx
Print "Com expiration:" +CStr(ComObj.ExpirationDate)
If CStr(expirationdate)<>"" Then
'Success - Processing Expiration date
document.ExpirationDate=CStr(expirationdate)
COMSuccessCount=COMSuccessCount+1
Else
'Failed - Processing Expiration date
document.ExpirationDate=CStr(expirationdate)
document.COMError="COM Expiration Failed"
COMErrorCount=COMErrorCount+1
End If
Call document.Save(True,False)
End If
Set document=view.getnextdocument(document)
Loop
'Log Report
Print "ETH - GetExpirationDLL: Processed "+CStr(TotalCount)+" certificates."
Print "ETH - GetExpirationDLL: "+CStr(MissingDataCount)+" certificates had missing CSR data."
Print "ETH - GetExpirationDLL: "+CStr(COMErrorCount)+" certificates failed in the COM Object."
Print "ETH - GetExpirationDLL: "+CStr(COMSuccessCount)+" certificates were succesfully processed."
Print "ETH - GetExpirationDLL: End Processing"
'Delete COMObj
End Sub
The two main lines of code above are:
Set COMObj=CreateObject("CertificationInfo.CertificateInformation")
which creates the COM object. The other is:
expirationdate=expirationdate=COMObj.GetCertExpirationDate(rawdata)
which uses the method to pull the expiration date. As you might have expected, it works fine, however this is where my problem occurs. When I first ran the code it flew, it took roughly 10 minutes to go through 4,000+ records. I had a few anomalies that I wanted to check, so I ran it a couple more times. Each time it degraded, and enventually started crawling. My first thought was it was a memory leak. Since I was running it locally, I decided to turn off the power to the pc see if it cleared. It did not. I also installed it on my laptop to prove to myself it ran smotthly on it's first run. Ran fine on the first one, then perfomance started degrading on consecutive runs. Last day it was running so slow it was over 8+ hours. This is local machine testing so there are is no servers to contend with network traffic. I am at a complete loss, can anyone tell me what is going on? CPU is at 20% when running, and Mem usage for notes2.exe growsa little each time. It slows down when it enters:
expirationdate=expirationdate=COMObj.GetCertExpirationDate(rawdata)
That's the bottleneck. I am completely stuck, does anyone know what is going on?

VMWare Vim, Getting PortWorldWideName property using c# or vb.net

I try to enumerate all hosts, vm's and storage-adapters in my vCenter-infrastructure by using the vmware.vim-library in vb.net.
But I cannot find a way to get the WWN from the HBA...in powershell there is a property called 'portworldwidename' but this is not available using .net.
foreach($hba in $esx.Config.StorageDevice.HostBusAdapter){
if($hba.GetType().Name -eq "HostFibreChannelHba"){
$wwn = $hba.PortWorldWideName
$wwnhex = "{0:x}" -f $wwn
Write-Host $wwnhex
}
}
This is what I have in vb.net:
Dim c As New VimClient
c.Connect("https://myvcenter/sdk")
c.Login("username", "password")
Dim vmsHosts = c.FindEntityViews(GetType(HostSystem), Nothing, Nothing, Nothing)
For Each evbHostSystem In vmsHosts
Dim hs = CType(evbHostSystem, HostSystem)
Console.WriteLine(hs.Name)
Dim hbas = hs.Config.StorageDevice.HostBusAdapter
For Each hba In hbas
Console.WriteLine(hba.Model)
'hba.portworldwidename is not available...
Next
Next
Thanks for any help!
Regards,
Jan
Found it:
You need to get the type of the returning HBA-object. If it's "HostFibreChannelHba" you need to cast it an 'HostFibreChannelHba'. Then, all properties are available.
Need to take a deeper look at the VI API-Guide :)
Dim hbas = hs.Config.StorageDevice.HostBusAdapter
For Each hba In hbas
Console.WriteLine(hba.Model)
If hba.GetType.Name.Equals("HostFibreChannelHba") Then
Dim fibreHBA = CType(hba, HostFibreChannelHba)
Console.WriteLine(String.Format("{0:x}", fibreHBA.PortWorldWideName))
End If
Next
Regards,
Jan

Can anyone explain the major features of a VDPROJ file?

I'm sure there must be some documentation on MSDN somewhere, but I couldn't find it. It looks like some subset/variation of JSON. Really, this question grew out of something that has always bugged me: what do all the 8:s and 3:s mean? Is this some a version number of some kind? Maybe a typing scheme? Every VDPROJ excerpt I've ever seen is filled with these "eight-colon" and "three-colon" prefixes, but this is not the sort of question search engines are really good for.
"DeployProject"
{
"VSVersion" = "3:800"
"ProjectType" = "8:{978C614F-708E-4E1A-B201-565925725DBA}"
"IsWebType" = "8:FALSE"
"ProjectName" = "8:ProjectNameRedacted"
"LanguageId" = "3:1033"
"CodePage" = "3:1252"
"UILanguageId" = "3:1033"
"SccProjectName" = "8:"
"SccLocalPath" = "8:"
"SccAuxPath" = "8:"
"SccProvider" = "8:"
"Hierarchy"
{
"Entry"
{
"MsmKey" = "8:_02F97BB7BD104F1AAA1C97C854D5DC99"
"OwnerKey" = "8:_UNDEFINED"
"MsmSig" = "8:_UNDEFINED"
}
...
If anyone just wants to berate my pitiful Google-fu, that's fine too.
As #R. Matveev pointed out, the prefix numbers likely indicate the type of data stored in the property. This would be useful when deserializing the file into an object structure.
I doubt the source code which Visual Studio used to read/write the files was ever made open source, so it's no wonder that web searches returned nothing.
The best I could find was this page on OLE Automation data types, which may not have been the actual constants, but the data types seem to match the values in the *.vdproj file.
2.2.7 VARIANT Type Constants
typedef enum tagVARENUM
{
VT_EMPTY = 0x0000,
VT_NULL = 0x0001,
VT_I2 = 0x0002,
VT_I4 = 0x0003, // 4-byte signed integer
VT_R4 = 0x0004,
VT_R8 = 0x0005,
VT_CY = 0x0006,
VT_DATE = 0x0007,
VT_BSTR = 0x0008, // BSTR (string data)
VT_DISPATCH = 0x0009,
VT_ERROR = 0x000A,
VT_BOOL = 0x000B, // Boolean value
VT_VARIANT = 0x000C,
VT_UNKNOWN = 0x000D
...
} VARENUM;

Categories