I know the method
ApplicationDescriptor.currentApplicationDescriptor();
But I aim to download another JAD and compare it's version number to the current applications version. What is the best/easiest way to do this? Is there a way to construct an ApplicationDescriptor from a simple String?
Get the version from the current Apps JAD:
String currentVersion = ApplicationDescriptor.currentApplicationDescriptor().getVersion();
Get the version from a downloaded JAD as String:
public static String getJADProperty(String jadString, String propKey) {
int indexFrom = jadString.indexOf(propKey) + propKey.length();
// Value reaches until line break (Unix vs. Win)
int indexTo = jadString.indexOf("\r", indexFrom);
if (indexTo == -1) { indexTo = jadString.indexOf("\n", indexFrom); }
return jadString.substring(indexFrom, indexTo).trim();
}
Compare the version strings:
/**
* Compares two version strings that are in the format 1.1.1
*
* #param current Version String in the format 1.1.1 (current version of the app)
* #param remote Version String in the format 1.1.1 (remote version of the app)
*
* #return true if the remote version is newer
*/
public static boolean compareVersionStrings(String current, String remote) {
int lastIndexCurrent = 0;
int indexCurrent = 0;
int lastIndexRemote = 0;
int indexRemote = 0;
String currentVersionSubstring = "";
String remoteVersionSubstring = "";
do {
lastIndexCurrent = indexCurrent + currentVersionSubstring.length();
indexCurrent = current.indexOf(".", lastIndexCurrent);
lastIndexRemote = indexRemote + remoteVersionSubstring.length();
indexRemote = remote.indexOf(".", lastIndexRemote);
// Needed because there is no "." at the last number of the version string
if (indexCurrent != -1) {
currentVersionSubstring = current.substring(lastIndexCurrent, indexCurrent);
} else {
currentVersionSubstring = current.substring(lastIndexCurrent);
}
if (indexRemote != -1) {
remoteVersionSubstring = remote.substring(lastIndexRemote, indexRemote);
} else {
remoteVersionSubstring = remote.substring(lastIndexRemote);
}
if (Integer.parseInt(currentVersionSubstring) < Integer.parseInt(remoteVersionSubstring)) {
return true;
}
} while (indexCurrent != -1);
// 1.0 < 1.0.1
if (indexRemote != -1) {
return true;
}
return false;
}
Any corrections and improvements are appreciated. Feel free to edit and share your experiences with me.
Related
I'm sorting strings that are comprised of text and numbers.
I want the sort to sort the number parts as numbers, not alphanumeric.
For example I want: abc1def, ..., abc9def, abc10def
instead of: abc10def, abc1def, ..., abc9def
Does anyone know an algorithm for this (in particular in c++)
Thanks
I asked this exact question (although in Java) and got pointed to http://www.davekoelle.com/alphanum.html which has an algorithm and implementations of it in many languages.
Update 14 years later: Dave Koelle’s blog has gone off line and I can’t find his actual algorithm, but here’s an implementation.
https://github.com/cblanc/koelle-sort
Several natural sort implementations for C++ are available. A brief review:
natural_sort<> - based on Boost.Regex.
In my tests, it's roughly 20 times slower than other options.
Dirk Jagdmann's alnum.hpp, based on Dave Koelle's alphanum algorithm
Potential integer overlow issues for values over MAXINT
Martin Pool's natsort - written in C, but trivially usable from C++.
The only C/C++ implementation I've seen to offer a case insensitive version, which would seem to be a high priority for a "natural" sort.
Like the other implementations, it doesn't actually parse decimal points, but it does special case leading zeroes (anything with a leading 0 is assumed to be a fraction), which is a little weird but potentially useful.
PHP uses this algorithm.
This is known as natural sorting. There's an algorithm here that looks promising.
Be careful of problems with non-ASCII characters (see Jeff's blog entry on the subject).
Partially reposting my another answer:
bool compareNat(const std::string& a, const std::string& b){
if (a.empty())
return true;
if (b.empty())
return false;
if (std::isdigit(a[0]) && !std::isdigit(b[0]))
return true;
if (!std::isdigit(a[0]) && std::isdigit(b[0]))
return false;
if (!std::isdigit(a[0]) && !std::isdigit(b[0]))
{
if (a[0] == b[0])
return compareNat(a.substr(1), b.substr(1));
return (toUpper(a) < toUpper(b));
//toUpper() is a function to convert a std::string to uppercase.
}
// Both strings begin with digit --> parse both numbers
std::istringstream issa(a);
std::istringstream issb(b);
int ia, ib;
issa >> ia;
issb >> ib;
if (ia != ib)
return ia < ib;
// Numbers are the same --> remove numbers and recurse
std::string anew, bnew;
std::getline(issa, anew);
std::getline(issb, bnew);
return (compareNat(anew, bnew));
}
toUpper() function:
std::string toUpper(std::string s){
for(int i=0;i<(int)s.length();i++){s[i]=toupper(s[i]);}
return s;
}
Usage:
std::vector<std::string> str;
str.push_back("abc1def");
str.push_back("abc10def");
...
std::sort(str.begin(), str.end(), compareNat);
To solve what is essentially a parsing problem a state machine (aka finite state automaton) is the way to go. Dissatisfied with the above solutions i wrote a simple one-pass early bail-out algorithm that beats C/C++ variants suggested above in terms of performance, does not suffer from numerical datatype overflow errors, and is easy to modify to add case insensitivity if required.
sources can be found here
For those that arrive here and are already using Qt in their project, you can use the QCollator class. See this question for details.
Avalanchesort is a recursive variation of naturall sort, whiche merge runs, while exploring the stack of sorting-datas. The algorithim will sort stable, even if you add datas to your sorting-heap, while the algorithm is running/sorting.
The search-principle is simple. Only merge runs with the same rank.
After finding the first two naturell runs (rank 0), avalanchesort merge them to a run with rank 1. Then it call avalanchesort, to generate a second run with rank 1 and merge the two runs to a run with rank 2. Then it call the avalancheSort to generate a run with rank 2 on the unsorted datas....
My Implementation porthd/avalanchesort divide the sorting from the handling of the data using interface injection. You can use the algorithmn for datastructures like array, associative arrays or lists.
/**
* #param DataListAvalancheSortInterface $dataList
* #param DataRangeInterface $beginRange
* #param int $avalancheIndex
* #return bool
*/
public function startAvalancheSort(DataListAvalancheSortInterface $dataList)
{
$avalancheIndex = 0;
$rangeResult = $this->avalancheSort($dataList, $dataList->getFirstIdent(), $avalancheIndex);
if (!$dataList->isLastIdent($rangeResult->getStop())) {
do {
$avalancheIndex++;
$lastIdent = $rangeResult->getStop();
if ($dataList->isLastIdent($lastIdent)) {
$rangeResult = new $this->rangeClass();
$rangeResult->setStart($dataList->getFirstIdent());
$rangeResult->setStop($dataList->getLastIdent());
break;
}
$nextIdent = $dataList->getNextIdent($lastIdent);
$rangeFollow = $this->avalancheSort($dataList, $nextIdent, $avalancheIndex);
$rangeResult = $this->mergeAvalanche($dataList, $rangeResult, $rangeFollow);
} while (true);
}
return $rangeResult;
}
/**
* #param DataListAvalancheSortInterface $dataList
* #param DataRangeInterface $range
* #return DataRangeInterface
*/
protected function findRun(DataListAvalancheSortInterface $dataList,
$startIdent)
{
$result = new $this->rangeClass();
$result->setStart($startIdent);
$result->setStop($startIdent);
do {
if ($dataList->isLastIdent($result->getStop())) {
break;
}
$nextIdent = $dataList->getNextIdent($result->getStop());
if ($dataList->oddLowerEqualThanEven(
$dataList->getDataItem($result->getStop()),
$dataList->getDataItem($nextIdent)
)) {
$result->setStop($nextIdent);
} else {
break;
}
} while (true);
return $result;
}
/**
* #param DataListAvalancheSortInterface $dataList
* #param $beginIdent
* #param int $avalancheIndex
* #return DataRangeInterface|mixed
*/
protected function avalancheSort(DataListAvalancheSortInterface $dataList,
$beginIdent,
int $avalancheIndex = 0)
{
if ($avalancheIndex === 0) {
$rangeFirst = $this->findRun($dataList, $beginIdent);
if ($dataList->isLastIdent($rangeFirst->getStop())) {
// it is the last run
$rangeResult = $rangeFirst;
} else {
$nextIdent = $dataList->getNextIdent($rangeFirst->getStop());
$rangeSecond = $this->findRun($dataList, $nextIdent);
$rangeResult = $this->mergeAvalanche($dataList, $rangeFirst, $rangeSecond);
}
} else {
$rangeFirst = $this->avalancheSort($dataList,
$beginIdent,
($avalancheIndex - 1)
);
if ($dataList->isLastIdent($rangeFirst->getStop())) {
$rangeResult = $rangeFirst;
} else {
$nextIdent = $dataList->getNextIdent($rangeFirst->getStop());
$rangeSecond = $this->avalancheSort($dataList,
$nextIdent,
($avalancheIndex - 1)
);
$rangeResult = $this->mergeAvalanche($dataList, $rangeFirst, $rangeSecond);
}
}
return $rangeResult;
}
protected function mergeAvalanche(DataListAvalancheSortInterface $dataList, $oddListRange, $evenListRange)
{
$resultRange = new $this->rangeClass();
$oddNextIdent = $oddListRange->getStart();
$oddStopIdent = $oddListRange->getStop();
$evenNextIdent = $evenListRange->getStart();
$evenStopIdent = $evenListRange->getStop();
$dataList->initNewListPart($oddListRange, $evenListRange);
do {
if ($dataList->oddLowerEqualThanEven(
$dataList->getDataItem($oddNextIdent),
$dataList->getDataItem($evenNextIdent)
)) {
$dataList->addListPart($oddNextIdent);
if ($oddNextIdent === $oddStopIdent) {
$restTail = $evenNextIdent;
$stopTail = $evenStopIdent;
break;
}
$oddNextIdent = $dataList->getNextIdent($oddNextIdent);
} else {
$dataList->addListPart($evenNextIdent);
if ($evenNextIdent === $evenStopIdent) {
$restTail = $oddNextIdent;
$stopTail = $oddStopIdent;
break;
}
$evenNextIdent = $dataList->getNextIdent($evenNextIdent);
}
} while (true);
while ($stopTail !== $restTail) {
$dataList->addListPart($restTail);
$restTail = $dataList->getNextIdent($restTail);
}
$dataList->addListPart($restTail);
$dataList->cascadeDataListChange($resultRange);
return $resultRange;
}
}
My algorithm with test code of java version. If you want to use it in your project you can define a comparator yourself.
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.function.Consumer;
public class FileNameSortTest {
private static List<String> names = Arrays.asList(
"A__01__02",
"A__2__02",
"A__1__23",
"A__11__23",
"A__3++++",
"B__1__02",
"B__22_13",
"1_22_2222",
"12_222_222",
"2222222222",
"1.sadasdsadsa",
"11.asdasdasdasdasd",
"2.sadsadasdsad",
"22.sadasdasdsadsa",
"3.asdasdsadsadsa",
"adsadsadsasd1",
"adsadsadsasd10",
"adsadsadsasd3",
"adsadsadsasd02"
);
public static void main(String...args) {
List<File> files = new ArrayList<>();
names.forEach(s -> {
File f = new File(s);
try {
if (!f.exists()) {
f.createNewFile();
}
files.add(f);
} catch (IOException e) {
e.printStackTrace();
}
});
files.sort(Comparator.comparing(File::getName));
files.forEach(f -> System.out.print(f.getName() + " "));
System.out.println();
files.sort(new Comparator<File>() {
boolean caseSensitive = false;
int SPAN_OF_CASES = 'a' - 'A';
#Override
public int compare(File left, File right) {
char[] csLeft = left.getName().toCharArray(), csRight = right.getName().toCharArray();
boolean isNumberRegion = false;
int diff=0, i=0, j=0, lenLeft=csLeft.length, lenRight=csRight.length;
char cLeft = 0, cRight = 0;
for (; i<lenLeft && j<lenRight; i++, j++) {
cLeft = getCharByCaseSensitive(csLeft[i]);
cRight = getCharByCaseSensitive(csRight[j]);
boolean isNumericLeft = isNumeric(cLeft), isNumericRight = isNumeric(cRight);
if (isNumericLeft && isNumericRight) {
// Number start!
if (!isNumberRegion) {
isNumberRegion = true;
// Remove prefix '0'
while (i < lenLeft && cLeft == '0') i++;
while (j < lenRight && cRight == '0') j++;
if (i == lenLeft || j == lenRight) break;
}
// Diff start: calculate the diff value.
if (cLeft != cRight && diff == 0)
diff = cLeft - cRight;
} else {
if (isNumericLeft != isNumericRight) {
// One numeric and one char.
if (isNumberRegion)
return isNumericLeft ? 1 : -1;
return cLeft - cRight;
} else {
// Two chars: if (number) diff don't equal 0 return it.
if (diff != 0)
return diff;
// Calculate chars diff.
diff = cLeft - cRight;
if (diff != 0)
return diff;
// Reset!
isNumberRegion = false;
diff = 0;
}
}
}
// The longer one will be put backwards.
return (i == lenLeft && j == lenRight) ? cLeft - cRight : (i == lenLeft ? -1 : 1) ;
}
private boolean isNumeric(char c) {
return c >= '0' && c <= '9';
}
private char getCharByCaseSensitive(char c) {
return caseSensitive ? c : (c >= 'A' && c <= 'Z' ? (char) (c + SPAN_OF_CASES) : c);
}
});
files.forEach(f -> System.out.print(f.getName() + " "));
}
}
The output is,
1.sadasdsadsa 11.asdasdasdasdasd 12_222_222 1_22_2222 2.sadsadasdsad 22.sadasdasdsadsa 2222222222 3.asdasdsadsadsa A__01__02 A__11__23 A__1__23 A__2__02 A__3++++ B__1__02 B__22_13 adsadsadsasd02 adsadsadsasd1 adsadsadsasd10 adsadsadsasd3
1.sadasdsadsa 1_22_2222 2.sadsadasdsad 3.asdasdsadsadsa 11.asdasdasdasdasd 12_222_222 22.sadasdasdsadsa 2222222222 A__01__02 A__1__23 A__2__02 A__3++++ A__11__23 adsadsadsasd02 adsadsadsasd1 adsadsadsasd3 adsadsadsasd10 B__1__02 B__22_13
Process finished with exit code 0
// -1: s0 < s1; 0: s0 == s1; 1: s0 > s1
static int numericCompare(const string &s0, const string &s1) {
size_t i = 0, j = 0;
for (; i < s0.size() && j < s1.size();) {
string t0(1, s0[i++]);
while (i < s0.size() && !(isdigit(t0[0]) ^ isdigit(s0[i]))) {
t0.push_back(s0[i++]);
}
string t1(1, s1[j++]);
while (j < s1.size() && !(isdigit(t1[0]) ^ isdigit(s1[j]))) {
t1.push_back(s1[j++]);
}
if (isdigit(t0[0]) && isdigit(t1[0])) {
size_t p0 = t0.find_first_not_of('0');
size_t p1 = t1.find_first_not_of('0');
t0 = p0 == string::npos ? "" : t0.substr(p0);
t1 = p1 == string::npos ? "" : t1.substr(p1);
if (t0.size() != t1.size()) {
return t0.size() < t1.size() ? -1 : 1;
}
}
if (t0 != t1) {
return t0 < t1 ? -1 : 1;
}
}
return i == s0.size() && j == s1.size() ? 0 : i != s0.size() ? 1 : -1;
}
I am not very sure if it is you want, anyway, you can have a try:-)
public ActionResult ExcelFile(IEnumerable < HttpPostedFileBase > excelFile) {
try {
if (excelFile != null) {
foreach(var singleExcel in excelFile) {
string path = "~/ExcelFolder/";
singleExcel.SaveAs(Server.MapPath(path + singleExcel.FileName));
using(FileStream fs = new FileStream(Server.MapPath(path + singleExcel.FileName), FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) {
using(ExcelPackage package = new ExcelPackage(fs)) {
ExcelWorksheet sheet = package.Workbook.Worksheets[1];
int startRowNumber = sheet.Dimension.Start.Row;
int endRowNumber = sheet.Dimension.End.Row;
int startColumnNumber = sheet.Dimension.Start.Column;
int endColumnNumber = sheet.Dimension.End.Column;
if (endColumnNumber > 26) {
for (int currentColumnNumber = endColumnNumber; startColumnNumber < currentColumnNumber; currentColumnNumber--) {
var cellValue = sheet.Cells[startRowNumber, currentColumnNumber].Value ? .ToString();
if (!string.IsNullOrWhiteSpace(cellValue)) {
if (cellValue == "延人公里小計") {
sheet.DeleteColumn(currentColumnNumber);
sheet.Cells[1, currentColumnNumber].Value = "小計";
//return fsr;
package.SaveAs(
new FileInfo(# "C:\Users\leon0944\Desktop\123\" + singleExcel.FileName));
break;
}
}
}
}
}
}
}
Hello,when I upload many Excel to the file then read every single Excel to do someting.then i got error in ExcelPackage package = new ExcelPackage(fs) this row
error message :System.Runtime.InteropServices.COMException: HRESULT:
0x8003001D (STG_E_WRITEFAULT)
sometime is working normally sometime I got error,Please tell me How Can I fix this. The problem existed for several days.
I am developing a module in a billing system for a national Utility. The module is supposed to pick all successfully billed customers and print their bills.Bills are written as text files and saved on a local folder and the program has to pick them up and print them one by one.I'm using a DFX-9000 printer and pre-formatted roll paper,however,each time a new bill comes in,the printer skips some space before it prints it which distorts the 2nd and following bills.
I tried putting all the bills in a single text file which prints well when opened in notepad but not in my code.
Here is part of my code
Font printFont = new Font("Lucida Console", 10);
//static string filename;
StreamReader reader = new StreamReader(Filename);
public void Print()
{
try
{
PrintDocument pd = new PrintDocument();
pd.DefaultPageSettings.PaperSize = new System.Drawing.Printing.PaperSize("myPaper", 826, 1169);
pd.DefaultPageSettings.Margins = new Margins(0, 0, 0, 0);
//pd.DefaultPageSettings.PrinterSettings.IsPlotter = true;
pd.DefaultPageSettings.PrinterResolution.Kind = PrinterResolutionKind.Custom;
pd.PrintPage += new PrintPageEventHandler(this.PrintTextFileHandler);
pd.Print();
if (reader != null)
reader.Close();
Console.WriteLine("Printout Complete");
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
}
}
private void PrintTextFileHandler(object sender, PrintPageEventArgs pe)
{
StringFormat sf = new StringFormat();
Graphics g = pe.Graphics;
float linesPerPage = 0;
float yPos = 0;
int count = 0;
float leftMargin = 40;//pe.MarginBounds.Left;
float topMargin = pe.MarginBounds.Top;
string line = null;
linesPerPage = 500;// pe.MarginBounds.Height / printFont.GetHeight(g);
while (count <= linesPerPage &&((line = reader.ReadLine()) != null))
{
yPos = topMargin + (count * printFont.GetHeight(g));
g.DrawString(line, printFont, Brushes.Black, leftMargin, yPos);
count++;
}
if (line != null)
{
pe.HasMorePages = true;
}
else
{
pe.HasMorePages = false;
}
Could your printing.papersize be wrong? I notice it's 1169, doesn't standard paper stop at 1100?
I am building an AppWorld sort of thing in blackberry.I have Categories,sub categories and apps within.I want to do in-app download,but as of now i am calling the browser and passing the url and downloading of the content happens.How to make in-app download or download from within my app just like the AppWorld of blackberry.
YOu need to use code module manager API to download and install applications.
Code in bits and pieces
_moduleGroup = new CodeModuleGroup(appVendorName);
_moduleGroup.setVersion(JADParser.getValue("MIDlet-Version"));
_moduleGroup.setVendor(vendorName);
_moduleGroup.setFriendlyName(appName);
_moduleGroup.setDescription(JADParser.getValue("MIDlet-Description"));
String dependency = JADParser.getValue("RIM-COD-Module-Dependencies");
if (dependency != null)
{
dependency = dependency.trim();
String[] dependencyList = vStringUtils.split(dependency, ',');
for (int i = 0; i < dependencyList.length; i++)
{
_moduleGroup.addDependency(dependencyList[i]);
}
}
for (i = 0; i < count; i++)
{
if (!writeCODFile(getCodFileData(i), getCodFileName(i)))
{
throw new Exception();
}
}
private boolean writeCODFile(byte[] data, String fileName)
{
boolean isSuccess = true;
int moduleId = 0;
if (data.length > MODULE_SIZE_LIMIT)
{
moduleId = CodeModuleManager.createNewModule(data.length, data, MODULE_SIZE_LIMIT);
isSuccess = CodeModuleManager.writeNewModule(moduleId, MODULE_SIZE_LIMIT, data, MODULE_SIZE_LIMIT, data.length - MODULE_SIZE_LIMIT);
}
else
{
moduleId = CodeModuleManager.createNewModule(data.length, data, data.length);
}
if (moduleId > 0 && isSuccess)
{
int ret = CodeModuleManager.saveNewModule(moduleId, true, _transactionId);
if (ret == CodeModuleManager.CMM_OK_MODULE_OVERWRITTEN || ret == CodeModuleManager.CMM_OK)
{
return true;
}
}
return false;
}
Hi guys this is a long shot but here goes...
I basically have what I mentioned in the title running on my server. When I upload a video ffmpeg decomplies it and gives me screenshots, then I pick a screenshot that I want to use for that video. Currently, my server can process 3 videos at a time. The down side is that this uses up A LOT of the server processing power. :(
Is there a way, or a program, that can process several video at a time and generate me screenshots on my Desktop? If this is possible then I can just use my spare computer here to process everything then upload the screenshots/video to my server.
This is what I basically have running now on the server. kayweb.com.au/blogs/Web-Development/Generating-screenshots-using-FFmpeg
Something like this, But this thumbnail generator puts everything into one image. I need to be able to choose with thumbnail I want to use.
http://www.tothepc.com/archives/make-movie-caps-screenshots-with-free-video-thumbnails-maker/
Anyone have any suggestions?
The problem with getting multiple thumbs is the time. So far I have not been able to get multiple thumbs from a single scan, so it means I have to scan three times for three images.
In my case I took the video time in seconds then got the the three images from 1/4, 1/2 and 3/4. But for long videos this is far too slow, even using ffmpeg's offset value. It is better if you can to select from the first 10-20 seconds into the video.
So I start with a pre-process, this scans the images at the time of the file search then any that haven't got a thumb created it creates one from a few seconds into the video, that is a quick process and in a thread of it's own isn't really noticeable, unless there are a lot of videos needing an icon, so a first run will be slow.
Then as with the functions form, if the thumb isn't any good I allow the selection from my 3 thumbs which are generated on the fly. In my case I used MDI so I could marry various parts of a media suite together. So the part below is a form on it's own, the file list 'videoList', has been filled when the user selected a directory in another form.
Just for completeness I will include my MediaItem and MediaType enums.
Ignore the way I have named my temporary files, I am still working on that because I will be marrying it with a service later which will supply the name. You can get problems using the same files in C# that were just created or modified in an external process, so you do need some clever file use convention.
public partial class ThumbSelector : Form
{
public List<MediaItem> videoList = new List<MediaItem>();
private Random ra = new Random();
int iCount = 1;
public ThumbSelector()
{
InitializeComponent();
}
public void FillList()
{
if(videoList.Count() < 1)
return;
//only get mp4 files
var videosOnly = from n in videoList
where n.mainType == MediaMainType.MMT_VIDEO
select n;
lbVideoList.Items.Clear();
foreach (MediaItem mi in videosOnly)
{
lbVideoList.Items.Add(mi.shortName);
}
}
private void lbVideoList_SelectedIndexChanged(object sender, EventArgs e)
{
if(lbVideoList.SelectedItems.Count < 1)
return;
CreateThumbs(lbVideoList.SelectedItems[0].ToString());
}
private void CreateThumbs(string fShortName)
{
string sourceVideoName;
int sourceLength = 0;
int quarter = 0;
int half = 0;
int threequarter = 0;
string destDir = #"C:\Users\robert\dwhelper\VideoIcons";
string ffPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ffmpeg.exe";
var sname = (from n in videoList
where n.shortName == fShortName
select n).First();
sourceVideoName = sname.fullName;
sourceLength = GetVideoLength(ffPath, sourceVideoName);
quarter = sourceLength / 4;
half = sourceLength / 2;
threequarter = quarter * 3;
Image im1;
Image im2;
Image im3;
string n1;
string n2;
string n3;
while (File.Exists(string.Concat(destDir, #"\", "x1_", iCount.ToString(), ".jpg")))
{
++iCount;
}
n1 = string.Concat("x1_", iCount.ToString(), ".jpg");
++iCount;
while (File.Exists(string.Concat(destDir, #"\", "x2_", iCount.ToString(), ".jpg")))
{
++iCount;
}
n2 = string.Concat("x2_", iCount.ToString(), ".jpg");
++iCount;
while (File.Exists(string.Concat(destDir, #"\", "x3_", iCount.ToString(), ".jpg")))
{
++iCount;
}
n3 = string.Concat("x3_", iCount.ToString(), ".jpg");
pic1.Image = null;
pic2.Image = null;
pic3.Image = null;
CreateThumbs(sname, quarter, n1);
im1 = Image.FromFile(string.Concat(destDir, #"\", n1));
pic1.Image = im1;
CreateThumbs(sname, half, n2);
im2 = Image.FromFile(string.Concat(destDir, #"\", n2));
pic2.Image = im2;
CreateThumbs(sname, threequarter, n3);
im3 = Image.FromFile(string.Concat(destDir, #"\", n3));
pic3.Image = im3;
}
private void CreateThumbs(MediaItem mi, int timeIn, string outName)
{
this.Cursor = Cursors.WaitCursor;
Process pth;
string destDir = #"C:\Users\robert\dwhelper\VideoIcons";
string sourceFile;
string destFile;
string ffPath = System.Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\ffmpeg.exe";
string strCommand;
string fullCommand;
string[] ssplit;
sourceFile = mi.fullName;
ssplit = mi.shortName.Split('.');
destFile = string.Concat(destDir, "\\", outName);
strCommand = string.Concat(
" -i \"", sourceFile, "\" -r 1 -ss ", timeIn.ToString(), " -t 00:00:01 -f image2 \"", destFile, "\"");
fullCommand = string.Concat(ffPath, strCommand);
pth = new Process();
pth.StartInfo.FileName = ffPath;
pth.StartInfo.Arguments = strCommand;
pth.StartInfo.UseShellExecute = false;
pth.StartInfo.CreateNoWindow = true;
pth.Start();
pth.WaitForExit();
this.Cursor = Cursors.Default;
}
private int GetVideoLength(string ffmpeg, string sourceFile)
{
//exec('start C:\Inetpub\ffmpeg\ffmpeg -i "D:/Jaime-flex.wmv" 2>&1 | grep "Duration" | cut -d " " -f 4 - | sed s/,//', $output);
string result = "";
string strCommand = string.Concat(
" -i \"", sourceFile, "\" 2>");
Process pth = new Process();
pth.StartInfo.FileName = ffmpeg;
pth.StartInfo.Arguments = strCommand;
pth.StartInfo.UseShellExecute = false;
pth.StartInfo.CreateNoWindow = true;
pth.StartInfo.RedirectStandardOutput = true;
pth.StartInfo.RedirectStandardError = true;
pth.Start();
pth.WaitForExit();
//result = pth.StandardOutput.ReadToEnd();
//result = pth.StandardError.ReadToEnd();
string str = "";
string[] ssplit;
char[] splitChars = new char[] { '.', ' ' };
int seconds = 0;
while (!pth.StandardError.EndOfStream)
{
str = pth.StandardError.ReadLine();
if (str.Contains("Duration"))
{
ssplit = str.Split(splitChars);
seconds = GetSeconds(ssplit[3]);
}
}
return seconds;
}
private int GetSeconds(string p)
{
string[] ssplit = p.Split(':');
int ho = Convert.ToInt32(ssplit[0]) * 120;
int mi = Convert.ToInt32(ssplit[1]) * 60;
int se = Convert.ToInt32(ssplit[2]);
return ho + mi + se;
}
}
public class MediaItem
{
public string shortName { get; set; }
public string fullName { get; set; }
public string iconName { get; set; }
public MediaMainType mainType { get; set; }
public MediaSubType subType { get; set; }
public long length { get; set; }
}
public enum MediaMainType
{
MMT_VIDEO = 0, MMT_IMAGE, MMT_ICON, MMT_NOTMEDIA
}
public enum MediaSubType
{
MST_JPG = 0, MST_GIF, MST_BMP, MST_PNG, MST_MP4, MST_WMV, MST_FLV, MST_NOTMEDIA
3