could not find a part of the path - vb.net

I have a XSD file which i am using to validate XML. The problem is i get an error. The error is not thrown when i run the code in local machine. But if i run the code in integration, the error is thrown.
Dim strSchemaPath As String = String.Empty
Dim xmlSettings As XmlReaderSettings = Nothing
Dim msStream As MemoryStream = Nothing
IsXMLValid = True
msStream = New MemoryStream(System.Text.ASCIIEncoding.UTF8.GetBytes(xmlRequest))
strSchemaPath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "XSD\Input.xsd")
xmlSettings = New XmlReaderSettings()
xmlSettings.ValidationType = ValidationType.Schema
xmlSettings.Schemas.Add(Nothing, strSchemaPath)

There was no issues with access of the file. There was a issue with the files to be copied in the server path. We can manage the files in the properties. I just changed the file property to copy always and it worked.

Related

copy file to directory in visual basic vb.net

I am tringing to copy files settings.copy from sourceDir to backupDir but getting error
Dim sourceDir As String = "c:\in\settings.copy"
Dim backupDir As String = "c:\out\"
File.Copy(sourceDir, backupDir)
while executing above script getting below error
System.IO.DirectoryNotFoundException: 'Could not find a part of the path 'c:\out\'.'
I already created c:\out\ folder
Have you read the documentation for File.Copy, or even just paid attention to Intellisense? Both arguments must be file paths. Neither can be folder paths.
On a related note, why do you have a variable named 'sourceDir' when it's clearly a file path and not a directory path? If you name things clearly - and particularly not misleadingly - then it's more likely that you'll avoid such mistakes. Of course, using the Help menu or F1 key to confirm that you're using a type of method correctly would help too.
Dim userprofile As String = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile)
Dim SystemDir As String = Environment.GetEnvironmentVariable("SystemDrive")
Dim sourceDir As String = "y\inbound\settings.exe"
Dim backupDir As String = "AppData\Local\user\default_user\"
Dim root As String = Path.GetPathRoot(userprofile)
Dim useDrpath As String = Path.Combine(userprofile, backupDir)
Dim SysDrpath As String = Path.Combine(SystemDir, root, sourceDir)
Dim file = New FileInfo("settings.cps")
file.CopyTo(Path.Combine(SysDrpath, useDrpath, file.Name), True)
My gole is to copy file from system installed driver to user profile driver
with above code i am able to copy file
c:\y\inbound\settings.exe C:\Users\pavan\AppData\Local\user\default_user\
please suggested any other better way to do above

Cannot upload the file to dropbox when published on server

I'm trying to upload a file to dropbox. The file gets uploaded and code works when i'm running locally. But file never gets uploaded when published on the server. I'm having the following error .
Could not load type 'System.Security.Authentication.SslProtocols' from assembly 'System.Net.Primitives, Version=4.0.0.0, Culture=neutral, PublicKeyToken=*********'.
I'm trying the below code sample to upload it
public sub uploadtodropbox()
Using httpclient As New HttpClient
httpclient.Timeout = TimeSpan.FromMinutes(20)
Dim _DropboxClient = New DropboxClient(ApiKeyDropBox, config)
Dim resultstring As String = UploadToDB(_DropboxClient, dropboxdir, docName, fileBytes)
_DropboxClient.Dispose()
If Not resultstring = "RanToCompletion" Then
ErrorMsg &= "The following error occured: " & resultstring
End If
End Using
End Sub
and this is the funtion that is uploading to Dropbox
Private Function UploadToDB(_DropboxClient As DropboxClient, Directory As String, Filename As String, Content As [Byte]()) As String
Try
Dim result As String = "Unknown"
Dim trycnt As String = 0
Dim tryLimit As String = 20
Dim respnse As Task(Of FileMetadata)
Using _mStream = New MemoryStream(Content)
respnse = _DropboxClient.Files.UploadAsync(Convert.ToString(Directory & Convert.ToString("/")) & Filename, WriteMode.Overwrite.Instance, body:=_mStream)
While Not respnse.IsCompleted And trycnt < tryLimit
Threading.Thread.Sleep(1000)
trycnt += 1
result = respnse.Status.ToString()
End While
UploadToDB = result
End Using
End try
END function.
I have tried without using the httpclient then i am getting this error :
The type initializer for 'Dropbox.Api.DropboxRequestHandlerOptions' threw an exception.
Thank you
I go the answer . I have system.Net.primitives assembly that is creating a problem uploading the file to Dropbox. All i need to do is delete the reference and also the System.Net.Http has versions have been set wrong in the web.config file. Once i set that in the configuration everything works fine.
For the certificate I have set the on post back to validate and allow the certificates generated in the event handler.

Saving embedded resource contents to string

I am trying to copy the contents of an embedded file to a string in Visual Basic using Visual Studio 2013. I already have the resource (Settings.xml) imported and set as an embedded resource. Here is what I have:
Function GetFileContents(ByVal FileName As String) As String
Dim this As [Assembly]
Dim fileStream As IO.Stream
Dim streamReader As IO.StreamReader
Dim strContents As String
this = System.Reflection.Assembly.GetExecutingAssembly
fileStream = this.GetManifestResourceStream(FileName)
streamReader = New IO.StreamReader(fileStream)
strContents = streamReader.ReadToEnd
streamReader.Close()
Return strContents
End Function
When I try to save the contents to a string by using:
Dim contents As String = GetFileContents("Settings.xml")
I get the following error:
An unhandled exception of type 'System.ArgumentNullException' occurred in mscorlib.dll
Additional information: Value cannot be null.
Which occurs at line:
streamReader = New IO.StreamReader(fileStream)
Nothing else I've read has been very helpful, hoping someone here can tell me why I'm getting this. I'm not very good with embedded resources in vb.net.
First check fileStream that its not empty as it seems its contains nothing that's why you are getting a Null exception.
Instead of writing to file test it by using a msgBox to see it its not null.
fileStream is Nothing because no resources were specified during compilation, or because the resource is not visible to GetFileContents.
After fighting the thing for hours, I discovered I wasn't importing the resource correctly. I had to go to Project -> Properties -> Resources and add the resource from existing file there, rather than importing the file from the Solution Explorer. After adding the file correctly, I was able to write the contents to a string by simply using:
Dim myString As String = (My.Resources.Settings)
Ugh, it's always such a simple solution, not sure why I didn't try that first. Hopefully this helps someone else because I saw nothing about this anywhere else I looked.

How to save changes to app.config file from runtime for a Visual Studio Add-In

Thanks to Is there a config type file for Visual Studio Add-In? I was able to create an app.config file for the Visual Studio add-in I am developing with the ability to read/write to it.
Now I am having trouble saving the changes made to it at runtime. I have been running the following test code, but when I look the app.config file after running in debug, nothing has changed.
Dim pluginAssemblyPath As String = Assembly.GetExecutingAssembly().Location
Dim configuration As Configuration = ConfigurationManager.OpenExeConfiguration(pluginAssemblyPath)
Dim test1 As String = configuration.AppSettings.Settings.Item("Key1").Value
configuration.AppSettings.Settings.Item("Key1").Value = "Is this thing on?"
Dim test3 As String = configuration.AppSettings.Settings.Item("Key1").Value
configuration.AppSettings.SectionInformation.ForceSave = True
configuration.Save(ConfigurationSaveMode.Modified)
Dim pluginAssemblyPath As String = Assembly.GetExecutingAssembly().Location
'Dim configuration As Configuration = ConfigurationManager.OpenExeConfiguration(pluginAssemblyPath)
Dim test1 As String = configuration.AppSettings.Settings.Item("Key1").Value
configuration.AppSettings.Settings.Item("Key1").Value = "Is this thing on?"
Dim test3 As String = configuration.AppSettings.Settings.Item("Key1").Value
configuration.AppSettings.SectionInformation.ForceSave = True
configuration.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("appSettings")
The actual app.config will not change, but the config file inside of the bin folder does.

unable to run Exchange Powershell through vb.net application

So I'm going round in circles trying to get this to work, I've been trying for two days and I just can't figure it out.
I have the following vb function that takes a created powershell script, and should run it in powershell. Everything works fine, until the point at which the command pipeline is invoked. At this point, no commands run.
As you can see, I have tried to add the Microsoft.Exchange.Management.PowerShell.E2010 snapin to the runspace, it didn't like that at all stating something along the lines of the snapin didnt exist (which it does), and also when I run the code as shown, no commands are recognised as valid. I even added the specific command "Add-PSSnapin" to try and load any Exchange snapins, but it states that "Add-PSSnapin" is not recognised as a valid command.
If I pause the program just before the commands are involked, I can see every command within the pipeline, in the correct format. If I copy and paste the command text in the pipeline directly into a powershell window, it runs fine.
My code is below, any suggestions welcome.
edit: I have also tried adding the line "Add-PSSnapin Ex" (with an asterisk each side of Ex - I cant figure the formatting out on this, sorry)
to try and load the Exchange PS Snapins as the first thing the script would run (opposed to setting this up in the runspace) but no luck
Private Function scriptRunner(ByVal scripttorun As String) As String
Dim initial As InitialSessionState = InitialSessionState.CreateDefault()
Dim result As String = ""
Dim lineFromScript As String = ""
Dim reader As New StreamReader(tempScript)
Dim rsConfig As RunspaceConfiguration = RunspaceConfiguration.Create()
Dim snapInException As New PSSnapInException
Dim strUserName As String = "DOMAIN\USER"
Dim strPassword As String = "PASSWORD"
Dim SecuredPSWD As New System.Security.SecureString()
For Each character As Char In strPassword
SecuredPSWD.AppendChar(character)
Next
Dim wsmConnectionInfo As WSManConnectionInfo
Dim strSystemURI As String = "http://SERVER.DOMAIN/powershell?serializationLevel=Full"
Dim strShellURI As String = "http://schemas.microsoft.com/powershell/Microsoft.Exchange"
Dim powerShellCredentials As PSCredential = New PSCredential(strUserName, SecuredPSWD)
wsmConnectionInfo = New WSManConnectionInfo(New Uri(strSystemURI), strShellURI, powerShellCredentials)
Dim runspace As Runspace = RunspaceFactory.CreateRunspace(wsmConnectionInfo)
Runspace.Open()
' runspace.RunspaceConfiguration.AddPSSnapIn("Microsoft.Exchange.Management.PowerShell.E2010", snapInException)
Dim pipeLine As Pipeline = runspace.CreatePipeline()
Dim command As Command = New Command("")
' TEST >> pipeLine.Commands.Add("Add-PSSnapin *Ex*")
Do While reader.Peek() <> -1
lineFromScript = Nothing
lineFromScript = reader.ReadLine()
pipeLine.Commands.Add(lineFromScript)
'command.Parameters.Add(lineFromScript)
'pipeLine.Commands.Add(command)
Loop
'' Run the contents of the pipeline
Dim psObjCollection As Collection(Of PSObject) = pipeLine.Invoke()
runspace.Close()
runspace.Dispose()
Return ""
End Function
I ended up working around the problem rather than fixing it.
I moved the script code into the vb.net application, and wrote each line to a file, i.e.
writer.WriteLine("Add-PSSnapin *Ex*")
Then I loaded the script through PowerShell as an application;
Dim exeStartInfo As System.Diagnostics.ProcessStartInfo
Dim exeStart As New System.Diagnostics.Process
exeStartInfo = New System.Diagnostics.ProcessStartInfo("C:\Windows\System32\WindowsPowerShell\v1.0\powershell.exe")
exeStartInfo.Arguments = ("-command work\scriptbuilder.ps1")
exeStartInfo.WorkingDirectory = "C:\ExchangeManager\"
exeStartInfo.UseShellExecute = False
exeStart.StartInfo = exeStartInfo
exeStart.Start()
exeStart.Close()
Not ideal but it got the job done.