DOS based printing through ASP.NET - asp.net

Well my situation is like this:
I am generating a report as a text file at the server which needs to be printed using DOS mode on a dot matrix printer. I want to avoid Windows printing because it would be too slow. Is there a way in ASP.NET through which I can carry out DOS based printing as it is best suited for Dot matrix printers. I have scoured the net but could not come across any solution or pointers. Does any body have any pointers/solutions which they might have implemented or stumbled across.
This application is a Web based application.
Thanx.

If I understand you right, one option is to execute a batch file that would do the actual printing from ASP.NET. From here: (Obviously, you can omit some of the code writing the output to the page)
// Get the full file path
string strFilePath = “c:\\temp\\test.bat”;
// Create the ProcessInfo object
System.Diagnostics.ProcessStartInfo psi = new System.Diagnostics.ProcessStartInfo("cmd.exe");
psi.UseShellExecute = false;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.RedirectStandardError = true;
psi.WorkingDirectory = “c:\\temp\\“;
// Start the process
System.Diagnostics.Process proc = System.Diagnostics.Process.Start(psi);
// Open the batch file for reading
System.IO.StreamReader strm = System.IO.File.OpenText(strFilePath);
// Attach the output for reading
System.IO.StreamReader sOut = proc.StandardOutput;
// Attach the in for writing
System.IO.StreamWriter sIn = proc.StandardInput;
// Write each line of the batch file to standard input
while(strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}
strm.Close();
// Exit CMD.EXE
string stEchoFmt = "# {0} run successfully. Exiting";
sIn.WriteLine(String.Format(stEchoFmt, strFilePath));
sIn.WriteLine("EXIT");
// Close the process
proc.Close();
// Read the sOut to a string.
string results = sOut.ReadToEnd().Trim();
// Close the io Streams;
sIn.Close();
sOut.Close();
// Write out the results.
string fmtStdOut = "<font face=courier size=0>{0}</font>";
this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "<br>")));

The answer from BobbyShaftoe is correct. Here's a pedantic version of it:
public static void CreateProcess(string strFilePath)
{
// Create the ProcessInfo object
var psi = new ProcessStartInfo("cmd.exe")
{
UseShellExecute = false,
RedirectStandardOutput = true,
RedirectStandardInput = true,
RedirectStandardError = true,
WorkingDirectory = "c:\\temp\\"
};
// Start the process
using (var proc = Process.Start(psi))
{
// Attach the in for writing
var sIn = proc.StandardInput;
using (var strm = File.OpenText(strFilePath))
{
// Write each line of the batch file to standard input
while (strm.Peek() != -1)
{
sIn.WriteLine(strm.ReadLine());
}
}
// Exit CMD.EXE
sIn.WriteLine(String.Format("# {0} run successfully. Exiting", strFilePath));
sIn.WriteLine("EXIT");
// Read the sOut to a string.
var results = proc.StandardOutput.ReadToEnd().Trim();
// Write out the results.
string fmtStdOut = "<font face=courier size=0>{0}</font>";
this.Response.Write(String.Format(fmtStdOut,results.Replace(System.Environment.NewLine, "<br>")));
}
}

Related

Powershell runquery in clients machine ASP.NET

I want to get the program names installed from Windows Store(client side). Heres my code. First of all is it possible? Secondly if yes why my code is not working?
StringBuilder stringBuilder = new StringBuilder();
var shell = PowerShell.Create();
// Add the script to the PowerShell object
shell.Commands.AddScript("Import-Module Appx");
shell.Commands.AddScript("Get-AppxPackage ");
Command c = new Command("Out-String");
c.Parameters.Add("width", 150);
shell.Commands.AddCommand(c);
// var results = shell.Invoke();
Collection<PSObject> results = shell.Invoke();
foreach (PSObject obj in results)
{
stringBuilder.AppendLine(obj.ToString());
}
No results returned (Only one and it is empty . )

imagemagick file paths? Getting a 'The system cannot find the file specified error'

I cannot figure out where I need to put files for ImageMagick to process them. I am trying to use it in my ASP.NET MVC website and having zero luck having it find my files to process. And if it does how do I specify where they will be output?
I have been looking here and I mut be missing something:
http://www.imagemagick.org/script/command-line-processing.php
Here is my code to call the process:
//Location of the ImageMagick applications
private const string pathImageMagick = #"C:\Program Files\ImageMagick-6.7.3-8";
private const string appImageMagick = "MagickCMD.exe";
CallImageMagick("convert -density 400 SampleCtalog.pdf -scale 2000x1000 hi-res%d.jpg");
private static string CallImageMagick(string fileArgs)
{
ProcessStartInfo startInfo = new ProcessStartInfo
{
Arguments = fileArgs,
WorkingDirectory = pathImageMagick,
FileName = appImageMagick,
UseShellExecute = false,
CreateNoWindow = true,
RedirectStandardOutput = true
};
using (Process exeProcess = Process.Start(startInfo))
{
string IMResponse = exeProcess.StandardOutput.ReadToEnd();
exeProcess.WaitForExit();
exeProcess.Close();
return !String.IsNullOrEmpty(IMResponse) ? IMResponse : "True";
}
}
We do something similar but use the environment variables (which is advantageous because it works on every system) to execute cmd.exe which we feed with convert and the parameters. This is how we create the ProcessStartInfo object:
// Your command
string command = "convert...";
ProcessStartInfo procStartInfo = new ProcessStartInfo {CreateNoWindow = true};
string fileName = Environment.GetEnvironmentVariable("ComSpec");
if (String.IsNullOrEmpty(fileName))
{
// The "ComSpec" environment variable is not present
fileName = Environment.GetEnvironmentVariable("SystemRoot");
if (!String.IsNullOrEmpty(fileName))
{
// Try "%SystemRoot%\system32\cmd.exe"
fileName = Path.Combine(Path.Combine(fileName, "system32"), "cmd.exe");
}
if ((String.IsNullOrEmpty(fileName)) || (!File.Exists(fileName)))
{
// If the comd.exe is not present, let Windows try to find it
fileName = "cmd";
}
}
procStartInfo.FileName = fileName;
procStartInfo.RedirectStandardInput = true;
procStartInfo.RedirectStandardOutput = true;
procStartInfo.UseShellExecute = false;
Process proc = Process.Start(procStartInfo);
proc.StandardInput.WriteLine(command);
proc.StandardInput.Flush();
Then we read from proc.StandardOutput in order to get error messages and result codes. Afterwards, we destroy the objects.
Sorry if this is not 100%, I copied it from a more complex OO code.

Running a batch file from an ASP.Net page

I'm trying to run a batch file on a server via an ASP.Net page, and it's driving my crazy. When I run the below code, nothing happnes - I can see from some log statements that this code runs, but the .bat file that I pass to the function never runs.
Could anybody please tell me what I'm doing wrong?
public void ExecuteCommand(string batchFileLocation)
{
Process p = new Process();
// Create secure password
string prePassword = "myadminpwd";
SecureString passwordSecure = new SecureString();
char[] passwordChars = prePassword.ToCharArray();
foreach (char c in passwordChars)
{
passwordSecure.AppendChar(c);
}
// Set up the parameters to the process
p.StartInfo.FileName = #"C:\\Windows\\System32\cmd.exe";
p.StartInfo.Arguments = #" /C " + batchFileLocation;
p.StartInfo.LoadUserProfile = true;
p.StartInfo.UserName = "admin";
p.StartInfo.Password = passwordSecure;
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
// Run the process and wait for it to complete
p.Start();
p.WaitForExit();
}
In the 'Application' Event Viewer log on the server, every time I try to run this, the following issue seems to occur:
Faulting application cmd.exe, version 6.0.6001.18000, time stamp 0x47918bde, faulting module kernel32.dll, version 6.0.6001.18000, time stamp 0x4791a7a6, exception code 0xc0000142, fault offset 0x00009cac, process id 0x8bc,application start time 0x01cc0a67825eda4b.
UPDATE
The following code works fine (it runs the batch file):
Process p = new Process();
p.StartInfo.FileName = batchFileLocation;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation);
p.StartInfo.UseShellExecute = false;
// Run the process and wait for it to complete
p.Start();
p.WaitForExit();
This however doesn't (when i try to run as a specific user):
Process p = new Process();
// Create secure password
string prePassword = "adminpassword";
SecureString passwordSecure = new SecureString();
char[] passwordChars = prePassword.ToCharArray();
foreach (char c in passwordChars)
{
passwordSecure.AppendChar(c);
}
p.StartInfo.FileName = batchFileLocation;
p.StartInfo.WorkingDirectory = Path.GetDirectoryName(batchFileLocation);
p.StartInfo.UseShellExecute = false;
p.StartInfo.UserName = "admin";
p.StartInfo.Password = passwordSecure;
// Run the process and wait for it to complete
p.Start();
p.WaitForExit();
Just call the batch file directly:
p.StartInfo.FileName = batchFileLocation;
Also, make sure the WorkingDirectory is set to the right location:
p.StartInfo.WorkingDirectory= Path.GetDirectoryName(batchFileLocation);
A little google on "Faulting application cmd.exe" points me to this IIS forum.
It seems that you cannot create a new process in the background under IIS, unless you use the CreateProcessWithLogon method. (I have not tested this).

Need to find the length of audio file in minutes in asp.net

I have asp.net application in which i am uploading audio files by converting them into the stream and upload to the database.But not able to find the length of the audio file into minutes.Here problem is that my asp.net application is present in the cloud.For uploading i am using upload file control of asp.net.Please suggest solution for this.
You may look at taglib#
I would have expected that you can calculate this from the bit rate and the file length: (file.lenghtInBits / kbsp ) / 60 = minutes.
rather assumes that you can get the bit rate from the file header though.
You will need to reference Windows Media Player. Go to Com Add-ins to add the wmp.dll to your project.
string Duration = null;
WMPLib.WindowsMediaPlayer w = new WMPLib.WindowsMediaPlayer();
WMPLib.IWMPMedia mediaFile = w.newMedia(Filename);
if (mediaFile != null) {
Duration = mediaFile.durationString;
}
w.close();
You could use the NAudio library as suggested in this answer to a similar SO question.
We can do it easily by given below code
private string GetDuration(string FileFullPath)
{
string duration = "";
string fName = FileFullPath.Substring(FileFullPath.LastIndexOf("\\") + 1);
string filePath = FileFullPath.Substring(0, FileFullPath.LastIndexOf("\\"));
Shell32.Shell shell = new Shell32.ShellClass();
Shell32.Folder folder = shell.NameSpace(filePath);
Shell32.FolderItem folderItem = folder.ParseName(fName);
if (folderItem != null)
{
duration = folder.GetDetailsOf(folderItem, 21);
}
folderItem = null;
folder = null;
shell = null;
return duration;
}
TimeSpan span= GetWavFileDuration(filePath + "\" + fileName);
string spanSeconds = span.TotalSeconds.ToString();
string[] spanSecondsArray=spanSeconds.Split('.');
spanSeconds = spanSecondsArray[0].ToString();
public static TimeSpan GetWavFileDuration(string fileName) {
WaveFileReader wf = new WaveFileReader(fileName);
return wf.TotalTime;
}
You can use this library for getting the Audio file duration

ASP.NET Backgroundworkers for spreadsheet creation: multiple ones interfering with each other?

I am writing an ASP.NET application in which i need to create multiple excel reports. the report creation is pretty time-consuming (up to ten seconds for each) so i am using backgroundworkers to create them simultaneously.
My code looks a bit like this:
if (condition1)
{
excel_file_name = "TRANSFER";
BackgroundWorker worker_t = new BackgroundWorker();
worker_t.DoWork += new DoWorkEventHandler(DoWork);
worker_t.WorkerReportsProgress = false;
worker_t.WorkerSupportsCancellation = true;
worker_t.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
worker_t.RunWorkerAsync(excel_file_name);
}
if (Condition2)
{
excel_file_name = "NEFT";
BackgroundWorker worker_n = new BackgroundWorker();
worker_n.DoWork += new DoWorkEventHandler(DoWork);
worker_n.WorkerReportsProgress = false;
worker_n.WorkerSupportsCancellation = true;
worker_n.RunWorkerCompleted +=
new RunWorkerCompletedEventHandler(WorkerCompleted);
worker_n.RunWorkerAsync(excel_file_name);
}
there are more conditions but i haven't written them, since they are all similar. the only difference is the Excel_File_Name
the DoWork even then calls a class to create the excel files with the given name.
When condition1 and condition2 are both true, Here is the issue:
1. if i run this slowly using breakpoints during debugging, both files (TRANSFER and NEFT) are created.
2. if, however, i run it without breakpoints like a normal application, only the last file (NEFT in this example) is created.
What can be the issue?
Thanks
PS: For further information, here is the important code from the class that creates the excel file:
private static string placeDataInTemplate(string destFilePath, DataRow dr, bool isCoverLetter)
{
int loop = 0;
ExcelNamespace.Application excelApplication = new ExcelNamespace.Application();
ExcelNamespace.Workbook workbook = excelApplication.Workbooks.Open(destFilePath, 0, false, 5,
"", "", true, ExcelNamespace.XlPlatform.xlWindows, "\t", false, false, 0, true, true, false);
ExcelNamespace.Worksheet workSheet = (ExcelNamespace.Worksheet)workbook.Sheets[sheet_no];
try
{
string value;
string replicate;
string replicate_end;
// get data for Place Holders
sDataTable dtPlaceHolderData = getPlaceHolderData(dr);
//make Display Alerts False
excelApplication.DisplayAlerts = false;
if (dtPlaceHolderData != null && dtPlaceHolderData.Rows.Count > 0)
{
int rowCntDt = 0; //Which row will be used for data?
int i = 1;
Excel.Range Find = (ExcelNamespace.Range)workSheet.Cells.Find("#",
(ExcelNamespace.Range)workSheet.Cells[1, 1],
Excel.XlFindLookIn.xlValues,
Excel.XlLookAt.xlPart,
Excel.XlSearchOrder.xlByRows,
Excel.XlSearchDirection.xlNext,
false,
false,
Missing.Value);
while (Find != null && loop <= 200)
{
loop++;
value = Find.Value2.ToString();
if (condition)
//VERY long if...else if
}
string approveDirPath = destFilePath.Replace(Path.GetFileName(destFilePath), string.Empty);
workbook.Close(true, destFilePath, Type.Missing);
excelApplication.Quit();
string filepath = destFilePath.Split('-')[0];
string approval_id = dr[0].ToString();
return destFilePath;
}
return string.Empty;
}
catch (Exception ex)
{
//do something
}
finally
{
//release resources
}
NOTE: I have removed a lot of needless code. I can paste it if needed. Thank you
Most likely cause is some shared state between two threads - shared state may include excel application and workbooks. So you need to inspect your code for the same.
On the side note, instead of using Excel Automation to generate excel files, you may consider using some in-process library which would be perhaps more scalable and void of such issues. Have a look at one such free basic library at code project

Resources