writing csv adds extra lines - asp.net

I've to write a csv for a third-party upload. They're saying they can't read the csv file created because it has two extra lines of code and doesn't end (when opened in Notepad) on the last character of the last line. That's true - but can anyone tell me why?
Dim _csvLine As New System.IO.StreamWriter(Server.MapPath("~/folder/_" & rptType.SelectedItem.Value.ToString & ".csv"), False)
Dim tb As New StringBuilder
Dim x As Integer = ds.Tables("csv").Columns.Count, y As Integer = 1
For Each row As Data.DataRow In ds.Tables("csv").Rows
For Each col As Data.DataColumn In ds.Tables("csv").Columns
If y <> x Then
tb.Append(Trim(System.Text.RegularExpressions.Regex.Replace(row.Item(col).ToString, "\s+", " ", RegexOptions.IgnoreCase Or RegexOptions.Multiline)) & ",")
y = y + 1
Else
tb.Append(Trim(System.Text.RegularExpressions.Regex.Replace(row.Item(col).ToString, "\s+", " ", RegexOptions.IgnoreCase Or RegexOptions.Multiline)))
tb.AppendLine()
y = 1
End If
Next
Next
_csvLine.WriteLine(Left(tb.ToString, Len(tb.ToString) - 2))
_csvLine.Flush()
_csvLine.Close()
_csvLine.Dispose()

One line is appended by _csvLine.WriteLine, use Write() instead.
tb.AppendLine() adds the second line, try avoiding it on the last line.

You're doing _csvLine.WriteLine( which is gonna add a linebreak to the end of the file.

Related

How to get r to read 'date taken' of a JPG file

I could use some help performing a database correction, in regards to date and time of pictures were taken.
Essentially, the research we perform entails taking many pictures and entering the picture information into a database (we automated this with Microsoft Access). However, I performed a random check of our database and found that several dates and times of the photos were incorrect, and I am attempting to correct this via R as I was unable to correct it via Access.
What I need to do is to is write a script that reads these data, and compiles a list of the date taken information for all photos (there are several thousand). So far the best thing that I've found is
file.info(list.files(
"E:/Whatcom Creek Project/Data/Seal photos/Discovery/Catalog/Phoca vitulina",
recursive = T))
However this returns a list of NA NA for all information. Also, if I manually select one image to run file.info on, it doesn't return date taken (see the picture for the data I am attempting to retrieve)
If anyone has any suggestions I am all ears. Thanks in advance!!
-Ian
enter image description here
maybe still of any use?
i saw this message. I solved this a long time ago (2011) with a very basic VB6 code. The job is still working, but it is not applicable to all '.jpg files'. It depends with what camera the picture has been taken, but mostly pictures taken from a smartphone and classic camera's are returning the date the picture has been taken (not usable for whatsapp images or edited images).
The code is here below, and it is very basic code (but i hope it still can help or give idea's, and ... any new idea's are welcome too) :
'Reading of "Date Picture Taken" from .jpg file
'-----------------------------------------------
Debug.Print ">>>>>==== Start Read of .jpg-file ===== "; Date; " ===== "; Time; " ====<<<<<"
X = 0
DatePictureTaken = ""
TimePictureTaken = ""
FOUNDdatum = False
SWdatum = False
TELdatum = 0
Foto = FOLDER & "\" & tabFileName(FotoNr)
Open Foto For Binary Access Read As #1
'get startposition of the field "date picture taken"
Do
X = X + 1
Get #1, X, MyByte ': Debug.Print Chr(MyByte);
DoEvents
If Chr(MyByte) = ":" Then
'Debug.Print
SWdatum = True
Get #1, X + 3, MyByte
'Debug.Print "x+03="; Chr(MyByte)
If Chr(MyByte) <> ":" Then SWdatum = False 'Debug.Print "x+03="; Chr(MyByte)
Get #1, X + 9, MyByte
'Debug.Print "x+09="; Chr(MyByte)
If Chr(MyByte) <> ":" Then SWdatum = False 'Debug.Print "x+09="; Chr(MyByte)
Get #1, X + 12, MyByte
'Debug.Print "x+12="; Chr(MyByte)
If Chr(MyByte) <> ":" Then SWdatum = False 'Debug.Print "x+12="; Chr(MyByte)
'if a ':' is on the 3 locations (found above) then it is a date!
If SWdatum _
Then
TELdatum = TELdatum + 1
End If
'the 3e date is the date the picture has been taken
If TELdatum = 3 _
Then
FOUNDdatum = True
X = X - 4
Exit Do
End If
X = X + 12
End If
Loop Until EOF(1) 'Or X = 32765
If FOUNDdatum = False Then Close 1: End
BPdatum = X
EPdatum = X + 9
BPuur = X + 11
EPuur = X + 15
For X = BPdatum To EPdatum
Get #1, X, MyByte
'Debug.Print Chr(MyByte)
If Chr(MyByte) <> ":" _
Then
' DatePictureTaken = DatePictureTaken & "/"
'Else
DatePictureTaken = DatePictureTaken & Chr(MyByte)
End If
Next X
For X = BPuur To EPuur
Get #1, X, MyByte
'Debug.Print Chr(MyByte)
If Chr(MyByte) <> ":" _
Then
' DatePictureTaken = DatePictureTaken & "/"
'Else
TimePictureTaken = TimePictureTaken & Chr(MyByte)
End If
Next X
'Debug.Print "Date Picture Taken = "; DATUM
tbxDatum.Text = DatePictureTaken
tbxUur.Text = TimePictureTaken
Close 1
End Sub

Format datetime day with st, nd, rd, th

I'm creating a report in SSRS and across the top I have a header with a placeholder for "Last Refreshed" which will show when the report last ran.
My function in the placeholder is simply this:
=Format(Now, "dddd dd MMMM yyyy hh:mm tt")
Which looks like this:
Monday 22 September 2015 09:46 AM
I want to format the day value with the English suffix of st, nd, rd and th appropriately.
I can't find a built in function for this and the guides I've looked at so far seem to describe doing it on the SQL side with stored procedures which I don't want. I'm looking for a report side solution.
I thought I could get away with an ugly nested IIF that did it but it errors out despite not giving me any syntax errors (whitespace is just for readability).
=Format(Now, "dddd " +
IIF(DAY(Now) = "1", "1st",
IIF(DAY(Now) = "21","21st",
IIF(DAY(Now) = "31","31st",
IIF(DAY(Now) = "2","2nd",
IIF(DAY(Now) = "22","22nd",
IIF(DAY(Now) = "3","3rd",
IIF(DAY(Now) = "23","23rd",
DAY(Now) + "th")))))))
+ " MMMM yyyy hh:mm tt")
In any other language I would have nailed this ages ago, but SSRS is new to me and so I'm not sure about how to do even simple string manipulation. Frustrating!
Thanks for any help or pointers you can give me.
Edit: I've read about inserting VB code into the report which would solve my problem, but I must be going nuts because I can't see where to add it. The guides say to go into the Properties > Code section but I can't see that.
Go to layout view. Select Report Properties.Click on the "Code" tab and Enter this code
Public Function ConvertDate(ByVal mydate As DateTime) as string
Dim myday as integer
Dim strsuff As String
Dim mynewdate As String
'Default to th
strsuff = "th"
myday = DatePart("d", mydate)
If myday = 1 Or myday = 21 Or myday = 31 Then strsuff = "st"
If myday = 2 Or myday = 22 Then strsuff = "nd"
If myday = 3 Or myday = 23 Then strsuff = "rd"
mynewdate = CStr(DatePart("d", mydate)) + strsuff + " " + CStr(MonthName(DatePart("m", mydate))) + " " + CStr(DatePart("yyyy", mydate))
return mynewdate
End function
Add the following expression in the required field. I've used a parameter, but you might be referencing a data field?
=code.ConvertDate(Parameters!Date.Value)
Right Click on the Textbox, Go To Textbox Properties then, Click on Number tab, click on custom format option then click on fx button in black.
Write just one line of code will do your work in simpler way:
A form will open, copy the below text and paste there to need to change following text with your database date field.
Fields!FieldName.Value, "Dataset"
Replace FieldName with your Date Field
Replace Dataset with your Dateset Name
="d" + switch(int(Day((Fields!FieldName.Value, "Dataset"))) mod
10=1,"'st'",int(Day((Fields!FieldName.Value, "Dataset"))) mod 10 =
2,"'nd'",int(Day((Fields!FieldName.Value, "Dataset"))) mod 10 =
3,"'rd'",true,"'th'") + " MMMM, yyyy"
I found an easy way to do it. Please see example below;
= DAY(Globals!ExecutionTime) &
SWITCH(
DAY(Globals!ExecutionTime)= 1 OR DAY(Globals!ExecutionTime) = 21 OR DAY(Globals!ExecutionTime)=31, "st",
DAY(Globals!ExecutionTime)= 2 OR DAY(Globals!ExecutionTime) = 22 , "nd",
DAY(Globals!ExecutionTime)= 3 OR DAY(Globals!ExecutionTime) = 23 , "rd",
true, "th"
)

Highlight keywords in classic ASP

I have this sentense, "The man went outside".
I also have 4 search criterias I would like to get highligted (ignore the brackets), [went|"an WeNT o"|a|t] with [span id="something"][/span].
I have tried out a lot of stuff but I can't figure out how to do this in classic ASP!? If I insert a somewhere in the text, it will search the HTML code for SPAN too, which is bad or it will not find the text as it has been messed up with HTML code. I also tried inserting on all positions in the original text and even with some magic regular expression which I do not understand but I can't get this working :-/
The search-thing is divided with | and can be anything from 1 to 20 things to search for.
Can anyone help me solving how to do this?
I found and tweaked some code and it works perfectly for me:
Function highlightStr (haystack, needles)
' Taken (and tweaked) from these two sites:
' http://forums.aspfree.com/asp-development-5/asp-highlight-keywords-295641.html
' http://www.eggheadcafe.com/forumarchives/scriptingVisualBasicscript/Jul2005/post23377133.asp
'
' INPUT: haystack = search in this string
' INPUT: needles = searches divided by |... example: this|"is a"|search
' OUTPUT: HTML formatted highlighted string
'
If Len(haystack) > 0 Then
' Delete the first and the last array separator "|" (if any)
If Left(needles,1) = "|" Then needles = Right(needles,Len(needles)-1)
If Right(needles,1) = "|" Then needles = Mid(needles,1,Len(needles)-1)
' Delete a multiple seperator (if any)
needles = Replace(needles,"||","|")
' Delete the exact-search chars (if any)
needles = Replace(needles,"""","")
' Escape all special regular expression chars
needles = Replace(needles,"(","\(")
needles = Replace(needles,")","\)")
needles = Replace(needles,".","\.")
If Len(needles) > 0 Then
haystack = " " & haystack & " "
Set re = New RegExp
re.Pattern = "(" & needles & ")"
re.IgnoreCase = True
re.Global = True
highlightStr = re.Replace(haystack,"<span style='background-color:khaki;'>$&</span>")
Else
highlightStr = haystack
End If
Else
highlightStr = haystack
End If
End Function

Generate Conditional Code From String

I want to generate conditional code of the string, which will check the string. An example is the following string
sampleString = "C123 A091 A111 A122 B120 B309 C000"
and examples of conditional string I have is as follows
example 1 :
A123 + B123 would I generate as
if sampleString.contains ("A123") And sampleString.contains ("B123") Then
'doSomething
else
'doSomething
end if
example 2 :
A111+A122+(B120/-C123)
if sampleString.contains ("A111") And sampleString.contains ("A122") And (sampleString.contains ("B120") Or Not sampleString.contains ("C123")) Then
'doSomething
else
'doSomething
end if
Plus (+) means AND
Minus (-) means NOT
Slash (/) means OR
Will I be able to do this in VB.Net?
Use Regex to solve the Contains problem by finding the matches and replace them with 1 or 0.
Dim sample As String = "C123 A091 A111 A122 B120 B309 C000"
Dim input As String = "A111 + A122 + ( B120/- C123)"
Dim nRegex As New Regex("\w+", RegexOptions.IgnoreCase)
Dim nMatches As MatchCollection = nRegex.Matches(input)
For Each nMatch As Match In nMatches
input = input.Replace(nMatch.Value, IIf(sample.Contains(nMatch.Value), "1", "0"))
Next
Now replace the special characters you have with ones that can actually give you the right result when evaluated as a math expression (Since logic is originally math).
input = input.Replace(" ", "")
input = input.Replace("+", "*")
input = input.Replace("/", "+")
input = input.Replace("-1", "0").Replace("-0", "1")
after all this you will get this expression :
1*1*(1+0)
You can now use any math evaluator as suggested in this Answer. If the result you get is bigger than zero means Its logically True. Otherwise False

check if a string's first 16 char is a number

I'm storing some files in database which has filename like 1839341255115211butterflies.jpg.I need to show this filename to the user as butterflies.jpg.I need to remove the first 16 digit and then show the filename.Added to it I also have few filenames which don't have this 16digit addition prior to the filename.Now my question is how do I identify if this string has 16digit numeric value prior to the filename, based on it remove the 1st 16digit and display just the filename. I'm aware of how to remove the first 16digit and retrive the filename but need help on how to identify a string that has 16digit.
Any suggestion is much appreciated.
A regular expression looks like a good fit here:
^[0-9]{16}
The above will match on strings that start with 16 digits (0 to 9).
Usage:
if(Regex.Match(fileName, #"^[0-9]{16}").Success)
{
fileName = fileName.Remove(0, 16);
}
string.Remove will work quite nicely:
var str = "1839341255115211butterflies.jpg";
str = str.Remove(0, 16);
Console.WriteLine(str);
With Linq:
remove all digits at the beginning until 16 digits:
string file = "1839341255115211butterflies.jpg";
string extension = Path.GetExtension(file);
string fileName = Path.GetFileNameWithoutExtension(file);
fileName = new string(fileName.Where((c, i) => i >= 17 || !Char.IsDigit(c)).ToArray());
file = fileName + extension;
Demo
Edit: If you just want to know if the first 16 chars are digits, it's easier and more readable:
bool startsWith16Digits = file.Take(16).All(Char.IsDigit);

Resources