Get specific value from .txt file using identifier VB.Net - vb.net

I try to create a config file using .txt files, here I find it difficult to read the contents of the format.. already from yesterday I searched on google , but no similar case like me or maybe I missed it..
contents of .txt I have is as follows :
Cek Server IP = 192.168.10.1
Server IP = 192.168.10.1
Cek My Website = www.google.com
My Website = www.anothersite.com
this is my code :
WebControl.Source = New Uri("about:blank")
If My.Computer.Network.Ping("XXX") Then
WebControl.Source = New Uri("ZZZ")
Else
MsgBox("CANNOT CONNECT TO SERVER")
Exit Sub
End If
what i want is how to get value "192.168.10.1" From "Cek Server IP" then send to "XXX" and Get Value "192.168.10.1" from "Server IP" then send to "ZZZ"
How can i do that?
Sory for my bad english. Thanks.

As per my understanding, you want to read the values from your .txt file by giving its key. For that, you will have to write a function first that gets a key as a parameter and return the value:
private String GetValue(String key)
{
Boolean isValueFound = false;
String line = null;
//Open your file
using (StreamReader sr = new StreamReader("YourFile.txt"))
{
//Read it line-by-line
while ((line = sr.ReadLine()) != null)
{
//When the required line is found, set the flag and come out of the loop
if (line.Trim().StartsWith(key))
{
isValueFound = true;
break;
}
}
}
if (isValueFound)
{
//Split the line by using = as separator. So at index 0, you have the key and at index 1 you have the value
String[] strArray = line.Split('=');
//Trim the value before returning to get rid of extra spaces
return strArray[1].Trim();
}
else
{
//if value is not found, return null
return null;
}
}
Now you can call the above function like this:
//This line will give you 192.168.10.1
String result = this.GetValue("Cek Server IP");
//This line will return www.google.com
result = this.GetValue("Cek My Website");

For file I/O, the System.IO.File class has some useful methods, and for text files, the ReadLines method is probably what you want. You can then use String.Contains to check for the = character, and String.Split to separate the lines into key and value parts.
You could wrap this up into a class to read and parse your configuration file, and give you access to the specific values, e.g. (you will probably need some Imports and Option Infer On):
Public Class SettingsFile
Private ReadOnly _settings As IDictionary(Of String, String)
Private Sub New(settings As IDictionary(Of String, String))
_settings = settings
End Sub
Public Default ReadOnly Property Item(name As String) As String
Get
Dim value As String = Nothing
_settings.TryGetValue(name, value)
Return value
End Get
End Property
Public Shared Function Load(fileName As String) As SettingsFile
Dim settings = New Dictionary(Of String, String)()
For Each line In File.ReadLines(fileName).Where(Function(x) x.Contains("="))
Dim parts = line.Split("="c)
If parts.Count = 2 Then
settings(parts(0).Trim()) = parts(1).Trim()
End If
Next
Return New SettingsFile(settings)
End Function
End Class
You could then use this class in your code, e.g.:
Dim s = SettingsFile.Load("C:\Path\To\Settings.txt")
Dim s1 = s("Cek Server IP") ' 192.168.10.1
Dim s2 = s("Cek My Website") ' www.google.com
Dim s3 = s("Bad Key") ' Nothing

Related

RS.exe subscribe report with parameters

I am trying to create dynamic report subscriptions through rs.exe. How ever I cannot get the parameters to work. The enddate value is data/time, so I think that might be causing it, but I do not know what to do about it. I have tried casting, but the error msg. stays the same.
rs.exe call:
C:\Program Files (x86)\Microsoft SQL Server\130\Tools\Binn>rs.exe -i C:\Users\me\Desktop\rss_gen\subs.rss -s "localhost/ReportserverT"
subs.rss file:
Public Sub Main()
rs.Credentials = System.Net.CredentialCache.DefaultCredentials
Dim desc As String = "Report description"
Dim eventType As String = "TimedSubscription"
Dim scheduleXml As String = "<ScheduleDefinition><StartDateTime>2017-12-08T15:00:00</StartDateTime><WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Thursday>True</Thursday></DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>"
Dim parameters() As ParameterValue
' If you need setup parameters
Dim parameter As ParameterValue
parameter.Name = "enddate"
parameter.Value = "2017-12-30 10:03:01.250" 'this is date/time
parameters(0) = parameter
Dim matchData As String = scheduleXml
Dim returnValue As String
Dim reports() As String = { _
"/My Folder/report"}
For Each report As String In reports
returnValue = rs.CreateSubscription(report, parameters)
Console.WriteLine(returnValue)
Next
End Sub 'Main`enter code here`
Error msg:
C:\Users\mee\AppData\Local\Temp\11\dhexge0m.1.vb(43) : error BC30455:
Argument n ot specified for parameter 'Parameters' of 'Public Function
CreateSubscription(R eport As String, ExtensionSettings As
Microsoft.SqlServer.ReportingServices2005. ExtensionSettings,
Description As String, EventType As String, MatchData As Stri ng,
Parameters() As
Microsoft.SqlServer.ReportingServices2005.ParameterValue) As String'.
Let me teach you a trick to program in .Net and in general. It sounds simple, all you need to do is pass functions what they expect. Let me give you a simple example.
With this code I've got a similar error to you:
CS7036 There is no argument given that corresponds to the required formal parameter 'fileName' of 'FileInfo.FileInfo(string)'
The squiggle red line tells you where the problem is. If I type the opening bracket it will give me a tooltip with what it expects:
Ok it needs a string, so I declare a string and give it to the function as it expects:
So the problem you have is because you are not giving the CreateSubscription function the parameters it expects.
Argument not specified for parameter 'Parameters' of 'Public Function CreateSubscription
To fix it provide all the mandatory parameters to the ReportingService2005.CreateSubscription Method:
public static void Main()
{
ReportingService2005 rs = new ReportingService2005();
rs.Credentials = System.Net.CredentialCache.DefaultCredentials;
string report = "/SampleReports/Employee Sales Summary";
string desc = "Send email to anyone#microsoft.com";
string eventType = "TimedSubscription";
string scheduleXml = #"<ScheduleDefinition><StartDateTime>2003-02-24T09:00:00-08:00</StartDateTime><WeeklyRecurrence><WeeksInterval>1</WeeksInterval><DaysOfWeek><Monday>True</Monday></DaysOfWeek></WeeklyRecurrence></ScheduleDefinition>";
ParameterValue[] extensionParams = new ParameterValue[8];
extensionParams[0] = new ParameterValue();
extensionParams[0].Name = "TO";
extensionParams[0].Value = "dank#adventure-works.com";
extensionParams[1] = new ParameterValue();
extensionParams[1].Name = "ReplyTo";
extensionParams[1].Value = "reporting#adventure-works.com";
ParameterValue parameter = new ParameterValue();
parameter.Name = "EmpID";
parameter.Value = "38";
ParameterValue[] parameters = new ParameterValue[1];
parameters[0] = parameter;
string matchData = scheduleXml;
ExtensionSettings extSettings = new ExtensionSettings();
extSettings.ParameterValues = extensionParams;
extSettings.Extension = "Report Server Email";
try
{
rs.CreateSubscription(report, extSettings, desc, eventType, matchData, parameters);
}
catch (SoapException e)
{
Console.WriteLine(e.Detail.InnerXml.ToString());
}
}
As part of the 2005 report service for ms SQL, none of the parameters passed to CreateSubscription are optional. Please refer to the link and update the way you are calling the function. The error is clear, you are missing the parameters which is the last one. Look at the bottom of the page for an example.
https://technet.microsoft.com/en-us/library/microsoft.wssux.reportingserviceswebservice.rsmanagementservice2005.reportingservice2005.createsubscription(v=sql.90).aspx

Set statement, return empty string if error

From the following link there is an example at the bottom of the page which I have recreated in vb.net.
Before the following function runs, I save some data from a textfile into a dictionary called T.
For example:
Name - T0962
Value - 5.89
Public Shared Function initialization()
'Variables initialization
Dim parts As New List(Of Intialization)
'Add parts to the list.
parts.Add(New Intialization() With {
.PartName = "T0962",
.PartId = T.Item(.PartName))
})
If parts.Exists(Function(p) p.PartName = "T0962") Then
Dim value = parts.Where(Function(p) p.PartName = variable_type).FirstOrDefault()
Msgbox(value.PartId)
End If
End Function
The program works perfectly when I have "T0962" variable. When that variable does not exist in the textfile, it does not exist in the dictionary aswell. Thus, I get an error in the code, because the .PartId fails to be initialized. This is because in that textfile sometimes I have that value sometimes I do not.
After I have analized carefully I have noticed that the error happens in the Property statement, at Set(value As String) to be more exactly.
Public Property PartId() As String
Get
Return m_PartId
End Get
'here the error happens
Set(value As String)
m_PartId = value
End Set
End Property
Is there a way to avoid this in the Set statement? For example when there is an error then return an empty string?
Please let me know if there is something you do not understand.
Ok. Try Below. It works for me.
Dim partName As String
partName = "T0962"
parts.Add(New Intialization() With {
.PartName = partName,
.PartId = T.FirstOrDefault(Function(f) f.Key = partName).Value
})

How to I fix my deserialize error?

Why, hello everyone!
I've got this program i've been working on for months. Basic back story of it is, its supposed to be able to transport and install applications for windows in the background, like iCloud does for apps!
Anywho, i'm using a serialize/deserialize method to save the properties (eg admin username and passwordhash, directories, ports, etc.).
I have a class called 'PropertyNest' representing the properties and links to memory allocations. I'll cut it down to only the parts that the XMLSerializer looks at and saves.
Public Class PropertyNest
'Huge bunch of functions that we dont need to look at
'#######################
Public _wasLoadedFromFile As Boolean = False
Private _port As Integer = 201
Private _httpPort As Integer = 202
Private _rootFolder As String = "\appstreamRoot"
Private _adminUser As String = "Admin"
Private _adminPass As String = "21232F297A57A5A743894A0E4A801FC3" 'admin
Private _appstreamServerType As appStreamServerType = appStreamServerType.http
Private _useDES3forserver As Boolean = True
Private _encDES3pswd As String = "21232F297A57A5A743894A0E4A801FC3" 'admin
'Properties and descriptors for 'PropertyGrid' object go here \|/
'=================================================================
End Class
And its declared in the main window, serverMain like this,
Public Shared Property_Nest As AdvancedSettings.PropertyNest
and initialized later in like this,
If settingsfilename = "" Then
Property_Nest = New AdvancedSettings.PropertyNest()
Else
If propFileEncrypted = False Then
WriteLog("From unprotected file...", False)
Try
Property_Nest = AdvancedSettings.PropertyNest.LoadFrom(settingsfilename)
Catch ex As Exception
WriteLog("FAILED! Making default property nest...")
Property_Nest = New AdvancedSettings.PropertyNest()
End Try
Else
WriteLog("From encrypted file...", False)
Try
Property_Nest = AdvancedSettings.PropertyNest.LoadFrom(settingsfilename, True, propFilePswd)
Catch ex As Exception
WriteLog("FAILED! Making default property nest...", False)
Property_Nest = New AdvancedSettings.PropertyNest()
End Try
End If
End If
Thats all well and good. Loading it from the file that its saved to is the problem. Inside the PropertyNest class, I have 2 serializers programmed like so:
(Sorry its a bunch, there's optional encrypting of the serialized products with TrippleDES)
Public Sub SaveAs(ByVal filename As String, Optional ByVal Encrypted As Boolean = False)
Dim extra As String
If Encrypted = True Then : extra = "Encrypted? : Yes." : Else : extra = "Encrypted? : No."
End If
If filename = Nothing Then
Exit Sub
End If
writeLog2("Saving Property Nest to: " & filename & vbCrLf & extra, False)
If Encrypted = False Then
Dim writer As New Xml.Serialization.XmlSerializer(GetType(PropertyNest))
Dim file As New System.IO.StreamWriter(filename)
writer.Serialize(file, Me)
file.Close()
Else
Dim writer As New Xml.Serialization.XmlSerializer(GetType(PropertyNest))
Dim memstream As New System.IO.MemoryStream
writer.Serialize(memstream, Me)
memstream.Seek(0, IO.SeekOrigin.Begin)
Dim file As New System.IO.StreamWriter(filename)
Dim memstreamReader As New System.IO.StreamReader(memstream)
Do
file.WriteLine(serverMain.admin_des3Manager.Encrypt(memstreamReader.ReadLine()))
Loop Until memstreamReader.EndOfStream = True
file.Close()
End If
writeLog2("OK!")
End Sub
Shared Function LoadFrom(ByVal filename As String, Optional ByVal EncryptedWithPswd As Boolean = False, Optional ByVal Password As String = "") As PropertyNest
Dim reader As New Xml.Serialization.XmlSerializer(GetType(PropertyNest))
Dim file As New System.IO.StreamReader(filename)
Dim newPropNest As PropertyNest
If EncryptedWithPswd = False Then
newPropNest = reader.Deserialize(file) 'Error in XML Document(11, 3)
Else
If Password = "" Then
Dim convertedStream As New System.IO.MemoryStream
Dim convertedWriter As New System.IO.StreamWriter(convertedStream)
Do
convertedWriter.WriteLine(serverMain.admin_des3Manager.Decrypt(file.ReadLine()))
Loop Until file.EndOfStream = True
convertedWriter.Close()
newPropNest = reader.Deserialize(convertedStream)
Else
Dim tempDES3 As New DES3(Password)
Dim convertedStream As New System.IO.MemoryStream
Dim convertedWriter As New System.IO.StreamWriter(convertedStream)
Do
convertedWriter.WriteLine(tempDES3.Decrypt(file.ReadLine()))
Loop Until file.EndOfStream = True
convertedWriter.Close()
newPropNest = reader.Deserialize(convertedStream)
End If
End If
Return newPropNest
End Function
I marked the error in there.
Phew. Almost done.
i'm only worried about unencrypted right now, so i did my duty to save a custom, non default property nest, and it wrote to the file like so:
<?xml version="1.0" encoding="utf-8"?>
<PropertyNest xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance">
<_wasLoadedFromFile>false</_wasLoadedFromFile>
<ServerPort>2010</ServerPort>
<AdminUser>Matthew</AdminUser>
<AdminPasswordHash>21232F297A57A5A743894A0E4A801FC3</AdminPasswordHash>
<AppStreamPort>2020</AppStreamPort>
<AppStream_ServerRoot>\appstreamRoot</AppStream_ServerRoot>
<UseDES3>true</UseDES3>
<EncDES3Pswd>21232F297A57A5A743894A0E4A801FC3</EncDES3Pswd>
</PropertyNest>
Awesome! now.... If you look at the 'LoadFrom' function, you'll see i commented the line where i get the error... I dont see an error at 11, 3. Please help!
Thanks so much :D
Your XML is valid, however the class you need to deserialise, should be like this according to visual studio, copy you XML to the clipboard, go to the edit menu, paste special and past XML as classes give you this, give it a try see if it works, you can use a c# to vb converter to change to VB if you need to.
/// <remarks/>
[System.Xml.Serialization.XmlTypeAttribute(AnonymousType = true)]
[System.Xml.Serialization.XmlRootAttribute(Namespace = "", IsNullable = false)]
public partial class PropertyNest
{
private bool _wasLoadedFromFileField;
private ushort serverPortField;
private string adminUserField;
private string adminPasswordHashField;
private ushort appStreamPortField;
private string appStream_ServerRootField;
private bool useDES3Field;
private string encDES3PswdField;
/// <remarks/>
public bool _wasLoadedFromFile
{
get
{
return this._wasLoadedFromFileField;
}
set
{
this._wasLoadedFromFileField = value;
}
}
/// <remarks/>
public ushort ServerPort
{
get
{
return this.serverPortField;
}
set
{
this.serverPortField = value;
}
}
/// <remarks/>
public string AdminUser
{
get
{
return this.adminUserField;
}
set
{
this.adminUserField = value;
}
}
/// <remarks/>
public string AdminPasswordHash
{
get
{
return this.adminPasswordHashField;
}
set
{
this.adminPasswordHashField = value;
}
}
/// <remarks/>
public ushort AppStreamPort
{
get
{
return this.appStreamPortField;
}
set
{
this.appStreamPortField = value;
}
}
/// <remarks/>
public string AppStream_ServerRoot
{
get
{
return this.appStream_ServerRootField;
}
set
{
this.appStream_ServerRootField = value;
}
}
/// <remarks/>
public bool UseDES3
{
get
{
return this.useDES3Field;
}
set
{
this.useDES3Field = value;
}
}
/// <remarks/>
public string EncDES3Pswd
{
get
{
return this.encDES3PswdField;
}
set
{
this.encDES3PswdField = value;
}
}
}

How to Search for a specific record in a .dat file by a keyword

So i have a listbox which displays the contents of a .dat file.
Each record in the file has name,time,location and description.
On my form there is a search button which when clicked, I would like the user to be able to type in a name to check if that particular record exists. If it does, I would like a msgbox to show the entire record in the order I mentioned earlier. On the other hand if not I want a msgbox to display saying record cannot be found.
Assuming a tab delimited file with carrage return between records with the first field being the field you are searching (Edited to me more complete and better match the question):
Public Class Form1
Public Function FindRecord(name As String, path As String) As Record
Using reader As New IO.StreamReader(path)
Do While Not reader.EndOfStream
Dim line As String = reader.ReadLine
Dim record As Record = record.FromLine(line)
If record.Name = name Then
Return record
End If
Loop
End Using
Return Nothing
End Function
Public Class Record
Public Property Name As String
Public Property Time As Date
Public Property Location As String
Public Property Description As String
Public Shared Function FromLine(line As String) As Record
Dim record As Record = Nothing
Dim fields() As String = line.Split(ControlChars.Tab)
If fields.Length = 4 Then
record = New Record
record.Name = fields(0)
record.Time = Date.Parse(fields(1))
record.Location = fields(2)
record.Description = (3)
Else
Throw New FormatException("Line is not in the correct format.")
End If
Return record
End Function
End Class
End Class

Converting Fixed length statement from VB6 to VB.Net

We perform a protocol based data sending to device where the device requires a formatted data packets.
the sample packet data is XXFSXXXFSXXXXXXXFSXXXXXX. The X mentioned is the max length size of each string. if data is less than string max length it should be filled with NULL character like ..11FS123FS1234XXXX (the remaining X will be filled with NULL).
I am just trying to convert one of VB6 function to VB.Net and below is the converted statement where i am facing issue
Option Strict Off
Option Explicit On
Imports Microsoft.VisualBasic.Compatibility.VB6
Imports System
Imports System.Runtime.InteropServices
Module FunctionCmd_Msg
Public FunCommand_Msg As Fun_CommandMessage = Fun_CommandMessage.CreateInstance()
'Function Command Message
<StructLayout(LayoutKind.Sequential, CharSet:=CharSet.Auto)> _ _
Public Structure Fun_CommandMessage
<VBFixedString(1)> Public one As String
<VBFixedString(1)> Public two As String
<VBFixedString(3)> Public three As String
Dim five As String
<VBFixedString(8)> Public four As String
Public Shared Function CreateInstance() As Fun_CommandMessage
Dim result As New Fun_CommandMessage
result.one = String.Empty
result.two = String.Empty
result.three = String.Empty
result.four = String.Empty
result.five = String.Empty
End Function
End Structure
End Module
assuming:
one = "1"
two = "1"
three = "123"
four = "5678"
five = "testing"
FS = character (field separator)
on concatenating the strings i need a fixed length string such like this:
one & two & FS & three & FS & five & FS & four
output: since four is a fixed length string of 8 length remaining 4 characters should be filled with null as below
11 FS 123 FS testing FS 5678XXXX
Fixed-length strings simply make no sense in .NET any more. Microsoft tried to provide a similar class for easier upgrade but the truth is that you should change your code depending on usage:
What did the fixed-length string do in your VB6 code? Was it for no good reason? Then use a normal String in .NET.
Was it for interop with a C API? Then use marshalling to set a size for an array in the C API call.
Just forget about the fixed length, and use regular vb.net strings. They will return fine to whatever calls that code, including interop.
So, just pad your strings, and you off to the races.
In fact, build a Msg class that does the dirty work for you.
This looks quite nice to me:
NOTE how I set this up that you ONLY define the length of the string in ONE place. (so I use len(m_string) to determine the length from THEN on in the code.
Also, for debug and this example, in place of vbcharNull (which you should use), I used X for testing.
Now, in your code?
Just use this:
Dim Msg As New MyMsg
With Msg
.one = "A"
.two = "B"
.three = "C"
.four = "D"
.Five = "E"
End With
Debug.WriteLine(Msg.Msg("*") & vbCrLf)
Debug.WriteLine("total lenght = " & Len(Msg.Msg("X").ToString))
Output:
A*B*CXX*EXXXXXXX*DXXXXXXX
total lenght = 25
I note in your code that you have FIVE before FOUR - but if that is what you want, then no problem
Note that the class ALWAYS maintains the lengths for you.
So just paste this code into your module or even a new separate class.
Public Class MyMsg
'Dim cPad As Char = vbNullChar
Dim cPad As Char = "X"
Private m_one As String = New String(cPad, 1)
Private m_two As String = New String(cPad, 1)
Private m_three As String = New String(cPad, 3)
Private m_four As String = New String(cPad, 8)
Private m_five As String = New String(cPad, 8)
Public Property one As String
Get
Return m_one
End Get
Set(value As String)
m_one = MyPad(value, m_one)
End Set
End Property
Public Property two As String
Get
Return m_two
End Get
Set(value As String)
m_two = MyPad(value, m_two)
End Set
End Property
Public Property three As String
Get
Return m_three
End Get
Set(value As String)
m_three = MyPad(value, m_three)
End Set
End Property
Public Property four As String
Get
Return m_four
End Get
Set(value As String)
m_four = MyPad(value, m_four)
End Set
End Property
Public Property Five As String
Get
Return m_five
End Get
Set(value As String)
m_five = MyPad(value, m_five)
End Set
End Property
Public Function Msg(FS As String) As String
Return m_one & FS & m_two & FS & m_three & FS & m_five & FS & m_four
End Function
Private Function MyPad(str As String, strV As String) As String
Return Strings.Left(str & New String(Me.cPad, Len(strV)), Len(strV))
End Function
End Class
As noted, change the commented out line of "X" for the char back to vbCharNull.
And of course you STILL get to choose the delimiter. I used
Msg.Msg("*")
so I used a "*", but you can use space, or anything you want.