If statement in vb.net - vb.net

In my If-statement I have 6 conditions to test. Is there any way to mininmize this code below?
If (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("_default") AndAlso (Convert.ToInt32(Request.QueryString("numFormNumber")) = 1) AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("RequiredOwner_default") AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("cmbConsequence_default") AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("cmbLikelihood_default") AndAlso Not (DataBinder.Eval(e.Item.DataItem, "strControlId")).ToString.Contains("cmbSeverity_default") Then
End If

I don't know enough about the logic of you "if" condition, but you can make the code more clean if you will use variables for repeated code.
Dim strControlId As String = DataBinder.Eval(item, "strControlId")).ToString
If (strControlId.Contains("_default")_
AndAlso (Convert.ToInt32(Request.QueryString("numFormNumber")) = 1) _
AndAlso Not (strControlId.Contains("RequiredOwner_default")_
AndAlso Not (strControlId.Contains("cmbConsequence_default") _
AndAlso Not (strControlId.Contains("cmbLikelihood_default")_
AndAlso Not (strControlId.Contains("cmbSeverity_default") Then

Related

Visual Basic Or, OrElse still returning false

I am new to VB.net and i have little problem with this statement, i want to throw msgBox just if in txtBox txtTitul is not "Bc." or "" or "Ing." ...
and this is throwing msgBox everytime
If Not txtTitul.Text.Equals("Bc.") _
OrElse Not txtTitul.Text.Equals("") _
OrElse Not txtTitul.Text.Equals("Bc.") _
OrElse Not txtTitul.Text.Equals("Mgr.") _
OrElse Not txtTitul.Text.Equals("Ing.") _
OrElse Not txtTitul.Text.Equals("Mgr. art.") _
OrElse Not txtTitul.Text.Equals("Ing. arch.") _
OrElse Not txtTitul.Text.Equals("MUDr.") _
OrElse Not txtTitul.Text.Equals("MVDr.") _
OrElse Not txtTitul.Text.Equals("RNDr.") _
OrElse Not txtTitul.Text.Equals("PharmDr.") _
OrElse Not txtTitul.Text.Equals("PhDr.") _
OrElse Not txtTitul.Text.Equals("JUDr.") _
OrElse Not txtTitul.Text.Equals("PaedDr.") _
OrElse Not txtTitul.Text.Equals("ThDr.") Then
MsgBox("Neplatny titul!")
Exit Sub
End If
You don't want to use OrElse but AndAlso, because only if it's not one of those it's an invalid title (so not 1st and not 2nd and not 3rd and so on....).
But can i show you a much simpler and more maintainable approach?
Dim allowedTitles = {"Bc.","Ing.","Ing. arch.","MUDr.","MVDr.","RNDr.","PhDr.","PaedDr.","ThDr."}
If Not allowedTitles.Contains(txtTitul.Text) Then
MsgBox("Invalid title!")
End If
If you also want to accept lower-case, so ignore the case, you can use:
If Not allowedTitles.Contains(txtTitul.Text, StringComparer.InvariantCultureIgnoreCase) Then
MsgBox("Invalid title!")
End If
Consider your input is "Bc."
Not txtTitul.Text.Equals("Bc.") <- false
Not txtTitul.Text.Equals("") <- true
false OrElse true = true
Consider your input is "abc"
Not txtTitul.Text.Equals("Bc.") <- true
Not txtTitul.Text.Equals("") <- true
true OrElse true = true
For solution, you may consider Tim's answer.

InvalidCastException Specified cast is not valid

I wan't to make a PictureBox and a Label show if TextBox1 and TextBox2 Texts equal definite word.
But I receive an error...
Please, help
Here is the code:
Public Class Appearance
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If TextBox1.Text = "Brown" & TextBox2.Text = "Brown" Then
PictureBox4.Image = My.Resources.brown
PictureBox2.Image = My.Resources.blue
PictureBox5.Image = My.Resources.green
PictureBox4.Visible = True
PictureBox2.Visible = True
PictureBox5.Visible = True
Label7.Visible = True
Label8.Visible = True
Label9.Visible = True
End If
End Sub
End Class
In VB.NET & means string concatenation. You probably want to use AndAlso:
If TextBox1.Text = "Brown" AndAlso TextBox2.Text = "Brown" Then
Edit : Sorry, missed you wanted to compare both TextBox1 and TextBox2 values to one String Value
Right evaluation is already provided by Neolisk :
If TextBox1.Text = "Brown" AndAlso TextBox2.Text = "Brown" Then
EDIT : the following suggestion is wrong..
Replace this
If TextBox1.Text = "Brown" & TextBox2.Text = "Brown" Then
by this :
If TextBox1.Text = TextBox2.Text Then
EDIT : I leave the explanation here
If you write If TextBox1.Text = "Brown" & TextBox2.Text = "Brown" Then, and we suppose that TextBox2.Text is "Brown" what's happening is :
Since the & is for String concatenation in VB, just like +, TextBox1.Text will be compared to the chain "Brown" & TextBox2.Text = "Brown".
With "Brown" & TextBox2.Text = "Brown", "Brown" & TextBox2.Text will be evaluated first, since the & string concatener takes precedence over the = boolean evaluation. You'll get the concatenated string "BrownBrown" (= "Brown").
But then, you'll have "BrownBrown" = "Brown", and at this stage, the full chain of evaluation is If TextBox1.Text = "BrownBrown" = "Brown" Then.
TextBox1.Text = "BrownBrown" will be evaluated first and will return False. In the end, you're evaluating :
If False = "Brown" Then ' <- Boolean comparison with String Error !
Since you're new to VB, good to know :
Note that AndAlso has the shorcut feature. If the evaluation on the left part is False, the right part is not evaluated.
To evaluate both left and right, there is the And comparer. But, honestly, comparing
If False = True And "SameValue" = "SameValue" ' will always return False.
There is NO meaning in comparing the right side if the left is already False. You ought to know that this is a unique glitch of VB. However, I don't know if it was fixed since. But if not, the same applies for Or and OrElse.
=> You'd better use AndAlso and OrElse instead of And/Or from the start.

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)

Importing logon hours from active directory to SQL Server

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

Filtering DBNull With LINQ

Why does the following query raise the error below for a row with a NULL value for barrel when I explicitly filter out those rows in the Where clause?
Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
Where Not IsDBNull(row.Cal) AndAlso tiCal_drop.Text = row.Cal _
AndAlso Not IsDBNull(row.Tran) AndAlso tiTrans_drop.Text = row.Tran _
AndAlso Not IsDBNull(row.barrel) _
Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
Run-time exception thrown : System.Data.StrongTypingException - The value for column 'barrel' in table 'conformal' is DBNull.
How should my query / condition be rewritten to work as I intended?
By default, in strongly typed datasets, properties throw that exception if the field is null. You need to use the generated Is[Field]Null method :
Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
Where Not row.IsCalNull() AndAlso tiCal_drop.Text = row.Cal _
AndAlso Not row.IsTranNull() AndAlso tiTrans_drop.Text = row.Tran _
AndAlso Not row.IsbarrelNull() _
Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
Or the DataRow.IsNull method :
Dim query = From row As dbDataSet.conformalRow In dbDataSet.Tables("conformal") _
Where Not row.IsNull("Cal") AndAlso tiCal_drop.Text = row.Cal _
AndAlso Not row.IsNull("Tran") AndAlso tiTrans_drop.Text = row.Tran _
AndAlso Not row.IsNull("barrel") _
Select row.barrel
If query.Count() > 0 Then tiBarrel_txt.Text = query(0)
This worked for me.
Dim query = From row As dbDataSet.conformalRow
In dbDataSet.Tables("conformal") _
Where row.Cal.Length > 0 AndAlso tiCal_drop.Text = row.Cal _
AndAlso row.Tran.Length > 0 AndAlso tiTrans_drop.Text = row.Tran _
AndAlso row.barrel.Length > 0 _
Select row.barrel