VB.NET/ASP.NET - Getting duration of MP3 file on upload - asp.net

I'm trying to upload an MP3 file to a site and finding the duration of the audio at the same time. I'm quite new to ASP and VB.NET, but I've managed to get the file to upload to the server using a file upload tool.
However I can't seem to figure out how to read the duration of the audio file?
I'm not particularly looking for a complete solution (although that would be nice), but if anyone could point me in the right direction I'd be very appreciative.
If you require any more information let me know and I'll add it to the question.

I've done this in a recent project using naudio (download using package manager). I've converted the code from c# quickly without testing so double check for errors.
private shared function GetMp3Duration(filename as string) as double
Dim duration as double = 0.0
using (fs as FileStream = File.OpenRead(filename))
Dim frame as Mp3Frame = Mp3Frame.LoadFromStream(fs)
while (frame isnot nothing)
if (frame.ChannelMode = ChannelMode.Mono) then
duration += frame.SampleCount / frame.SampleRate
else
duration += frame.SampleCount * 2.0 / frame.SampleRate
end if
frame = Mp3Frame.LoadFromStream(fs)
End While
End Using
return duration
End Function

I'm not convinced the "* 2.0" in the previous answer is appropriate. I tried this, and resulting duration was two times the actual, for a stereo mp3 sound sample. I suggest the following code, successfully tested in MSVS Community 2013:
Imports NAudio.Wave
'...
Private Shared Function GetMp3Duration(filename As String) As Double
Dim reader As New Mp3FileReader(filename)
Dim duration As Double = reader.TotalTime.TotalSeconds
reader.Dispose()
Return duration
End Function

hii add this code to trackbar timer dont forgot to add laber to player
Label4.Text = AxWindowsMediaPlayer1.Ctlcontrols.currentItem.durationString

Related

Need change compression of images stored in SQLite database with XOJO but getting error during process

I have a table that stores instruction book pages.
while working on the app and finished adding an instuction book, I found that that the table was over 200MB, however the PDF containing the pages was only 70MB 438 Pages.
The problem is that it saves the images as max quality. now i want to make a script that goes over every record opens the images and saves it again as medium compression.
I've made a record set and a loop to go through each record to change the compression, but but the app crashes half way the process.
No matter how i Change the code, it always crashes.
So i took an other approach and make a for loop of 200 records.
This wend well, but it didn't change the file size of the database???
The runtime error is an UnsupportedOperationException, as shown here:
This is the code:
dim rs as RecordSet
rs=lego.LegoData.SQLSelect("SELECT * FROM Books")
dim resize as Picture
while not rs.EOF
resize = picture.FromData(rs.Field("intructions").StringValue)
rs.Edit
rs.Field("intructions").StringValue = resize.GetData(Picture.FormatJPEG, Picture.QualityMedium)
rs.Update
rs.MoveNext
wend
Somehow it reads NIL after 200 records, but it's not NIL.
The error is not happening every time at the same record, it has its own will?
Any suggestions? I want to build-in a book image compression function as well so people can make the exported manual smaller.
The database file does not automatically get smaller if you remove or compact data inside it. You have to issue the VACCUM command (e.g. with SQLExecute("VACUUM")). You can issue that command only after committing, so first do a SQLExecute("COMMIT"). Or use a SQLite tool such as SQLVue to do that by hand.
If resize.GetData returns nil, it means that it can't read the data as JPEG. Maybe it's not in JPEG data but a GIF or something else. Try loading the data into a string first and look at it in the debugger, using the Binary (hex bytes) view to see what's up with it.
If you get an exception, wrap the code in an try block to keep the app from stopping, like this:
try
resize = picture.FromData(rs.Field("intructions").StringValue)
catch exc as RuntimeException
// The image could not be loaded - let's skip it
rs.MoveNext
continue
end try
I've found a solution to make the code faster, still having the crash
OutofMemorry exception
dim rs as RecordSet
dim pic as RecordSet
rs=lego.LegoData.SQLSelect("SELECT ID, SETID, Page FROM Books")
dim resize as Picture
dim count as Integer = 0
while not rs.EOF
pic = LegoData.SQLSelect("Select ID, Intructions FROM Books WHERE ID = " + Str(rs.Field("ID").IntegerValue))
if pic <> nil then
if len(pic.Field("intructions").StringValue) > 0 then
resize = picture.FromData(pic.Field("intructions").StringValue)
pic.Edit
pic.Field("intructions").StringValue = resize.GetData(Picture.FormatJPEG, Picture.QualityMedium)
pic.Update
if count = 100 then
LegoData.SQLExecute("COMMIT")
LegoData.SQLExecute("VACUUM")
count = 0
else
count = count + 1
end if
end if
end if
rs.MoveNext
wend
LegoData.SQLExecute("COMMIT")
LegoData.SQLExecute("VACUUM")
Before the crash its start updating my images with Nil
like 15 images before it crash

(asp.net) my sql-code (update statement) works in database but not in program

I wrote a program to easily store/edit my comic book collection. I can add, delete and request anything (comic/character/team) by my update statement doesn't work. I made a copy in a query in my access database and that worked perfectly. The strangest thing is that my program doesn't give any errors, it completes the transaction but doesn't change the data in my database. (this is a problem on both comic, character and team updates).
Here is my code to update a comic.
Public Sub UpdateComic(comic As Comic)
Dim cn As New OleDbConnection(persistenceController.connectiestring)
Dim cmd As New OleDbCommand("UPDATE tblComics SET serie = #serie, volume = #volume, issue = #issue, release = #release, inpossession = #inpossession, timesread = #read, story = #story, Languages = #languages WHERE ID = #ID", cn)
cmd.Parameters.AddWithValue("serie", comic.Serie)
cmd.Parameters.AddWithValue("volume", comic.Volume)
cmd.Parameters.AddWithValue("issue", comic.Issue)
cmd.Parameters.AddWithValue("release", comic.Release)
cmd.Parameters.AddWithValue("inpossession", comic.InPossession)
cmd.Parameters.AddWithValue("read", comic.Read)
cmd.Parameters.AddWithValue("story", comic.story)
cmd.Parameters.AddWithValue("ID", comic.ID)
cmd.Parameters.AddWithValue("Languages", comic.Language)
cn.Open()
cmd.ExecuteNonQuery()
cn.Close()
End Sub
Can anyone help me with this.
Thanks in advance.
Switch the position of the last two parameters added to the OleDbParameterCollection
cmd.Parameters.AddWithValue("Languages", comic.Language)
cmd.Parameters.AddWithValue("ID", comic.ID)
OleDb doesn't recognize the parameters by their name, but by their position. You should add the parameters in the exact order defined by the parameter placeholders in the command text
By the way. OleDb wants its placeholders parameter defined with the single question mark character (?), but MS-Access accepts also the syntax #name probably to have a better upgrade compatibility with its big cousin Sql Server.

Trying to read MIRC logs in ASP.net

I am trying to make a page that lets my admins read the MIRC Log files from our bot...I am having the hardest time trying to get this to work for some reason...i have taken bits and pieces of code to get what i have working...but it still either doesn't display at all OR after about 200 lines, it stops reading each line but instead make it one big mess of text...here is what i have for code
Protected Sub bView_Click(sender As Object, e As EventArgs) Handles bView.Click
Response.Write(Server.MapPath("~/mirc/logs/" & lbfiles.SelectedItem.Text))
lFileOut.Text = ""
Try
Dim FILENAME As String = Server.MapPath("~/mirc/logs/" & lbfiles.SelectedItem.Text)
Dim objStreamReader As StreamReader = New StreamReader(FILENAME, Encoding.UTF8)
Dim cont As String
Do
cont = objStreamReader.ReadLine()
lFileOut.Text = lFileOut.Text & cont & "<br>"
'Response.Write(cont)
Loop Until cont Is Nothing
Catch ex As Exception
Response.Write(ex.Message)
End Try
End Sub
Here is a test file i have been testing everything on...it just doesn't do anything nor does it throw any error...i am completely stumped on this one.
test file
Do this: go into your server, in your root folder make a new folder called whatever you want then go into your mIRC script goto tools/options/logging change directory to the new folder you made click save.. that way you or anyone you want to view all logs from your mIRC script can view by going to www.yoursite.net/foldername and it will show you the list of all logged things, status and room window conversations...
If you want to know how to code it so your opers can just have a clickable link in their remotes I can do that for you as well.... hope this helps

Running a series of VBScripts within an ASP.net (vb.net) page?

I have a requirement when a user clicks a specific arrangement of radio buttons to run a series of vbscripts (and soon Perl scripts).
I have all of the vbscripts stored server side, they do not need to be on the remote system to run. Oh yes, the scripts are gathering information on remote system in our intranet.
What would be the best way. Currently I have this to run just one script, not multiple...should I keep this or dispose of this idea.
Protected Sub windowsScript(ByVal COMPUTERNAME As String)
' Create an array to store VBScript results
Dim winVariables(1) As String
Dim filePath As String = COMPUTERNAME & "\C$\Windows\somefile.txt"
'Execute PsExec on script
runPsExec(COMPUTERNAME, "systemInfo.vbs", 1)
'Import data from text file into variables
textRead(filePath, winVariables)
System.Threading.Thread.Sleep(1000)
'Delete the file on server - we don't need it anymore
runPsExec(COMPUTERNAME, "systemInfo.vbs", 2)
MsgBox("Windows OS: " & winVariables(0).ToString())
MsgBox("Service Pack: " & winVariables(1).ToString())
End Sub
Also, it is hard to see here because I do have another function "textRead" but what is going on is this particular script is stored client side and the vbscript it outputting to a text file. textRead will read the variable and send a text file back to the server to read it.
This is definitely not what I want to do.
I want to be a little more dynamic, plus with my new scripts...they don't need to be on the client at all.
Any help would be appreciated :)
I'm thinking of making some type of While loop, not sure if that would work.
It's kind of strange to do this through the browser. In my company we collect systeminfo at logontime with a vbscript logonscript and add the result to a logfile which we can access through a webapp to do research. Occasionally when the need rises we run a specific script to gather more data or change some system setting through windows SCCM.
If the goal is to provide the user with info about his system there are some good utilities around which can be run locally (but from a location on a server share).
EDIT
a simple way to start multiple processes
dim scripts_to_run, script
const COMPUTERNAME = 0, SCRIPTNAME = 1, EXTRA_PARAMS = 2
scripts_to_run = Array(_
Array("computer1","script1.vbs",1),_
Array("computer2","script1.vbs",0),_
Array("computer3","script3.vbs",3)_
)
for each script in scripts_to_run
runPsExec script(COMPUTERNAME), script(SCRIPTNAME), script(EXTRA_PARAMS)
runPsExec join(script,",")
next
sub runPsExec(p1, p2, p3)
'here coms your code shat runs the script
wscript.echo p1 & p2 & p3
end sub
or a shorter version
dim scripts_to_run, aArgs
scripts_to_run = Array(_
Array("computer1","script1.vbs",1),_
Array("computer2","script1.vbs",0),_
Array("computer3","script3.vbs",3)_
)
for each aArgs in scripts_to_run
runPsExec aArgs
next
sub runPsExec(aArgs)
'here coms your code shat runs the script
wscript.echo aArgs(0) & aArgs(1) & aArgs(2)
end sub

How to optimize this code that read from xml file

We have ther following classic asp code that read from xml file, it shows a poor performance when there are more than 10 concurrent requests to that page , can someone figure out the performance problem in this code( we know one of the the problems which is using fileSystemObject but we do not have alternatives for it!):
set filesys=server.CreateObject("Scripting.FileSystemObject")
if filesys.FileExists(sourcefile) then
set source = Server.CreateObject("Msxml2.DOMDocument")
source.validateOnParse = false
source.resolveExternals = false
source.preserveWhiteSpace = false
source.load(sourcefile)
If source.ParseError.errorCode <> 0 Then
str_head=source.selectSingleNode("/LIST/ITEM/NEWSITEM/HEADLINE//").text
str_by=source.selectSingleNode("//LIST//ITEM//NEWSITEM//PROVIDER//").text
News_date_orig = source.selectSingleNode("/LIST/ITEM/NEWSITEM/CREATED//").text
str_date= formatdatetime(source.selectSingleNode("//LIST//ITEM//NEWSITEM//CREATED//").text,1)
set bodyNode=source.selectSingleNode("/LIST/ITEM/NEWSITEM//BODY//")
styleFile=Server.MapPath("/includes/xsl/template.xsl")
Set style = Server.CreateObject("Msxml2.DOMDocument")
style.validateOnParse = false
style.resolveExternals = false
style.preserveWhiteSpace = false
style.load(styleFile)
news_full = bodyNode.transformNode(style)
if len(news_full) < 10 then
news_full = str_abstract
end if
DiscriptionKeyWord = stripHTMLtags(news_full)
DiscriptionKeyWord=StrCutOff(DiscriptionKeyWord, 200, "...")
headerTitle=str_head
Set style=nothing
Set source = nothing
end if
set filesys= nothing
The following is stripHTMLtags function:
Function stripHTMLtags(HTMLstring)
Set RegularExpressionObject = New RegExp
With RegularExpressionObject
.Pattern = "<[^>]+>"
.IgnoreCase = True
.Global = True
End With
stripHTMLtags = RegularExpressionObject.Replace(HTMLstring, "")
Set RegularExpressionObject = nothing
End Function
UPDATE: I put a timer to show the execution time for the function that read xml file and found that it takes around 3 seconds on the production server while it takes less than 1 second on my PC! What does tht mean?! I'm lost.
Option Explicit
If your scripts don't begin with Option Explict then make that change now. Then fix all the compile errors that show up. Doesn't help performance but when I see evidence that this biggest of all scripting mistakes is being made it just needs mentioning.
FileSystemObject
I doubt the performance problem is a result of the FileSystemObject, all you are doing is creating an instance and testing for the existance of a file. That is hardly likely to cause a problem.
Having said that I would ditch the FileSystemObject anyway. Just let the script throw an error if there is a problem. Use IIS Manager to map 500.100 status codes to an ASP page that presents a friendly "Something bad happened" page to the user. (500.100 is the status of a request when the script throws an exception). Also test the boolean result of the DOM load method, throw an error when parse error is not 0 also. That way you hand over all the ugly exception handling to the 500.100 handling page and your code can remain clean just dealing with the nominal path of the code.
Tidy up the paths
Perhaps there is a reason why you are using "//" a lot in your paths (but inconsistently) but I'm going to assume there isn't so we can simplify some of the paths:
Dim newsItem: Set newsItem = source.selectSingleNode("/LIST/ITEM/NEWSITEM")
Dim str_head: str_head = newsItem .selectSingleNode("HEADLINE").text
Dim str_by: str_by = newsItem .selectSingleNode("PROVIDER").text
Dim News_date_orig: News_date_orig = newsItem .selectSingleNode("CREATED").text
Dim str_date: str_date = formatdatetime(News_date_orig, 1)
Dim bodyNode: Set bodyNode = newsItem.selectSingleNode("BODY")
Cache XSLTemplate
An area where you could gain some real perfomance improvement is to cache the XSL Transform in the application object (which is possible due to XSLTemplate being a free threaded object). Like this:
Dim xslTemplate
If IsObject(Application("xsl_template")) Then
Set xslTemplate = Application("xsl_template")
Else
Set style = Server.CreateObject("Msxml2.FreeThreadedDOMDocument.3.0")
style.async = false
style.validateOnParse = false
style.resolveExternals = false
style.preserveWhiteSpace = false
style.load Server.MapPath("/includes/xsl/template.xsl")
Set xslTemplate = CreateObject("MSXML2.XSLTemplate.3.0")
xslTemplate.stylesheet = xsl
Set Application("template") = xslTemplate
End If
Dim xslProc: Set xslProc = xslTemplate.createProcessor()
xslProc.input = bodyNode
xslProc.transform()
news_full = xslProc.output
The effort to read, parse and compile the XSL transform is only done once in the whole lifetime of the application.
The most likely culprit
To be honest I suspect the most likely culprit is stripHTMLtags. This sounds like a whole load of string handling and the performance of VBScript string handling is poor. Its especially poor when code is not properly optomised to be aware of the string handling performance limitations (e.g. excessive and repeative string concatenations). Its also likely to be where the most actual VBScript occurs which is often the cause of a performance problem.
You can load the XML into a string on application startup and store it in an Application object.
Then, instead of using source.load, use source.loadXML with this string - you will not be accessing the filesystem anymore. See the documentation for loadXML.
Make sure you use a version of MSXML 3.0 or over to use this method.
Server.CreateObject("Msxml2.DOMDocument.6.0")
Update - seeing as you have thousands of these files and you believe it is infeasible to store them in memory in the Application object, you should be using a database to handle the concurrency issues you are seeing. Store the contents of the files keyed to something like their current filename/path - retrieve them from the database and load to a document using the same loadXML mechanism.

Resources