/// <summary> /// Generates control fields /// </summary> /// <param name="source">The source.</param> /// <param name="classType">Type of the class.</param> /// <param name="method">The initialize method.</param> /// <param name="generateField">if set to <c>true</c> [generate field].</param> /// <returns></returns> public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod method, bool generateField) { CodeExpression fieldReference = new CodeThisReferenceExpression(); CodeComHelper.GenerateBrushField(method, fieldReference, source, Control.BackgroundProperty); CodeComHelper.GenerateBrushField(method, fieldReference, source, Control.BorderBrushProperty); CodeComHelper.GenerateThicknessField(method, fieldReference, source, Control.BorderThicknessProperty); CodeComHelper.GenerateThicknessField(method, fieldReference, source, Control.PaddingProperty); CodeComHelper.GenerateBrushField(method, fieldReference, source, Control.ForegroundProperty); CodeComHelper.GenerateField<bool>(method, fieldReference, source, UIRoot.IsTabNavigationEnabledProperty); CodeComHelper.GenerateColorField(method, fieldReference, source, UIRoot.MessageBoxOverlayProperty); CodeComHelper.GenerateTemplateStyleField(classType, method, fieldReference, source, FrameworkElement.StyleProperty); Control control = source as Control; if (!CodeComHelper.IsDefaultValue(source, Control.FontFamilyProperty) || !CodeComHelper.IsDefaultValue(source, Control.FontSizeProperty) || !CodeComHelper.IsDefaultValue(source, Control.FontStyleProperty) || !CodeComHelper.IsDefaultValue(source, Control.FontWeightProperty)) { FontGenerator.Instance.AddFont(control.FontFamily, control.FontSize, control.FontStyle, control.FontWeight, method); } CodeComHelper.GenerateFontFamilyField(method, fieldReference, source, Control.FontFamilyProperty); CodeComHelper.GenerateFieldDoubleToFloat(method, fieldReference, source, Control.FontSizeProperty); CodeComHelper.GenerateFontStyleField(method, fieldReference, source, Control.FontStyleProperty, Control.FontWeightProperty); return fieldReference; }
public void TypeReferenceExpressionTest () { StringBuilder sb = new StringBuilder(); using (StringWriter sw = new StringWriter (sb)) { CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression(); CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression(); parentField.TargetObject = thisRef; parentField.FieldName = "Parent"; CodeBinaryOperatorExpression expression = new CodeBinaryOperatorExpression( parentField, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null)); Assert.AreEqual ("(Not (Me.Parent) Is Nothing)", Generate (expression, sw), "#1"); sw.Close (); } sb = new StringBuilder(); using (StringWriter sw = new StringWriter (sb)) { CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression(); CodeFieldReferenceExpression parentField = new CodeFieldReferenceExpression(); parentField.TargetObject = thisRef; parentField.FieldName = "Parent"; CodeBinaryOperatorExpression expression = new CodeBinaryOperatorExpression( new CodePrimitiveExpression(null), CodeBinaryOperatorType.IdentityInequality, parentField); Assert.AreEqual ("(Not (Me.Parent) Is Nothing)", Generate (expression, sw), "#2"); sw.Close (); } }
public TypescriptThisReferenceExpression( CodeThisReferenceExpression codeExpression, CodeGeneratorOptions options) { _codeExpression = codeExpression; _options = options; System.Diagnostics.Debug.WriteLine("TypescriptThisReferenceExpression Created"); }
/// <summary> /// Generates control fields /// </summary> /// <param name="source">The source.</param> /// <param name="classType">Type of the class.</param> /// <param name="initMethod">The initialize method.</param> /// <param name="generateField">if set to <c>true</c> [generate field].</param> /// <returns></returns> public override CodeExpression Generate(DependencyObject source, CodeTypeDeclaration classType, CodeMemberMethod initMethod, bool generateField) { CodeExpression fieldReference = new CodeThisReferenceExpression(); CodeComHelper.GenerateTemplateStyleField(classType, initMethod, fieldReference, source, FrameworkElement.StyleProperty); return fieldReference; }
public override CodeExpression GetCodeExpression (BoundPropertyEntry entry, object parsedData, ExpressionBuilderContext context) { if (entry == null) throw new NullReferenceException (".NET emulation (entry == null)"); var ret = new CodeMethodInvokeExpression (); ret.Method = new CodeMethodReferenceExpression (new CodeTypeReferenceExpression (typeof (RouteValueExpressionBuilder)), "GetRouteValue"); var thisref = new CodeThisReferenceExpression (); CodeExpressionCollection parameters = ret.Parameters; parameters.Add (new CodePropertyReferenceExpression (thisref, "Page")); parameters.Add (new CodePrimitiveExpression (entry.Expression)); parameters.Add (new CodeTypeOfExpression (new CodeTypeReference (entry.DeclaringType))); parameters.Add (new CodePrimitiveExpression (entry.Name)); return ret; }
public override void ExplicitVisit(ColumnReferenceExpression node) { string columnName; if (node.MultiPartIdentifier.Count == 1) { columnName = node.MultiPartIdentifier[0].Value; } else { throw new NotImplementedException(node.AsText()); } cs.CodeExpression targetObject = new cs.CodeThisReferenceExpression(); this.lastExpression = new cs.CodeFieldReferenceExpression(targetObject, columnName); }
private void CreateConstructorBody(GMethod constructor, CodeConstructor con, string uName) { if (!type.IsRootType) { con.BaseConstructorArgs.Add( new CodeCastExpression(TypeReference("net.sf.jni4net.inj.INJEnv"), new CodePrimitiveExpression(null))); con.BaseConstructorArgs.Add(new CodePrimitiveExpression(0)); } var parameters = new CodeExpression[constructor.Parameters.Count + 1]; for (int p = 0; p < constructor.Parameters.Count; p++) { parameters[p + 1] = new CodeVariableReferenceExpression(constructor.ParameterNames[p]); } parameters[0] = new CodeThisReferenceExpression(); con.Statements.Add( new CodeMethodInvokeExpression(CurrentTypeEx, uName, parameters)); }
public static void GenerateConstructor(CodeTypeDeclaration classDecl) { CodeConstructor constructorMember = new CodeConstructor() ; constructorMember.Attributes = MemberAttributes.Public; CodeParameterDeclarationExpression parameter = new CodeParameterDeclarationExpression(new CodeTypeReference("IContext"), "context"); constructorMember.Parameters.Add(parameter); CodeThisReferenceExpression thisExp = new CodeThisReferenceExpression(); CodeFieldReferenceExpression ctxFieldExp = new CodeFieldReferenceExpression(thisExp, "context"); CodeArgumentReferenceExpression argExp = new CodeArgumentReferenceExpression("context"); CodeAssignStatement assignStatement = new CodeAssignStatement(ctxFieldExp, argExp); constructorMember.Statements.Add(assignStatement); classDecl.Members.Add(constructorMember); }
internal void AddBodyParameter(CodeConstructor constructor, IMethod request) { const string varName = "body"; if (!request.HasBody) { return; // No body parameter required. } CodeTypeReference bodyType = objectTypeProvider.GetBodyType(request); var thisRef = new CodeThisReferenceExpression(); // TBody body constructor.Parameters.Add(new CodeParameterDeclarationExpression(bodyType, varName)); // this.Body = body; var assign = new CodeAssignStatement(); assign.Left = new CodePropertyReferenceExpression(thisRef, BodyPropertyDecorator.BodyPropertyName); assign.Right = new CodeVariableReferenceExpression(varName); constructor.Statements.Add(assign); }
static CodeMemberProperty GetIndexer() { var indexer = new CodeMemberProperty(); indexer.Attributes = MemberAttributes.Public | MemberAttributes.Final; indexer.Name = "Item"; indexer.Type = new CodeTypeReference(typeof(object)); indexer.HasSet = true; indexer.HasGet = true; indexer.Parameters.Add(new CodeParameterDeclarationExpression(new CodeTypeReference(typeof(string)), "field")); //return RecordHelper.Get(this, field); //RecordHelper.Set(this, field, value); var helper = new CodeTypeReferenceExpression("RecordHelper"); var field = new CodeVariableReferenceExpression("field"); var _this = new CodeThisReferenceExpression(); var value = new CodeVariableReferenceExpression("value"); var g = new CodeMethodInvokeExpression(helper, "Get", _this, field); indexer.GetStatements.Add(new CodeMethodReturnStatement(g)); var s = new CodeMethodInvokeExpression(helper, "Set", _this, field, value); indexer.SetStatements.Add(s); return indexer; }
CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, HttpOperationBinding httpOper, XmlMembersMapping inputMembers, XmlTypeMapping outputMember) { CodeIdentifiers pids = new CodeIdentifiers (); CodeMemberMethod method = new CodeMemberMethod (); CodeMemberMethod methodBegin = new CodeMemberMethod (); CodeMemberMethod methodEnd = new CodeMemberMethod (); method.Attributes = MemberAttributes.Public; methodBegin.Attributes = MemberAttributes.Public; methodEnd.Attributes = MemberAttributes.Public; // Find unique names for temporary variables for (int n=0; n<inputMembers.Count; n++) pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]); string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult"); string varCallback = pids.AddUnique ("callback","callback"); string varAsyncState = pids.AddUnique ("asyncState","asyncState"); string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name),method); method.Name = Operation.Name; methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + Operation.Name),method); methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + Operation.Name),method); method.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.Parameters.Add (new CodeParameterDeclarationExpression (typeof (IAsyncResult),varAsyncResult)); CodeExpression[] paramArray = new CodeExpression [inputMembers.Count]; for (int n=0; n<inputMembers.Count; n++) { string ptype = GetSimpleType (inputMembers[n]); CodeParameterDeclarationExpression param = new CodeParameterDeclarationExpression (ptype, inputMembers[n].MemberName); param.Direction = FieldDirection.In; method.Parameters.Add (param); methodBegin.Parameters.Add (param); paramArray [n] = new CodeVariableReferenceExpression (param.Name); } bool isVoid = true; if (outputMember != null) { method.ReturnType = new CodeTypeReference (outputMember.TypeFullName); methodEnd.ReturnType = new CodeTypeReference (outputMember.TypeFullName); xmlExporter.AddMappingMetadata (method.ReturnTypeCustomAttributes, outputMember, ""); isVoid = false; } methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (AsyncCallback),varCallback)); methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object),varAsyncState)); methodBegin.ReturnType = new CodeTypeReference (typeof(IAsyncResult)); // Array of input parameters CodeArrayCreateExpression methodParams; if (paramArray.Length > 0) methodParams = new CodeArrayCreateExpression (typeof(object), paramArray); else methodParams = new CodeArrayCreateExpression (typeof(object), 0); // Generate method url CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodeExpression thisURlExp = new CodeFieldReferenceExpression (ethis, "Url"); CodePrimitiveExpression metUrl = new CodePrimitiveExpression (httpOper.Location); CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression (thisURlExp, CodeBinaryOperatorType.Add, metUrl); // Invoke call CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName); CodeMethodInvokeExpression inv; inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, expMethodLocation, methodParams); if (!isVoid) method.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (method.ReturnType, inv))); else method.Statements.Add (inv); // Begin Invoke Call CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback); CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState); inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, expMethodLocation, methodParams, expCallb, expAsyncs); methodBegin.Statements.Add (new CodeMethodReturnStatement (inv)); // End Invoke call CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult); inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr); if (!isVoid) methodEnd.Statements.Add (new CodeMethodReturnStatement (new CodeCastExpression (methodEnd.ReturnType, inv))); else methodEnd.Statements.Add (inv); // Attributes CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.HttpMethodAttribute"); att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetOutMimeFormatter ()))); att.Arguments.Add (new CodeAttributeArgument (new CodeTypeOfExpression(GetInMimeFormatter ()))); AddCustomAttribute (method, att, true); CodeTypeDeclaration.Members.Add (method); CodeTypeDeclaration.Members.Add (methodBegin); CodeTypeDeclaration.Members.Add (methodEnd); return method; }
CodeMemberMethod GenerateMethod (CodeIdentifiers memberIds, SoapOperationBinding soapOper, SoapBodyBinding bodyBinding, XmlMembersMapping inputMembers, XmlMembersMapping outputMembers) { CodeIdentifiers pids = new CodeIdentifiers (); CodeMemberMethod method = new CodeMemberMethod (); CodeMemberMethod methodBegin = new CodeMemberMethod (); CodeMemberMethod methodEnd = new CodeMemberMethod (); method.Attributes = MemberAttributes.Public | MemberAttributes.Final; methodBegin.Attributes = MemberAttributes.Public | MemberAttributes.Final; methodEnd.Attributes = MemberAttributes.Public | MemberAttributes.Final; SoapBindingStyle style = soapOper.Style != SoapBindingStyle.Default ? soapOper.Style : soapBinding.Style; // Find unique names for temporary variables for (int n=0; n<inputMembers.Count; n++) pids.AddUnique (inputMembers[n].MemberName, inputMembers[n]); if (outputMembers != null) for (int n=0; n<outputMembers.Count; n++) pids.AddUnique (outputMembers[n].MemberName, outputMembers[n]); string varAsyncResult = pids.AddUnique ("asyncResult","asyncResult"); string varResults = pids.AddUnique ("results","results"); string varCallback = pids.AddUnique ("callback","callback"); string varAsyncState = pids.AddUnique ("asyncState","asyncState"); string messageName = memberIds.AddUnique(CodeIdentifier.MakeValid(Operation.Name),method); method.Name = CodeIdentifier.MakeValid(Operation.Name); if (method.Name == ClassName) method.Name += "1"; methodBegin.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("Begin" + method.Name),method); methodEnd.Name = memberIds.AddUnique(CodeIdentifier.MakeValid("End" + method.Name),method); method.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.ReturnType = new CodeTypeReference (typeof(void)); methodEnd.Parameters.Add (new CodeParameterDeclarationExpression (typeof (IAsyncResult),varAsyncResult)); CodeExpression[] paramArray = new CodeExpression [inputMembers.Count]; CodeParameterDeclarationExpression[] outParams = new CodeParameterDeclarationExpression [outputMembers != null ? outputMembers.Count : 0]; for (int n=0; n<inputMembers.Count; n++) { CodeParameterDeclarationExpression param = GenerateParameter (inputMembers[n], FieldDirection.In); method.Parameters.Add (param); GenerateMemberAttributes (inputMembers, inputMembers[n], bodyBinding.Use, param); methodBegin.Parameters.Add (GenerateParameter (inputMembers[n], FieldDirection.In)); paramArray [n] = new CodeVariableReferenceExpression (param.Name); } if (outputMembers != null) { bool hasReturn = false; for (int n=0; n<outputMembers.Count; n++) { CodeParameterDeclarationExpression cpd = GenerateParameter (outputMembers[n], FieldDirection.Out); outParams [n] = cpd; bool found = false; foreach (CodeParameterDeclarationExpression ip in method.Parameters) { if (ip.Name == cpd.Name && ip.Type.BaseType == cpd.Type.BaseType) { ip.Direction = FieldDirection.Ref; methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out)); found = true; break; } } if (found) continue; if (!hasReturn) { hasReturn = true; method.ReturnType = cpd.Type; methodEnd.ReturnType = cpd.Type; GenerateReturnAttributes (outputMembers, outputMembers[n], bodyBinding.Use, method); outParams [n] = null; continue; } method.Parameters.Add (cpd); GenerateMemberAttributes (outputMembers, outputMembers[n], bodyBinding.Use, cpd); methodEnd.Parameters.Add (GenerateParameter (outputMembers[n], FieldDirection.Out)); } } methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (AsyncCallback),varCallback)); methodBegin.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object),varAsyncState)); methodBegin.ReturnType = new CodeTypeReference (typeof(IAsyncResult)); // Array of input parameters CodeArrayCreateExpression methodParams; if (paramArray.Length > 0) methodParams = new CodeArrayCreateExpression (typeof(object), paramArray); else methodParams = new CodeArrayCreateExpression (typeof(object), 0); // Assignment of output parameters CodeStatementCollection outAssign = new CodeStatementCollection (); CodeVariableReferenceExpression arrVar = new CodeVariableReferenceExpression (varResults); for (int n=0; n<outParams.Length; n++) { CodeExpression index = new CodePrimitiveExpression (n); if (outParams[n] == null) { CodeExpression res = new CodeCastExpression (method.ReturnType, new CodeArrayIndexerExpression (arrVar, index)); outAssign.Add (new CodeMethodReturnStatement (res)); } else { CodeExpression res = new CodeCastExpression (outParams[n].Type, new CodeArrayIndexerExpression (arrVar, index)); CodeExpression var = new CodeVariableReferenceExpression (outParams[n].Name); outAssign.Insert (0, new CodeAssignStatement (var, res)); } } if (Style == ServiceDescriptionImportStyle.Client) { // Invoke call CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodePrimitiveExpression varMsgName = new CodePrimitiveExpression (messageName); CodeMethodInvokeExpression inv; CodeVariableDeclarationStatement dec; inv = new CodeMethodInvokeExpression (ethis, "Invoke", varMsgName, methodParams); if (outputMembers != null && outputMembers.Count > 0) { dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv); method.Statements.Add (dec); method.Statements.AddRange (outAssign); } else method.Statements.Add (inv); // Begin Invoke Call CodeExpression expCallb = new CodeVariableReferenceExpression (varCallback); CodeExpression expAsyncs = new CodeVariableReferenceExpression (varAsyncState); inv = new CodeMethodInvokeExpression (ethis, "BeginInvoke", varMsgName, methodParams, expCallb, expAsyncs); methodBegin.Statements.Add (new CodeMethodReturnStatement (inv)); // End Invoke call CodeExpression varAsyncr = new CodeVariableReferenceExpression (varAsyncResult); inv = new CodeMethodInvokeExpression (ethis, "EndInvoke", varAsyncr); if (outputMembers != null && outputMembers.Count > 0) { dec = new CodeVariableDeclarationStatement (typeof(object[]), varResults, inv); methodEnd.Statements.Add (dec); methodEnd.Statements.AddRange (outAssign); } else methodEnd.Statements.Add (inv); } else { method.Attributes = MemberAttributes.Public | MemberAttributes.Abstract; } // Attributes ImportHeaders (method); CodeAttributeDeclaration att = new CodeAttributeDeclaration ("System.Web.Services.WebMethodAttribute"); if (messageName != method.Name) att.Arguments.Add (GetArg ("MessageName",messageName)); AddCustomAttribute (method, att, (Style == ServiceDescriptionImportStyle.Server)); if (style == SoapBindingStyle.Rpc) { att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapRpcMethodAttribute"); att.Arguments.Add (GetArg (soapOper.SoapAction)); if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName)); if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName)); att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace)); if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace)); if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true)); } else { if (outputMembers != null && (inputMembers.ElementName == "" && outputMembers.ElementName != "" || inputMembers.ElementName != "" && outputMembers.ElementName == "")) throw new InvalidOperationException ("Parameter style is not the same for the input message and output message"); att = new CodeAttributeDeclaration ("System.Web.Services.Protocols.SoapDocumentMethodAttribute"); att.Arguments.Add (GetArg (soapOper.SoapAction)); if (inputMembers.ElementName != "") { if (inputMembers.ElementName != method.Name) att.Arguments.Add (GetArg ("RequestElementName", inputMembers.ElementName)); if (outputMembers != null && outputMembers.ElementName != (method.Name + "Response")) att.Arguments.Add (GetArg ("ResponseElementName", outputMembers.ElementName)); att.Arguments.Add (GetArg ("RequestNamespace", inputMembers.Namespace)); if (outputMembers != null) att.Arguments.Add (GetArg ("ResponseNamespace", outputMembers.Namespace)); att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Wrapped")); } else att.Arguments.Add (GetEnumArg ("ParameterStyle", "System.Web.Services.Protocols.SoapParameterStyle", "Bare")); if (outputMembers == null) att.Arguments.Add (GetArg ("OneWay", true)); att.Arguments.Add (GetEnumArg ("Use", "System.Web.Services.Description.SoapBindingUse", bodyBinding.Use.ToString())); } AddCustomAttribute (method, att, true); CodeTypeDeclaration.Members.Add (method); if (Style == ServiceDescriptionImportStyle.Client) { CodeTypeDeclaration.Members.Add (methodBegin); CodeTypeDeclaration.Members.Add (methodEnd); } return method; }
internal void AddApplicationEvent(MarkupEventInfo mei) { // validate the event handler name per C# grammar for identifiers ValidateEventHandlerName(mei.eventName, mei.eventHandler); // this.FooEvent += new FooEventHandlerDelegate(this.OnFoo); CodeThisReferenceExpression ctre = new CodeThisReferenceExpression(); CodeStatement csEvent = AddCLREvent(_ccRoot, ctre, mei); Debug.Assert(_ccRoot == (_codeContexts.Peek() as CodeContextRoot)); _ccRoot.EnsureInitializeComponentFn.Statements.Add(csEvent); }
protected abstract void GenerateThisReferenceExpression (CodeThisReferenceExpression e);
internal void AddApplicationProperty(MemberInfo memberInfo, string attributeValue, int lineNumber) { Debug.Assert(_ccRoot == (_codeContexts.Peek() as CodeContextRoot)); Debug.Assert(_ccRoot.ElementType == null || (memberInfo.DeclaringType.IsAssignableFrom(_ccRoot.ElementType) && (memberInfo is PropertyInfo))); TypeConvertContext ctx = new TypeConvertContext(_parserContext, attributeValue); CodeExpression ceValue = GetPropertyValueExpression(ctx, typeof(Uri), null, attributeValue); CodeThisReferenceExpression ctreTag = new CodeThisReferenceExpression(); CodePropertyReferenceExpression cprePropSet = new CodePropertyReferenceExpression(ctreTag, memberInfo.Name); CodeStatement csPropSet = new CodeAssignStatement(cprePropSet, ceValue); AddLinePragma(csPropSet, lineNumber); _ccRoot.EnsureInitializeComponentFn.Statements.Add(csPropSet); }
public override object Visit(InvocationExpression invocationExpression, object data) { Expression target = invocationExpression.TargetObject; CodeExpression targetExpr; string methodName = null; if (target == null) { targetExpr = new CodeThisReferenceExpression(); } else if (target is FieldReferenceOrInvocationExpression) { FieldReferenceOrInvocationExpression fRef = (FieldReferenceOrInvocationExpression)target; targetExpr = (CodeExpression)fRef.TargetObject.AcceptVisitor(this, data); if (fRef.TargetObject is FieldReferenceOrInvocationExpression) { FieldReferenceOrInvocationExpression fRef2 = (FieldReferenceOrInvocationExpression)fRef.TargetObject; if (fRef2.FieldName != null && Char.IsUpper(fRef2.FieldName[0])) { // an exception is thrown if it doesn't end in an indentifier exception // for example for : this.MyObject.MyMethod() leads to an exception, which // is correct in this case ... I know this is really HACKY :) try { CodeExpression tExpr = ConvertToIdentifier(fRef2); if (tExpr != null) { targetExpr = tExpr; } } catch (Exception) {} } } methodName = fRef.FieldName; // HACK for : Microsoft.VisualBasic.ChrW(NUMBER) //Console.WriteLine(methodName); if (methodName == "ChrW") { //Console.WriteLine("Return CAST EXPRESSION" + GetExpressionList(invocationExpression.Parameters)[0]); return new CodeCastExpression("System.Char", GetExpressionList(invocationExpression.Parameters)[0]); } } else { targetExpr = (CodeExpression)target.AcceptVisitor(this, data); } return new CodeMethodInvokeExpression(targetExpr, methodName, GetExpressionList(invocationExpression.Parameters)); }
public override void ProcessDirective (string directiveName, IDictionary<string, string> arguments) { string name = arguments["name"]; string type = arguments["type"]; if (string.IsNullOrEmpty (name)) throw new DirectiveProcessorException ("Parameter directive has no name argument"); if (string.IsNullOrEmpty (type)) throw new DirectiveProcessorException ("Parameter directive has no type argument"); string fieldName = "_" + name + "Field"; var typeRef = new CodeTypeReference (type); var thisRef = new CodeThisReferenceExpression (); var fieldRef = new CodeFieldReferenceExpression (thisRef, fieldName); var property = new CodeMemberProperty () { Name = name, Attributes = MemberAttributes.Public | MemberAttributes.Final, HasGet = true, HasSet = false, Type = typeRef }; property.GetStatements.Add (new CodeMethodReturnStatement (fieldRef)); members.Add (new CodeMemberField (typeRef, fieldName)); members.Add (property); string acquiredName = "_" + name + "Acquired"; var valRef = new CodeVariableReferenceExpression ("data"); var namePrimitive = new CodePrimitiveExpression (name); var sessionRef = new CodePropertyReferenceExpression (thisRef, "Session"); var callContextTypeRefExpr = new CodeTypeReferenceExpression ("System.Runtime.Remoting.Messaging.CallContext"); var nullPrim = new CodePrimitiveExpression (null); var acquiredVariable = new CodeVariableDeclarationStatement (typeof (bool), acquiredName, new CodePrimitiveExpression (false)); var acquiredVariableRef = new CodeVariableReferenceExpression (acquiredVariable.Name); this.postStatements.Add (acquiredVariable); //checks the local called "data" can be cast and assigned to the field, and if successful, sets acquiredVariable to true var checkCastThenAssignVal = new CodeConditionStatement ( new CodeMethodInvokeExpression ( new CodeTypeOfExpression (typeRef), "IsAssignableFrom", new CodeMethodInvokeExpression (valRef, "GetType")), new CodeStatement[] { new CodeAssignStatement (fieldRef, new CodeCastExpression (typeRef, valRef)), new CodeAssignStatement (acquiredVariableRef, new CodePrimitiveExpression (true)), }, new CodeStatement[] { new CodeExpressionStatement (new CodeMethodInvokeExpression (thisRef, "Error", new CodePrimitiveExpression ("The type '" + type + "' of the parameter '" + name + "' did not match the type passed to the template"))), }); //tries to gets the value from the session var checkSession = new CodeConditionStatement ( new CodeBinaryOperatorExpression (NotNull (sessionRef), CodeBinaryOperatorType.BooleanAnd, new CodeMethodInvokeExpression (sessionRef, "ContainsKey", namePrimitive)), new CodeVariableDeclarationStatement (typeof (object), "data", new CodeIndexerExpression (sessionRef, namePrimitive)), checkCastThenAssignVal); this.postStatements.Add (checkSession); //if acquiredVariable is false, tries to gets the value from the host if (hostSpecific) { var hostRef = new CodePropertyReferenceExpression (thisRef, "Host"); var checkHost = new CodeConditionStatement ( BooleanAnd (IsFalse (acquiredVariableRef), NotNull (hostRef)), new CodeVariableDeclarationStatement (typeof (string), "data", new CodeMethodInvokeExpression (hostRef, "ResolveParameterValue", nullPrim, nullPrim, namePrimitive)), new CodeConditionStatement (NotNull (valRef), checkCastThenAssignVal)); this.postStatements.Add (checkHost); } //if acquiredVariable is false, tries to gets the value from the call context var checkCallContext = new CodeConditionStatement ( IsFalse (acquiredVariableRef), new CodeVariableDeclarationStatement (typeof (object), "data", new CodeMethodInvokeExpression (callContextTypeRefExpr, "LogicalGetData", namePrimitive)), new CodeConditionStatement (NotNull (valRef), checkCastThenAssignVal)); this.postStatements.Add (checkCallContext); }
/// <summary> /// Adds a property to the given type which raises PropertyChange Notifications when the property is set. /// </summary> /// <param name="type">The type to add property to.</param> /// <param name="propertyType">Type of the property.</param> /// <param name="propertyName">Name of the property.</param> /// <returns>Added property.</returns> protected CodeMemberProperty AddPropertyWithChangeNotification(CodeTypeDeclaration type, CodeTypeReference propertyType, string propertyName) { // Declare a private property to be the backing field string backingFieldName = string.Format(CultureInfo.InvariantCulture, "backing{0}", propertyName); type.AddField(propertyType, backingFieldName); CodeMemberProperty propertyWithChangeNotifications = new CodeMemberProperty() { Name = propertyName, Type = propertyType, Attributes = MemberAttributes.Public }; CodeThisReferenceExpression thisReference = new CodeThisReferenceExpression(); // this will hold the reference to the backing field CodeFieldReferenceExpression backingFieldReference = new CodeFieldReferenceExpression(thisReference, backingFieldName); // add a getter which returns the backing field propertyWithChangeNotifications.GetStatements.Add(new CodeMethodReturnStatement(backingFieldReference)); // add a statement which sets the value of the backing field CodeAssignStatement setStatement = new CodeAssignStatement(backingFieldReference, new CodeArgumentReferenceExpression("value")); // This will call the RaisePropertyChanged method passing in the propertyName CodeMethodInvokeExpression invokePropertyChangeNotifier = new CodeMethodInvokeExpression(thisReference, "RaisePropertyChanged", new CodeExpression[] { new CodePrimitiveExpression(propertyName) }); propertyWithChangeNotifications.SetStatements.Add(setStatement); propertyWithChangeNotifications.SetStatements.Add(invokePropertyChangeNotifier); type.Members.Add(propertyWithChangeNotifications); return propertyWithChangeNotifications; }
public override object Visit(InvocationExpression invocationExpression, object data) { Expression target = invocationExpression.TargetObject; CodeExpression targetExpr; string methodName = null; if (target == null) { targetExpr = new CodeThisReferenceExpression(); } else if (target is FieldReferenceExpression) { FieldReferenceExpression fRef = (FieldReferenceExpression)target; targetExpr = (CodeExpression)fRef.TargetObject.AcceptVisitor(this, data); if (fRef.TargetObject is FieldReferenceExpression) { FieldReferenceExpression fRef2 = (FieldReferenceExpression)fRef.TargetObject; if (fRef2.FieldName != null && Char.IsUpper(fRef2.FieldName[0])) { // an exception is thrown if it doesn't end in an indentifier exception // for example for : this.MyObject.MyMethod() leads to an exception, which // is correct in this case ... I know this is really HACKY :) try { targetExpr = ConvertToIdentifier(fRef2); } catch (Exception) {} } } methodName = fRef.FieldName; } else { targetExpr = (CodeExpression)target.AcceptVisitor(this, data); } return new CodeMethodInvokeExpression(targetExpr, methodName, GetExpressionList(invocationExpression.Parameters)); }
protected override void GenerateThisReferenceExpression (CodeThisReferenceExpression e) { }
QyotoCodeGenerator(QyotoForm form) { CodeCompileUnit unit = new CodeCompileUnit(); CodeNamespace nspace = new CodeNamespace(form.Namespace); nspace.Imports.Add(new CodeNamespaceImport("System")); nspace.Imports.Add(new CodeNamespaceImport("Qyoto")); unit.Namespaces.Add(nspace); CodeTypeDeclaration type = new CodeTypeDeclaration(form.ClassName); type.IsClass = true; type.IsPartial = true; type.TypeAttributes = TypeAttributes.Public; type.BaseTypes.Add(new CodeTypeReference(form.BaseTypeName)); nspace.Types.Add(type); m_SetupUiMethod = new CodeMemberMethod(); m_SetupUiMethod.Name = "SetupUi"; m_SetupUiMethod.Attributes = MemberAttributes.Family | MemberAttributes.Final; type.Members.Add(m_SetupUiMethod); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(new CodeBaseReferenceExpression(), "ObjectName"), new CodePrimitiveExpression(form.ClassName))); XmlDocument doc = new XmlDocument(); doc.Load(form.UiFile); XmlElement widgetNode = (XmlElement)doc.SelectSingleNode("/ui/widget"); ParseWidget(widgetNode, type, null, null); foreach (XmlElement node in doc.SelectNodes("/ui/connections/connection")) { string sender = node.SelectSingleNode("sender").InnerText; string signal = node.SelectSingleNode("signal").InnerText; string receiver = node.SelectSingleNode("receiver").InnerText; string slot = node.SelectSingleNode("slot").InnerText; CodeExpression senderExpression = null; if (sender == type.Name) senderExpression = new CodeThisReferenceExpression(); else senderExpression = new CodeVariableReferenceExpression(sender); CodeExpression receiverExpression = null; if (receiver == type.Name) receiverExpression = new CodeThisReferenceExpression(); else receiverExpression = new CodeVariableReferenceExpression(receiver); m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("QObject"), "Connect", senderExpression, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Qt"), "SIGNAL", new CodePrimitiveExpression(signal)), receiverExpression, new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("Qt"), "SLOT", new CodePrimitiveExpression(slot)))); } m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(new CodeTypeReferenceExpression("QMetaObject"), "ConnectSlotsByName", new CodeThisReferenceExpression())); foreach (var expr in m_SetBuddyExpressions) { m_SetupUiMethod.Statements.Add(expr); } using (TextWriter writer = new StreamWriter(form.GeneratedSourceCodeFile)) { CodeDomProvider provider = form.Project.LanguageBinding.GetCodeDomProvider(); provider.GenerateCodeFromCompileUnit(unit, writer, new CodeGeneratorOptions()); } }
void ParseWidget(XmlElement widgetNode, CodeTypeDeclaration formClass, CodeExpression parentWidgetReference, CodeExpression parentLayoutReference, XmlElement parentItemNode) { string widgetClass = widgetNode.GetAttribute("class"); string widgetName = widgetNode.GetAttribute("name"); CodeExpression widgetReference; if (parentWidgetReference == null) { widgetReference = new CodeThisReferenceExpression(); } else { if (widgetClass == "Line") widgetClass = "QFrame"; CodeMemberField widgetField = new CodeMemberField(widgetClass, widgetName); widgetField.Attributes = MemberAttributes.Family; formClass.Members.Add(widgetField); widgetReference = new CodeFieldReferenceExpression(new CodeThisReferenceExpression(), widgetName); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(widgetReference, new CodeObjectCreateExpression(widgetClass, parentWidgetReference))); m_SetupUiMethod.Statements.Add(new CodeAssignStatement(new CodePropertyReferenceExpression(widgetReference, "ObjectName"), new CodePrimitiveExpression(widgetName))); } ParseProperties(widgetNode, widgetReference, widgetReference); XmlElement layoutNode = (XmlElement)widgetNode.SelectSingleNode("layout"); if (layoutNode != null) { ParseLayout(layoutNode, formClass, widgetReference, null); } if (parentWidgetReference != null) { if (parentItemNode == null || parentItemNode.Attributes["row"] == null || parentItemNode.Attributes["column"] == null) { if (parentLayoutReference != null) { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayoutReference, "AddWidget", widgetReference)); } else { var parentWidgetNode = (XmlElement)widgetNode.ParentNode; if (GetClassName(parentWidgetNode) == "QTabWidget") { string tabLabel = widgetNode.SelectSingleNode("attribute[@name='title']/string").InnerText; m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentWidgetReference, "AddTab", widgetReference, new CodePrimitiveExpression(tabLabel))); } else if (GetClassName(parentWidgetNode) == "QScrollArea") { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentWidgetReference, "SetWidget", widgetReference)); } else { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentWidgetReference, "AddWidget", widgetReference)); } } } else { int row = Convert.ToInt32(parentItemNode.GetAttribute("row")); int column = Convert.ToInt32(parentItemNode.GetAttribute("column")); var parentLayoutNode = (XmlElement)parentItemNode.ParentNode; if (GetClassName(parentLayoutNode) == "QFormLayout") { var roleName = (column == 0) ? "LabelRole" : "FieldRole"; var roleExpression = new CodeFieldReferenceExpression(new CodeTypeReferenceExpression("QFormLayout.ItemRole"), roleName); m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayoutReference, "SetWidget", new CodePrimitiveExpression(row), roleExpression, widgetReference)); } else { var colSpan = parentItemNode.Attributes["colspan"] != null ? Convert.ToInt32(parentItemNode.GetAttribute("colspan")) : 1; var rowSpan = parentItemNode.Attributes["rowspan"] != null ? Convert.ToInt32(parentItemNode.GetAttribute("rowspan")) : 1; m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(parentLayoutReference, "AddWidget", widgetReference, new CodePrimitiveExpression(row), new CodePrimitiveExpression(column), new CodePrimitiveExpression(rowSpan), new CodePrimitiveExpression(colSpan))); } } } if (widgetClass == "QComboBox") { List<CodeExpression> itemTextExpressions = new List<CodeExpression>(); foreach (XmlElement itemElement in widgetNode.GetElementsByTagName("item")) { string text = itemElement.SelectSingleNode("property[@name='text']").InnerText; itemTextExpressions.Add(new CodePrimitiveExpression(text)); } if (itemTextExpressions.Count > 0) { m_SetupUiMethod.Statements.Add(new CodeMethodInvokeExpression(widgetReference, "InsertItems", new CodePrimitiveExpression(0), new CodeObjectCreateExpression(typeof (List<string>), new CodeArrayCreateExpression(typeof(string[]), itemTextExpressions.ToArray())))); } } foreach (XmlElement childWidgetNode in widgetNode.SelectNodes("widget")) { ParseWidget(childWidgetNode, formClass, widgetReference, null); } }
internal override CodeExpression BuildInvokeAsync (string messageName, CodeArrayCreateExpression paramsArray, CodeExpression delegateField, CodeExpression userStateVar) { HttpOperationBinding httpOper = OperationBinding.Extensions.Find (typeof (HttpOperationBinding)) as HttpOperationBinding; CodeThisReferenceExpression ethis = new CodeThisReferenceExpression(); CodeExpression thisURlExp = new CodeFieldReferenceExpression (ethis, "Url"); CodePrimitiveExpression metUrl = new CodePrimitiveExpression (httpOper.Location); CodeBinaryOperatorExpression expMethodLocation = new CodeBinaryOperatorExpression (thisURlExp, CodeBinaryOperatorType.Add, metUrl); CodeMethodInvokeExpression inv2 = new CodeMethodInvokeExpression (ethis, "InvokeAsync"); inv2.Parameters.Add (new CodePrimitiveExpression (messageName)); inv2.Parameters.Add (expMethodLocation); inv2.Parameters.Add (paramsArray); inv2.Parameters.Add (delegateField); inv2.Parameters.Add (userStateVar); return inv2; }
protected override void GenerateThisReferenceExpression(System.CodeDom.CodeThisReferenceExpression e) { Output.Write("self"); }
/// <summary> /// Generates the code to store the views in a C# or a VB file based on the /// options passed in by the user. /// </summary> /// <param name="mappingCollection"></param> /// <param name="generatedViews"></param> /// <param name="sourceWriter"></param> /// <param name="provider"></param> /// <returns></returns> private static void GenerateAndStoreViews(StorageMappingItemCollection mappingCollection, Dictionary<EntitySetBase, string> generatedViews, TextWriter sourceWriter, CodeDomProvider provider, IList<EdmSchemaError> schemaErrors) { EdmItemCollection edmCollection = mappingCollection.EdmItemCollection; StoreItemCollection storeCollection = mappingCollection.StoreItemCollection; //Create an emtpty compile unit and build up the generated code CodeCompileUnit compileUnit = new CodeCompileUnit(); //Add the namespace for generated code CodeNamespace codeNamespace = new CodeNamespace(EntityViewGenerationConstants.NamespaceName); //Add copyright notice to the namespace comment. compileUnit.Namespaces.Add(codeNamespace); foreach (var storageEntityContainerMapping in mappingCollection.GetItems<StorageEntityContainerMapping>()) { //Throw warning when containerMapping contains query view for bug 547285. if (HasQueryView(storageEntityContainerMapping)) { schemaErrors.Add(new EdmSchemaError( Strings.UnsupportedQueryViewInEntityContainerMapping(storageEntityContainerMapping.Identity), (int)StorageMappingErrorCode.UnsupportedQueryViewInEntityContainerMapping, EdmSchemaErrorSeverity.Warning)); continue; } #region Class Declaration string edmContainerName = storageEntityContainerMapping.EdmEntityContainer.Name; string storeContainerName = storageEntityContainerMapping.StorageEntityContainer.Name; string hashOverMappingClosure = MetadataMappingHasherVisitor.GetMappingClosureHash(edmCollection.EdmVersion, storageEntityContainerMapping); StringBuilder inputForTypeNameContent = new StringBuilder(hashOverMappingClosure); string viewStorageTypeName = EntityViewGenerationConstants.ViewGenerationTypeNamePrefix + StringHashBuilder.ComputeHash(MetadataHelper.CreateMetadataHashAlgorithm(edmCollection.EdmVersion), inputForTypeNameContent.ToString()).ToUpperInvariant(); //Add typeof expression to get the type that contains ViewGen type. This will help us in avoiding to go through //all the types in the assembly. I have also verified that this works with VB with a root namespace prepended to the //namespace since VB is picking up the type correctly as long as it is in the same assembly even with out the root namespace. CodeTypeOfExpression viewGenTypeOfExpression = new CodeTypeOfExpression(EntityViewGenerationConstants.NamespaceName + "." + viewStorageTypeName); //Add the assembly attribute that marks the assembly as the one that contains the generated views CodeAttributeDeclaration viewGenAttribute = new CodeAttributeDeclaration(EntityViewGenerationConstants.ViewGenerationCustomAttributeName); CodeAttributeArgument viewGenTypeArgument = new CodeAttributeArgument(viewGenTypeOfExpression); viewGenAttribute.Arguments.Add(viewGenTypeArgument); compileUnit.AssemblyCustomAttributes.Add(viewGenAttribute); //Add the type which will be the class that contains all the views in this assembly CodeTypeDeclaration viewStoringType = CreateTypeForStoringViews(viewStorageTypeName); //Add the constructor, this will be the only method that this type will contain //Create empty constructor. CodeConstructor viewStoringTypeConstructor = CreateConstructorForViewStoringType(); viewStoringType.Attributes = MemberAttributes.Public; //Get an expression that expresses this instance CodeThisReferenceExpression thisRef = new CodeThisReferenceExpression(); string viewHash = MetadataHelper.GenerateHashForAllExtentViewsContent(edmCollection.EdmVersion, GenerateDictionaryForEntitySetNameAndView(generatedViews)); CodeAssignStatement EdmEntityContainerNameStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.EdmEntityContainerName), new CodePrimitiveExpression(edmContainerName)); CodeAssignStatement StoreEntityContainerNameStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.StoreEntityContainerName), new CodePrimitiveExpression(storeContainerName)); CodeAssignStatement HashOverMappingClosureStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.HashOverMappingClosure), new CodePrimitiveExpression(hashOverMappingClosure)); CodeAssignStatement HashOverAllExtentViewsStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.HashOverAllExtentViews), new CodePrimitiveExpression(viewHash)); CodeAssignStatement ViewCountStatement = new CodeAssignStatement( new CodeFieldReferenceExpression(thisRef, EntityViewGenerationConstants.ViewCountPropertyName), new CodePrimitiveExpression(generatedViews.Count)); viewStoringTypeConstructor.Statements.Add(EdmEntityContainerNameStatement); viewStoringTypeConstructor.Statements.Add(StoreEntityContainerNameStatement); viewStoringTypeConstructor.Statements.Add(HashOverMappingClosureStatement); viewStoringTypeConstructor.Statements.Add(HashOverAllExtentViewsStatement); viewStoringTypeConstructor.Statements.Add(ViewCountStatement); //Add the constructor to the type viewStoringType.Members.Add(viewStoringTypeConstructor); //Add the method to store views to the type CreateAndAddGetViewAtMethod(viewStoringType, generatedViews); //Add the type to the namespace codeNamespace.Types.Add(viewStoringType); #endregion } if (codeNamespace.Types.Count > 0) { GenerateCode(sourceWriter, provider, compileUnit); sourceWriter.Flush(); } }
public override object VisitInvocationExpression(InvocationExpression invocationExpression, object data) { Expression target = invocationExpression.TargetObject; CodeExpression targetExpr; string methodName = null; if (target == null) { targetExpr = new CodeThisReferenceExpression(); } else if (target is MemberReferenceExpression) { MemberReferenceExpression fRef = (MemberReferenceExpression)target; targetExpr = null; if (fRef.TargetObject is MemberReferenceExpression) { if (IsPossibleTypeReference((MemberReferenceExpression)fRef.TargetObject)) { targetExpr = ConvertToTypeReference((MemberReferenceExpression)fRef.TargetObject); } } if (targetExpr == null) targetExpr = (CodeExpression)fRef.TargetObject.AcceptVisitor(this, data); methodName = fRef.MemberName; // HACK for : Microsoft.VisualBasic.ChrW(NUMBER) if (methodName == "ChrW") { return new CodeCastExpression("System.Char", GetExpressionList(invocationExpression.Arguments)[0]); } } else if (target is IdentifierExpression) { targetExpr = new CodeThisReferenceExpression(); methodName = ((IdentifierExpression)target).Identifier; } else { targetExpr = (CodeExpression)target.AcceptVisitor(this, data); } return new CodeMethodInvokeExpression(targetExpr, methodName, GetExpressionList(invocationExpression.Arguments)); }
protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e) { Output.Write("[CodeThisReferenceExpression]"); }
public void Visit (CodeThisReferenceExpression o) { g.GenerateThisReferenceExpression (o); }
/// <summary> /// Adds an implementation of the INotifyPropertyChanged interface to the given type. /// </summary> /// <param name="type">The type declaration</param> /// <returns>Type with INotifyPropertyChanged implemented.</returns> protected CodeTypeDeclaration ImplementINotifyPropertyChanged(CodeTypeDeclaration type) { //// This method will implement the INotifyPropertyChanged interface //// Here's an example : //// public class Customer :INotifyPropertyChanged { //// public PropertyChangedEventHandler PropertyChanged; //// public void RaisePropertyChanged(string propertyName) { //// if( this.PropertyChanged !=null ) { //// this.PropertyChanged (this, new PropertyChangedEventArgs( propertyName ) ); //// } //// } //// } CodeThisReferenceExpression thisReference = new CodeThisReferenceExpression(); CodeTypeReference notifyPropertyChanged = Code.TypeRef(typeof(INotifyPropertyChanged)); // Add the implements INotifyPropertyChanged statement // public class Customer :INotifyPropertyChanged { type.BaseTypes.Add(notifyPropertyChanged); // Add the PropertyChanged event as a field to the type // public PropertyChangedEventHandler PropertyChanged; CodeMemberEvent propertyChangedEvent = type.AddEvent(Code.TypeRef(typeof(PropertyChangedEventHandler)), "PropertyChanged"); propertyChangedEvent.ImplementationTypes.Add(notifyPropertyChanged); // this.PropertyChanged CodeEventReferenceExpression eventFieldReference = new CodeEventReferenceExpression(thisReference, "PropertyChanged"); // Add the RaisePropertyChanged Method which will invoke the PropertyChanged handler whenever a property value changes // if( this.PropertyChanged !=null ) CodeConditionStatement invokeEventHandlersIfAny = new CodeConditionStatement(new CodeBinaryOperatorExpression(eventFieldReference, CodeBinaryOperatorType.IdentityInequality, new CodePrimitiveExpression(null))); // this.PropertyChanged (this, new PropertyChangedEventArgs( propertyName ) ); invokeEventHandlersIfAny.TrueStatements.Add( new CodeDelegateInvokeExpression(eventFieldReference, new CodeExpression[] { thisReference, new CodeObjectCreateExpression("PropertyChangedEventArgs", new CodeArgumentReferenceExpression("propertyName")) })); // public void RaisePropertyChanged CodeMemberMethod method = type.AddMethod("RaisePropertyChanged", MemberAttributes.Public); method.Parameters.Add(new CodeParameterDeclarationExpression("System.String", "propertyName")); //// public void RaisePropertyChanged(string propertyName) { //// if( this.PropertyChanged !=null ) { //// this.PropertyChanged (this, new PropertyChangedEventArgs( propertyName ) ); //// } //// } method.Statements.Add(invokeEventHandlersIfAny); return type; }
protected override void GenerateThisReferenceExpression(CodeThisReferenceExpression e) { base.Output.Write("Me"); }
private void GenerateCodeFromThisReferenceExpression(CodeThisReferenceExpression e, TextWriter w, CodeGeneratorOptions o) { w.Write("$MainForm"); }
void GenerateEventBasedAsyncSupport (CodeTypeDeclaration type, OperationDescription od, CodeNamespace cns) { var method = FindByName (type, od.Name) ?? FindByName (type, "Begin" + od.Name); var endMethod = method.Name == od.Name ? null : FindByName (type, "End" + od.Name); bool methodAsync = method.Name.StartsWith ("Begin", StringComparison.Ordinal); var resultType = endMethod != null ? endMethod.ReturnType : method.ReturnType; var thisExpr = new CodeThisReferenceExpression (); var baseExpr = new CodeBaseReferenceExpression (); var nullExpr = new CodePrimitiveExpression (null); var asyncResultType = new CodeTypeReference (typeof (IAsyncResult)); // OnBeginXxx() implementation var cm = new CodeMemberMethod () { Name = "OnBegin" + od.Name, Attributes = MemberAttributes.Private | MemberAttributes.Final, ReturnType = asyncResultType }; type.Members.Add (cm); AddMethodParam (cm, typeof (object []), "args"); AddMethodParam (cm, typeof (AsyncCallback), "asyncCallback"); AddMethodParam (cm, typeof (object), "userState"); var call = new CodeMethodInvokeExpression ( thisExpr, "Begin" + od.Name); for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++) { var p = method.Parameters [idx]; cm.Statements.Add (new CodeVariableDeclarationStatement (p.Type, p.Name, new CodeCastExpression (p.Type, new CodeArrayIndexerExpression (new CodeArgumentReferenceExpression ("args"), new CodePrimitiveExpression (idx))))); call.Parameters.Add (new CodeVariableReferenceExpression (p.Name)); } call.Parameters.Add (new CodeArgumentReferenceExpression ("asyncCallback")); call.Parameters.Add (new CodeArgumentReferenceExpression ("userState")); cm.Statements.Add (new CodeMethodReturnStatement (call)); // OnEndXxx() implementation cm = new CodeMemberMethod () { Name = "OnEnd" + od.Name, Attributes = MemberAttributes.Private | MemberAttributes.Final, ReturnType = new CodeTypeReference (typeof (object [])) }; type.Members.Add (cm); AddMethodParam (cm, typeof (IAsyncResult), "result"); var outArgRefs = new List<CodeVariableReferenceExpression> (); for (int idx = 0; idx < method.Parameters.Count; idx++) { var p = method.Parameters [idx]; if (p.Direction != FieldDirection.In) { cm.Statements.Add (new CodeVariableDeclarationStatement (p.Type, p.Name)); outArgRefs.Add (new CodeVariableReferenceExpression (p.Name)); // FIXME: should this work? They need "out" or "ref" modifiers. } } call = new CodeMethodInvokeExpression ( thisExpr, "End" + od.Name, new CodeArgumentReferenceExpression ("result")); call.Parameters.AddRange (outArgRefs.Cast<CodeExpression> ().ToArray ()); // questionable var retCreate = new CodeArrayCreateExpression (typeof (object)); if (resultType.BaseType == "System.Void") cm.Statements.Add (call); else { cm.Statements.Add (new CodeVariableDeclarationStatement (typeof (object), "__ret", call)); retCreate.Initializers.Add (new CodeVariableReferenceExpression ("__ret")); } foreach (var outArgRef in outArgRefs) retCreate.Initializers.Add (new CodeVariableReferenceExpression (outArgRef.VariableName)); cm.Statements.Add (new CodeMethodReturnStatement (retCreate)); // OnXxxCompleted() implementation cm = new CodeMemberMethod () { Name = "On" + od.Name + "Completed", Attributes = MemberAttributes.Private | MemberAttributes.Final }; type.Members.Add (cm); AddMethodParam (cm, typeof (object), "state"); string argsname = identifiers.AddUnique (od.Name + "CompletedEventArgs", null); var iaargs = new CodeTypeReference ("InvokeAsyncCompletedEventArgs"); // avoid messy System.Type instance for generic nested type :| var iaref = new CodeVariableReferenceExpression ("args"); var methodEventArgs = new CodeObjectCreateExpression (new CodeTypeReference (argsname), new CodePropertyReferenceExpression (iaref, "Results"), new CodePropertyReferenceExpression (iaref, "Error"), new CodePropertyReferenceExpression (iaref, "Cancelled"), new CodePropertyReferenceExpression (iaref, "UserState")); cm.Statements.Add (new CodeConditionStatement ( new CodeBinaryOperatorExpression ( new CodeEventReferenceExpression (thisExpr, od.Name + "Completed"), CodeBinaryOperatorType.IdentityInequality, nullExpr), new CodeVariableDeclarationStatement (iaargs, "args", new CodeCastExpression (iaargs, new CodeArgumentReferenceExpression ("state"))), new CodeExpressionStatement (new CodeMethodInvokeExpression (thisExpr, od.Name + "Completed", thisExpr, methodEventArgs)))); // delegate fields type.Members.Add (new CodeMemberField (new CodeTypeReference ("BeginOperationDelegate"), "onBegin" + od.Name + "Delegate")); type.Members.Add (new CodeMemberField (new CodeTypeReference ("EndOperationDelegate"), "onEnd" + od.Name + "Delegate")); type.Members.Add (new CodeMemberField (new CodeTypeReference (typeof (SendOrPostCallback)), "on" + od.Name + "CompletedDelegate")); // XxxCompletedEventArgs class var argsType = new CodeTypeDeclaration (argsname); argsType.BaseTypes.Add (new CodeTypeReference (typeof (AsyncCompletedEventArgs))); cns.Types.Add (argsType); var argsCtor = new CodeConstructor () { Attributes = MemberAttributes.Public | MemberAttributes.Final }; argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object []), "results")); argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (Exception), "error")); argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (bool), "cancelled")); argsCtor.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "userState")); argsCtor.BaseConstructorArgs.Add (new CodeArgumentReferenceExpression ("error")); argsCtor.BaseConstructorArgs.Add (new CodeArgumentReferenceExpression ("cancelled")); argsCtor.BaseConstructorArgs.Add (new CodeArgumentReferenceExpression ("userState")); var resultsField = new CodeFieldReferenceExpression (thisExpr, "results"); argsCtor.Statements.Add (new CodeAssignStatement (resultsField, new CodeArgumentReferenceExpression ("results"))); argsType.Members.Add (argsCtor); argsType.Members.Add (new CodeMemberField (typeof (object []), "results")); if (resultType.BaseType != "System.Void") { var resultProp = new CodeMemberProperty { Name = "Result", Type = resultType, Attributes = MemberAttributes.Public | MemberAttributes.Final }; resultProp.GetStatements.Add (new CodeMethodReturnStatement (new CodeCastExpression (resultProp.Type, new CodeArrayIndexerExpression (resultsField, new CodePrimitiveExpression (0))))); argsType.Members.Add (resultProp); } // event field var handlerType = new CodeTypeReference (typeof (EventHandler<>)); handlerType.TypeArguments.Add (new CodeTypeReference (argsType.Name)); type.Members.Add (new CodeMemberEvent () { Name = od.Name + "Completed", Type = handlerType, Attributes = MemberAttributes.Public | MemberAttributes.Final }); // XxxAsync() implementations bool hasAsync = false; foreach (int __x in Enumerable.Range (0, 2)) { cm = new CodeMemberMethod (); type.Members.Add (cm); cm.Name = od.Name + "Async"; cm.Attributes = MemberAttributes.Public | MemberAttributes.Final; var inArgs = new List<CodeParameterDeclarationExpression > (); for (int idx = 0; idx < method.Parameters.Count - (methodAsync ? 2 : 0); idx++) { var pd = method.Parameters [idx]; inArgs.Add (pd); cm.Parameters.Add (pd); } // First one is overload without asyncState arg. if (!hasAsync) { call = new CodeMethodInvokeExpression (thisExpr, cm.Name, inArgs.ConvertAll<CodeExpression> (decl => new CodeArgumentReferenceExpression (decl.Name)).ToArray ()); call.Parameters.Add (nullExpr); cm.Statements.Add (new CodeExpressionStatement (call)); hasAsync = true; continue; } // Second one is the primary one. cm.Parameters.Add (new CodeParameterDeclarationExpression (typeof (object), "userState")); // if (onBeginBarOperDelegate == null) onBeginBarOperDelegate = new BeginOperationDelegate (OnBeginBarOper); // if (onEndBarOperDelegate == null) onEndBarOperDelegate = new EndOperationDelegate (OnEndBarOper); // if (onBarOperCompletedDelegate == null) onBarOperCompletedDelegate = new BeginOperationDelegate (OnBarOperCompleted); var beginOperDelegateRef = new CodeFieldReferenceExpression (thisExpr, "onBegin" + od.Name + "Delegate"); var endOperDelegateRef = new CodeFieldReferenceExpression (thisExpr, "onEnd" + od.Name + "Delegate"); var operCompletedDelegateRef = new CodeFieldReferenceExpression (thisExpr, "on" + od.Name + "CompletedDelegate"); var ifstmt = new CodeConditionStatement ( new CodeBinaryOperatorExpression (beginOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr), new CodeAssignStatement (beginOperDelegateRef, new CodeDelegateCreateExpression (new CodeTypeReference ("BeginOperationDelegate"), thisExpr, "OnBegin" + od.Name))); cm.Statements.Add (ifstmt); ifstmt = new CodeConditionStatement ( new CodeBinaryOperatorExpression (endOperDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr), new CodeAssignStatement (endOperDelegateRef, new CodeDelegateCreateExpression (new CodeTypeReference ("EndOperationDelegate"), thisExpr, "OnEnd" + od.Name))); cm.Statements.Add (ifstmt); ifstmt = new CodeConditionStatement ( new CodeBinaryOperatorExpression (operCompletedDelegateRef, CodeBinaryOperatorType.IdentityEquality, nullExpr), new CodeAssignStatement (operCompletedDelegateRef, new CodeDelegateCreateExpression (new CodeTypeReference (typeof (SendOrPostCallback)), thisExpr, "On" + od.Name + "Completed"))); cm.Statements.Add (ifstmt); // InvokeAsync (onBeginBarOperDelegate, inValues, onEndBarOperDelegate, onBarOperCompletedDelegate, userState); inArgs.Add (new CodeParameterDeclarationExpression (typeof (object), "userState")); var args = new List<CodeExpression> (); args.Add (beginOperDelegateRef); args.Add (new CodeArrayCreateExpression (typeof (object), inArgs.ConvertAll<CodeExpression> (decl => new CodeArgumentReferenceExpression (decl.Name)).ToArray ())); args.Add (endOperDelegateRef); args.Add (new CodeFieldReferenceExpression (thisExpr, "on" + od.Name + "CompletedDelegate")); args.Add (new CodeArgumentReferenceExpression ("userState")); call = new CodeMethodInvokeExpression (baseExpr, "InvokeAsync", args.ToArray ()); cm.Statements.Add (new CodeExpressionStatement (call)); } }