public ActionResult Slogin(SocialNetworks social) { var res = new OperationResult <string>(); try { switch (social) { case SocialNetworks.Fb: { break; } case SocialNetworks.Go: { break; } case SocialNetworks.Ig: { break; } case SocialNetworks.In: { break; } case SocialNetworks.Tw: { break; } case SocialNetworks.Vk: { res = new Social.Vk.Auth().Authorization(); break; } case SocialNetworks.Yt: { break; } default: return(Json(new { IsSuccess = false })); } } catch (Exception ex) { _log.AddError("[Account]/[Login]", ex.Message); } return(res.IsSuccess ? Json(new { IsSuccess = true, Html = StringManager.CleanFromXmlTags(res.Data) }) : Json(new { IsSuccess = false, Data = res })); }
private static void AdminFunction() { logger.AddLog(LogLevel.Trace, "Admin function enter"); Console.WriteLine("Hello from my Main :)"); logger.AddError("some error occured"); logger.AddLog(LogLevel.Trace, "Admin function exit"); }
public ActionResult GetState() { try { var parlourPath = Settings.UserParlourPath; var session = new PrivateSession().Current; _log.AddInfo("GetState", "User: "******" IsAuthenticated: " + User.Identity.IsAuthenticated); if (session.User != null) { if (session.User.IsAdmin) { parlourPath = Settings.AdminParlourPath; } if (session.User.IsModerator) { parlourPath = Settings.ModeratorParlourPath; } return(Json(new { IsEnabled = true, IsAuthanticated = session.User.IsEnabled, ImagePath = !string.IsNullOrEmpty(session.User.UserLogoPath) ? session.User.UserLogoPath : Settings.DefaulLogoPath, UserName = session.User.Name, ParlourPath = parlourPath, SessionId = session.User.Id, Groups = session.User.SubscribeToGroups })); } if (!User.Identity.IsAuthenticated) { return(Json(new { IsEnabled = false, IsAuthanticated = false, ImagePath = (string)null, ParlourPath = (string)null })); } session.User = _user.GetUserInfo(Guid.Parse(User.Identity.Name)); if (session.User.IsAdmin) { parlourPath = Settings.AdminParlourPath; } if (session.User.IsModerator) { parlourPath = Settings.ModeratorParlourPath; } return(Json(new { IsEnabled = true, IsAuthanticated = session.User.IsEnabled, ImagePath = !string.IsNullOrEmpty(session.User.UserLogoPath) ? session.User.UserLogoPath : Settings.DefaulLogoPath, UserName = session.User.Name, ParlourPath = parlourPath, SessionId = session.User.Id, Groups = session.User.SubscribeToGroups })); } catch (Exception ex) { _log.AddError("GetState", ex.Message); return(Json(new { IsEnabled = false, IsAuthanticated = false, ImagePath = (string)null, ParlourPath = (string)null })); } }
private void AddNotReachedEnd(Token token) { log.AddError(token.Position.ToString() + ": Didn't reach end, currently at " + token.ToString()); switch (token.Type) { case TokenType.Comma: log.AddError("Maybe you tried to use a non-defined Macro?"); break; case TokenType.IntegerLiteral: log.AddError("Maybe this number isn't formatted properly?"); break; } }
static public async Task <string> PerformQuery(string name, WISA.TWISAAPIParamValue[] values) { return(await Task.Run(() => { try { var data = service.GetCSVData(credentials, name, values, true, ",", ""); return Encoding.Default.GetString(data); } catch (Exception e) { Log?.AddError(Origin.Wisa, e.Message); return String.Empty; } })); }
private void AddPointerListCodes(int offset, int[] pointerList, SortedDictionary <int, Code> lines, ILog log) { CanCauseError <ICodeTemplate> template = this.codeStorage.FindTemplate("POIN", Priority.pointer); if (template.CausedError) { log.AddError(template.ErrorMessage); } else { ICodeTemplate result = template.Result; int index1 = 0; for (int index2 = 0; index2 < this.pointerList.Length; ++index2) { List <string> stringList = new List <string> (); stringList.Add(result.Name); int offset1 = offset + 4 * index1; for (int index3 = 0; index3 < this.pointerList [index2].Length; ++index3) { stringList.Add(pointerList [index1].ToHexString("$")); ++index1; } lines [offset1] = new Code(stringList.ToArray(), result, this.pointerList [index2].Length * 4, offset1); } } }
private byte[] GetDataUnit(string[] text, ILog messageLog) { byte[] code = this.baseData.Clone() as byte[]; for (int index1 = 1; index1 < text.Length; ++index1) { TemplateParameter templateParameter = this[index1 - 1]; if (templateParameter.lenght > 0) { string[] strArray = text[index1].Trim('[', ']').Split(new char[1] { ',' }, templateParameter.maxDimensions, StringSplitOptions.RemoveEmptyEntries); int[] values = new int[strArray.Length]; for (int index2 = 0; index2 < strArray.Length; ++index2) { if (!strArray[index2].GetMathStringValue(out values[index2])) { messageLog.AddError(strArray[index2] + " is not a valid number."); } if (templateParameter.pointer) { values[index2] = this.pointerMaker.MakePointer(values[index2]); } } templateParameter.InsertValues(values, code); } } return(code); }
public IEnumerable <string[]> DisassembleChapter(byte[] rom, int offset, ILog log, bool addEndingLines) { List <int> intList = new List <int> (); SortedDictionary <int, Code> codeMap = new SortedDictionary <int, Code> (); SortedDictionary <int, string> labelMap = new SortedDictionary <int, string> (); labelMap [offset] = "PointerList"; foreach (Tuple <int, Tuple <string, List <Priority> > > tuple in pointerList.SelectMany(x => x).Index()) { int pointerOffset = offset + 4 * tuple.Item1; int pointer = BitConverter.ToInt32(rom, pointerOffset); if (this.pointerMaker.IsAValidPointer(pointer)) { int codeOffset = pointerMaker.MakeOffset(pointer); intList.Add(codeOffset); if (codeOffset > 0 && !labelMap.ContainsKey(codeOffset)) { labelMap.Add(codeOffset, tuple.Item2.Item1); foreach (Code code in FindTemplatesUntil(rom, codeOffset, codeMap, tuple.Item2.Item2, x => x.EndingCode, log)) { codeMap [code.Offset] = code; } } } else { log.AddError("Invalid pointer {0} at offset {1} in pointer list.", new object[2] { pointer.ToHexString("$"), pointerOffset }); return(Enumerable.Empty <string[]> ()); } } this.FindPointedCodes(rom, (IEnumerable <Code>)codeMap.Values, codeMap, log); this.FindLables((IDictionary <int, Code>)codeMap, (IDictionary <int, string>)labelMap); this.MergeRepeatableCodes(codeMap, (Predicate <int>)(x => !labelMap.ContainsKey(x))); this.AddPointerListCodes(offset, intList.ToArray(), codeMap, log); /* * * // Why was this a thing? To test stuff? * // This breaks empty pointer lists (right now used for non-FE languages) * * KeyValuePair<int, Code> keyValuePair = sortedDictionary.Last (); * * int key = keyValuePair.Key; * int length = keyValuePair.Value.Length; * */ return(this.GetLines(codeMap, labelMap, addEndingLines)); }
public void Assemble(IPositionableInputStream input, BinaryWriter output, ILog log) { var assemblyContext = new AssemblyContext <T>(log, output); var scanner = new TokenScanner(input); if (!scanner.MoveNext()) { return; } Match <Token> match; var tree = parser.Parse(scanner, out match); if (!match.Success) { log.AddError(match.Error);// + " " + inputStream.PeekOriginalLine() return; } if (scanner.IsAtEnd) { log.AddError("Consumed all input. Shouldn't have happened."); return; } if (scanner.Current.Type != TokenType.EndOfStream) { log.AddError(scanner.Current.Position + ": Didn't reach end, currently at " + scanner.Current); return; } assemblyContext.CurrentOffset = (int)output.BaseStream.Position; foreach (var item in FirstPass(tree, assemblyContext)) { assemblyContext.AddCodeData(item.code, item.offset, item.template); } assemblyContext.CurrentOffset = (int)output.BaseStream.Position; SecondPass(tree, assemblyContext); }
public ActionResult Index() { try { var session = new PrivateSession().Current; if (User.Identity.IsAuthenticated && session.User == null) { session.User = _user.GetUserInfo(Guid.Parse(User.Identity.Name)); } } catch (Exception ex) { _log.AddError("[HomeController]/[Index]", ex.Message); } return(View()); }
// Used by Emblem Magic (and could potentially be used by other external software) public static void Disassemble( EACodeLanguage language, byte[] rom, string filename, TextWriter output, bool addEndGuards, DisassemblyMode mode, int offset, Priority priority, int size, ILog log) { if (offset > rom.Length) { log.AddError("Offset is larger than size of ROM."); } if (size <= 0 || size + offset > rom.Length) { size = rom.Length - offset; } IEnumerable <string[]> strArrays; string[] lines; switch (mode) { case DisassemblyMode.Block: strArrays = language.Disassemble(rom, offset, size, priority, addEndGuards, log); lines = CoreInfo.DefaultLines(language.Name, Path.GetFileName(filename), offset, new int?(size)); break; case DisassemblyMode.ToEnd: strArrays = language.DisassembleToEnd(rom, offset, priority, addEndGuards, log); lines = CoreInfo.DefaultLines(language.Name, Path.GetFileName(filename), offset, new int?()); break; case DisassemblyMode.Structure: strArrays = language.DisassembleChapter(rom, offset, addEndGuards, log); lines = CoreInfo.DefaultLines(language.Name, Path.GetFileName(filename), offset, new int?()); break; default: throw new ArgumentException(); } if (log.ErrorCount == 0) { if (filename.Length > 0) { output.WriteLine(Program.Frame(lines, "//", 1)); output.WriteLine(); } foreach (string[] strArray in strArrays) { output.WriteLine(((IEnumerable <string>)strArray).ToElementWiseString(" ", "", "")); } } }
public static void Init(string url, int port, string accountName, string password, string database, ILog log = null) { Log = log; credentials = new WISA.TWISAAPICredentials(); credentials.Username = accountName; credentials.Password = password; credentials.Database = database; service = new WISA.WisaAPIServiceService(); try { service.Url = "http://" + url + ":" + port.ToString() + "/SOAP/"; } catch (Exception e) { Log?.AddError(Origin.Wisa, e.Message); } }
private string[] HandleLabels(IPositionableInputStream input, Context assemblyContext, ILog log, string[] code) { string labelName = code[0].TrimEnd(':'); if (IsValidLableName(labelName)) { assemblyContext.AddLabel(labelName); } else { log.AddError(input.GetErrorString( string.Format("Invalid label name {0}", labelName))); } string[] temp = new string[code.Length - 1]; Array.Copy(code, 1, temp, 0, temp.Length); code = temp; return(code); }
public void Compile(IPositionableInputStream input, TextWriter output, ILog log) { this.log = log; this.offsetHistory = new Stack <int> (); this.protectedRegions = new List <Tuple <int, int> > (); this.scopeStructures = new Dictionary <IExpression <int>, ScopeStructure <int> > (); TokenScanner tokenScanner = new TokenScanner(input); if (!tokenScanner.MoveNext()) { return; } Match <Token> match; IExpression <int> expression = parser.Parse(tokenScanner, out match); if (!match.Success) { log.AddError(match.Error); return; } if (!tokenScanner.IsAtEnd && tokenScanner.Current.Type != TokenType.EndOfStream) { AddNotReachedEnd(tokenScanner.Current); return; } if (log.ErrorCount == 0) { this.currentOffset = 0; // DeclareExternASMCLabels(ExecuteLayoutPass<TextWriter> (expression, null,output), output); ExecuteLayoutPass <TextWriter>(expression, null, output); } if (log.ErrorCount == 0) { this.currentOffset = 0; ExecuteWritePass(output, expression, null); } }
public static void Init(string site, string password, ILog log = null) { try { service = new V3Service { Url = "https://" + site + ".smartschool.be/Webservices/V3" }; Connector.password = password; Connector.log = log; Error.GetCodes(); } catch (Exception e) { if (log != null) { log.AddError(Origin.Smartschool, e.Message); } } }
private static void SecondPass(IEnumerable <KeyValuePair <INamed <string>, string[]> > codes, Context assemblyContext, ILog log, BinaryWriter output) { foreach (var code in codes) { //Insert labels and currentOffsetCode for (int i = 1; i < code.Value.Length; i++) { int offset; if (code.Value[i].Equals(currentOffsetCode, StringComparison.OrdinalIgnoreCase)) { code.Value[i] = assemblyContext.Offset.ToString(); } else if (assemblyContext.TryGetLabelOffset(code.Value[i], out offset)) { code.Value[i] = offset.ToString(); } } if (code.Key is IBuiltInCode) { var error = ((IBuiltInCode)code.Key).SecondPass(code.Value, assemblyContext); if (error) { log.AddError(error.ErrorMessage); } else if (error.Result) { output.Seek(assemblyContext.Offset, SeekOrigin.Begin); } } else if (code.Key is ICodeTemplate) { output.Write(((ICodeTemplate)code.Key).GetData(code.Value, log)); assemblyContext.Offset = (int)output.BaseStream.Position; } } }
private IEnumerable <Code> FindTemplates(byte[] code, int offset, int lengthToDiss, SortedDictionary <int, Code> lines, IEnumerable <Priority> prioritiesToUse, ILog log) { int currOffset = offset; while (currOffset - lengthToDiss < offset) { Code ccode; if (!lines.TryGetValue(currOffset, out ccode)) { CanCauseError <Code> res = this.GetCode(code, currOffset, prioritiesToUse); if (res.CausedError) { log.AddError(res.ErrorMessage); } else { ccode = res.Result; yield return(res.Result); } } currOffset += ccode.Length; } }
private IEnumerable <Code> FindTemplatesUntil(byte[] code, int offset, SortedDictionary <int, Code> lines, IEnumerable <Priority> prioritiesToUse, Predicate <ICodeTemplate> predicate, ILog log) { while (offset < code.Length) { Code ccode; if (!lines.TryGetValue(offset, out ccode)) { CanCauseError <Code> res = this.GetCode(code, offset, prioritiesToUse); if (res.CausedError) { log.AddError(res.ErrorMessage); break; } ccode = res.Result; yield return(res.Result); } if (predicate(ccode.Template)) { break; } offset += ccode.Length; } }
public static void Assemble(string inputFile, string outputFile, string languageName, ILog messageLog) { TextReader reader; bool close; if (inputFile != null) { reader = File.OpenText(inputFile); close = true; } else { reader = Console.In; close = false; } EACodeLanguage language = languages[languageName]; if (outputFile != null) { if (File.Exists(outputFile)) { if (File.GetAttributes(outputFile).HasFlag(FileAttributes.ReadOnly)) { messageLog.AddError("outputFile is read-only."); goto end; } } var cache = new ChangeStream(); using (BinaryWriter writer = new BinaryWriter(cache)) { Assemble(language, reader, writer, messageLog); if (messageLog.ErrorCount == 0) { using (Stream stream = File.OpenWrite(outputFile)) { cache.WriteToFile(stream); } } } } else { messageLog.AddError("outputFile needs to be specified for assembly."); } end: if (close) reader.Close(); }
public static void Disassemble(string inputFile, string outputFile, string languageName, bool addEndGuards, DisassemblyMode mode, int offset, Priority priority, int size, ILog messageLog) { if (!File.Exists(inputFile)) { messageLog.AddError("File " + inputFile + " doesn't exist."); return; } else if (File.Exists(outputFile)) { if (File.GetAttributes(outputFile).HasFlag(FileAttributes.ReadOnly)) { messageLog.AddError("Output cannot be written to. It is read-only."); return; } } EACodeLanguage language = languages[languageName]; byte[] data = File.ReadAllBytes(inputFile); if (offset > data.Length) { messageLog.AddError("Offset is larger than size of file."); } else { if (size <= 0 || size + offset > data.Length) { size = data.Length - offset; } IEnumerable<string[]> code; string[] defaultLines; switch (mode) { case DisassemblyMode.Block: code = language.Disassemble(data, offset, size, priority, addEndGuards, messageLog); defaultLines = CoreInfo.DefaultLines(language.Name, Path.GetFileName(inputFile), offset, size); break; case DisassemblyMode.ToEnd: code = language.DisassembleToEnd(data, offset, priority, addEndGuards, messageLog); defaultLines = CoreInfo.DefaultLines(language.Name, Path.GetFileName(inputFile), offset, null); break; case DisassemblyMode.Structure: code = language.DisassembleChapter(data, offset, addEndGuards, messageLog); defaultLines = CoreInfo.DefaultLines(language.Name, Path.GetFileName(inputFile), offset, null); break; default: throw new ArgumentException(); } if (messageLog.ErrorCount == 0) { using (StreamWriter sw = new StreamWriter(outputFile)) { sw.WriteLine(); sw.WriteLine(Frame(defaultLines, "//", 1)); sw.WriteLine(); foreach (string[] line in code) { sw.WriteLine(line.ToElementWiseString(" ", "", "")); } } } } }
public IEnumerable<string[]> DisassembleChapter(byte[] code, int offset, ILog log, bool addEndingLines) { List<int> pointerlistValues = new List<int>(); SortedDictionary<int, Code> lines = new SortedDictionary<int, Code>(); SortedDictionary<int, string> labels = new SortedDictionary<int, string>(); labels[offset] = "PointerList"; foreach (var item in this.pointerList.Flatten().Index()) { int pointerOffset = offset + 4 * item.Item1; int pointer = BitConverter.ToInt32(code, pointerOffset); if (this.pointerMaker.IsAValidPointer(pointer)) { int offsetVal = this.pointerMaker.MakeOffset(pointer); pointerlistValues.Add(offsetVal); if (offsetVal > 0 && !labels.ContainsKey(offsetVal)) { labels.Add(offsetVal, item.Item2.Item1); FindTemplatesUntil(code, offsetVal, lines, item.Item2.Item2, x => x.EndingCode, log); } } else { log.AddError("Invalid pointer at pointer list: " + pointer.ToHexString("$")); return Enumerable.Empty<string[]>(); } } FindPointedCodes(code, lines, log); FindLables(lines, labels); MergeRepeatableCodes(lines, x => !labels.ContainsKey(x));//Can cause labels to get omitted, needs to be fixed. //After merging because I want custom format AddPointerListCodes(offset, pointerlistValues.ToArray(), lines, log); KeyValuePair<int, Code> last = lines.Last(); int length = last.Key + last.Value.Length - offset; return GetLines(lines, labels, addEndingLines); }
private void AddPointerListCodes(int offset, int[] pointerList, SortedDictionary<int, Code> lines, ILog log) { var pointerTemplateResult = codeStorage.FindTemplate("POIN", Priority.pointer); if (pointerTemplateResult.CausedError) { log.AddError(pointerTemplateResult.ErrorMessage); } else { var pointerTemplate = pointerTemplateResult.Result; int totalIndex = 0; for (int i = 0; i < this.pointerList.Length; i++) { List<string> line = new List<string>(); line.Add(pointerTemplate.Name); int thisOffset = offset + 4 * totalIndex; for (int j = 0; j < this.pointerList[i].Length; j++) { line.Add(pointerList[totalIndex].ToHexString("$")); totalIndex++; } lines[thisOffset] = new Code(line.ToArray(), pointerTemplate, this.pointerList[i].Length * 4); } } }
private static void Assemble(ILog log) { TextReader input; bool inputIsFile; if (Program.RunConfig.inputFile != null) { input = File.OpenText(Program.RunConfig.inputFile); inputIsFile = false; } else { input = Console.In; inputIsFile = true; } using (IDirectivePreprocessor preprocessor = new Preprocessor(log)) { // preprocessor.AddReserved (eaCodeLanguage.GetCodeNames ()); preprocessor.AddDefined(new string[] { "_" + Program.RunConfig.language + "_", "_EA_" }); DependencyMakingIncludeListener depMaker = null; if (Program.RunConfig.ppDepEnable) { depMaker = new DependencyMakingIncludeListener(); preprocessor.IncludeListener = depMaker; } using (IInputStream inputStream = new PreprocessingInputStream(input, preprocessor)) { if (Program.RunConfig.ppSimulation) { // preprocess to null output while (inputStream.ReadLine() != null) { ; } } else { if (Program.RunConfig.outputFile == null) { log.AddError("No output file specified for assembly."); return; } string outFile = Program.RunConfig.outputFile; if (File.Exists(outFile) && File.GetAttributes(outFile).HasFlag((Enum)FileAttributes.ReadOnly)) { log.AddError("File `{0}` exists and cannot be written to.", outFile); return; } ChangeStream changeStream = new ChangeStream(); using (BinaryWriter output = new BinaryWriter((Stream)changeStream)) { if (!Program.CodesLoaded) { LoadCodes(false); } EACodeLanguage language = Program.Languages [Program.RunConfig.language]; EAExpressionAssembler assembler = new EAExpressionAssembler(language.CodeStorage, new TokenParser <int> (new Func <string, int> (StringExtensions.GetValue))); assembler.Assemble(inputStream, output, log); if (Program.RunConfig.symbolOutputFile != null) { // Outputting global symbols to another file try { if (File.Exists(Program.RunConfig.symbolOutputFile)) { File.Delete(Program.RunConfig.symbolOutputFile); } using (FileStream fileStream = File.OpenWrite(Program.RunConfig.symbolOutputFile)) using (StreamWriter symOut = new StreamWriter(fileStream)) foreach (KeyValuePair <string, int> symbol in assembler.GetGlobalSymbols()) { symOut.WriteLine("{0}={1}", symbol.Key, symbol.Value.ToHexString("$")); } } catch (Exception e) { log.AddError(e.ToString()); } } } if (log.ErrorCount == 0) { using (Stream stream = (Stream)File.OpenWrite(outFile)) changeStream.WriteToFile(stream); } } } if (depMaker != null) { try { depMaker.GenerateMakeDependencies(log); } catch (Exception e) { log.AddError(e.ToString()); } } } if (inputIsFile) { input.Close(); } }
private static ProgramRunConfig ReadProgramArguments(string[] args, ILog log) { IEnumerator <string> it = args.AsEnumerable().GetEnumerator(); if (!it.MoveNext()) { Program.PrintUsage(); return(null); } ProgramRunConfig result = new ProgramRunConfig(); // First argument is always what kind of exec we want switch (it.Current) { case "doc": result.execType = ProgramRunConfig.RunExecType.GenDoc; break; case "plusplus": result.execType = ProgramRunConfig.RunExecType.GenNppHighlight; break; case "prognotepad": result.execType = ProgramRunConfig.RunExecType.GenPNHighlight; break; case "A": case "assemble": result.execType = ProgramRunConfig.RunExecType.Assemble; break; case "D": case "disassemble": result.execType = ProgramRunConfig.RunExecType.Disassemble; break; default: log.AddError("Unknown run mode `{0}`", it.Current); return(null); } // For Assembling & Disassembling, second argument is what game we're doing that for switch (result.execType) { case ProgramRunConfig.RunExecType.Assemble: case ProgramRunConfig.RunExecType.Disassemble: if (!it.MoveNext()) { log.AddError("You need to specify a game for which to (dis)assemble!"); return(null); } result.language = it.Current; break; } // From now on, the argument order doesn't matter while (it.MoveNext()) { // -quiet if (it.Current.Equals("-quiet")) { result.quiet = true; continue; } // -raws <file> if (it.Current.Equals("-raws")) { if (!it.MoveNext()) { log.AddError("`-raws` passed without specifying a path."); return(null); } if (!result.TrySetRawsPath(it.Current)) { log.AddError("File or folder `{0}` doesn't exist.", it.Current); return(null); } continue; } // -raws:<file> if (it.Current.StartsWith("-raws:")) { string path = it.Current.Substring("-raws:".Length); if (!result.TrySetRawsPath(path)) { log.AddError("File or folder `{0}` doesn't exist.", path); return(null); } continue; } // -rawsExt <ext> if (it.Current.Equals("-rawsExt")) { if (!it.MoveNext()) { log.AddError("`-rawsExt` passed without specifying an extension."); return(null); } if (it.Current.ContainsAnyOf(Path.GetInvalidFileNameChars())) { log.AddError("`{0}` isn't valid as a file extension.", it.Current); return(null); } result.rawsExtension = it.Current; continue; } // -rawsExt:<ext> if (it.Current.StartsWith("-rawsExt:")) { string ext = it.Current.Substring("-rawsExt:".Length); if (ext.ContainsAnyOf(Path.GetInvalidFileNameChars())) { log.AddError("`{0}` isn't valid as a file extension.", ext); return(null); } result.rawsExtension = ext; continue; } // -input <file> if (it.Current.Equals("-input")) { if (!it.MoveNext()) { log.AddError("`-input` passed without specifying a file."); return(null); } if (!File.Exists(it.Current)) { log.AddError("File `{0}` doesn't exist.", it.Current); return(null); } result.inputFile = it.Current; continue; } // -input:<file> if (it.Current.StartsWith("-input:")) { string file = it.Current.Substring("-input:".Length); if (!File.Exists(file)) { log.AddError("File `{0}` doesn't exist.", file); return(null); } result.inputFile = file; continue; } // -output <file> if (it.Current.Equals("-output")) { if (!it.MoveNext()) { log.AddError("`-output` passed without specifying a file."); return(null); } if (!IsValidFileName(it.Current)) { log.AddError("`{0}` isn't a valid file name.", it.Current); return(null); } result.outputFile = it.Current; continue; } // -output:<file> if (it.Current.StartsWith("-output:")) { string file = it.Current.Substring("-output:".Length); if (!IsValidFileName(file)) { log.AddError("`{0}` isn't a valid file name", file); return(null); } result.outputFile = file; continue; } // -error <file> if (it.Current.Equals("-error")) { if (!it.MoveNext()) { log.AddError("`-error` passed without specifying a file."); return(null); } if (!IsValidFileName(it.Current)) { log.AddError("`{0}` isn't a valid file name.", it.Current); return(null); } result.errorFile = it.Current; continue; } // -error:<file> if (it.Current.StartsWith("-error:")) { string file = it.Current.Substring("-error:".Length); if (!IsValidFileName(file)) { log.AddError("`{0}` isn't a valid file name.", file); return(null); } result.errorFile = file; continue; } // special disassembly-specific parameters if (result.execType == ProgramRunConfig.RunExecType.Disassemble) { // -addEndGuards if (it.Current.Equals("-addEndGuards")) { result.addEndGuards = true; continue; } DisassemblyMode dMode; if (it.Current.TryGetEnum <DisassemblyMode> (out dMode)) { result.disassemblyMode = dMode; continue; } int dOffset; if (result.disassemblyOffset < 0 && it.Current.TryGetValue(out dOffset)) { result.disassemblyOffset = dOffset; continue; } Priority dPriority; if (it.Current.TryGetEnum <Priority> (out dPriority)) { result.disassemblyPriority = dPriority; continue; } int dSize; if (result.disassemblyMode == DisassemblyMode.Block && it.Current.TryGetValue(out dSize)) { result.disassemblySize = dSize; continue; } } // special assembly-specific parameters if (result.execType == ProgramRunConfig.RunExecType.Assemble) { // -symOutput <file> if (it.Current.Equals("-symOutput")) { if (!it.MoveNext()) { log.AddError("`-symOutput` passed without specifying a file."); return(null); } if (!IsValidFileName(it.Current)) { log.AddError("`{0}` isn't a valid file name.", it.Current); return(null); } result.symbolOutputFile = it.Current; continue; } // -symOutput:<file> if (it.Current.StartsWith("-symOutput:")) { string file = it.Current.Substring("-symOutput:".Length); if (!IsValidFileName(file)) { log.AddError("`{0}` isn't a valid file name", file); return(null); } result.symbolOutputFile = file; continue; } // -M if (it.Current.Equals("-M")) { result.ppSimulation = true; result.ppDepEnable = true; continue; } // -MM if (it.Current.Equals("-MM")) { result.ppSimulation = true; result.ppDepEnable = true; result.ppDepIgnoreSystemFiles = true; continue; } // -MD if (it.Current.Equals("-MD")) { result.ppDepEnable = true; continue; } // -MMD if (it.Current.Equals("-MMD")) { result.ppDepEnable = true; result.ppDepIgnoreSystemFiles = true; continue; } // -MG if (it.Current.Equals("-MG")) { result.ppDepIgnoreMissingFiles = true; continue; } // -MP if (it.Current.Equals("-MP")) { result.ppDepAddEmptyTargets = true; continue; } // -MF <file> if (it.Current.Equals("-MF")) { if (!it.MoveNext()) { log.AddError("`-MF` passed without specifying a file."); return(null); } if (!IsValidFileName(it.Current)) { log.AddError("`{0}` isn't a valid file name.", it.Current); return(null); } result.ppDepOutput = it.Current; continue; } // -MF:<file> if (it.Current.StartsWith("-MF:")) { string file = it.Current.Substring("-MF:".Length); if (!IsValidFileName(file)) { log.AddError("`{0}` isn't a valid file name.", file); return(null); } result.ppDepOutput = file; continue; } // -MT <name> if (it.Current.Equals("-MT")) { if (!it.MoveNext()) { log.AddError("`-MT` passed without specifying a target."); return(null); } if (it.Current.Length <= 0) { result.ppDepTargets.Clear(); } else { result.ppDepTargets.Add(it.Current); } continue; } // -MT:<name> if (it.Current.StartsWith("-MT:")) { string name = it.Current.Substring("-MT:".Length); if (name.Length <= 0) { result.ppDepTargets.Clear(); } else { result.ppDepTargets.Add(name); } continue; } } // special docgen-specific parameters if (result.execType == ProgramRunConfig.RunExecType.GenDoc) { // -docHeader <file> if (it.Current.Equals("-docHeader")) { if (!it.MoveNext()) { log.AddError("`-docHeader` passed without specifying a file."); return(null); } if (!File.Exists(it.Current)) { log.AddError("File `{0}` doesn't exist.", it.Current); return(null); } result.docHeader = it.Current; continue; } // -docHeader:<file> if (it.Current.StartsWith("-docHeader:")) { string file = it.Current.Substring("-docHeader:".Length); if (!File.Exists(file)) { log.AddError("File `{0}` doesn't exist.", file); return(null); } result.docHeader = file; continue; } // -docFooter <file> if (it.Current.Equals("-docFooter")) { if (!it.MoveNext()) { log.AddError("`-docFooter` passed without specifying a file."); return(null); } if (!File.Exists(it.Current)) { log.AddError("File `{0}` doesn't exist.", it.Current); return(null); } result.docFooter = it.Current; continue; } // -docFooter:<file> if (it.Current.StartsWith("-docFooter:")) { string file = it.Current.Substring("-docFooter:".Length); if (!File.Exists(file)) { log.AddError("File `{0}` doesn't exist.", file); return(null); } result.docFooter = file; continue; } } log.AddWarning("Unhandled parameter `{0}`. Ignoring.", it.Current); } return(result); }
private IEnumerable <KeyValuePair <INamed <string>, string[]> > FirstPass(IPositionableInputStream input, Context assemblyContext, ILog log) { while (true) { string line = input.ReadLine(); if (line == null) { break; } string[] code = Nintenlord.Utility.Parser.SplitToParameters(line); if (code.Length > 0) { if (code[0].EndsWith(":")) { code = HandleLabels(input, assemblyContext, log, code); } if (code.Length == 0) { continue; } IBuiltInCode builtIn; if (buildInCodes.TryGetValue(code[0], out builtIn)) { string error; if (builtIn.Matches("Code " + code[0], code.Length - 1, out error)) { var causedError = builtIn.FirstPass(code, assemblyContext); if (causedError) { log.AddError(input.GetErrorString(causedError.ErrorMessage)); } yield return(new KeyValuePair <INamed <string>, string[]>(builtIn, code)); } else { log.AddError(input.GetErrorString(error)); } } else { ICodeTemplate template = codeStorage.FindTemplate(code); if (template != null) { if (assemblyContext.Offset % template.OffsetMod != 0) { log.AddError(input.GetErrorString( string.Format( "Code {0}'s offset {1} is not divisible by {2}", template.Name, assemblyContext.Offset, template.OffsetMod ))); } assemblyContext.Offset += template.GetLengthBytes(code); yield return(new KeyValuePair <INamed <string>, string[]>(template, code)); } else { log.AddError(input.GetErrorString(string.Format( "No code named {0} with {1} parameters found", code[0], code.Length - 1 ))); } } } } }
public ActionResult GetInitialPageData() { try { var session = new PrivateSession().Current; //var newMessages = _chatMessages.CountNewMessages(session.User.Pk).Data; var incompleteTasks = _tasks.CountIncompleteTasks(session.User.Pk).Data; var incompleteJobs = _tasks.CountIncompleteJobs(session.User.Pk).Data; //var tasks = new List<Task> { // Task.Run(() => newMessages = _chatMessages.CountNewMessages(session.User.Pk).Data), // Task.Run(() => incompleteTasks = _tasks.CountIncompleteTasks(session.User.Pk).Data), // Task.Run(() => incompleteJobs = _tasks.CountIncompleteJobs(session.User.Pk).Data), //}.ToArray(); //Task.WaitAll(tasks); return(Json(new { IsSuccess = true, //NewMessages = newMessages, IncompleteTasks = incompleteTasks, IncompleteJobs = incompleteJobs })); } catch (Exception ex) { _log.AddError("[MyUser]/[GetInitialPageData]", ex.Message); return(Json(new { IsSuccess = false })); } }
private IEnumerable<KeyValuePair<INamed<string>, string[]>> FirstPass(IPositionableInputStream input, Context assemblyContext, ILog log) { while (true) { string line = input.ReadLine(); if (line == null) break; string[] code = Nintenlord.Utility.Parser.SplitToParameters(line); if (code.Length > 0) { if (code[0].EndsWith(":")) { code = HandleLabels(input, assemblyContext, log, code); } if (code.Length == 0) continue; IBuiltInCode builtIn; if (buildInCodes.TryGetValue(code[0], out builtIn)) { string error; if (builtIn.Matches("Code " + code[0], code.Length - 1, out error)) { var causedError = builtIn.FirstPass(code, assemblyContext); if (causedError) { log.AddError(input.GetErrorString(causedError.ErrorMessage)); } yield return new KeyValuePair<INamed<string>, string[]>(builtIn, code); } else { log.AddError(input.GetErrorString(error)); } } else { ICodeTemplate template = codeStorage.FindTemplate(code); if (template != null) { if (assemblyContext.Offset % template.OffsetMod != 0) { log.AddError(input.GetErrorString( string.Format( "Code {0}'s offset {1} is not divisible by {2}", template.Name, assemblyContext.Offset, template.OffsetMod ))); } assemblyContext.Offset += template.GetLengthBytes(code); yield return new KeyValuePair<INamed<string>, string[]>(template, code); } else { log.AddError(input.GetErrorString(string.Format( "No code named {0} with {1} parameters found", code[0], code.Length - 1 ))); } } } } }
private static void Compile(ILog log) { TextReader input; bool inputIsFile; if (Program.RunConfig.inputFile != null) { input = File.OpenText(Program.RunConfig.inputFile); inputIsFile = false; } else { input = Console.In; inputIsFile = true; } using (IDirectivePreprocessor preprocessor = new Preprocessor(log)) { // preprocessor.AddReserved (eaCodeLanguage.GetCodeNames ()); preprocessor.AddDefined(new string[] { "_" + Program.RunConfig.language + "_", "_EA_" }); DependencyMakingIncludeListener depMaker = null; if (Program.RunConfig.ppDepEnable) { depMaker = new DependencyMakingIncludeListener(); preprocessor.IncludeListener = depMaker; } using (IInputStream inputStream = new PreprocessingInputStream(input, preprocessor)) { if (Program.RunConfig.ppSimulation) { // preprocess to null output while (inputStream.ReadLine() != null) { ; } } else { if (Program.RunConfig.outputFile == null) { log.AddError("No output file specified for assembly."); return; } string outFile = Program.RunConfig.outputFile; if (File.Exists(outFile) && File.GetAttributes(outFile).HasFlag((Enum)FileAttributes.ReadOnly)) { log.AddError("File `{0}` exists and cannot be written to.", outFile); return; } using (StreamWriter output = new StreamWriter(outFile, false, Encoding.Default)) { // Make entry point label global to call in C source file //TODO support ARM? output.WriteLine("\t.thumb"); output.WriteLine("\t.global " + Path.GetFileNameWithoutExtension(outFile).Replace(".", "_")); output.WriteLine("\t.include \"event_func_Thumb.inc\""); output.WriteLine("\t.include \"event_func_C.inc\""); output.WriteLine(Path.GetFileNameWithoutExtension(outFile).Replace(".", "_") + ":"); if (!Program.CodesLoaded) { LoadCodes(false); } // Console.WriteLine("language: {0}", Program.RunConfig.language); EACodeLanguage language = Program.languages [Program.RunConfig.language]; EAExpressionAssembler assembler = new EAExpressionAssembler(language.CodeStorage, new TokenParser <int> (new Func <string, int> (StringExtensions.GetValue))); assembler.Compile(inputStream, output, log); if (Program.RunConfig.symbolOutputFile != null) { // Outputting global symbols to another file try { if (File.Exists(Program.RunConfig.symbolOutputFile)) { File.Delete(Program.RunConfig.symbolOutputFile); } using (FileStream fileStream = File.OpenWrite(Program.RunConfig.symbolOutputFile)) using (StreamWriter symOut = new StreamWriter(fileStream)) foreach (KeyValuePair <string, int> symbol in assembler.GetGlobalSymbols()) { symOut.WriteLine("{0}={1}", symbol.Key, symbol.Value.ToHexString("$")); } } catch (Exception e) { log.AddError(e.ToString()); } } output.Close(); } } } if (depMaker != null) { try { depMaker.GenerateMakeDependencies(log); } catch (Exception e) { log.AddError(e.ToString()); } } } if (inputIsFile) { input.Close(); } }
private static void Disassemble(ILog log) { if (!File.Exists(Program.RunConfig.inputFile)) { log.AddError("File `{0}` doesn't exist.", Program.RunConfig.inputFile); return; } if (File.Exists(Program.RunConfig.outputFile) && File.GetAttributes(Program.RunConfig.outputFile).HasFlag(FileAttributes.ReadOnly)) { log.AddError("Output cannot be written to. It is read-only."); return; } if (!Program.CodesLoaded) { LoadCodes(false); } EACodeLanguage eaCodeLanguage = Program.Languages [Program.RunConfig.language]; byte[] code = File.ReadAllBytes(Program.RunConfig.inputFile); if (Program.RunConfig.disassemblyOffset > code.Length) { log.AddError("Offset is larger than size of file."); return; } int size = Program.RunConfig.disassemblySize; int offset = Program.RunConfig.disassemblyOffset; if (size <= 0 || size + offset > code.Length) { size = code.Length - offset; } IEnumerable <string[]> strArrays; string[] lines; switch (Program.RunConfig.disassemblyMode) { case DisassemblyMode.Block: strArrays = eaCodeLanguage.Disassemble( code, offset, size, Program.RunConfig.disassemblyPriority, Program.RunConfig.addEndGuards, log ); lines = CoreInfo.DefaultLines( eaCodeLanguage.Name, Path.GetFileName(Program.RunConfig.inputFile), offset, new int?(size) ); break; case DisassemblyMode.ToEnd: strArrays = eaCodeLanguage.DisassembleToEnd( code, offset, Program.RunConfig.disassemblyPriority, Program.RunConfig.addEndGuards, log ); lines = CoreInfo.DefaultLines( eaCodeLanguage.Name, Path.GetFileName(Program.RunConfig.inputFile), offset, new int?() ); break; case DisassemblyMode.Structure: strArrays = eaCodeLanguage.DisassembleChapter( code, offset, Program.RunConfig.addEndGuards, log ); lines = CoreInfo.DefaultLines( eaCodeLanguage.Name, Path.GetFileName(Program.RunConfig.inputFile), offset, new int?() ); break; default: throw new ArgumentException(); } if (log.ErrorCount == 0) { using (StreamWriter streamWriter = new StreamWriter(Program.RunConfig.outputFile)) { streamWriter.WriteLine(); streamWriter.WriteLine(Program.Frame(lines, "//", 1)); streamWriter.WriteLine(); foreach (string[] strArray in strArrays) { streamWriter.WriteLine(((IEnumerable <string>)strArray).ToElementWiseString <string> (" ", "", "")); } } } }
private string[] HandleLabels(IPositionableInputStream input, Context assemblyContext, ILog log, string[] code) { string labelName = code[0].TrimEnd(':'); if (IsValidLableName(labelName)) { assemblyContext.AddLabel(labelName); } else { log.AddError(input.GetErrorString( string.Format("Invalid label name {0}", labelName))); } string[] temp = new string[code.Length - 1]; Array.Copy(code, 1, temp, 0, temp.Length); code = temp; return code; }
private void FindTemplatesUntil(byte[] code, int offset, SortedDictionary<int, Code> lines, IEnumerable<Priority> prioritiesToUse, Predicate<ICodeTemplate> predicate, ILog log) { int currOffset = offset; while (currOffset < code.Length) { Code ccode; ICodeTemplate template; int length; if (!lines.TryGetValue(currOffset, out ccode)) { var templateResult = codeStorage.FindTemplate(code, currOffset, prioritiesToUse); if (templateResult.CausedError) { log.AddError(templateResult.ErrorMessage); break; } else { template = templateResult.Result; length = template.GetLengthBytes(code, currOffset); var line = template.GetAssembly(code, currOffset); if (line.CausedError) { log.AddError(line.ErrorMessage); } else { lines.Add(currOffset, new Code(line.Result, template, length)); } } } else { template = ccode.Template; length = template.GetLengthBytes(code, currOffset); } if (predicate(template)) { break; } currOffset += length; } }
private static void SecondPass(IEnumerable<KeyValuePair<INamed<string>, string[]>> codes, Context assemblyContext, ILog log, BinaryWriter output) { foreach (var code in codes) { //Insert labels and currentOffsetCode for (int i = 1; i < code.Value.Length; i++) { int offset; if (code.Value[i].Equals(currentOffsetCode, StringComparison.OrdinalIgnoreCase)) { code.Value[i] = assemblyContext.Offset.ToString(); } else if (assemblyContext.TryGetLabelOffset(code.Value[i], out offset)) { code.Value[i] = offset.ToString(); } } if (code.Key is IBuiltInCode) { var error = ((IBuiltInCode)code.Key).SecondPass(code.Value, assemblyContext); if (error) { log.AddError(error.ErrorMessage); } else if (error.Result) { output.Seek(assemblyContext.Offset, SeekOrigin.Begin); } } else if (code.Key is ICodeTemplate) { output.Write(((ICodeTemplate)code.Key).GetData(code.Value, log)); assemblyContext.Offset = (int)output.BaseStream.Position; } } }
// GET: /Task/Tasks public ActionResult Tasks(string subg, Guid?pk, int?prop) { try { if (prop == 1) { var propPks = _notifycations.GetMyProposals(new PrivateSession().Current.User.Pk).Data; if (propPks.Any()) { new PrivateSession().Current.ProposalsTaskPks = propPks; } } ViewBag.PublicKey = pk; ViewBag.Subgroup = subg; return(View()); } catch (Exception ex) { _log.AddError("[Task]/[Tasks]", ex.Message); return(View()); } }