I need to change the connectionstring area of my aap.config file in vb.net. I have tried several codes but nothing worked for me. I was suggested following code
Dim config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None)
Dim connectionStringsSection = DirectCast(config.GetSection("connectionStrings"), ConnectionStringsSection)
connectionStringsSection.ConnectionStrings("Blah").ConnectionString = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah"
config.Save()
ConfigurationManager.RefreshSection("connectionStrings")
But I do not understand what will be "Blah" in my code? Also how does this change the text?
Secondly, if I use Readalltext and replacetext and then writealltext, will it be ok or it can cause any problems?
Thanks
To store and retrieve connection string from app.config use the following method:
Create a key in app.config:
<appSettings>
<add key="ConnectionString" value=""/>
</appSettings>
To set value of connection string:
Dim config As System.Configuration.Configuration
Dim fileMap As New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "Path of app.config"
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
' Sets values to config file.
If config.HasFile() Then
config.AppSettings.Settings.Item("ConnectionString").Value = "Data Source=blah;Initial Catalog=blah;UID=blah;password=blah"
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("AppSettings")
End If
To get the value of Connection String:
Dim config As System.Configuration.Configuration
Dim fileMap As New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "Path of app.config"
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
' Sets values to config file.
If config.HasFile() Then
strConnString = config.AppSettings.Settings.Item("ConnectionString").Value
End If
Here strConnString is a string variable which will store connection string value.
Related
I am using the following vb code to get the list of files in a ftp directory and populate a database table with it to be used in another integration process. Please forgive my bad bad programming skills (I am not a vb.net developer).
Public Sub Main()
Dim StrFolderArrary As String() = Nothing
Dim StrFileArray As String() = Nothing
Dim fileName As String
Dim RemotePath As String
RemotePath = Dts.Variables("User::FTPFullPath").Value.ToString()
Dim ADODBConnection As SqlClient.SqlConnection
ADODBConnection = DirectCast(Dts.Connections("DB_Connection").AcquireConnection(Dts.Transaction), SqlClient.SqlConnection)
Dim cm As ConnectionManager = Dts.Connections("FTP_Connection") 'FTP connection manager name
Dim ftp As FtpClientConnection = New FtpClientConnection(cm.AcquireConnection(Nothing))
ftp.Connect() 'Connecting to FTP Server
ftp.SetWorkingDirectory(RemotePath) 'Provide the Directory on which you are working on FTP Server
ftp.GetListing(StrFolderArrary, StrFileArray) 'Get all the files and Folders List
'If there is no file in the folder, strFile Arry will contain nothing, so close the connection.
If StrFileArray Is Nothing Then
ftp.Close()
'If Files are there, Loop through the StrFileArray arrary and insert into table
Else
For Each fileName In StrFileArray
'MessageBox.Show(fileName)
Dim SQLCommandText As String
SQLCommandText = "INSERT INTO dbo._FTPFileList ([DirName],[FileName]) VALUES (N'" + RemotePath + "', N'" + fileName + "')"
'MessageBox.Show(SQLCommandText)
Dim cmdDatabase As SqlCommand = New SqlCommand(SQLCommandText, ADODBConnection)
cmdDatabase.ExecuteNonQuery()
Next
ftp.Close()
End If
' Add your code here
'
Dts.TaskResult = ScriptResults.Success
End Sub
It works fine and I get the results in the database table. The problem is that the encoding of the strings coming from FTP makes the file names with accentuation to be written incorrectly as shown in the example below.
database table
The correct file name is Razão and I know that the db collation is correct since it can be written like this.
So I tried to convert the strings using this code for each file name in the string array but without any success.
For Each fileName In StrFileArray
Dim utf8 As UTF8Encoding = New UTF8Encoding(True, True)
Dim bytes As Byte() = New Byte(utf8.GetByteCount(fileName) + utf8.GetPreamble().Length - 1) {}
Array.Copy(utf8.GetPreamble(), bytes, utf8.GetPreamble().Length)
utf8.GetBytes(fileName, 0, fileName.Length, bytes, utf8.GetPreamble().Length)
Dim fileName2 As String = utf8.GetString(bytes, 0, bytes.Length)
I believe it is coming with different encoding from the FTP side so I would like to know how to convert the strings during the GetListing method.
Or do you have any ideas how to deal with this?
Thanks in advance.
edit:
I also tried the following code without success.
Dim utf8 As Encoding = Encoding.UTF8
Dim w1252 As Encoding = Encoding.GetEncoding(1252)
Dim w1252Bytes As Byte() = w1252.GetBytes(fileName)
Dim utf8Bytes As Byte() = Encoding.Convert(w1252, utf8, w1252Bytes)
Dim utf8Chars As Char() = New Char(utf8.GetCharCount(utf8Bytes, 0, utf8Bytes.Length) - 1) {}
utf8.GetChars(utf8Bytes, 0, utf8Bytes.Length, utf8Chars, 0)
Dim fileName2 As String = New String(utf8Chars)
i just want to ask how can i add a password on a existing PDF file, i just created a pdf file using crystal reports and i kinda need to add some security features for the report. Thank you very much in advance.
lets say the file "c:\Folder1\sample.pdf" already exist. i have seen codes like the one below, but i don't know if it works because i don't know what to add in my reference to make it work
' Define input and output files path.
Dim intputFilePath As String = Program.RootPath + "\\" + "1.pdf"
Dim outputFilePath As String = Program.RootPath + "\\" + "1_with_pw.pdf"
' Set passwords for user and owner.
Dim userPassword As String = "you"
Dim ownerPassword As String = "me"
' Create password setting.
Dim setting As PasswordSetting = New PasswordSetting(userPassword, ownerPassword)
' Add password to plain PDF file and output a new file.
Dim errorCode As Integer = PDFDocument.AddPassword(intputFilePath, outputFilePath, setting)
If errorCode = 0 Then
Console.WriteLine("Success")
Else
Console.WriteLine("Failed")
End If
Dim WorkingFolder As String = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
Dim InputFile As String = Path.Combine(WorkingFolder, "PSNOs.pdf")
Dim OutputFile As String = Path.Combine(WorkingFolder, "PSNOs_enc.pdf")
Using input As Stream = New FileStream(InputFile, FileMode.Open, FileAccess.Read, FileShare.Read)
Using output As Stream = New FileStream(OutputFile, FileMode.Create, FileAccess.Write, FileShare.None)
Dim reader As New PdfReader(input)
PdfEncryptor.Encrypt(reader, output, True, Nothing, "secret", PdfWriter.ALLOW_SCREENREADERS)
End Using
End Using
the word "PdfReader" have an error message but it doesn't ask to import something..
I can't seem to read a .xlsx file using the following connection string:
Webconfig
<add name="Excel07ConString" connectionString="Provider=Microsoft.ACE.OLEDB.12.0;Data Source={0};Extended Properties='Excel 8.0;HDR={1}'"/>
Code File
conStr = ConfigurationManager.ConnectionStrings("Excel07ConString").ConnectionString
Dim connExcel As New OleDbConnection(conStr)
connExcel.Open()
I have been getting this error:
Cannot initialize the data source object of OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)". OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)" returned message "'F:\Ishan\Projects\ImportExcel2DB\ImportExcel2DB\Files\Whole Extract.xlsx' is not a valid path. Make sure that the path name is spelled correctly and that you are connected to the server on which the file resides.".
and yes there is file at this specific location. Any help would be appreciated!
The HDR needs to be either Yes or No. See my project below
Imports System.IO
Imports System.Data
Imports System.Data.OleDb
Module Module1
Sub Main()
Dim reader As New CSVReader()
Dim ds As DataSet = reader.ReadCSVFile("filename", True)
End Sub
End Module
Public Class CSVReader
Public Function ReadCSVFile(ByVal fullPath As String, ByVal headerRow As Boolean) As DataSet
Dim path As String = fullPath.Substring(0, fullPath.LastIndexOf("\") + 1)
Dim filename As String = fullPath.Substring(fullPath.LastIndexOf("\") + 1)
Dim ds As DataSet = New DataSet()
Dim header As String
If headerRow Then
header = "Yes"
Else
header = "No"
End If
Try
If File.Exists(fullPath) Then
Dim ConStr As String = String.Format("Provider=Microsoft.Jet.OLEDB.4.0;Data Source={0}" + ";Extended Properties=""Text;HDR={1};FMT=Delimited\""", path, header)
Dim SQL As String = String.Format("SELECT * FROM {0}", filename)
Dim adapter As OleDbDataAdapter = New OleDbDataAdapter(SQL, ConStr)
adapter.Fill(ds, "TextFile")
ds.Tables(0).TableName = "Table1"
End If
For Each col As DataColumn In ds.Tables("Table1").Columns
col.ColumnName = col.ColumnName.Replace(" ", "_")
Next
Catch ex As Exception
Console.WriteLine(ex.Message)
End Try
Return ds
End Function
End Class
Hi I am trying to Authenticate to my web service and missing something..
My Service reference is called - MBSDKServiceLD
My Web Reference is called - LANDeskMBSDK
I have these connected in Visual Studio 2013 And are resolving methods in the code
Here is my code for the authentication but its not complete..
Option Explicit On
Imports System.Net
Dim objFSO As Object
Dim objExec As Object
Dim objNetwork As Object
Dim strComputer As String
Dim strUser As String
Dim User As String
Dim Password As String
Dim Domain As String
Dim URL As String
Dim Cred As String
Dim strTaskName As String
Dim strPackageName As String
Dim strDeliveryMethod As String
Dim strCustomGroup As String
Dim boolStartNow As Boolean
Dim WakeUpMachines As Boolean
Dim boolCommonTask As Boolean
Dim strAutoSync As String
Dim TaskID As String
Dim strConnection As New System.Data.SqlClient.SqlConnection
Dim LDWebService
Dim intTaskID As String
Dim LDService As Object
Dim strDeviceName As String
Sub RunLANDeskTask(ByVal sender As Object, ByVal LDService As MBSDKServiceLD.MBSDKSoap)
End Sub
Sub CreateTask
User = "username1"
Password = "password1"
Domain = "domain1"
URL = "http://myserver/MBSDKService/MsgSDK.asmx?WSDL"
Dim MyCredentails As New System.Net.CredentialCache()
Dim NetCred As New System.Net.NetworkCredential(User, Password, Domain)
MyCredentails.Add(New Uri(URL), "Basic", NetCred)
strPackageName = "Adobe Acrobat XI PRO"
strDeliveryMethod = "Standard push distribution"
Dim strTargetDevice As String
strTargetDevice = Nothing
strTaskName = strPackageName & " - " & DateTime.Now & " -Provisioning Task for" & " " & strComputer
Try
RunLANDeskTask(LANDeskMBSDK, LDService.CreateTask(strTaskName, strDeliveryMethod, strPackageName, False, False, strAutoSync).TaskID)
Catch ex As Exception
MsgBox("Error creating task")
End Try
End Sub
What comes after this part or have i got this totally wrong?
When I type LDService. I see all the methods so I am connecting to the reference in VS but not authenticating.
It should really be as simple as this (sorry it's in c#):
MyWebService svc = new MyWebService();
svc.Credentials = new System.Net.NetworkCredential(UserID, pwd);
bool result = svc.MyWebMethod();
The following might be helpful:
This is quite old, but the comments are good.
I've just found the following on MSDN, which looks like what you want:
localhost.Sample svc = new localhost.Sample();
try {
CredentialCache credCache = new CredentialCache();
NetworkCredential netCred =
new NetworkCredential( "Example", "Test$123", "sseely2" );
credCache.Add( new Uri(svc.Url), "Basic", netCred );
svc.Credentials = credCache;
Ok i got this working... But i have to run the code under an account that can access the Web service -
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim CredCache As New System.Net.CredentialCache
CredCache.Add(New Uri(myService.Url), "Basic", Cred)
myService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials
I am using following code to replace the passwords in my app.config. It replaces successfully but does not reload config file in the memory so datasets give error of wrong password.
Please help
Dim vrTextFind As String = "Password"
Dim vrTextReplaceWith As String = "PWD"
Dim path As String = "D:\VS2008\EncTest\EncTest\bin\Debug\enctest.exe.config"
Dim readText As String = File.ReadAllText(path)
TextBox1.Text = readText
'Find
Dim idx As Integer = 0
idx = TextBox1.Text.IndexOf(vrTextFind, idx)
If idx = -1 Then
MessageBox.Show(vrTextFind & " is not in Textbox1")
Else
TextBox1.SelectionStart = idx
TextBox1.SelectionLength = vrTextFind.Length
End If
'Replace
If TextBox1.Text.Contains(TextBox1.Text) Then
TextBox1.Text = TextBox1.Text.Replace(vrTextFind, vrTextReplaceWith)
Else
MessageBox.Show(TextBox1.Text & " is not in Textbox3")
End If
'''''
'Write all back
File.WriteAllText(path, TextBox1.Text)
'Refreshes the connection string section
ConfigurationManager.RefreshSection("connectionStrings")
In windows application app.config is read only once, when the application starts. If you modify it you will need to restart the app.
Suggestion
Instead of storing password in app.config store it in some other file (like Settings file). Which can be modified and read at runtime. For Settings you can read on MSDN. And choose User-Scope settings.
Hope this helps you.
Instead of using File.WriteallText use the following code to write to app.config:
config.AppSettings.Settings.Item("ConnectionString").Value = TextBox1.Text
config.Save(ConfigurationSaveMode.Modified)
ConfigurationManager.RefreshSection("AppSettings")
Then again load the connection string value from app.config.
Dim config As System.Configuration.Configuration
Dim fileMap As New ExeConfigurationFileMap()
fileMap.ExeConfigFilename = "Path of app.config"
config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None)
' Sets values to config file.
If config.HasFile() Then
strConnString = config.AppSettings.Settings.Item("ConnectionString").Value
End If