I have to run two commands using Process in asp.net as given below and the first command runs successfully while running the second command gets hung at result = p.StandardOutput.ReadToEnd()
How to implement this to run both commands successfully?
private static string FFMPEG_EXE_PATH = #"D:\ffmpeg\bin\ffmpeg.exe";
private static string FFPROBE_EXE_PATH = #"D:\ffmpeg\bin\ffprobe.exe";
protected void Page_Load(object sender, EventArgs e)
{
string firstArgs = #"-hide_banner -show_format -show_streams -pretty D:\Video\dolbycanyon.m4v";
var result1 = Execute(FFPROBE_EXE_PATH, firstArgs);
string secondArgs = #"-hide_banner -ss 00:00:05 -i D:\Video\dolbycanyon.m4v -r 1 -t 1 -f image2 D:\Video\test.jpg";
var result2 = Execute(FFMPEG_EXE_PATH, secondArgs);
}
private string Execute(string exePath, string parameters)
{
string result = String.Empty;
using (Process p = new Process())
{
p.StartInfo.UseShellExecute = false;
p.StartInfo.CreateNoWindow = true;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = exePath;
p.StartInfo.Arguments = parameters;
p.Start();
result = p.StandardOutput.ReadToEnd(); // the application hung here for the second command
p.WaitForExit();
}
return result;
}
I have changed the Execute method to as below and it worked for both commands.
public string Execute(string path, string args, int timeoutMs)
{
using (var outputWaitHandle = new ManualResetEvent(false))
{
using (var process = new Process())
{
process.StartInfo = new ProcessStartInfo(path);
process.StartInfo.Arguments = args;
process.StartInfo.UseShellExecute = false;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.CreateNoWindow = true;
var sb = new StringBuilder(1024);
process.OutputDataReceived += (sender, e) =>
{
sb.AppendLine(e.Data);
if (e.Data == null)
{
outputWaitHandle.Set();
}
};
process.Start();
process.BeginOutputReadLine();
process.WaitForExit(timeoutMs);
outputWaitHandle.WaitOne(timeoutMs);
process.CancelOutputRead();
return sb.ToString();
}
}
}
Related
In the program.cs the user is asked if he wanna read the data, if he types y then the method Doc.ReadDoc starts is there any proper way:
class Program
{
static void Main(string[] args)
{
do
{
var path = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path + #"\TestFile.txt";
Console.WriteLine("Do you want to read it? y/n");
string yesorno = Console.ReadLine();
if (yesorno=="y")
{
Console.Clear();
Doc.ReadDoc();
}
Console.WriteLine("Which type of vehicle");
string type = Console.ReadLine();
Console.WriteLine("how many tires");
int raeder = Convert.ToInt32( Console.ReadLine());
var Vehicle = new Used_Cars(type, raeder);
Doc.Write(Vehicle);
} while (true);
}
}
The Class with the methods (Read, Write):
public static List<string> ReadDoc()
{
var list = new List<string>();
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
try
{
using (StreamReader sr = new StreamReader(fileName))
{
Console.WriteLine("Data found");
string line;
Console.WriteLine(sr.ReadToEnd());
}
}
catch (Exception e)
{
// Let the user know what went wrong.
Console.WriteLine("Data not found");
Console.WriteLine(e.Message);
list = null;
}
return list;
}
And the last Method is the Write method, is this a good code to save properties in a file? How could i stop the program with ESC or smth like that, so if the user presses ESC it should stop.
public static void Write(Used_Cars vehicle)
{
var pfad = "C:\\Users\\ks\\Desktop\\C#";
string fileName = path+ #"\TestFile.txt";
Console.WriteLine("Is it correct?");
Console.WriteLine("y/n");
string yeahorno= Console.ReadLine();
if (jaodernein == "y")
{
try
{
using (StreamWriter writer = new StreamWriter(fileName))
{
writer.WriteLine(vehicle.Vehicle);
writer.WriteLine(vehicle.Wheels);
Console.WriteLine();
}
}
catch (Exception exp)
{
Console.Write(exp.Message);
}
}
}
I am trying to download file from FTP using Webclient DownloadFileAsync method. i have used below code
private bool DownloadFileFromFtp()
{
try
{
MyWebClient client = new MyWebClient();
Uri ftpurl = new Uri("ftp://MyFtpserver/Filename.pdf");
client.Credentials = new NetworkCredential("Userid", "mypassword");
client.DownloadProgressChanged += Client_DownloadProgressChanged;
client.DownloadDataCompleted += Client_DownloadDataCompleted;
client.DownloadFileAsync(ftpurl, #"D:\RTP\Filename.pdf");
return true;
}
catch (Exception ex)
{
return false;
}
}
private void Client_DownloadProgressChanged(object sender, DownloadProgressChangedEventArgs e)
{
double bytesIn = double.Parse(e.BytesReceived.ToString());
double totalBytes = double.Parse(e.TotalBytesToReceive.ToString());
double percentage = bytesIn / totalBytes * 100;
lbldatareceived.Text = bytesIn + "/" + totalBytes;
lblPercentage.Text = percentage+"%";
FileProgress.Attributes.CssStyle.Add("width", Convert.ToString(percentage) + '%');
FileProgress.Attributes.Add("aria-valuenow", Convert.ToString(percentage));
}
private void Client_DownloadDataCompleted(object sender, DownloadDataCompletedEventArgs e)
{
throw new NotImplementedException();
}
When I run this code file download gets starts and browser start loading. How can I download files without loading a browser?
We are using SignalR for information exchange.
When the web browser is connected a timer starts, but it is not stopping when user close the browser.
Here is the code. starttimer function runs when browser connected.
When user disconnect the browser, timer still running on the server.
[HubName("myChatHub")]
public class InboundCallsDataShare : Hub
{
private OverrideTimer timer ;
private List<GroupNConnectionId> groupsList = new List<GroupNConnectionId>();
public void send(string message)
{
Clients.All.addMessage(message);
//Clients..addMessage(message);
}
public void starttimer(string queue)
{
//var connectionId = this.Context.ConnectionId;
//GroupNConnectionId objGroupNConnectionId=new GroupNConnectionId();
//objGroupNConnectionId.Group = queue;
//objGroupNConnectionId.ConnectionID = connectionId;
//if(groupsList.Contains(objGroupNConnectionId))return;
//////////////////////////////////////////////////////
//groupsList.Add(objGroupNConnectionId);
Groups.Add(this.Context.ConnectionId, queue);
timer = new OverrideTimer(queue);
timer.Interval = 15000;
timer.Elapsed +=new EventHandler<BtElapsedEventArgs>(timer_Elapsed);
//first time call
timer_Elapsed(timer,new BtElapsedEventArgs(){Queue = queue});
//ends
timer.Start();
Console.WriteLine("Timer for queue " +queue);
}
public override Task OnConnected()
{
return base.OnConnected();
}
public override Task OnDisconnected()
{
//timer.Stop();
return base.OnDisconnected();
}
public void getdatafromxml(string queue)
{
string list = (new Random()).Next(1, 10000).ToString();
Clients.All.getList(list);
//Clients..addMessage(message);
}
public ICBMObject GetInterationList(string queue)
{
//ININInterations.QueueListViewItemData _obj = new ININInterations.QueueListViewItemData();
return GetInboundCallCountFromXML(queue);
//return _obj.MainFunctionIB();
}
void timer_Elapsed(object sender, BtElapsedEventArgs e)
{
ICBMObject objICBMObject = GetInboundCallCountFromXML(e.Queue);
Clients.Group(e.Queue).getList(objICBMObject);
CreateFile(e.Queue);
//Clients.All.getList(objICBMObject);
}
private void CreateFile(string queue)
{
string path = #"D:\t.txt";
string text = File.ReadAllText(path);
text += queue+ DateTime.Now.ToString() + Environment.NewLine;
File.WriteAllText(path, text);
}
public ICBMObject GetInboundCallCountFromXML(string queue)
{
FileStream fs = null;
int totalInboundCalls = 0,
totalInboundCallsUnassigned = 0;
string longestDuration = "";
bool updateText = false;
try
{
XmlDataDocument xmldoc = new XmlDataDocument();
XmlNodeList xmlnode;
int i = 0;
string str = null;
fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "InboundXML/" + queue + ".xml",
FileMode.Open, FileAccess.Read);
if (fs.CanRead)
{
xmldoc.Load(fs);
xmlnode = xmldoc.GetElementsByTagName(queue);
for (i = 0; i <= xmlnode.Count - 1; i++)
{
totalInboundCalls = Convert.ToInt32(xmlnode[i].ChildNodes.Item(0).InnerText.Trim());
totalInboundCallsUnassigned = Convert.ToInt32(xmlnode[i].ChildNodes.Item(1).InnerText.Trim());
longestDuration = xmlnode[i].ChildNodes.Item(2).InnerText.Trim();
}
updateText = true;
}
}
catch (Exception)
{
}
finally
{
if (fs != null)
{
fs.Close();
fs.Dispose();
}
}
return new ICBMObject()
{
TotalInboundCalls = totalInboundCalls,
TotalInboundCallsUnassigned = totalInboundCallsUnassigned,
LongestDuration = longestDuration,
UpdateText = updateText
//string.Format("{0:D2}:{1:D2}:{2:D2}",
// _LongetInbound.Hours,
// _LongetInbound.Minutes,
// _LongetInbound.Seconds)
};
}
}
Besides the fact that its commented out? Did you put a break point on the timer to see if its getting hit at all? It might be that there is a delay in calling the onDisconnect, if the timeout property is set too large, it might not fire. it might be entering onReconnected if it does not know the client is closed.
I have problem during running external process from ASP.NET application.
The process is run as follows:
[WebMethod(EnableSession = true)]
[ScriptMethod(UseHttpGet = false, ResponseFormat = ResponseFormat.Json)]
public static WebResult generateSomething(string language)
{
ProcessStartInfo psi = new ProcessStartInfo();
psi.UseShellExecute = false;
psi.RedirectStandardError = true;
psi.RedirectStandardOutput = true;
psi.RedirectStandardInput = true;
psi.WindowStyle = ProcessWindowStyle.Hidden;
psi.CreateNoWindow = true;
psi.ErrorDialog = false;
psi.WorkingDirectory = Environment.CurrentDirectory;
psi.FileName = String.Format("\"{0}\"", Path.Combine(appDir, Properties.Settings.Default.PATH_TO_APP_TEXT));
psi.Arguments = arguments.ToString();
modeller.log.Info("Arguments: " + psi.Arguments);
var outputText = new StringBuilder();
int exitCode;
var result = new WebResult();
using (Process process = new Process())
{
process.StartInfo = psi;
process.OutputDataReceived += (sendingProcess, args) => { outputText.Append(args.Data); };
process.ErrorDataReceived += (sendingProcess, args) => { outputText.Append(args.Data); };
process.Start();
process.BeginOutputReadLine();
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
}
string outText = outputText.ToString();
Immediately after process finishes (succesfully or not) and the method leaves ASP.NET IIS session is ended, so any authentication context via cookie breaks.
Can anyone help with this issue?
Thanks in advance
In Tridion 2011 I want to use the Core Service equivalent of UpdateXml to create new Tridion objects in a generic way. I intend to create new Components, Pages and later on Folders and Structure Groups. It works quite well using UpdateXml but I am having a problem with casting the RepositoryLocalObject (or another generic-type object) to a ComponentData object with the Core Service. My Core Service code is much longer (and growing by the second).
Error message when I try to access on object-type specific property:
Error 9 'Tridion.ContentManager.CoreService.Client.RepositoryLocalObjectData' does not contain a definition for 'Content' and no extension method 'Content' accepting a first argument of type 'Tridion.ContentManager.CoreService.Client.RepositoryLocalObjectData'
Would a possible solution be to create an extension method?
Tridion TOM API:
Function CreateNewItemCopy(organizationalItemUri, itemType, title, xml,
directory, filename)
Dim newItem : set newItem = tdse.GetNewObject(itemType, organizationalItemUri)
newItem.UpdateXml(xml)
newItem.Title = title
if(itemType = 64) then ' page
newItem.FileName = filename
elseif(itemType = 4) then ' sg
newItem.Directory = directory
end if
newItem.save(true)
CreateNewItemCopy = newItem.id
set newItem = nothing
End Function
Tridion 2011 Core Service
*Updated Code Based on Excellent Answer Below
private ItemType GetTridionItemType(RepositoryLocalObjectData source)
{
string itemType = source.GetType().Name;
switch (itemType)
{
case "ComponentData":
return ItemType.Component;
case "PageData":
return ItemType.Page;
}
return ItemType.UnknownByClient;
}
private string CreateNewItemCopy(string title, RepositoryLocalObjectData source,
string filename)
{
ItemType tridionItemType = GetTridionItemType(source);
string orgItemUri = source.LocationInfo.OrganizationalItem.IdRef;
var newItem = client.Copy(source.Id, orgItemUri, true, new ReadOptions());
newItem.Title = title;
if (tridionItemType == ItemType.Page)
{
PageData pageData = newItem as PageData;
pageData.FileName = filename;
client.Update(pageData, new ReadOptions());
}
else
{
client.Update(newItem, new ReadOptions());
}
return newItem.Id;
}
*Original Code
private string CreateNewItemCopy(string title, RepositoryLocalObjectData source,
string filename)
{
string newItemUri = "";
try
{
ItemType tridionItemType = GetTridionItemType(source.Id);
string orgItemUri = source.LocationInfo.OrganizationalItem.IdRef;
if (tridionItemType == ItemType.Component)
{
ComponentData sourceComp = source as ComponentData;
ComponentData newComponent = client.GetDefaultData(tridionItemType,
orgItemUri) as ComponentData;
newComponent.Title = title;
newComponent.Metadata = source.Metadata;
// ** Only Component has .Content and SchemaRef
newComponent.Content = sourceComp.Content;
newComponent.Schema.IdRef = sourceComp.Schema.IdRef;
client.Create(newComponent, null);
newItemUri = newComponent.Id;
}
else if (tridionItemType == ItemType.Page)
{
PageData sourcePage = source as PageData;
PageData newPage = client.GetDefaultData(tridionItemType,
orgItemUri) as PageData;
newPage.Title = title;
newPage.Metadata = source.Metadata;
// ** Only Page has .Filename
newPage.FileName = filename;
client.Create(newPage, null);
newItemUri = newPage.Id;
}
else // I would really like to handle all things here - but have problems with
// item-specific mandatory properties, such as Schema, Filename, and Dir
{
var newGenericTridionItem = client.GetDefaultData(tridionItemType,
orgItemUri) as RepositoryLocalObjectData;
newGenericTridionItem.Title = title;
newGenericTridionItem.Metadata = source.Metadata;
//if(GetTridionItemType(newGenericTridionItem.Id) == ItemType.Page)
// newGenericTridionItem.filename;
client.Create(newGenericTridionItem, null);
newItemUri = newGenericTridionItem.Id;
}
}
catch (Exception ex)
{
throw;
}
return newItemUri;
}
private ItemType GetTridionItemType(string uri)
{
const int itemTypeComp = 16;
const int itemTypePage = 64;
const int itemTypeSG = 4;
const int itemTypeFolder = 2;
int itemTypeInt = GetTridionItemTypeId(uri);
switch (itemTypeInt)
{
case itemTypeComp:
return ItemType.Component;
break;
case itemTypePage:
return ItemType.Page;
break;
case itemTypeSG:
return ItemType.StructureGroup;
break;
case itemTypeFolder:
return ItemType.Folder;
break;
}
return ItemType.UnknownByClient;
}
private int GetTridionItemTypeId(string uri)
{
const int itemTypeComp = 16;
string[] uriParts = uri.Split('-');
if (uriParts.Length == 2) // comp, tcm:9-1234
{
return itemTypeComp;
}
else // other, tcm:9-456-64 for a page...
{
int itemTypeId = Int32.Parse(uriParts[2]);
return itemTypeId;
}
}
I have slightly adjusted your code and now it's working:
private string CreateNewItemCopy(string title, RepositoryLocalObjectData source, string filename)
{
string newItemUri = "";
try
{
ItemType tridionItemType = GetTridionItemType(source);
string orgItemUri = source.LocationInfo.OrganizationalItem.IdRef;
if (tridionItemType == ItemType.Component)
{
ComponentData sourceComp = source as ComponentData;
ComponentData newComponent = client.GetDefaultData(tridionItemType, orgItemUri) as ComponentData;
newComponent.Title = title;
newComponent.Metadata = source.Metadata;
// ** Only Component has .Content and SchemaRef
newComponent.Content = sourceComp.Content;
newComponent.Schema.IdRef = sourceComp.Schema.IdRef;
newItemUri = client.Create(newComponent, new ReadOptions()).Id;
}
else if (tridionItemType == ItemType.Page)
{
PageData sourcePage = source as PageData;
PageData newPage = client.GetDefaultData(tridionItemType, orgItemUri) as PageData;
newPage.Title = title;
newPage.Metadata = source.Metadata;
// ** Only Page has .Filename
newPage.FileName = filename;
newItemUri = client.Create(newPage, new ReadOptions()).Id;
}
else //I would really like to handle all things here - but have problems with item-specific mandatory properties, such as Schema, Filename, and Dir
{
var newGenericTridionItem = client.GetDefaultData(tridionItemType, orgItemUri) as RepositoryLocalObjectData;
newGenericTridionItem.Title = title;
newGenericTridionItem.Metadata = source.Metadata;
//if(GetTridionItemType(newGenericTridionItem.Id) == ItemType.Page)
// newGenericTridionItem.filename;
newItemUri = client.Create(newGenericTridionItem, new ReadOptions()).Id;
}
}
catch (Exception ex)
{
throw;
}
return newItemUri;
}
private ItemType GetTridionItemType(RepositoryLocalObjectData source)
{
string itemType = source.GetType().Name;
switch (itemType)
{
case "ComponentData":
return ItemType.Component;
case "PageData":
return ItemType.Page;
}
return ItemType.UnknownByClient;
}
But I still don't understand why do you want to do it this way and not use simple Copy method?