strange problem with reflection and static method - wpf

Visual Studio 2008 - framework 3.5 - Visual Basic
Hi!
I have a problem with a static method invoked by reflection.
On the loading of my win-wpf I create a copy of "A4Library.dll" with the name "_temp.dll", in the same directory of the original.
Then, on a button-click event, I invoke a static method on the _temp.dll in this way:
Dim AssemblyFileName As String = Directory.GetCurrentDirectory() & "\_temp.dll"
Dim oAssembly As Assembly = Assembly.LoadFrom(AssemblyFileName)
Dim TypeName As String = "MyLibrary.MyService"
Dim t As Type = oAssembly.GetType(TypeName)
Dim mi As MethodInfo = t.GetMethod("MyMethod", BindingFlags.Static AndAlso BindingFlags.Public)
Dim bResponse As Boolean = mi.Invoke(Nothing, New Object() {MyPar1, MyPar2})
But this works well only if I the .exe file is not in the same directory of the .dll files, otherwise I obtain this error (translated):
InnerException {"Cast impossible of [A]MyType on [B]MyType. The type A is originated from ... in the context 'Default' in the position 'F:\MyPath\A4Library.dll'. The type B is originated from ... in the context 'LoadFrom' in the position 'F:\MyPath_temp.dll'."}
It's strange: it seems to be a conflict with the same method in the original .dll, but I can't undertend why it looks at the original and not at the copy. If the .exe file relative to the principal assembly is placed in another directory, all runs well.
I neet to have the .exe in the same folder of the .dll, how can I solve the problem?
Thank you!
Pileggi

Why create a copy of assembly before executing static method? If creating a copy is needed, load that assembly in another AppDomain and execute the method in there.

Related

Redirect a picture to a direct location

Im using WPF and VB.net and in order to use a picture (source) for an image you need the file to be in the folder of the application, so the source of stack.png would be stack.png.
But I want to use C:/APictureLocation/stack.png. I think Releative file name maybe? I honestly do not know how to ask a question without explaining. Sorry.
So I can do:
image.source = "C:\APictureLocation\stack.png"
instead of
image.source = "stack.png"
Thanks for you help!
Do not vote down without giving me pointers. Doesn't help the community.
My answer!
Private Sub BrowseButton_Click(ByVal sender As Object, ByVal e As System.Windows.RoutedEventArgs)
Dim dialog As New OpenFileDialog()
dialog.InitialDirectory = "C:\"
dialog.ShowDialog()
picbox.Source = New System.Windows.Media.Imaging.BitmapImage(New Uri(dialog.FileName, UriKind.Absolute))
End Sub
I believe I have the solution to your problem (or what I think your asking)...
Let's say your image source folder is 'C:\Images\ProgramImages'
(notice how I have used a '\' not a '/' in my path...)
Firstly, create a new form called 'ImageBrowser'. Then, add a ListBox control and name it 'ImageBrowserLB'. After this, double click on the ImageBrowser form so it takes you to the code editor. In the auto-generated sub, type the following:
For Each F As File In System.IO.Directory.GetFiles("C:\Images\ProgramImages\")
If Path.Extension(F) = ".png" Then
ImageBrowserLB.Items.Add(Path.GetFileName(F))
End If
Next
When that form loads, it will add all the files with a PNG extension in the directory I specified. I'm sure you can take this code and manipulate it to do what you would like (which isn't very clear in your question!).
Hope this helped,
Rodit

Querying Access database vb.net

I am trying to figure out how to query an access database to take info from the database and put it into a class array. I know how to do some querying using basic LINQ, but not sure how to do it the way I want it to. I have a character class I am using, I am storing all the character traits in a database. I want to query the database and add that info to a class array. Any help would be greatly appreciated.
Here at the class private variables which are the same traits in the database:
Public Class Character
Private _strName As String
Private _intLevel As Integer
Private _intHealth As Integer
Private _intDamage As Integer
Private _intScore As Integer
First of all. I have to say this is not a good question.
Actually what you are saying is...: Please build me the dataconnections for this acces database and a visual studio form.
But because I'm in a good mood, That's what I did for you.
I created a little database file in acces.I saved it into a folder called database. Which is located in the project directory.
I made 2 classes. 1 CharactersForm, and 2 Gateway
the gateway is to make an connection to your Acces database.
The CharactersForm is the form what you see when you debug
Here is the CharactersForm class.
Make sure you drag and drop a listbox and a button
Call the listbox ListBoxCharacters.
Call the button InladenButton. Or call it whatever you want, But make sure it will fit the code given.
Option Explicit On
Option Strict On
Option Infer On
Public Class CharactersForm
Dim _CharactersGateway As New Gateway
Private Sub InladenButton_Click(sender As Object, e As EventArgs) Handles InladenButton.Click
_CharactersGateway.LoadDataTableCharacters()
ListBoxCharacters.DataSource = _CharactersGateway.CharactersDataTable
ListBoxCharacters.DisplayMember = "Name"
End Sub
End Class
The Gateway Class ( to make connection to your acces file)
If somehow visual studio cannot reach the database then it means the connectionstring is not correct. Make sure the connection string is exactly as where your accesfile.accdb is located
Option Explicit On
Option Strict On
Option Infer On
Imports System.IO
Imports System.Data.OleDb
Public Class Gateway
Public Shared AppPath As String = Application.StartupPath()
'\Debug
Public Shared DirectoryUp1 As String = Path.GetDirectoryName(AppPath)
'\bin
Public Shared DirectoryUp2 As String = Path.GetDirectoryName(DirectoryUp1)
'\CharactersStackOverFlow
Public Shared DirectoryUp3 As String = Path.GetDirectoryName(DirectoryUp2)
'\CharactersStackOverFlow
Public Shared AccesDatabaseFilePath As String = DirectoryUp3 & "\DataBase\Characters.accdb"
Dim ConnectionString As New OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source= " & AccesDatabaseFilePath)
Public Property DataSetCharacters As New DataSet
Public ReadOnly Property CharactersDataTable As DataTable
Get
CharactersDataTable = DataSetCharacters.Tables("Characters")
End Get
End Property
Public CharactersDataAdapter As OleDbDataAdapter
Public Sub LoadDataTableCharacters()
CharactersDataAdapter = New OleDbDataAdapter("SELECT * FROM Characters", ConnectionString)
CharactersDataAdapter.Fill(DataSetCharacters, "Characters")
Dim kamersCommandBuilder As New OleDbCommandBuilder(CharactersDataAdapter)
End Sub
End Class
This is as Yuriy Galanter said. You need the OleDbConnection.
If you are using office 2010 and you get thsi warning ::
'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine
You need to download the 2007 Office System Driver. It works also for 2010 don't ask me why.
Type '2007 Office System Driver' in google. And from microsoft you can download and install it.
ALL DONE!
if you run the program and press the load button. The names of your characters will come in the listbox.
If you want to put values of the fields of the database in variables. Then it's just about making a for loop and put them in dimmed variables. That is something I'm sure you can do yourself. The connection to the database and the loading in the program is already sorted out now!
Good luck
Jonathan

WPF Vb.net Copyto not working?

I am simply tyring to fire an event that copies a program to the Startup folder. I do not understand where I am going wrong? I keep on getting exception message. The file that is being copies is NOT in use.
Try
Dim DesktopLink As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim StartupFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Startup)
Dim info As New FileInfo(StartupFolder)
info.CopyTo(DesktopLink + "\doessomething.bat")
Catch ex As Exception
MessageBox.Show("Error: Can not copy to startup folder")
End Try
Right now, you're creating a FileInfo from a folder, not a file.
This should likely be:
Dim info As New FileInfo(Path.Combine(StartupFolder, "doessomething.bat"))
info.CopyTo(Path.Combine(DesktopLink, "doessomething.bat"))
Or, even easier:
Dim source = Path.Combine(StartupFolder, "doessomething.bat")
Dim target = Path.Combine(DesktopLink, "doessomething.bat")
File.Copy(source, target)

VB.NET: WPF Single Instance

Has anyone using VB.NET 2010 been able to create a single instance application?
I've followed the MSDN sample but it does not have an Application.xaml file.
Converting any C# samples to VB doesn't work as I cannot override the Main sub in Application.xaml (C# calls it App.xaml).
You can try using a Mutex. In the projects properties, disable the application framework and set Sub Main as the startup object. Then add a Module to your project:
Imports System.Threading
Module EntryPoint
Sub Main()
Dim noPreviousInstance As Boolean
Using m As New Mutex(True, "Some Unique Identifier String", noPreviousInstance)
If Not noPreviousInstance Then
MessageBox.Show("Application is already started!")
Else
Dim mainWindow As New MainWindow()
Dim app As New Application()
app.Run(mainWindow)
End If
End Using
End Sub
End Module
With this method, you will have to take care of your app's shutdown by calling the Shutdown method of the application.
Here's a few possible solutions. I'd look through the whole thread here before deciding on one. Make sure you backup your code before trying any of these, so if one doesn't work, you can try another.
http://social.msdn.microsoft.com/forums/en-US/wpf/thread/6c15b837-9149-4b07-8a25-3266949621a7/

XAML Parser cannot find resource within dynamically loaded XAP when creating form instance

I've followed Tim Heuer's video for dynamically loading other XAP's (into a 'master' Silverlight application), as well as some other links to tweak the loading of resources and am stuck on the particular issue of loading style resources from within the dynamically loaded XAP (i.e. the contents of Assets\Styles.xaml). When I run the master/hosting applcation, it successfully streams the dynamic XAP and I can read the deployment info etc. and load the assembly parts. However, when I actuall try to create an instance of a form from the Dynamic XAP, it fails with
Cannot find a Resource with the Name/Key LayoutRootGridStyle
which is in it's Assets\Styles.xaml file (it works if I run it directly so I know it's OK). For some reason these don't show up as application resources - not sure if I've totally got the wrong end of the stick, or am just missing something? Code snippet below (apologies it's a bit messy - just trying to get it working first) ...
'' # Here's the code that reads the dynamic XAP from the web server ...
'' #...
wCli = New WebClient
AddHandler wCli.OpenReadCompleted, AddressOf OpenXAPCompleted
wCli.OpenReadAsync(New Uri("MyTest.xap", UriKind.Relative))
'' #...
'' #Here's the sub that's called when openread is completed
'' #...
Private Sub OpenXAPCompleted(ByVal sender As Object, ByVal e As System.Net.OpenReadCompletedEventArgs)
Dim sManifest As String = New StreamReader(Application.GetResourceStream(New StreamResourceInfo(e.Result, Nothing), New Uri("AppManifest.xaml", UriKind.Relative)).Stream).ReadToEnd
Dim deploymentRoot As XElement = XDocument.Parse(sManifest).Root
Dim deploymentParts As List(Of XElement) = _
(From assemblyParts In deploymentRoot.Elements().Elements() Select assemblyParts).ToList()
Dim oAssembly As Assembly = Nothing
For Each xElement As XElement In deploymentParts
Dim asmPart As AssemblyPart = New AssemblyPart()
Dim source As String = xElement.Attribute("Source").Value
Dim sInfo As StreamResourceInfo = Application.GetResourceStream(New StreamResourceInfo(e.Result, "application/binary"), New Uri(source, UriKind.Relative))
If source = "MyTest.dll" Then
oAssembly = asmPart.Load(sInfo.Stream)
Else
asmPart.Load(sInfo.Stream)
End If
Next
Dim t As Type() = oAssembly.GetTypes()
Dim AppClass = (From parts In t Where parts.FullName.EndsWith(".App") Select parts).SingleOrDefault()
Dim mykeys As Array
If Not AppClass Is Nothing Then
Dim a As Application = DirectCast(oAssembly.CreateInstance(AppClass.FullName), Application)
For Each strKey As String In a.Resources.Keys
If Not Application.Current.Resources.Contains(strKey) Then
Application.Current.Resources.Add(strKey, a.Resources(strKey))
End If
Next
End If
Dim objectType As Type = oAssembly.GetType("MyTest.MainPage")
Dim ouiel = Activator.CreateInstance(objectType)
Dim myData As UIElement = DirectCast(ouiel, UIElement)
Me.splMain.Children.Add(myData)
Me.splMain.UpdateLayout()
End Sub
'' #...
'' # And here's the line that fails with "Cannot find a Resource with the Name/Key LayoutRootGridStyle"
'' # ...
System.Windows.Application.LoadComponent(Me, New System.Uri("/MyTest;component/MainPage.xaml", System.UriKind.Relative))
'' #...
Just to re-cap, there are 3 scenarios to consider ...
1) The dynamically loaded XAP's style resources are left in a merged resource dictionary (in a seperate xaml file), referenced from the app.xaml of the dynamically loaded silverlight app (XAP) - When running the master application the resources from the dynamic XAP do not appear to be present under the current application (after loading the XAP assembly parts). Error occurs.
2) The dynamically loaded XAP's style resources are moved from the merged resource dictionary (from a seperate xaml file), into the app.xaml of the dynamic application, in place of the merged resource dictionary reference. - When running the master application the resources from the dynamic XAP DO appear to be present under the current application (after loading the XAP assembly parts). However, the error still occurs.
3) The dynamically loaded XAP's style resources are copied into the app.xaml of the calling/master application (not desirable). - Error no longer occurs.
Answer provided by bykinag on silverlight forums ...
I added the following line after loading the assembly.
App.Current.Resources.MergedDictionaries.Add(New ResourceDictionary() With {.Source = New Uri("/MyTest;component/Assets/Styles.xaml", UriKind.RelativeOrAbsolute)})
I now have an issue where the dynamic application can't seem to see other pages within it (Page not found) but I'll probably raise that separately if I can't resolve it.

Resources