/// <summary> /// Формирует простой для чтений реестр ошибок /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context){ var sb = new StringBuilder(); sb.AppendLine("<html>"); sb.AppendLine("\t<head>"); sb.AppendLine("\t\t<title>Ошибки по проекту " + Project.ProjectName + "</title>"); sb.AppendLine("\t\t<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">"); sb.AppendLine("\t<style type='text/css'>"); sb.AppendLine( "\t\ttable {border-collapse:collapse;} td, th { padding : 5px; border:solid 1px gray; } th {background-color:black;color:white;} "); sb.AppendLine("\t\t.level-error {background-color : #ffdddd;} "); sb.AppendLine("\t</style>"); sb.AppendLine("\t</head>"); sb.AppendLine("\t<body>"); sb.AppendLine("\t\t<h1>Ошибки по проекту " + Project.ProjectName + "</h1>"); sb.AppendLine("\t\t<table>"); sb.AppendLine("\t\t\t<tr>"); sb.AppendLine("\t\t\t\t<th>Номер</th><th>Уровень</th><th>Тип</th><th>Класс</th><th>Сообщение</th><th>Файл</th><th>Строка</th><th>Колонка</th><th>Фаза</th>"); sb.AppendLine("\t\t\t</tr>"); var id = 1; foreach (var d in context.GetErrors(ErrorLevel.Warning).Select(_ => _.GetDigest()).OrderByDescending(_ => _.ErrorLevel).ThenBy(_=>_.ClassName).ThenBy(_=>_.FileName)){ sb.AppendLine("\t\t\t<tr class='level-"+d.ErrorLevel+"'>"); sb.AppendFormat("\t\t\t\t<td>{0}</td><td>{1}</td><td>{2}</td><td>{3}</td><td>{4}</td><td>{5}</td><td>{6}</td><td>{7}</td><td>{8}</td>\r\n", id++,d.ErrorLevel,d.Type,d.ClassName,d.Message.Replace("\r\n","<br/>"),d.FileName,d.Line,d.Column,d.Phase ); sb.AppendLine("\t\t\t</tr>"); } sb.AppendLine("\t\t</table>"); sb.AppendLine("\t</body>"); sb.AppendLine("</html>"); var filename = Path.Combine(Project.GetOutputDirectory(), Project.ProjectName + ".formatted.errors.html"); Directory.CreateDirectory(Path.GetDirectoryName(filename)); File.WriteAllText(filename,sb.ToString()); }
public override void Execute(IBSharpContext context) { foreach (var cls in context.ResolveAll("attr:generate-json")) { var xml = RefineForJson(new XElement(cls.Compiled)); var opts = xml.Attr("generate-json").SmartSplit(); IDictionary<string,object> j = new Dictionary<string, object>(); if (opts.Contains("nooptions") && j.ContainsKey("options")) { IDictionary<string, object> _opts = j["options"].jsonifymap(); j.Remove("options"); foreach(var o in _opts.OrderBy(_=>_.Key)) { j[o.Key] = o.Value; } } WriteElements(xml, j, opts); WriteJson(cls, j, opts); } }
public override void Execute(IBSharpContext context) { foreach (var cls in context.ResolveAll("attr:generate-json")) { var xml = RefineForJson(new XElement(cls.Compiled)); var opts = xml.Attr("generate-json").SmartSplit(); IDictionary <string, object> j = new Dictionary <string, object>(); if (opts.Contains("nooptions") && j.ContainsKey("options")) { IDictionary <string, object> _opts = j["options"].jsonifymap(); j.Remove("options"); foreach (var o in _opts.OrderBy(_ => _.Key)) { j[o.Key] = o.Value; } } WriteElements(xml, j, opts); WriteJson(cls, j, opts); } }
/// <summary> /// </summary> public BSharpJsonCompiler() { _jsonContext = new List <string>(); _bSharpContext = new BSharpContext(); _bSharpCompiler = new BSharpCompiler(); _jsonParser = new JsonParser(); }
/// <summary> /// Трансформирует классы прототипа BIZINDEX в полноценные карты соотношения тем, блоков, подсистем /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { _context = context; Project.Log.Info(GetType().Name + " called"); var targetclasses = string.IsNullOrWhiteSpace(ClassSearchCriteria)?new IBSharpClass[] {} : _context.ResolveAll(ClassSearchCriteria).ToArray(); var outdir = GetOutDir(); foreach (var production in InternalGenerate(targetclasses)) { var filename = production.FileName; if (!Path.IsPathRooted(filename)) { filename = Path.Combine(outdir, filename); production.FileName = filename; } if (production.CanBeSaved) { Project.Log.Info("Write " + filename); Directory.CreateDirectory(Path.GetDirectoryName(filename)); File.WriteAllText(filename, production.GetContent()); } else { Project.Log.Info("Skip " + filename); } } }
public override void Execute(IBSharpContext context) { Project.Log.Info("Start xslt tasks"); var xslttasks = context.ResolveAll("xslttask"); foreach (var xslttask in xslttasks) { var task = new XsltTask(Project, xslttask.Compiled); Project.Log.Info("Start XSLT task " + xslttask.FullName); try { task.Execute(); Project.Log.Info("XSLT task " + xslttask.FullName + " finished"); } catch (Exception e) { Project.Context.RegisterError(new BSharpError { Class = xslttask, Error = e, Message = "Error in xslt task:\r\n" + e.ToString() }); Project.Log.Error("Error in xslt " + xslttask.FullName, e); } } }
public override void Execute(IBSharpContext context) { Project.Log.Info("Start xslt tasks"); var xslttasks = context.ResolveAll("xslttask"); foreach (var xslttask in xslttasks) { var task = new XsltTask(Project,xslttask.Compiled); Project.Log.Info("Start XSLT task "+xslttask.FullName); try { task.Execute(); Project.Log.Info("XSLT task " + xslttask.FullName+" finished"); } catch (Exception e) { Project.Context.RegisterError(new BSharpError { Class = xslttask, Error = e, Message = "Error in xslt task:\r\n"+e.ToString() }); Project.Log.Error("Error in xslt "+xslttask.FullName,e); } } }
/// <summary> /// Создает запись для класса /// </summary> /// <param name="cls"></param> /// <param name="context"></param> /// <returns></returns> protected override XElement CreateClassRecord(IBSharpClass cls, IBSharpContext context) { var result = GetIndexElement(cls); if (cls.AllImports.Any()) { var imports = new XElement("Imports"); result.Add(imports); foreach (var i in cls.AllImports) { imports.Add(new XElement("Import", new XAttribute("code", i.FullName))); } } if (cls.AllElements.Any()) { var elements = new XElement("Elements"); result.Add(elements); foreach (var i in cls.AllElements) { elements.Add(new XElement("Element", new XAttribute("code", i.Name), new XAttribute("target", i.TargetName ?? ""), new XAttribute("type", i.Type))); } } var src = new XElement(cls.Source) { Name = "Source" }; result.Add(src); return(result); }
private static void WriteOutConsoleMode(IBSharpContext ctx) { var result = new XElement("result"); foreach (var cls in ctx.Get(BSharpContextDataType.Working)) { var clsElement = new XElement("cls"); clsElement.SetAttr("code", cls.FullName); clsElement.SetAttr("name", cls.Name); clsElement.SetAttr("ns", cls.Namespace); clsElement.SetAttr("prototype", cls.Prototype); clsElement.Add(cls.Compiled); result.Add(clsElement); } foreach (var error in ctx.GetErrors()) { var errorElement = new XElement("error", new XAttribute("type", error.Type)) { Value = error.ToLogString() }; if (null != error.LexInfo) { var lex = new XElement("lexinfo", new XAttribute("file", error.LexInfo.File), new XAttribute("line", error.LexInfo.Line)); errorElement.Add(lex); } result.Add(errorElement); } Console.WriteLine(result.ToString()); }
/// <summary> /// </summary> /// <param name="compiler"></param> /// <param name="context"></param> /// <returns></returns> public IEnumerable<XElement> GetSources(IBSharpCompiler compiler, IBSharpContext context){ if (string.IsNullOrWhiteSpace(ResourceMarker)) throw new Exception("marker not set"); foreach (string rname in GetType().Assembly.FindAllResourceNames(ResourceMarker)){ string resource = GetType().Assembly.ReadManifestResource(rname); yield return Parser.Parse(resource, rname); } }
/// <summary> /// /// </summary> /// <param name="compiledProject"></param> /// <returns></returns> protected override IBSharpProject ConvertToBSharpBuilderProject(IBSharpContext compiledProject) { var projectClass = compiledProject.Get(Project.ProjectName); if (null != projectClass) { return GenerateProject(projectClass); } throw new Exception("cannot find project " + Project.ProjectName); }
/// <summary> /// Выполнение цели /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { string message = Phase == BSharpBuilderPhase.PreProcess ? "предварительная" : "дополнительная"; Project.Log.Warn("Выполняется " + message + " обработка кода ВНИМАНИЕ - данный функционал не считается безопасным"); Stopwatch sw = Stopwatch.StartNew(); //сначла собираем скрипты ProcessorScript[] scripts = ExtractScrtips(Project.Sources).OrderBy(_ => _.Index).ToArray(); IList <Task> pendingScripts = new List <Task>(); foreach (ProcessorScript script in scripts) { if (script.Async) { pendingScripts.Add(script.ExecuteAsync()); } else { script.Execute(); } } Task.WaitAll(pendingScripts.ToArray()); sw.Stop(); Project.Log.Warn(message + " обработка кода выполнялась " + sw.Elapsed); }
/// <summary> /// Создает запись для класса /// </summary> /// <param name="cls"></param> /// <param name="context"></param> /// <returns></returns> protected override XElement CreateClassRecord(IBSharpClass cls, IBSharpContext context) { var result = GetIndexElement(cls); var src = new XElement(cls.Compiled) { Name = "Compiled" }; result.Add(src); return result; }
/// <summary> /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { Model = (PersistentModel)context.ExtendedData[PrepareModelTask.DefaultModelName]; Tables = Model.Classes.Values.OrderBy(_ => _.Name).ToArray(); DefaultOutputName = "Orm"; base.Execute(context); }
private Graph BuildGraph(IBSharpContext context) { var result = new Graph { RankDir = RankDirType.RL, Label = "Графическая структура проекта", DefaultNode = new Node { FontName = "Consolas", Shape = NodeShapeType.Box3d, FontSize = 8, Style = NodeStyleType.Filled }, DefaultEdge = new Node { FontName = "Consolas", FontSize = 8 }, }; var visited= new List<IBSharpClass>(); if (null != ((BSharpContext) context).Dictionaries) { foreach (var e in ((BSharpContext) context).Dictionaries) { var node = new Node {Code = "d" + e.Key, Label = e.Key,SubgraphCode = "dicts",Shape = NodeShapeType.Mcircle}; result.AddNode(node); foreach (var i in e.Value) { result.AddEdge(new Edge {From = i.cls.FullName, To = "d" + e.Key, ArrowHead = ArrowType.Curve}); } } } foreach (var c in context.Get(BSharpContextDataType.Working)) { BuildClass(result,context, (BSharpClass)c, visited); } result.AutoTune(); return result; }
/// <summary> /// Формирует один большой файл JSON с рабочиим классами /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { Project.Log.Info("start generate json module"); using (var sw = new StreamWriter(OutFileName)) { sw.Write("["); var tojson = new XmlToJsonConverter(); var notformatedBuffer = new StringWriter(); var formattedBuffer = new StringWriter(); foreach (var cls in context.Get(BSharpContextDataType.LibPkg)) { var converted = tojson.ConvertToJson(cls.Compiled, false); notformatedBuffer.Write(converted); converted = tojson.ConvertToJson(cls.Compiled, true); formattedBuffer.Write(","); formattedBuffer.Write(converted); } var hashbase = notformatedBuffer.ToString(); var content = formattedBuffer.ToString(); sw.Write(tojson.ConvertToJson(new XElement(BSharpSyntax.Class, new XAttribute("code", "__module"), new XAttribute("fullcode", "__module"), new XAttribute("prototype", "__sys"), new XAttribute("hash", Convert.ToBase64String(MD5.Create().ComputeHash(Encoding.UTF8.GetBytes(hashbase)))), new XAttribute("timestamp", (DateTime.Now - new DateTime(2000, 1, 1)).TotalMilliseconds), new XAttribute("user", Application.Current.Principal.CurrentUser.Identity.Name), new XAttribute("host", Environment.MachineName) ), true)); sw.Write(content); sw.Write("]"); sw.Flush(); } Project.Log.Info("finish generate json module"); }
/// <summary> /// Выполнение операции в контексте /// </summary> /// <param name="context">Контекст</param> public override void Execute(IBSharpContext context) { if (!Project.OutputAttributes.HasFlag(IncludeFlag)) { return; } PrepareWorkEnviroment(); RollRealWriting(context); }
/// <summary> /// Формирует конфиг из XML /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <param name="machineName"></param> /// <param name="log"></param> public HostConfig(XElement xml,IBSharpContext context = null, string machineName = null, IUserLog log = null) : this() { if (!string.IsNullOrWhiteSpace(machineName)) MachineName = machineName; if (null != log) Log = log; if (null != xml){ LoadXmlConfig(xml,context); } }
private XElement CreateManifest(IBSharpContext context) { var result = new XElement("bsharp-manifest"); result.SetAttributeValue("create-time", DateTime.Now); result.SetAttributeValue("user-name", Application.Current.Principal.CurrentUser.Identity.Name); result.SetAttributeValue("project-name", Project.ProjectName); return(result); }
/// <summary> /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { if (!context.ExtendedData.ContainsKey(DefaultModelName)) { var gopts = new GenerationOptions(); gopts.IncludeSqlObjectTypes = SqlObjectType.All; gopts.ExcludeSqlObjectTypes = SqlObjectType.None; var conds = context.Compiler.GetConditions(); if (conds.ContainsKey("EX_ALL")) { gopts.ExcludeSqlObjectTypes = SqlObjectType.All; } if (conds.Any(_ => _.Key.StartsWith("DO_"))) { gopts.IncludeSqlObjectTypes = SqlObjectType.None; gopts.ExcludeSqlObjectTypes = SqlObjectType.All; } if (conds.ContainsKey("DO_DYN")) { gopts.IncludeSqlObjectTypes = SqlObjectType.Function | SqlObjectType.ClrTrigger | SqlObjectType.Procedure; gopts.ExcludeSqlObjectTypes = SqlObjectType.All; } foreach (var c in context.Compiler.GetConditions()) { if (c.Key.StartsWith("DO_") || c.Key.StartsWith("EX_")) { if (c.Key == "EX_ALL") { continue; } if (c.Key == "DO_DYN") { continue; } var type = c.Key.Substring(3); var tp = type.To <SqlObjectType>(true); if (tp != SqlObjectType.None) { if (c.Key.StartsWith("DO_")) { gopts.IncludeSqlObjectTypes |= tp; } else { gopts.ExcludeSqlObjectTypes |= tp; } } } } PersistentModel model = new PersistentModel { GenerationOptions = gopts }.Setup(context); context.ExtendedData[DefaultModelName] = model; } }
private static IScope InitializeBaseConfig(XElement serverDefinition, IBSharpContext context, string logicalServerName) { var result = new Scope(); result["definition"] = serverDefinition; result["baseservername"] = serverDefinition.ChooseAttr("server", "code"); result["servername"] = logicalServerName; result["conneciton"] = serverDefinition.Attr("connection", "Server=(local);Trusted_Connection=true"); return(result); }
/// <summary> /// Запуск задачи на выполнение /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { BSharpBuilderWriteManager.Join(); WroteTargets = Project.Get<IList<BSharpBuilderWriteTarget>>("WroteTargets"); Project.Log.Info("GenerateIndexTask"); PrepareWorkEnviroment(); PrepareIndexesForWriting(); WriteManager.Roll(); }
private void SetupStructs(IBSharpContext context) { var structClasses = context.ResolveAll("ui-data").ToArray(); foreach (var structClass in structClasses) { var structure = new AppStruct().Setup(this, structClass); Structs[structure.Code] = structure; } }
private void SetupServices(IBSharpContext context) { var serviceClasses = context.ResolveAll("ui-service").ToArray(); foreach (var serviceClass in serviceClasses) { var service = new AppService().Setup(serviceClass.Compiled); Services[service.Code] = service; } }
private void SetupActions(IBSharpContext context) { var actionClasses = context.ResolveAll("ui-action").ToArray(); foreach (var actionClass in actionClasses) { var action = new AppAction().Setup(this, actionClass); Actions[action.Code] = action; } }
private void SetupMenus(IBSharpContext context) { var menuClasses = context.ResolveAll("ui-menu").ToArray(); foreach (var menuClass in menuClasses) { var menu = new AppMenu().Setup(menuClass.Compiled); Menus[menu.Code] = menu; } }
private void SetupLayout(IBSharpContext context) { var layoutClasses = context.ResolveAll("ui-layout").ToArray(); foreach (var layoutClass in layoutClasses) { var layout = new AppLayout().Setup(layoutClass.Compiled, null, this); Layouts[layout.Code] = layout; } }
/// <summary> /// /// </summary> /// <param name="compiledProject"></param> /// <returns></returns> protected override IBSharpProject ConvertToBSharpBuilderProject(IBSharpContext compiledProject) { var projectClass = compiledProject.Get(Project.ProjectName); if (null != projectClass) { return(GenerateProject(projectClass)); } throw new Exception("cannot find project " + Project.ProjectName); }
/// <summary> /// /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { var filter = ClassFilter.Create(Project); if (!filter.HasConditions) { return; } Project.Sources.AsParallel().ForAll(_ => Execute(filter, _, "")); }
/// <summary> /// Выполнение цели /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { var compiler = new BSharpCompiler(); foreach (var e in Project.CompilerExtensions ) { compiler.Extensions.Add(e); } var cfg = GetConfig(); compiler.Initialize(cfg); compiler.Compile(Project.Sources, context); HandleErrorStream(context); }
/// <summary> /// Выполнение операции в контексте /// </summary> /// <param name="context">Контекст</param> public override void Execute(IBSharpContext context) { if (!Project.OutputAttributes.HasFlag(IncludeFlag)) { return; } PrepareWorkEnviroment(); RollRealWriting(context); }
/// <summary> /// Создает запись для класса /// </summary> /// <param name="cls"></param> /// <param name="context"></param> /// <returns></returns> protected override XElement CreateClassRecord(IBSharpClass cls, IBSharpContext context) { var result = GetIndexElement(cls); var src = new XElement(cls.Compiled) { Name = "Compiled" }; result.Add(src); return(result); }
private void WriteManifest(IBSharpContext context, Package pkg) { var manifest = CreateManifest(context); var part = pkg.CreatePart(new Uri("/manifest", UriKind.Relative), "text/xml", CompressionOption.Normal); using (var s = XmlWriter.Create(part.GetStream(FileMode.Create))) { manifest.WriteTo(s); s.Flush(); } pkg.CreateRelationship(part.Uri, TargetMode.Internal, "bsharp://manifest"); }
private void HandleErrorStream(IBSharpContext context) { var errors = context.GetErrors(); foreach (var c in context.Get(BSharpContextDataType.Working)) { var witherrors = errors.Any(_ => _.Class == c || _.AltClass == c || _.ClassName == c.FullName); if (witherrors) { Project.Log.Warn("class " + c.FullName + " compiled with some errors"); } else { Project.Log.Debug("class " + c.FullName + " compiled"); } } }
/// <summary> /// </summary> /// <param name="compiler"></param> /// <param name="context"></param> /// <returns></returns> public IEnumerable <XElement> GetSources(IBSharpCompiler compiler, IBSharpContext context) { if (string.IsNullOrWhiteSpace(ResourceMarker)) { throw new Exception("marker not set"); } foreach (string rname in GetType().Assembly.FindAllResourceNames(ResourceMarker)) { string resource = GetType().Assembly.ReadManifestResource(rname); yield return(Parser.Parse(resource, rname)); } }
/// <summary> /// Запуск задачи на выполнение /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { BSharpBuilderWriteManager.Join(); WroteTargets = Project.Get <IList <BSharpBuilderWriteTarget> >("WroteTargets"); Project.Log.Info("GenerateIndexTask"); PrepareWorkEnviroment(); PrepareIndexesForWriting(); WriteManager.Roll(); }
/// <summary> /// Выполнение цели /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { Project.Log.Info("Start GenerateClassGraphTask"); var graph = BuildGraph(context); var dot = GraphRender.Create(graph).GenerateGraphScript(); var dotfile = Path.Combine(Project.GetOutputDirectory(), "project.dot"); File.WriteAllText(dotfile, dot); var dotr = new DotGraphProvider(); var svg = dotr.Generate(dot,new GraphOptions()); var svgfile = Path.Combine(Project.GetOutputDirectory(), "project.svg"); File.WriteAllText(svgfile,(string)svg); Project.Log.Info("Finish GenerateClassGraphTask"); }
/// <summary> /// Произведение реальной записки скомпилированного контекста /// на диск с резольвингом пути и формы записи согласно OutputAttributes /// </summary> /// <param name="context"></param> protected virtual void RollRealWriting(IBSharpContext context) { PrepareTargets(context); if (Project.OutputAttributes.HasFlag(BSharpBuilderOutputAttributes.SingleFile)) { WriteManager.SingleFile(); } else { WriteManager.Roll(); } }
/// <summary> /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { var errors = context.GetErrors().ToArray(); if (errors.Length == 0) { return; } PrepareWorkEnv(); var xmlstring = GetSerializedErrors(errors); var xml = XElement.Parse(xmlstring); RollWriting(GetWritePath(), xml.ToString()); RollWriting(GetWritePath()+".html",ConvertToErrorHtml(xml)); }
/// <summary> /// Формирует ZIP пакет с индексированным исходным кодом пакета /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { using (var pkg = Package.Open(PackageName, FileMode.Create)) { WriteManifest(context, pkg); WriteIndex(context, pkg); foreach (var cls in context.Get(GetContextClassType())) { WriteClass(cls, context, pkg); } pkg.Flush(); pkg.Close(); } }
private void WriteClass(IBSharpClass cls, IBSharpContext context, Package pkg) { var classRecord = CreateClassRecord(cls, context); var uri = GetUri(cls); var part = pkg.CreatePart(uri, "text/xml", CompressionOption.Normal); using (var s = XmlWriter.Create(part.GetStream(FileMode.Create))) { classRecord.WriteTo(s); s.Flush(); } pkg.CreateRelationship(part.Uri, TargetMode.Internal, "bsharp://class"); }
/// <summary> /// Создает индекс /// </summary> /// <param name="context"></param> /// <returns></returns> private XElement CreateIndex(IBSharpContext context) { var result = new XElement("bsharp-index"); var classes = context.Get(GetContextClassType()).ToArray(); result.SetAttributeValue("count", classes.Length); foreach (var c in context.Get(GetContextClassType())) { var e = GetIndexElement(c); e.SetAttributeValue("uri", GetUri(c)); result.Add((object)e); } return(result); }
private void LoadBxlSources(IBSharpContext context) { var bxlparser = new BxlParser(); foreach (var file in DirectoryFileFilter.Create(Project).Collect()) { try { var xml = bxlparser.Parse(null, file); Project.Sources.Add(xml); Project.Log.Debug("add src from " + file); } catch (Exception ex) { context.RegisterError(BSharpErrors.Generic(ex)); Project.Log.Fatal("cannot load src from " + file + " : " + ex.Message); } } }
/// <summary> /// Формирует конфиг из XML /// </summary> /// <param name="xml"></param> /// <param name="context"></param> /// <param name="machineName"></param> /// <param name="log"></param> public HostConfig(XElement xml, IBSharpContext context = null, string machineName = null, IUserLog log = null) : this() { if (!string.IsNullOrWhiteSpace(machineName)) { MachineName = machineName; } if (null != log) { Log = log; } if (null != xml) { LoadXmlConfig(xml, context); } }
/// <summary> /// Выполнение цели /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { Project.Log.Info("Start GenerateClassGraphTask"); var graph = BuildGraph(context); var dot = GraphRender.Create(graph).GenerateGraphScript(); var dotfile = Path.Combine(Project.GetOutputDirectory(), "project.dot"); File.WriteAllText(dotfile, dot); var dotr = new DotGraphProvider(); var svg = dotr.Generate(dot, new GraphOptions()); var svgfile = Path.Combine(Project.GetOutputDirectory(), "project.svg"); File.WriteAllText(svgfile, (string)svg); Project.Log.Info("Finish GenerateClassGraphTask"); }
private void LoadJsonSources(IBSharpContext context) { var jsonparser = new Json.JsonParser(); foreach (var file in Directory.GetFiles(Project.GetRootDirectory(), "*.bxls.json", SearchOption.AllDirectories)) { try { var xml = jsonparser.ParseXml(File.ReadAllText(file)); ConvertToBSharpSourceXml(file, xml); Project.Sources.Add(xml); Project.Log.Debug("add src from " + file); } catch (Exception ex) { context.RegisterError(BSharpErrors.Generic(ex)); Project.Log.Fatal("cannot load src from " + file + " : " + ex.Message); } } }
private void BuildClass(Graph g, IBSharpContext ctx, BSharpClass cls, IList<IBSharpClass> visited) { if (visited.Contains(cls)) return; visited.Add(cls); var label = cls.Name; if (!string.IsNullOrWhiteSpace(cls.Prototype)) { label = "[" + cls.Prototype + "]\r\n" + cls.Name; } var n = new Node {Code = cls.FullName, Label = label}; if (!string.IsNullOrWhiteSpace(cls.Namespace)) { n.SubgraphCode = (cls.Namespace.Replace(".", "__")) + "__"; } CheckoutNamespace(g,cls.Namespace); if (cls.Is(BSharpClassAttributes.Abstract)) { n.Shape = NodeShapeType.Box; n.FillColor = Color.Yellow; } g.AddNode(n); if (null != cls.DefaultImport) { g.AddEdge(new Edge {From = cls.FullName, To = cls.DefaultImport.FullName,Label = "0"}); BuildClass(g,ctx,(BSharpClass)cls.DefaultImport,visited); } int idx = 1; foreach (var i in cls.SelfImports) { g.AddEdge(new Edge {From = cls.FullName, To = i.Target.FullName,Label = (idx++).ToString()}); BuildClass(g, ctx, (BSharpClass)i.Target, visited); } foreach (var i in cls.IncludedClasses) { g.AddEdge(new Edge { From = cls.FullName, To = i.FullName, ArrowHead =ArrowType.Diamond}); BuildClass(g, ctx, (BSharpClass)i, visited); } foreach (var i in cls.ReferencedClasses) { g.AddEdge(new Edge { From = cls.FullName, To = i.FullName, ArrowHead = ArrowType.Vee,Color = Color.Blue}); BuildClass(g, ctx, (BSharpClass)i, visited); } foreach (var i in cls.LateIncludedClasses) { g.AddEdge(new Edge { From = cls.FullName, To = i.FullName, ArrowHead = ArrowType.ODiamond, Color = Color.Blue }); BuildClass(g, ctx, (BSharpClass)i, visited); } foreach (var i in cls.ReferencedDictionaries) { g.AddEdge(new Edge { From = cls.FullName, To = "d"+i, ArrowHead = ArrowType.Inv, Color = Color.Blue }); } }
/// <summary> /// Трансформирует классы прототипа BIZINDEX в полноценные карты соотношения тем, блоков, подсистем /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { _context = context; Project.Log.Info(GetType().Name+" called"); var targetclasses = string.IsNullOrWhiteSpace(ClassSearchCriteria)?new IBSharpClass[]{} : _context.ResolveAll(ClassSearchCriteria).ToArray(); var outdir = GetOutDir(); foreach (var production in InternalGenerate(targetclasses)){ var filename = production.FileName; if (!Path.IsPathRooted(filename)){ filename = Path.Combine(outdir, filename); production.FileName = filename; } if (production.CanBeSaved){ Project.Log.Info("Write " + filename); Directory.CreateDirectory(Path.GetDirectoryName(filename)); File.WriteAllText(filename, production.GetContent()); } else{ Project.Log.Info("Skip "+filename); } } }
private void ExecuteTask(IBSharpContext result, IBSharpBuilderTask t){ t.Execute(result); Log.Trace("\t\t" + t.GetType().Name + " executed"); }
/// <summary> /// </summary> /// <param name="compiledProject"></param> /// <returns></returns> protected abstract IBSharpProject ConvertToBSharpBuilderProject(IBSharpContext compiledProject);
/// <summary> /// Загружает конфигурационный файл из XML /// </summary> /// <param name="xml"></param> /// <param name="context"></param> public void LoadXmlConfig(XElement xml,IBSharpContext context = null) { foreach (var condition in xml.Elements("machine")) { var machine = condition.Attr("code").ToLowerInvariant(); var not = false; if (machine == "not" && !string.IsNullOrWhiteSpace(condition.Attr("name"))) { not = true; machine = condition.Attr("name").ToLowerInvariant(); } if ((machine == MachineName && !not) || (not && machine != MachineName )) { var target = condition.Attr("use"); if (context == null) throw new Exception("Cannot resolve machine-related config cause context is null"); var config = context[target]; if (config == null) throw new Exception("Cannot resolve machine-related config"); xml = config.Compiled; Log.Info("Usage config " + target +" because machine name is " + (not ? "not " : "") + MachineName); break; } } this.BSharpContext = context; this.Definition = xml; RootFolder = xml.ResolveValue("root", RootFolder); RootFolder = xml.ResolveValue(HostUtils.RootFolderXmlName, RootFolder); ConfigFolder = xml.ResolveValue(HostUtils.ConfigFolderXmlName, ConfigFolder); DllFolder = xml.ResolveValue(HostUtils.DllFolderXmlName, DllFolder); LogFolder = xml.ResolveValue(HostUtils.LogFolderXmlName, LogFolder); TmpFolder = xml.ResolveValue(HostUtils.TmpFolderXmlName, TmpFolder); LogLevel = xml.ResolveValue(HostUtils.LogLevelXmlName, "Info").To<LogLevel>(); UseApplicationName = xml.ResolveValue(HostUtils.UseApplicationName, "false").To<bool>(); AuthCookieName = xml.ResolveValue(HostUtils.AuthCookieName, AuthCookieName); AuthCookieDomain = xml.ResolveValue(HostUtils.AuthCookieDomain, AuthCookieDomain); EncryptBasis = xml.ResolveValue(HostUtils.EncryptBasis, Guid.NewGuid().ToString()); DefaultPage = xml.ResolveValue(HostUtils.DefaultPage, "default.html"); MaxRequestSize = xml.ResolveValue("maxrequestsize", "10000000").ToInt(); RequireLogin = xml.ResolveValue("requirelogin").ToBool(); foreach (XElement bind in xml.Elements(HostUtils.BindingXmlName)) { var excludehost = bind.Attr("excludehost").SmartSplit(); bool process = true; if (0 != excludehost.Count) { var machine = Environment.MachineName.ToUpperInvariant(); foreach (var h in excludehost) { if (machine == h.ToUpperInvariant().Trim()) { process = false; break; } } } if(!process)continue; var hostbind = new HostBinding(); hostbind.Port = bind.Attr(HostUtils.PortXmlName).ToInt(); hostbind.Interface = bind.Attr(HostUtils.InterfaceXmlName); string schema = bind.Attr(HostUtils.SchemaXmlName); if (!string.IsNullOrWhiteSpace(schema)){ if (schema == HostUtils.HttpsXmlValue){ hostbind.Schema = HostSchema.Https; } } if (hostbind.Port == 0){ hostbind.Port = HostUtils.DefaultBindingPort; } if (string.IsNullOrWhiteSpace(hostbind.Interface)){ hostbind.Interface = HostUtils.DefaultBindingInterface; } Bindings.Add(hostbind); } foreach (var constant in xml.Elements("constant")) { if (string.IsNullOrWhiteSpace(constant.Attr("code"))) continue; Constants[constant.Attr("code").ToLowerInvariant()] = constant.Attr("name"); } foreach (XElement e in xml.Elements(HostUtils.ContentFolder)) { ContentFolders.Add(e.Attr("code")); } ReadModules(xml); foreach (var e in xml.Elements("connection")) { var name = e.Attr("code"); var cstr = e.Attr("name"); if (string.IsNullOrWhiteSpace(name)) continue; if (string.IsNullOrWhiteSpace(cstr)) continue; ConnectionStrings[name] = cstr; } foreach (var e in xml.Elements("static")) { var name = e.Attr("code"); var folder = EnvironmentInfo.ResolvePath(e.Attr("name")); var role = e.Attr("role"); if (!name.StartsWith("/")) { name = "/" + name; } if (!name.EndsWith("/")) { name += "/"; } if (e.Attr("cache").ToBool()) { this.StaticContentCacheMap[name] = e; } else { this.StaticContentMap[name] = new StaticFolderDescriptor{Key=name,Path=folder,Role=role}; } } foreach (var e in xml.Elements("startup")) { var name = e.Attr("code"); Initializers.Add(name); } foreach (XElement e in xml.Elements(HostUtils.ExContentFolder)) { ExtendedContentFolders.Add(e.Attr("code")); } foreach (XElement e in xml.Elements(HostUtils.IncludeConfigXmlName)){ IncludeConfigMasks.Add(e.Describe().GetEfficienValue()); } foreach (XElement e in xml.Elements(HostUtils.ExcludeConfigXmlName)){ ExcludeConfigMasks.Add(e.Describe().GetEfficienValue()); } foreach (XElement e in xml.Elements("cache")){ Cached.Add(e.Value); } foreach (XElement e in xml.Elements("proxize")) { var key = e.Attr("code"); var url = e.Attr("url"); if (string.IsNullOrWhiteSpace(url)) { if (!string.IsNullOrWhiteSpace(e.Attr("appid"))) { url += "appid=" + e.Attr("appid")+";"; } if (!string.IsNullOrWhiteSpace(e.Attr("secure"))) { url += "secure=" + e.Attr("secure")+";"; } if (!string.IsNullOrWhiteSpace(e.Attr("server"))) { url += "server=" + e.Attr("server") + ";"; } } Proxize[key] = url; } foreach (XElement e in xml.Elements("lib")) { AutoconfigureAssemblies.Add(e.AttrOrValue("code")); } ForceNoCache = xml.Attr("forcenocache").ToBool(); var appid = xml.ResolveValue("appid", "0").ToInt(); if (appid != 0) { AddQorpentBinding(appid); Loggy.Info(string.Concat("AppId is [", appid , "]")); } LoggerName = xml.ResolveValue("loggername", ""); LoggerHost = xml.ResolveValue("loggerhost", ""); LoggerPort = xml.ResolveValue("loggerport", "0").ToInt(); LoggerFormat = xml.ResolveValue("loggerformat", "").Replace("%{","${"); this.AccessAllowOrigin = xml.ResolveValue("origin", ""); foreach (var e in xml.Elements("require")) { var appname = e.Attr("code")+e.Attr("suffix"); var proxize = e.GetSmartValue("proxize").ToBool() || e.Attr("name")=="proxize"; if (proxize) { if (null == context) { this.Log.Error("context not provi " + appname); } var cls = context[appname]; if (null == cls) { this.Log.Error("cannot find application for proxize " + appname); } else { var sappid = cls.Compiled.ResolveValue("appid"); var services = cls.Compiled.Elements("service"); foreach (var srv in services) { var root = srv.Attr("code"); var server = e.Attr("server"); var cp = "appid=" + sappid + ";"; if (!string.IsNullOrWhiteSpace(server)) { cp += "server=" + server; } this.Proxize[root] = cp; } } } } }
/// <summary> /// </summary> /// <param name="result"></param> protected virtual void PreVerify(IBSharpContext result){ ExecutePhase(result, BSharpBuilderPhase.PreVerify); }
private void ExecutePhase(IBSharpContext result, BSharpBuilderPhase phase){ Log.Trace("\tstart phase " + phase); IBSharpBuilderTask[] tasks = Tasks.Where(_ => _.Phase == phase).OrderBy(_ => _.Index).ToArray(); foreach (IBSharpBuilderTask t in tasks){ Log.Trace("\t\t" + t.GetType().Name + " started"); if (t.Async){ pending.Add(Task.Run(() => ExecuteTask(result, t))); } else{ ExecuteTask(result, t); } } Task.WaitAll(pending.ToArray()); Log.Trace("\tend phase " + phase); }
/// <summary> /// </summary> /// <param name="result"></param> protected virtual void PostProcess(IBSharpContext result){ ExecutePhase(result, BSharpBuilderPhase.PostProcess); }
/// <summary> /// Выполнение цели /// </summary> /// <param name="context"></param> public override void Execute(IBSharpContext context) { LoadBxlSources(context); LoadJsonSources(context); Project.Log.Info("added "+Project.Sources.Count+" source files"); }
/// <summary> /// Регистратор ошибок /// </summary> /// <param name="result"></param> /// <param name="e"></param> protected virtual void RegisterError(IBSharpContext result, Exception e){ result.RegisterError(BSharpErrors.Generic(e)); }
/// <summary> /// Внутернний метод билда /// </summary> /// <param name="result"></param> protected virtual void InternalBuild(IBSharpContext result){ ExecutePhase(result, BSharpBuilderPhase.Build); }
/// <summary> /// </summary> public BSharpClass(IBSharpContext context):this(){ _context = context; }
/// <summary> /// Произведение реальной записки скомпилированного контекста /// на диск с резольвингом пути и формы записи согласно OutputAttributes /// </summary> /// <param name="context"></param> protected virtual void RollRealWriting(IBSharpContext context) { PrepareTargets(context); WriteManager.Roll(); }
/// <summary> /// Подготавливает список целевых файлов с содержимым /// для записи на диск /// </summary> /// <param name="context">Контекст компилятора</param> protected virtual void PrepareTargets(IBSharpContext context) { context.Get(DataType).ToArray().AsParallel().ForAll(_ =>{ var target = GenerateTarget(_); WriteManager.Add(target); }); }