Get Thumbnail from Video file in ASP.NET - asp.net

I am trying to get thumbnail from video file and my code run successfully but thumbnail is not saved here is my code..
protected void Convert(string fileIn, string fileOut, string thumbOut)
{
try
{
System.Diagnostics.Process ffmpeg;
string video;
string thumb;
video = Server.MapPath("~/Content/UploadVedio/YouTube.FLV");
thumb = Server.MapPath("~/Content/UploadImage/frame.jpg");
ffmpeg = new System.Diagnostics.Process();
ffmpeg.StartInfo.Arguments = " -i " + video + " -ss 00:00:07 -vframes 1 -f image2 -vcodec mjpeg " + thumb;
ffmpeg.StartInfo.FileName = Server.MapPath("~/Content/EXE/ffmpeg.exe");
ffmpeg.Start();
ffmpeg.WaitForExit();
ffmpeg.Close();
}
catch (Exception ex)
{
Response.Write("Error: " + ex.Message);
}
}

Your code are running in IIS, make sure you have write right to the proper folder

Things to check :
Is the directory contain space(s)? If so, please add :
video = "\"" + video + "\"";
thumb = "\"" + thumb + "\"";
Is ffmpeg.exe path is correct? If you want to set up environment variable for ffmpeg, go here so you do not need locate where ffmpeg.exe path to run ffmpeg.
i.e. your argument : -ss 00:00:07. Is the video length longer than 7 second?
Copy ffmpeg.exe to drive C (if you do not set path for ffmpeg) and Try to run directly at cmd, and post here what is the output if any error(s) occured? i.e:
c:\ffmpeg.exe -i "c:\video.mp4" -ss 00:00:07 -vframes 1 -f image2 -vcodec mjpeg "c:\result.jpg"

Related

Execute .jar file in .net core on Openshift container platform

net core application which internally calls a java (.jar) file using .net Process class. I have used cmd.exe to run .jar file along with parameters. I have deployed this application on Openshift Container Platform. But as openshift is running on Linux, so cmd.exe is not available.
Below is code in .net core to execute jar file.
Process cmd = new Process();
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = Common.JarWorkingDir;
cmd.StartInfo.FileName = "cmd.exe";
cmd.StartInfo.Arguments = "/K java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"');
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start();
cmd.StandardInput.WriteLine("exit");
cmd.StandardInput.Flush();
cmd.WaitForExit();
So Jar file is unable to execute. Any alternative to execute this jar with .net on OpenShift. Please help.
OpenShift is essentially Kubernetes running Linux containers. In other words, your code should act as if it is running on Linux.
Instead of cmd.exe, use bash (or, sh, or really, whatever shell is pre-installed in your container):
Process cmd = new Process();
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.WorkingDirectory = Common.JarWorkingDir;
cmd.StartInfo.FileName = "bash";
cmd.StartInfo.Arguments = "-c 'java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"'');
cmd.StartInfo.CreateNoWindow = true;
cmd.StartInfo.RedirectStandardInput = true;
cmd.Start();
cmd.StandardInput.WriteLine("exit");
cmd.StandardInput.Flush();
cmd.WaitForExit();
You can maybe even remove some of the lines. CreateNoWindow, for example, is not required because .NET Core does not create windows on Linux at all.
If you have no shell expressions, perhaps you can even get things to be simpler and simplify from this:
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.FileName = "bash";
cmd.StartInfo.Arguments = "-c 'java -jar " + string.Format("{0} {1}", '"' + Common.JarFilePath + '"', '"' + sourceCodePath + '"'');
to something like this:
cmd.StartInfo.UseShellExecute = false;
cmd.StartInfo.FileName = "java";
cmd.StartInfo.Arguments = $"-jar \"{Common.JarFilePath}\" \"{sourceCodePath}\"";
Oh, and watch out for the quoting in your Arguments variable. If you wrap the entire command after -c with single quotes, you should be fine, but if you are doing something trickier - if Common.JarFilePath isn't a simple file name - it may not work so well. Definitely test and tweak that. Maybe consider EscapeAndConcatenate.

Invoke-Webrequest ASP.Net Error

I have a script which I use to load a webpage, retrieve information from said webpage, then output said information to a file. It had been working perfectly until today, when I have been getting an error which reads:
invoke-webrequest : Response object error 'ASP 0251 : 80004005'
Response Buffer Limit Exceeded
/foo/Reports/SearchLocation.asp, line 0
Execution of the ASP page caused the Response Buffer to exceed its configured limit.
At C:\path.ps1:7 char:12
+ $url = invoke-webrequest "http://url/ ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : InvalidOperation: (System.Net.HttpWebRequest:HttpWebRequest) [Invoke-WebRequest], WebException
+ FullyQualifiedErrorId : WebCmdletWebResponseException,Microsoft.PowerShell.Commands.InvokeWebRequestCommand
I do not believe there have been any changes to the site which it is pulling its data from, and the file it is getting the input information from has no formatting errors.
Some googling around leads me to believe that the issue is that the page has more than 4 mb worth of data to load, and the default buffer size is 4 mb, but I can't find any instructions for how to change the buffer size in PowerShell.
I came across the clear-webconfiguration cmdlet, but I'm not certain whether or not that is what I need, or how exactly to implement it within my script. Here is the main portion of my code:
foreach($c in $csv){
[array]$tags = $null
$url = invoke-webrequest "http://url.com" -UseDefaultCredentials
$table = $url.ParsedHTML.getElementsByTagName('table')[7]
$rows = $table.getElementsByTagName('tr')
if($c.'Was this user on the old file?' -eq 'Yes'){
if($table.innerText -like "*N/A*" ){
$man = $c.'Manager Name' -replace ',',';'
$badusers += $c.'User ID' + "," + $c.Name + "," + $man + "," + $c.'CC'
}
else{
foreach($row in $rows){
$bcol = $row.getElementsByTagName('td') | Where-Object{$_.cellIndex -eq 1} | select -First 1
$ccol = $row.getElementsByTagName('td') | Where-Object{$_.cellIndex -eq 7} | select -First 1
$bcol = $bcol.innerText
$ccol = $ccol.innerText
if($ccol -ne $c.'CC'){
$tags += $bcol + ",," + $c.'CC' + "," + $c.'User ID'
}
}
if($tags -ne $null){
$results += $tags
}
}
}
}
Any help on solving this issue is much appreciated.

Running powershell script on asp.net site

I am trying to run a powershell script and have it output to my asp.net site. I have made it work with a very simple script where the only command in the script was
Get-Service | Out-String
and this output onto my site everything I expected
but when I use the script I actually want info from it doesn't output anything
I can tell it runs (or trys to run) because when my site hits the code that invokes the script it hangs about 10 seconds.
The script I am trying to run is
$user = "user"
$token = "token"
$base64AuthInfo = [Convert]::ToBase64String([Text.Encoding]::ASCII.GetBytes(("{0}:{1}" -f $user,$token)))
$result = Invoke-WebRequest -Method Get -Uri 'https://site.vsrm.visualstudio.com/defaultcollection/product/_apis/release/releases?definitionId=1&api-version=3.0-preview.2&$expand=environments' -ContentType "application/json" -Headers #{Authorization=("Basic {0}" -f $base64AuthInfo)}
$releaseArr = $result.Content | ConvertFrom-Json
[System.Collections.ArrayList]$enviromentName = #()
[System.Collections.ArrayList]$latestRelease = #()
foreach($env in $releaseArr.value[0].environments)
{
$enviromentName.Add($env.name) | Out-Null
}
foreach($releaseValue in $releaseArr.value)
{
For($i = 0; $i -lt $enviromentName.Count; $i++)
{
if($latestRelease[$i] -eq $null)
{
foreach($release in $releaseValue.environments)
{
if($release.name -eq $enviromentName[$i] -and $release.status -eq "succeeded")
{
$latestRelease.Add($releaseValue.name) | Out-Null
}
}
}
}
}
For($i = 0; $i -lt $enviromentName.Count; $i++)
{
Write-Host $enviromentName[$i] " : " $latestRelease[$i]
}
I know this script runs and outputs, but is there some code in this script that would cause it to not output properly.
The code in my asp.net site I am using to call the script is
ResultBox.Text = string.Empty;
// Initialize PowerShell engine
var shell = PowerShell.Create();
// Add the script to the PowerShell object
shell.Commands.AddScript(#"C:\Users\user\Desktop\script.ps1");
// Execute the script
var results = shell.Invoke();
// display results, with BaseObject converted to string
// Note : use |out-string for console-like output
if (results.Count > 0)
{
// We use a string builder ton create our result text
var builder = new StringBuilder();
foreach (var psObject in results)
{
// Convert the Base Object to a string and append it to the string builder.
// Add \r\n for line breaks
builder.Append(psObject.BaseObject.ToString() + "\r\n");
}
// Encode the string in HTML (prevent security issue with 'dangerous' caracters like < >
ResultBox.Text = Server.HtmlEncode(builder.ToString());
}
Change "Write-Host" to "Write-Output." Write-Host only outputs to interactive consoles.
You can see this in action:
Make a new PowerShell file and add a write-host statement to it:
[nick#nick-lt temp]$ New-Item -Type File -Path .\example.ps1 -Force
[nick#nick-lt temp]$ Set-Content .\example.ps1 "Write-Host 'Hello World'"
Then try and set a variable to the result of the script:
[nick#nick-lt temp]$ $what = .\example.ps1
Hello World
[nick#nick-lt temp]$ $what
[nick#nick-lt temp]$
Hello World shows up when the script executes but the variable is empty.
Now change it to write-output:
[nick#nick-lt temp]$ Set-Content .\example.ps1 "Write-Output 'Hello World'"
[nick#nick-lt temp]$ $what = .\example.ps1
[nick#nick-lt temp]$ $what
Hello World
The variable actually contains what it is supposed to now.
One of the cardinal rules of PowerShell is to not use Write-Host except in script that will be run interactively. .NET needs the results in the output stream not the host stream.

PowerShell script not working on server

I have a simple PowerShell script in which I try to write some log data.
The script that's not working:
Add-Content -Path C:\temp\logg.txt -Value $file.FullName
This line I placed in the middle of the script and I never get any text in the logg.txt. The Script executes fine except this, it compiles some files to a zip file.
This is on a Windows server.
If I, however, run the same script on my local machine, Win7, it does work!?
So I think it must be something with the server but I can't figure it out. Am using -ExecutionPolicy Bypass when I run the script.
EDIT: more info.
The script is called from an ASP.NET webpage:
Process.Start("Powershell.exe", "-ExecutionPolicy Bypass -Command ""& {" & destinationFolderRoot.Replace("\\", "\") & "\scriptParameters.ps1}""")
BaseZipScript:
function New-Zip
{
param([string]$zipfilename)
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
function Add-Zip
{
param([string]$zipfilename)
if(-not (Test-Path($zipfilename)))
{
Set-Content $zipfilename ("PK" + [char]5 + [char]6 + ("$([char]0)" * 18))
(dir $zipfilename).IsReadOnly = $false
}
$shellApplication = New-Object -COM Shell.Application
$zipPackage = $shellApplication.NameSpace($zipfilename)
foreach($file in $input)
{
$zipPackage.CopyHere($file.FullName)
Add-Content -Path "C:\temp\logg.txt" -Value $file.FullName
Start-Sleep -Milliseconds 750
}
}
scriptParameters1:
. "C:\temp\multiDownload\baseZipScript.ps1"
New-Zip c:\temp\multiDownload\user379\2016-09-15_14.39\files_2016-09-15_14.39.zip
dir c:\temp\multiDownload\user379\2016-09-15_14.39\tempCopy\*.* -Recurse |
Add-Zip c:\temp\multiDownload\user379\2016-09-15_14.39\files_2016-09-15_14.39.zip
Start-sleep -milliseconds 250
exit
As I said earlier the script works on local machine and also on the server, e.g. the files are being zipped, except that on the server nothing is logged in logg.txt.
Though the logg.txt works and exists on the server because the webpage also log some info there and that is being written.
Update:
As the comments guessed it was as simple as write access to the file. Though, it is kind of wierd because all files are created from the webservice if they doesn't exists? Any how, it works now. Thx! : )

Powershell Script to copy files based on date modifed to check newest file from a remote location

I am new to powershell scripting and i cant figure out why my script copies
all files and doesn't seem to check the date and then copies all the files
anyway. I was trying to do by days and minutes too, but I am not quite sure
on how to do that. any help would be great!
see my script below.
$RemotePath = "\\eb-pc\E$\testlocation\*.txt"
$LocalPath = "C:\testlocation"
$Max_days = "-1"
#Max_mins = "-5"
$Curr_date = get-date
#Checking date and then copying file from RemotePath to LocalPath
Foreach($file in (Get-ChildItem $RemotePath))
{
if($file.LastWriteTime -gt ($Curr_date).adddays($Max_days))
{
Copy-Item -Path $file.fullname -Destination $LocalPath
#Move-Item -Path $file.fullname -Destination $LocalPath
}
}
If you want to use Hours and minutes, instead of AddDays, just use the .AddMinutes(), .AddHours(), or .AddSeconds() methods instead.
For what it's worth, I made a small modifcation, adding an Else{Scriptblock} to the script to echo out the files which aren't being copied. As written your code will only copy files written in the last 24 hours.
$RemotePath = "t:\"
$LocalPath = "C:\temp"
$Max_days = "-1"
#Max_mins = "-5"
$Curr_date = get-date
#Checking date and then copying file from RemotePath to LocalPath
Foreach($file in (Get-ChildItem $RemotePath))
{
if($file.LastWriteTime -gt ($Curr_date).adddays($Max_days))
{
Copy-Item -Path $file.fullname -Destination $LocalPath -WhatIf
#Move-Item -Path $file.fullname -Destination $LocalPath
}
ELSE
{"not copying $file"
}
}
>What if: Performing the operation "Copy File" on target "Item: T:\file.htm Destination: C:\temp\file.ht
m".
not copying ListOfSacredVMs.txt
not copying newUser_01.png
not copying newUser_015.png
not copying newUser_02.png
not copying newUser_03.png
What if: Performing the operation "Copy File" on target "Item: T:\values.csv Destination: C:\temp\values.csv".
It has been a while since I did anything in PowerShell. However you may want to try to Echo out the values you are comparing to see what they are really returning.
Echo "LastWrite : " & $file.LastWriteTime
Echo "Copy After : " & ($Curr_date).adddays($Max_days)
This would help to determine what you are attempting to compare.
HopeThisHelps at least a little.

Resources