How to append Text at the begining of a file? - vb.net

I'm using the command IO.File.AppendAllLines("3.txt", "text", System.Text.Encoding.Default)
to write to 3.txt.
But the string is writing in down.
How I can write a string upper?

Call the strings ToUpper method to make the string upper case
IO.File.AppendAllLines("3.txt", "text".ToUpper(), System.Text.Encoding.Default)

The .Append() method will always append(add) the given string to an existing content. so n this case you cannot do like this.
I suggest you to read the content first, write the content back to the file along with the additional string. If you are expecting this, then the following code will help you:
var currentContent= File.ReadAllText(#"D:\3.txt");
File.WriteAllText(#"D:\3.txt", "Some string" + currentContent);
// here you are adding "Some string" at the begining of the file

Related

Parse string into JSON

I have an array of objects $arr and an object has a property named as jsonData which contains json data in a string, how to parse that string to actual JSON object and retrieve lets say value for key name? I tried this:
#foreach ($obj in $arr)
#set ($jsonData = "#evaluate(${obj.jsonData})")
$jsonData.get("name") ## <-- not working
#end
If anyone using velocity in AWS API Gateway ends up here, you can use AWS'
$util.parseJson() to covert a string to JSON.
Make sure you note if your string is using single or double quotes. You may need to use $util.escapeJavaScipt.replaceAll() before parsing the string.
Fixed it like this:
#foreach ($obj in $arr)
#set( $jsonData = '#set( $jsonData = ' + $obj.jsonData + ' )' )
#evaluate ($jsonData)
$jsonData.get("name") ##<-- works now
#end
I was using velocity 1.7
This is mainly AWS lambda (in python) response template related.. so.. if you want to return custom response code with json it is easy to return JSON in node js but when it comes to python as per i know, we cant raise dict as a value. So.. this may help. If you are doing like..
raise Exception({"responseCode": 400, "response": "missing :\"recipientCount\""})
It will throw exception in errorMessage key and value as a string.
To overcome this..
Add response code 400 in Method Response
regExp in Integration Response :
.*'responseCode': 400.*
Add Body Mapping Template as application/json:
$util.escapeJavaScript( $input.path('$.errorMessage')).replaceAll("\\'",'\"')
Make sure you are not using single quotes in value in exception string.
Wrong:
raise Exception({"responseCode": 400, "response": "missing :'recipientCount'"})
Right:
raise Exception({"responseCode": 400, "response": "missing :\"recipientCount\""})
I know it is not best solution... but this is the only solution i have found. Feel free if you have better solution.

VisualBasic - View object in the listbox in ListView

I decided to program a simple application. And I need advice. I must point out that I'm a complete beginner, yesterday I started with VB ...
I have a listbox:
Code:
listUzivatelu.Items.Clear ()
listUzivatelu.Items.AddRange (databaze.VratVsechny ())
And I needed it to appear in the ListView:
Code:
Dim TempStr (1) As String
TempStr (0) = "1111"
TempStr (1) = "Doe, John"
ListView1.Items.Add (New ListViewItem (TempStr))
But when I write databaze.VratVsechny () so it just throws an error.
databaze.VratVsechny() returns:
Code:
Public Function VratVsechny () As Product ()
Return Vyrobek.ToArray ()
end Function
I'm attach source code: https://www.dropbox.com/s/btg5c66wvafo8qj/csv-zapis-a-cteni-objektu.zip
Thanks in advance for any advice on the topic.
I tried to run your project, the only problem appeared when executing this line:
databaze.Nacti()
And after digging to the method, I found that error caused by parsing "invalid" string to DateTime. Date strings in csv file appear in date.month.year format, when I edited csv to use month.date.year it parsed successfully and the program run with no error. Another alternative is to use ParseExact instead of Parse method. For Example:
Dim registrovan = DateTime.ParseExact(rozdeleno(2), "d", CultureInfo.CreateSpecificCulture("ru-RU"))
That will successfully parse your current date string in csv, because date format in Russian culture is dd.mm.yy.

How do you remove this text in vb net?

Whenever I use streamwriter to put a textbox value into a .txt file it goes like this:
System.Windows.Forms.TextBox, Text: dadadadaad what is wrong here?
Dim Na_1 As New IO.StreamWriter(folder & "\name.txt")
Na_1.WriteLine(TextName)
Na_1.Close()
You have flush the StreamWriter before you close it:
Na_1.Flush()
Clears all buffers for the current writer and causes any buffered data to be written to the underlying stream.
Source: MSDN
So this should be your code:
Na_1 As New IO.StreamWriter(folder & "\name.txt")
Na_1.WriteLine(TextName)
Na_1.Flush()
Na_1.Close()
Alternatively you can use the Using-statement which automatically flushes and closes the stream (this is the better practice):
Using Na_1 As New IO.StreamWriter(folder & "\name.txt")
Na_1.WriteLine(TextName)
End Using
Following the comments of Ric and ForkAndBeard I think I misunderstood the problem:
Your problem is that you are calling the TextNameobject of the TextBox-Class directly via Na_1.WriteLine(TextName).
Now since you can't write an object to a file, the runtime simply call the ToString()-method of the Class TextBox which inherits from Object.
The result will be following:
"System.Windows.Forms.TextBox, Text: "
or generally:
"YourNamespace.YourClass"
Source:MSDN
If you want to have the text of the TextBox, you have to call the property TextBox.Text of the object:
Na_1.WriteLine(TextName.Text);

convert vb.net data to json string and send it to a specific URL

this is the JSON string the data is required in to be sent using a given URL.
$jsonstr = '{"data":
[{
"id":"5",
"owner_id":"0",
"status":"unassigned",
"first_name":"Test",
"last_name":"IS",
"tobacco_user":"",
"date_of_birth":"",
"age":"",
"gender":"",
"email":"lb#you.com",
"zip":"",
"phone":"(210)629-2560",
"phone_type":"cell",
"phone_alt":"",
"phone_alt_type":"",
"product_msip":"",
"product_pdp":"",
"product_sdhv":""
},
I am using VB.net and i need to create this string using VB.net. I tried using namevaluecollection and doing a POST. I also tried making a string and send data using GET. Both failed. how can i do this?
Create an object with property names that are identical to those in your example, use the DataContract and DataMember attributes to mark serialization.
Then use the JavaScriptSerializer to serialize the object into JSON.
you can use the class when you want to work with JavaScript Object Notation (JSON) in managed code.
If you don't want to build an actual class as #Oded recommended you can just hack it together as a string. I usually use a NameValueCollection as you said you tried.
''//Setup some values
Dim NVC As New NameValueCollection()
NVC.Add("id", "5")
NVC.Add("owner_id", "0")
NVC.Add("status", "unassigned")
''//Convert to string
Dim Pairs As New List(Of String)
For Each N As String In NVC.Keys
Pairs.Add(String.Format("""{0}"":""{1}""", N.Replace("""", "\"""), NVC(N).Replace("""", "\""")))
Next
Dim S = Join(Pairs.ToArray(), ",")
S now holds "id":"5","owner_id":"0","status":"unassigned" which you should be able to concat into your bigger JSON string.

Special character into querystring .NET

I need to send the follow querystring:
http://prod.intranet.siemens.com.br/drvs/index.aspx?page=2&pag=4&varpatch=%20C:\Documents%20and%20Settings\OPE253\My%20Documents\Ca$##!
Then i try to assing this to a string,but .NET break string at
http://prod.intranet.siemens.com.br/drvs/index.aspx?page=2&pag=4&varpatch=%20C:\Documents%20and%20Settings\OPE253\My%20Documents\Ca$#
'#" do not appears in querystring
Any ideas?
No, because "#" is a reserved character. It's used to link to a specific location in a web page:
http://en.wikipedia.org/wiki/HTML_anchor#Overview
So browsers split the URL at the "#".
You'll need to encode the "#" as "%23"
You need to use String.Replace:
Dim outputURL As String = inputURL.Replace("#", "%23")
or HttpUtility.UrlEncode (only encode the querystring):
Dim outputQueryString As String = HttpUtility.UrlEncode(inputQueryString)