private static async Task Main(string[] args) { Output.WriteHeader(); _cmdAllowedArgs = CmdAllowedArgsFactory.CreateCmdAllowedArgs(); var cmdArgInfo = new CmdArgInfo(args, _cmdAllowedArgs); CmdArg searchTermArg = cmdArgInfo.GetArgument('s'); CmdArg packageIdCsv = cmdArgInfo.GetArgument('i'); if (searchTermArg != null) { await SearchAsync(searchTermArg.Value); } else if (packageIdCsv != null) { var packageIds = packageIdCsv.Value.ToCsvList(); await GetByIdsAsync(packageIds); } else { HandleError("Provide either a search term or CSV list of package IDs argument."); } }
private static void AssertAreEqual(CmdArg cmdArg, CmdAllowedArg cmdAllowedArg) { Assert.That(cmdArg.ShortName, Is.EqualTo(cmdAllowedArg.ShortName)); Assert.That(cmdArg.LongName, Is.EqualTo(cmdAllowedArg.LongName)); Assert.That(cmdArg.Description, Is.EqualTo(cmdAllowedArg.Description)); Assert.That(cmdArg.HasValue, Is.EqualTo(cmdAllowedArg.HasValue)); }
void Run(CmdArg Arg) { try { var pClass = SPCTypes.GetClassType(Arg.GetShortCutSegment(0)); if (pClass != null) { //Runable non UI command if (pClass.GetInterfaces().Contains(typeof(IRunable))) { var Sample = BOFactory.CreateSample(pClass) as IRunable; Task.Run(async() => await Sample.RunAsync(Arg)); } } else { var prs = new ProcessStartInfo(@"C:\Program Files (x86)\Google\Chrome\Application\chrome.exe"); prs.Arguments = Arg.Url.Replace(@" ", "%20"); Process.Start(prs); } } catch (Exception ex) { WaitingService.Done(); AlertService.ShowError(ex); } }
/// <summary> /// Returns the argument's Value given the argument Name /// If the argument doesn't exist the value with be a blank string /// </summary> /// <param argName="arg">The argument argName. Ex: "v" for when "-v" is specified</param> /// <returns></returns> public string GetArgValue(string argName, out CmdArg argInfo) { string ret = ""; // Trim off any leading argument qualifier char if ((argName.StartsWith("-") || argName.StartsWith("/")) && argName.Length > 1) { argName = argName.Substring(1); } // Ensure that the arguments have already been initialized if (allCmdLines == null) { PopulateArgData_InternalList(); } // Perform lookup CmdArg argFound = allCmdLines.FirstOrDefault(x => x.Name.ToLower() == argName.ToLower()); if (argFound != null) { ret = argFound.Value; } argInfo = argFound; return(ret); }
/// <summary> /// Checks to see if any argument in the string array was specified or not /// </summary> /// <param argNames="argNames">An array of argument names. Ex: new string[] = { "1", "2" }</param> /// <returns></returns> public bool WasArgSupplied(string[] argNames) { bool ret = false; // Ensure that the arguments have already been initialized if (allCmdLines == null) { PopulateArgData_InternalList(); } // See if any of the supplied arguments were specified foreach (string arg in argNames) { string argName = arg; // Trim off any leading argument qualifier char, in case it was accidently added if ((argName.StartsWith("-") || argName.StartsWith("/")) && argName.Length > 1) { argName = argName.Substring(1); } // Perform lookup CmdArg argFound = allCmdLines.FirstOrDefault(x => x.Name.ToLower() == argName.ToLower()); // Once one was found, then exit if (argFound != null) { ret = true; break; } } return(ret); }
public void AnalyzeCmdString(string CmdLine, int capturetype) { if (capturetype == (int)VoiceCaptureType.SearchYN) { if (prevCmdData.speechstring != null) { if (prevCmdData.ChromeMotionCode == (int)ChromeMotionCode.NaverSearch) { prevCmdData = new CmdData(); AnalyzeSearchYNCmdString(CmdLine); } else { prevCmdData = new CmdData(); } } return; } string[] MulitiCmdArgs = SplitCmdline(CmdLine); foreach (var CmdArg in MulitiCmdArgs) { if (CmdArg.IndexOf("검색") > -1) { if (CmdArg.Substring(0, 2) == "검색") { string SearchKey = CmdArg.Substring(2).Trim(); Console.WriteLine("|" + SearchKey + "|"); prevCmdData = new CmdData(CmdArg, (int)ChromeMotionCode.NaverSearch, SearchKey); OnCmdanalyzed?.Invoke((int)ChromeMotionCode.NaverSearch, new ChromeHandleValue(SearchKey)); } else { string SearchKey = ""; for (int i = 2; i < CmdArg.Length; i++) { int index2looking = CmdArg.Length - i; if (CmdArg.Substring(index2looking, 2) == "검색") { SearchKey = CmdArg.Substring(0, index2looking).Trim(); break; } } Console.WriteLine("|" + SearchKey + "|"); prevCmdData = new CmdData(CmdArg, (int)ChromeMotionCode.NaverSearch, SearchKey); OnCmdanalyzed?.Invoke((int)ChromeMotionCode.NaverSearch, new ChromeHandleValue(SearchKey)); } } else if (CmdArg.IndexOf("읽어") > -1) { } else if (CmdArg.IndexOf("열어") > -1) { } } }
async Task ResendPasswordAsync(ToolbarItemClickEventArgs e) { if (SelectedRow != null) { var cmd = new CmdArg($"SPC.Cloud.Commands.Subscriber.ResetPassword?SubscriberId={SelectedRow.UserId}"); await SPC.Services.UI.RunURLService.RunAsync(cmd); bs.Toast($"Đã gửi mật khẩu mới cho user {SelectedRow.UserId}"); } }
private static void Main(string[] args) { var sw = new Stopwatch(); sw.Start(); Output.WriteAppHeader(); _cmdAllowedArgs = CmdAllowedArgsFactory.Create(); try { _cmdArgInfo = new CmdArgInfo(args, _cmdAllowedArgs); CmdArg path = _cmdArgInfo.GetArgument('p'); CmdArg useTable = _cmdArgInfo.GetArgument('t'); var slnsToIgnore = _cmdArgInfo.GetSlnsToIgnore(); var slnPaths = GetSlnPaths(path.Value, slnsToIgnore); if (slnPaths.Count == 0) { HandleError($"{path.Value} and its sub directories contain no solution files."); } Output.WriteLine($"{slnPaths.Count} solutions found."); Output.WriteBlankLines(); if (useTable != null) { WriteSlnDetailsAsTable(slnPaths); } else { WriteSlnDetails(slnPaths); } } catch (Exception ex) { HandleError(ex.Message); } sw.Stop(); Output.WriteBlankLines(); Output.WriteLine($"Time taken: {sw.Elapsed.TotalSeconds} seconds."); Output.WriteBlankLines(); }
/// <summary> /// Throw exception if user did not in any entity /// </summary> /// <param name="Arg"></param> internal static void GuardCurrentEntity(CmdArg Arg) { var theClass = Arg.GetShortCutSegment(0); if (theClass.StartsWith("SPC.UsrMan", StringComparison.OrdinalIgnoreCase) || theClass.MatchesRegExp(@"^SPC.Commands$|^SPC\.BO\.CD$|^SPC\.BO\.PS\.CD$")) { //system menu is ok } else { if (string.IsNullOrEmpty(Ctx.EntityInfo.CurrentBECode)) { ExceptionThower.BusinessRuleStop("Please select an Entity first.".Translate()); } } }
/// <summary> /// Returns the Name of the first argument Names supplied, if any. /// </summary> public string GetAnyArgName(params string[] args) { foreach (string arg in args) { string modArgName = ""; if (arg.StartsWith("-")) { modArgName = arg.Replace("-", ""); } CmdArg argFound = allCmdLines.Where(x => x.Name.ToLower() == modArgName.ToLower()).FirstOrDefault(); if (argFound != null) { return(argFound.Name); } } return(""); }
private static void ExecCmd(CmdArg cmdArg) { Reader red = new Reader(cmdArg.FileName, cmdArg.OutputFile, cmdArg.Encoding); if (cmdArg.CmdName == "head") { red.PrintHead(cmdArg.Lines); } else if (cmdArg.CmdName == "tail") { red.PrintTail(cmdArg.Lines); } else if (cmdArg.CmdName=="find") { red.PrintMatch(cmdArg.Keyword, cmdArg.Regex, cmdArg.ReadHead, cmdArg.IgnoreCase, cmdArg.Lines); } else { Console.WriteLine("命令有误!"); } }
private static void ExecCmd(CmdArg cmdArg) { Reader red = new Reader(cmdArg.FileName, cmdArg.OutputFile, cmdArg.Encoding); if (cmdArg.CmdName == "head") { red.PrintHead(cmdArg.Lines); } else if (cmdArg.CmdName == "tail") { red.PrintTail(cmdArg.Lines); } else if (cmdArg.CmdName == "find") { red.PrintMatch(cmdArg.Keyword, cmdArg.Regex, cmdArg.ReadHead, cmdArg.IgnoreCase, cmdArg.Lines); } else { Console.WriteLine("命令有误!"); } }
/// <summary> /// Returns the list of Names of all of the arguments supplied /// </summary> public List <string> GetAllArgNamesSupplied(params string[] args) { List <string> ret = new List <string>(); foreach (string arg in args) { string modArgName = ""; if ((arg.StartsWith("-") || arg.StartsWith("/")) && arg.Length > 1) { //modArgName = arg.Replace("-", ""); modArgName = arg.Substring(1); } CmdArg argFound = allCmdLines.Where(x => x.Name.ToLower() == modArgName.ToLower()).FirstOrDefault(); if (argFound != null) { ret.Add(argFound.Name); } } return(ret); }
public async Task <string> GenerateThumbnail(ILocalContent localContent) { var thumbnailPath = Path.Combine(FilePathHelper.THUMBNAIL_CACHE_DIRECTORY, "cached_" + localContent.Name.Replace(' ', '_')); if (!File.Exists(thumbnailPath)) { await CmdHelper.RunAsync(FilePathHelper.FFMPEG_PATH, new List <CmdArg> { CmdArg.Named("itsoffset"), CmdArg.Named("1"), CmdArg.Named("y"), new CmdArg("i", "\"" + localContent.Path + "\""), new CmdArg("vcodec", "mjpeg"), new CmdArg("vframes", ProgramSettings.VideoFrame.ToString()), CmdArg.Named("an"), new CmdArg("f", "rawvideo"), new CmdArg("s", ProgramSettings.ThumbnailWidth + "x" + ProgramSettings.ThumbnailHeight), CmdArg.Valued(thumbnailPath) }); } return(thumbnailPath); }
public void SendCommand(CmdArg arg) { Thread t = new Thread(new ParameterizedThreadStart(doUserCommand)); t.Name = "SendCommand"; t.Start(arg); }
Task IRunURLService.RunAsync(CmdArg Arg) { Open(Arg.Url); return(Task.CompletedTask); }
public LoadCommand() : base("load", "") { var param = new CmdArg <string>("param", "", LoadMovie); }
static int Main(string[] args) { string emailSenderPass = ""; string emailSenderSmtp = ""; bool noSSL = false; bool bInvalidArgs = false; CmdArg lastCmdSwitch = CmdArg.None; foreach (string arg in args) { switch (lastCmdSwitch) { case CmdArg.None: case CmdArg.EmailNoSSL: if (arg.Length > 1 && (arg[0] == '/' || arg[0] == '-')) { string option = arg.Substring(1); if (option == "username") { lastCmdSwitch = CmdArg.EmailSenderId; } else if (option == "pass") { lastCmdSwitch = CmdArg.EmailSenderPass; } else if (option == "smtp") { lastCmdSwitch = CmdArg.EmailSenderSmtp; } else if (option == "nossl") { lastCmdSwitch = CmdArg.EmailNoSSL; noSSL = true; } else { bInvalidArgs = true; } } else { bInvalidArgs = true; } break; case CmdArg.EmailSenderId: emailSenderId = arg; lastCmdSwitch = CmdArg.None; break; case CmdArg.EmailSenderPass: emailSenderPass = arg; lastCmdSwitch = CmdArg.None; break; case CmdArg.EmailSenderSmtp: emailSenderSmtp = arg; lastCmdSwitch = CmdArg.None; break; default: bInvalidArgs = true; break; } if (bInvalidArgs) { break; } } if (!bInvalidArgs) { bInvalidArgs = (emailSenderId == "") || (emailSenderSmtp == ""); } if (!bInvalidArgs && (emailSenderPass == "")) { Console.WriteLine("Type sender's email password for " + emailSenderId + ":"); ConsoleKeyInfo key; do { key = Console.ReadKey(true); if (key.Key != ConsoleKey.Backspace && key.Key != ConsoleKey.Enter) { emailSenderPass += key.KeyChar; Console.Write("*"); } else { if (key.Key == ConsoleKey.Backspace && emailSenderPass.Length > 0) { emailSenderPass = emailSenderPass.Substring(0, (emailSenderPass.Length - 1)); Console.Write("\b \b"); } } }while (key.Key != ConsoleKey.Enter); if (emailSenderPass == "") { bInvalidArgs = true; } Console.WriteLine("\n"); } if (bInvalidArgs) { Console.WriteLine("Invalid command line arguments. Usage: PdfLetterBulkMailer.exe -username <Sender's email Id> -smtp <Sender's smpt server[:port]>. Optional arguments: -pass <Sender's email password> -nossl"); return(1); } String record = null; try { using (StreamReader sr = new StreamReader("Letter.tex")) texBase = sr.ReadToEnd(); } catch (Exception) { Console.WriteLine("The source tex file could not be read."); return(2); } try { using (StreamReader sr = new StreamReader("EmailMessage.txt")) emailMsgBase = sr.ReadToEnd(); } catch (Exception) { Console.WriteLine("The source email message text file could not be read."); return(2); } smtpClient = new SmtpClient(); int colonIndex = emailSenderSmtp.IndexOf(':'); if (colonIndex != -1) { smtpClient.Host = emailSenderSmtp.Substring(0, colonIndex); if (emailSenderSmtp.Length > (colonIndex + 1)) { string smtpPort = emailSenderSmtp.Substring(colonIndex + 1); try { smtpClient.Port = Convert.ToInt32(smtpPort); } catch (Exception) { Console.WriteLine("The smtp server argument is invalid."); return(1); } } } else { smtpClient.Host = emailSenderSmtp; } NetworkCredential credentials = new NetworkCredential(emailSenderId, emailSenderPass); smtpClient.UseDefaultCredentials = false; smtpClient.Credentials = credentials; smtpClient.EnableSsl = !noSSL; //smtpClient.Timeout = 10000; //10,000 milli-seconds StreamReader donorDb = null; try { donorDb = new StreamReader("MailingListDb.csv"); } catch (Exception) { Console.WriteLine("The mailing list database file could not be read."); return(3); } try { StreamWriter successLog = new StreamWriter("Output\\Processed.log", true); StreamWriter failLog = new StreamWriter("Output\\Failed_" + DateTime.Now.ToString("HHmmss") + ".log", false); record = donorDb.ReadLine(); int recordNum = 0; while (record != null) { recordNum++; string recordCorrected = null; string [] quotedTokens = record.Split(new Char[] { '"' }); if (quotedTokens.Length > 2) { StringBuilder sb = new StringBuilder("");; sb.Append(quotedTokens[0]); for (int i = 1; i < (quotedTokens.Length - 1); ++i) { string token = quotedTokens[i]; if ((i % 2) != 0) { token = token.Replace(",", "^"); } sb.Append(token); } sb.Append(quotedTokens[quotedTokens.Length - 1]); recordCorrected = sb.ToString(); } else { recordCorrected = record; } string[] recordFields = recordCorrected.Split(new Char[] { ',' }); for (int i = 0; i < recordFields.Length; ++i) { if (i != 2) { recordFields[i] = recordFields[i].Replace("^", ""); } else { recordFields[i] = recordFields[i].Replace("^", ","); } } Console.WriteLine("Processing record: " + record); ErrorCode err; try { err = ProcessOneRecord(recordFields); switch (err) { case ErrorCode.Success: { break; } case ErrorCode.InvalidRecord: { Console.WriteLine("Skipped record as the required fields were not found."); break; } case ErrorCode.LatexError: { Console.WriteLine("The latex processor failed to create a pdf. Do you want to skip this record and continue?"); string consoleInput = Console.ReadLine(); consoleInput.ToUpper(); if (!((consoleInput == "Y") || (consoleInput == "Yes") || (consoleInput == "y") || (consoleInput == "yes"))) { return(5); } break; } case ErrorCode.EmailError: { Console.WriteLine("Could not send email."); break; } default: { Console.WriteLine("An unspecified error occurred while processing the record."); return(8); } } } catch (Exception ex) { Console.WriteLine("An error occurred while processing. Details: " + ex.Message); return(9); } if (err == ErrorCode.Success) { successLog.WriteLine(record); successLog.Flush(); } else { failLog.WriteLine(record); failLog.Flush(); } record = donorDb.ReadLine(); } successLog.Close(); failLog.Close(); } catch (Exception ex) { Console.WriteLine("An error occurred. Details: " + ex.Message); return(3); } return(0); }
public void doLogin(object o) { Account curAcc = (Account) o; if (curAcc == null) { return; } curAcc.bIsLogined = false; // 组装包发到登陆服务器 Dictionary<string, string> data = new Dictionary<string, string>(); data.Add("entry", "sso"); data.Add("callback", "sinaSSOController.preloginCallBack"); data.Add("su", base64_encode("undefined")); data.Add("rsakt", "mod"); data.Add("client", "ssologin.js(v1.4.2)"); data.Add("_", UnixTimeStamp(DateTime.Now).ToString()); string strSvrTimeURL = "sso/prelogin.php?" + CreateQueryString(data); string result = curAcc.PageQuery("login.sina.com.cn", strSvrTimeURL); // 解析并获得加密公钥等信息 string strSvrTime, pcid, nonce, pubkey, rsakv; Match m = Regex.Match(result, "\"servertime\":(.*?),\"pcid\":\"(.*?)\",\"nonce\":\"(.*?)\"," + "\"pubkey\":\"(.*?)\",\"rsakv\":\"(.*?)\"", RegexOptions.Singleline); if (!m.Success) { DebugLog("无法解析[sso/prelogin.php]"); return; } strSvrTime = m.Groups[1].Value; pcid = m.Groups[2].Value; nonce = m.Groups[3].Value; pubkey = m.Groups[4].Value; rsakv = m.Groups[5].Value; // 组装登陆包 Random r = new Random(); data.Clear(); data.Add("entry", "weibo"); data.Add("gateway", "1"); data.Add("from", ""); data.Add("savestate", "7"); data.Add("useticket", "1"); data.Add("vsnf", "1"); data.Add("ssosimplelogin", "1"); data.Add("su", base64_encode(curAcc.strUserName)); data.Add("service", "miniblog"); data.Add("servertime", strSvrTime); data.Add("nonce", nonce); data.Add("pwencode", "rsa2"); data.Add("rsakv", rsakv); data.Add("sp", PswRSAEncode(curAcc.strPassword, pubkey, strSvrTime, nonce)); data.Add("encoding", "UTF-8"); data.Add("prelt", r.Next(100, 150).ToString()); data.Add("url", "http://weibo.com/ajaxlogin.php?framelogin=1&callback=parent.sinaSSOController.feedBackUrlCallBack"); data.Add("returntype", "META"); // 发送登陆包,解析出微博的登陆URL result = curAcc.PageQuery("login.sina.com.cn", "sso/login.php?client=ssologin.js(v1.4.2)", data, Encoding.GetEncoding("GBK")); m = Regex.Match(result, "location\\.replace\\(\"http://weibo\\.com/(.*?)\"\\);", RegexOptions.Singleline); if (!m.Success) { DebugLog("无法解析[sso/login.php]\r\n" + result); return; } string strLoginURL = m.Groups[1].Value; // 登陆微博,并解析出微博用户ID result = curAcc.PageQuery("weibo.com", strLoginURL); m = Regex.Match(result, "\"uniqueid\":\"(.*?)\",", RegexOptions.Singleline); if (!m.Success) { DebugLog("无法解析[weibo.com/ajaxlogin.php],可能因为手机端或其他电脑的客户端已经登入新浪微博,请先从这些客户端登出\r\n" + result); return; } // 利用微博用户ID获得游戏登陆地址及游戏会话信息 result = curAcc.PageQuery("game.weibo.com", "mengjiangwushuang?origin=" + ServerParam.strOrigin); m = Regex.Match(result, "mjwssina\\.app\\.koramgame\\.com(.*?)\"", RegexOptions.Singleline); if (!m.Success) { DebugLog("无法解析[game.weibo.com/mengjiangwushuang]"); return; } string koram_url_param = m.Groups[1].Value; m = Regex.Match(koram_url_param + "END", "origin=(.*?)&wyx_user_id=(.*?)&wyx_session_key=(.*?)&wyx_create=(.*?)&wyx_expire=(.*?)&wyx_signature=(.*?)END", RegexOptions.Singleline); if (!m.Success) { DebugLog("无法解析出会话信息!"); return; } ServerParam.strOrigin = m.Groups[1].Value; curAcc.wyx_user_id = m.Groups[2].Value; curAcc.wyx_session_key = m.Groups[3].Value; curAcc.wyx_create = m.Groups[4].Value; curAcc.wyx_expire = m.Groups[5].Value; curAcc.wyx_signature = m.Groups[6].Value; // 组装游戏页面URL data.Clear(); data.Add("act", ServerParam.strAct); data.Add("wyx_user_id", curAcc.wyx_user_id); data.Add("wyx_session_key", curAcc.wyx_session_key); data.Add("wyx_create", curAcc.wyx_create); data.Add("wyx_expire", curAcc.wyx_expire); data.Add("wyx_signature", curAcc.wyx_signature); data.Add("serverId", ServerParam.strServerID); koram_url_param = "?" + CreateQueryString(data); // 获取游戏页面并获取游戏版本号以及swf下载地址 result = curAcc.PageQuery(ServerParam.strGameSvr, koram_url_param); m = Regex.Match(result, "embedSWF\\(\"(.*?)=(.*?)\"", RegexOptions.Singleline); if (!m.Success) { DebugLog("无法解析出版本号以及swf下载地址!"); return; } ServerParam.strSWFDownLoadURL = m.Groups[1].Value + "=" + m.Groups[2].Value; ServerParam.strVersion = m.Groups[2].Value; // 获取游戏资料 CmdArg arg = new CmdArg(CmdIDs.USER_GET_INFO, curAcc); this.doUserCommand(arg); curAcc.bIsLogined = true; curAcc.QrySta = QueryStatus.Logined; DebugLog("已成功登陆!"); }
private async Task RunTaskAsync(CmdArg Arg) { try { if (Arg.Action == Helper.Action._Help) { SPC.Services.InternetChecker.OnlineGuard(); string Topic = Arg.ShortCut; if (!string.IsNullOrEmpty(Topic)) { WaitingService.Wait("Openning Online Help".Translate(), Arg.Url); var theHelpUrl = await SPC.Cloud.HelpService.GetHelpTopicUrlAsync(Topic); nav.NavigateTo(theHelpUrl); WaitingService.Done(); } } else if (Arg.GetShortCutSegment(0).Equals("Debug", StringComparison.OrdinalIgnoreCase)) { var onoff = Arg.GetDefaultParameter(); if (string.IsNullOrEmpty(onoff)) { Ctx.AppConfig.DebugMode = !Ctx.AppConfig.DebugMode; } else { Ctx.AppConfig.DebugMode = onoff.ToBoolean(); } AlertService.Toast($"Debug Mode is : {(Ctx.AppConfig.DebugMode ? "ON" : "OFF")}"); } else if (Arg.Url.StartsWith("http", StringComparison.OrdinalIgnoreCase)) //Open online resources { WaitingService.Wait("Openning browser", Arg.Url); nav.NavigateTo(Arg.Url); WaitingService.Done(); } else if (Arg.Url.StartsWith(@"/", StringComparison.OrdinalIgnoreCase)) //Open Local files { WaitingService.Done(); } else if (Arg.Url.StartsWith(@"mailto://", StringComparison.OrdinalIgnoreCase)) { WaitingService.Wait("Composing mail ...", ""); nav.NavigateTo(Arg.Url); WaitingService.Done(); } else if (Arg.Url.MatchesRegExp(@"^[A-Za-z]+://")) //Open other apps "lyft:// { WaitingService.Done(); } else if (Arg.Action.MatchesRegExp("^Insert$|^Update$|^InsertUpdate$|^UpdateAll$|^Delete$|^DeleteAll$")) //NON-UI Commands { WaitingService.Wait(Arg.Action, Arg.Url); await SPC.Commands.NonUIActionRunner.RunURLCommandAsync(Arg); WaitingService.Done(); } else { var pClass = SPCTypes.GetClassType(Arg.GetShortCutSegment(0), true); if (pClass != null) { //Runable non UI command if Action = Run or the command is not a mix of Editable and Runnable if (pClass.GetInterfaces().Contains(typeof(IRunable)) && (Arg.Action == Helper.Action._Run || !pClass.GetInterfaces().Contains(typeof(IEditable)))) { var Sample = BOFactory.CreateSample(pClass) as IRunable; await Sample.RunAsync(Arg); } //Class is ISupportQueryInfoList and the Action = Select else if (Arg.Action == Helper.Action._Select && pClass.GetInterfaces().Contains(typeof(SPC.Interfaces.ISupportQueryInfoList))) //Query BO { if (BOFactory.CreateSample(pClass) is ISupportQueryInfoList sample) { var theList = await sample.GetInfoListAsync(Arg.GetDictionary()) as IList; await ValueSelector.SelectAsync(theList, "Info List"); } } else { AlertService.Toast($"Could not find any suitable Page for class : {Arg.ShortCut}"); WaitingService.Done(); } } else //Short Command is not a class { WaitingService.Done(); AlertService.Toast($"Could not find the class {Arg.GetShortCutSegment(0)}"); } } } catch (Exception ex) { WaitingService.Done(); if (ex.GetType() == typeof(NullReferenceException)) //file extension is not support by ios { try { AlertService.ShowError(ex); } catch (Exception ex1) { //ExceptionHandler.LogAndAlert(ex1); // AlertService.ShowError(ex1); } } //if (ex.GetType() == typeof(ExitScriptException)) //file extension is not support by ios //ExceptionHandler.LogAndToast(ex); //else //ExceptionHandler.LogAndAlert(ex); //AlertService.ShowError(ex); } }
Task IRunURLService.RunAsync(CmdArg Arg) { return(RunTaskAsync(Arg)); }
public GetCommand() : base("get", "") { var param = new CmdArg("param", ""); //param.AddArgument }
/// <summary> /// Core method - Initalizes an argument list (which will be returned) given a string array of command line arguments /// </summary> private List <CmdArg> ParseArgs(string[] argArray, bool includeSpecialCommands = false) { // Note: // 'argArray' needs to be a linear list of Arg Name (ex: "-Say") followed next by its Arg Value (ex: "Hello"), Name, Value, ... List <CmdArg> retList = new List <CmdArg>(); CmdArg currArg = null; bool currentArgAdded = true; // (true: start out like a previous argument was successfully added) // Flag used to prevent checking for "-" or "/" in parameters that are nested and meant to be passed on to the next application's command line, // which will also use the same special characters. bool passEverything = false; bool startingPassAllIndicator = false; bool startedPassAllRightNow = false; // Now adding support to [A] nesting like [A1] [A1], [A2] [A2] (possibly add support for any number later)... // See ParseArgs_NestingCheck // Arguments here within the argArray will be separated out by spaces (like a split on " ") // So the logic in this loop determines which arguments to combine, and which ones are separate based on special argument characters encountered: // Those are "-" or "/". bool startOfNewArgument = true; bool turnOffSlashSwitch = false; bool turnOffDashSwitch = false; for (int i = 0; i < argArray.Length; i++) { var argStr = argArray[i].Trim(); // 8-9-17 // Always reset -- only set on first encountered [a] if (startingPassAllIndicator) { // Reset this flag startingPassAllIndicator = false; string startingString = StringSupportMethods.FindStartingString(argStr, PASS_ALL_INDICATORS); if (!StringSupportMethods.IsStringNullOrWhitespace(startingString) && startingString.ToLower().Trim() == argStr.ToLower().Trim()) { // In this case, this will be the ending [a], so just stop passEverything, and this loop execution can be completly skipped passEverything = false; continue; } } // Always reset startedPassAllRightNow = false; // Always recheck to see if the current argument begins with the "include-everything", which is a single double-quote (but the argName / caller has to escape it via 3 double quotes: """) // This is re-evaluated below if (passEverything == false) { // Special args: // -disableSlash // -disableDash // If found, then "-" or "/" will not be considered the start of a new argument // This is an alternative to specifying [a] or [all] around a string such as: -a [a] cmd.exe /k ... [a] --> -noSlash -a cmd.exe /k ... if (!includeSpecialCommands && (DisableSlash || argStr.ToLower() == "-disableslash")) { turnOffSlashSwitch = true; WasDashOrSlashDisabled = true; continue; } else if (!includeSpecialCommands && (DisableDash || argStr.ToLower() == "-disabledash")) { turnOffDashSwitch = true; WasDashOrSlashDisabled = true; continue; } // If a quote is encountered, it means that the user escaped it in the command line by passing it as """ // When this occurs it means to pass everything through in this current parameter (meaning I can nest in other single "-" or "/" as special chars to a sub-application that also uses these, like cmd.exe, or another application that I created which uses this parser) passEverything = StringSupportMethods.StartsWithAny_NoCase(argStr, PASS_ALL_INDICATORS); if (passEverything && currArg != null) { currArg.FullArgSupplied = true; startingPassAllIndicator = true; // Prevention of setting disablePassEverything to true below when checking to see if the string is the ending [A] startedPassAllRightNow = true; } //startOfNewArgument = true; } else { // Always disable startingPassAllIndicator unless it was just enabled for the first [A] if (!startedPassAllRightNow) { startingPassAllIndicator = false; } } // // New arg or not? // // Start a new arg if the current string begins with a "-" or "/" if (passEverything == false && ((!turnOffDashSwitch && argStr.StartsWith("-")) || (!turnOffSlashSwitch && argStr.StartsWith("/")))) { // // New argument to add // startOfNewArgument = true; // If a new arg was encountered before the previous argument's value, then simply add in the previous argument if (currentArgAdded == false) { if (currArg != null) { retList.Add(currArg); currentArgAdded = true; } } // Start the new arg currArg = new CmdArg(); if (argStr.Length > 1) { // Store the argument Name currArg.ArgDelimiterUsed = argStr.Substring(0, 1); // the "-" or "/" char currArg.Name = argStr.Substring(1); // Remove the "-" or "/" start of the argument Name currentArgAdded = false; } } else { // // Not a new argument (so append this onto the current one in progress) // // If this is not a new arg Name, then this string is added to the current argument's value if (currArg != null) { // Note: // If the current argument has data in it from the previous array value, then that means there was a space in the cmdline parsed from CommandLineToArgvW // and hence can be preserved by adding 1 space // HOPEFULLY only is one space in the Name, if 2 spaces back-to-back, then this could be problematic, as we wouldn't know, unless implementing our own CommandLineToArgvW parser bool disablePassEverything = false; if ( !startOfNewArgument && // Prevent the starting [a] from being looked at as the ending [a] (not sufficient, need the next check too: !startedPassAllRightNow) !startedPassAllRightNow && // Set to true if this is the starting [a] Added - 8-9-17 passEverything && StringSupportMethods.EndsWithAny_NoCase(argStr, PASS_ALL_INDICATORS) ) { // Stop the PassEverything sequence if this argument ends with the quote disablePassEverything = true; argStr = StringSupportMethods.ReplaceAny_NoCase(argStr, PASS_ALL_INDICATORS, ""); } else if (currArg.FullArgSupplied) { // 8-9-17 // Passing something like this: -u0 -s [a]-1[a] -a [a] C:\Program Files (x86)\Tweaking.com\Registry Backup\TweakingRegistryBackup.exe /silent [a] // Causes the pass-all to occur all the way to the end after the first set of [a] [a], since there is no space in that value (between the [a]s). // Hence its all grouped under -s, and no -a is seen as another argument // Therefore a check must be done to see if the string ends in [a] (excluding if its the starting [a] in the event that the user did pass in spaces) string startingString = StringSupportMethods.FindStartingString(argStr, PASS_ALL_INDICATORS); if (!StringSupportMethods.IsStringNullOrWhitespace(startingString) && // MUST check for IsNullOrWhitespace, otherwise EndsWith will return true for ending with "" (a blank string)... probably the same for starts with argStr.Length > startingString.Length) { // This shows that this scenario is possibly like this: [a]-1[a] That is, [a]-1[a] length is greater than [a] // Must check the length for it being grater, otherwise having the argStr just be [a] (that is a space was added between this and the actual full string), would incorrectly satisfy StartsWith and EndsWith // However its possible that a space was added, so therefore we now must check to see if the string ends with this indicator if (argStr.EndsWith(startingString, StringComparison.CurrentCultureIgnoreCase)) { // Go ahead and just disable Pass Everything now (we could just set startingPassAllIndicator = false to satisfy the condition below, but we truly just want disablePassEverything to disable it at the end of this method) disablePassEverything = true; } } // Fix / Check - 11-13-16 // Before replacing [A] or [ALL], need to check if the string already ends with [A] or [ALL] in the event that no space was provided in the trailing [a] or [all] // Ex: -s [a]-2[a] -d hello -s would incorrectly include everything else // -s [a]-a [a] -d hello This would work, but we don't want to rely on the user having to remember that a space in the trailing [a] is required if ( passEverything && !startingPassAllIndicator && // Ensures that this is not turned off on the first encountered [A] // Using EndsWith in the event that no space was provided at the end and the [A] is right next to the last char and is included in this token StringSupportMethods.EndsWithAny_NoCase(argStr, PASS_ALL_INDICATORS) ) { disablePassEverything = true; } argStr = StringSupportMethods.ReplaceAny_NoCase(argStr, PASS_ALL_INDICATORS, ""); startOfNewArgument = false; // Toggle off now, since this is going to be a string of arguments until an ending [a] is found } // // Update the arg value // // Always add a space between the args, which is possible until a new switch is encountered - 11-1-16 if (!StringSupportMethods.IsStringNullOrWhitespace(currArg.Value)) // Will be blank if this was a [a] { argStr = " " + argStr; } // Need to trim off any quotes, which may have been supplied in order to pass in a negative value, like "-1", which will be undesirably returned when called GetArgValue (since it cannot be parsed into an int) if (!passEverything) { argStr = StringSupportMethods.TrimQuotes(argStr); } // Store the Argument Value currArg.Value += argStr; // Optionally add it in the list -- Only add in this argument if its a brand new one if (startOfNewArgument && !StringSupportMethods.IsStringNullOrWhitespace(currArg.Value.Trim())) { retList.Add(currArg); // [Re]set flags: currentArgAdded = true; startOfNewArgument = false; } // Lastly, toggle off the special case flag once complete if (disablePassEverything) { passEverything = false; } } } } // foreach arg // If this loop finished (no more arguments), and the last argument wasn't added (it didn't have a value) then add it in if (currentArgAdded == false) { if (currArg != null) { retList.Add(currArg); } } // Ensure everything is tidy for (int i = 0; i < retList.Count; i++) { retList[i].Value = retList[i].Value.Trim(); } return(retList); }