objectSID coming back in non-standard format - active-directory

I'm using JNDI to query Active directory from group catalog servers:
Hashtable<String, Object> env = new Hashtable<String, Object>();
env.put(Context.INITIAL_CONTEXT_FACTORY,
"com.sun.jndi.ldap.LdapCtxFactory");
env.put(Context.PROVIDER_URL, "ldap://" + serverUrl + "/");
env.put(Context.SECURITY_AUTHENTICATION, "simple");
env.put(Context.SECURITY_PRINCIPAL, userName + "#" + currentDomain);
env.put(Context.SECURITY_CREDENTIALS, credentials);
env.put("java.naming.ldap.attributes.binary", "objectSid");
// Create the initial context
DirContext ctx = new InitialDirContext(env);
When I get objectSid back and convert the byte[] to hex string I get sids such as:
HEX: ACED0005757200025B42ACF317F8060854E002000078700000001001020000000000052000000025020000
SID: S-172-23445241858-4088152667-134674455-188500-7370752-17825792-2-537198592-620756992
This results in byte 0 having a value of 172 and byte 1 of 237, as well as 3 bytes at the end of parsing the 4 byte sub authorities.
Byte 0 should always be 1 and byte 2 should be the number of 4 byte sub authority identifiers (in this case 9). I'm having trouble figuring out what's going on as I'm unable to correctly map between expected and actual.
I'm betting there's some newbie mistake that I'm making, but can't figure out what it might be; my hope is that someone out there has been through this and can tell me what it is!

This was actually not an LDAP issue, but an issue with writing the object I was getting back to a byte array. The lesson is, debug harder...

Related

Splitting String into Array Errors

Trying to write a script that will be run in WinPE, that essentially gets the IP address of the localhost and chooses an action based on the IP range.
In Windows, the script runs flawlessly. However, in WinPE, I'm getting the following error:
script.vbs(1,1) Microsoft VBScript runtime error: Subscript out of range
Google-fu is telling me that has something to do with my array being outside of the range. Here I thought I had a decent understanding, but apparently not.
Code that works as is on Windows:
Option Explicit
Dim sIP, sHostname,sPingBat
Dim aIP
Dim iOct1, iOct2, iOct3, iOct4, iReturn
Dim oWMIService, oCmd, oAdapter
Dim cAdapters
iReturn = 999
sHostname = "."
Set oWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" & sHostname & "\root\cimv2")
Set cAdapters = oWMIService.ExecQuery("Select IPAddress from Win32_NetworkAdapterConfiguration Where IPEnabled = True")
Set oCmd = CreateObject("Wscript.Shell")
For Each oAdapter in cAdapters
If Not IsNull(oAdapter.IPAddress) Then
sIP = Trim(oAdapter.IPAddress(0))
Else
iReturn = 404
WScript.Quit iReturn
End If
Next
sIP = CStr(sIP)
aIP = Split(sIP, ".")
iOct1 = CInt(aIP(0))
iOct2 = CInt(aIP(1))
iOct3 = CInt(aIP(2))
iOct4 = CInt(aIP(3))
Now, if I change the declaration of the aIP array to either of the following:
aIP()
aIP(4)
and run
aIP = Split(sIP, ".")
I get
script.vbs(26, 1) Microsoft VBScript runtime error: Type mismatch
Changing the array assignment / split line to
aIP() = Split(sIP,".")
results in
script.vbs(26, 1) Microsoft VBScript runtime error: Subscript out of range
So I'm obviously doing something wrong.
It's also entirely possible that my original error message is completely unrelated to my array range, and WinPE just doesn't like my script (in which case, if anybody has any pointers, it'd be appreciated)
At the moment, I'm mounting my wim to get the install packages to make sure the WMI and Scripting packages are installed from the ADK.
There is nothing wrong with the code except the assumption being made about what Win32_NetworkAdapterConfiguration returns.
From MSDN - Win32_NetworkAdapterConfiguration class
Array of all of the IP addresses associated with the current network adapter. This property can contain either IPv6 addresses or IPv4 addresses. For more information, see IPv6 and IPv4 Support in WMI.
Because sIP could contain an IPv6 address the Split() will not work as expected. IPv6 addresses don't contain . as a separator so Split() will return a Array containing the original string as the first index only. Hence attempting to read anything other then aIP(0) will cause an
Microsoft VBScript runtime error:
Subscript out of range
error.
To avoid this use InStr() to check for the existence of . in the sIP variable first, you will also need to iterate through the oAdapter.IPAddress array to check each address to get the correct one, you can't assume IPAddress(0) will always be the right one.
Try this
Dim ips, ip
For Each oAdapter in cAdapters
ips = oAdapter.IPAddress
If IsArray(ips) Then
For Each ip In ips
If InStr(1, ip, ".") > 0 Then
sIP = Trim(ip)
Exit For
End If
Next
If Len(sIP) > 0 Then Exit For
Else
iReturn = 404
WScript.Quit iReturn
End If
Next
Untested on iPad sorry
I guess sIP variable contains some string which can not be splitted wity delimiter "."(ex: "somestringwithNoDOT")
So in the 1st case
aIP = Split(sIP,".") ' Split("somestringwithNoDOT",".")
statement returned only 1 string, which can not be coverted to Integer. So i returned Type mismatch error in below line
iOct1 = CInt(aIP(0)) ' returns Type mismatch error
In the 2nd case
aIP() = Split(sIP,".") ' Split("somestringwithNoDOT",".")
above statement will return 1 element, but aIP is array with NO elements. So this statement rturned "Subscript out of range" error
Resolution for this issue is to check whether correct value is passing to sIP

PrintCapabilities not returning Duplex for enabled printer

I have an HP 6500 printer that will print in Duplex when set appropriately.
I'm working on a program to print automatically to other printers, but I notice a problem with the PrintCapabilities for this printer - it does not contain JobDuplexAllDocumentsContiguously - the Duplex options.
The method is below. I can't post the results because they are too long. Does anyone know why this does not work as expected? I would like to confirm that a printer can print Duplex before I send it a job, but how?
Rick
Here is how I get the PrintCapabilites:
Dim pq As Printing.PrintQueue = Printing.LocalPrintServer.GetDefaultPrintQueue
' get a stored printticket that has Duplex = TwoSidedShortEdge
Dim ps As RG.Data.Program_Setting = RG.Data.Program_Setting.GetObject(Environment.MachineName)
Dim cs As RG.Data.Computer_Setting = ps.value_object_cast
Dim pt As Printing.PrintTicket = cs.print_ticket_document
'confirm that duplex is set
MsgBox(pt.Duplexing.ToString)
Dim ms = pq.GetPrintCapabilitiesAsXml(pt)
ms.Position = 0
Using fs = RG.Utilities.GetTempFileStream(".xml")
fs.Write(ms.ToArray, 0, ms.Length - 1)
fs.Close()
End Using
I have also tried pq.GetPrintCapabilitiesAsXml() and get the same results:

Send/Receive data via USB between Vex Cortex and .net

I'm coding in vb.net (I will accept answers in c# as I can approach this either way) and I need to send data to and receive data from a Vex Cortex. It has a USB port on it which I will be connecting to a computer to send it data via a program.
I have researched this and the .net side seems fairly straightforward. Here is the code I currently have:
Dim sensor As New SerialPort("COM1")
sensor.BaudRate = 9600
sensor.Parity = Parity.None
sensor.StopBits = StopBits.One
sensor.DataBits = 8
sensor.ReadTimeout = 300
sensor.WriteTimeout = 300
sensor.Handshake = Handshake.None
sensor.Open()
I was looking around and i found some steps to take to send data from the program, which is below:
Dim byteOut(5) As Byte
Dim byteIn(6) As Byte
Dim Voltage, i As Integer
Try
byteOut(0) = &H2 '2 bytes in output message
byteOut(1) = &H0 'should be 0 for NXT
byteOut(2) = &H0 '&H0 = reply expected &H80 = no reply expected
byteOut(3) = &HB '$HB = read battery command
sensor.Write(byteOut, 0, 4) '0 = offset into byteOut and 4 = number of bytes
'now read the reply
byteIn(0) = sensor.ReadByte ' number of bytes in message
byteIn(1) = sensor.ReadByte ' should be 0 for NXT
For i = 2 To 1 + byteIn(0) ' read rest of message
byteIn(i) = sensor.ReadByte()
Next
Voltage = byteIn(5) + byteIn(6) * 256 ' the voltage has low byte in 5 and high in 6
Console.Write(Voltage) 'display voltage
Catch ex As Exception
MsgBox(ex.ToString)
End Try
The example above is used to return battery data for an irrelevant device for this question. Basically I need to be able to read the data I send, and send data back to the computer, on the Vex Cortex.
The Cortex is coded in c and I'm using RobotC to compile and download the code to the Cortex. I can't figure out how to read the data for the life of me (example code said to do Serial.begin(9600); but this raises a compilation error in RobotC).
Can anyone assist me on how to read (and write back) data on the Cortex end of this transfer? I may need to ditch RobotC and I'm perfectly fine with that if a solution is proposed without it, so long as it's still c code.

How to receive variables in a post in google app engine that contains string with chars like: õ á?

email = self.request.get('email')
name = self.request.get('name')
mail.send_mail(sender="myemail", email=email, body=name, subject="sss " + name + "sdafsaã")
// added ã: the problem was that "sdafsaã" should be u"sdafsaã". with a "u" before the string. and now it works
then i get this
main.py", line 85, in post
subject="sss " + name + "sdafsa",
UnicodeDecodeError: 'ascii' codec can't decode byte 0xc3 in position 36: ordinal not in range(128)
the might have chars like õ ó and something like that.
for more details:
the code to run the worker(the code before)
the name is the one that is received from the datastore and contains chars like õ and ó...
taskqueue.add(url='/emailworker', params={'email': e.email, 'name': e.name})
thanks
Try reading a little about how unicode works in Python:
Dive Into Python - Unicode
Unicode In Python, Completely Demystified
Also, make sure you're running Python 2.5 if you are seeing this error on the development server.
You should use:
email = self.request.get('email')
name = self.request.get('name')
mail.send_mail(sender="myemail",
email=email,
body=name,
subject="hello " + name.encode('utf-8') + " user!")
The variable name is a unicode string and should encoded in utf-8 or in the kind of encode you are using in you web application before concatenating to other byte strings.
Without name.encode(), Python uses the default 7 bits ascii codec that can't encode that specific character.
the problem is joining 2 strings: ||| body = name + "ã" => error ||| body = name + u"ã" => works!!! |||
Try with encode
t ='việt ứng '
m = MyModel()
m.data = t.encode('utf-8')
m.put() #success!

Converting binary file to Base64 string

I need to convert uploaded binary files to base64 string format on the fly. I'm using ASP, Vbscript. Using Midori's component for base64 conversion. For small size files (<20K) the performance is okay. But when it exceeds 75 or 100K, its totally lost. Is there any efficient way to convert big binary files (2MB) to base64 string format?
Thanks in advance,
Kenney
I have solved this issue by implementing a .net component for converting to base64 string. The hard part is the binary data sent to the .net COM from ASP is received as a string. Convert.ToBase64() accepts only byte[]. So I tried converting string to byte[].
But the encoding available in .net (Unicode, ASCII, UTF) doesn't works fine. There are data loss, while these encodings are used. Finally I get it done by using StringReader object. Read char by char(16 bit) and converted them to (8 bit) byte[] array.
And the performance is best.
Regards,
Siva.
you should use the .NET methods Convert.ToBase64String and Convert.FromBase64String.
Use the Convert.FromBase64String( ) method. This will give you the binary
data back (as a byte array).
To convert binary data to a Base64 string see conversion functions from binary data to a string in vbscript
from http://www.motobit.com/tips/detpg_Base64Encode/
Function Base64EncodeBinary(inData)
Base64EncodeBinary = Base64Encode(BinaryToString(inData))
End Function
Function Base64Encode(inData)
'rfc1521
'2001 Antonin Foller, Motobit Software, http://Motobit.cz
Const Base64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"
Dim cOut, sOut, I
'For each group of 3 bytes
For I = 1 To Len(inData) Step 3
Dim nGroup, pOut, sGroup
'Create one long from this 3 bytes.
nGroup = &H10000 * Asc(Mid(inData, I, 1)) + _
&H100 * MyASC(Mid(inData, I + 1, 1)) + MyASC(Mid(inData, I + 2, 1))
'Oct splits the long To 8 groups with 3 bits
nGroup = Oct(nGroup)
'Add leading zeros
nGroup = String(8 - Len(nGroup), "0") & nGroup
'Convert To base64
pOut = Mid(Base64, CLng("&o" & Mid(nGroup, 1, 2)) + 1, 1) + _
Mid(Base64, CLng("&o" & Mid(nGroup, 3, 2)) + 1, 1) + _
Mid(Base64, CLng("&o" & Mid(nGroup, 5, 2)) + 1, 1) + _
Mid(Base64, CLng("&o" & Mid(nGroup, 7, 2)) + 1, 1)
'Add the part To OutPut string
sOut = sOut + pOut
'Add a new line For Each 76 chars In dest (76*3/4 = 57)
'If (I + 2) Mod 57 = 0 Then sOut = sOut + vbCrLf
Next
Select Case Len(inData) Mod 3
Case 1: '8 bit final
sOut = Left(sOut, Len(sOut) - 2) + "=="
Case 2: '16 bit final
sOut = Left(sOut, Len(sOut) - 1) + "="
End Select
Base64Encode = sOut
End Function
Function MyASC(OneChar)
If OneChar = "" Then MyASC = 0 Else MyASC = Asc(OneChar)
End Function
Use MSXML to do the encoding for you. Here is function encapsulating the procedure:-
Function ToBase64(rabyt)
Dim xml: Set xml = CreateObject("MSXML2.DOMDocument.3.0")
xml.LoadXml "<root />"
xml.documentElement.dataType = "bin.base64"
xml.documentElement.nodeTypedValue = rabyt
ToBase64 = xml.documentElement.Text
End Function
Note this will include linebreaks in the base64 encoding but most base64 decoders are tolerant of linebreaks. If not you could simpy use Replace(base64, vbLF, "") to remove them, this will still be quicker than a pure VBScript solution.
Edit Example usage:-
Dim sBase64: sBase64 = ToBase64(Request.BinaryRead(Request.TotalBytes))
I use next code for c#:
public static string ImageToBase64(Image image, ImageFormat format)
{
using (MemoryStream ms = new MemoryStream())
{
// Convert Image to byte[]
image.Save(ms, format);
byte[] imageBytes = ms.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
public static Image Base64ToImage(string base64String)
{
// Convert Base64 String to byte[]
byte[] imageBytes = Convert.FromBase64String(base64String);
MemoryStream ms = new MemoryStream(imageBytes, 0,
imageBytes.Length);
// Convert byte[] to Image
ms.Write(imageBytes, 0, imageBytes.Length);
Image image = Image.FromStream(ms, true);
return image;
}
for vbscript see http://www.freevbcode.com/ShowCode.asp?ID=5248 maybe help you.
There is a good discussion of this in base64-encode-string-in-vbscript.
In addition, I have found this site useful for trying to eek speed out of vb code. There are several variants of base 64 there for vb6 that are quite fast.
This is what worked for me
Function Base64DataURI(url)
'Create an Http object, use any of the four objects
Dim Http
Set Http = CreateObject("WinHttp.WinHttpRequest.5.1")
'Send request To URL
Http.Open "GET", url, False
Http.Send
'Get response data As a string and encode as base64
Base64DataURI = Encrypt(Http.ResponseText)
End Function
In my case the URL is a script that generates a barcode on the fly and needed to encode to include that in emails.
Encrypt is a pretty standard function we use to encode as Base64, but the main concept we needed was to get the file via URL not file system.

Resources