Converted my code from C# to VB.NET and now it's throwing an error of var - wpf

I am converted that code from c# but its give an error var is not define
can you please give me a suggestion what to do , I am new in vb.net. what can i use instead of var
If searchCriteria = "Title" Then
Dim Searchresults As New List(Of SearchResultsTitle)()
Dim searchfields As String() = New String() {"title", ""}
Dim queryparser = New QueryParser(Lucene.Net.Util.Version.LUCENE_29, "title", analyzer)
Dim indexSearcher As New IndexSearcher(directory)
Dim hits = indexSearcher.Search(QueryMaker(searchString, searchfields))
Dim dt As New DataTable()
Dim SrNo As Integer = 1
For i As Integer = 0 To hits.Length() - 1
Dim result As New SearchResultsTitle()
result.SrNo = SrNo
result.Title = hits.Doc(i).GetField("title").StringValue()
result.Accessionno = hits.Doc(i).GetField("AccessionNo").StringValue()
result.Author = hits.Doc(i).GetField("Author").StringValue()
result.Location = hits.Doc(i).GetField("location").StringValue()
result.ClassNo = hits.Doc(i).GetField("ClassNo").StringValue()
result.Status = hits.Doc(i).GetField("status").StringValue()
Searchresults.Add(result)
SrNo = SrNo + 1
Next
Dim outputText As New StringBuilder()
Dim query = queryparser.Parse(txtSearch.Text)
Dim result = searcher.Search(query)
'now facets
Dim facetsText As New StringBuilder()
For Each result As<b> Var</b> In GetFacets(query, "title").Where(Function(k) k.Value > 0).OrderByDescending(Function(k) k.Value)
facetsText.AppendLine(item.Key + " ( " + item.Value + " )")
Next
Dim doc As New FlowDocument()
' Add paragraphs to the FlowDocument.
doc.Blocks.Add(New Paragraph(New Run(outputText.ToString())))
doc.Blocks.Add(New Paragraph(New Run("title")))
doc.Blocks.Add(New Paragraph(New Run(facetsText.ToString())))
rtbResult.Document = doc
dGridResults.ItemsSource = Searchresults
End If

For Each is defined as:
For Each o As Type In Collection
'do something with o
Next
Your Var in For Each is not definded. Var has to be an existing objecttype. Try KeyValuePair(of, ) (return type of GetFacets(..)) or something similar instead. Deleting As Var is also an option.

Related

Why image cannot be saved in database

I'm using VB.NET and SQL Server for my system. I have a problem saving an image into the database. I need to save and retrieve image on the same page but I get an error:
unable to cast System.DBNull to system bytes.
I have tried several coding to fix my coding but it does not worked.
Code for retrieve image.
Dim id As String = txtImages.Text.Trim() 'txtImages is textbox name
Image1.Visible = id <> ""
If id <> "" Then
Dim dt As DataTable = GetData((Convert.ToString("SELECT ImagePic FROM masterlist WHERE id
='") & Request.QueryString("id")) + "'") 'image data will be select depend on what user search in the
serch textbox
If dt.Rows.Count > 0 Then
Dim bytes As Byte() = TryCast(dt.Rows(0)("ImagePic"), Byte())
Dim base64String As String = Convert.ToBase64String(bytes, 0, bytes.Length)
Image1.ImageUrl = Convert.ToString("data:images/png;base64,") & base64String
Else
Image1.ImageUrl = ""
Image1.AlternateText = "No image present in database with the name" 'if there is no image
in db the message will displayed
End If
End If
End Sub
Code for save image
Dim fileName As String = String.Empty
Dim filePath As String = String.Empty
Dim getPath As String = String.Empty
Dim pathToStore As String = String.Empty
Dim bytes As [Byte]()
Dim fs As FileStreamenter code here
Dim br As BinaryReader
Dim cmd As New SqlCommand("Updateonlyimage_Sp3", cs) ' SQL command for this page is inside SQL Server I declare it as Insertapprovalcustom_Sp2"
cmd.CommandType = CommandType.StoredProcedure
Try
If FileUpload1.HasFile Then
fileName = FileUpload1.FileName
filePath = Server.MapPath("HSCODE/" & Convert.ToString(System.Guid.NewGuid()) & fileName)
'path to doucument inside approval_pdf file
FileUpload1.SaveAs(filePath)
cmd.Parameters.AddWithValue("#id", Request.QueryString("id"))
cmd.Parameters.AddWithValue("#ImagePicName", fileName)
Dim getPos As Integer = filePath.LastIndexOf("\")
Dim len As Integer = filePath.Length()
getPath = filePath.Substring(getPos, len - getPos)
pathToStore = getPath.Remove(0, 1)
cmd.Parameters.AddWithValue("#ImagePicPath", pathToStore)
fs = New FileStream(filePath, FileMode.Open, FileAccess.Read)
br = New BinaryReader(fs)
bytes = br.ReadBytes(Convert.ToInt32(fs.Length))
br.Close()
fs.Close()
cmd.Parameters.AddWithValue("#ImagePic", bytes)
cmd.Parameters.AddWithValue("#ContentType", FileUpload1.PostedFile.ContentType)

Problem retrieving data: System.IndexOutOfRangeException: There is no row at position 0

Dim command As New SqlCommand("SELECT * From tblUserInfo WHERE Username='" & Trim(frmdashboard.ToolStripLabel4.Text) & "'", con)
Dim table As New DataTable()
Dim sqlAdapter As New SqlDataAdapter(command)
sqlAdapter.Fill(table)
Me.UserTypeTextBox.Text = table.Rows(0)(10).ToString()
Me.UsernameTextBox.Text = table.Rows(0)(9).ToString()
Me.Email_AddressTextBox.Text = table.Rows(0)(12).ToString()
Me.PositionTextBox.Text = table.Rows(0)(1).ToString()
Me.NameTextBox.Text = table.Rows(0)(2).ToString()
Me.AddressTextBox.Text = table.Rows(0)(3).ToString()
Me.Date_of_BirthDateTimePicker.Value = table.Rows(0)(4).ToString()
Me.AgeTextBox.Text = table.Rows(0)(5).ToString()
Me.SexComboBox.Text = table.Rows(0)(6).ToString()
Me.Telephone_NumberTextBox.Text = table.Rows(0)(7).ToString()
Me.Mobile_NumberTextBox.Text = table.Rows(0)(8).ToString()
Me.Security_Question_1TextBox.Text = table.Rows(0)(13).ToString()
Me.Security_Question_2TextBox.Text = table.Rows(0)(15).ToString()
Dim img() As Byte
img = table.Rows(0)(17)
Dim ms As New MemoryStream(img)
Me.PicturePictureBox.Image = Image.FromStream(ms)
This should retrieve the data of a specific person. The error I get is
System.IndexOutOfRangeException: There is no row at position 0
You are assuming that your query will return at least one record which might/might not be true all times. You should first check if your tables has at least one row as below:
if ( table.Rows != null && tables.Rows.Count > 0)
{
Dim img() As Byte;
img = table.Rows(0)(17)
Dim ms As New MemoryStream(img)
Me.PicturePictureBox.Image = Image.FromStream(ms)
}

WPF Dynamic image generation and printing is not working

In an application I'm developing, the user can select a number of items (max. 6) in a datagrid. These items should then be printed in a matrix style on pre-printed forms (see it like CD labels, 6 on a page).
I'm generating these images dynamically containing the selected content from a database. I then put these in a grid so they can be printed on the pre-printed forms.
I have the following code that creates the grid, generates the images from a user control and adds them to the grid and then prints these images.
I'm not following the MVVM pattern for the printing action. I created a reference to my view model in my code-behind.
Private Sub PrintButton_Click(sender As Object, e As RoutedEventArgs) Handles ButtonPrint.Click
Dim dlg As New PrintDialog
dlg.PrintTicket.PageMediaSize = New PageMediaSize(PageMediaSizeName.ISOA4)
Dim pageWidth As Double = GetPageWidth(dlg)
'Since the label is a perfect square: labelWidth = labelHeight
Dim labelWidthInPx As Integer = Utilities.ConvertMmToPixels(My.Settings.LabelWidthInMm)
'Set spacing distances in pixels
Dim horizontalLabelSpacing As Integer = Utilities.ConvertMmToPixels(My.Settings.HorizontalLabelSpacinginMm)
Dim verticalLabelSpacing As Integer = Utilities.ConvertMmToPixels(My.Settings.VerticalLabelSpacingInMm)
Dim topMargin As Integer = Utilities.ConvertMmToPixels(My.Settings.TopMarginInMm)
Dim leftMargin As Integer = Utilities.ConvertMmToPixels(My.Settings.LeftMarginInMm)
Dim bottomMargin As Integer = Utilities.ConvertMmToPixels(My.Settings.BottomMarginInMm)
'Create the table/grid
Dim tbl As New Grid
If CheckBoxPrintGridLines.IsChecked Then
tbl.ShowGridLines = True
Else
tbl.ShowGridLines = False
End If
'Add 3 columns (2 for the labels, 1 for spacing)
Dim col1 As New ColumnDefinition With {
.Width = New GridLength(labelWidthInPx, GridUnitType.Pixel)
}
Dim col2 As New ColumnDefinition With {
.Width = New GridLength(horizontalLabelSpacing, GridUnitType.Pixel)
}
Dim col3 As New ColumnDefinition With {
.Width = New GridLength(labelWidthInPx, GridUnitType.Pixel)
}
tbl.ColumnDefinitions.Add(col1)
tbl.ColumnDefinitions.Add(col2)
tbl.ColumnDefinitions.Add(col3)
'Add 5 Rows (3 for labels, 2 for spacing)
Dim row1 As New RowDefinition With {
.Height = New GridLength(labelWidthInPx, GridUnitType.Pixel)
}
Dim row2 As New RowDefinition With {
.Height = New GridLength(verticalLabelSpacing, GridUnitType.Pixel)
}
Dim row3 As New RowDefinition With {
.Height = New GridLength(labelWidthInPx, GridUnitType.Pixel)
}
Dim row4 As New RowDefinition With {
.Height = New GridLength(verticalLabelSpacing, GridUnitType.Pixel)
}
Dim row5 As New RowDefinition With {
.Height = New GridLength(labelWidthInPx, GridUnitType.Pixel)
}
tbl.RowDefinitions.Add(row1)
tbl.RowDefinitions.Add(row2)
tbl.RowDefinitions.Add(row3)
tbl.RowDefinitions.Add(row4)
tbl.RowDefinitions.Add(row5)
'Add label images
Dim reelData = CType(DataGridReels.ItemsSource, List(Of ReelInfo))
Dim rowIndex As Integer = 0
Dim colIndex As Integer = 0
For Each reel In reelData.Where(Function(r) r.IsSelected = True)
Dim partNumberData = ViewModel.DataService.GetPartNumberDataAsync(reel.PartNumber)
Dim batchData = ViewModel.DataService.GetBatchDataAsync(reel.PartNumber, reel.HENBatchNumber)
LabelImageControl.IsPrinting = True
LabelImageControl.PartNumberData = partNumberData.Result
LabelImageControl.BatchData = batchData.Result
LabelImageControl.ReelData = reel
LabelImageControl.Refresh
UpdateUI()
Dim labelImage As New Image
labelImage = GetImageFromLabel(LabelImageControl)
labelImage.Width = labelWidthInPx
labelImage.Height = labelWidthInPx
Grid.SetRow(labelImage, rowIndex)
Grid.SetColumn(labelImage, colIndex)
tbl.Children.Add(labelImage)
tbl.Refresh
colIndex += 1
If colIndex > 1 Then
colIndex = 0
rowIndex += 1
End If
Next
Dim iuc As New InlineUIContainer(tbl)
Dim p As New Paragraph(iuc)
'Create print dialog
If dlg.ShowDialog.GetValueOrDefault Then
'Create a flow document
Dim doc As New FlowDocument With {
.Name = "LabelPage",
.ColumnWidth = pageWidth,
.PagePadding = New Thickness(leftMargin, topMargin, 0, bottomMargin)
}
doc.Blocks.Add(p)
'Create IDocumentPagniatorSource from FlowDocument
Dim idpSource As IDocumentPaginatorSource = doc
Try
Me.Cursor = Cursors.Wait
dlg.PrintDocument(idpSource.DocumentPaginator, "Label Page")
Catch ex As Exception
Me.Cursor = Cursors.Arrow
MessageBox.Show("An error occurred during printing: " & ex.Message, "Print error")
Finally
Me.Cursor = Cursors.Arrow
End Try
End If
End Sub
When I send the output to the PDF printer I only get one image in the top left corner of the page/grid.
Since the user control (LabelImageControl) is in the XAML, I can see it changing while debugging. So the data is coming into the user control correctly.
When I check the grid with the XML Visualiser I see it has the same number of children as the items I selected in the datagrid.
Can anyone point me in the right direction on how to get the grid printing correctly?

Import CSV into DataGrid

In winForms adding a CSV to a DataGrid was quite easy. I am now trying to add this to a Silverlight DataGrid. Here is my attempt - which yields 3 columns Capacity|Count|Items - mind you the values are correct 83|83|_ on each row. There are 83 rows, but the columns should be 23 with diff values in each. Thanks for looking and enjoy your bounty!
Code:
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
Dim srsCol As New List(Of List(Of String))
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
While Not sr.Peek = -1
srsCol.Add(New List(Of String)(sr.ReadLine.Split(","c).ToList))
End While
End Using
End Using
dgStaff.ItemsSource = srsCol
End If
End If
Catch ex As Exception
MessageBox.Show(ex.ToString)
End Try
I decided to use the BindableDataGrid from CodePlex Since the binding is being set dynamically I had to come up with a Random string generator and assign that for the binding and all is well.
csvDs.Tables.Clear()
Try
Dim ofd As New OpenFileDialog
If ofd.ShowDialog Then
If IO.File.Exists(ofd.File.FullName) Then
csvDs.Tables.Add(csvDt)
Using fs As IO.FileStream = ofd.File.OpenRead
Using sr As New IO.StreamReader(fs)
Dim i As Integer
While Not sr.EndOfStream
If i = 0 Then
Dim cols = sr.ReadLine.Split(","c)
For ii As Integer = 0 To cols.Count - 1
Dim rndValue As String = RndColName()
Dim col As New BindableDataGrid.Data.DataColumn(rndValue)
rndValues.Add(rndValue)
col.DataType = GetType(System.String)
col.Caption = ii.ToString
col.ReadOnly = True
col.AllowReorder = False
col.AllowResize = False
col.AllowSort = False
csvDt.Columns.Add(col)
AddItemsToCb(ii)
Next
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
Dim s As String = cols(_i).Replace("""", String.Empty)
row(rndValues(_i)) = s
csvValues.Add(s)
Next
csvDt.Rows.Add(row)
Else
Dim cols = sr.ReadLine.Split(","c)
Dim row As New BindableDataGrid.Data.DataRow
For _i As Integer = 0 To cols.Count - 1
row(rndValues(_i)) = cols(_i).Replace("""", String.Empty)
Next
csvDt.Rows.Add(row)
End If
i += 1
End While
End Using
End Using
dgStaff.DataSource = csvDs
dgStaff.DataMember = "csvTable"
dgStaff.DataBind()

column does not belong to table Table

I don't know exactly where I have to look for.
Error is:
Column 'pkJudge' does not belong to table Table. '
at System.Data.DataRow.GetDataColumn(String columnName)
at System.Data.DataRow.set_Item(String columnName, Object value)
at ReadyCollect.CaseEntry.S_GetJudges(Int32 courtID)
at ReadyCollect.CaseEntry.S_GetExistCaseInfo()
at ReadyCollect.CaseEntry.CaseReminder_HoldCase()
at ReadyCollect.CaseEntry.btnSave_Click(Object sender, EventArgs e)
It occurs in the following code fragment. Any Ideas?
Private Sub S_GetJudges(ByVal courtID As Integer)
' Load the list of judges '
Dim JudgeSet As New DataSet
Dim dv As System.Data.DataView
Dim DAl As New DataAccessLayer
Dim pfkCourt As Integer = CourtDDL.SelectedValue
If ClientKey > 0 And pfkCourt > 0 Then
JudgeSet = DAl.GetJudgespkJudgesJudgeNamefkCourt(ClientKey, pfkCourt)
JudgeDataTable = JudgeSet.Tables(0)
Dim dr As System.Data.DataRow
dr = JudgeDataTable.NewRow()
dr("pkJudge") = "0"
dr("Judge Name") = "(Select a Judge)"
JudgeDataTable.Rows.Add(dr)
JudgeDDL.SelectedValue = 0
JudgeDDL.DataSource = JudgeDataTable.DefaultView
dv = JudgeDataTable.DefaultView
dv.Sort ="pkJudge ASC"
JudgeDDL.DataBind()
End If
End Sub
And the dataaccess method that is called in the code fragment is below.
Now JudgeDataTable is declared as
Private JudgeDataTable As System.Data.DataTable on top of the page.
Rest is in the code fragment as I posted above.
'Retreives fields pkJudge and [Judge Name] from the table Judges where field fkCourt is equal to fkCourt '
Public Function GetJudgespkJudgesJudgeNamefkCourt(ByVal ClientKey As Integer, ByVal fkCourt As Integer) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase()
Dim sqlCommand As String = "USP_DISPLAYJUDGESPKJUDGEJUDGENAMEFKCOURT"
Dim dbCommand As DbCommand = db.GetStoredProcCommand(sqlCommand)
db.AddInParameter(dbCommand,"ClientKey", DbType.Int32, ClientKey)
db.AddInParameter(dbCommand,"fkCourt", DbType.Int32, fkCourt)
Return db.ExecuteDataSet(dbCommand)
End Function
Partial Class CaseEntry
Inherits System.Web.UI.Page
Private JudgeDataTable As System.Data.DataTable
Private Sub S_GetJudges(ByVal courtID As Integer)
' Load the list of judges
JudgeDataTable = New System.Data.DataTable
Dim JudgeSet As New DataSet
Dim dv As System.Data.DataView
Dim DAl As New DataAccessLayer
Dim pfkCourt As Integer = CourtDDL.SelectedValue
If ClientKey > 0 And pfkCourt > 0 Then
JudgeSet = DAl.GetJudgespkJudgesJudgeNamefkCourt(ClientKey, pfkCourt)
JudgeDataTable = JudgeSet.Tables(0)
Dim dr As System.Data.DataRow
dr = JudgeDataTable.NewRow()
dr("pkJudge") = "0"
dr("Judge Name") = "(Select a Judge)"
JudgeDataTable.Rows.Add(dr)
JudgeDDL.SelectedValue = 0
JudgeDDL.DataSource = JudgeDataTable.DefaultView
dv = JudgeDataTable.DefaultView
dv.Sort = "pkJudge ASC"
JudgeDDL.DataBind()
End If
End Sub
'Retreives fields pkJudge and [Judge Name] from the table Judges where field fkCourt is equal to fkCourt
Public Function GetJudgespkJudgesJudgeNamefkCourt(ByVal ClientKey As Integer, ByVal fkCourt As Integer) As DataSet
Dim db As Database = DatabaseFactory.CreateDatabase()
Dim sqlCommand As String = "USP_DISPLAYJUDGESPKJUDGEJUDGENAMEFKCOURT"
Dim dbCommand As DbCommand = db.GetStoredProcCommand(sqlCommand)
db.AddInParameter(dbCommand, "ClientKey", DbType.Int32, ClientKey)
db.AddInParameter(dbCommand, "fkCourt", DbType.Int32, fkCourt)
Return db.ExecuteDataSet(dbCommand)
End Function
What happens if you break after the getdataset stuff and look at the datatable? Is the column there? Otherwise, maybe try to access it via column index.

Resources