Dinamically load XAML in UserControl for Excel Add In (VB) - vb.net

I am developing an Excel Add In in which I intend to dinamically load a XAML canvas to a WPF UserControl.
The code below worked fine in a full WPF template...
Imports Microsoft.Win32
Imports System.IO
Class MainWindow
Private Sub btnLoadXAML_Click(sender As Object, e As RoutedEventArgs)
Try
Dim FlDialog As OpenFileDialog = New OpenFileDialog()
FlDialog.ShowDialog()
Dim lFlName As String = FlDialog.FileName
'load selected file
Dim fs As FileStream = New FileStream(lFlName, FileMode.Open)
Dim gridToLoad As New Canvas
With gridToLoad
.Height = 300
.Width = 300
End With
gridToLoad = System.Windows.Markup.XamlReader.Load(fs)
grdLoadXAML.Children.Add(gridToLoad)
fs.Close()
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
End Class
...but when I use it on a Excel Add In template, I can't refer to a XAML object via VB code, such as:
Dim gridToLoad As New Canvas
I mean "New Canvas" doesn't seem to be "imported" into this kind of template. I couldn't find which library to refer to make this work.
Thanks in advance.

Sorry,
Just a few minutes after I've tried to build the project and Visual Basic itself gave me the answer!
Just had to add reference for System.Xaml (dumb!).
Thanks anyway!! :)
Best.

Related

what wrong with this code?. Converting VBA to VB.Net

I would like to ask if someone can help me with this.
I have this code that Unload a CorelDRAW Macro project a get the new one from the network in order to became easier to update several machines.
VBA code:
Sub CDRMacroUpdate()
' Unloads the project from CorelDRAW
GMSManager.Projects("Project1").Unload
Dim nMacro As String
' The project have the same name, but it's a new file, here is in the C drive, but it's located in the network folder
nMacro = "C:\Project1.gms"
' Loads the new file and copy to the User GMS folder
GMSManager.Projects.Load nMacro, True, False
End Sub
Now I'm trying to convert this VB.Net but I'm getting a lot of errors and I can't see what I'm doing wrong.
In a form with a Button I have this code:
I'm using SharpDevelop
Imports Corel.Interop.VGCore
Public Partial Class MainForm
Public Sub New()
' The Me.InitializeComponent call is required for Windows Forms designer support.
Me.InitializeComponent()
End Sub
Sub BtnUpdateMacroClick(sender As Object, e As EventArgs)
Dim GMSManager As Corel.Interop.VGCore.GMSManager
GMSManager.Projects("Project1").Unload
Dim nMacro As String
nMacro = "C:\Project1.gms"
GMSManager.Projects.Load(nMacro, True, False)
End Sub
End Class
Now, can someone please explain what I'm doing wrong in the VB.Net code?
Thank very much for the help.

copy windowsform chart to clipboard VB

I need to copy a chart (System.Windows.Forms.DataVisualization.Charting.Chart) to clipboard in order to paste it in other application. I use below code but it gives error on the last line for "img" says "Value of Type Bitmap cannot be converted to Bitmapsource"
Any help to rectify the error is highly appreciated.
Private Sub CopyChartBtn_Click(sender As Object, e As RoutedEventArgs) Handles CopyChartBtn.Click
Dim main = DirectCast(Application.Current.MainWindow, MainWindow)
Dim SET_H = DirectCast(main.Frame1.Content, SET_Home)
Dim chart1 = DirectCast(SET_H.Benchchart.Child, System.Windows.Forms.DataVisualization.Charting.Chart)
'save image
Dim img As New System.Drawing.Bitmap(chart1.Width, chart1.Height)
Dim gr As System.Drawing.Graphics = System.Drawing.Graphics.FromImage(img)
chart1.Printing.PrintPaint(gr, New System.Drawing.Rectangle(System.Drawing.Point.Empty, chart1.Size))
Clipboard.SetImage(img)
End Sub
My project is WPF and I am hosting windowsform chart in it. Maybe that is the problem because when I run it in a windows form project it works fine
I used System.Windows.Forms.Clipboard.SetImage(img) and it works.Originally when it is a WPF project it uses System.Windows.Clipboard.SetImage(img) when not using the namespace

How can I emulate a PictureBox control in a console application

Is there any way to emulate a picturebox in a console application? I tried this way but the image always returned completely black:
Using P As New PictureBox
P.Size = New Point(255, 255)
P.Image = New Bitmap(255, 255) 'I did set a real image, but I didn't for the sake this example
End Using
Assuming you've imported everything needed to show the form, don't use the form.Show method. Instead, use Application.Run(New Form1) to show the form. This post has a more complete answer.
You can design the form in the designer,use it as is, or declare it as a new object and change any properties and pass the new object to the Run method.
Imports System.Drawing
Imports System.Windows.Forms
Module Module1
Sub Main()
Dim newform1 As New Form1
newform1.PictureBox1.Image = New Bitmap("MyImageFile")
Application.Run(newform1)
Console.ReadLine()
End Sub
End Module

persisting textbox text in visual basic

I am pretty new to VB and am compiling a program which contains several forms, each of which is populated with text boxes. The purpose of the program is for text to be dragged between boxes to move assets around. I've managed the drag and drop functionality but need to persist the text in the text boxes once the program is shut down so that when reopened, the last location of all moved text is still present.
Can anyone make any suggestions/supply sample code please?
I've tried the easiest to understand suggestion to get me started but when I build and publish the program it says that I do not have access to the file to save the values!! Can anyone help? Code below
Public Class Form1
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
Dim txtpersist As IO.TextWriter = New IO.StreamWriter("C:\Users\HP\Documents\namestore")
txtpersist.WriteLine(TextBox1.Text)
txtpersist.WriteLine(TextBox2.Text)
txtpersist.WriteLine(TextBox3.Text)
txtpersist.Close()
Dim yourfile As IO.TextReader = New IO.StreamReader("C:\Users\HP\Documents\namestore")
TextBox1.Text = yourfile.ReadLine()
TextBox2.Text = yourfile.ReadLine()
TextBox3.Text = yourfile.ReadLine()
yourfile.Close()
End Sub
End Class
You can use the built in PropertyBinding to link your TextBox.Text to a Property. It will put it into your App.Config File which will allow you to edit it through MySettings as long as it is per user. If the settings are application level you would be better of using one of the other answers. You can also look at this article for some more information.
You should write the location of the textboxes to a persistent store on program exit, such as a file, a database, or the registry. On program load, you can retrieve the saved values and set the locations accordingly.
You could save each textbox's text inside of a file and re-open it at runtime.
Dim yourfile As TextWriter = New StreamWriter("pathtofile")
Say you had 3 textBoxes called textBox1, textBox2 and textBox3. You would save each one's status by simply writing each textbox's text property inside the file. Like so:
yourfile.WriteLine(textBox1.Text)
yourfile.WriteLine(textBox2.Text)
yourfile.WriteLine(textBox3.Text)
At the end, you just close the file.
yourfile.Close()
Loading the data back is just as simple.
Dim yourfile As TextReader = New StreamReader("pathtofile")
textBox1.Text = yourfile.ReadLine()
textBox2.Text = yourfile.ReadLine()
textBox3.Text = yourfile.ReadLine()
yourfile.Close()
Let me know if you have any questions or require further assistance. Be sure to import the System.IO namespace, to get access to the IO classes used here.
The most common method of persisting data is to store it in a database. Of course that adds more work to your project since you now have to create, update, and maintain a database. An easier solution is to use a file.
We'll create a new class in order to read & write data from the file. This way if you switch to a database later on, you only need to change the class. And since I'm sure at some point you'll want a database we'll make the class use datatables to minimize the changes needed to it. Here's our class:
Public Class TextBoxes
Private tbl As DataTable
Private filename As String
'Use constants for our column names to reduce errors
Private Const ctrlName As String = "CtrlName"
Private Const text As String = "Text"
Public Sub New(ByVal file As String)
'Create the definition of our table
tbl = New DataTable("TextBox")
tbl.Columns.Add(ctrlName, Type.GetType("System.String"))
tbl.Columns.Add(text, Type.GetType("System.String"))
'Save the filename to store the data in
Me.filename = file
End Sub
Public Sub Save(ByVal frm As Form)
Dim row As DataRow
'Loop through the controls on the form
For Each ctrl As Control In frm.Controls
'If the control is a textbox, store its name & text in the datatable
If TypeOf (ctrl) Is TextBox Then
row = tbl.NewRow
row.Item(ctrlName) = ctrl.Name
row.Item(text) = ctrl.Text
tbl.Rows.Add(row)
End If
Next
'Save the additions to the dataset and write it out as an XML file
tbl.AcceptChanges()
tbl.WriteXml(filename)
End Sub
Public Sub Load(ByVal frm As Form)
'Don't load data if we can't find the file
If Not IO.File.Exists(filename) Then Return
tbl.ReadXml(filename)
For Each row As DataRow In tbl.Rows
'If this control is on the form, set its text property
If frm.Controls.ContainsKey(row.Item(ctrlName)) Then
CType(frm.Controls(row.Item(ctrlName)), TextBox).Text = row.Item(text).ToString
End If
Next
End Sub
End Class
Next you'll want to use this fine class to read & write your data. The code for doing this is nice and simple:
Dim clsTextBoxes As New TextBoxes("C:\Txt.xml")
'Save the textboxes on this form
clsTextBoxes.Save(Me)
'Load the textboxes on this form
clsTextBoxes.Load(Me)
I would do it using either the Application settings as Mark Hall pointed out or like this...
Public Class MyTextBoxValueHolder
Public Property Value1 As String
Public Property Value2 As String
Public Property Value3 As String
Public Sub Save(Path As String)
Dim serializer As New XmlSerializer(GetType(MyTextBoxValueHolder))
Using streamWriter As New StreamWriter(Path)
serializer.Serialize(streamWriter, Me)
End Using
End Sub
Public Shared Function Load(Path As String) As MyTextBoxValueHolder
Dim serializer As New XmlSerializer(GetType(MyTextBoxValueHolder))
Using streamReader As New StreamReader(Path)
Return DirectCast(serializer.Deserialize(streamReader), MyTextBoxValueHolder)
End Using
End Function
End Class
So what you can then do is...
Dim myValues As MyTextBoxValueHolder = MyTextBoxValueHolder.Load("SomeFilePath.xml")
myTextBox1.Text = myValues.Value1
myTextBox2.Text = myValues.Value2
'And so on....
2 Save
Dim myValues As New MyTextBoxValueHolder
myValues.Value1 = myTextBox1.Text
myValues.Value2 = myTextBox2.Text
myValues.Save("SomeFilePath.xml")
'All saved
to maintain the values ​​you can use stored user settings, see the following links.
http://msdn.microsoft.com/en-us/library/ms379611(v=vs.80).aspx
http://www.codeproject.com/KB/vb/appsettings2005.aspx
Regards.

how can i see output of Console.Error.WriteLine?

in vb.net i have some code that looks like this:
Imports System
Imports System.IO
Imports iTextSharp.text
Imports iTextSharp.text.pdf
Public Class Form1
Public Sub New1()
Directory.SetCurrentDirectory("C:\Users\alexluvsdanielle\Desktop\") '"
Console.WriteLine("Chapter 10 example 10: nested PdfPTables")
Dim doc As Document = New Document(PageSize.A4, 50, 50, 50, 50)
Try
Dim writer As PdfWriter = PdfWriter.GetInstance(doc, New FileStream("Chap1010.pdf", FileMode.Create))
doc.Open()
Dim table As PdfPTable = New PdfPTable(4)
Dim nested1 As PdfPTable = New PdfPTable(2)
nested1.AddCell("1.1")
nested1.AddCell("1.2")
Dim nested2 As PdfPTable = New PdfPTable(1)
nested2.AddCell("2.1")
nested2.AddCell("2.2")
Dim k As Integer = 0
While k < 24
If k = 1 Then
table.AddCell(nested1)
Else
If k = 20 Then
table.AddCell(nested2)
Else
table.AddCell("cell " + k)
End If
End If
System.Threading.Interlocked.Increment(k)
End While
table.TotalWidth = 300
table.WriteSelectedRows(0, -1, 100, 600, writer.DirectContent)
doc.Close()
Catch de As Exception
Console.Error.WriteLine(de.Message)
Console.Error.WriteLine(de.StackTrace)
End Try
End Sub
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
New1()
End
End Sub
End Class
i would like to see what the console is writing. how do i do this?
An alternative is to use the System.Diagnostics.Trace class for these messages. Then they will show up in your Visual Studio output window, and you can optionally attach other "listeners", like a ConsoleTraceListener (for the console, when it's available) or the TextWriterTraceListener (for log files). You can even implement your own (like a DatabaseLogTraceListener or MessageBoxTraceListener — be careful with that last one, though).
I have piped the output of a WinForms application by starting it from the command line:
myapp.exe > debugfile.txt
I've done that before to redirect the output to a file that I can then read.
Why not use Debug.Print ? it will show up in the output window while developing and is much cleaner then a bunch of Message boxes everywhere...
There is no Console in a Winforms application.
You will need to use a MessageBox to display your message.
MessageBox.Show(de.Message)
I have my own solution:
I created a form with a multiline textbox docked to fill the window size. I created a function to append some text to the textbox. My function looks like this:
Friend Sub ConsoleBox(ByVal message As String)
If frmConsole.Visible = False Then
frmConsole.Show()
End If
frmConsole.txtConsole.AppendText(message & vbNewLine)
End Sub
Then, instead of using MsgBox("error message") i call my function this way:
ConsoleBox("My error message")
This has worked so far, and replaces all the annoying message boxes whose Accept buttons you must clik every time something goes wrong.
Hope this helps.