public override CommandOutput Execute(Dictionary <string, string> Parameters = null) { CommandOutput output = new CommandOutput(); string path = Path.GetFullPath(Parameters["Path"]); long length = new FileInfo(path).Length; output.Complete = true; // hard limit of 300mb for file uploads. Because of the b64 we have to do, this would inflate to like 500mb if (length > 314572800) { output.Message = $"File size of {length} is over the 300mb limit of uploads."; output.Success = false; } else { byte[] fileBytes = File.ReadAllBytes(path); output.Success = true; output.Message = $"{path} has been uploaded"; output.Type = "File"; output.Content = Convert.ToBase64String(fileBytes); output.ContentId = path; } return(output); }
private void Backup(string gameDataPath) { var savePath = EditorUtility.SaveFilePanel(Resources.UI_UNITYPLUGIN_INSPECTOR_BACKUP_BUTTON, Path.GetFullPath("./"), Path.GetFileName(gameDataPath), null); if (string.IsNullOrEmpty(savePath)) { return; } var format = default(string); switch (Path.GetExtension(savePath)) { case "gdml": format = "xml"; break; case "gdmp": format = "msgpack"; break; case "gdbs": format = "bson"; break; case "gdjs": format = "json"; break; default: format = Path.GetExtension(savePath); break; } CharonCli.BackupAsync(gameDataPath, CommandOutput.File(savePath, format)).ContinueWith(_ => this.Repaint()); }
public static string GetCommandOutputSimple(ProcessStartInfo info, bool returnErrorIfPopulated = true) { // Redirect the output stream of the child process. info.UseShellExecute = false; info.CreateNoWindow = true; info.RedirectStandardOutput = true; info.RedirectStandardError = true; var process = new Process(); process.StartInfo = info; process.ErrorDataReceived += ErrorDataHandler; process.OutputDataReceived += OutputDataHandler; var output = new CommandOutput(); Outputs.Add(process, output); process.Start(); process.BeginErrorReadLine(); process.BeginOutputReadLine(); // Wait for the process to finish reading from error and output before it is finished process.WaitForExit(); Outputs.Remove(process); if (returnErrorIfPopulated && (!String.IsNullOrWhiteSpace(output.Error))) { return(output.Error.TrimEnd('\n')); } return(output.Output.TrimEnd('\n')); }
public void RenderResults(CommandOutput output, CommandLineArgs args) { foreach (var renderer in GetRenderers(args)) { renderer.RenderOutput(output); } }
public static string RunGitCmd(string command, bool includeGitDir, CommandOutput outputDelegate) { string cmd = GetGitExePath(); string repoPath = GetRepoPath(); if (proc != null) { Debug.LogWarning("You must wait for previous processes to finish!"); return(""); } if (cmd != "") { ProcessStartInfo startInfo = new ProcessStartInfo(cmd); string result; proc = new Process(); if (includeGitDir) { command = "--git-dir=\"" + repoPath + "/.git\" --work-tree=\"" + repoPath + "\" " + command; } // startInfo.Arguments = "cd.. && cd.. && " + command; startInfo.Arguments = command; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; proc.StartInfo = startInfo; proc.Start(); if (outputDelegate == null) { StreamReader streamReader = proc.StandardOutput; while (!proc.HasExited) { Thread.Sleep(0); result = streamReader.ReadToEnd(); proc.Close(); proc = null; return(result); } } else { ThreadPool.QueueUserWorkItem(ThreadedUpdateProcess, outputDelegate); return("Threaded Process"); } } return("No Git.exe path defined!"); }
public static CommandOutput SetupCommandOutputMaps <TOutputType>(CommandStage stage, SettingsCollection settings, string fileName) where TOutputType : class, IContainer, new() { var settingsCopy = settings.Copy(); var commandOutput = CommandOutput.Create(Resource.CreateOutput <TOutputType>(), settingsCopy); stage.StreamIdentifiers.ForEach(streamId => { var theStream = StreamFromStreamIdentifier(stage.Command, streamId); var theResource = CommandInputFromStreamIdentifier(stage.Command, streamId); if (theResource == null) { commandOutput.Settings.Merge(new Map(streamId), FFmpegMergeOptionType.NewWins); } else { var resourceIndex = IndexOfResource(stage.Command, streamId); commandOutput.Settings.Merge(new Map(string.Format("{0}:{1}", resourceIndex, theStream.ResourceIndicator)), FFmpegMergeOptionType.NewWins); } commandOutput.Resource.Streams.Add(theStream.Copy()); }); if (!string.IsNullOrWhiteSpace(fileName)) { commandOutput.Resource.Name = fileName; } return(commandOutput); }
public override CommandOutput Execute(Dictionary <string, string> Parameters = null) { CommandOutput output = new CommandOutput(); string path = Path.GetFullPath(Parameters["Path"]); string type = "file"; // get the file attributes for file or directory FileAttributes attr = File.GetAttributes(path); //detect whether its a directory or file if ((attr & FileAttributes.Directory) == FileAttributes.Directory) { Directory.Delete(path, true); type = "directory"; } else { File.Delete(path); } output.Complete = true; output.Success = true; output.Message = $"Deleted {path}"; output.IOCs.Add(new IOC("file", path, "delete", $"Deleted {type} {path}")); return(output); }
public void CanRenderProblemsToHTMLFile(string relativeSlnPath) { var slnPath = TestPaths.GetVerifiedFileRelativeToProjectDir(relativeSlnPath); var solution = DIRegistrar.GetInstance <ISolutionReader>().ReadSolution(slnPath); var problemDetector = DIRegistrar.GetInstance <ProblemDetectorService>(); var problems = problemDetector.DetectAllSolutionProblems(solution); var outFile = new FileInfo("testout.html"); if (outFile.Exists) { outFile.Delete(); } var renderer = new HTMLProblemRenderer(outFile); var output = new CommandOutput(); output.DetectedProblems.AddRange(problems); renderer.RenderOutput(output); var fileText = File.ReadAllText(outFile.FullName); Assert.That(fileText.Contains(@"<span class='Highlighted'>Newtonsoft.Json</span>")); }
private void PrintDialogTitle(string title) { CommandOutput batch = new CommandOutput(); batch.NameOfAnalysis = "Open R package dataset"; batch.IsFromSyntaxEditor = false; batch.Insert(0, new BSkyOutputOptionsToolbar()); string rcommcol = confService.GetConfigValueForKey("dctitlecol");//23nov2012 //before was syntitlecol byte red = byte.Parse(rcommcol.Substring(3, 2), NumberStyles.HexNumber); byte green = byte.Parse(rcommcol.Substring(5, 2), NumberStyles.HexNumber); byte blue = byte.Parse(rcommcol.Substring(7, 2), NumberStyles.HexNumber); Color c = Color.FromArgb(255, red, green, blue); AUParagraph aup = new AUParagraph(); aup.Text = title; // dialogTitle; aup.FontSize = BSkyStyler.BSkyConstants.HEADER_FONTSIZE; //16;// before it was 16 aup.FontWeight = FontWeights.DemiBold; aup.textcolor = new SolidColorBrush(c); //Colors.Blue);//SlateBlue //DogerBlue aup.ControlType = "Title"; batch.Add(aup); SyntaxEditorWindow sewindow = LifetimeService.Instance.Container.Resolve <SyntaxEditorWindow>(); sewindow.AddToSession(batch); }
private void Update() { string line; while (m_Commands.TryDequeue(out line)) { CommandOutput?.Invoke(line); AnyOutput?.Invoke(line); } while (m_StandardOutput.TryDequeue(out line)) { StandardOutput?.Invoke(line); AnyOutput?.Invoke(line); } while (m_ErrorOutput.TryDequeue(out line)) { ErrorOutput?.Invoke(line); AnyOutput?.Invoke(line); } if (HasFinished) { EditorApplication.update -= Update; AssemblyReloadEvents.beforeAssemblyReload -= AssemblyReload; Completed?.Invoke(this); } ; }
public override CommandOutput Execute(Dictionary <string, string> Parameters = null) { CommandOutput output = new CommandOutput(); string path = Path.GetFullPath(Parameters["Path"]); #if DEBUG Console.WriteLine($"[Download Command] Got path: {path}"); #endif string content = Parameters["File"]; byte[] bytes = Convert.FromBase64String(content); File.WriteAllBytes(path, bytes); FileStream fop = File.OpenRead(path); fop.Position = 0; byte[] hash = System.Security.Cryptography.SHA1.Create().ComputeHash(fop); string hashString = ""; for (int i = 0; i < hash.Length; i++) { hashString += String.Format("{0:X2}", hash[i]); } #if DEBUG Console.WriteLine($"[Download Command] File downloaded. Hash: {hashString}"); #endif output.Complete = true; output.Success = true; output.Message = $"File written to {path}"; output.IOCs.Add(new IOC("file", path, "create", $"Downloaded file to {path}", hashString)); return(output); }
void EmitSingle(CommandOutput output) { base.EmitSingle(output); tempPage.Add(output); displayPageIndicator( ); }
private static void Main(string[] args) { Console.WriteLine($"Version: {Assembly.GetExecutingAssembly().GetName().Version}"); Console.WriteLine("Map data folder found: {0}", GamePath.GetMapStudioPath()); Console.WriteLine(); CommandOutput.InputHelp(); string command; while (true) { Console.Write("\nInput>>"); command = Console.ReadLine(); Console.WriteLine("Processing, DONT QUIT"); if (CommandInput.Command(command)) { Console.Write("Operation finished!"); } else { Console.Write("Check out the input, something is wrong"); } Console.Write(" Press \'r\' to do other operations\n"); Console.WriteLine("Press other keys to exit, and remember to use UXM to patch if any changes have taken place"); if (Console.ReadKey().Key != ConsoleKey.R) { break; } } }
public override CommandOutput Execute(Dictionary <string, string> Parameters = null) { CommandOutput output = new CommandOutput(); output.Complete = true; output.Success = true; string task_id = ""; if (Parameters.ContainsKey("Kill")) { task_id = Parameters["Kill"]; } try { if (!String.IsNullOrEmpty(task_id) && Parameters.ContainsKey("Kill")) { RunningTask task = State.RunningTasks.Find(x => x.Id == task_id); task.CancellationTokenSource.Cancel(); output.Message = $"Requested task {task_id} to cancel"; } else { output.Message = JsonConvert.SerializeObject(State.RunningTasks); } } catch (Exception e) { output.Complete = true; output.Success = false; output.Message = e.Message; } return(output); }
public override CommandOutput Execute(Dictionary <string, string> Parameters = null) { CommandOutput output = new CommandOutput(); List <ServiceObject> results = new List <ServiceObject>(); string ComputerName = "localhost"; if (Parameters.ContainsKey("ComputerName")) { ComputerName = Parameters["ComputerName"]; } ServiceController[] services = ServiceController.GetServices(ComputerName); foreach (ServiceController sc in services) { ServiceObject result = new ServiceObject(); result.Name = sc.ServiceName; result.DisplayName = sc.DisplayName; result.Status = sc.Status.ToString(); results.Add(result); } output.Message = JsonConvert.SerializeObject(results); output.Success = true; output.Complete = true; return(output); }
void cb_Checked(object sender, RoutedEventArgs e) { CheckBox cb = sender as CheckBox; CommandOutput tag = cb.Tag as CommandOutput; if (cb.IsChecked == true) { tag.SelectedForDump = true; // dump this analysis } else { tag.SelectedForDump = false; } if (cb != null) { TreeViewItem tvparentnode = (TreeViewItem)cb.Parent; StackPanel leafnodesp; CheckBox leafcb; foreach (TreeViewItem tvi in tvparentnode.Items) { leafnodesp = (StackPanel)tvi.Header; leafcb = (CheckBox)leafnodesp.Children[0]; leafcb.IsChecked = cb.IsChecked; } } }
public void Command_OutputManager_Verify() { var command = CommandHelper.CreateCommand(); Assert.Throws <ArgumentNullException>(() => command.OutputManager.Add(null)); Assert.Throws <ArgumentException>(() => command.OutputManager.AddRange(null)); Assert.DoesNotThrow(() => command.OutputManager.Add(CommandOutput.Create(Resource.From(AssetPath)))); var assetsList = new List <IContainer> { Resource.From(AssetPath), Resource.From(AssetPath) }; var commandList = new List <CommandOutput> { CommandOutput.Create(assetsList[0]), CommandOutput.Create(assetsList[1]) }; Assert.DoesNotThrow(() => command.OutputManager.AddRange(commandList)); Assert.True(command.Outputs.Count == 3); }
public CommandOutput OnExecute(CommandInput arguments) { var output = new CommandOutput { PostAction = CommandOutput.PostCommandAction.None }; long suiteId = -1; long userId = arguments.GetUserId(); long.TryParse(arguments["sid"], out suiteId); var name = arguments["name"]; List <ParameterModel> listOfParams = new List <ParameterModel>(); if (suiteId != -1) { listOfParams = CurrentHostContext.Default.Provider.ConfigurationStore.GetParametersLike(userId, suiteId, name); } else { output.DisplayMessage = "No such suite id exists: " + suiteId; output.PostAction = CommandOutput.PostCommandAction.ShowCommandHelp; output.MessageType = CommandOutput.DisplayMessageType.Error; } if (listOfParams.Count > 0) { var pk = arguments["pk"]; if (pk != null) { var suite = CurrentHostContext.Default.Provider.ConfigurationStore.GetSuite(userId, suiteId); if (suite.PublicKey.Equals(pk, StringComparison.InvariantCulture)) { listOfParams.ForEach( x => { x.ParameterValue = EncryptionEngine.Default.Decrypt(x.ParameterValue, suite.PrivateKey, null); }); } else { output.DisplayMessage = "Invalid combination of Private / Public Key to decrypt ParameterValue"; output.MessageType = CommandOutput.DisplayMessageType.Error; return(output); } } output.Data = listOfParams; output.DisplayMessage = "Success"; } else { output.DisplayMessage = DoesNotExist; output.MessageType = CommandOutput.DisplayMessageType.Error; } return(output); }
internal static CommandOutput Execute(string command, string workingDirectory, int timeoutMS = 10000, int limitSeconds = 30, bool redirectInput = false) { ProcessStartInfo processInfo = new ProcessStartInfo("cmd.exe", "/s /c \"" + command + "\"") { WorkingDirectory = workingDirectory, CreateNoWindow = true, UseShellExecute = false, RedirectStandardError = true, RedirectStandardOutput = true, RedirectStandardInput = redirectInput }; Process process = Process.Start(processInfo); TimeSpan T = new TimeSpan(), limit = new TimeSpan(0, 0, limitSeconds); DateTime start = DateTime.Now; string output = ""; if (process == null) { return new CommandOutput { error = "Command process could not be created.", exitCode = 1, output = "Command process could not be created." } } ; process.WaitForExit(timeoutMS); //Timeout 10 sec. if (DateTime.Now - start >= TimeSpan.FromMilliseconds(timeoutMS)) { start = DateTime.Now; string oStream = "", nOutStream = ""; while (T < limit) { if (!oStream.Equals(nOutStream)) { start = DateTime.Now; } T = DateTime.Now - start; oStream = nOutStream; nOutStream = process.StandardOutput.ReadToEnd(); output += nOutStream; } } CommandOutput co = new CommandOutput { output = String.IsNullOrEmpty(output) ? process.StandardOutput.ReadToEnd() : output, error = process.StandardError.ReadToEnd(), exitCode = process.ExitCode }; return(co); } }
public static MetadataInfoTreeGroup Create(FFmpegCommand command, CommandOutput commandOutput) { var metadataInfoTreeGroup = new MetadataInfoTreeGroup(commandOutput.Settings); metadataInfoTreeGroup.Fill(command, commandOutput); return metadataInfoTreeGroup; }
/// <summary> /// Append a command to the list of commands for a given output controller. /// </summary> public void AddCommand(CommandOutput commandOutput) { if (!_outputStateList.ContainsKey(commandOutput.Id)) { _AddOutput(commandOutput); } _outputStateList[commandOutput.Id].Add(commandOutput.Command); }
public static MetadataInfoTreeGroup Create(FFmpegCommand command, CommandOutput commandOutput) { var metadataInfoTreeGroup = new MetadataInfoTreeGroup(commandOutput.Settings); metadataInfoTreeGroup.Fill(command, commandOutput); return(metadataInfoTreeGroup); }
public static void SaveAsPDFAllAnalyisOuput(ObservableCollection <AnalyticsData> DataList, string fullpathzipcsvhtmfilename) { int imgnamecounter = 0; List <string> filelist = new List <string>(); bool extratags = false; bool fileExists = File.Exists(fullpathzipcsvhtmfilename); double left, top, right, bottom; GetPDFpageMargins(strPDFPageMargin, out left, out top, out right, out bottom); //Creating a PDF doc to which we will add PDFTables MigraDoc.DocumentObjectModel.Document Doc = new MigraDoc.DocumentObjectModel.Document(); MigraDoc.DocumentObjectModel.Tables.Table pdfTable; //Set Page margins from configuration Doc.DefaultPageSetup.LeftMargin = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(left); //left margin Doc.DefaultPageSetup.TopMargin = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(top); //top margin Doc.DefaultPageSetup.RightMargin = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(right); //right margin Doc.DefaultPageSetup.BottomMargin = MigraDoc.DocumentObjectModel.Unit.FromMillimeter(bottom); //bottom margin Doc.AddSection(); //////// looping thru all analysis one by one ////// foreach (AnalyticsData analysisdata in DataList) { //03Aug2012 ICommandAnalyser analyser = CommandAnalyserFactory.GetClientAnalyser(analysisdata); CommandOutput output = analysisdata.Output; // getting refrence of already generated objects. SessionOutput sessionoutput = analysisdata.SessionOutput; //27Nov2013 if there is session output if (output != null) { output.NameOfAnalysis = analysisdata.AnalysisType;//For Parent Node name 02Aug2012 } if (sessionoutput != null) { sessionoutput.NameOfSession = analysisdata.AnalysisType; } /////// dumping output // if (output != null) { ExportOutputPDF(output, Doc, extratags, filelist); } else if (sessionoutput != null) { foreach (CommandOutput cout in sessionoutput) { ExportOutputPDF(cout, Doc, extratags, filelist, true); } } } ////rendering doc MigraDoc.Rendering.PdfDocumentRenderer docrender = new MigraDoc.Rendering.PdfDocumentRenderer(false); docrender.Document = Doc; docrender.RenderDocument(); docrender.PdfDocument.Save(fullpathzipcsvhtmfilename); }
internal static bool TryFromResult(CommandOutput result, out IPastJob pastJob) { pastJob = null; if (result != null && result.Status == CommandStatus.Completed && result.Started.HasValue) { pastJob = new PastJob(result); } return(pastJob != null); }
public void Execute(JukeClient client, CommandOutput output, string[] arguments) { if (arguments.Length < 1) { output.WriteError("Missing song title param"); return; } output.WriteMessage("Enqueueing " + arguments[0]); client.Play(arguments[0]); }
private void Execute_Click(object sender, EventArgs e) { CommandOutput.AppendText("\n>>>" + CommandInput.Text + "\n"); CommandOutput.AppendText(DbInterpretter.Execute(CommandInput.Text) + '\n'); CommandInput.Clear(); if (!DbInterpretter.isRunning) { Close(); } UpdateDbInfo(); }
/// <summary> /// when user releases button for a given command /// </summary> /// <param name="cmd"></param> internal void keyUpCommand(CommandOutput cmd) { if (cmd == CommandOutput.Left || cmd == CommandOutput.Right) { this.AngularV = 0; } if (cmd == CommandOutput.Thrust) { this.IsThrust = false; } }
private void RenderOutput(CommandOutput output, TContext context) { BeginReport(context); RenderMessages(context, output.Messages); if (output.CorrectedProblems.Any()) { RenderProblems(context, "Corrected Problems", output.CorrectedProblems); } RenderProblems(context, "Detected Problems", output.DetectedProblems); EndReport(context); }
public static JsonServiceCommandOutput ConvertForJson(this CommandOutput commandOutput) { var output = new JsonServiceCommandOutput { Data = commandOutput.Data.ToJsonUnIndented(), DisplayMessage = commandOutput.DisplayMessage, MessageType = commandOutput.MessageType }; return(output); }
public static NativeServiceCommandOutput ConvertForNative(this CommandOutput commandOutput) { var output = new NativeServiceCommandOutput { Data = commandOutput.Data, DisplayMessage = commandOutput.DisplayMessage, MessageType = commandOutput.MessageType }; return(output); }
public IDataFlowComponent GetAdapter(CommandOutput output) { CommandOutputDataFlowAdapter adapter; if (!_instances.TryGetValue(output.Id, out adapter)) { adapter = new CommandOutputDataFlowAdapter(output); _instances[output.Id] = adapter; } return(adapter); }
public void Add(CommandOutput output) { if (output == null) { throw new ArgumentNullException("output"); } output.Owner = Owner; if (Owner.Objects.ContainsOutput(output)) { throw new ArgumentException("Cannot add the same command output twice to command.", "output"); } Owner.Objects.Outputs.Add(output); }
private void Fill(FFmpegCommand command, CommandOutput commandOutput) { //find the command output map setting, if the command output has map settings //then they make up its dependecy tree. var allSettingMaps = commandOutput.Settings.OfType<Map>(); if (allSettingMaps.Any()) { var streamIdListFromMaps = allSettingMaps.Select(map => StreamIdentifier.Create(command.Owner.Id, command.Id, map.Stream)).ToList(); Fill(command, streamIdListFromMaps); return; } //if the command output does not contain map settings then the dependency tree //is made up of all the input streams. command.Objects.Inputs.ForEach(commandResource => DependecyTree.Add(MetadataInfoTreeSource.Create(commandResource))); }
public CommandOutput Decode(AnalyticsData analysisdata) { CommandOutput op = new CommandOutput(); Paragraph Title = new Paragraph(); OutputHelper.AnalyticsData = analysisdata; OutputReader reader = new OutputReader(); if (analysisdata.Result.CommandString != null && analysisdata.Result.CommandString.Contains("UAloadDataset")) { reader.Hdr = "Open Dataset"; //21Oct2013 } else { reader.Hdr = analysisdata.Result.CommandString; } List<DependencyObject> objs = reader.GetOutput(analysisdata.OutputTemplate); op.AddRange(objs); return op; }
private void RDotNetExecute(OutputWindow ow) { CommandOutput lst = new CommandOutput(); lst.IsFromSyntaxEditor = true; engine.Evaluate("BSky_One_Way_Anova = as.data.frame (summary(dd <- aov(mpg ~ year,data=Dataset1))[[1]])"); engine.Evaluate("bskyfrmtobj <- BSkyFormat(BSky_One_Way_Anova)"); CharacterMatrix cmatrix = engine.Evaluate("bskyfrmtobj").AsCharacterMatrix(); string[,] mtx = new string[cmatrix.RowCount, cmatrix.ColumnCount]; for (int r = 0; r < cmatrix.RowCount; r++) { for (int c = 0; c < cmatrix.ColumnCount; c++) { mtx[r, c] = cmatrix[r, c]; } } string objectname = "bskyfrmtobj"; string headername = "This is generated in R.NET"; CommandRequest cmddf = new CommandRequest(); int dimrow = 1, dimcol = 1; bool rowexists = false, colexists = false; string dataclassname = string.Empty; //Find class of data passed. data.frame, matrix, or array cmddf.CommandSyntax = "class(" + objectname + ")"; // Row exists object retres = engine.Evaluate(cmddf.CommandSyntax).AsCharacter()[0]; if (retres != null) dataclassname = retres.ToString(); //find if dimension exists cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[1])"; // Row exists rowexists = engine.Evaluate(cmddf.CommandSyntax).AsLogical()[0]; cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[2])";// Col exists colexists = engine.Evaluate(cmddf.CommandSyntax).AsLogical()[0]; /// Find size of matrix(objectname) & initialize data array /// if (rowexists) { cmddf.CommandSyntax = "dim(" + objectname + ")[1]"; retres = engine.Evaluate(cmddf.CommandSyntax).AsInteger()[0]; if (retres != null) dimrow = Int16.Parse(retres.ToString()); } if (colexists) { cmddf.CommandSyntax = "dim(" + objectname + ")[2]"; retres = engine.Evaluate(cmddf.CommandSyntax).AsInteger()[0]; if (retres != null) dimcol = Int16.Parse(retres.ToString()); } string[,] data = new string[dimrow, dimcol]; //// now create FlexGrid and add to lst /// /////////finding Col headers ///// cmddf.CommandSyntax = "colnames(" + objectname + ")"; CharacterVector colhdrobj = engine.Evaluate(cmddf.CommandSyntax).AsCharacter(); string[] colheaders; if (colhdrobj != null && !colhdrobj.ToString().Contains("Error")) { if (true)//colhdrobj.GetType().IsArray) { int siz = colhdrobj.Count(); colheaders = new string[siz]; for (int ri = 0; ri < siz; ri++) { colheaders[ri] = colhdrobj[ri]; } } else { colheaders = new string[1]; colheaders[0] = colhdrobj.ToString(); } } else { colheaders = new string[dimcol]; for (int i = 0; i < dimcol; i++) colheaders[i] = (i + 1).ToString(); } /////////finding Row headers ///// //read configuration and then decide to pull row headers bool shownumrowheaders = true; /// cmddf.CommandSyntax = "rownames(" + objectname + ")"; CharacterVector rowhdrobj = engine.Evaluate(cmddf.CommandSyntax).AsCharacter(); string[] rowheaders;// = (string[])rowhdrobj;//{ "11", "22", "33" }; if (rowhdrobj != null && !rowhdrobj.ToString().Contains("Error")) { if (true)//rowhdrobj.GetType().IsArray) { int siz = rowhdrobj.Count(); rowheaders = new string[siz]; for (int ri = 0; ri < siz; ri++) { rowheaders[ri] = rowhdrobj[ri]; } //rowheaders = (string[])rowhdrobj;//{ "Aa", "Bb", "Cc" };// } else { rowheaders = new string[1]; rowheaders[0] = rowhdrobj.ToString(); } } else { rowheaders = new string[dimrow]; //Type 1.//filling number for row header if rowheader is not present for (int i = 0; i < dimrow; i++) rowheaders[i] = (i + 1).ToString(); } bool isnumericrowheaders = true; // assuming that row headers are numeric short tnum; for (int i = 0; i < dimrow; i++) { if (!Int16.TryParse(rowheaders[i], out tnum)) { isnumericrowheaders = false; //row headers are non-numeric break; } //if (i == 10)//just cheking first 10 numbers for being int. Not cheking all the row headers. // break; } if (isnumericrowheaders && !shownumrowheaders) { //Type 2.//filling empty values for row header if rowheader is not present for (int i = 0; i < dimrow; i++) rowheaders[i] = ""; } /// Populating array using data frame data bool isRowEmpty = true;//for Virtual. int emptyRowCount = 0;//for Virtual. List<int> emptyRowIndexes = new List<int>(); //for Virtual. string cellData = string.Empty; for (int r = 1; r <= dimrow; r++) { isRowEmpty = true;//for Virtual. for (int c = 1; c <= dimcol; c++) { if (dimcol == 1 && !dataclassname.ToLower().Equals("data.frame")) cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "])"; else cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "," + c + "])"; object v = engine.Evaluate(cmddf.CommandSyntax).AsCharacter()[0]; cellData = (v != null) ? v.ToString().Trim() : ""; data[r - 1, c - 1] = cellData;// v.ToString().Trim(); //for Virtual. // cell is non-empty in row, means row is non empty because of atleast 1 col if (cellData.Length > 0) isRowEmpty = false; } //for Virtual. // counting empty rows for virtual if (isRowEmpty) { emptyRowCount++; emptyRowIndexes.Add(r - 1);//making it zero based as in above nested 'for' } } // whether you want C1Flexgrid to be generated by using XML DOM or by Virtual class(Dynamic) bool DOMmethod = false; if (DOMmethod) { //12Aug2014 Old way of creating grid using DOM and then creating and filling grid step by step XmlDocument xdoc = createFlexGridXmlDoc(colheaders, rowheaders, data); //string xdoc = "<html><body><table><thead><tr><th class=\"h\"></th><th class=\"c\">A</th><th class=\"c\">B</th></tr></thead><tbody><tr><td class=\"h\">X</td><td class=\"c\">5</td><td class=\"c\">6</td></tr><tr><td class=\"h\">Y</td><td class=\"c\">8</td><td class=\"c\">9</td></tr></tbody></table></body></html>"; createFlexGrid(xdoc, lst, headername);// headername = 'varname' else 'leftvarname' else 'objclass' } else//virutal list method { //There is no logic to remove empty rows in this vitual list method so //here we try to send data with non-empty rows by dropping empty ones first. if (emptyRowCount > 0) { int nonemptyrowcount = dimrow - emptyRowCount; string[,] nonemptyrowsdata = new string[nonemptyrowcount, dimcol]; string[] nonemptyrowheaders = new string[nonemptyrowcount]; for (int rr = 0, rrr = 0; rr < data.GetLength(0); rr++) { if (emptyRowIndexes.Contains(rr))//skip empty rows. continue; for (int cc = 0; cc < data.GetLength(1); cc++) { nonemptyrowsdata[rrr, cc] = data[rr, cc];//only copy non-empty rows } nonemptyrowheaders[rrr] = rowheaders[rr];//copying row headers too. rrr++; } //Using Dynamic Class creation and then populating the grid. //12Aug2014 CreateDynamicClassFlexGrid(headername, colheaders, nonemptyrowheaders, nonemptyrowsdata, lst); } else { //Using Dynamic Class creation and then populating the grid. //12Aug2014 CreateDynamicClassFlexGrid(headername, colheaders, rowheaders, data, lst); } } if (ow != null)//22May2014 SendToOutput("", ref lst, ow);//send dataframe/matrix/array to output window or disk file }
public TestCommandRuntime() { Output = new CommandOutput(); }
//pulled out from ExecuteBSkyFromatCommand() method above. For BskyFormat DataFrame Matrix Array private void BSkyFormatDFMtxArr(CommandOutput lst, string objectname, string headername, OutputWindow ow) { CommandRequest cmddf = new CommandRequest(); int dimrow = 1, dimcol = 1; bool rowexists = false, colexists = false; string dataclassname = string.Empty; //Find class of data passed. data.frame, matrix, or array cmddf.CommandSyntax = "class(" + objectname + ")"; // Row exists object retres = analytics.ExecuteR(cmddf, true, false); if (retres != null) dataclassname = retres.ToString(); //find if dimension exists cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[1])"; // Row exists retres = analytics.ExecuteR(cmddf, true, false); if (retres != null && retres.ToString().ToLower().Equals("true")) rowexists = true; cmddf.CommandSyntax = "!is.na(dim(" + objectname + ")[2])";// Col exists retres = analytics.ExecuteR(cmddf, true, false); if (retres != null && retres.ToString().ToLower().Equals("true")) colexists = true; /// Find size of matrix(objectname) & initialize data array /// if (rowexists) { cmddf.CommandSyntax = "dim(" + objectname + ")[1]"; retres = analytics.ExecuteR(cmddf, true, false); if (retres != null) dimrow = Int16.Parse(retres.ToString()); } if (colexists) { cmddf.CommandSyntax = "dim(" + objectname + ")[2]"; retres = analytics.ExecuteR(cmddf, true, false); if (retres != null) dimcol = Int16.Parse(retres.ToString()); } string[,] data = new string[dimrow, dimcol]; //// now create FlexGrid and add to lst /// /////////finding Col headers ///// cmddf.CommandSyntax = "colnames(" + objectname + ")"; object colhdrobj = analytics.ExecuteR(cmddf, true, false); string[] colheaders; if (colhdrobj != null && !colhdrobj.ToString().Contains("Error")) { if (colhdrobj.GetType().IsArray) colheaders = (string[])colhdrobj;//{ "Aa", "Bb", "Cc" };// else { colheaders = new string[1]; colheaders[0] = colhdrobj.ToString(); } } else { colheaders = new string[dimcol]; for (int i = 0; i < dimcol; i++) colheaders[i] = (i + 1).ToString(); } /////////finding Row headers ///// //read configuration and then decide to pull row headers string numrowheader = confService.AppSettings.Get("numericrowheaders"); // load default value if no value is set if (numrowheader.Trim().Length == 0) numrowheader = confService.DefaultSettings["numericrowheaders"]; bool shownumrowheaders = numrowheader.ToLower().Equals("true") ? true : false; /// cmddf.CommandSyntax = "rownames(" + objectname + ")"; object rowhdrobj = analytics.ExecuteR(cmddf, true, false); string[] rowheaders;// = (string[])rowhdrobj;//{ "11", "22", "33" }; if (rowhdrobj != null && !rowhdrobj.ToString().Contains("Error")) { if (rowhdrobj.GetType().IsArray) rowheaders = (string[])rowhdrobj;//{ "Aa", "Bb", "Cc" };// else { rowheaders = new string[1]; rowheaders[0] = rowhdrobj.ToString(); } } else { rowheaders = new string[dimrow]; //Type 1.//filling number for row header if rowheader is not present for (int i = 0; i < dimrow; i++) rowheaders[i] = (i + 1).ToString(); } bool isnumericrowheaders = true; // assuming that row headers are numeric short tnum; for (int i = 0; i < dimrow; i++) { if (!Int16.TryParse(rowheaders[i], out tnum)) { isnumericrowheaders = false; //row headers are non-numeric break; } } if (isnumericrowheaders && !shownumrowheaders) { //Type 2.//filling empty values for row header if rowheader is not present for (int i = 0; i < dimrow; i++) rowheaders[i] = ""; } /// Populating array using data frame data bool isRowEmpty = true;//for Virtual. int emptyRowCount = 0;//for Virtual. List<int> emptyRowIndexes = new List<int>(); //for Virtual. string cellData = string.Empty; for (int r = 1; r <= dimrow; r++) { isRowEmpty = true;//for Virtual. for (int c = 1; c <= dimcol; c++) { if (dimcol == 1 && !dataclassname.ToLower().Equals("data.frame")) cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "])"; else cmddf.CommandSyntax = "as.character(" + objectname + "[" + r + "," + c + "])"; object v = analytics.ExecuteR(cmddf, true, false); cellData = (v != null) ? v.ToString().Trim() : ""; data[r - 1, c - 1] = cellData;// v.ToString().Trim(); //for Virtual. // cell is non-empty in row, means row is non empty because of atleast 1 col if (cellData.Length > 0) isRowEmpty = false; } //for Virtual. // counting empty rows for virtual if (isRowEmpty) { emptyRowCount++; emptyRowIndexes.Add(r - 1);//making it zero based as in above nested 'for' } } // whether you want C1Flexgrid to be generated by using XML DOM or by Virtual class(Dynamic) bool DOMmethod = false; if (DOMmethod) { //12Aug2014 Old way of creating grid using DOM and then creating and filling grid step by step XmlDocument xdoc = createFlexGridXmlDoc(colheaders, rowheaders, data); //string xdoc = "<html><body><table><thead><tr><th class=\"h\"></th><th class=\"c\">A</th><th class=\"c\">B</th></tr></thead><tbody><tr><td class=\"h\">X</td><td class=\"c\">5</td><td class=\"c\">6</td></tr><tr><td class=\"h\">Y</td><td class=\"c\">8</td><td class=\"c\">9</td></tr></tbody></table></body></html>"; createFlexGrid(xdoc, lst, headername);// headername = 'varname' else 'leftvarname' else 'objclass' } else//virutal list method { //There is no logic to remove empty rows in this vitual list method so //here we try to send data with non-empty rows by dropping empty ones first. if (emptyRowCount > 0) { int nonemptyrowcount = dimrow - emptyRowCount; string[,] nonemptyrowsdata = new string[nonemptyrowcount, dimcol]; string[] nonemptyrowheaders = new string[nonemptyrowcount]; for (int rr = 0, rrr = 0; rr < data.GetLength(0); rr++) { if (emptyRowIndexes.Contains(rr))//skip empty rows. continue; for (int cc = 0; cc < data.GetLength(1); cc++) { nonemptyrowsdata[rrr, cc] = data[rr, cc];//only copy non-empty rows } nonemptyrowheaders[rrr] = rowheaders[rr];//copying row headers too. rrr++; } //Using Dynamic Class creation and then populating the grid. //12Aug2014 CreateDynamicClassFlexGrid(headername, colheaders, nonemptyrowheaders, nonemptyrowsdata, lst); } else { //Using Dynamic Class creation and then populating the grid. //12Aug2014 CreateDynamicClassFlexGrid(headername, colheaders, rowheaders, data, lst); } } if (ow != null)//22May2014 SendToOutput("", ref lst, ow);//send dataframe/matrix/array to output window or disk file }
//18Nov2013 Add BSky OSMT and CrossTab to Session. This output is return back from OutputWindow public void AddToSession(CommandOutput co) { if (co != null && co.Count > 0) { sessionlst.Add(co); co = new CommandOutput();//after adding to session new object is allocated for futher output creation } }
// reading back sink file and creating & displaying output; for non-BSkyFormat commands private void CreateOuput(OutputWindow ow) { if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Started creating output.", LogLevelEnum.Info); //////////////////// for fetching BSkyFormat object Queue and process each object ////////////////////// int bskyformatobjectindex = 0; bool bskyQFetched = false; CommandRequest fetchQ = null; string sinkfileBSkyFormatMarker = "[1] \"BSkyFormatInternalSyncFileMarker\""; string sinkfileBSkyGraphicFormatMarker = "[1] \"BSkyGraphicsFormatInternalSyncFileMarker\""; //09Jun2015 //used to maintain the sequence of print in between BSkyFormats in case of block BSkyFormat bool isBlockCommand = false; //09Jun2015 used to maintain the sequence of print in between BSkyGraphicFormats in case of block commands bool isBlockGraphicCommand = false; //for deciding when to send output to output window in case of block BSkyFormat //for block BSkyFormat we wait and create all different UI elements first so as to maintain sequence and then send them to output //for non-block BSkFormat we send immediately after execution. No stacking up of UI elements ( AUXGrid, AUPara etc..) bool isBlock = false; //////////////////////////////////////////////////////////////////////////////////////////////////////// //if (true) return; CommandOutput lst = new CommandOutput(); ////one analysis//////// CommandOutput grplst = new CommandOutput();//21Nov2013 Separate for Graphic. So Parent node name will be R-Graphic lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor if (saveoutput.IsChecked == true)//10Jan2013 lst.SelectedForDump = true; XmlDocument xd = null; //string auparas = ""; StringBuilder sbauparas = new StringBuilder(""); //////////////// Read output ans message from file and create output then display ///// //// read line by line ///// string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink"));//23nov2012 // load default value if no path is set or invalid path is set if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, true)) { MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting..."); return; } System.IO.StreamReader file = new System.IO.StreamReader(sinkfilefullpathname);// OpenSinkFile(@sinkfilefullpathname, "rt"); object linetext = null; string line; bool insideblock = false;//20May2014 bool readSinkFile = true; if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Started reading sink", LogLevelEnum.Info); //int imgcount = GraphicDeviceImageCounter;//couter that keeps track of how many images already got processed. Helps in creating a image filename. while ((line = file.ReadLine()) != null)//(readSinkFile) { { linetext = line; } if (linetext == null || linetext.ToString().Equals("EOF")) { break; } if (linetext != null && linetext.Equals("NULL") && lastcommandwasgraphic)//27May2015 to supress NULL for some listed graphic commands { continue; } if (linetext.ToString().Trim().Contains(sinkfileBSkyFormatMarker))//Contains("[1] \"BSkyFormat\"")) //14Jun2014 if it is BSkyFormat in block (read from sink file) { isBlockCommand = true; } else if (linetext.ToString().Trim().Contains(sinkfileBSkyGraphicFormatMarker))//Contains("[1] \"BSkyGraphicsFormat\"")) //09Jun2015 if it is BSkyGraphicsFormat in block (read from sink file) { isBlockGraphicCommand = true; } else { isBlockCommand = false; } //////// create XML doc ///////// if (linetext != null)//06May2013 we need formatting so we print blank lines.. && linetext.ToString().Length > 0) { /////// Trying to extract command from print ////// string commnd = linetext.ToString(); int opncurly = commnd.IndexOf("{"); int closcurly = commnd.IndexOf("}"); int lencommnd = closcurly - opncurly - 1; if (opncurly != -1 && closcurly != -1) commnd = commnd.Substring(opncurly + 1, lencommnd);//could be graphic or BSkyFormat in sink file. if (false)//11Aug2015 fix for BSkyFormat not printed if inside R function. if (commnd.Contains("BSkyFormat("))//09Jun2015 || isGraphicCommand(_command)) // is BSKyFormat or isGraphic Command { SendToOutput(sbauparas.ToString(), ref lst, ow);//22May2014 sbauparas.Clear(); } else if (isBlockCommand)//14Jun2014 for Block BSkyFormat. { if (sbauparas.Length > 0) { createAUPara(sbauparas.ToString(), lst);//Create & Add AUPara to lst sbauparas.Clear(); } } else { if (sbauparas.Length < 1) { sbauparas.Append(linetext.ToString());//First Line of AUPara. Without \n if (sbauparas.ToString().Trim().IndexOf("BSkyFormat(") == 0)//21Nov2013 lst.NameOfAnalysis = "BSkyFormat-Command"; } else { //auparas = auparas.Replace("<", "<") + "\n" + linetext.ToString();//all lines separated by new line sbauparas.Append("\n" + linetext.ToString());//all lines separated by new line } } ////for graphics//// //09Jun2015 This whole 'if' may not be needed if (false) { SendToOutput(commnd, ref lst, ow); //////////// Here is new code///////20May2014 CommandRequest grpcmd = new CommandRequest(); CloseGraphicsDevice(); OpenGraphicsDevice();//05May2013 grpcmd.CommandSyntax = commnd;// linetext.ToString(); analytics.ExecuteR(grpcmd, false, false); CloseGraphicsDevice(); insideblock = true; ////////////////////////////////////////////////////////////////////////////////// //// add auparas first to lst to maintain order/// if (sbauparas.Length > 0) { createAUPara(sbauparas.ToString(), lst);//Create & Add AUPara to lst and empty dommid sbauparas.Clear(); } ////// now add image to lst //// string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012 /////03May2013 Create zero padding string //// %03d means 000, %04d means 0000 int percentindex = synedtimg.IndexOf("%"); int dindex = synedtimg.IndexOf("d", percentindex); string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1)); string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1)); int zerocount = Convert.ToInt16(numbr); string zeropadding = string.Empty; for (int zeros = 1; zeros <= zerocount; zeros++) { zeropadding = zeropadding + "0"; } int img_count = 0;//number of images to load in output for (; ; )//03May2013 earlier there was no for loop for following code { img_count++; string tempsynedtimg = synedtimg.Replace(percentstr, img_count.ToString(zeropadding)); // load default value if no path is set or invalid path is set if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true)) { break; } string source = @tempsynedtimg; long imgsize = new FileInfo(synedtimg).Length;//find size of the imagefile Image myImage = new Image(); ///////////RequestCachePolicy uriCachePolicy = new RequestCachePolicy(RequestCacheLevel.CacheOnly); var bitmap = new BitmapImage(); try { var stream = File.OpenRead(source); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; bitmap.EndInit(); stream.Close(); stream.Dispose(); myImage.Source = bitmap; bitmap.StreamSource.Close(); //trying to close stream 03Feb2014 if (isBlockCommand) createBSkyGraphic(myImage, lst); //20May2014 If graphic is inside block or loop else createBSkyGraphic(myImage, grplst); //if graphic is outside block or loop DeleteFileIfPossible(@tempsynedtimg); } catch (Exception ex) { logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error); MessageBox.Show(this, ex.Message); } } if (img_count < 1) ////03May2013 if no images were added to output lst. then return. { return; } } if (isBlockGraphicCommand)//for block graphics //09Jun2015 { CloseGraphicsDevice(); insideblock = true; ////// now add image to lst //// string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012 /////03May2013 Create zero padding string //// %03d means 000, %04d means 0000 int percentindex = synedtimg.IndexOf("%"); int dindex = synedtimg.IndexOf("d", percentindex); string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1)); string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1)); int zerocount = Convert.ToInt16(numbr); string zeropadding = string.Empty; for (int zeros = 1; zeros <= zerocount; zeros++) { zeropadding = zeropadding + "0"; } { GraphicDeviceImageCounter++;//imgcount++; string tempsynedtimg = synedtimg.Replace(percentstr, GraphicDeviceImageCounter.ToString(zeropadding)); // load default value if no path is set or invalid path is set if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true)) { isBlockGraphicCommand = false; //09Jun2015 reset, as we dont know what next command is. May or may not be graphic marker // not needed if one graphic for one graphic marker imgcount--; break; } string source = @tempsynedtimg; Image myImage = new Image(); var bitmap = new BitmapImage(); try { var stream = File.OpenRead(source); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; bitmap.EndInit(); stream.Close(); stream.Dispose(); myImage.Source = bitmap; bitmap.StreamSource.Close(); //trying to close stream 03Feb2014 if (isBlockGraphicCommand) createBSkyGraphic(myImage, lst); //20May2014 If graphic is inside block or loop else createBSkyGraphic(myImage, grplst); //if graphic is outside block or loop DeleteFileIfPossible(@tempsynedtimg); } catch (Exception ex) { logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error); MessageBox.Show(this, ex.Message); } } if (GraphicDeviceImageCounter < 1) ////03May2013 if no images were added to output lst. then return. { sbauparas.Clear();//resetting isBlockGraphicCommand = false; return; } sbauparas.Clear();//resetting isBlockGraphicCommand = false; } else if (isBlockCommand)// (linetext.ToString().Trim().Contains("[1] \"BSkyFormat\""))//21may2014 { int bskyfrmtobjcount = 0; if (!bskyQFetched) { fetchQ = new CommandRequest(); fetchQ.CommandSyntax = "BSkyQueue = BSkyGetHoldFormatObjList()";// Fetch Queue object analytics.ExecuteR(fetchQ, false, false); fetchQ.CommandSyntax = "is.null(BSkyQueue)";// check if Queue is null object o = analytics.ExecuteR(fetchQ, true, false);//return false or true if (o.ToString().ToLower().Equals("false"))//Queue has elements { bskyQFetched = true; } } if (bskyQFetched) { bskyformatobjectindex++; commnd = "BSkyFormat(BSkyQueue[[" + bskyformatobjectindex + "]])"; ExecuteSinkBSkyFormatCommand(commnd, ref bskyfrmtobjcount, lst); lst = new CommandOutput();//"Child already has parent" error, fix isBlock = true; } isBlockCommand = false;//09Jun2015 next command may or may not be BSkyFormat marker. } }//if linetext!null }//while EOF sink file if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Finished reading sink", LogLevelEnum.Info); file.Close(); //CloseSinkFile(); SendToOutput(sbauparas.ToString(), ref lst, ow, isBlock);//send output to window or disk file SendToOutput(null, ref grplst, ow, isBlock);//21Nov2013. separate node for graphic if (lst != null && lst.Count > 0 && isBlock) // Exceutes when there is block command { sessionlst.Add(lst);//15Nov2013 lst = new CommandOutput();//after adding to session new object is allocated for futher output creation } if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Finished creating output.", LogLevelEnum.Info); }
private void createAUPara(string auparas, CommandOutput lst) { string startdatetime = string.Empty; if (lst.NameOfAnalysis == null || lst.NameOfAnalysis.Trim().Length < 1) { lst.NameOfAnalysis = "R-Output";//Parent Node name. 02Aug2012 } if (auparas == null || auparas.Trim().Length < 1) return; string selectnode = "bskyoutput/bskyanalysis/aup"; string AUPara = "<aup>" + auparas.Replace("&", "&").Replace("<", "<").Replace(">", ">") + "</aup>";//single AUPara for all lines XmlDocument xd = null; ///// Creating DOM for generation output /////// string fulldom = "<bskyoutput> <bskyanalysis>" + AUPara + "</bskyanalysis> </bskyoutput>"; xd = new XmlDocument(); xd.LoadXml(fulldom); //// for creating AUPara ////////////// BSkyOutputGenerator bsog = new BSkyOutputGenerator(); int noofaup = xd.SelectNodes(selectnode).Count;// should be 3 for (int k = 1; k <= noofaup; k++) { if (lst.NameOfAnalysis.Equals("R-Output") || lst.NameOfAnalysis.Contains("Command Editor Execution")) { lst.Add(bsog.createAUPara(xd, selectnode + "[" + (1) + "]", "")); } else if (lst.NameOfAnalysis.Equals("Datasets")) { lst.Add(bsog.createAUPara(xd, selectnode + "[" + (1) + "]", "Open Datasets")); } else { lst.Add(bsog.createAUPara(xd, selectnode + "[" + k + "]", startdatetime)); } } }
private void createFlexGrid(XmlDocument xd, CommandOutput lst, string header) { AUXGrid xgrid = new AUXGrid(); AUGrid c1FlexGrid1 = xgrid.Grid;// new C1flexgrid. xgrid.Header.Text = header;//FlexGrid header as well as Tree leaf node text(ControlType) //XmlDocument xd = new XmlDocument(); xd.LoadXml(xdoc); BSkyOutputGenerator bsog = new BSkyOutputGenerator(); bsog.html2flex(xd, c1FlexGrid1); lst.Add(xgrid); }
private void WriteOutput(CommandOutput output) { if (output == null) { throw new ArgumentNullException("output"); } WriteOutputSettings(output); BuilderBase.AppendFormat(" {0}", Helpers.EscapePath(output.Resource)); }
private void WriteOutputSettings(CommandOutput output) { if (output == null) { throw new ArgumentNullException("output"); } output.Settings.SettingsList.ForEach(setting => { BuilderBase.Append(" "); BuilderBase.Append(SettingSerializer.Serialize(setting)); }); }
public static MetadataInfoStreamCalculator Create(FFmpegCommand command, CommandOutput commandOutput) { var infoStreamItem = MetadataInfoTreeGroup.Create(command, commandOutput); return new MetadataInfoStreamCalculator(infoStreamItem); }
private void AddToSyntaxSession(CommandOutput co) { SyntaxEditorWindow sewindow = LifetimeService.Instance.Container.Resolve<SyntaxEditorWindow>(); sewindow.AddToSession(co); }
public static void Pull(string remoteName, CommandOutput outputDelegate) { if ( IsRemoteLocal(remoteName) ) { string feedback = RunGitCmd("pull " + remoteName + " " + GetCurrentBranch(), true, outputDelegate); if ( feedback.Contains("Aborting") ) { Debug.LogError(feedback); Debug.LogError("Error pulling!"); } } else Debug.Log("Sorry, UnityGit can only pull from a local git repo for now."); }
public bool ContainsOutput(CommandOutput commandOutput) { return Outputs.Any(output => output.Id == commandOutput.Id); }
/* **** Push **** */ public static void Push(string remoteName, CommandOutput outputDelegate) { if ( IsRemoteLocal(remoteName) ) { string feedback = RunGitCmd("push -v --progress --porcelain " + remoteName + " " + GetCurrentBranch(), outputDelegate); if ( feedback.Contains("[rejected]") ) Debug.LogError("Push error: " + feedback + "\n\nTry fetch or pull first."); } else Debug.Log("Sorry, UnityGit can only push to a local git repo for now."); }
//No Need of following. Logic changed //15Apr2014. List location 1 will have listname and number of tables it caontains. Location 2 onwards are tables. 1 table per location. private void FormatBSkyList2(CommandOutput lst, string objectname, string headername, OutputWindow ow) // for BSky list2 processing { MessageBox.Show(this, "BSkyList2 Processing... close this box"); }
private void CreateAllGraphicOutput(OutputWindow ow) { CommandOutput grplst = new CommandOutput(); long EmptyImgSize = EMPTYIMAGESIZE;//size(in bytes) of empty png file CloseGraphicsDevice(); ////// now add image to lst //// string synedtimg = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("sinkimage"));//23nov2012 /////03May2013 Create zero padding string //// %03d means 000, %04d means 0000 int percentindex = synedtimg.IndexOf("%"); int dindex = synedtimg.IndexOf("d", percentindex); string percentstr = synedtimg.Substring(percentindex, (dindex - percentindex + 1)); string numbr = synedtimg.Substring(percentindex + 1, (dindex - percentindex - 1)); int zerocount = Convert.ToInt16(numbr); string zeropadding = string.Empty; for (int zeros = 1; zeros <= zerocount; zeros++) { zeropadding = zeropadding + "0"; } int imgcount = GraphicDeviceImageCounter;//number of images to load in output for (; ; )//03May2013 earlier there was no for loop for following code { imgcount++; string tempsynedtimg = synedtimg.Replace(percentstr, imgcount.ToString(zeropadding)); // load default value if no path is set or invalid path is set if (tempsynedtimg.Trim().Length == 0 || !IsValidFullPathFilename(tempsynedtimg, true)) { break; } string source = @tempsynedtimg; long imgsize = new FileInfo(source).Length;//find size of the imagefile if (imgsize > EmptyImgSize)//if image is not an empty image { Image myImage = new Image(); var bitmap = new BitmapImage(); try { var stream = File.OpenRead(source); bitmap.BeginInit(); bitmap.CacheOption = BitmapCacheOption.OnLoad; bitmap.StreamSource = stream; bitmap.EndInit(); stream.Close(); stream.Dispose(); myImage.Source = bitmap; bitmap.StreamSource.Close(); //trying to close stream 03Feb2014 createBSkyGraphic(myImage, grplst); //add graphic DeleteFileIfPossible(@tempsynedtimg); } catch (Exception ex) { logService.WriteToLogLevel("Error reading Image file " + source + "\n" + ex.Message, LogLevelEnum.Error); MessageBox.Show(this, ex.Message); } } } if (imgcount < 1) ////03May2013 if no images were added to output lst. then return. { return; } SendToOutput(null, ref grplst, ow, false);//send all graphic to output OpenGraphicsDevice();//in case of errors or no errors, you must open graphic device }
//18Dec2013 Sending command to output to make them appear different than command-output private void SendCommandToOutput(string command, string NameOfAnalysis) { string rcommcol = confService.GetConfigValueForKey("rcommcol");//23nov2012 byte red = byte.Parse(rcommcol.Substring(3, 2), NumberStyles.HexNumber); byte green = byte.Parse(rcommcol.Substring(5, 2), NumberStyles.HexNumber); byte blue = byte.Parse(rcommcol.Substring(7, 2), NumberStyles.HexNumber); Color c = Color.FromArgb(255, red, green, blue); CommandOutput lst = new CommandOutput(); lst.NameOfAnalysis = NameOfAnalysis; // left tree Parent AUParagraph Title = new AUParagraph(); Title.Text = command; //right side contents Title.FontSize = BSkyStyler.BSkyConstants.TEXT_FONTSIZE;//10Nov2014 //12; //right side content size Title.textcolor = new SolidColorBrush(c);//new SolidColorBrush(Colors.DeepSkyBlue); Title.ControlType = "Command"; // left tree child lst.Add(Title); AddToSession(lst); }
private void SendToOutput(string auparas, ref CommandOutput lst, OutputWindow ow, bool isBlockCommand = false)//, bool last=false) { if (auparas != null && auparas.Trim().Length > 0) { this.createAUPara(auparas, lst);//Create & Add AUPara to lst and empty dommid auparas = null; } if (lst != null && lst.Count > 0 && !isBlockCommand) //if non block command, then sent to output { sessionlst.Add(lst);//15Nov2013 lst = new CommandOutput();//after adding to session new object is allocated for futher output creation //15Nov2013 ow.AddAnalyisFromSyntaxEditor(lst);//, last);/// send to output and/or dump file } }
private void createBSkyGraphic(Image img, CommandOutput lst)//30Aug2012 { lst.NameOfAnalysis = "R-Graphics"; BSkyGraphicControl bsgc = new BSkyGraphicControl(); bsgc.BSkyImageSource = img.Source; bsgc.ControlType = "Graphic"; lst.Add(bsgc); }
public void RunCommands(string commands, BSkyDialogProperties dlgprop = null) //30Apr2013 { try { ShowMouseBusy(); AdvancedLogging = AdvancedLoggingService.AdvLog;//01May2015 logService.WriteToLogLevel("Adv Log Flag:" + AdvancedLogging.ToString(), LogLevelEnum.Info); DlgProp = dlgprop; #region Load registered graphic commands from GraphicCommandList.txt 18Sep2012 // loads each time run is clicked. Performance will be effected, as we read file each time. string grplstfullfilepath = confService.GetConfigValueForKey("sinkregstrdgrph");//23nov2012 //if graphic file does not exists the n create one. if (!IsValidFullPathFilename(grplstfullfilepath, true))//17Jan2014 { string text = "plot"; System.IO.File.WriteAllText(@grplstfullfilepath, text); } // load default value if no path is set or invalid path is set if (grplstfullfilepath.Trim().Length == 0 || !IsValidFullPathFilename(grplstfullfilepath, true)) { //grplstfullfilepath = confService.DefaultSettings["sinkregstrdgrph"]; MessageBox.Show(this, "Key 'sinkregstrdgrph' not found in config file. You cannot run Graphics from Command Editor."); //return; } else { LoadRegisteredGraphicsCommands(@grplstfullfilepath); } #endregion #region Save to Disk if (saveoutput.IsChecked == true) { if (fullpathfilename.Text != null && fullpathfilename.Text.Trim().Length > 0) { fullfilepathname = fullpathfilename.Text;///setting filename bool fileExists = File.Exists(fullfilepathname); fileExists = false; if (fullfilepathname.Contains('.') && !fileExists) { string extension = Path.GetExtension(fullfilepathname).ToLower();// fullfilepathname.Substring(fullfilepathname.LastIndexOf('.')); if (extension.Equals(".csv")) { fileformat = C1.WPF.FlexGrid.FileFormat.Csv; extratags = false; } else if (extension.Equals(".html")) { fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = false; } else if (extension.Equals(".bsoz")) { fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = true; } else { fileformat = C1.WPF.FlexGrid.FileFormat.Html; extratags = true; fullfilepathname = fullfilepathname + ".bsoz"; } } else { MessageBox.Show(this, "Output File Already Exists! Provide different name in Command Editor window."); return; } } else { MessageBox.Show(this, "Please provide new output filename and fileformat by clicking 'Browse' in Command Editor for saving the output.", "Save Output is checked...", MessageBoxButton.OK, MessageBoxImage.Asterisk); return; } } #endregion #region Get Active output Window //////// Active output window /////// OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer; ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window if (saveoutput.IsChecked == true) { ow.ToDiskFile = true;//save lst to disk. Dump } #endregion #region Executing Syntax Editors Commands ///// Now statements from Syntax Editor will be executed //// CommandOutput lst = new CommandOutput(); ////one analysis//////// lst.IsFromSyntaxEditor = true; if (saveoutput.IsChecked == true)//10Jan2013 lst.SelectedForDump = true; ////03Oct2014 We should remove R comments right here, before proceeding with execution. string nocommentscommands = RemoveCommentsFromCommands(commands); ExecuteCommandsAndCreateSinkFile(ow, lst, nocommentscommands); bool s = true; if (s) CreateOuput(ow); /// for last remaining few non BSkyFormat commands, if any. /// #endregion #region Saving to Disk //////Dumping results from Syntax Editor ////08Aug2012 if (saveoutput.IsChecked == true) ow.DumpAllAnalyisOuput(fullfilepathname, fileformat, extratags); #endregion } catch (Exception ex) { logService.WriteToLogLevel("Exeception:" + ex.Message, LogLevelEnum.Error); } finally { HideMouseBusy(); } }
private void CreateDynamicClassFlexGrid(string header, string[] colheaders, string[] rowheaders, string[,] data, CommandOutput lst) { IList list; AUXGrid xgrid = new AUXGrid(); AUGrid c1FlexGrid1 = xgrid.Grid;// new C1flexgrid. xgrid.Header.Text = header;//FlexGrid header as well as Tree leaf node text(ControlType) ///////////// merge and sizing ///// c1FlexGrid1.AllowMerging = AllowMerging.ColumnHeaders | AllowMerging.RowHeaders; c1FlexGrid1.AllowSorting = false; //trying to fix the size of the grid so that rendering does not take much time calculating these c1FlexGrid1.MaxHeight = 800;// NoOfRows* EachRowHeight; c1FlexGrid1.MaxWidth = 1000; int nrows = data.GetLength(0); int ncols = data.GetLength(1); //// Dynamic class logic FGDataSource ds = new FGDataSource(); ds.RowCount = nrows; ds.Data = data; foreach (string s in colheaders) { ds.Variables.Add(s.Trim()); } list = new DynamicList(ds); if (list != null) { c1FlexGrid1.ItemsSource = list; } FillColHeaders(colheaders, c1FlexGrid1); FillRowHeaders(rowheaders, c1FlexGrid1); lst.Add(xgrid); }
private void ExecuteBSkyFormatCommand(string stmt, ref int bskyfrmtobjcount, OutputWindow ow) { KillTempBSkyFormatObj("bskytempvarname"); KillTempBSkyFormatObj("bskyfrmtobj"); string originalCommand = stmt; CommandOutput lst = new CommandOutput(); ////one analysis//////// lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor if (saveoutput.IsChecked == true)//10Jan2013 lst.SelectedForDump = true; object o; CommandRequest cmd = new CommandRequest(); /// find argument passed in BSkyFormat(argu) and var name //// /// eg.. BSkyFormat(osmt <-one.smt.t.test(....) ) /// subcomm will be : osmt<-one.smt.t.test(....) /// varname will be : osmt string subcomm = string.Empty, varname = string.Empty, BSkyLeftVar = string.Empty, headername = string.Empty; string firstparam = string.Empty, restparams = string.Empty, leftvarname = string.Empty;//23Sep2014 string userpassedtitle = string.Empty; //SplitBSkyFormat(stmt, out subcomm, out varname, out BSkyLeftVar); SplitBSkyFormatParams(stmt, out firstparam, out restparams, out userpassedtitle);//23Spe2014 if (userpassedtitle.Trim().Length > 0)//user passed title has the highest priority { headername = userpassedtitle.Trim(); } { //23Sep2014 if firstParam is of the type obj<-OSMT(...) OR obj<-obj2 if (firstparam.Contains("<-") || firstparam.Contains("=")) //if it has assignment { int idxassign=-1, idxopenbrket=-1; if(firstparam.Contains("("))// if obj<-OSMT(...) { idxopenbrket = firstparam.IndexOf("("); string firsthalf = firstparam.Substring(0,idxopenbrket);// "obj <- OSMT(" idxassign = firsthalf.IndexOf("<-"); if (idxassign == -1)// '<-' not present(found in half) idxassign = firsthalf.IndexOf("="); } if (idxassign > -1 && idxopenbrket > -1 && idxopenbrket > idxassign) { leftvarname = firstparam.Substring(0, idxassign); headername = leftvarname.Trim(); cmd.CommandSyntax = firstparam;// command: osmt<-one.smt.tt(...) o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...) } else if (idxopenbrket < 0 )//type obj <- obj2 { idxassign = firstparam.IndexOf("<-"); if (idxassign == -1)// '<-' not present idxassign = firstparam.IndexOf("="); if (idxassign > -1)//if assignment is there { leftvarname = firstparam.Substring(0, idxassign); headername = leftvarname.Trim(); cmd.CommandSyntax = firstparam;// command: osmt<-one.smt.tt(...) o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...) } } } /////25Feb2013 for writing errors in OutputWindow//// string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink")); //23nov2012 // load default value if no path is set or invalid path is set if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false)) { MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting..."); return; //return type was void before 22May2014 } OpenSinkFile(@sinkfilefullpathname, "wt"); //06sep2012 SetSink(); //06sep2012 //////////////////////////////////////////////////////////////////////// //13Aug2012 headername = findHeaderName(subcomm); // data.frame / matrix / array header varname = "bskytempvarname"; KillTempBSkyFormatObj(varname); //Now run command firstparam = (leftvarname.Trim().Length>0? leftvarname : firstparam); //23Sep2014 cmd.CommandSyntax = varname + " <- " + subcomm;// command: varname <- one.smt.tt(...) cmd.CommandSyntax = varname + " <- " + firstparam;// varname <- obj OR OSMT() o = analytics.ExecuteR(cmd, false, false);//executing sub-command //////////////////////////////////////////////////////////////////////// /////25Feb2013 for writing errors in OutputWindow//// ResetSink(); CloseSinkFile(); CreateOuput(ow); } //if var does not exists then there could be error in command execution. cmd.CommandSyntax = "exists('" + varname + "')"; o = analytics.ExecuteR(cmd, true, false); if (o.ToString().ToLower().Equals("false"))//possibly some error occured { string ewmessage = "Object cannot be formatted using BSKyFormat. Object: " + firstparam + ", does not exists."; //if (ow != null)//22May2014 SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013 return; //return type was void before 22May2014 } //Check if varname is null cmd.CommandSyntax = "is.null(" + varname + ")"; o = analytics.ExecuteR(cmd, true, false); if (o.ToString().ToLower().Equals("true"))//possibly some error occured { string ewmessage = "Object cannot be formatted using BSKyFormat. Object: " + firstparam + ", is null."; SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013 return; //return type was void before 22May2014 } //setting up flag for showing default ("1","2","3" )row headers. //This will not work if BSkyReturnStructure is returned(in varname). bsky_no_row_header = false; cmd.CommandSyntax = "is.null(row.names(" + varname + ")[1])"; o = analytics.ExecuteR(cmd, true, false); if (o.ToString().ToLower().Equals("false"))//row name at [1] exists { cmd.CommandSyntax = "row.names(" + varname + ")[1]"; o = analytics.ExecuteR(cmd, true, false); if (o.ToString().Trim().ToLower().Equals("bsky_no_row_header")) { bsky_no_row_header = true; } } //one mandatory parameter string mandatoryparamone = ", bSkyFormatAppRequest = TRUE"; if (restparams.Trim().Length > 0 && restparams.Trim().Contains("bSkyFormatAppRequest"))//if parameter is already present, no need to add it. { mandatoryparamone = string.Empty; } //second mandatory parameter string mandatoryparamtwo = ", singleTableOutputHeader = '" + headername + "'"; // \"c(\\\"a\\\")\" )" if (restparams.Trim().Length > 0 && restparams.Trim().Contains("singleTableOutputHeader"))//if parameter is already present, no need to add it. { mandatoryparamtwo = string.Empty; } //create BSkyFormat command for execution and execute if(restparams.Trim().Length > 0) stmt = "BSkyFormat(" + varname + mandatoryparamone + mandatoryparamtwo +","+restparams+")";//stmt = "BSkyFormat(" + varname + ")"; else stmt = "BSkyFormat(" + varname + mandatoryparamone + mandatoryparamtwo+" )"; stmt = BSkyLeftVar + stmt;// command is BSkyLeftVar <- BSkyFormat(varname) /// BSkyLeftVar <- can be blank if user has no assigned leftvar to BSkyFormat if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Command reconstructed : " + stmt, LogLevelEnum.Info); string objclass = "", objectname = ""; if (stmt.Contains("BSkyFormat("))// Array, Matrix, Data Frame or BSkyObject(ie..Analytic commands) { bskyfrmtobjcount++; stmt = "bskyfrmtobj <- " + stmt; // BSkyFormat has BSkyFormat2 call inside of it objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString(); cmd.CommandSyntax = stmt;// command o = analytics.ExecuteR(cmd, false, false);//executing BSkyFormat ///Check if returned object is null cmd.CommandSyntax = "is.null(" + objectname + ")"; o = analytics.ExecuteR(cmd, true, false); if (o.ToString().ToLower().Equals("true"))//possibly some error occured { string ewmessage = "Object cannot be formatted using BSKyFormat. Type not supported. Supported types are :\n array, matrix dataframe and BSky return structure."; SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013 return; //return type was void before 22May2014 } #region Generate UI for data.frame/ matrix / array and analytics commands if (BSkyLeftVar.Trim().Length < 1) // if left var does not exists then generate UI tables { lst.NameOfAnalysis = originalCommand.Contains("BSkyFormat") ? "BSkyFormat-Command" : originalCommand; //cmd.CommandSyntax = "class(bskyfrmtobj" + bskyfrmtobjcount.ToString() + ")"; cmd.CommandSyntax = "class(bskyfrmtobj)"; objclass = (string)analytics.ExecuteR(cmd, true, false); if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormat object type : " + objclass, LogLevelEnum.Info); if (objclass.ToString().ToLower().Equals("data.frame") || objclass.ToString().ToLower().Equals("matrix") || objclass.ToString().ToLower().Equals("array")) { if (headername != null && headername.Trim().Length < 1) //06May2014 headername = subcomm; if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormatting DF/Matrix/Arr : " + objclass, LogLevelEnum.Info); BSkyFormatDFMtxArr(lst, objectname, headername, ow); } else if (objclass.ToString().ToLower().Equals("list"))//BSkyObject returns "list" { if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: BSkyFormatting : " + objclass, LogLevelEnum.Info); SendToOutput("", ref lst, ow); ///tetsing whole else if objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString(); cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info); bool isNonBSkyList1=false; object isNonBSkyList1str = analytics.ExecuteR(cmd, true, false); if (isNonBSkyList1str != null && isNonBSkyList1str.ToString().ToLower().Equals("true")) { isNonBSkyList1 = true; } cmd.CommandSyntax = "is.null(" + objectname + "$list2name)";//another type pf BSky list if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info); bool isNonBSkyList2=false ; object isNonBSkyList2str = analytics.ExecuteR(cmd, true, false); if (isNonBSkyList2str != null && isNonBSkyList2str.ToString().ToLower().Equals("true")) { isNonBSkyList2 = true; } if (!isNonBSkyList1) { //if there was error in execution, say because non scale field has scale variable // so now if we first check if $executionstatus = -2, we know that some error has occured. cmd.CommandSyntax = objectname + "$executionstatus";//$BSkySplit or $split in return structure if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info); object errstat = analytics.ExecuteR(cmd, true, false); if (errstat != null && (errstat.ToString().ToLower().Equals("-2") || errstat.ToString().ToLower().Equals("-1"))) { if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Execution Stat : " + errstat, LogLevelEnum.Info); if(errstat.ToString().ToLower().Equals("-2")) SendErrorToOutput("Critical Error Occurred!", ow);//15Jan2015 else SendErrorToOutput("Error Occurred!", ow);//03Jul2013 } cmd.CommandSyntax = objectname + "$nooftables";//$nooftables=0, means no data to display. Not even error warning tables are there. if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Executing : " + cmd.CommandSyntax, LogLevelEnum.Info); object retval = analytics.ExecuteR(cmd, true, false); if (retval != null && retval.ToString().ToLower().Equals("0")) { if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: No of Tables : " + retval, LogLevelEnum.Info); SendErrorToOutput("No tables to show in output!", ow);//03Jul2013 } if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Start creating actual UI tables : ", LogLevelEnum.Info); //finally we can now format the tables of BSkyReturnStruture list RefreshOutputORDataset(objectname, cmd, originalCommand, ow); //list like one sample etc.. } else if (!isNonBSkyList2) { //if (ow != null)//22May2014 FormatBSkyList2(lst, objectname, headername, ow); //list that contains tables 2nd location onwards } } else // invalid format { /// put it in right place string ewmessage = "This Object cannot be formatted using BSKyFormat. BSkyFormat can be used on Array, Matrix, Data Frame and BSky List objects only"; //if (ow != null)//22May2014 SendErrorToOutput(originalCommand + "\n" + ewmessage, ow);//03Jul2013 } }/// if leftvar is not assigned generate UI #endregion } return;//22May2014 }
private void ExecuteCommandsAndCreateSinkFile(OutputWindow ow, CommandOutput lst, string seltext)//sending message and output to sink file { string objectname; seltext = seltext.Replace('\n', ';').Replace('\r', ' ').Trim(); seltext = JoinCommaSeparatedStatment(seltext); string stmt = ""; //////wrap in sink//////// string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink"));//23nov2012 // load default value if no path is set or invalid path is set if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false)) { //sinkfilefullpathname = confService.DefaultSettings["tempsink"]; MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting..."); return; } OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); string _command = string.Empty;//05May2013 int bskyfrmtobjcount = 0; bool breakfor = false;//, continuefor=false;//14Nov2013 for (int start = 0, end = 0; start < seltext.Length; start = start + end + 1) //28Jan2013 final condition was start < seltext.Length-1 { objectname = ""; end = seltext.IndexOf(';', start) - start; if (end < 0) // if ; not found end = seltext.IndexOf('\n', start) - start; if (end < 0)// if new line not found end = seltext.Length - start; stmt = seltext.Substring(start, end).Replace('\n', ' ').Replace('\r', ' ').Trim(); if (stmt.Trim().Length < 1 || stmt.Trim().IndexOf('#') == 0) continue; if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Syntax going to execute : " + stmt, LogLevelEnum.Info); if (stmt.Trim().IndexOf('#') > 1) //12May2014 if any statment has R comments in the end in same line. stmt = stmt.Substring(0, stmt.IndexOf("#")); object o = null; if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorizing command before execution.", LogLevelEnum.Info); _command = ExtractCommandName(stmt);//07sep2012 RCommandType rct = GetRCommandType(_command); if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Syntax command category : " + rct.ToString(), LogLevelEnum.Info); try { switch (rct) { case RCommandType.CONDITIONORLOOP: //Block Commands int end2 = end; stmt = CurlyBracketParser(seltext, start, ref end); if (stmt.Equals("ERROR")) { breakfor = true; } else { SendCommandToOutput(stmt, "R-Command"); ExecuteOtherCommand(ow, stmt); } //02Dec2014 ResetSink(); CloseSinkFile(); CreateOuput(ow); OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); ///02Dec2015 Now add graphic (all of them, from temp location) CreateAllGraphicOutput(ow);//get all grphics and send to output break; case RCommandType.GRAPHIC: CommandRequest grpcmd = new CommandRequest(); grpcmd.CommandSyntax = "write(\"" + stmt.Replace("<", "<").Replace('"', '\'') + "\",fp)";// http://www.w3schools.com/xml/xml_syntax.asp o = analytics.ExecuteR(grpcmd, false, false); //for printing command in file CloseGraphicsDevice(); //GetGraphicSize() ResetSink(); CloseSinkFile(); CreateOuput(ow); OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); OpenGraphicsDevice();//05May2013 //continuefor = true; //continue; break; case RCommandType.GRAPHICXML: ExecuteXMLTemplateDefinedCommands(stmt); break; case RCommandType.BSKYFORMAT: ResetSink(); CloseSinkFile(); CreateOuput(ow); SendCommandToOutput(stmt, "BSkyFormat");//26Aug2014 blue colored ExecuteBSkyFormatCommand(stmt, ref bskyfrmtobjcount, ow); // this should be out of block and so "TRUE" must be passed in BSkyFormat OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); break; case RCommandType.BSKYLOADREFRESHDATAFRAME: //BSkyLoadRefreshDataframe(dfname) ResetSink(); CloseSinkFile(); CreateOuput(ow); SendCommandToOutput(stmt, "Load-Refresh Dataframe");//26Aug2014 blue colored bool success = ExecuteBSkyLoadRefreshDataframe(stmt); if (!success) SendErrorToOutput("Error:Cannot Load/Refresh Dataset. Dataframe does not exists. OR not 'data.frame' type.", ow); //03Jul2013 OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); break; case RCommandType.BSKYREMOVEREFRESHDATAFRAME: //BSkyRemoveRefreshDataframe(dfname) ResetSink(); CloseSinkFile(); CreateOuput(ow); ExecuteBSkyRemoveRefreshDataframe(stmt); OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); break; case RCommandType.SPLIT: // set/remove split and refresh status bar in main window showing split vars ResetSink(); CloseSinkFile(); CreateOuput(ow); ExecuteSplit(stmt); OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); break; case RCommandType.RCOMMAND: SendCommandToOutput(stmt, "R-Command"); if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. Before execution.", LogLevelEnum.Info); ExecuteOtherCommand(ow, stmt); if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. After execution.", LogLevelEnum.Info); ResetSink(); CloseSinkFile(); CreateOuput(ow); OpenSinkFile(@sinkfilefullpathname, "wt"); SetSink(); if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. Before getting graphic if any.", LogLevelEnum.Info); ///02Dec2015 Now add graphic (all of them, from temp location) CreateAllGraphicOutput(ow);//get all grphics and send to output if (AdvancedLogging) logService.WriteToLogLevel("ExtraLogs: Categorized. After getting graphic if any.", LogLevelEnum.Info); break; case RCommandType.RDOTNET: InitializeRDotNet(); RDotNetOpenDataset(); RDotNetExecute(ow); DisposeRDotNet(); break; default: break; }//switch } catch (Exception exc) { SendCommandToOutput(exc.Message, "Error:"); logService.WriteToLogLevel("Error executing: " + _command, LogLevelEnum.Error); logService.WriteToLogLevel(exc.Message, LogLevelEnum.Error); } if (breakfor) break; }/////for //////wrap in sink//////// ResetSink(); CloseSinkFile(); }
private void ExecuteSinkBSkyFormatCommand(string stmt, ref int bskyfrmtobjcount, CommandOutput lst) { string originalCommand = stmt; //CommandOutput lst = new CommandOutput(); ////one analysis//////// lst.IsFromSyntaxEditor = true;//lst belongs to Syn Editor if (saveoutput.IsChecked == true)//10Jan2013 lst.SelectedForDump = true; object o; CommandRequest cmd = new CommandRequest(); /// find argument passed in BSkyFormat(argu) and var name //// /// eg.. BSkyFormat(osmt <-one.smt.t.test(....) ) /// subcomm will be : osmt<-one.smt.t.test(....) /// varname will be : osmt string subcomm = string.Empty, varname = string.Empty, BSkyLeftVar = string.Empty, headername = string.Empty; SplitBSkyFormat(stmt, out subcomm, out varname, out BSkyLeftVar); if (BSkyLeftVar.Trim().Length > 0) // if left var exists { BSkyLeftVar = BSkyLeftVar + " <- "; // so that BSkyLeftVar <- BSkyFormat(...) ) } ////now execute subcomm first then pass varname in BSkyFormat(varname) if (varname.Length > 0)//will be > 0 only for BSkyFormat(osmt<-one.smt.tt(...) ) OR for BSkyFormat(df) { headername = varname.Trim(); cmd.CommandSyntax = subcomm;// command: osmt<-one.smt.tt(...) if (!varname.Equals(subcomm)) o = analytics.ExecuteR(cmd, false, false);//executing sub-command; osmt<-one.smt.tt(...) } else //for BSkyFormat(one.smt.tt(...) ) { /////25Feb2013 for writing errors in OutputWindow//// string sinkfilefullpathname = Path.Combine(System.IO.Path.GetTempPath().Replace("\\", "/"), confService.GetConfigValueForKey("tempsink"));//23nov2012 // load default value if no path is set or invalid path is set if (sinkfilefullpathname.Trim().Length == 0 || !IsValidFullPathFilename(sinkfilefullpathname, false)) { MessageBox.Show(this, "Key 'tempsink' not found in config file. Aborting..."); return; } //////////////////////////////////////////////////////////////////////// //13Aug2012 headername = findHeaderName(subcomm); // data.frame / matrix / array header varname = "bskytempvarname"; //Find if bskytempvarname already exists. If it exists then remove from memory cmd.CommandSyntax = "exists('" + varname + "')";//removing var so that old obj from last session is not present. o = analytics.ExecuteR(cmd, true, false); if (o.ToString().ToLower().Equals("true")) // if found, remove it { cmd.CommandSyntax = "rm('" + varname + "')";//removing var so that old obj from last session is not present. o = analytics.ExecuteR(cmd, false, false); } //Now run command cmd.CommandSyntax = varname + " <- " + subcomm;// command: varname <- one.smt.tt(...) o = analytics.ExecuteR(cmd, false, false);//executing sub-command //////////////////////////////////////////////////////////////////////// } //if var does not exists then there could be error in command execution. cmd.CommandSyntax = "exists('" + varname + "')"; o = analytics.ExecuteR(cmd, true, false); if (o.ToString().ToLower().Equals("false"))//possibly some error occured { string ewmessage = "Object cannot be formatted using BSKyFormat. Object: " + varname + ", does not exists."; SendErrorToOutput(originalCommand + "\n" + ewmessage, ow); //03Jul2013 return; } //Added extra parameter with TRUE value to fix problem related to uadatasets.sk$holdBSkyFormatObject getting back objeects. // when cmd executes in R, few line below. "analytics.ExecuteR(c..." stmt = "BSkyFormat(" + varname + ", bSkyFormatAppRequest = TRUE)"; stmt = BSkyLeftVar + stmt;// command is BSkyLeftVar <- BSkyFormat(varname) /// BSkyLeftVar <- can be blank if user has no assigned leftvar to BSkyFormat string objclass = "", objectname = ""; if (stmt.Contains("BSkyFormat("))// Array, Matrix, Data Frame or BSkyObject(ie..Analytic commands) { bskyfrmtobjcount++; stmt = "bskyfrmtobj <- " + stmt;// +"$tables[[1]][[1]]";// +"$additional";//return value additional objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString(); cmd.CommandSyntax = stmt;// command //Following statement brings back the objects of uadatasets.sk$holdBSkyFormatObject o = analytics.ExecuteR(cmd, false, false);//executing syntax editor commands #region Generate UI for data.frame/ matrix / array and analytics commands if (BSkyLeftVar.Trim().Length < 1) // if left var does not exists then generate UI tables { lst.NameOfAnalysis = originalCommand.Contains("BSkyFormat") ? "BSkyFormat-Command" : originalCommand; //cmd.CommandSyntax = "class(bskyfrmtobj" + bskyfrmtobjcount.ToString() + ")"; cmd.CommandSyntax = "class(bskyfrmtobj)"; objclass = (string)analytics.ExecuteR(cmd, true, false); if (objclass.ToString().ToLower().Equals("data.frame") || objclass.ToString().ToLower().Equals("matrix") || objclass.ToString().ToLower().Equals("array")) { //lst.NameOfAnalysis = originalCommand;//for tree Parent node 07Aug2012 if (headername != null && headername.Trim().Length < 1) //06May2014 { headername = subcomm; } BSkyFormatDFMtxArr(lst, objectname, headername, null); } else if (objclass.ToString().Equals("list"))//BSkyObject returns "list" { //if (ow != null)//22May2014 SendToOutput("", ref lst, ow); ///tetsing whole else if objectname = "bskyfrmtobj";// +bskyfrmtobjcount.ToString(); cmd.CommandSyntax = "is.null(" + objectname + "$BSkySplit)";//$BSkySplit or $split in return structure bool isNonBSkyList1 = false; object isNonBSkyList1str = analytics.ExecuteR(cmd, true, false); if (isNonBSkyList1str != null && isNonBSkyList1str.ToString().ToLower().Equals("true")) { isNonBSkyList1 = true; } cmd.CommandSyntax = "is.null(" + objectname + "$list2name)";//another type pf BSky list bool isNonBSkyList2 = false; object isNonBSkyList2str = analytics.ExecuteR(cmd, true, false); if (isNonBSkyList2str != null && isNonBSkyList2str.ToString().ToLower().Equals("true")) { isNonBSkyList2 = true; } ///////////////// if (!isNonBSkyList1) { RefreshOutputORDataset(objectname, cmd, originalCommand, ow); //list like one sample etc.. } else if (!isNonBSkyList2) { FormatBSkyList2(lst, objectname, headername, ow); //list that contains tables 2nd location onwards } } else // invalid format { /// put it in right place string ewmessage = "This Object cannot be formatted using BSKyFormat. BSkyFormat can be used on Array, Matrix, Data Frame and BSky List objects only"; SendErrorToOutput(originalCommand + "\n" + ewmessage, ow);//03Jul2013 } }/// if leftvar is not assigned generate UI #endregion } }
public static string RunGitCmd(string command, bool includeGitDir, CommandOutput outputDelegate) { string cmd = GetGitExePath(); string repoPath = GetRepoPath(); if ( proc != null ) { Debug.LogWarning("You must wait for previous processes to finish!"); return ""; } if ( cmd != "" ) { ProcessStartInfo startInfo = new ProcessStartInfo (cmd); string result; proc = new Process(); if ( includeGitDir ) command = "--git-dir=\"" + repoPath + "/.git\" --work-tree=\"" + repoPath + "\" " + command; // startInfo.Arguments = "cd.. && cd.. && " + command; startInfo.Arguments = command; startInfo.UseShellExecute = false; startInfo.RedirectStandardInput = true; startInfo.RedirectStandardOutput = true; startInfo.CreateNoWindow = true; proc.StartInfo = startInfo; proc.Start (); if ( outputDelegate == null ) { StreamReader streamReader = proc.StandardOutput; while (!proc.HasExited) { Thread.Sleep (0); result = streamReader.ReadToEnd (); proc.Close(); proc = null; return result; } } else { ThreadPool.QueueUserWorkItem(ThreadedUpdateProcess, outputDelegate); return "Threaded Process"; } } return "No Git.exe path defined!"; }
public static string RunGitCmd(string command, CommandOutput outputDelegate) { return RunGitCmd(command, true, outputDelegate); }