Placing a collection of values into a For...each loop - vb.net

I have this code written to return a collection of an object with properties as follows:
Public Shared Function Create() As Collection(Of Element)
Return New Collection(Of Element)() From { _
New Element() With { _
.Group = 1, _
.Period = 1, _
.Name = "Hydrogen" _
}, _
New Element() With { _
.Group = 18, _
.Period = 1, _
.Name = "Helium" _
}, _
New Element() With { _
.Group = 1, _
.Period = 2, _
.Name = "Lithium" _
}
}
End Function
I would now like to get these values from a database, but I can't figure out how to reformat the code. My returning procedure should be something like this:
Public Shared Function CreateDB() As Collection(Of Element)
Using db As New DataClassesDataContext(ACCCon)
Dim rows = (From row In db.PeriodicTableQs
Order By row.ID
Select row).ToList()
For Each s In rows
<<collect the elements here as result>>
<<eg, New Element() With {.Group = s.Group}>>
Next
End Using
Return Result
End Function
Thanks!

Try this:
Public Shared Function CreateDB() As Collection(Of Element)
Dim ACCCon As String = "ConnectionString"
Using db As New DataClassesDataContext(ACCCon)
Dim List = db.PeriodicTableQs.
OrderBy(Function(Q) Q.ID).ToList.
Select(Function(row)
Return New Element With {
.Group = row.Group,
.Name = row.Name,
.Period = row.Period
}
End Function)
End Using
Return New Collection(Of Element)(List)
End Function

Related

object Collection Containing a List of IDs Linq

I have a list box and the user is able to multi-select. I want to use Linq and bring back the records of the selected IDs that the user selects. I need to bring back the full object record for each selected ID
Here is the contact object along with collection object
Namespace MODEL
<System.Serializable()> _
Public Class ContactCollection
Inherits System.Collections.ObjectModel.Collection(Of Contact)
Implements IList(Of Contact)
End Class
End Namespace
Namespace MODEL
<System.Serializable()> _
Public Class Contact
Private mContactID As Int32 = 0
Private mFirstName As String
Private mLastName As String
Public Property ContactID As Int32
Get
Return mContactID
End Get
Set(value As Int32)
mContactID = value
End Set
End Property
Public Property FirstName As String
Get
Return mFirstName
End Get
Set(value As String)
mFirstName = value
End Set
End Property
Public Property LastName As String
Get
Return mLastName
End Get
Set(value As String)
mLastName = value
End Set
End Property
End Class
End Namespace
Adding 5 Records to the collection object
Dim objCollection As New MODEL.ContactCollection
Dim obj As New MODEL.Contact
objCollection.Add(New MODEL.Contact With {
.ContactID = 1, _
.FirstName = "John", _
.LastName = "Smtih" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 2, _
.FirstName = "Mark", _
.LastName = "Davis" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 3, _
.FirstName = "Tom", _
.LastName = "Howe" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 4, _
.FirstName = "Jerry", _
.LastName = "Thomas" _
})
objCollection.Add(New MODEL.Contact With {
.ContactID = 5, _
.FirstName = "Jane", _
.LastName = "Marry" _
})
This is the selected contact List from the list box
Dim lstContacts As New List(Of Integer)
lstContacts.Add(2)
lstContacts.Add(4)
I am not sure what to do at this point with Linq to find the values. I think I have to use contains but I have tried may different ways but I was unable to get the values.
I have tried this Linq but does not work or bring any records back
Dim objSearch from SearchContacts in objCollection
Where (lstContacts.Contains(SearchContacts.ContactID))
To get the Ids, try that :
Dim ids As IEnumerable(Of Int32) = myListBox.SelectedItems _
.OfType(Of Contact)() _
.Select( Function(c) c.ContactID ) _
Edit
If you want the Contacts, you can just just :
Dim ids As IEnumerable(Of Contact) = myListBox.SelectedItems _
.OfType(Of Contact)()
And if you want the contacts in a separate copied collection, you can :
Dim ids As List(Of Contact) = myListBox.SelectedItems _
.OfType(Of Contact)() _
.ToList()
Last (if think this is your real question - just tell and I erase everything above)
Dim selectedContacts As IEnumerable(Of MODEL.Contact) = From contact In objCollection
Join id In lstContacts
On contact.ContactID Equals id
Select contact

Get current URL from active tab chrome vb net?

I have search on google with keyword same as this question title.
Some code not work or complicated explanation, even in stackoverflow link.
I found one link work here.
But that code result is page title, not url.
How to make this code below to retrieve current url active tab on chrome?
here the code,
'//Grab all the Chrome processes
Dim chrome() As Process = Process.GetProcessesByName("chrome")
'//Exit if chrome isn't running
If chrome.Length <= 0 Then Exit Sub
For Each chromeProcess As Process In chrome
'//If the chrome process doesn't have a window handle then ignore it
If chromeProcess.MainWindowHandle <> IntPtr.Zero Then
'//To find the tabs we first need to locate something reliable - the 'New Tab' button
Dim rootElement As AutomationElement = AutomationElement.FromHandle(chromeProcess.MainWindowHandle)
Dim condNewTab As Condition = New PropertyCondition(AutomationElement.NameProperty, "New Tab")
Dim elemNewTab As AutomationElement = rootElement.FindFirst(TreeScope.Descendants, condNewTab)
'//Get the tabstrip by getting the parent of the 'new tab' button
Dim tWalker As TreeWalker = TreeWalker.ControlViewWalker
Dim elemTabStrip As AutomationElement = tWalker.GetParent(elemNewTab)
'//Loop through all the tabs and get the names which is the page title
Dim tabItemCondition As Condition = New PropertyCondition(AutomationElement.ControlTypeProperty, ControlType.TabItem)
For Each tabItem As AutomationElement In elemTabStrip.FindAll(TreeScope.Children, tabItemCondition)
Debug.WriteLine(tabItem.Current.Name)
Next
End If
Next
Solved, From another forum,
Imports System.Windows.Automation
Module GoogleChrome
Private Const ChromeProcess As [String] = "chrome"
Private Const AddressCtl As [String] = "Address and search bar"
Public Function GetChromeActiveWindowUrl() As [String]
Dim procs = Process.GetProcessesByName(ChromeProcess)
If (procs.Length = 0) Then
Return [String].Empty
End If
Return procs _
.Where(Function(p) p.MainWindowHandle <> IntPtr.Zero) _
.Select(Function(s) GetUrlControl(s)) _
.Where(Function(p) p IsNot Nothing) _
.Select(Function(s) GetValuePattern(s)) _
.Where(Function(p) p.Item2.Length > 0) _
.Select(Function(s) GetValuePatternUrl(s)) _
.FirstOrDefault
End Function
Private Function GetUrlControl( _
proses As Process) _
As AutomationElement
Dim propCondition = _
New PropertyCondition( _
AutomationElement.NameProperty, _
AddressCtl)
Return AutomationElement _
.FromHandle(proses.MainWindowHandle) _
.FindFirst( _
TreeScope.Descendants, _
propCondition)
End Function
Private Function GetValuePatternUrl( _
element As Tuple(Of _
AutomationElement, AutomationPattern())) As [String]
Dim ap = element.Item2(0)
Dim ovp = element.Item1.GetCurrentPattern(ap)
Dim vp = CType(ovp, ValuePattern)
Return vp.Current.Value
End Function
Private Function GetValuePattern( _
element As AutomationElement) _
As Tuple(Of _
AutomationElement, _
AutomationPattern())
Return New Tuple(Of _
AutomationElement, _
AutomationPattern())( _
element, _
element.GetSupportedPatterns())
End Function
End Module
If you are using .Net framework 2.0 it works for Google Chrome 55 And Firefox. Send the process name to the method ("CHROME" or "FIREFOX"). Also, you must import UIAutomationClient.dll. I hope it helps someone.
private string GetBrowserUrlActivaChromeFirefox(string process)
{
Process[] procsChrome = Process.GetProcessesByName(process);
foreach (Process chrome in procsChrome)
{
if (chrome.MainWindowHandle == IntPtr.Zero)
continue;
UIAutomationClient.CUIAutomation element = new UIAutomationClient.CUIAutomation();
UIAutomationClient.IUIAutomationElement root = element.ElementFromHandle(chrome.MainWindowHandle);
if (element == null)
return "";
UIAutomationClient.IUIAutomationCondition condition1 = element.CreatePropertyCondition(UIAutomationClient.UIA_PropertyIds.UIA_ProcessIdPropertyId, chrome.Id);
UIAutomationClient.IUIAutomationCondition condition2 = element.CreatePropertyCondition(UIAutomationClient.UIA_PropertyIds.UIA_IsControlElementPropertyId, true);
UIAutomationClient.IUIAutomationCondition condition3 = element.CreatePropertyCondition(UIAutomationClient.UIA_PropertyIds.UIA_IsContentElementPropertyId, true);
UIAutomationClient.IUIAutomationCondition condition4 = element.CreatePropertyCondition(UIAutomationClient.UIA_PropertyIds.UIA_ControlTypePropertyId, UIAutomationClient.UIA_ControlTypeIds.UIA_EditControlTypeId);
UIAutomationClient.IUIAutomationCondition[] conditions = new UIAutomationClient.IUIAutomationCondition[4];
conditions[0] = condition1;
conditions[1] = condition2;
conditions[2] = condition3;
conditions[3] = condition4;
UIAutomationClient.IUIAutomationCondition andCondition = element.CreateAndConditionFromArray(conditions);
UIAutomationClient.IUIAutomationElement elementx = root.FindFirst(UIAutomationClient.TreeScope.TreeScope_Descendants, andCondition);
return ((UIAutomationClient.IUIAutomationValuePattern)elementx.GetCurrentPattern(UIAutomationClient.UIA_PatternIds.UIA_ValuePatternId)).CurrentValue.ToString();
}
return string.Empty;
}
This C# code works for me on non-English browsers:
// Check for Chrome
if (processName.Equals("chrome"))
{
Process[] procsChrome = Process.GetProcessesByName("chrome");
foreach (Process chrome in procsChrome)
{
// the chrome process must have a window
if (chrome.MainWindowHandle == IntPtr.Zero)
continue;
try
{
CUIAutomation _automation = new CUIAutomation();
var appElement = _automation.ElementFromHandle(chrome.MainWindowHandle);
IUIAutomationCondition[] conditionArray = new IUIAutomationCondition[3];
conditionArray[0] = _automation.CreatePropertyCondition(UIA_PropertyIds.UIA_ProcessIdPropertyId, chrome.Id);
conditionArray[1] = _automation.CreatePropertyCondition(UIA_PropertyIds.UIA_NamePropertyId, "Google Chrome");
conditionArray[2] = _automation.CreatePropertyCondition(UIA_PropertyIds.UIA_ControlTypePropertyId, UIA_ControlTypeIds.UIA_PaneControlTypeId);
IUIAutomationCondition conditions = _automation.CreateAndConditionFromArray(conditionArray);
IUIAutomationElement frameElement = appElement.FindFirst(TreeScope.TreeScope_Subtree, conditions);
if (frameElement != null)
{
conditionArray = new IUIAutomationCondition[2];
conditionArray[0] = _automation.CreatePropertyCondition(UIA_PropertyIds.UIA_ProcessIdPropertyId, chrome.Id);
conditionArray[1] = _automation.CreatePropertyCondition(UIA_PropertyIds.UIA_ControlTypePropertyId, UIA_ControlTypeIds.UIA_EditControlTypeId);
conditions = _automation.CreateAndConditionFromArray(conditionArray);
frameElement = frameElement.FindFirst(TreeScope.TreeScope_Descendants, conditions);
if (frameElement != null)
return ((IUIAutomationValuePattern)frameElement.GetCurrentPattern(10002)).CurrentValue;
}
}
catch (Exception e)
{
continue;
}
}
}
The COM interface is much more efficient then the old one from System.Windows.Automation.

local variable 'request' cannot be referred to before it is declared

Dim list = New List(Of ECozum.HPM.Helper.Models.CustomData)
list.Add(cdata)
Dim request = New HttpPostRequestMessage() With { _
.User = New User() With { _
.Verify = 1, _
.VerifyFailAct = 1, _
.Id = 2 _
}, _
.Order = New Order() With { _
.DateTime = DateTime.UtcNow.ToString("u"), _
.Reference = Guid.NewGuid().ToString() _
}, _
.Payment = New Payment() With { _
.CData = list, _
.Method = New List(Of Integer)() From { _
-1 _
}, _
.Amount = tutar, _
.AmntEdit = 1, _
.SuccessUrl = "http://localhost:50/sonuc.aspx?s=basarili", _
.FailUrl = "http://localhost:50/sonuc.aspx?s=basarisiz", _
.ReturnUrl = "http://localhost:50/sonuc.aspx?s=return" _
}, _
.HashMethod = CInt(Hash.HashType.HMACSHA256) _
}
In this page I get the error:
"local variable 'request' cannot be referred to before it is declared"
at line: tutar = Request.QueryString("tutar")
Dim request = New HttpPostRequestMessage() change this line. Use any random name like 'requestobject' or 'rnd123'. Since you have it declared as a variable, it is conflicting with default request object.

How to return from ienumerable function in vb.net

Public Shared Function GetDataSet() As IEnumerable(Of SerialData)
Dim sCon As New SQLConnect
Dim strsql As String
Dim p As New Control
sCon.sqlAdp = New SqlDataAdapter
strsql = "select serialid," & _
" serialno," & _
" serialdesc," & _
" b.materialname," & _
" b.drawing," & _
" a.workorder," & _
" isnull((select top 1 patno from patternmaster where patid = a.patid),'Not Defined') as patno," & _
" case when a.activeflag = 1 then 'True' else 'False' end as activeflag" & _
" from serialmaster a," & _
" materialmaster b" & _
" where 1 = 1" & _
" and a.materialid = b.materialid" & _
" and b.activeflag = 1"
sCon.sqlCmd.CommandText = strsql
sCon.sqlAdp.SelectCommand = sCon.sqlCmd
sCon.sqlAdp.Fill(sCon.DS, "Listing")
Dim dtTable As DataTable
dtTable = sCon.DS.Tables("Listing")
' For Each row As DataRow In dtTable.Rows
' Return dtTable.AsEnumerable().[Select](Function(row) New With { _
' Key .serialid = row("serialid"), _
' Key .serialno = row("serialno"), _
' Key .serialdesc = row("serialdesc"), _
' Key .materialname = row("materialname"), _
' Key .drawing = row("drawing"), _
' Key .workorder = row("workorder"), _
' Key .patno = row("patno") _
'})
' Next
For Each row As DataRow In dtTable.Rows
p.serialid.Add(row("serialid"))
p.serialno.Add(row("serialno"))
p.serialdesc.Add(row("serialdesc"))
p.materialname.Add(row("materialname"))
p.drawing.Add(row("drawing"))
p.workorder.Add(row("workorder"))
p.patno.Add(row("patno"))
Next
Return p
End Function
Control class:
Public Class Control
Public serialid As New Generic.List(Of String)
Public serialno As New Generic.List(Of String)
Public serialdesc As New Generic.List(Of String)
Public materialname As New Generic.List(Of String)
Public drawing As New Generic.List(Of String)
Public workorder As New Generic.List(Of String)
Public patno As New Generic.List(Of String)
Public result As New Generic.List(Of String)
End Class
ServerSidePro class:
Public Class ServerSidePro
Implements System.Web.IHttpHandler
Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest
Dim d As New Control
' Those parameters are sent by the plugin
Dim iDisplayLength = Integer.Parse(context.Request("iDisplayLength"))
Dim iDisplayStart = Integer.Parse(context.Request("iDisplayStart"))
Dim iSortCol = Integer.Parse(context.Request("iSortCol_0"))
Dim iSortDir = context.Request("sSortDir_0")
'Fetch the data from a repository (in my case in-memory)
'Dim p = SerialData.GetDataSet()
Dim p = DirectCast(SerialData.GetDataSet(), IEnumerable(Of SerialData))
' prepare an anonymous object for JSON serialization
Dim aaData2 = p.select(Function(h) New With {h.serialid, h.serialno, h.serialdesc, _
h.materialname, h.drawing, h.workorder, h.patno}).Skip(iDisplayStart).Take(iDisplayLength)
Dim str As New List(Of String())
For Each item In aaData2
Dim arr As String() = New String(6) {item.serialid, item.serialno, item.serialdesc, _
item.materialname, item.drawing, item.workorder, item.patno}
str.Add(arr)
Next
Dim result = New With { _
Key .iTotalRecords = p.Count(), _
Key .iTotalDisplayRecords = p.Count(), _
Key .aaData = str
}
Dim serializer As New JavaScriptSerializer()
Dim json = serializer.Serialize(result)
context.Response.ContentType = "application/json"
context.Response.ClearHeaders()
context.Response.Write(json)
context.Response.End()
'Return d
End Sub
ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
Get
Return False
End Get
End Property
End Class
How to return dataset from this function it is giving error Unable to cast object of type 'Control' to type 'System.Collections.Generic.IEnumerable'.
Easiest way is to use a List() object. I would restructure your class
Public Class Control
Public LControl As New List(Of Control)
Public serialid As String
Public serialno As String
Public serialdesc As String
Public materialname As String
Public drawing As String
Public workorder As String
Public patno As String
Public result As String
End Class
​

How to use the vb equivalent of ++ for an index property in a Linq query projecting a new type

I'd normally do this in C# but since I've got to get this code in this particular assembly which is a vb.net one, I'm stuck.
Here's my linq query:
Dim i As Integer = 0
Dim oldAndCurrentIntersectionOnNames = From currentApplicant In currentApplicants _
Group Join oldApplicant In oldApplicants _
On _
New With {Key .FirstName = currentApplicant.FirstName, _
Key .LastName = currentApplicant.LastName} _
Equals _
New With {Key .FirstName = oldApplicant.FirstName, _
Key .LastName = oldApplicant.LastName} Into applicants = Group _
From applicant In applicants.DefaultIfEmpty(New ApplicantNameDetails()) _
Select New ApplicantNameDetails() With _
{ _
.Index = i+=1, _
.FirstName = CStr(IIf(Not currentApplicant.FirstName Is Nothing, currentApplicant.FirstName, Nothing)), _
.OldFirstName = CStr(IIf(Not applicant.FirstName Is Nothing, applicant.FirstName, Nothing)), _
.LastName = CStr(IIf(Not currentApplicant.LastName Is Nothing, currentApplicant.LastName, Nothing)), _
.OldLastName = CStr(IIf(Not applicant.LastName Is Nothing, applicant.LastName, Nothing)) _
}
You'll see the .Index = i+=1
This was my attempt to do what I'd quite happily do in C# (i.e. Index = i++) in VB. Unfortunately the VB compiler doesn't like that.
Has anybody got any suggestions as to how I'd do this in VB.
Thanks in advance
Essentially, you can’t. If you want the Linq query to get consecutive values, use a special (so-called “generator”) class that has an IncrementAndGet (or simply Next) method for your integer.
class IntegerGenerator
private state as integer = 0
public function Next() as integer
dim oldState = state
state += 1
return oldState
end function
end class
There is an overload of the Select method that lets you use the index of the item on the result collection. http://msdn.microsoft.com/en-us/library/bb534869.aspx
You could split your query in two parts to use it (untested)
Dim q = From currentApplicant In currentApplicants _
Group Join oldApplicant In oldApplicants On _
New With {Key.FirstName = currentApplicant.FirstName, _
Key.LastName = currentApplicant.LastName} _
Equals _
New With {Key.FirstName = oldApplicant.FirstName, _
Key.LastName = oldApplicant.LastName} Into applicants = Group _
From applicant In applicants.DefaultIfEmpty(New ApplicantNameDetails())
Dim oldAndCurrentIntersectionOnNames = _
q.Select(Function(x, i) New ApplicantNameDetails() With _
{ _
.Index = i, _
.FirstName = CStr(IIf(Not x.currentApplicant.FirstName Is Nothing, x.currentApplicant.FirstName, Nothing)), _
.OldFirstName = CStr(IIf(Not x.applicant.FirstName Is Nothing, x.applicant.FirstName, Nothing)), _
.LastName = CStr(IIf(Not x.currentApplicant.LastName Is Nothing, x.currentApplicant.LastName, Nothing)), _
.OldLastName = CStr(IIf(Not x.applicant.LastName Is Nothing, x.applicant.LastName, Nothing)) _
})