What is the VB equivalent of the following code snippet? - c#-to-vb.net

XmlWriterSettings settings = new XmlWriterSettings();
settings.Encoding = Encoding.UTF8;
settings.Indent = true;
using (XmlWriter writer = XmlWriter.Create(stream, settings))

Dim settings As New XmlWriterSettings()
settings.Encoding = Encoding.UTF8
settings.Indent = True
Using writer As XmlWriter = XmlWriter.Create(stream, settings)
End Using
You can use this for conversions:
http://converter.telerik.com/

Dim settings As New XmlWriterSettings()
settings.Encoding = Encoding.UTF8
settings.Indent = True
Not sure on the last line though.

Related

The image is missing a frame. COMException (0x88982F62)

We have the following popup in a WPF application that should display two images returned from the internet, but throws the toys out with 'The image is missing a frame' when it hits EndInit()
Never come across this error before and can't find any explanation online that relates to this use - could it be an issue with the downloaded image, and if so how do I check it?
Thank you
Public Sub PopupModals_ChequeImages(ImageOne() As Byte, ImageTwo() As Byte)
Try
MainPopUp = New Window
With MainPopUp
.Width = 800
.Height = 750
.ResizeMode = ResizeMode.NoResize
.Title = "Check Images"
.Icon = BitmapFrame.Create(ReturnIconImage("GIF_ICO.ico"))
End With
MainPopUpGrid = New Grid
NameScope.SetNameScope(MainPopUpGrid, New NameScope())
Dim vGrid As New Grid
For i As Integer = 0 To 2
Dim vRow As New RowDefinition
If i = 2 Then
vRow.Height = New GridLength(35)
Else
vRow.Height = New GridLength(35, GridUnitType.Star)
End If
MainPopUpGrid.RowDefinitions.Add(vRow)
Next
Dim UpperSV As New ScrollViewer
With UpperSV
.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
End With
Grid.SetRow(UpperSV, 0)
MainPopUpGrid.Children.Add(UpperSV)
Dim LowerSV As New ScrollViewer
With LowerSV
.VerticalScrollBarVisibility = ScrollBarVisibility.Auto
End With
Grid.SetRow(LowerSV, 1)
MainPopUpGrid.Children.Add(LowerSV)
'Convert the files and load into the scrollviewers'
Dim vImage1 As New Image
Dim vBitmap As New BitmapImage
Using vStream As New IO.MemoryStream(ImageOne)
With vBitmap
.BeginInit()
.CreateOptions = BitmapCreateOptions.PreservePixelFormat
.CacheOption = BitmapCacheOption.OnLoad
.StreamSource = vStream
.EndInit()
.Freeze()
End With
vImage1.Source = vBitmap
End Using
UpperSV.Content = vImage1
Dim vImage2 As New Image
vBitmap = New BitmapImage
Using vStream As New IO.MemoryStream(ImageTwo)
With vBitmap
.BeginInit()
.CreateOptions = BitmapCreateOptions.PreservePixelFormat
.CacheOption = BitmapCacheOption.OnLoad
.StreamSource = vStream
.EndInit()
.Freeze()
End With
vImage2.Source = vBitmap
End Using
LowerSV.Content = vImage2
Dim DP As DockPanel = PopupStatusBar()
Grid.SetRow(DP, 2)
MainPopUpGrid.Children.Add(DP)
StatusBarLoaded("Check images...")
MainPopUp.Content = MainPopUpGrid
MainPopUp.WindowStartupLocation = WindowStartupLocation.CenterOwner
Dim CurApp As Application = Application.Current
Dim vWindow As Window = CurApp.MainWindow
MainPopUp.Owner = vWindow
MainPopUp.ShowDialog()
Catch ex As Exception
EmailError(ex)
End Try
End Sub
Full exception is
The image is missing a frame.
at System.Windows.Media.Imaging.BitmapDecoder.SetupDecoderFromUriOrStream(Uri uri, Stream stream, BitmapCacheOption cacheOption, Guid& clsId, Boolean& isOriginalWritable, Stream& uriStream, UnmanagedMemoryStream& unmanagedMemoryStream, SafeFileHandle& safeFilehandle)
at System.Windows.Media.Imaging.BitmapDecoder.CreateFromUriOrStream(Uri baseUri, Uri uri, Stream stream, BitmapCreateOptions createOptions, BitmapCacheOption cacheOption, RequestCachePolicy uriCachePolicy, Boolean insertInDecoderCache)
at System.Windows.Media.Imaging.BitmapImage.FinalizeCreation()
at System.Windows.Media.Imaging.BitmapImage.EndInit()
at HOAManagerClient051.PopupModals.PopupModals_ChequeImages(Byte[] ImageOne, Byte[] ImageTwo) in C:\Users\Dave\Documents\Visual Studio 2017\Projects\HOAManagerClient051\HOAManagerClient051\PopupModals.vb:line 3125
System.Runtime.InteropServices.COMException (0x88982F62): Exception from HRESULT: 0x88982F62
Images are returned like this
Await Task.Run(Sub()
Using response As HttpWebResponse = DirectCast(request.GetResponse(), HttpWebResponse)
Dim deserializer As New DataContractJsonSerializer(GetType(AllianceBank.CheckImageResponse))
checkResponseObject = DirectCast(deserializer.ReadObject(response.GetResponseStream()), AllianceBank.CheckImageResponse)
End Using
End Sub)
Dim frontImageRawGif As Byte() = Nothing
Dim backImageRawGif As Byte() = Nothing
Dim IsCheckImage As Boolean = True
Try
frontImageRawGif = Convert.FromBase64String(checkResponseObject.FrontImage)
Catch ex As Exception
IsCheckImage = False
End Try
Try
backImageRawGif = Convert.FromBase64String(checkResponseObject.BackImage)
Catch ex As Exception
IsCheckImage = False
End Try

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

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.

Read data from SQL Server database with c#

I have list of BuilderString which I want to contain data
public List<int> IDS = new List<int>();
public List<StringBuilder> Items = new List<StringBuilder>();
What's wrong with this code?
SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True");
SqlDataReader rdr2;
SqlCommand cmd2;
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS[i]", con2);
cmd2.CommandType = CommandType.Text;
rdr2 = cmd2.ExecuteReader();
SqlParameter param = new SqlParameter();
param.ParameterName = "#IDS[i]"
while (rdr2.Read())
{
Items[i].Append((StringBuilder)rdr2["item"]);
}
}
You need to rearrange your code a bit:
using (SqlConnection con2 = new SqlConnection("Data Source=aya-PC\\SQLEXPRESS;Initial Catalog=ItemSet;Integrated Security=True"))
using (SqlCommand cmd2 = new SqlCommand("select item From TransactiontData where idT = #IDS", con2))
{
// add the paramter to the command
cmd2.Parameter.Add("#IDS", SqlDbType.Int);
con2.Open();
for (int i = 0; i < IDS.Count; i++)
{
// set the parameter value
cmd2.Parameter["#IDS"].Value = IDS[i];
// only *THEN* call ExecuteReader()
using (SqlDataReader rdr2 = cmd2.ExecuteReader())
{
while (rdr2.Read())
{
// **NOT SURE** what you're trying to do here.....
// First of all, you need to just call Items.Add()
// to add new items to the list - and I'm TOTALLY
// UNCLEAR what you're trying to do casting the reader
// value to a StringBuilder.......
//
// Items[i].Append((StringBuilder)rdr2["item"]);
//
// replaced with what *might* make more sense.....
Items.Add(rdr2["item"].ToString());
}
rdr.Close();
}
}
con2.Close();
}
Points to note:
I would recommend to always put your SqlConnection, SqlCommand and SqlDataReader into using() {...} blocks to ensure proper disposal
you need to add your parameter and set its value BEFORE you call .ExecuteReader()!
Since the query itself never changes - there's no point in creating a new SqlCommand on every iteration. Create the command once - and then just set the parameter value (which is the only thing changing) once per iteration
You need to assign the parameter value in the application code rather than within the query. I'm not sure exactly what you are trying to accomplish by casting the column value as a StringBuilder. Assuming that each StringBuilder item is to contain a single string retrieved from a varchar/nvarchar column, the example below will do that.
for (int i = 0; i < IDS.Count; i++)
{
var cmd2 = new SqlCommand("select item From TransactiontData where idT=#IDS", con2);
SqlParameter param = new SqlParameter("#IDS", SqlDbType.Int) { Value = IDS[i] };
var rdr2 = cmd2.ExecuteReader();
while (rdr2.Read())
{
Items.Add(new StringBuilder((string)rdr2["item"]));
}
}

Listbox and SqlDataReader Issue

I am attempting load employee data from a stored procedure into a listbox in a form load event by ID and assign each with an image. The code above is what I have thus far. So what I'm trying to do here is to fill the listview with data from my data reader.
SqlConnection conn = new SqlConnection(
#"Data Source=MyPC\Test;Initial Catalog=TEST5;Integrated Security=True");
SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn);
cmd.CommandType = CommandType.Text;
SqlDataReader dr = cmd.ExecuteReader();
listView1.Items.Clear();
while (dr.Read())
{
ListViewItem recs = new ListViewItem();
recs.Text = dr["dept_name"].ToString();
recs.Text = dr["emp_first_name"].ToString();
recs.Text = dr["emp_last_name"].ToString();
recs.Text = dr["emp_email"].ToString();
recs.Text = dr["emp_phone"].ToString();
recs.Text = dr["emp_position"].ToString();
recs.Text = dr["emp_address1"].ToString();
recs.Text = dr["emp_address2"].ToString();
recs.Text = dr["emp_city"].ToString();
recs.Text = dr["emp_state"].ToString();
recs.Text = dr["emp_postal_code"].ToString();
recs.Tag = dr["empId"].ToString();
recs.ImageIndex = 0;
listView1.Items.Add(recs);
}
Thank you in advance.
Your query is currently only returning one fieid:
SqlCommand cmd = new SqlCommand("SELECT emp_first_name FROM Employees", conn);
I'm guessing you wanted this:
SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn);
You need to open the connection and close your disposable resources. Your current code is constantly replacing the recs.Text property to the point that the only thing you should see in the list are "emp_postal_code" values. I suspect you are looking for something like this, where you display the user name as the main item of the ListViewItem and then include the other information as SubItems of the item (for when displaying in Detailed view):
listView1.Items.Clear();
using (SqlConnection conn = new SqlConnection(...)) {
conn.Open();
using (SqlCommand cmd = new SqlCommand("SELECT * FROM Employees", conn)) {
using (SqlDataReader dr = cmd.ExecuteReader()) {
while (dr.Read()) {
ListViewItem recs = new ListViewItem();
recs.Text = dr["emp_first_name"].ToString() + " " +
dr["emp_last_name"].ToString();
recs.SubItems.Add(dr["dept_name"].ToString());
recs.SubItems.Add(dr["emp_email"].ToString());
etc...
recs.Tag = dr["empId"].ToString();
recs.ImageIndex = 0;
listView1.Items.Add(recs);
}
}
}
}
I see several things here:
You never open the connection:
You reference a number of fields in the reader that are not included in your statement's select clause.
You overwrite, rather than append to, the text property of your ListViewItem, so that only the last assigned property value will show.

Can multiple xps documents be merged to one in WPF?

Can multiple xps documents be merged to one xps document in WPF and shown in DocumentViewer?
An application has 4 small xps documents each displayed seperately, but in one of the places all 4 documents should be shown as one document. How do I go about it?
Here, targetDocument is the target path of the new file and list is a list of all documents to be merged.
public void CreateXPSStreamPages(string targetDocument, List<string> list)
{
Package container = Package.Open(targetDocument, FileMode.Create);
XpsDocument xpsDoc = new XpsDocument(container);
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
SerializerWriterCollator vxpsd = writer.CreateVisualsCollator();
vxpsd.BeginBatchWrite();
foreach (string sourceDocument in list)
{
AddXPSDocument(sourceDocument, vxpsd);
}
vxpsd.EndBatchWrite();
container.Close();
}
public void AddXPSDocument(string sourceDocument, SerializerWriterCollator vxpsd)
{
XpsDocument xpsOld = new XpsDocument(sourceDocument, FileAccess.Read);
FixedDocumentSequence seqOld = xpsOld.GetFixedDocumentSequence();
foreach (DocumentReference r in seqOld.References)
{
FixedDocument d = r.GetDocument(false);
foreach (PageContent pc in d.Pages)
{
FixedPage fixedPage = pc.GetPageRoot(false);
double width = fixedPage.Width;
double height = fixedPage.Height;
Size sz = new Size(width, height);
fixedPage.Width = width;
fixedPage.Height = height;
fixedPage.Measure(sz);
fixedPage.Arrange(new Rect(new Point(), sz));
//fixedPage.UpdateLayout();
ContainerVisual newPage = new ContainerVisual();
newPage.Children.Add(fixedPage);
//test: add Watermark from Feng Yuan sample
//newPage.Children.Add(CreateWatermark(width, height, "Watermark"));
vxpsd.Write(newPage);
}
}
xpsOld.Close();
}
In case someone is interested in the VB code:
Public Sub CreateXPSStream(targetDocument As String, ListToMerge As List(Of String))
If (File.Exists(targetDocument)) Then
File.Delete(targetDocument)
End If
Dim container As Package = Package.Open(targetDocument, FileMode.Create)
Dim xpsDoc = New System.Windows.Xps.Packaging.XpsDocument(container)
Dim seqNew As FixedDocumentSequence = New FixedDocumentSequence()
For Each sourceDocument As String In ListToMerge
AddXPSDocuments(sourceDocument, seqNew)
Next
Dim xpsWriter As XpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc)
xpsWriter.Write(seqNew)
xpsDoc.Close()
container.Close()
End Sub
Public Sub AddXPSDocuments(ByVal sourceDocument As String, ByRef seqNew As FixedDocumentSequence)
Try
Dim xpsOld As XpsDocument = New XpsDocument(sourceDocument, FileAccess.Read)
Dim seqOld As FixedDocumentSequence = xpsOld.GetFixedDocumentSequence()
For Each r As DocumentReference In seqOld.References
Dim newRef As DocumentReference = New DocumentReference()
CType(newRef, IUriContext).BaseUri = CType(r, IUriContext).BaseUri
newRef.Source = r.Source
seqNew.References.Add(newRef)
Next
Catch ex As Exception
myStatusAdd("Error with " & sourceDocument)
End Try
End Sub
thanks for the initial code.
This requires also a fair amount of references in your projects:
PresentationCore
PresentationFramework
ReachFramwork
System.Core
System.Windows.Presentation
System.Xaml
System.Printing
WindowsBase
I think that's all.

Resources