public ElementValuePair Read(ClassData classData) { this.ElementNameIndex = classData.ReadUint16(); this.ElementValue = new ElementValue().Read(classData); return(this); }
public ElementValue Read(ClassData classData) { this.Tag = classData.ReadUint8(); this.Value = new Value().Read(classData); return(this); }
public void LoadData() { if (_listClass != null) { _listClass.Clear(); } else { _listClass = new ObservableCollection <ClassData>(); } List <@class> Classes = DataProvider.Ins.DB.classes.Join( DataProvider.Ins.DB.grades, d => d.id_grade, f => f.id, (d, f) => d ).ToList(); foreach (@class c in Classes) { ClassData temp = new ClassData(); temp.Id = c.id; temp.ClassName = c.name; temp.GradeName = c.grade.name; _listClass.Add(temp); } }
internal async Task<string> RenderPropertyListAsync(object model, bool ReadOnly) { HtmlBuilder hb = new HtmlBuilder(); Type modelType = model.GetType(); ClassData classData = ObjectSupport.GetClassData(modelType); RenderHeader(hb, classData); bool showVariables = YetaWF.Core.Localize.UserSettings.GetProperty<bool>("ShowVariables"); // property table HtmlBuilder hbProps = new HtmlBuilder(); string divId = Manager.UniqueId(); hbProps.Append($@" <div id='{divId}' class='yt_propertylist {(ReadOnly ? "t_display" : "t_edit")}'> {await RenderHiddenAsync(model)} {await RenderListAsync(model, null, showVariables, ReadOnly)} </div>"); if (!string.IsNullOrWhiteSpace(classData.Legend)) { YTagBuilder tagFieldSet = new YTagBuilder("fieldset"); YTagBuilder tagLegend = new YTagBuilder("legend"); tagLegend.SetInnerText(classData.Legend); tagFieldSet.InnerHtml = tagLegend.ToString(YTagRenderMode.Normal) + hbProps.ToString(); hb.Append(tagFieldSet.ToString(YTagRenderMode.Normal)); } else { hb.Append(hbProps.ToString()); } RenderFooter(hb, classData); ControlData cd = GetControlSets(model, divId); Manager.ScriptManager.AddLast($@"new YetaWF_ComponentsHTML.PropertyListComponent('{divId}', {Utility.JsonSerialize(new PropertyList.PropertyListSetup())}, {Utility.JsonSerialize(cd)});"); return hb.ToString(); }
public void LoadClass(VLTDataClassLoad classLoad, VLTFile vltFile) { _vltFile = vltFile; _classLoad = classLoad; _classHash = classLoad.NameHash; _pointers = vltFile.GetChunk(VLTChunkId.Pointers) as VLTPointers; int offset = _pointers[classLoad.Pointer].OffsetDest; vltFile.RawStream.Seek(offset, SeekOrigin.Begin); BinaryReader br = new BinaryReader(vltFile.RawStream); _classFields = new ClassField[_classLoad.TotalFieldsCount]; for (int i = 0; i < _classLoad.TotalFieldsCount; i++) { ClassField field = new ClassField(); field.Read(br); // HACK: for hash dumping later on HashResolver.Resolve(field.NameHash); _classFields[i] = field; } _data = new ClassData(this); }
public void RoundConstructorShouldCreateCorrectly() { var radius = new ClassData { DataName = "Radius", Value = 5 }; var x = new ClassData { DataName = "X", Value = 10 }; var y = new ClassData { DataName = "Y", Value = 5 }; var expectedCircumference = new ClassData { DataName = "Circumference", Value = 31.4 }; var expectedArea = new ClassData { DataName = "Area", Value = 78.5 }; var round = ReflectionHelper.ExecuteConstructorWithCorrectParametersOrder(_subjectType, radius, x, y); AssertEquality(round, radius); AssertEquality(round, x); AssertEquality(round, y); AssertRoundedEquality(round, expectedCircumference); AssertRoundedEquality(round, expectedArea); }
private void Form1_Load(object sender, EventArgs e) { try { Limpiar(); HabDeshCamp(false); toolGuardar.Enabled = false; toolCancelar.Enabled = false; ClassData data = new ClassData(); if (data.IsConnect()) { MessageBox.Show("Conexión Exitosa", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information); } else { MessageBox.Show("Conexión Fallida", "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } dgvUsers.DataSource = data.LoadData(); } catch (Exception ex) { } }
private void GetData(MemoryMappedViewAccessor viewAccessor) { Attacks = new AttackData[MemoryAddresses.Attacks.Length]; viewAccessor.ReadArray(MemoryAddresses.Attacks.Address, Attacks, 0, MemoryAddresses.Attacks.Length); Castles = new CastleData[MemoryAddresses.Castles.Length]; viewAccessor.ReadArray(MemoryAddresses.Castles.Address, Castles, 0, MemoryAddresses.Castles.Length); DefaultKnights = new DefaultKnightData[MemoryAddresses.DefaultKnights.Length]; viewAccessor.ReadArray(MemoryAddresses.DefaultKnights.Address, DefaultKnights, 0, MemoryAddresses.DefaultKnights.Length); Classes = new ClassData[MemoryAddresses.Classes.Length]; viewAccessor.ReadArray(MemoryAddresses.Classes.Address, Classes, 0, MemoryAddresses.Classes.Length); Items = new ItemData[MemoryAddresses.Items.Length]; viewAccessor.ReadArray(MemoryAddresses.Items.Address, Items, 0, MemoryAddresses.Items.Length); SpecialAttacks = new SpecialAttackData[MemoryAddresses.SpecialAttacks.Length]; viewAccessor.ReadArray(MemoryAddresses.SpecialAttacks.Address, SpecialAttacks, 0, MemoryAddresses.SpecialAttacks.Length); Spells = new SpellData[MemoryAddresses.Spells.Length]; viewAccessor.ReadArray(MemoryAddresses.Spells.Address, Spells, 0, MemoryAddresses.Spells.Length); Skills = new SkillData[MemoryAddresses.Skills.Length]; viewAccessor.ReadArray(MemoryAddresses.Skills.Address, Skills, 0, MemoryAddresses.Skills.Length); #if WORK_IN_PROGRESS monstersInSummon = new MonsterInSummonData[MemoryAddresses.MonstersInSummon.Length]; viewAccessor.ReadArray(MemoryAddresses.MonstersInSummon.Address, monstersInSummon, 0, MemoryAddresses.MonstersInSummon.Length); statGrowth = new StatGrowthData[MemoryAddresses.StatGrowth.Length]; thisViewAccessor.ReadArray(MemoryAddresses.StatGrowth.Address, statGrowth, 0, MemoryAddresses.StatGrowth.Length); #endif }
public Path Read(ClassData classData) { this.TypePathKind = classData.ReadUint8(); this.TypeArgumentIndex = classData.ReadUint8(); return(this); }
private void toolGuardar_Click(object sender, EventArgs e) { ClassData data = new ClassData(); if (isupdate == true) { data.ActualizaDato(textUsuario.Text, textNickname.Text, textCont.Text, textCorreo.Text, Id); } else { data.InsertaDato(textUsuario.Text, textNickname.Text, textCont.Text, textCorreo.Text); } dgvUsers.DataSource = data.LoadData(); Limpiar(); HabDeshCamp(false); toolAgregar.Enabled = true; toolActualizar.Enabled = true; toolBorrar.Enabled = true; toolGuardar.Enabled = false; toolCancelar.Enabled = false; isupdate = false; this.Refresh(); }
public void TriangleConstructorShouldCreateCorrectly() { var a = new ClassData { DataName = "A", Value = 3 }; var b = new ClassData { DataName = "B", Value = 4 }; var c = new ClassData { DataName = "C", Value = 5 }; var expectedArea = new ClassData { DataName = "GetArea", Value = 6 }; var expectedPerimeter = new ClassData { DataName = "GetPerimeter", Value = 12 }; var triangle = ReflectionHelper.ExecuteConstructorWithCorrectParametersOrder(_subjectType, a, b, c); AssertEquality(triangle, a); AssertEquality(triangle, b); AssertEquality(triangle, c); AssertMethodResultEquality(triangle, expectedPerimeter); AssertMethodResultEquality(triangle, expectedArea); }
public TypePath Read(ClassData classData) { this.PathLength = classData.ReadUint8(); this.Path = new Path().Read(classData); return this; }
public TypeParameterBoundTarget Read(ClassData classData) { this.TypeParameterIndex = classData.ReadUint8(); this.BoundIndex = classData.ReadUint8(); return this; }
public static ClassData CurrentAlliedClan() { var saveData = (SaveData)AccessTools.Property(typeof(SaveManager), "ActiveSaveData").GetValue(SaveManager); ClassData mainClass = SaveManager.GetAllGameData().FindClassData(saveData.GetStartingConditions().Class); return(mainClass); }
public CodeCompileUnit Generate(ClassData classData) { if (classData == null) { throw FxTrace.Exception.ArgumentNull("classData"); } CodeCompileUnit result = new CodeCompileUnit(); // Add global namespace CodeNamespace globalNamespace = new CodeNamespace(); result.Namespaces.Add(globalNamespace); CodeTypeDeclaration classDeclaration = GenerateClass(classData); if (!String.IsNullOrEmpty(classData.Namespace)) { // Add namespace the class is defined in CodeNamespace classNamespace = new CodeNamespace(classData.Namespace); result.Namespaces.Add(classNamespace); classNamespace.Types.Add(classDeclaration); } else { // Add class to global namespace globalNamespace.Types.Add(classDeclaration); } return result; }
public override ConstantPoolInfo ReadNotPublic(ClassData classData, ConstantPool constantPool) { this.NameIndex = classData.ReadUint16(); this.DescriptorIndex = classData.ReadUint16(); return(this); }
IWorkshopTree CreateVirtualMap(IEnumerable <IWorkshopTree> macroValues) { // The array of macro values, collected from the potential virtual options. var expArray = Element.CreateArray(macroValues.ToArray()); // The array of class identifiers. var identifierArray = Element.CreateArray(_valueMaps.Select(i => Element.Num(i.Identifier)).ToArray()); ClassData classData = ActionSet.Translate.DeltinScript.GetComponent <ClassData>(); // The class identifier, extracted from the Action Set's current object. Element classIdentifier = classData.ClassIndexes.Get()[ActionSet.CurrentObject]; if (!_mappingArrayCanBeOptimizedOut) { // Maps class identifiers (identifierArray) to a macro value (expArray). var mapArray = Element.CreateArray(_valueMaps.Select(i => Element.Num(i.ExpressionIndex)).ToArray()); return(expArray[mapArray[Element.IndexOfArrayValue(identifierArray, classIdentifier)]]); } else { // Mapping the class identifier is not required, use it directly. return(expArray[Element.IndexOfArrayValue(identifierArray, classIdentifier)]); } }
// Builds a lookup table of class+method name. // // It's easier to build it at once by enumerating, once we have the table, we // can use the symbolIds to look up the sources when we need them. private static AssemblyData FetchSymbolData(IDiaSession session) { // This will be a *flat* enumerator of all classes. // // A nested class will not contain a '+' in it's name, just a '.' separating the parent class name from // the child class name. IDiaEnumSymbols diaClasses; session.findChildren( session.globalScope, // Search at the top-level. SymTagEnum.SymTagCompiland, // Just find classes. name: null, // Don't filter by name. compareFlags: 0u, // doesn't matter because name is null. ppResult: out diaClasses); var assemblyData = new AssemblyData(); // Resist the urge to use foreach here. It doesn't work well with these APIs. var classesFetched = 0u; IDiaSymbol diaClass; diaClasses.Next(1u, out diaClass, out classesFetched); while (classesFetched == 1 && diaClass != null) { var classData = new ClassData() { Name = diaClass.name, SymbolId = diaClass.symIndexId, }; assemblyData.Classes.Add(diaClass.name, classData); IDiaEnumSymbols diaMethods; session.findChildren( diaClass, SymTagEnum.SymTagFunction, name: null, // Don't filter by name. compareFlags: 0u, // doesn't matter because name is null. ppResult: out diaMethods); // Resist the urge to use foreach here. It doesn't work well with these APIs. var methodsFetched = 0u; IDiaSymbol diaMethod; diaMethods.Next(1u, out diaMethod, out methodsFetched); while (methodsFetched == 1 && diaMethod != null) { classData.Methods[diaMethod.name] = new MethodData() { Name = diaMethod.name, SymbolId = diaMethod.symIndexId, }; diaMethods.Next(1u, out diaMethod, out methodsFetched); } diaClasses.Next(1u, out diaClass, out classesFetched); } return(assemblyData); }
/// <summary> /// Create an instance of SaveClassClass /// </summary> /// <param name="saveClass">SaveClass model</param> public ClassDataClass(ClassData saveClass) : base(saveClass.Name) { this._SaveClass = saveClass; this.IsPartial = false; this.IsStruct = saveClass.IsStruct; AddInherit("Skill.Framework.IO.ISavable"); if (!this.IsStruct) { base.AddAttribute("System.Serializable"); Method constructor = new Method("", Name, ""); constructor.Modifier = Modifiers.Public; Add(constructor); } CreateIsDirtyProperty(); CreateSetAsCleanMethod(); // create static creator method CreateCreatorMethod(); // create variables and properties CreateProperties(); CreateXmlSaveMethod(); CreateBinarySaveMethod(); CreateXmlLoadMethods(); CreateBinaryLoadMethod(); }
public Parameter Read(ClassData classData) { this.NameIndex = classData.ReadUint16(); this.AccessFlags = classData.ReadUint16(); return(this); }
public int RollHitPoints(ClassData _charClass) { if (_charClass == null) { return(0); } var hitPoints = this.Health.HitDieMod + this.Stats.GetConstitutionMod(); //Console.WriteLine("Class: " + _charClass.Name); //Console.WriteLine("HD: d"+_charClass.HitDie.ToString()); //Console.WriteLine("HitPoints before Roll: " + hitPoints.ToString()); switch (this.RollMethod) { case "roll": hitPoints += RollDie(_charClass.HitDie); break; case "round": default: hitPoints += Convert.ToInt32(_charClass.HitDie / 2.0) + 1; break; } //Console.WriteLine("HitPoints After Roll: " + hitPoints.ToString()); return(hitPoints); }
public static void Test() { var mc1 = new ManagedClass(); ManagedClass?mc2 = new ManagedClass(); var mc3 = new ManagedClass(); var cwt = new ConditionalWeakTable <ManagedClass, ClassData>(); cwt.Add(mc1, new ClassData()); cwt.Add(mc2, new ClassData()); cwt.Add(mc3, new ClassData()); var wr2 = new WeakReference(mc2); mc2 = null; GC.Collect(); ClassData data = null; if (wr2.Target == null) { Console.WriteLine("No strong reference to mc2 exists."); } else if (cwt.TryGetValue((ManagedClass)wr2.Target, out data)) { Console.WriteLine("Data created at {0}", data.CreationTime); } else { Console.WriteLine("mc2 not found in the table."); } }
private void GetNotebook() { ClassData notebookClass = Master.VersionData.ClassData["Notebook"]; ClassData mathGameClass = Master.VersionData.ClassData["MathGame"]; if (FindObjectOfType(mathGameClass.Type) != null) { return; } foreach (Component notebook in FindObjectsOfType(notebookClass.Type)) { if ((bool)notebookClass.GetField("Up").GetValue(notebook)) { notebook.transform.position = new Vector3(0f, -20f, 0f); notebookClass.GetField("Up").SetValue(notebook, false); notebookClass.GetField("RespawnTime").SetValue(notebook, 120f); Master.VersionData.ClassData["GameController"].InvokeMethod("CollectNotebook", FindObjectOfType(Master.VersionData.GetType("GameController")), new object[] { }); GameObject learningGame = Instantiate <GameObject>((GameObject)notebookClass.GetField("LearningGame").GetValue(notebook)); Component mathGame = learningGame.GetComponent(mathGameClass.Type); mathGameClass.GetField("GameController").SetValue(mathGame, notebookClass.GetField("GameController").GetValue(notebook)); mathGameClass.GetField("Baldi").SetValue(mathGame, notebookClass.GetField("Baldi").GetValue(notebook)); mathGameClass.GetField("PlayerPosition").SetValue(mathGame, ((Transform)notebookClass.GetField("Player").GetValue(notebook)).position); return; } } }
public void Update(PBPlayerData playerData) { ID = playerData.PlayerId; Level = playerData.Level; ClassData = new ClassData(playerData.CharacterId); LevelTableSetting levelData = LevelTableSettings.Get(Level); if (levelData == null) { return; } Name = playerData.Name; HP = playerData.Hp; MaxHP = playerData.MaxHp; MP = playerData.Mp; MaxMP = playerData.MaxMp; Food = playerData.Food; MaxFood = playerData.MaxFood; Gold = playerData.Gold; HeadIcon = playerData.HeadIcon; MapSkillID = playerData.MapSkillId; BattleSkillID = playerData.BattleSkillId; Exp = playerData.Exp; }
bool ClassInherits(ClassData classData) { return(classData.Inherits != null && classData.Inherits.ID != typeof(object).MetadataToken && classData.Inherits.ID != typeof(ValueType).MetadataToken && classData.Inherits.ID != typeof(Delegate).MetadataToken); }
private ClassData ClassDataFromUI(ClassData data) { if (txtClassName.Text == "_Projectiles") // AKA someone tries to break this program { txtClassName.Text = "Projectiles"; } data.Name = txtClassName.Text; data.MapSprite = picIcon.Image; data.Inclination = (Inclination)cmbClassInclination.SelectedIndex; data.Flies = ckbFlies.Checked; data.Growths = gthClassGrowths.Data; data.Weapon.Name = txtWeaponName.Text; data.Weapon.Range = (int)nudWeaponRange.Value; data.Weapon.Damage = (int)nudWeaponDamage.Value; data.Weapon.HitStat = (int)nudWeaponHit.Value; data.Weapon.Weight = (int)nudWeaponWeight.Value; // Battle animations data.BattleAnimations.Clear(); foreach (var item in balBattleAnimations.Datas) { data.BattleAnimations.Add(item); } data.BattleAnimationModeMelee = (BattleAnimationMode)cmbClassAnimationModeMelee.SelectedIndex; data.BattleAnimationModeRanged = (BattleAnimationMode)cmbClassAnimationModeRanged.SelectedIndex; data.ProjectileImage = picProjectile.Image; data.ProjectilePos = new UnityPoint((int)nudProjectileLocationX.Value, (int)nudProjectileLocationY.Value); CurrentFile = data.Name; Dirty = false; return(data); }
public static void Postfix(ContextRankConfig __instance, ref int __result, MechanicsContext context, ref ContextRankBaseValueType ___m_BaseValueType) { if (!BloodArcanist.wantToModify_ContextRankConfig.Contains(__instance)) { return; } if (___m_BaseValueType == ContextRankBaseValueType.SummClassLevelWithArchetype) { ClassData classdata = context.MaybeCaster.Descriptor.Progression.GetClassData(ArcanistClass.arcanist); if (classdata != null && classdata.Archetypes.Contains(BloodArcanist.archetype)) { __result += classdata.Level; return; } } if (___m_BaseValueType == ContextRankBaseValueType.OwnerSummClassLevelWithArchetype) { var maybeOwner = context.MaybeOwner; if (maybeOwner == null) { return; } ClassData classdata = maybeOwner.Descriptor.Progression.GetClassData(ArcanistClass.arcanist); if (classdata != null && classdata.Archetypes.Contains(BloodArcanist.archetype)) { __result += classdata.Level; return; } } }
public ParameterAnotation Read(ClassData classData) { this.NumAnnotations = classData.ReadUint16(); this.Annotations = new AnnotationReader(classData).ReadAnnotations(this.NumAnnotations); return(this); }
public TypeArgumentTarget Read(ClassData classData) { this.Offset = classData.ReadUint16(); this.TypeArgumentIndex = classData.ReadUint8(); return this; }
public LineNumberTable Read(ClassData classData) { this.StartPc = classData.ReadUint16(); this.LineNumber = classData.ReadUint16(); return(this); }
public void Initialize() { CustomLocalizationManager.ImportCSV("Disciple.csv", ';'); clanRef = Clan.Make(); RegisterSubtypes(); MakeStatuses(); MakeEnhancers(); MakeCards(); foreach (var bundle in BundleManager.LoadedAssetBundles) { Trainworks.Trainworks.Log(BepInEx.Logging.LogLevel.All, bundle.Value.GetAllAssetNames().Join()); } SecondDisciple.Make(); Disciple.Make(); Clan.RegisterBanner(); MakeArtifacts(); ProviderManager.SaveManager.GetMetagameSave().SetLevelAndXP(clanRef.GetID(), 10, 99999); //PrintCardStats(); //foreach (SubtypeData s in SubtypeManager.AllData) //{ // Trainworks.Trainworks.Log(BepInEx.Logging.LogLevel.All, "Subtype: " + s.LocalizedName + " - Key: " + s.Key); //} //ProviderManager.SaveManager.EnableTestScenario(ProviderManager.SaveManager.GetAllGameData().FindScenarioDataByName("Level4BattleJunk"), true); }
public static void UpdateClass(Guid OrganizationId, int DepartmentId, int ClassId, ClassData cd) { lib.bwa.bigWebDesk.LinqBll.Context.MutiBaseDataContext dc = new lib.bwa.bigWebDesk.LinqBll.Context.MutiBaseDataContext(OrganizationId, DepartmentId); var c = dc.Tbl_class.Where(cc => cc.Id == ClassId && cc.Company_id == DepartmentId).FirstOrNull(); if (c == null) return; FillClass(cd, c); dc.SubmitChanges(); }
public static void InsertClass(Guid OrganizationId, int DepartmentId, ClassData cd) { lib.bwa.bigWebDesk.LinqBll.Context.MutiBaseDataContext dc = new lib.bwa.bigWebDesk.LinqBll.Context.MutiBaseDataContext(OrganizationId, DepartmentId); Context.Tbl_class c = new Context.Tbl_class(); FillClass(cd, c); dc.Tbl_class.InsertOnSubmit(c); dc.SubmitChanges(); }
static void FillClass(ClassData s, Context.Tbl_class d) { if (s.IsAdded("parent_class_id")) d.ParentId = GetNullId(s.parent_class_id); if (s.IsAdded("name")) d.Name = s.name; if (s.IsAdded("description")) d.TxtDesc = s.description; if (s.IsAdded("active") && s.active!=null) d.BtInactive = !(bool)s.active; if (s.IsAdded("priority_id")) d.IntPriorityId = GetNullId(s.priority_id); if (s.IsAdded("level")) d.TintLevelOverride = (s.level == null ? null : (byte?)(byte)((int)s.level)); if (s.IsAdded("last_resort_tech_userid")) d.LastResortTechId = GetId(s.last_resort_tech_userid); if (s.IsAdded("class_type_id")) d.TintClassType = GetByte(s.class_type_id); if (s.IsAdded("routing_type_id")) d.ConfigDistributedRouting = GetByte(s.routing_type_id); }
public void ToCode_given_TwoPropertiesAndConstructor_should_ReturnCode() { // # Arrange. var sut = new ClassData(); sut.Comment = new CommentData("Simple DTO class."); sut.Name = "Customer"; sut.Properties = new List<PropertyData> { new PropertyData { Name="CustomerID", SystemType=typeof(int), Scope=Common.VisibilityScope.Internal }, new PropertyData { Name="Name", SystemType =typeof(string), Scope=Common.VisibilityScope.Public } }; sut.Methods = new List<MethodData> { new MethodData { Name="Customer", IsConstructor= true, Scope=Common.VisibilityScope.Internal } }; // # Act. var res = sut.ToCode(); // # Assert. Assert.AreEqual(12, res.Count); CollectionAssert.AreEqual( new[] { "/// <summary> Simple DTO class.", "/// </summary>", "public class Customer", "{", "\tinternal System.Int32 CustomerID{ get; set; }", string.Empty, "\tpublic System.String Name{ get; set; }", string.Empty, "\tinternal Customer()", "\t{", "\t}", "}" }, res.ToList()); }
CodeTypeDeclaration GenerateClass(ClassData classData) { CodeTypeDeclaration result = GenerateClassDeclaration(classData); result.Members.Add(new CodeMemberField() { Name = "_contentLoaded", Type = new CodeTypeReference(typeof(bool)) }); // Generate fields that match x:Name objects var fields = classData.NamedObjects; var memberFields = new List<CodeMemberField>(); foreach (NamedObject field in fields) { CodeMemberField fieldMember = GenerateField(field, classData); memberFields.Add(fieldMember); result.Members.Add(fieldMember); } // Generate properties if (classData.Properties != null) { foreach (PropertyData property in classData.Properties) { CodeTypeMember[] propertyMembers = GenerateProperty(property, classData); result.Members.AddRange(propertyMembers); } } // Generate all x:Code foreach (string code in classData.CodeSnippets) { CodeSnippetTypeMember codeSnippet = new CodeSnippetTypeMember(code); result.Members.Add(codeSnippet); } // Generate InitializeComponent method CodeMemberMethod initializeMethod = GenerateInitializeMethod(classData, memberFields); result.Members.Add(initializeMethod); // Generate Before/AfterInitializeComponent partial methods if (ArePartialMethodsSupported()) { result.Members.AddRange(GeneratePartialMethods()); } // Generate helper method to look up assembly resources result.Members.Add(GenerateFindResourceMethod(classData)); // Generate ISupportInitialize implementation result.BaseTypes.Add(new CodeTypeReference(typeof(ISupportInitialize))); result.Members.AddRange(GenerateISupportInitializeImpl(initializeMethod)); // Generate public parameterless constructor if user-provided source file does not exist if (!classData.SourceFileExists) { result.Members.Add(GenerateConstructorImpl(initializeMethod)); } return result; }
CodeMemberMethod GenerateFindResourceMethod(ClassData classData) { // [System.CodeDom.Compiler.GeneratedCodeAttribute("<%= AssemblyName %>", "<%= AssemblyVersion %>")] // private string FindResource() { // CodeMemberMethod findResourceMethod = new CodeMemberMethod() { Name = "FindResource", Attributes = MemberAttributes.Private | MemberAttributes.Final, ReturnType = new CodeTypeReference(typeof(string)), CustomAttributes = { GeneratedCodeAttribute } }; // string[] resources = typeof(<%= className %>).Assembly.GetManifestResourceNames(); // CodeVariableReferenceExpression resourcesVar = findResourceMethod.Statements.DeclareVar( typeof(string[]), "resources", new CodeMethodInvokeExpression() { Method = new CodeMethodReferenceExpression() { MethodName = "GetManifestResourceNames", TargetObject = new CodePropertyReferenceExpression() { PropertyName = "Assembly", TargetObject = new CodeTypeOfExpression() { Type = new CodeTypeReference(classData.Name) } } }, } ); // for (int i = 0; i < resources.Length; i++) { // string resource = resources[i]; // if (resource.Contains(searchString)) { // return resource; // } // } findResourceMethod.Statements.Add( new CodeIterationStatement() { InitStatement = new CodeVariableDeclarationStatement() { Type = new CodeTypeReference(typeof(int)), Name = "i", InitExpression = new CodePrimitiveExpression(0), }, TestExpression = new CodeBinaryOperatorExpression() { Left = new CodeVariableReferenceExpression("i"), Operator = CodeBinaryOperatorType.LessThan, Right = new CodePropertyReferenceExpression() { TargetObject = new CodeVariableReferenceExpression(resourcesVar.VariableName), PropertyName = "Length", }, }, IncrementStatement = new CodeAssignStatement() { Left = new CodeVariableReferenceExpression("i"), Right = new CodeBinaryOperatorExpression() { Left = new CodeVariableReferenceExpression("i"), Operator = CodeBinaryOperatorType.Add, Right = new CodePrimitiveExpression(1), } }, Statements = { new CodeVariableDeclarationStatement() { Type = new CodeTypeReference(typeof(string)), Name = "resource", InitExpression = new CodeArrayIndexerExpression( new CodeVariableReferenceExpression(resourcesVar.VariableName), new CodeVariableReferenceExpression("i")), }, new CodeConditionStatement() { Condition = new CodeBinaryOperatorExpression() { Left = new CodeMethodInvokeExpression() { Method = new CodeMethodReferenceExpression() { TargetObject = new CodeVariableReferenceExpression("resource"), MethodName = "Contains", }, Parameters = { new CodePrimitiveExpression("." + classData.EmbeddedResourceFileName), }, }, Operator = CodeBinaryOperatorType.BooleanOr, Right = new CodeMethodInvokeExpression() { Method = new CodeMethodReferenceExpression() { TargetObject = new CodeVariableReferenceExpression("resource"), MethodName = "Equals", }, Parameters = { new CodePrimitiveExpression(classData.EmbeddedResourceFileName), }, } }, TrueStatements = { new CodeMethodReturnStatement() { Expression = new CodeVariableReferenceExpression("resource"), } } } }, } ); // throw new InvalidOperationException("Resource not found."); // findResourceMethod.Statements.Add( new CodeThrowExceptionStatement() { ToThrow = new CodeObjectCreateExpression() { CreateType = new CodeTypeReference(typeof(InvalidOperationException)), Parameters = { new CodePrimitiveExpression("Resource not found."), } } } ); return findResourceMethod; }
CodeStatementCollection GetInitializeMethodTryStatements(CodeExpression xmlReaderVar, CodeExpression xamlReaderVar, CodeExpression objWriterVar, CodeExpression initializeXamlVar, ClassData classData, List<CodeMemberField> memberFields) { CodeStatementCollection tryStatements = new CodeStatementCollection(); // System.Xaml.XamlSchemaContext schemaContext = _XamlStaticHelperNamespace._XamlStaticHelper.SchemaContext; CodeVariableReferenceExpression SchemaContextReference = new CodeVariableReferenceExpression(classData.HelperClassFullName + ".SchemaContext"); CodeVariableReferenceExpression SchemaContext = tryStatements.DeclareVar(typeof(XamlSchemaContext), "schemaContext", SchemaContextReference); // xmlReader = System.Xml.XmlReader.Create(initializeXaml); CodeExpression xmlReader = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression() { MethodName = "System.Xml.XmlReader.Create" }, initializeXamlVar); tryStatements.Add(new CodeAssignStatement(xmlReaderVar, xmlReader)); // System.Xaml.XamlXmlReaderSettings readerSettings = new System.Xaml.XamlXmlReaderSettings(); CodeVariableReferenceExpression readerSettingsVar = tryStatements.DeclareVar( typeof(XamlXmlReaderSettings), "readerSettings", typeof(XamlXmlReaderSettings).New()); // readerSettings.LocalAssembly = System.Reflection.Assembly.GetExecutingAssembly(); tryStatements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(readerSettingsVar, "LocalAssembly"), new CodeMethodInvokeExpression( new CodeMethodReferenceExpression() { MethodName = "System.Reflection.Assembly.GetExecutingAssembly" }))); // readerSettings.AllowProtectedMembersOnRoot = true; tryStatements.Add( new CodeAssignStatement( new CodePropertyReferenceExpression(readerSettingsVar, "AllowProtectedMembersOnRoot"), new CodePrimitiveExpression(true))); // reader = new System.Xaml.XamlXmlReader(xmlReader, schemaContext, readerSettings); CodeExpression newReader = typeof(XamlXmlReader).New(xmlReaderVar, SchemaContext, readerSettingsVar); tryStatements.Add(new CodeAssignStatement(xamlReaderVar, newReader)); // XamlObjectWriterSettings writerSettings = new XamlObjectWriterSettings(); CodeVariableReferenceExpression writerSettingsVar = tryStatements.DeclareVar( typeof(XamlObjectWriterSettings), "writerSettings", typeof(XamlObjectWriterSettings).New()); // writerSettings.RootObjectInstance = this; tryStatements.Add(new CodeAssignStatement() { Left = writerSettingsVar.Property("RootObjectInstance"), Right = CodeThis }); // writerSettings.AccessLevel = System.Xaml.Permissions.XamlAccessLevel.PrivateAccessTo(typeof(<TypeBeingGenerated>)); tryStatements.Add(new CodeAssignStatement() { Left = writerSettingsVar.Property("AccessLevel"), Right = new CodeMethodInvokeExpression( new CodeMethodReferenceExpression() { MethodName = "System.Xaml.Permissions.XamlAccessLevel.PrivateAccessTo" }, new CodeTypeOfExpression(classData.Name) ) }); // var writer = new XamlObjectWriter(schemaContext, settings); // CodeExpression newObjectWriter = typeof(XamlObjectWriter).New(SchemaContext, writerSettingsVar); tryStatements.Add(new CodeAssignStatement(objWriterVar, newObjectWriter)); // XamlServices.Transform(reader, writer); // tryStatements.Add( new CodeMethodInvokeExpression( new CodeMethodReferenceExpression() { MethodName = "System.Xaml.XamlServices.Transform" }, xamlReaderVar, objWriterVar )); // For all fields generated, generate the wireup to get the value from xaml. For eg, for a field of type "Bar" and name "Baz": // Baz = ((Tests.Build.Tasks.Xaml.Bar)(objectWriter.RootNameScope.FindName("Baz"))); if (memberFields != null && memberFields.Count > 0) { foreach (var field in memberFields) { tryStatements.Add( new CodeAssignStatement( new CodeVariableReferenceExpression(field.Name), new CodeCastExpression( field.Type, new CodeMethodInvokeExpression( new CodePropertyReferenceExpression(objWriterVar, "RootNameScope"), "FindName", new CodePrimitiveExpression(field.Name))))); } } return tryStatements; }
private void CreateButton_Click(object sender, System.Windows.RoutedEventArgs e) { ClassData data = new ClassData("未命名課程" + classNum.ToString()); this.classList.Add(data); this.classNum++; this.ClassList.ItemsSource = null; this.ClassList.ItemsSource = classList; this.ClassNameTextbox.IsEnabled = true; //開啟ClassNameTextbox 輸入功能 ObjectData Odata = new ObjectData((this.objectList.Count + 1).ToString()); this.objectList.Add(Odata); this.ObjectList.ItemsSource = null; this.ObjectList.ItemsSource = objectList; }
internal void Generate() { IParserLogic2 parserLogic2 = new ParserLogic2(); _classDataList = new List<ClassData>(); _database.Tables .Where(t => t.Include) .ToList() .ForEach(table => { // Set data for the very [class]. var classData = new ClassData { Name = table.Name, IsPartial = _pocoSettings.MakePartial, Properties = new List<PropertyData>(), Methods = new List<MethodData>() }; // # Create the properties. table.Columns .ForEach(column => { classData.Properties.Add( new PropertyData { Name = column.Name, Scope = Common.VisibilityScope.Public, SystemType = parserLogic2.ConvertDatabaseTypeToDotnetType(column.DatabaseTypeName), Comment = column.IsInPrimaryKey ? new CommentData("This property is part of the primary key.") : null }); }); // # Create the constructors. if (_pocoSettings.CreateDefaultConstructor) { classData.Methods.Add(new MethodData { IsConstructor = true, Name = classData.Name, Comment = new CommentData("Default constructor needed for instance for de/serialising.") }); } if (_pocoSettings.CreateAllPropertiesConstructor) { classData.Methods.Add( new MethodData { IsConstructor = true, Name = classData.Name, Comment = new CommentData("This constructor takes all properties as parameters."), Parameters = table.Columns.Select(p => new ParameterData { Name = p.Name, SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString( p.DatabaseTypeName) }).ToList() }); } if (_pocoSettings.CreateAllPropertiesSansPrimaryKeyConstructor) { classData.Methods.Add(new MethodData { IsConstructor = true, Name = classData.Name, Comment = new CommentData("This constructor takes all properties but primary keys as parameters."), Parameters = table.Columns .Where(p=>false == p.IsInPrimaryKey) .Select(p => new ParameterData { Name = p.Name, SystemTypeString = parserLogic2.ConvertDatabaseTypeToDotnetTypeString( p.DatabaseTypeName) }).ToList() }); } if(_pocoSettings.CreateCopyConstructor) { classData.Methods.Add(new MethodData { IsConstructor = true, Name = classData.Name, Comment = new CommentData("This is the copy constructor."), Parameters = new List<ParameterData> { new ParameterData { Name = classData.Name, SystemTypeString = classData.Name } }, Body = new BodyData { Lines = table.Columns .Select(p => string.Format("this.{0} = {1}.{2};", p.Name, Common.Safe(Common.ToCamelCase(table.Name)), p.Name)) .ToList() } }); } // # Create the methods. if (_pocoSettings.CreateMethodEquals && Regex.IsMatch(classData.Name, _pocoSettings.CreateMethodEqualsRegex)) { classData.Methods.Add( CreateEqualsMethod(table, classData, "o")); classData.Methods.Add( CreateHashMethod(table, classData)); } _classDataList.Add(classData); }); _log.Add("Included classes are:"); _log.Add(_classDataList.ToInfo()); }
private static MethodData CreateEqualsMethod(TableData table, ClassData classData, string ParameterName) { return new MethodData { IsConstructor = false, Name = "Equals", Override = true, ReturnTypeString = typeof(bool).ToString(), Comment = new CommentData("This is the Equals method."), Parameters = new List<ParameterData> { new ParameterData { Name = ParameterName, SystemTypeString = typeof(object).ToString() } }, Body = new BodyData( CreateBodyForEqualsMethod(table, classData, ParameterName) ) }; }
bool GetTypeArgumentFromXamlType(CodeTypeReference codeTypeReference, XamlType xamlType, ClassData classData) { // // Depending on the name passed into the CodeTypeReference // constructor the type args may already be populated if (codeTypeReference.TypeArguments != null && codeTypeReference.TypeArguments.Count == 0 && xamlType.TypeArguments != null && xamlType.TypeArguments.Count > 0) { foreach (XamlType argumentTypeReference in xamlType.TypeArguments) { CodeTypeReference argumentCodeTypeReference = null; if (!GetCodeTypeReferenceFromXamlType(argumentTypeReference, classData, out argumentCodeTypeReference)) { return false; } codeTypeReference.TypeArguments.Add(argumentCodeTypeReference); } } return true; }
CodeAttributeDeclarationCollection GetAttributeDeclarations(IList<AttributeData> attributes, ClassData classData) { CodeAttributeDeclarationCollection attributeCollection = new CodeAttributeDeclarationCollection(); foreach (AttributeData attrib in attributes) { string clrTypeName; bool isLocal = false; if (!XamlBuildTaskServices.TryGetClrTypeName(attrib.Type, classData.RootNamespace, out clrTypeName, out isLocal)) { throw FxTrace.Exception.AsError( new InvalidOperationException(SR.TaskCannotResolveType(XamlBuildTaskServices.GetFullTypeName(attrib.Type))), classData.FileName); } classData.RequiresCompilationPass2 |= isLocal; CodeAttributeArgument[] arguments = new CodeAttributeArgument[attrib.Parameters.Count + attrib.Properties.Count]; int i; for (i = 0; i < attrib.Parameters.Count; i++) { arguments[i] = new CodeAttributeArgument(GetCodeExpressionForAttributeArgument(attrib, attrib.Parameters[i], classData)); } foreach (KeyValuePair<string, AttributeParameterData> propertyEntry in attrib.Properties) { arguments[i] = new CodeAttributeArgument(propertyEntry.Key, GetCodeExpressionForAttributeArgument(attrib, propertyEntry.Value, classData)); i++; } attributeCollection.Add(new CodeAttributeDeclaration(new CodeTypeReference(clrTypeName), arguments)); } return attributeCollection; }
CodeTypeDeclaration GenerateClassDeclaration(ClassData classData) { if (!this.codeDomProvider.IsValidIdentifier(classData.Name)) { throw FxTrace.Exception.AsError( new InvalidOperationException(SR.InvalidIdentifiers(classData.Name)), classData.FileName); } // <%= visibility%> partial class <%= className %> : <%= type %> // { // } // CodeTypeDeclaration rootType = new CodeTypeDeclaration() { Name = classData.Name, IsPartial = true, TypeAttributes = classData.IsPublic ? TypeAttributes.Public : TypeAttributes.NotPublic }; if (classData.Attributes != null && classData.Attributes.Count > 0) { CodeAttributeDeclarationCollection attributeCollection = GetAttributeDeclarations(classData.Attributes, classData); if (attributeCollection != null && attributeCollection.Count > 0) { rootType.CustomAttributes.AddRange(attributeCollection); } } string baseClrTypeName; bool isLocal = false; if (!XamlBuildTaskServices.TryGetClrTypeName(classData.BaseType, classData.RootNamespace, out baseClrTypeName, out isLocal)) { throw FxTrace.Exception.AsError( new InvalidOperationException(SR.TaskCannotResolveType(XamlBuildTaskServices.GetFullTypeName(classData.BaseType))), classData.FileName); } classData.RequiresCompilationPass2 |= isLocal; rootType.BaseTypes.Add(baseClrTypeName); Type baseClrType = classData.BaseType.UnderlyingType; if (baseClrType != null) { if (!IsComVisible(baseClrType)) { CodeAttributeDeclaration comVisibleFalseDeclaration = new CodeAttributeDeclaration("System.Runtime.InteropServices.ComVisible", new CodeAttributeArgument(new CodePrimitiveExpression(false))); rootType.CustomAttributes.Add(comVisibleFalseDeclaration); } } return rootType; }
bool ExecuteExtensions(ClassData classData, ITaskItem markupItem) { // Execute pass1 extensions only // we skip pass1 extensions if we are doing in-proc compile if (!this.IsInProcessXamlMarkupCompile) { bool extensionExecutedSuccessfully = true; foreach (IXamlBuildTypeGenerationExtension extension in this.xamlBuildTypeGenerationExtensions) { if (extension == null) { continue; } this.BuildContextForExtensions.InputTaskItem = markupItem; try { extensionExecutedSuccessfully = extension.Execute(classData, this.BuildContextForExtensions) && extensionExecutedSuccessfully; } catch (Exception e) { if (Fx.IsFatal(e)) { throw; } throw FxTrace.Exception.AsError(new LoggableException(SR.ExceptionThrownInExtension(extension.ToString(), e.GetType().ToString(), e.Message))); } } if (this.BuildLogger.HasLoggedErrors || !extensionExecutedSuccessfully) { return false; } } return true; }
void RemoveXamlSpaceAttribute(ClassData classData) { using (XamlReader reader = classData.EmbeddedResourceXaml.GetReader()) { XamlNodeList newList = new XamlNodeList(reader.SchemaContext); using (XamlWriter writer = newList.Writer) { bool nodesAvailable = reader.Read(); while (nodesAvailable) { if (reader.NodeType == XamlNodeType.StartMember && reader.Member == XamlLanguage.Space) { reader.Skip(); } else { writer.WriteNode(reader); nodesAvailable = reader.Read(); } } } classData.EmbeddedResourceXaml = newList; } }
// Builds a lookup table of class+method name. // // It's easier to build it at once by enumerating, once we have the table, we // can use the symbolIds to look up the sources when we need them. private static AssemblyData FetchSymbolData(IDiaSession session) { // This will be a *flat* enumerator of all classes. // // A nested class will not contain a '+' in it's name, just a '.' separating the parent class name from // the child class name. IDiaEnumSymbols diaClasses; session.findChildren( session.globalScope, // Search at the top-level. SymTagEnum.SymTagCompiland, // Just find classes. name: null, // Don't filter by name. compareFlags: 0u, // doesn't matter because name is null. ppResult: out diaClasses); var assemblyData = new AssemblyData(); // Resist the urge to use foreach here. It doesn't work well with these APIs. var classesFetched = 0u; IDiaSymbol diaClass; diaClasses.Next(1u, out diaClass, out classesFetched); while (classesFetched == 1 && diaClass != null) { var classData = new ClassData() { Name = diaClass.name, SymbolId = diaClass.symIndexId, }; assemblyData.Classes.Add(diaClass.name, classData); IDiaEnumSymbols diaMethods; session.findChildren( diaClass, SymTagEnum.SymTagFunction, name: null, // Don't filter by name. compareFlags: 0u, // doesn't matter because name is null. ppResult: out diaMethods); // Resist the urge to use foreach here. It doesn't work well with these APIs. var methodsFetched = 0u; IDiaSymbol diaMethod; diaMethods.Next(1u, out diaMethod, out methodsFetched); while (methodsFetched == 1 && diaMethod != null) { classData.Methods[diaMethod.name] = new MethodData() { Name = diaMethod.name, SymbolId = diaMethod.symIndexId, }; diaMethods.Next(1u, out diaMethod, out methodsFetched); } diaClasses.Next(1u, out diaClass, out classesFetched); } return assemblyData; }
private IList<string> MakeClass(ClassData classData) { var ret = new List<string>(); ret.Add(string.Format( "//\tThis file was generated by St4mpede.Poco {0}.", DateTime.Now.ToString("u"))); ret.Add(string.Empty); ret.AddRange(_pocoSettings.NameSpaceComments.Select(c => string.Format("//\t{0}",c))); ret.Add(string.Format("namespace {0}", _pocoSettings.NameSpace)); ret.Add("{"); ret.AddRange(classData.ToCode(new Indent(1))); ret.Add("}"); return ret; }
CodeTypeMember[] GenerateProperty(PropertyData property, ClassData classData) { // CodeTypeReference propertyCodeType = null; if (!GetCodeTypeReferenceFromXamlType(property.Type, classData, out propertyCodeType)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.TaskCannotResolvePropertyType( XamlBuildTaskServices.GetFullTypeName(property.Type), property.Name)), classData.FileName); } if (!this.codeDomProvider.IsValidIdentifier(property.Name)) { throw FxTrace.Exception.AsError( new InvalidOperationException(SR.InvalidIdentifiers(property.Name)), classData.FileName); } // private <%= property.Type %> _<%= property.Name %>; // CodeMemberField fieldMember = new CodeMemberField() { Attributes = MemberAttributes.Private, Name = "_" + property.Name, Type = propertyCodeType }; // public <%= property.Type %> <%= property.Name %> { // get { return this._<%= property.Name %>; } // set { this._<%= property.Name %> = value; } // } // CodeMemberProperty propertyMember = new CodeMemberProperty() { Attributes = MemberAttributes.Final, Name = property.Name, Type = propertyCodeType, GetStatements = { new CodeMethodReturnStatement(CodeThis.Field(fieldMember.Name)) }, SetStatements = { new CodeAssignStatement() { Left = CodeThis.Field(fieldMember.Name), Right = new CodeVariableReferenceExpression("value") } } }; propertyMember.Attributes |= GetMemberAttributes(property.Visibility); if (property.Attributes != null && property.Attributes.Count > 0) { CodeAttributeDeclarationCollection attributeCollection = GetAttributeDeclarations(property.Attributes, classData); if (attributeCollection != null && attributeCollection.Count > 0) { propertyMember.CustomAttributes.AddRange(attributeCollection); } } return new CodeTypeMember[] { fieldMember, propertyMember }; }
CodeExpression GetCodeExpressionForAttributeArgument(AttributeData attrib, AttributeParameterData paramInfo, ClassData classData) { CodeExpression codeExp; if (paramInfo.IsArray) { CodeExpression[] codeInitializationArray; if (paramInfo.ArrayContents != null && paramInfo.ArrayContents.Count > 0) { codeInitializationArray = new CodeExpression[paramInfo.ArrayContents.Count]; for (int i = 0; i < paramInfo.ArrayContents.Count; i++) { codeInitializationArray[i] = GetCodeExpressionForAttributeArgument(/* attrib = */ null, paramInfo.ArrayContents[i], classData); } codeExp = new CodeArrayCreateExpression(paramInfo.Type.UnderlyingType.GetElementType(), codeInitializationArray); } else { codeExp = new CodeArrayCreateExpression(paramInfo.Type.UnderlyingType.GetElementType()); } } else { if (attrib != null && language.Equals("VB") && string.Equals(attrib.Type.UnderlyingType.FullName, typeof(DefaultValueAttribute).FullName) && paramInfo.Type == null) { // // This is a special case for VB DefaultValueAttribute because by default the VB compiler does not compile the following code: // // < System.ComponentModel.DefaultValueAttribute(Nothing) > // // VB compiler complained that code has multiple interpretation because DefaultValueAttribute has multiple constructors that accept null. // // The solution here is to just pick the one that take in an object as a parameter. Internally, all these constructor will simply set // an internal field named value to null and therefore picking which one does not matter anyway. // codeExp = new CodeCastExpression { TargetType = new CodeTypeReference(typeof(object)), Expression = new CodePrimitiveExpression(null) }; } else if (paramInfo.TextValue == null) { codeExp = new CodePrimitiveExpression(null); } else if (typeof(System.Type).IsAssignableFrom(paramInfo.Type.UnderlyingType)) { codeExp = new CodeTypeOfExpression(paramInfo.TextValue); } else if (paramInfo.Type.UnderlyingType == typeof(String)) { codeExp = new CodePrimitiveExpression(paramInfo.TextValue); } else if (paramInfo.Type.UnderlyingType == typeof(bool)) { if (paramInfo.TextValue == "true") { codeExp = new CodePrimitiveExpression(true); } else { codeExp = new CodePrimitiveExpression(false); } } else { codeExp = new CodeSnippetExpression(paramInfo.TextValue); } } return codeExp; }
bool GetCodeTypeReferenceFromXamlType(XamlType xamlType, ClassData classData, out CodeTypeReference codeTypeReference) { codeTypeReference = null; string propClrTypeName; bool isLocal = false; if (!XamlBuildTaskServices.TryGetClrTypeName(xamlType, classData.RootNamespace, out propClrTypeName, out isLocal)) { return false; } classData.RequiresCompilationPass2 |= isLocal; codeTypeReference = new CodeTypeReference(propClrTypeName); if (!GetTypeArgumentFromXamlType(codeTypeReference, xamlType, classData)) { return false; } return true; }
private CodeMemberField GenerateField(NamedObject fieldData, ClassData classData) { CodeTypeReference fieldCodeType = null; if (!GetCodeTypeReferenceFromXamlType(fieldData.Type, classData, out fieldCodeType)) { throw FxTrace.Exception.AsError( new InvalidOperationException(SR.TaskCannotResolveFieldType(XamlBuildTaskServices.GetFullTypeName(fieldData.Type), fieldData.Name)), classData.FileName); } if (!this.codeDomProvider.IsValidIdentifier(fieldData.Name)) { throw FxTrace.Exception.AsError(new InvalidOperationException(SR.InvalidIdentifiers(fieldData.Name)), classData.FileName); } // <%= fieldData.Visibility %> WithEvents <%= fieldData.Type %> <%= fieldData.Name %>; // CodeMemberField field = new CodeMemberField() { Name = fieldData.Name, Type = fieldCodeType, Attributes = GetMemberAttributes(fieldData.Visibility) }; field.UserData["WithEvents"] = true; return field; }
private static IList<string> CreateBodyForEqualsMethod(TableData table, ClassData classData, string parameterName) { var bodyLines = new List<string> { string.Format("var obj = {0} as {1};", parameterName, classData.Name), "if( obj == null ){", "\treturn false;", "}", string.Empty, "return" }; bodyLines.AddRange(table.Columns.Select(c => string.Format("\tthis.{0} == obj.{0} &&", c.Name, parameterName ))); bodyLines[bodyLines.Count - 1] = bodyLines.Last().Replace(" &&", ";"); return bodyLines; }
CodeMemberMethod GenerateInitializeMethod(ClassData classData, List<CodeMemberField> memberFields) { // /// <summary> InitializeComponent </summary> // [DebuggerNonUserCodeAttribute] // [System.CodeDom.Compiler.GeneratedCodeAttribute("<%= AssemblyName %>", "<%= AssemblyVersion %>")] // public void InitializeComponent() { // CodeMemberMethod initializeMethod = new CodeMemberMethod() { Name = "InitializeComponent", Attributes = MemberAttributes.Public | MemberAttributes.Final, CustomAttributes = { new CodeAttributeDeclaration(new CodeTypeReference(typeof(DebuggerNonUserCodeAttribute))), GeneratedCodeAttribute } }; initializeMethod.Comments.AddRange(GenerateXmlComments(initializeMethod.Name)); // if (__contentLoaded) { return; } initializeMethod.Statements.Add( new CodeConditionStatement() { Condition = new CodeBinaryOperatorExpression() { Left = new CodeFieldReferenceExpression() { FieldName = "_contentLoaded", TargetObject = new CodeThisReferenceExpression() }, Operator = CodeBinaryOperatorType.ValueEquality, Right = new CodePrimitiveExpression(true) }, TrueStatements = { new CodeMethodReturnStatement() } } ); // __contentLoaded = true; initializeMethod.Statements.Add( new CodeAssignStatement() { Left = new CodeFieldReferenceExpression() { FieldName = "_contentLoaded", TargetObject = new CodeThisReferenceExpression() }, Right = new CodePrimitiveExpression(true) } ); if (ArePartialMethodsSupported()) { // bool isInitialized = false; // BeforeInitializeComponent(ref isInitialized); // if (isInitialized) { // AfterInitializeComponent(); // return; // } initializeMethod.Statements.Add(new CodeVariableDeclarationStatement( typeof(bool), "isInitialized", new CodePrimitiveExpression(false))); initializeMethod.Statements.Add(new CodeMethodInvokeExpression( new CodeThisReferenceExpression(), "BeforeInitializeComponent", new CodeDirectionExpression(FieldDirection.Ref, new CodeVariableReferenceExpression("isInitialized")) )); initializeMethod.Statements.Add( new CodeConditionStatement { Condition = new CodeBinaryOperatorExpression( new CodeVariableReferenceExpression("isInitialized"), CodeBinaryOperatorType.ValueEquality, new CodePrimitiveExpression(true) ), TrueStatements = { new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "AfterInitializeComponent"), new CodeMethodReturnStatement() } } ); } // string resourceName = FindResource(); CodeVariableReferenceExpression resourceNameVar = initializeMethod.Statements.DeclareVar( typeof(string), "resourceName", new CodeMethodInvokeExpression() { Method = new CodeMethodReferenceExpression() { MethodName = "FindResource", TargetObject = new CodeThisReferenceExpression(), }, } ); // Stream initializeXaml = typeof(<%= className %>).Assembly.GetManifestResourceStream(resourceName); // CodeVariableReferenceExpression initializeXamlVar = initializeMethod.Statements.DeclareVar( typeof(Stream), "initializeXaml", new CodeMethodInvokeExpression() { Method = new CodeMethodReferenceExpression() { MethodName = "GetManifestResourceStream", TargetObject = new CodePropertyReferenceExpression() { PropertyName = "Assembly", TargetObject = new CodeTypeOfExpression() { Type = new CodeTypeReference(classData.Name) } } }, Parameters = { new CodeVariableReferenceExpression(resourceNameVar.VariableName), } } ); // var reader = new System.Xaml.XamlXmlReader(new System.IO.StreamReader(initializeXaml)); // CodeVariableReferenceExpression xmlReaderVar = initializeMethod.Statements.DeclareVar( typeof(XmlReader), "xmlReader", new CodePrimitiveExpression(null)); CodeVariableReferenceExpression xamlReaderVar = initializeMethod.Statements.DeclareVar( typeof(XamlReader), "reader", new CodePrimitiveExpression(null)); CodeVariableReferenceExpression objWriterVar = initializeMethod.Statements.DeclareVar( typeof(XamlObjectWriter), "objectWriter", new CodePrimitiveExpression(null)); // Enclose in try finally block // This is to call Dispose on the xmlReader in the finally block, which is the CodeDom way of the C# "using" block CodeTryCatchFinallyStatement tryCatchFinally = new CodeTryCatchFinallyStatement(); tryCatchFinally.TryStatements.AddRange(GetInitializeMethodTryStatements(xmlReaderVar, xamlReaderVar, objWriterVar, initializeXamlVar, classData, memberFields)); tryCatchFinally.FinallyStatements.AddRange(GetInitializeMethodFinallyStatements(xmlReaderVar, xamlReaderVar, objWriterVar)); initializeMethod.Statements.Add(tryCatchFinally); if (ArePartialMethodsSupported()) { // AfterInitializeComponent(); initializeMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeThisReferenceExpression(), "AfterInitializeComponent")); } return initializeMethod; }
private MethodData CreateHashMethod(TableData table, ClassData classData) { return new MethodData { IsConstructor = false, Name = "GetHashCode", Override = true, ReturnTypeString = typeof(int).ToString(), Comment = new CommentData("This is the GetHashCode method."), Parameters = null, Body = new BodyData(CreateBodyForGetHashCodeMethod(table)) }; }
void SetClassName(string fullClassName, ClassData classData) { int lastIndex = fullClassName.LastIndexOf('.'); if (lastIndex != -1) { string classNamespace = fullClassName.Substring(0, lastIndex); string className = fullClassName.Substring(lastIndex + 1); classData.Name = className; classData.Namespace = classNamespace; } else { classData.Name = fullClassName; classData.Namespace = String.Empty; } if (string.IsNullOrEmpty(classData.Name)) { throw FxTrace.Exception.AsError(LogInvalidOperationException(null, SR.ClassNameMustBeNonEmpty)); } }
internal static IList<string> UT_CreateBodyForEqualsMethod(TableData table, ClassData classData, string parameterName) { return CreateBodyForEqualsMethod(table, classData,parameterName); }
bool ProcessDirective(XamlReader reader, ClassData classData, NamedObject currentObject, bool isRootElement, XamlNodeList strippedXamlNodes, out bool readNextNode) { Fx.Assert(reader.NodeType == XamlNodeType.StartMember, "Current node should be a Start Member Node"); XamlMember member = reader.Member; bool directiveRecognized = false; readNextNode = false; switch (member.Name) { case "Name": // Unlike all the other directives that we process, x:Name should be written // to the stripped output. strippedXamlNodes.Writer.WriteStartMember(member); string objectName = ReadAtom(reader, XamlLanguage.Name.Name); if (!objectName.StartsWith(XamlBuildTaskServices.SerializerReferenceNamePrefix, StringComparison.Ordinal)) { currentObject.Name = objectName; classData.NamedObjects.Add(currentObject); } strippedXamlNodes.Writer.WriteValue(objectName); strippedXamlNodes.Writer.WriteEndMember(); directiveRecognized = true; break; case "Class": if (isRootElement) { string fullClassName = ReadAtom(reader, XamlLanguage.Class.Name); SetClassName(fullClassName, classData); directiveRecognized = true; } break; case "ClassModifier": if (isRootElement) { string classModifier = ReadAtom(reader, XamlLanguage.ClassModifier.Name); classData.IsPublic = XamlBuildTaskServices.IsPublic(classModifier); directiveRecognized = true; } break; case "FieldModifier": string fieldModifier = ReadAtom(reader, XamlLanguage.FieldModifier.Name); currentObject.Visibility = XamlBuildTaskServices.GetMemberVisibility(fieldModifier); directiveRecognized = true; break; case "Code": string codeSnippet = ReadAtom(reader, XamlLanguage.Code.Name); classData.CodeSnippets.Add(codeSnippet); directiveRecognized = true; break; case "Members": foreach (PropertyData property in ReadProperties(reader.ReadSubtree())) { classData.Properties.Add(property); } if (!classData.RequiresCompilationPass2) { foreach (PropertyData property in classData.Properties) { if (property.Type.IsUnknown) { classData.RequiresCompilationPass2 = true; break; } } } directiveRecognized = true; readNextNode = true; break; case "ClassAttributes": foreach (AttributeData attribute in ReadAttributesCollection(reader.ReadSubtree())) { classData.Attributes.Add(attribute); } directiveRecognized = true; readNextNode = true; break; } if (directiveRecognized == true && readNextNode == false) { reader.Read(); Fx.Assert(reader.NodeType == XamlNodeType.EndMember, "Current node should be a XamlEndmember"); } return directiveRecognized; }
ClassData getOrCreateClassData(MethodEvent mev) { String hash = mev.getHash(); if (!classData.ContainsKey(hash)) { ClassData c = new ClassData(); c.instanceObjectID = mev.InstanceObjectID; c.columnNumber = nextFreeColumn++; this.classData[hash] = c; } return (ClassData) this.classData[hash]; }
// Throws InvalidOperationException at DesignTime: Input XAML contains invalid constructs for generating a class. For example, unexpected content or unknown class or field modifiers. public ClassData ReadFromXaml(XamlNodeList nodes) { if (nodes == null) { throw FxTrace.Exception.ArgumentNull("nodeList"); } Stack<NamedObject> currentTypes = new Stack<NamedObject>(); XamlReader reader = nodes.GetReader(); XamlSchemaContext xsc = reader.SchemaContext; XamlNodeList strippedXamlNodes = new XamlNodeList(xsc); XamlWriter strippedXamlNodesWriter = strippedXamlNodes.Writer; ClassData result = new ClassData() { FileName = this.xamlFileName, IsPublic = this.DefaultClassIsPublic, RootNamespace = this.rootNamespace }; // We loop through the provided XAML; for each node, we do two things: // 1. If it's a directive that's relevant to x:Class, we extract the data. // 2. Unless it's a directive that's exclusively relevant to x:Class, we write it to strippedXamlNodes. // The result is two outputs: class data, and stripped XAML that can be used to initialize the // an instance of the class. bool readNextNode = false; while (readNextNode || reader.Read()) { bool stripNodeFromXaml = false; readNextNode = false; namespaceTable.ManageNamespace(reader); switch (reader.NodeType) { case XamlNodeType.StartObject: if (result.BaseType == null) { result.BaseType = reader.Type; } currentTypes.Push(new NamedObject() { Type = reader.Type, Visibility = DefaultFieldVisibility, }); break; case XamlNodeType.EndObject: currentTypes.Pop(); break; case XamlNodeType.StartMember: XamlMember member = reader.Member; if (member.IsDirective) { bool isRootElement = (currentTypes.Count == 1); stripNodeFromXaml = ProcessDirective(reader, result, currentTypes.Peek(), isRootElement, strippedXamlNodes, out readNextNode); } else { NamedObject currentType = currentTypes.Peek(); XamlType currentXamlType = currentType.Type; if (currentXamlType.IsUnknown) { result.RequiresCompilationPass2 = true; } } break; case XamlNodeType.EndMember: break; case XamlNodeType.Value: break; case XamlNodeType.NamespaceDeclaration: break; case XamlNodeType.None: break; case XamlNodeType.GetObject: //Push a dummy NamedObject so that it gets popped when you see the corresponding EndObject currentTypes.Push(new NamedObject()); break; default: Debug.Fail("Unrecognized XamlNodeType value" + reader.NodeType.ToString()); break; } if (!stripNodeFromXaml) { WritestrippedXamlNode(reader, strippedXamlNodesWriter); } } // ClassData.Name should be initialized to a non-null non-empty value if // the file contains x:Class. Throw an error if neither is found. if (result.Name == null) { string xClassDirectiveName = "{" + XamlLanguage.Class.PreferredXamlNamespace + "}" + XamlLanguage.Class.Name; throw FxTrace.Exception.AsError(LogInvalidOperationException(null, SR.TaskCannotProcessFileWithoutType(xClassDirectiveName))); } strippedXamlNodes.Writer.Close(); strippedXamlNodes = RewriteRootNode(strippedXamlNodes, result.Name, result.Namespace); result.EmbeddedResourceXaml = strippedXamlNodes; return result; }