Importing logon hours from active directory to SQL Server - sql-server-2005

I am trying to pull all the users from the Active Directory, I am able to pull all the records but when I read the data in the tables it displays as SYSTEM.BYTE[](for logonhours), need to convert before inserting that into SQL table.
I did a googling and found some solution like first converting that into byte then into a string and inserting it, where you can read the data, but I am not able to implement that.
Can anyone help me out?
I am inserting into SQL Server 2005 and importing all the data using SSIS ( since there is a limitation on ADSI when you query, you get only 1000 records I am using a custom script and setting a page default to more than 1000 to retrive all the records from active directory)
below is my custom script how I am pulling my records from ADSI:
' Microsoft SQL Server Integration Services user script component
' This is your new script component in Microsoft Visual Basic .NET
' ScriptMain is the entrypoint class for script components
Option Strict Off
Imports System
Imports System.Data
Imports System.DirectoryServices
Imports System.Math
Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper
Imports Microsoft.SqlServer.Dts.Runtime.Wrapper
Public Class ScriptMain
Inherits UserComponent
Public Overrides Sub CreateNewOutputRows()
Dim arrayDomains As String()
ReDim arrayDomains(1)
arrayDomains(0) = "LDAP://DC=cba,DC=acb,DC=com"
arrayDomains(1) = "LDAP://DC=abc,DC=bca,DC=com"
Dim Domain As String
For Each Domain In arrayDomains
Dim objSearch As New DirectorySearcher()
objSearch.SearchRoot = New DirectoryEntry(Domain)
objSearch.Filter = "(&(objectclass=user)(objectcategory=Person)(samAccountType=805306368))"
'(|(&(!(groupType:1.2.840.113556.1.4.803:=1))(groupType:1.2.840.113556.1.4.804:=14))(samAccountType=805306368))
objSearch.SearchScope = SearchScope.Subtree
objSearch.PageSize = 999
objSearch.ServerTimeLimit = New TimeSpan(0, 15, 0)
objSearch.ClientTimeout = New TimeSpan(0, 30, 0)
objSearch.PropertiesToLoad.Add("cn")
objSearch.PropertiesToLoad.Add("c")
objSearch.PropertiesToLoad.Add("department")
objSearch.PropertiesToLoad.Add("displayName")
objSearch.PropertiesToLoad.Add("distinguishedName")
objSearch.PropertiesToLoad.Add("employeeID")
objSearch.PropertiesToLoad.Add("extensionAttribute14")
objSearch.PropertiesToLoad.Add("extensionAttribute2")
objSearch.PropertiesToLoad.Add("givenName")
objSearch.PropertiesToLoad.Add("l")
objSearch.PropertiesToLoad.Add("lastLogon")
objSearch.PropertiesToLoad.Add("logonHours")
objSearch.PropertiesToLoad.Add("mail")
objSearch.PropertiesToLoad.Add("manager")
objSearch.PropertiesToLoad.Add("physicalDeliveryOfficeName")
objSearch.PropertiesToLoad.Add("postalCode")
objSearch.PropertiesToLoad.Add("pwdLastSet")
objSearch.PropertiesToLoad.Add("sn")
objSearch.PropertiesToLoad.Add("st")
objSearch.PropertiesToLoad.Add("streetAddress")
objSearch.PropertiesToLoad.Add("telephoneNumber")
objSearch.PropertiesToLoad.Add("title")
objSearch.PropertiesToLoad.Add("userAccountControl")
objSearch.PropertiesToLoad.Add("whenCreated")
Dim colQueryResults As SearchResultCollection
colQueryResults = objSearch.FindAll()
Dim objResult As SearchResult
For Each objResult In colQueryResults
'Console.WriteLine("3")
'
' Add rows by calling AddRow method on member variable called "<Output Name>Buffer"
' E.g., MyOutputBuffer.AddRow() if your output was named "My Output"
'
Output0Buffer.AddRow()
If objResult.Properties.Contains("cn") AndAlso objResult.Properties("cn")(0) IsNot Nothing Then
Output0Buffer.cn = objResult.Properties("cn")(0).ToString()
End If
If objResult.Properties.Contains("c") AndAlso objResult.Properties("c")(0) IsNot Nothing Then
Output0Buffer.c = objResult.Properties("c")(0).ToString()
End If
If objResult.Properties.Contains("department") AndAlso objResult.Properties("department")(0) IsNot Nothing Then
Output0Buffer.Department = objResult.Properties("department")(0).ToString()
End If
If objResult.Properties.Contains("displayName") AndAlso objResult.Properties("displayname")(0) IsNot Nothing Then
Output0Buffer.DisplayName = objResult.Properties("displayName")(0).ToString()
End If
If objResult.Properties.Contains("distinguishedName") AndAlso objResult.Properties("distinguishedName")(0) IsNot Nothing Then
Output0Buffer.DistinguishedName = objResult.Properties("distinguishedName")(0).ToString()
End If
If objResult.Properties.Contains("employeeID") AndAlso objResult.Properties("employeeID")(0) IsNot Nothing Then
Output0Buffer.EmployeeID = objResult.Properties("employeeID")(0).ToString()
End If
If objResult.Properties.Contains("extensionAttribute14") AndAlso objResult.Properties("extensionAttribute14")(0) IsNot Nothing Then
Output0Buffer.ExtensionAttribute14 = objResult.Properties("extensionAttribute14")(0).ToString()
End If
If objResult.Properties.Contains("extensionAttribute2") AndAlso objResult.Properties("extensionAttribute2")(0) IsNot Nothing Then
Output0Buffer.ExtensionAttribute2 = objResult.Properties("extensionAttribute2")(0).ToString()
End If
If objResult.Properties.Contains("givenName") AndAlso objResult.Properties("givenName")(0) IsNot Nothing Then
Output0Buffer.GivenName = objResult.Properties("givenName")(0).ToString()
End If
If objResult.Properties.Contains("l") AndAlso objResult.Properties("l")(0) IsNot Nothing Then
Output0Buffer.L = objResult.Properties("l")(0).ToString()
End If
If objResult.Properties.Contains("lastLogon") AndAlso objResult.Properties("lastLogon")(0) <> 0 AndAlso objResult.Properties("lastLogon")(0) IsNot Nothing Then
Output0Buffer.LastLogon = DateTime.Parse(DateTime.FromFileTime(objResult.Properties("lastLogon")(0).ToString()))
End If
'If objResult.Properties.Contains("pwdLastSet") AndAlso objResult.Properties("pwdLastSet")(0) <> 0 AndAlso objResult.Properties("pwdLastSet")(0) IsNot Nothing Then
' Output0Buffer.PwdLastSet = DateTime.Parse(DateTime.FromFileTime(objResult.Properties("pwdLastSet")(0)).ToString())
'End If
If objResult.Properties.Contains("logonHours") AndAlso objResult.Properties("logonHours")(0) IsNot Nothing Then
Output0Buffer.LogonHours = objResult.Properties("logonHours")(0).ToString()
End If
If objResult.Properties.Contains("mail") AndAlso objResult.Properties("mail")(0) IsNot Nothing Then
Output0Buffer.Mail = objResult.Properties("mail")(0).ToString()
End If
If objResult.Properties.Contains("manager") AndAlso objResult.Properties("manager")(0) IsNot Nothing Then
Output0Buffer.Manager = objResult.Properties("manager")(0).ToString()
End If
If objResult.Properties.Contains("physicalDeliveryOfficeName") AndAlso objResult.Properties("physicalDeliveryOfficeName")(0) IsNot Nothing Then
Output0Buffer.PhysicalDeliveryOfficeName = objResult.Properties("physicalDeliveryOfficeName")(0).ToString()
End If
If objResult.Properties.Contains("postalCode") AndAlso objResult.Properties("postalCode")(0) IsNot Nothing Then
Output0Buffer.PostalCode = objResult.Properties("postalCode")(0).ToString()
End If
If objResult.Properties.Contains("pwdLastSet") AndAlso objResult.Properties("pwdLastSet")(0) <> 0 AndAlso objResult.Properties("pwdLastSet")(0) IsNot Nothing Then
Output0Buffer.PwdLastSet = DateTime.Parse(DateTime.FromFileTime(objResult.Properties("pwdLastSet")(0)).ToString())
End If
'If objResult.Properties.Contains("pwdLastSet") AndAlso objResult.Properties("pwdLastSet")(0) IsNot Nothing Then
' Output0Buffer.PwdLastSet = objResult.Properties("pwdLastSet")(0).ToString()
'End If
If objResult.Properties.Contains("sn") AndAlso objResult.Properties("sn")(0) IsNot Nothing Then
Output0Buffer.Sn = objResult.Properties("sn")(0).ToString()
End If
If objResult.Properties.Contains("st") AndAlso objResult.Properties("st")(0) IsNot Nothing Then
Output0Buffer.St = objResult.Properties("st")(0).ToString()
End If
If objResult.Properties.Contains("streetAddress") AndAlso objResult.Properties("streetAddress")(0) IsNot Nothing Then
Output0Buffer.StreetAddress = objResult.Properties("streetAddress")(0).ToString()
End If
If objResult.Properties.Contains("telephoneNumber") AndAlso objResult.Properties("telephoneNumber")(0) IsNot Nothing Then
Output0Buffer.TelephoneNumber = objResult.Properties("telephoneNumber")(0).ToString()
End If
If objResult.Properties.Contains("title") AndAlso objResult.Properties("title")(0) IsNot Nothing Then
Output0Buffer.Title = objResult.Properties("title")(0).ToString()
End If
If objResult.Properties.Contains("userAccountControl") AndAlso objResult.Properties("userAccountControl")(0) IsNot Nothing Then
Output0Buffer.UserAccountControl = objResult.Properties("userAccountControl")(0).ToString()
End If
If objResult.Properties.Contains("whenCreated") AndAlso objResult.Properties("whenCreated")(0) IsNot Nothing Then
Output0Buffer.WhenCreated = CDate(objResult.Properties("whenCreated")(0).ToString())
End If
Next
Next
End Sub
End Class

You need to create a function to convert that OctetString to a String. If you directly convert it that will show System.Byte[] this is because OctetString is a Byte Array type. Fof the function do something like this
Private Function ConvertByteArrayToString(xArray As Byte()) As String
Dim [sByte] As String = ""
For Each x As Byte In xArray
[sByte] += x.ToString() & " "
Next
Return [sByte]
End Function
and use it like such
If objResult.Properties.Contains("logonHours") AndAlso objResult.Properties("logonHours")(0) IsNot Nothing Then
Output0Buffer.LogonHours = ConvertByteArrayToString(objResult.Properties("logonHours"))
End If

Related

Determine if screen is active or not from Windows 8 Registry

I am looking at monitors list in
HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Enum\DISPLAY
In Windows 7, there are a subkey under each screen node named "Control" that indicate if the screen is active or not.
In Windows 8 there are no such subkey.
How can determine if a monitor is active or not from the Windows 8 registry?
Try this code (I verified this):
Public Function GetMonitorDetails() As List(Of WSGetLoginData.Monitor)
'Open the Display Reg-Key
Dim wmiPNPID As New List(Of String)
Dim mc As System.Management.ManagementClass
Dim moc As ManagementObjectCollection
Dim PathPNPID As String
mc = New ManagementClass("Win32_DesktopMonitor")
moc = mc.GetInstances()
For Each mo In moc
PathPNPID = mo.Item("PNPDeviceID")
If PathPNPID.Trim <> "" AndAlso PathPNPID.Contains("\") Then
PathPNPID = PathPNPID.Substring(PathPNPID.LastIndexOf("\") + 1)
wmiPNPID.Add(PathPNPID.ToUpper)
End If
Next
Dim Display As RegistryKey = Registry.LocalMachine
Dim bFailed As [Boolean] = False
Dim obj_ListMonitor As New List(Of WSGetLoginData.Monitor)
Try
Display = Registry.LocalMachine.OpenSubKey("SYSTEM\CurrentControlSet\Enum\DISPLAY")
Catch
bFailed = True
End Try
If Not bFailed And (Display IsNot Nothing) Then
'Get all MonitorIDss
For Each sMonitorID As String In Display.GetSubKeyNames()
Dim MonitorID As RegistryKey = Display.OpenSubKey(sMonitorID)
If MonitorID IsNot Nothing Then
'Get all Plug&Play ID's
For Each sPNPID As String In MonitorID.GetSubKeyNames()
Dim PnPID As RegistryKey = MonitorID.OpenSubKey(sPNPID)
If PnPID IsNot Nothing Then
Dim sSubkeys As String() = PnPID.GetSubKeyNames()
'Check if Monitor is active
'If Array.IndexOf(sSubkeys, "Control") > -1 Then
If Not wmiPNPID Is Nothing AndAlso wmiPNPID.Count > 0 AndAlso wmiPNPID.Contains(sPNPID.ToUpper) Then
If Array.IndexOf(sSubkeys, "Device Parameters") > -1 Then
Dim DevParam As RegistryKey = PnPID.OpenSubKey("Device Parameters")
Dim sSerial As String = ""
Dim sModel As String = ""
'Define Search Keys
Dim sSerFind As New String(New Char() {ChrW(0), ChrW(0), ChrW(0), ChrW(&HFF)})
Dim sModFind As New String(New Char() {ChrW(0), ChrW(0), ChrW(0), ChrW(&HFC)})
'Get the EDID code
Dim bObj As Byte() = TryCast(DevParam.GetValue("EDID", Nothing), Byte())
If bObj IsNot Nothing Then
'Get the 4 Vesa descriptor blocks
Dim sDescriptor As String() = New String(3) {}
sDescriptor(0) = Encoding.[Default].GetString(bObj, &H36, 18)
sDescriptor(1) = Encoding.[Default].GetString(bObj, &H48, 18)
sDescriptor(2) = Encoding.[Default].GetString(bObj, &H5A, 18)
sDescriptor(3) = Encoding.[Default].GetString(bObj, &H6C, 18)
'Search the Keys
For Each sDesc As String In sDescriptor
If sDesc.Contains(sSerFind) Then
sSerial = sDesc.Substring(4).Replace(vbNullChar, "").Trim()
End If
If sDesc.Contains(sModFind) Then
sModel = sDesc.Substring(4).Replace(vbNullChar, "").Trim()
End If
Next
End If
If Not String.IsNullOrEmpty(sSerial) AndAlso sSerial.Trim <> "" Then
Dim insertar As Boolean = True
If Not obj_ListMonitor Is Nothing AndAlso obj_ListMonitor.Count > 0 Then
For k As Integer = 0 To obj_ListMonitor.Count - 1
If obj_ListMonitor(k).SerialNumber.Trim = sSerial Then
insertar = False
Exit For
End If
Next
End If
If insertar Then
Dim obj_monitor As New WSGetLoginData.Monitor
obj_monitor.UUID = Security.FingerPrint.Value(sModel & sSerial)
obj_monitor.Modelo = sModel
obj_monitor.SerialNumber = sSerial
obj_ListMonitor.Add(obj_monitor)
End If
End If
End If
End If
End If
Next
End If
Next
End If
Return obj_ListMonitor
End Function

get row data from data gridview on vb.net 2012

I want get data from 1 row of a DataGridView, I select to my textbox
this is my code,
Private Sub DataGridView1_CurrentCellChanged(sender As Object, e As EventArgs) Handles DataGridView1.CurrentCellChanged
Dim dColums(0) As DataColumn
dColums(0) = dsetmember.Tables("member").Columns(0)
dsetmember.Tables("member").PrimaryKey = dColums
'MessageBox.Show(DataGridView1.CurrentRow.Index, 1)
If DataGridView1.CurrentRow.Index = -1 Then
txtNamaMember.Text = ""
txtKodeMember.Text = ""
txtNoHP.Text = ""
Else
Dim dr As DataRow = dsetmember.Tables("member").Rows.Find(DataGridView1.Item(DataGridView1.CurrentRow.Index, 0))
txtKodeMember.Text = dr(0)
End If
End Sub
I get this error, nullreferenceException was unhandled
Object reference not set to an instance of an object.
thx b4.
Try change this part ..
If DataGridView1.CurrentRow.Index = -1 Then
txtNamaMember.Text = ""
txtKodeMember.Text = ""
txtNoHP.Text = ""
Else
Dim dr As DataRow = dsetmember.Tables("member").Rows.Find(DataGridView1.Item(DataGridView1.CurrentRow.Index, 0))
txtKodeMember.Text = dr.item(0)
End If
The error happens in the assigniment of dr(0) to the textbox.Text.
This means that the Find method has not found the value passed and so the result is NULL.
Trying to reference dr(0) when dr is Nothing is like writing NOTHING(0) and, of course, this will fail
Dim dr As DataRow = dsetmember.Tables("member").Rows.Find(DataGridView1.Item(DataGridView1.CurrentRow.Index, 0))
if dr IsNot Nothing then
txtKodeMember.Text = dr(0)
else
MessageBox.Show("Value not found")
End If
Also remember that the Find method search the value passed on the primary key column(s) of the table. Are you sure that the first column of the grid contains the primary keys?

nullable object must have a value vb

I have a bigger code block which I have recreated in this simpler example:
Dim evalcheck As Boolean
Dim aEntityId, bEntityId As Integer?
Dim aCheckNumber, bCheckNumber As Integer?
aEntityId = Nothing
bEntityId = Nothing
aCheckNumber = Nothing
bCheckNumber = Nothing
evalcheck = aEntityId = bEntityId And aCheckNumber = bCheckNumber
I get nullable object must have a value when I compare Nothing to Nothing pairs.
Is there a quick fix for the eval part -
evalcheck = aEntityId = bEntityId And aCheckNumber = bCheckNumber
You should really use parentheses for readability. Even then, the comparison is ugly.
If ((aEntityId IsNot Nothing And bEntityId IsNot Nothing) AndAlso (aEntityId = bEntityId)) Or (aEntityId Is Nothing And bEntityId Is Nothing) Then
If ((aCheckNumber IsNot Nothing And bCheckNumber IsNot Nothing) AndAlso (aEntityId = bEntityId)) Or (aCheckNumber Is Nothing And bCheckNumber Is Nothing) Then
evalcheck = True
Else
evalcheck = False
End If
Else
evalcheck = False
End If
I prefer this method better though
Private Function NullableIntsEqual(ByVal a As Integer?, ByVal b As Integer?) As Boolean
If ((a IsNot Nothing And b IsNot Nothing) AndAlso (a = b)) Or (a Is Nothing And b Is Nothing) Then
Return True
Else
Return False
End If
End Function
You evalcheck line becomes
evalcheck = NullableIntsEqual(aEntityId, bEntityId) And NullableIntsEqual(aCheckNumber, bCheckNumber)

Linq to entities. GetPropety(name).GetValue not recognised by linq

I have a listbox on my xaml form that I bound to a List(Of MyType) property. I populated this list like so:
Dim fields As List(Of CheckableFields) = New List(Of CheckableFields)
Using context As ITIPEntities = New ITIPEntities()
Try
Dim propertyInfoList As List(Of PropertyInfo) = GetType(PC).GetProperties().ToList()
For Each pI In propertyInfoList
If (pI.PropertyType <> GetType(EntityState) _
And pI.PropertyType <> GetType(EntityKey) _
And pI.PropertyType <> GetType(EntityCollection(Of DiskDrive)) _
And pI.PropertyType <> GetType(EntityCollection(Of Memory)) _
And pI.PropertyType <> GetType(EntityCollection(Of Monitor)) _
And pI.PropertyType <> GetType(EntityCollection(Of Network)) _
And pI.PropertyType <> GetType(EntityCollection(Of Processor))) Then
fields.Add(New CheckableFields(pI.Name))
End If
Next
Catch ex As Exception
End Try
End Using
Now I'm at the point where the user selects the fields they want included in a report and I need to iterate over the required fields. This is my linq query:
For Each checkedField In _requiredFields
If checkedField.IsChecked Then
If checkedField.FieldData IsNot Nothing AndAlso checkedField.FieldData.Trim IsNot String.Empty Then
Dim fieldData As String = checkedField.FieldData
Dim name As String = checkedField.Name
lquery = From comp In lquery Where CType(comp.GetType.GetProperty(name).GetValue(comp, Nothing), String).ToUpper.Contains(fieldData.ToUpper) Select comp
End If
End If
Next
Which throws the exception that linq doesn't recognize the GetValue method.
How can I get the property values dynamically?
Edit:
I couldn't find a way to do this with Linq to Entities, but I did find a way without Linq that works for me:
For Each field In _requiredFields
If field.IsChecked Then
reportGenerator.AllFields.Add(field.Name)
If field.FieldData IsNot Nothing Then
For i As Integer = pcs.Count - 1 To 0 Step -1
Dim compPropertyValue As String = CType(pcs(i).GetType().GetProperty(field.Name).GetValue(pcs(i), Nothing), String).ToUpper()
If Not compPropertyValue.Contains(field.FieldData.ToUpper()) Then
pcs.RemoveAt(i)
End If
Next i
End If
End If
Next
This construct is not supported in LINQ-to-Entities. It is a designed limitation.
Try using Entity SQL instead as shown in the following example:
"SELECT VALUE comp From COMPs AS comp WHERE comp." & name & ".ToUpper().Contains(" & fieldData & ".ToUpper()"

How do I invoke HasValue on a nullable property of an object via reflection?

This function loops all properties of an object to create the updatequery to save te object to the DB.
We had to make some changes to it because of the introduction of nullable properties.
If the property is nullable we would like to check the 'HasValue' property.
This does works when it has a value. When the property has no value we get an 'Non-static method requires a target'-error at the CBool-line
Any suggestions?
An other way to check the 'HasValue'-prop of a property using reflection?
Thanks.
Private Function GetUpdateQuery(ByVal obj As Object, ByRef params As List(Of SqlParameter), Optional ByVal excl As String() = Nothing) As String
Dim sql As String = String.Empty
Dim props As PropertyInfo() = obj.GetType().GetProperties
If excl Is Nothing Then
excl = New String() {}
End If
For Each prop As PropertyInfo In props
Try
If Not excl.Contains(prop.Name) And prop.CanWrite = True Then
sql &= String.Format("{0} = #{1},", prop.Name, prop.Name)
Dim param As SqlParameter
Dim value As Object
If prop.PropertyType.IsGenericType AndAlso prop.PropertyType.GetGenericTypeDefinition() = GetType(Nullable(Of )) Then
If CBool(prop.PropertyType.GetProperty("HasValue").GetValue(prop.GetValue(obj, Nothing), Nothing)) Then
value = prop.GetValue(obj, Nothing)
Else
value = DBNull.Value
End If
Else
If prop.GetValue(obj, Nothing) = Nothing Then
value = DBNull.Value
Else
value = prop.GetValue(obj, Nothing)
End If
End If
param = ConnSql.CreateParameter("#" & prop.Name, value)
params.Add(param)
End If
Catch ex As Exception
End Try
Next
sql = sql.Substring(0, sql.Length - 1)
Return sql
End Function
You do not need the following If. You can remove it.
If prop.PropertyType.IsGenericType AndAlso prop.PropertyType.GetGenericTypeDefinition() = GetType(Nullable(Of )) Then
BUT you do need to fix the following If:
If prop.GetValue(obj, Nothing) = Nothing Then
to
If prop.GetValue(obj, Nothing) IS Nothing Then
--
Complete code:
Private Function GetUpdateQuery(ByVal obj As Object, ByRef params As List(Of SqlParameter), Optional ByVal excl As String() = Nothing) As String
Dim sql As String = String.Empty
Dim props As PropertyInfo() = obj.GetType().GetProperties
If excl Is Nothing Then
excl = New String() {}
End If
For Each prop As PropertyInfo In props
If Not excl.Contains(prop.Name) And prop.CanWrite = True Then
sql &= String.Format("{0} = #{1},", prop.Name, prop.Name)
Dim param As SqlParameter
Dim value As Object
If prop.GetValue(obj, Nothing) Is Nothing Then
value = DBNull.Value
Else
value = prop.GetValue(obj, Nothing)
End If
param = ConnSql.CreateParameter("#" & prop.Name, value)
params.Add(param)
End If
Next
sql = sql.Substring(0, sql.Length - 1)
Return sql
End Function