Beispiel #1
0
 public void Add(PropertyData propertyData)
 {
     var single = new SinglePropertyMapper();
     single.Add(propertyData);
     Properties.Add(propertyData, single);
     PropertyDatas.Add(propertyData.Name, propertyData);
 }
Beispiel #2
0
    public string CheckForWarning(PropertyData propertyData, InvokerTypes invokerType)
    {
        var propertyDefinition = propertyData.PropertyDefinition;
        var setMethod = propertyDefinition.SetMethod;

        if (setMethod.Name == "set_Item" && setMethod.Parameters.Count == 2 && setMethod.Parameters[1].Name == "value")
        {
            return "Property is an indexer.";
        }
        if (setMethod.Parameters.Count > 1)
        {
            return "Property takes more than one parameter.";
        }
        if (setMethod.IsAbstract)
        {
            return "Property is abstract.";
        }
        if ((propertyData.BackingFieldReference == null) && (propertyDefinition.GetMethod == null))
        {
            return "Property has no field set logic or it contains multiple sets and the names cannot be mapped to a property.";
        }
        if (invokerType == InvokerTypes.BeforeAfter && (propertyDefinition.GetMethod == null))
        {
            return "When using a before/after invoker the property have a 'get'.";
        }
        return null;
    }
 public PropertyWeaver(MsCoreReferenceFinder msCoreReferenceFinder, Logger logger, PropertyData propertyData, TypeNode typeNode)
 {
     this.msCoreReferenceFinder = msCoreReferenceFinder;
     this.logger = logger;
     this.propertyData = propertyData;
     this.typeNode = typeNode;
 }
Beispiel #4
0
        public void ToCode_given_CommentAndNameAndType_should_ReturnCode()
        {
            //	#	Arrange.
            var sut = new PropertyData
            {
                Comment = new CommentData("MyComment"),
                Scope = Common.VisibilityScope.Private,
                Name = "CustomerID",
                SystemType = typeof(int)
            };

            //	#	Act.
            var res = sut.ToCode();

            //	#	Assert.
            Assert.AreEqual(3, res.Count);
            CollectionAssert.AreEqual(
                new[]
                {
                    "/// <summary> MyComment",
                    "/// </summary>",
                    "private System.Int32 CustomerID{ get; set; }"
                },
                res.ToList());
        }
Beispiel #5
0
 public void Should_Return_False_For_PropertyInfo_Objects_With_Different_Names()
 {
     var type = new { Prop1 = 10, Prop2 = 20 }.GetType();
       var propData1 = new PropertyData(type.GetProperties()[0]);
       var propData2 = new PropertyData(type.GetProperties()[1]);
       Assert.IsFalse(propData1.Equals(propData2));
 }
 public PropertyWeaver(ModuleWeaver moduleWeaver, PropertyData propertyData, TypeNode typeNode, TypeSystem typeSystem )
 {
     this.moduleWeaver = moduleWeaver;
     this.propertyData = propertyData;
     this.typeNode = typeNode;
     this.typeSystem = typeSystem;
 }
        public void Add(PropertyData propertyData) {
            if (this.propertyData != null) {
                throw new AuditException("Only one property can be added!");
            }

            this.propertyData = propertyData;
        }
 public ToOneIdMapper(IIdMapper delegat, PropertyData propertyData, String referencedEntityName, bool nonInsertableFake)
 {
     this.delegat = delegat;
     this.propertyData = propertyData;
     this.referencedEntityName = referencedEntityName;
     this.nonInsertableFake = nonInsertableFake;
 }
 public OneToOneNotOwningMapper(String owningReferencePropertyName, String owningEntityName,
     PropertyData propertyData)
 {
     this.owningReferencePropertyName = owningReferencePropertyName;
     this.owningEntityName = owningEntityName;
     this.propertyData = propertyData;
 }
Beispiel #10
0
        /// <summary>
        /// Initializes a new instance of the <see cref="PropertyValue"/> class.
        /// </summary>
        /// <param name="propertyData">The property data.</param>
        /// <param name="name">The name of the property.</param>
        /// <param name="value">The value of the property.</param>
        /// <exception cref="ArgumentNullException">The <paramref name="propertyData"/> is <c>null</c>.</exception>
        /// <exception cref="ArgumentException">The <paramref name="name"/> is <c>null</c> or whitespace.</exception>
        public PropertyValue(PropertyData propertyData, string name, object value)
        {
            Argument.IsNotNull("propertyData", propertyData);
            Argument.IsNotNullOrWhitespace("name", name);

            PropertyData = propertyData;
            Name = name;
            Value = value;
        }
 public CommonCollectionMapperData(AuditEntitiesConfiguration verEntCfg, String versionsMiddleEntityName,
                                   PropertyData collectionReferencingPropertyData, MiddleIdData referencingIdData,
                                   IRelationQueryGenerator queryGenerator) {
     this._verEntCfg = verEntCfg;
     this._versionsMiddleEntityName = versionsMiddleEntityName;
     this._collectionReferencingPropertyData = collectionReferencingPropertyData;
     this._referencingIdData = referencingIdData;
     this._queryGenerator = queryGenerator;
 }
        public ICompositeMapperBuilder AddComponent(PropertyData propertyData, String componentClassName) {
            if (Properties[propertyData] != null) {
			    // This is needed for second pass to work properly in the components mapper
                return (ICompositeMapperBuilder) Properties[propertyData];
            }

            ComponentPropertyMapper componentMapperBuilder = new ComponentPropertyMapper(propertyData, componentClassName);
		    AddComposite(propertyData, componentMapperBuilder);

            return componentMapperBuilder;
        }
Beispiel #13
0
        public string Map(PageData pageData, PropertyData propertyData)
        {
            var propertyDate = propertyData as PropertyDate;
            if (propertyDate != null)
            {
                var d = propertyDate.Date;
                return d != default(DateTime) ? UnixTicks(d).ToString(CultureInfo.InvariantCulture) : (-1).ToString(CultureInfo.InvariantCulture);
            }

            return String.Empty;
        }
 protected override void HandleSetterAccessor(IInvocation invocation, PropertyData propertyData)
 {
     IPropertyDataInterceptor propertyInterceptor = _contentDataInterceptorHandler.GetPropertyInterceptor(propertyData.GetType());
     if (propertyInterceptor != null)
     {
         Type parameterType = invocation.Method.GetParameters()[0].ParameterType;
         propertyInterceptor.SetValue(propertyData, parameterType, invocation.Arguments[0]);
     }
     else
     {
         propertyData.Value = invocation.Arguments[0];
     }
 }
    public void IsIndexer()
    {
        var checker = new ModuleWeaver();
        var propertyDefinition = DefinitionFinder.FindType<IndexerClass>()
            .Properties
            .First();

        var propertyData = new PropertyData
        {
            PropertyDefinition = propertyDefinition,
        };
        var message = checker.CheckForWarning(propertyData, InvokerTypes.String);
        Approvals.Verify(message);
    }
 protected override void HandleGetterAccessor(IInvocation invocation, PropertyData propertyData)
 {
     IPropertyDataInterceptor propertyInterceptor = _contentDataInterceptorHandler.GetPropertyInterceptor(propertyData.GetType());
     if (propertyInterceptor != null)
     {
         invocation.ReturnValue = propertyInterceptor.GetValue(propertyData, invocation.Method.ReturnType);
     }
     else if ((propertyData.Value == null) && invocation.Method.ReturnType.IsValueType)
     {
         invocation.ReturnValue = Activator.CreateInstance(invocation.Method.ReturnType);
     }
     else
     {
         invocation.ReturnValue = propertyData.Value;
     }
 }
        private void AddControl(string propertyName, PropertyData propertyValue, Guid propertyTypeId, string headerText, string parameters) {
            var propertyType = Core.PropertyType.GetPropertyType(propertyTypeId);
            var editControl = propertyType.EditControl;

            var loadControl = (PropertyEditorBase)LoadControl(editControl);
            loadControl.PropertyName = propertyName;
            loadControl.PropertyLabel = headerText;
            
            if (propertyValue != null) {
                loadControl.PropertyValue = propertyValue;
            }

            if (!string.IsNullOrEmpty(parameters)) {
                loadControl.Parameters = parameters;
            }

            EditControls.Controls.Add(loadControl);
            _controls.Add(loadControl);
        }
Beispiel #18
0
        public void ToCode_given_NameAndType_should_ReturnCode()
        {
            //	#	Arrange.
            var sut = new PropertyData
            {
                Scope = Common.VisibilityScope.Public,
                Name = "MyName",
                SystemType = typeof(string)
            };

            //	#	Act.
            var res = sut.ToCode();

            //	#	Assert.
            Assert.AreEqual(1, res.Count);
            Assert.AreEqual(
                @"public System.String MyName{ get; set; }",
                res[0]);
        }
        public string Map(PageData pageData, PropertyData propertyData)
        {
            //http://tedgustaf.com/en/blog/2009/9/parse-an-episerver-xhtml-property-with-dynamic-content/

            // Create a Property control which will parse the XHTML value for us
            var ctrl = new PropertyLongStringControl { PropertyData = propertyData };

            // Set the PropertyData to the property we want to parse
            // Initialize the Property control
            ctrl.SetupControl();

            // Create a string writer...
            var sw = new StringWriter();

            // ...and an HtmlTextWriter using that string writer
            var htw = new HtmlTextWriter(sw);

            // Render the Property control to get the markup
            ctrl.RenderControl(htw);

            return string.Format("\"{0}\"", Utils.EscapeStringForJs(sw.ToString()));
        }
Beispiel #20
0
        /// <summary>
        /// Extract the properties for a type.
        /// </summary>
        /// <param name="context"></param>
        /// <param name="typeInfo"></param>
        /// <param name="type"></param>
        public void ExtractProperties(IExtractorCollector context, TypeData typeInfo, Type type)
        {
            //this should only get properties either directly on the type or ovverriden on the type. Properties of base classes should not be added
            PropertyInfo[] properties = type.GetProperties( BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static);
            foreach (PropertyInfo property in properties) {
                PropertyData propertyData = new PropertyData() {
                    Name = property.Name,
                    TypeName = property.PropertyType.AssemblyQualifiedName,
                };

                AccessType getAccessType = AccessType.None;
                AccessType setAccessType = AccessType.Private;
                MethodInfo getMethod = property.GetGetMethod(true);
                MethodInfo setMethod = property.GetSetMethod(true);
                MethodInfo anyAccessor = getMethod ?? setMethod;

                if (getMethod != null) {
                    if (getMethod.IsFamily)
                        getAccessType = AccessType.Protected;
                    else if (getMethod.IsPublic)
                        getAccessType = AccessType.Public;
                    else
                        getAccessType = AccessType.Private;
                }
                if (setMethod != null) {
                    if (setMethod.IsFamily)
                        setAccessType = AccessType.Protected;
                    else if (setMethod.IsPublic)
                        setAccessType = AccessType.Public;
                }

                propertyData.GetAccessType = getAccessType;
                propertyData.SetAccessType = setAccessType;
                propertyData.IsStatic = anyAccessor.IsStatic;
                propertyData.IsVirtual = anyAccessor.IsVirtual;
                propertyData.IsAbstract = anyAccessor.IsAbstract;
                context.AddProperty(typeInfo, propertyData);
            }
        }
    public string CheckForErrors(PropertyData propertyData, bool isBeforeAfter)
    {
        var propertyDefinition = propertyData.PropertyDefinition;
        if (propertyDefinition.SetMethod.Name == "set_Item" && propertyDefinition.SetMethod.Parameters.Count == 2 && propertyDefinition.SetMethod.Parameters[1].Name == "value")
        {
            return "Property is an indexer.";
        }
        if (propertyDefinition.SetMethod.IsAbstract)
        {
            return "Property is abstract.";
        }
        if (propertyData.CheckForEquality && (propertyData.BackingFieldReference == null) && (propertyDefinition.GetMethod == null))
        {
            return "When using CheckForEquality the property set must contain code that sets the backing field or have a property Get. Either the property contains no field set or it contains multiple sets and the names cannot be mapped to a property.";
        }
        if (isBeforeAfter && (propertyDefinition.GetMethod == null))
        {
            return "When using a before/after invoker the property have a 'get'.";
        }

        return null;
    }
Beispiel #22
0
        public ICompositeMapperBuilder AddComponent(PropertyData propertyData, string componentClassName)
        {
            if (Properties.ContainsKey(propertyData))
            {
                // This is needed for second pass to work properly in the components mapper
                return (ICompositeMapperBuilder) Properties[propertyData];
            }

            ICompositeMapperBuilder componentMapperBuilder;
            //todo: rk - not really reliable I think!
            if(componentClassName==null)
            {
                componentMapperBuilder = new DynamicComponentPropertyMapper(propertyData);
            }
            else
            {
                componentMapperBuilder = new ComponentPropertyMapper(propertyData, componentClassName);
            }

            AddComposite(propertyData, (IPropertyMapper) componentMapperBuilder);

            return componentMapperBuilder;
        }
 protected AbstractToOneMapper(PropertyData propertyData)
 {
     PropertyData = propertyData;
 }
Beispiel #24
0
        public SchemaMapping(Type type, SchemaNaming naming, Hashtable mapTypeToConverterClassName)
        {
            codeClassName = (string)mapTypeToConverterClassName[type];
            classType     = type;

            bool hasGenericEmbeddedObject = false;

            string baseClassName = ManagedNameAttribute.GetBaseClassName(type);

            className           = ManagedNameAttribute.GetMemberName(type);
            instrumentationType = InstrumentationClassAttribute.GetAttribute(type).InstrumentationType;

            classPath = naming.NamespaceName + ":" + className;

            if (null == baseClassName)
            {
                newClass = new ManagementClass(naming.NamespaceName, "", null);
                newClass.SystemProperties ["__CLASS"].Value = className;
            }
            else
            {
                ManagementClass baseClass = new ManagementClass(naming.NamespaceName + ":" + baseClassName);
                if (instrumentationType == InstrumentationType.Instance)
                {
                    bool baseAbstract = false;
                    try
                    {
                        QualifierData o = baseClass.Qualifiers["abstract"];
                        if (o.Value is bool)
                        {
                            baseAbstract = (bool)o.Value;
                        }
                    }
                    catch (ManagementException e)
                    {
                        if (e.ErrorCode != ManagementStatus.NotFound)
                        {
                            throw;
                        }
                    }
                    if (!baseAbstract)
                    {
                        throw new Exception(RC.GetString("CLASSINST_EXCEPT"));
                    }
                }

                newClass = baseClass.Derive(className);
            }


            // Create the converter class
            CodeWriter codeClass = code.AddChild("public class " + codeClassName + " : IWmiConverter");

            // Create code block for one line Members
            CodeWriter codeOneLineMembers = codeClass.AddChild(new CodeWriter());

            codeOneLineMembers.Line("static ManagementClass managementClass = new ManagementClass(@\"" + classPath + "\");");
            codeOneLineMembers.Line("static IntPtr classWbemObjectIP;");
            codeOneLineMembers.Line("static Guid iidIWbemObjectAccess = new Guid(\"49353C9A-516B-11D1-AEA6-00C04FB68820\");");
            codeOneLineMembers.Line("internal ManagementObject instance = managementClass.CreateInstance();");
            codeOneLineMembers.Line("object reflectionInfoTempObj = null ; ");
            codeOneLineMembers.Line("FieldInfo reflectionIWbemClassObjectField = null ; ");
            codeOneLineMembers.Line("IntPtr emptyWbemObject = IntPtr.Zero ; ");
            codeOneLineMembers.Line("IntPtr originalObject = IntPtr.Zero ; ");
            codeOneLineMembers.Line("bool toWmiCalled = false ; ");

            //
            // Reuters VSQFE#: 750	[marioh] see comments above
            // Used as a temporary pointer to the newly created instance that we create to avoid re-using the same
            // object causing unbound memory usage in IWbemClassObject implementation.
            codeOneLineMembers.Line("IntPtr theClone = IntPtr.Zero;");
            codeOneLineMembers.Line("public static ManagementObject emptyInstance = managementClass.CreateInstance();");

            //
            codeOneLineMembers.Line("public IntPtr instWbemObjectAccessIP;");

            // Create static constructor to initialize handles
            CodeWriter codeCCTOR = codeClass.AddChild("static " + codeClassName + "()");

            codeCCTOR.Line("classWbemObjectIP = (IntPtr)managementClass;");
            codeCCTOR.Line("IntPtr wbemObjectAccessIP;");
            codeCCTOR.Line("Marshal.QueryInterface(classWbemObjectIP, ref iidIWbemObjectAccess, out wbemObjectAccessIP);");
            codeCCTOR.Line("int cimType;");

            // Create constructor
            CodeWriter codeCTOR = codeClass.AddChild("public " + codeClassName + "()");

            codeCTOR.Line("IntPtr wbemObjectIP = (IntPtr)instance;");
            codeCTOR.Line("originalObject = (IntPtr)instance;");
            codeCTOR.Line("Marshal.QueryInterface(wbemObjectIP, ref iidIWbemObjectAccess, out instWbemObjectAccessIP);");

            //
            // Reuters VSQFE#: 750	[marioh]
            // In the CCTOR we set things up only once:
            //  1. We get the IWbemClassObjectFreeThreaded object '_wbemObject' from the ManagementObject instance
            //  2. We then get the actual IntPtr to the underlying WMI object
            //  3. Finally, the simple cast to IntPtr from the ManagementObject instance
            // These fields will be used later during the ToWMI call.
            codeCTOR.Line("FieldInfo tempField = instance.GetType().GetField ( \"_wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            codeCTOR.Line("if ( tempField == null )");
            codeCTOR.Line("{");
            codeCTOR.Line("   tempField = instance.GetType().GetField ( \"wbemObject\", BindingFlags.Instance | BindingFlags.NonPublic ) ;");
            codeCTOR.Line("}");

            codeCTOR.Line("reflectionInfoTempObj = tempField.GetValue (instance) ;");
            codeCTOR.Line("reflectionIWbemClassObjectField = reflectionInfoTempObj.GetType().GetField (\"pWbemClassObject\", BindingFlags.Instance | BindingFlags.NonPublic );");
            codeCTOR.Line("emptyWbemObject = (IntPtr) emptyInstance;");

            // Create destructor that will be called at process cleanup
            CodeWriter codeDTOR = codeClass.AddChild("~" + codeClassName + "()");

            codeDTOR.AddChild("if(instWbemObjectAccessIP != IntPtr.Zero)").Line("Marshal.Release(instWbemObjectAccessIP);");
            // [marioh] Make sure we release the initial instance so that we dont leak
            codeDTOR.Line("if ( toWmiCalled == true )");
            codeDTOR.Line("{");
            codeDTOR.Line("	Marshal.Release (originalObject);");
            codeDTOR.Line("}");


            // Create method to convert from managed code to WMI
            CodeWriter codeToWMI = codeClass.AddChild("public void ToWMI(object obj)");

            //
            // Reuters VSQFE#: 750	[marioh] see comments above
            // Ensure the release of the WbemObjectAccess interface pointer.
            codeToWMI.Line("toWmiCalled = true ;");
            codeToWMI.Line("if(instWbemObjectAccessIP != IntPtr.Zero)");
            codeToWMI.Line("{");
            codeToWMI.Line("    Marshal.Release(instWbemObjectAccessIP);");
            codeToWMI.Line("    instWbemObjectAccessIP = IntPtr.Zero;");
            codeToWMI.Line("}");

            codeToWMI.Line("if(theClone != IntPtr.Zero)");
            codeToWMI.Line("{");
            codeToWMI.Line("    Marshal.Release(theClone);");
            codeToWMI.Line("    theClone = IntPtr.Zero;");
            codeToWMI.Line("}");

            codeToWMI.Line("IWOA.Clone_f(12, emptyWbemObject, out theClone) ;");
            codeToWMI.Line("Marshal.QueryInterface(theClone, ref iidIWbemObjectAccess, out instWbemObjectAccessIP) ;");
            codeToWMI.Line("reflectionIWbemClassObjectField.SetValue ( reflectionInfoTempObj, theClone ) ;");

            codeToWMI.Line(String.Format("{0} instNET = ({0})obj;", type.FullName.Replace('+', '.')));             //

            // Explicit cast to IntPtr
            CodeWriter codeIntPtrCast = codeClass.AddChild("public static explicit operator IntPtr(" + codeClassName + " obj)");

            codeIntPtrCast.Line("return obj.instWbemObjectAccessIP;");

            // Add GetInstance
            codeOneLineMembers.Line("public ManagementObject GetInstance() {return instance;}");

            PropertyDataCollection props = newClass.Properties;

            // type specific info
            switch (instrumentationType)
            {
            case InstrumentationType.Event:
                break;

            case InstrumentationType.Instance:
                props.Add("ProcessId", CimType.String, false);
                props.Add("InstanceId", CimType.String, false);
                props["ProcessId"].Qualifiers.Add("key", true);
                props["InstanceId"].Qualifiers.Add("key", true);
                newClass.Qualifiers.Add("dynamic", true, false, false, false, true);
                newClass.Qualifiers.Add("provider", naming.DecoupledProviderInstanceName, false, false, false, true);
                break;

            case InstrumentationType.Abstract:
                newClass.Qualifiers.Add("abstract", true, false, false, false, true);
                break;

            default:
                break;
            }

            int  propCount    = 0;
            bool needsNullObj = false;

            foreach (MemberInfo field in type.GetMembers())
            {
                if (!(field is FieldInfo || field is PropertyInfo))
                {
                    continue;
                }

                if (field.GetCustomAttributes(typeof(IgnoreMemberAttribute), false).Length > 0)
                {
                    continue;
                }

                if (field is FieldInfo)
                {
                    FieldInfo fi = field as FieldInfo;

                    // We ignore statics
                    if (fi.IsStatic)
                    {
                        ThrowUnsupportedMember(field);
                    }
                }
                else if (field is PropertyInfo)
                {
                    PropertyInfo pi = field as PropertyInfo;
                    // We must have a 'get' property accessor
                    if (!pi.CanRead)
                    {
                        ThrowUnsupportedMember(field);
                    }

                    // We ignore static properties
                    MethodInfo mi = pi.GetGetMethod();
                    if (null == mi || mi.IsStatic)
                    {
                        ThrowUnsupportedMember(field);
                    }

                    // We don't support parameters on properties
                    if (mi.GetParameters().Length > 0)
                    {
                        ThrowUnsupportedMember(field);
                    }
                }

                String propName = ManagedNameAttribute.GetMemberName(field);


#if SUPPORTS_ALTERNATE_WMI_PROPERTY_TYPE
                Type t2 = ManagedTypeAttribute.GetManagedType(field);
#else
                Type t2;
                if (field is FieldInfo)
                {
                    t2 = (field as FieldInfo).FieldType;
                }
                else
                {
                    t2 = (field as PropertyInfo).PropertyType;
                }
#endif
                bool isArray = false;
                if (t2.IsArray)
                {
                    // We only support one dimensional arrays in this version
                    if (t2.GetArrayRank() != 1)
                    {
                        ThrowUnsupportedMember(field);
                    }

                    isArray = true;
                    t2      = t2.GetElementType();
                }

                string embeddedTypeName      = null;
                string embeddedConverterName = null;
                if (mapTypeToConverterClassName.Contains(t2))
                {
                    embeddedConverterName = (string)mapTypeToConverterClassName[t2];
                    embeddedTypeName      = ManagedNameAttribute.GetMemberName(t2);
                }

                bool isGenericEmbeddedObject = false;
                if (t2 == typeof(object))
                {
                    isGenericEmbeddedObject = true;
                    if (hasGenericEmbeddedObject == false)
                    {
                        hasGenericEmbeddedObject = true;
                        // Add map
                        codeOneLineMembers.Line("static Hashtable mapTypeToConverter = new Hashtable();");
                        foreach (DictionaryEntry entry in mapTypeToConverterClassName)
                        {
                            codeCCTOR.Line(String.Format("mapTypeToConverter[typeof({0})] = typeof({1});", ((Type)entry.Key).FullName.Replace('+', '.'), (string)entry.Value));                             //
                        }
                    }
                }

                string propFieldName   = "prop_" + (propCount);
                string handleFieldName = "handle_" + (propCount++);

                // Add handle for field, which is static accross all instances
                codeOneLineMembers.Line("static int " + handleFieldName + ";");
                codeCCTOR.Line(String.Format("IWOA.GetPropertyHandle_f27(27, wbemObjectAccessIP, \"{0}\", out cimType, out {1});", propName, handleFieldName));

                // Add PropertyData for field, which is specific to each instance
                codeOneLineMembers.Line("PropertyData " + propFieldName + ";");
                codeCTOR.Line(String.Format("{0} = instance.Properties[\"{1}\"];", propFieldName, propName));

                if (isGenericEmbeddedObject)
                {
                    CodeWriter codeNotNull = codeToWMI.AddChild(String.Format("if(instNET.{0} != null)", field.Name));
                    CodeWriter codeElse    = codeToWMI.AddChild("else");
                    codeElse.Line(String.Format("{0}.Value = null;", propFieldName));
                    if (isArray)
                    {
                        codeNotNull.Line(String.Format("int len = instNET.{0}.Length;", field.Name));
                        codeNotNull.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                        codeNotNull.Line("IWmiConverter[] embeddedConverters = new IWmiConverter[len];");

                        CodeWriter codeForLoop = codeNotNull.AddChild("for(int i=0;i<len;i++)");

                        CodeWriter codeFoundType = codeForLoop.AddChild(String.Format("if((instNET.{0}[i] != null) && mapTypeToConverter.Contains(instNET.{0}[i].GetType()))", field.Name));
                        codeFoundType.Line(String.Format("Type type = (Type)mapTypeToConverter[instNET.{0}[i].GetType()];", field.Name));
                        codeFoundType.Line("embeddedConverters[i] = (IWmiConverter)Activator.CreateInstance(type);");
                        codeFoundType.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
                        codeFoundType.Line("embeddedObjects[i] = embeddedConverters[i].GetInstance();");

                        codeForLoop.AddChild("else").Line(String.Format("embeddedObjects[i] = SafeAssign.GetManagementObject(instNET.{0}[i]);", field.Name));

                        codeNotNull.Line(String.Format("{0}.Value = embeddedObjects;", propFieldName));
                    }
                    else
                    {
                        CodeWriter codeFoundType = codeNotNull.AddChild(String.Format("if(mapTypeToConverter.Contains(instNET.{0}.GetType()))", field.Name));
                        codeFoundType.Line(String.Format("Type type = (Type)mapTypeToConverter[instNET.{0}.GetType()];", field.Name));
                        codeFoundType.Line("IWmiConverter converter = (IWmiConverter)Activator.CreateInstance(type);");
                        codeFoundType.Line(String.Format("converter.ToWMI(instNET.{0});", field.Name));
                        codeFoundType.Line(String.Format("{0}.Value = converter.GetInstance();", propFieldName));

                        codeNotNull.AddChild("else").Line(String.Format("{0}.Value = SafeAssign.GetInstance(instNET.{1});", propFieldName, field.Name));
                    }
                }
                else if (embeddedTypeName != null)
                {
                    // If this is an embedded struct, it cannot be null
                    CodeWriter codeNotNull;
                    if (t2.IsValueType)
                    {
                        codeNotNull = codeToWMI;
                    }
                    else
                    {
                        codeNotNull = codeToWMI.AddChild(String.Format("if(instNET.{0} != null)", field.Name));
                        CodeWriter codeElse = codeToWMI.AddChild("else");
                        codeElse.Line(String.Format("{0}.Value = null;", propFieldName));
                    }

                    if (isArray)
                    {
                        codeNotNull.Line(String.Format("int len = instNET.{0}.Length;", field.Name));
                        codeNotNull.Line("ManagementObject[] embeddedObjects = new ManagementObject[len];");
                        codeNotNull.Line(String.Format("{0}[] embeddedConverters = new {0}[len];", embeddedConverterName));

                        CodeWriter codeForLoop = codeNotNull.AddChild("for(int i=0;i<len;i++)");
                        codeForLoop.Line(String.Format("embeddedConverters[i] = new {0}();", embeddedConverterName));

                        // If this is a struct array, the elements are never null
                        if (t2.IsValueType)
                        {
                            codeForLoop.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
                        }
                        else
                        {
                            CodeWriter codeArrayElementNotNull = codeForLoop.AddChild(String.Format("if(instNET.{0}[i] != null)", field.Name));
                            codeArrayElementNotNull.Line(String.Format("embeddedConverters[i].ToWMI(instNET.{0}[i]);", field.Name));
                        }
                        codeForLoop.Line("embeddedObjects[i] = embeddedConverters[i].instance;");

                        codeNotNull.Line(String.Format("{0}.Value = embeddedObjects;", propFieldName));
                    }
                    else
                    {
                        // We cannot create an instance of 'embeddedConverterName' because it may be the
                        // same type as we are defining (in other words, a cyclic loop, such as class XXX
                        // having an instance of an XXX as a member).  To prevent an infinite loop of constructing
                        // converter classes, we create a 'lazy' variable that is initialized to NULL, and the first
                        // time it is used, we set it to a 'new embeddedConverterName'.
                        codeOneLineMembers.Line(String.Format("{0} lazy_embeddedConverter_{1} = null;", embeddedConverterName, propFieldName));
                        CodeWriter codeConverterProp = codeClass.AddChild(String.Format("{0} embeddedConverter_{1}", embeddedConverterName, propFieldName));
                        CodeWriter codeGet           = codeConverterProp.AddChild("get");
                        CodeWriter codeIf            = codeGet.AddChild(String.Format("if(null == lazy_embeddedConverter_{0})", propFieldName));
                        codeIf.Line(String.Format("lazy_embeddedConverter_{0} = new {1}();", propFieldName, embeddedConverterName));
                        codeGet.Line(String.Format("return lazy_embeddedConverter_{0};", propFieldName));

                        codeNotNull.Line(String.Format("embeddedConverter_{0}.ToWMI(instNET.{1});", propFieldName, field.Name));
                        codeNotNull.Line(String.Format("{0}.Value = embeddedConverter_{0}.instance;", propFieldName));
                    }
                }
                else if (!isArray)
                {
                    if (t2 == typeof(Byte) || t2 == typeof(SByte))
                    {
                        //
                        // [PS#128409, marioh] CS0206 Compile error occured when instrumentated types contains public properties of type SByte, Int16, and UInt16
                        // Properties can not be passed as ref and therefore we store the property value in a tmp local variable before calling WritePropertyValue.
                        //
                        codeToWMI.Line(String.Format("{0} instNET_{1} = instNET.{1} ;", t2, field.Name));
                        codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 1, ref instNET_{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(Int16) || t2 == typeof(UInt16) || t2 == typeof(Char))
                    {
                        //
                        // [PS#128409, marioh] CS0206 Compile error occured when instrumentated types contains public properties of type SByte, Int16, and UInt16
                        // Properties can not be passed as ref and therefore we store the property value in a tmp local variable before calling WritePropertyValue.
                        //
                        codeToWMI.Line(String.Format("{0} instNET_{1} = instNET.{1} ;", t2, field.Name));
                        codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref instNET_{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(UInt32) || t2 == typeof(Int32) || t2 == typeof(Single))
                    {
                        codeToWMI.Line(String.Format("IWOA.WriteDWORD_f31(31, instWbemObjectAccessIP, {0}, instNET.{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(UInt64) || t2 == typeof(Int64) || t2 == typeof(Double))
                    {
                        codeToWMI.Line(String.Format("IWOA.WriteQWORD_f33(33, instWbemObjectAccessIP, {0}, instNET.{1});", handleFieldName, field.Name));
                    }
                    else if (t2 == typeof(Boolean))
                    {
                        //

                        codeToWMI.Line(String.Format("if(instNET.{0})", field.Name));
                        codeToWMI.Line(String.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolTrue);", handleFieldName));
                        codeToWMI.Line("else");
                        codeToWMI.Line(String.Format("    IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 2, ref SafeAssign.boolFalse);", handleFieldName));
                    }
                    else if (t2 == typeof(String))
                    {
                        CodeWriter codeQuickString = codeToWMI.AddChild(String.Format("if(null != instNET.{0})", field.Name));
                        codeQuickString.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, (instNET.{1}.Length+1)*2, instNET.{1});", handleFieldName, field.Name));
                        //                        codeToWMI.AddChild("else").Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
                        codeToWMI.AddChild("else").Line(String.Format("IWOA.Put_f5(5, instWbemObjectAccessIP, \"{0}\", 0, ref nullObj, 8);", propName));
                        if (needsNullObj == false)
                        {
                            needsNullObj = true;

                            //


                            codeOneLineMembers.Line("object nullObj = DBNull.Value;");
                        }
                    }
                    else if (t2 == typeof(DateTime) || t2 == typeof(TimeSpan))
                    {
                        codeToWMI.Line(String.Format("IWOA.WritePropertyValue_f28(28, instWbemObjectAccessIP, {0}, 52, SafeAssign.WMITimeToString(instNET.{1}));", handleFieldName, field.Name));
                        //                        codeToWMI.Line(String.Format("{0}.Value = SafeAssign.DateTimeToString(instNET.{1});", propFieldName, field.Name));
                    }
                    else
                    {
                        codeToWMI.Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
                    }
                }
                else
                {
                    // We have an array type
                    if (t2 == typeof(DateTime) || t2 == typeof(TimeSpan))
                    {
                        codeToWMI.AddChild(String.Format("if(null == instNET.{0})", field.Name)).Line(String.Format("{0}.Value = null;", propFieldName));
                        codeToWMI.AddChild("else").Line(String.Format("{0}.Value = SafeAssign.WMITimeArrayToStringArray(instNET.{1});", propFieldName, field.Name));
                    }
                    else
                    {
                        // This handles arrays of all primative types
                        codeToWMI.Line(String.Format("{0}.Value = instNET.{1};", propFieldName, field.Name));
                    }
                }


                CimType cimtype = CimType.String;

                if (field.DeclaringType != type)
                {
                    continue;
                }


#if REQUIRES_EXPLICIT_DECLARATION_OF_INHERITED_PROPERTIES
                if (InheritedPropertyAttribute.GetAttribute(field) != null)
                {
                    continue;
                }
#else
                // See if this field already exists on the WMI class
                // In other words, is it inherited from a base class
                //



                bool propertyExists = true;
                try
                {
                    PropertyData prop = newClass.Properties[propName];
                    // HACK for



                    CimType cimType = prop.Type;

                    // Make sure that if the property exists, it is inherited
                    // If it is local, they probably named two properties with
                    // the same name
                    if (prop.IsLocal)
                    {
                        throw new ArgumentException(String.Format(RC.GetString("MEMBERCONFLILCT_EXCEPT"), field.Name), field.Name);
                    }
                }
                catch (ManagementException e)
                {
                    if (e.ErrorCode != ManagementStatus.NotFound)
                    {
                        throw;
                    }
                    else
                    {
                        propertyExists = false;
                    }
                }
                if (propertyExists)
                {
                    continue;
                }
#endif


                if (embeddedTypeName != null)
                {
                    cimtype = CimType.Object;
                }
                else if (isGenericEmbeddedObject)
                {
                    cimtype = CimType.Object;
                }
                else if (t2 == typeof(ManagementObject))
                {
                    cimtype = CimType.Object;
                }
                else if (t2 == typeof(SByte))
                {
                    cimtype = CimType.SInt8;
                }
                else if (t2 == typeof(Byte))
                {
                    cimtype = CimType.UInt8;
                }
                else if (t2 == typeof(Int16))
                {
                    cimtype = CimType.SInt16;
                }
                else if (t2 == typeof(UInt16))
                {
                    cimtype = CimType.UInt16;
                }
                else if (t2 == typeof(Int32))
                {
                    cimtype = CimType.SInt32;
                }
                else if (t2 == typeof(UInt32))
                {
                    cimtype = CimType.UInt32;
                }
                else if (t2 == typeof(Int64))
                {
                    cimtype = CimType.SInt64;
                }
                else if (t2 == typeof(UInt64))
                {
                    cimtype = CimType.UInt64;
                }
                else if (t2 == typeof(Single))
                {
                    cimtype = CimType.Real32;
                }
                else if (t2 == typeof(Double))
                {
                    cimtype = CimType.Real64;
                }
                else if (t2 == typeof(Boolean))
                {
                    cimtype = CimType.Boolean;
                }
                else if (t2 == typeof(String))
                {
                    cimtype = CimType.String;
                }
                else if (t2 == typeof(Char))
                {
                    cimtype = CimType.Char16;
                }
                else if (t2 == typeof(DateTime))
                {
                    cimtype = CimType.DateTime;
                }
                else if (t2 == typeof(TimeSpan))
                {
                    cimtype = CimType.DateTime;
                }
                else
                {
                    ThrowUnsupportedMember(field);
                }
                // HACK: The following line cause a strange System.InvalidProgramException when run through InstallUtil
                //				throw new Exception("Unsupported type for event member - " + t2.Name);


                //

#if SUPPORTS_WMI_DEFAULT_VAULES
                Object defaultValue = ManagedDefaultValueAttribute.GetManagedDefaultValue(field);

                //
                if (null == defaultValue)
                {
                    props.Add(propName, cimtype, false);
                }
                else
                {
                    props.Add(propName, defaultValue, cimtype);
                }
#else
                try
                {
                    props.Add(propName, cimtype, isArray);
                }
                catch (ManagementException e)
                {
                    ThrowUnsupportedMember(field, e);
                }
#endif

                // Must at 'interval' SubType on TimeSpans
                if (t2 == typeof(TimeSpan))
                {
                    PropertyData prop = props[propName];
                    prop.Qualifiers.Add("SubType", "interval", false, true, true, true);
                }

                if (embeddedTypeName != null)
                {
                    PropertyData prop = props[propName];
                    prop.Qualifiers["CIMTYPE"].Value = "object:" + embeddedTypeName;
                }
            }
            codeCCTOR.Line("Marshal.Release(wbemObjectAccessIP);");
            //            codeToWMI.Line("Console.WriteLine(instance.GetText(TextFormat.Mof));");
        }
Beispiel #25
0
 /// <summary>
 /// Validates that no duplicate property exists (dry run).
 /// </summary>
 /// <param name="propertyName">Name of the property.</param>
 /// <param name="propertyData">Corresponding property data.</param>
 private static void CheckNestedResourceInfoDuplicateNameForExistingDuplicationRecord(string propertyName, PropertyData propertyData)
 {
     if (propertyData.State == PropertyState.NavigationProperty &&
         propertyData.AssociationLinkUrl != null &&
         propertyData.NestedResourceInfo == null)
     {
         // Association link has been processed, and this is the corresponding navigation property.
     }
     else if (propertyData.State != PropertyState.AnnotationSeen)
     {
         throw new ODataException(
                   Strings.DuplicatePropertyNamesNotAllowed(
                       propertyName));
     }
 }
Beispiel #26
0
 public InTerm(string field, IEnumerable <T> values, DataType type, bool not, ICollection <SqlParameter> parameters, PropertyData property)
 {
     _field  = field;
     _not    = not;
     _values = type.EscapeList(values, property, parameters);
 }
Beispiel #27
0
        public void GetWriteILCode(PropertyData prop, BinaryStruct currentStruct, GroboIL il, GroboIL.Local binaryStruct, GroboIL.Local value, GroboIL.Local typeSize, GroboIL.Local buffer, GroboIL.Local offset, bool listValue)
        {
            var arr = il.DeclareLocal(prop.PropertyInfo.PropertyType);

            il.Ldloc(value);
            il.Call(prop.Getter);
            il.Stloc(arr);

            var exitLabel = il.DefineLabel("exit");

            BinaryStruct.WriteSizeChecker(il, buffer, offset, 5);
            BinaryStruct.WriteObjectNull(il, exitLabel, arr, buffer, offset, typeSize);

            var arrSize = il.DeclareLocal(typeof(byte[]));
            var len     = il.DeclareLocal(typeof(int));

            il.Ldloc(value);
            il.Call(prop.Getter);
            il.Call(typeof(ICollection).GetProperty("Count").GetMethod);
            il.Stloc(len);

            il.Ldloc(len);
            il.Call(writeBitConverterMethodInfo);
            il.Stloc(arrSize);

            il.Ldloc(buffer);
            il.Ldloc(offset);
            il.Ldloc(arrSize);
            il.Ldc_I4(0);
            il.Ldelem(typeof(byte));
            il.Stelem(typeof(byte));

            for (int i = 1; i < 4; i++)
            {
                il.Ldloc(buffer);
                il.Ldloc(offset);
                il.Ldc_I4(i);
                il.Add();
                il.Ldloc(arrSize);
                il.Ldc_I4(i);
                il.Ldelem(typeof(byte));
                il.Stelem(typeof(byte));
            }

            BinaryStruct.WriteOffsetAppend(il, offset, 4);


            il.Ldloc(len);
            il.Ldc_I4(0);
            il.Ceq();
            il.Brtrue(exitLabel);

            var typeKey   = prop.PropertyInfo.PropertyType.GetGenericArguments()[0];
            var typeValue = prop.PropertyInfo.PropertyType.GetGenericArguments()[1];

            var ivar             = il.DeclareLocal(typeof(int));
            var currentItemKey   = il.DeclareLocal(typeKey);
            var currentItemValue = il.DeclareLocal(typeValue);

            var point = il.DefineLabel("for_label");

            il.Ldc_I4(0);
            il.Stloc(ivar);

            var enumeratorMethod = prop.PropertyInfo.PropertyType.GetMethod("GetEnumerator");

            var enumerator = il.DeclareLocal(enumeratorMethod.ReturnType);

            var moveNext   = typeof(IEnumerator).GetMethod("MoveNext");
            var getCurrent = enumerator.Type.GetMethod("get_Current");

            var temp  = il.DeclareLocal(getCurrent.ReturnType);
            var exist = il.DeclareLocal(typeof(bool));

            il.Ldloc(arr);
            il.Call(enumeratorMethod, isVirtual: true);
            il.Stloc(enumerator);

            var keyGetter   = getCurrent.ReturnType.GetMethod("get_Key");
            var valueGetter = getCurrent.ReturnType.GetMethod("get_Value");

            il.MarkLabel(point);

            //body

            il.Ldloc(enumerator);
            il.Call(moveNext);
            il.Stloc(exist);

            il.Ldloc(enumerator);
            il.Call(getCurrent, enumerator.Type);
            il.Stloc(temp);

            il.Ldloca(temp);
            il.Call(keyGetter, typeof(int));
            il.Stloc(currentItemKey);

            if (typeof(IBasicType).IsAssignableFrom(prop.BinaryAttr.Type.GetGenericArguments()[0]))
            {
                IBasicType t = (IBasicType)Activator.CreateInstance(prop.BinaryAttr.Type.GetGenericArguments()[0]);
                t.GetWriteILCode(prop, currentStruct, il, binaryStruct, currentItemKey, typeSize, buffer, offset, true);
            }
            else
            {
                BinaryStruct.CompileWriter(currentStruct.CurrentStorage.GetTypeInfo(typeKey, currentStruct.Scheme), il, binaryStruct, currentItemKey, buffer, offset, typeSize);
            }

            il.Ldloca(temp);
            il.Call(valueGetter);
            il.Stloc(currentItemValue);

            if (typeof(IBasicType).IsAssignableFrom(prop.BinaryAttr.Type.GetGenericArguments()[1]))
            {
                IBasicType t = (IBasicType)Activator.CreateInstance(prop.BinaryAttr.Type.GetGenericArguments()[1]);
                t.GetWriteILCode(prop, currentStruct, il, binaryStruct, currentItemValue, typeSize, buffer, offset, true);
            }
            else
            {
                BinaryStruct.CompileWriter(currentStruct.CurrentStorage.GetTypeInfo(typeValue, currentStruct.Scheme), il, binaryStruct, currentItemValue, buffer, offset, typeSize);
            }
            //end body

            il.Ldc_I4(1);
            il.Ldloc(ivar);
            il.Add();
            il.Stloc(ivar);

            il.Ldloc(ivar);
            il.Ldloc(len);

            il.Clt(false);
            il.Brtrue(point);


            il.MarkLabel(exitLabel);
        }
        /// <summary>
        /// Validates the property using data annotations.
        /// </summary>
        /// <param name="propertyName">Name of the property.</param>
        /// <param name="value">The value to validate.</param>
        /// <param name="catelPropertyData">The catel property data. Can be <c>null</c> for non-Catel properties.</param>
        /// <returns><c>true</c> if no errors using data annotations are found; otherwise <c>false</c>.</returns>
        private bool ValidatePropertyUsingAnnotations(string propertyName, object value, PropertyData catelPropertyData)
        {
            if (SuspendValidation)
            {
                _propertiesNotCheckedDuringDisabledValidation.Add(propertyName);
                return true;
            }

#if !WINDOWS_PHONE && !NETFX_CORE && !PCL && !NET35
            var type = GetType();

            try
            {
                if (!_propertyValuesIgnoredOrFailedForValidation[type].Contains(propertyName))
                {
                    if (catelPropertyData != null)
                    {
                        var propertyInfo = catelPropertyData.GetPropertyInfo(type);
                        if (propertyInfo == null || !propertyInfo.HasPublicGetter)
                        {
                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return false;
                        }
                    }
                    else
                    {
#if NET
                        if (type.GetPropertyEx(propertyName) == null)
                        {
                            Log.Debug("Property '{0}' cannot be found via reflection, ignoring this property for type '{1}'", propertyName, type.FullName);

                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return false;
                        }
#else
                        // Checking via reflection is faster than catching the exception
                        if (!Reflection.PropertyHelper.IsPublicProperty(this, propertyName))
                        {
                            Log.Debug("Property '{0}' is not a public property, cannot validate non-public properties in silverlight", propertyName);

                            _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);
                            return false;
                        }
#endif
                    }

                    if (!_dataAnnotationsValidationContext.ContainsKey(propertyName))
                    {
                        _dataAnnotationsValidationContext[propertyName] = new System.ComponentModel.DataAnnotations.ValidationContext(this, null, null) { MemberName = propertyName };
                    }

                    System.ComponentModel.DataAnnotations.Validator.ValidateProperty(value, _dataAnnotationsValidationContext[propertyName]);

                    // If succeeded, clear any previous error
                    if (_dataAnnotationValidationResults.ContainsKey(propertyName))
                    {
                        _dataAnnotationValidationResults[propertyName] = null;
                    }
                }
            }
            catch (System.ComponentModel.DataAnnotations.ValidationException validationException)
            {
                _dataAnnotationValidationResults[propertyName] = validationException.Message;
                return false;
            }
            catch (Exception ex)
            {
                _propertyValuesIgnoredOrFailedForValidation[type].Add(propertyName);

                Log.Warning(ex, "Failed to validate property '{0}' via Validator (property does not exists?)", propertyName);
            }
#endif

            return true;
        }
Beispiel #29
0
        static void Main(string[] args)
        {
            Console.SetWindowSize(Console.LargestWindowWidth - 5, Console.LargestWindowHeight - 1);
            PropertyDataCollection properties = null;

            System.Management.ManagementObjectSearcher   mox = null;
            System.Management.ManagementObjectCollection mok = null;
            int repeatTimes = 0;

            try
            {
                //define scope (namespace)
                System.Management.ManagementScope x = new System.Management.ManagementScope("root\\WMI");

                //define query
                System.Management.SelectQuery q = new System.Management.SelectQuery("WMIACPI_IO");

                //output current brightness
                mox = new System.Management.ManagementObjectSearcher(x, q);

                mok = mox.Get();
                while (true)
                {
                    using (ManagementObjectCollection.ManagementObjectEnumerator enumerator = mox.Get().GetEnumerator())
                    {
                        if (enumerator.MoveNext())
                        {
                            ManagementObject managementObject = (ManagementObject)enumerator.Current;

                            ConsoleKeyInfo ckey = Console.ReadKey();
                            if (ckey.Key == ConsoleKey.C)
                            {
                                break;
                            }
                            if (ckey.Key == ConsoleKey.F)
                            {
                                managementObject.SetPropertyValue("Active", false);
                            }
                            else
                            {
                                if (ckey.Key == ConsoleKey.T)
                                {
                                    managementObject.SetPropertyValue("Active", true);
                                }
                                else
                                {
                                    Console.WriteLine((bool)managementObject["Active"]);
                                }
                            }
                            managementObject.Put();
                        }
                    }
                }

                while (true)
                {
                    System.Threading.Thread.Sleep(200);
                    mok = mox.Get();


                    foreach (System.Management.ManagementObject o in mok)
                    {
                        properties = o.Properties;
                        //o.InvokeMethod("WmiSetBrightness", new Object[] { UInt32.MaxValue, targetBrightness }); //note the reversed order - won't work otherwise!
                        break; //only work on the first object
                    }

                    //Console.WriteLine(properties["IOBytes"].Value);
                    PropertyData ioBytes = properties["IOBytes"];
                    byte[]       bytes   = ioBytes.Value as byte[];
                    //bytes[83] = 100;
                    //lastBytes = bytes;
                    //((byte[])ioBytes.Value)[83] = 4;
                    //((byte[])ioBytes.Value)[84] = 100;
                    int place = -1;
                    if (!isTheSame(bytes, out place))
                    {
                        if (++repeatTimes >= 10)
                        {
                            repeatTimes = 0;
                            Console.Clear();
                        }
                        string message =
                            "PLACE: " + place + "\r\n"
                            + BitConverter.ToString(bytes);

                        Console.WriteLine(message);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
                Console.WriteLine(ex.Message);
                Console.WriteLine(ex.Source);
            }
            finally
            {
                if (mox != null)
                {
                    mox.Dispose();
                }
                if (mok != null)
                {
                    mok.Dispose();
                }
            }
        }
Beispiel #30
0
        /// <summary>
        /// Gets the dotnet type of a given PropertyData
        /// </summary>
        /// <param name="pData">PropertyData input.</param>
        /// <returns>A string representing dotnet type.</returns>
        protected static Type GetDotNetType(PropertyData pData)
        {
            Diagnostics.Assert(pData != null,
                               "Input PropertyData should not be null");

            tracer.WriteLine("Getting DotNet Type for CimType : {0}", pData.Type);

            string retValue;

            switch (pData.Type)
            {
            case CimType.SInt8:
                retValue = typeof(System.SByte).FullName;
                break;

            case CimType.UInt8:
                retValue = typeof(System.Byte).FullName;
                break;

            case CimType.SInt16:
                retValue = typeof(System.Int16).FullName;
                break;

            case CimType.UInt16:
                retValue = typeof(System.UInt16).FullName;
                break;

            case CimType.SInt32:
                retValue = typeof(System.Int32).FullName;
                break;

            case CimType.UInt32:
                retValue = typeof(System.UInt32).FullName;
                break;

            case CimType.SInt64:
                retValue = typeof(System.Int64).FullName;
                break;

            case CimType.UInt64:
                retValue = typeof(System.UInt64).FullName;
                break;

            case CimType.Real32:
                retValue = typeof(System.Single).FullName;
                break;

            case CimType.Real64:
                retValue = typeof(double).FullName;
                break;

            case CimType.Boolean:
                retValue = typeof(bool).FullName;
                break;

            case CimType.String:
                retValue = typeof(string).FullName;
                break;

            case CimType.DateTime:
                // this is actually a string
                retValue = typeof(string).FullName;
                break;

            case CimType.Reference:
                // this is actually a string
                retValue = typeof(string).FullName;
                break;

            case CimType.Char16:
                retValue = typeof(char).FullName;
                break;

            case CimType.Object:
            default:
                retValue = typeof(object).FullName;
                break;
            }

            if (pData.IsArray)
            {
                retValue += "[]";
            }

            return(Type.GetType(retValue));
        }
Beispiel #31
0
        /// <summary>
        /// Returns the value from a property coming from a previous call to DoGetProperty
        /// </summary>
        /// <param name="property">PSProperty coming from a previous call to DoGetProperty</param>
        /// <returns>The value of the property</returns>
        protected override object PropertyGet(PSProperty property)
        {
            PropertyData pd = property.adapterData as PropertyData;

            return(pd.Value);
        }
Beispiel #32
0
        private void GetValueParsed(Dictionary <string, Object> propsOut, String propName, PropertyData prop, String parser)
        {
            if (prop.Value != null)
            {
                Log.WriteLog(String.Format("Parsing: {0}, propValue: {1}, of CimType: {2}, Parsing Rule: {3}", propName, prop.Value.ToString(), prop.Type.ToString(), parser), Log.LogLevel.VERBOSE);
                switch (prop.Type)
                {
                case CimType.Boolean:
                    propsOut.Add(propName, prop.Value.ToString());
                    break;

                case CimType.DateTime:
                    try
                    {
                        DateTime dateToParse = DateTime.ParseExact(prop.Value.ToString(), "yyyyMMddHHmmss.ffffff-000", System.Globalization.CultureInfo.InvariantCulture);
                        propsOut.Add(propName, (long)(dateToParse - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds);
                    }
                    catch (FormatException fe)
                    {
                        Log.WriteLog(String.Format("Could not parse: {0}, propValue: {1}, of CimType: {2}", propName, prop.Value.ToString(), prop.Type.ToString()), Log.LogLevel.VERBOSE);
                        Log.WriteLog("Parsing Exception: " + fe.ToString(), Log.LogLevel.VERBOSE);
                    }
                    break;

                case CimType.String:
                    string propStr;
                    if (prop.IsArray)
                    {
                        propStr = String.Join(", ", (String[])prop.Value);
                    }
                    else
                    {
                        propStr = (String)prop.Value;
                    }

                    if (propStr.Length > 0)
                    {
                        if (!String.IsNullOrEmpty(parser))
                        {
                            Regex regex = new Regex(parser);
                            Match match = regex.Match(propStr);
                            if (match.Success)
                            {
                                var matchStr = "";
                                if (match.Groups.Count > 1)
                                {
                                    foreach (int groupNum in regex.GetGroupNumbers().Skip(1))
                                    {
                                        if (String.IsNullOrEmpty(matchStr))
                                        {
                                            matchStr = match.Groups[groupNum].Value;
                                        }
                                        else
                                        {
                                            matchStr += " " + match.Groups[groupNum].Value;
                                        }
                                    }
                                }
                                else
                                {
                                    matchStr = match.Value;
                                }
                                Log.WriteLog(String.Format("Regex matched - value parsed from {0} to {1}", propStr, matchStr), Log.LogLevel.VERBOSE);
                                propStr = matchStr;
                            }
                        }
                        propsOut.Add(propName, propStr);
                    }
                    break;

                default:
                    if (prop.IsArray)
                    {
                        var outStr = "";
                        foreach (object propItem in (Array)prop.Value)
                        {
                            if (String.IsNullOrEmpty(outStr))
                            {
                                outStr = propItem.ToString();
                            }
                            else
                            {
                                outStr += ", " + propItem.ToString();
                            }
                        }
                        propsOut.Add(propName, outStr);
                    }
                    else
                    {
                        propsOut.Add(propName, prop.Value);
                    }
                    break;
                }
            }
        }
Beispiel #33
0
        /*
         *  Game plan:
         *  1. Find the Level category
         *  2. Find the link with the Property SceneComponent
         *  3. Dig into the vanilla pak and the mod pak, try to find the connecting actor, add its nodes in the SimpleConstructionScript under BlueprintCreatedComponents (garbage1 = 0 no problem)
         *  4. Create the SceneComponent (garbage1 = 0), no RelativeLocation or UCSModifiedProperties, CreationMethod = EComponentCreationMethod::SimpleConstructionScript, bNetAddressable = 1
         *  5. Create the new Actor_C category, set its Linkage to the Level category, set the garbage1 to 0 (maybe random number idk), DefaultSceneRoot & RootComponent = the matching SceneComponent
         */

        public MemoryStream Bake(string[] newComponents, string[] newTrailheads, byte[] superRawData)
        {
            BinaryReader yReader = new BinaryReader(new MemoryStream(superRawData));
            AssetWriter  y       = new AssetWriter
            {
                WillStoreOriginalCopyInMemory = true, WillWriteSectionSix = true, data = new AssetReader()
            };

            y.data.Read(yReader);
            y.OriginalCopy = superRawData;

            // Missions
            if (newTrailheads.Length > 0)
            {
                for (int cat = 0; cat < y.data.categories.Count; cat++)
                {
                    if (y.data.categories[cat] is NormalCategory normalCat)
                    {
                        if (y.data.GetHeaderReference(y.data.GetLinkReference(normalCat.ReferenceData.connection)) != "AstroSettings")
                        {
                            continue;
                        }

                        for (int i = 0; i < normalCat.Data.Count; i++)
                        {
                            if (normalCat.Data[i].Name == "MissionData" && normalCat.Data[i] is ArrayPropertyData arrDat && arrDat.ArrayType == "ObjectProperty")
                            {
                                y.data.AddHeaderReference("AstroMissionDataAsset");

                                PropertyData[] usArrData = arrDat.Value;
                                int            oldLen    = usArrData.Length;
                                Array.Resize(ref usArrData, usArrData.Length + newTrailheads.Length);
                                for (int j = 0; j < newTrailheads.Length; j++)
                                {
                                    string realName      = newTrailheads[j];
                                    string softClassName = Path.GetFileNameWithoutExtension(realName);

                                    y.data.AddHeaderReference(realName);
                                    y.data.AddHeaderReference(softClassName);
                                    Link newLink    = new Link("/Script/Astro", "AstroMissionDataAsset", y.data.AddLink("/Script/CoreUObject", "Package", 0, realName).Index, softClassName, y.data);
                                    int  bigNewLink = y.data.AddLink(newLink);

                                    usArrData[oldLen + j] = new ObjectPropertyData(arrDat.Name, y.data)
                                    {
                                        LinkValue = bigNewLink
                                    };
                                }
                                arrDat.Value = usArrData;
                                break;
                            }
                        }
                        break;
                    }
                }
            }

            if (newComponents.Length == 0)
            {
                return(y.WriteData(new BinaryReader(new MemoryStream(y.OriginalCopy))));
            }

            LevelCategory levelCategory = null;
            int           levelLocation = -1;

            for (int i = 0; i < y.data.categories.Count; i++)
            {
                Category baseUs = y.data.categories[i];
                if (baseUs is LevelCategory levelUs)
                {
                    levelCategory = levelUs;
                    levelLocation = i;
                    break;
                }
            }
            if (levelLocation < 0)
            {
                throw new FormatException("Unable to find Level category");
            }

            // Preliminary header reference additions
            y.data.AddHeaderReference("bHidden");
            y.data.AddHeaderReference("bNetAddressable");
            y.data.AddHeaderReference("CreationMethod");
            y.data.AddHeaderReference("EComponentCreationMethod");
            y.data.AddHeaderReference("EComponentCreationMethod::SimpleConstructionScript");
            y.data.AddHeaderReference("BlueprintCreatedComponents");
            y.data.AddHeaderReference("AttachParent");
            y.data.AddHeaderReference("RootComponent");

            foreach (string componentPathRaw in newComponents)
            {
                CategoryReference refData1      = new CategoryReference(refData1B);
                string            componentPath = componentPathRaw;
                string            component     = Path.GetFileNameWithoutExtension(componentPathRaw);
                if (componentPathRaw.Contains("."))
                {
                    string[] tData = componentPathRaw.Split(new char[] { '.' });
                    componentPath = tData[0];
                    component     = tData[1].Remove(tData[1].Length - 2);
                }
                y.data.AddHeaderReference(componentPath);
                y.data.AddHeaderReference(component + "_C");

                Link newLink    = new Link("/Script/Engine", "BlueprintGeneratedClass", y.data.AddLink("/Script/CoreUObject", "Package", 0, componentPath).Index, component + "_C", y.data);
                int  bigNewLink = y.data.AddLink(newLink);
                refData1.connection = bigNewLink;
                refData1.typeIndex  = y.data.AddHeaderReference(component);

                // Note that category links are set to one more than you'd think since categories in the category list index from 1 instead of 0

                refData1.garbage1 = 0;
                refData1.link     = levelLocation + 1; // Level category

                // First we see if we can find the actual asset it's referring to
                List <SCS_Node> allBlueprintCreatedComponents = new List <SCS_Node>();
                byte[]          foundData = ParentIntegrator.SearchInAllPaksForPath(componentPath.ConvertGamePathToAbsolutePath(), Extractor);
                if (foundData != null && foundData.Length > 0)
                {
                    // If we can find the asset, then we read the asset and hop straight to the SimpleConstructionScript
                    AssetReader foundDataReader = new AssetReader();
                    foundDataReader.Read(new BinaryReader(new MemoryStream(foundData)), null, null);

                    int scsLocation = -1;
                    for (int i = 0; i < foundDataReader.categories.Count; i++)
                    {
                        Category foundCategory = foundDataReader.categories[i];
                        if (foundCategory is NormalCategory normalFoundCategory)
                        {
                            string nm = foundDataReader.GetHeaderReference(foundDataReader.GetLinkReference(normalFoundCategory.ReferenceData.connection));
                            switch (nm)
                            {
                            case "SimpleConstructionScript":
                                scsLocation = i;
                                break;
                            }
                        }
                    }

                    if (scsLocation >= 0)
                    {
                        List <int>     knownNodeCategories = new List <int>();
                        NormalCategory scsCategory         = (NormalCategory)foundDataReader.categories[scsLocation];
                        for (int j = 0; j < scsCategory.Data.Count; j++)
                        {
                            PropertyData bit = scsCategory.Data[j];
                            if (bit is ArrayPropertyData arrBit && arrBit.ArrayType == "ObjectProperty" && bit.Name == "AllNodes")
                            {
                                foreach (ObjectPropertyData objProp in arrBit.Value)
                                {
                                    if (objProp.LinkValue > 0)
                                    {
                                        knownNodeCategories.Add(objProp.LinkValue);
                                    }
                                }
                            }
                        }

                        Dictionary <int, int> knownParents = new Dictionary <int, int>();
                        foreach (int knownNodeCategory in knownNodeCategories)
                        {
                            Category knownCat = foundDataReader.categories[knownNodeCategory - 1];
                            string   nm       = foundDataReader.GetHeaderReference(foundDataReader.GetLinkReference(knownCat.ReferenceData.connection));
                            if (nm != "SCS_Node")
                            {
                                continue;
                            }
                            if (knownCat is NormalCategory knownNormalCat)
                            {
                                SCS_Node newSCS = new SCS_Node();
                                newSCS.InternalVariableName = "Unknown";
                                newSCS.OriginalCategory     = knownNodeCategory;
                                Link knownTypeLink1 = null;
                                Link knownTypeLink2 = null;

                                foreach (PropertyData knownNormalCatProp in knownNormalCat.Data)
                                {
                                    switch (knownNormalCatProp.Name)
                                    {
                                    case "InternalVariableName":
                                        if (knownNormalCatProp is NamePropertyData)
                                        {
                                            newSCS.InternalVariableName = ((NamePropertyData)knownNormalCatProp).Value;
                                        }
                                        break;

                                    case "ComponentClass":
                                        if (knownNormalCatProp is ObjectPropertyData)
                                        {
                                            knownTypeLink1 = ((ObjectPropertyData)knownNormalCatProp).Value;
                                        }
                                        knownTypeLink2 = foundDataReader.GetLinkAt(knownTypeLink1.Linkage);
                                        break;

                                    case "ChildNodes":
                                        if (knownNormalCatProp is ArrayPropertyData arrData2 && arrData2.ArrayType == "ObjectProperty")
                                        {
                                            foreach (ObjectPropertyData knownNormalCatPropChildren in arrData2.Value)
                                            {
                                                knownParents.Add(knownNormalCatPropChildren.LinkValue, knownNodeCategory);
                                            }
                                        }
                                        break;
                                    }
                                }

                                if (knownTypeLink1 != null && knownTypeLink2 != null)
                                {
                                    Link prospectiveLink2 = new Link();
                                    prospectiveLink2.Base     = (ulong)y.data.AddHeaderReference(foundDataReader.GetHeaderReference((int)knownTypeLink2.Base));
                                    prospectiveLink2.Class    = (ulong)y.data.AddHeaderReference(foundDataReader.GetHeaderReference((int)knownTypeLink2.Class));
                                    prospectiveLink2.Linkage  = knownTypeLink2.Linkage;
                                    prospectiveLink2.Property = (ulong)y.data.AddHeaderReference(foundDataReader.GetHeaderReference((int)knownTypeLink2.Property));

                                    int addedLink = y.data.SearchForLink(prospectiveLink2.Base, prospectiveLink2.Class, prospectiveLink2.Linkage, prospectiveLink2.Property);
                                    if (addedLink >= 0)
                                    {
                                        addedLink = y.data.AddLink(prospectiveLink2);
                                    }

                                    Link prospectiveLink1 = new Link();
                                    prospectiveLink1.Base     = (ulong)y.data.AddHeaderReference(foundDataReader.GetHeaderReference((int)knownTypeLink1.Base));
                                    prospectiveLink1.Class    = (ulong)y.data.AddHeaderReference(foundDataReader.GetHeaderReference((int)knownTypeLink1.Class));
                                    prospectiveLink1.Property = (ulong)y.data.AddHeaderReference(foundDataReader.GetHeaderReference((int)knownTypeLink1.Property));
                                    prospectiveLink1.Linkage  = addedLink;

                                    int newTypeLink = y.data.SearchForLink(prospectiveLink1.Base, prospectiveLink1.Class, prospectiveLink1.Linkage, prospectiveLink1.Property);
                                    if (newTypeLink >= 0)
                                    {
                                        newTypeLink = y.data.AddLink(prospectiveLink1);
                                    }
                                    newSCS.TypeLink = newTypeLink;
                                }

                                allBlueprintCreatedComponents.Add(newSCS);
                            }
                        }

                        foreach (SCS_Node node in allBlueprintCreatedComponents)
                        {
                            if (knownParents.ContainsKey(node.OriginalCategory))
                            {
                                node.AttachParent = knownParents[node.OriginalCategory];
                            }
                        }
                    }
                }

                // Then we add all our child components
                int templateCategoryPointer = y.data.categories.Count + allBlueprintCreatedComponents.Count + 1;

                List <ObjectPropertyData> BlueprintCreatedComponentsSerializedList = new List <ObjectPropertyData>();
                List <ObjectPropertyData> AttachParentDueForCorrection             = new List <ObjectPropertyData>();
                Dictionary <string, int>  NodeNameToCatIndex = new Dictionary <string, int>();
                Dictionary <int, int>     OldCatToNewCat     = new Dictionary <int, int>();
                foreach (SCS_Node blueprintCreatedComponent in allBlueprintCreatedComponents)
                {
                    CategoryReference refData2 = new CategoryReference(refData2B);

                    refData2.connection = blueprintCreatedComponent.TypeLink;
                    refData2.typeIndex  = y.data.AddHeaderReference(blueprintCreatedComponent.InternalVariableName);
                    refData2.garbage1   = 0;                       // unknown if this needs to be randomized or something
                    refData2.link       = templateCategoryPointer; // Template category

                    var determinedPropData = new List <PropertyData>
                    {
                        new BoolPropertyData("bNetAddressable", y.data)
                        {
                            Value = true,
                        },
                        new EnumPropertyData("CreationMethod", y.data)
                        {
                            EnumType = "EComponentCreationMethod",
                            Value    = "EComponentCreationMethod::SimpleConstructionScript"
                        }
                    };

                    if (blueprintCreatedComponent.AttachParent >= 0)
                    {
                        var nextOPD = new ObjectPropertyData("AttachParent", y.data)
                        {
                            LinkValue = blueprintCreatedComponent.AttachParent
                        };
                        AttachParentDueForCorrection.Add(nextOPD);
                        determinedPropData.Add(nextOPD);
                    }

                    y.data.categories.Add(new NormalCategory(determinedPropData, refData2, y.data, new byte[4] {
                        0, 0, 0, 0
                    }));
                    BlueprintCreatedComponentsSerializedList.Add(new ObjectPropertyData("BlueprintCreatedComponents", y.data)
                    {
                        LinkValue = y.data.categories.Count
                    });
                    NodeNameToCatIndex.Add(blueprintCreatedComponent.InternalVariableName, y.data.categories.Count);
                    OldCatToNewCat.Add(blueprintCreatedComponent.OriginalCategory, y.data.categories.Count);

                    y.data.AddLink(new Link((ulong)y.data.AddHeaderReference("/Script/Engine"), y.data.GetLinkAt(blueprintCreatedComponent.TypeLink).Property, refData1.connection, (ulong)y.data.AddHeaderReference(blueprintCreatedComponent.InternalVariableName + "_GEN_VARIABLE")));
                }

                foreach (ObjectPropertyData attachParentCorrecting in AttachParentDueForCorrection)
                {
                    attachParentCorrecting.LinkValue = OldCatToNewCat[attachParentCorrecting.LinkValue];
                }

                // Then we add the template category
                var templateDeterminedPropData = new List <PropertyData>
                {
                    new BoolPropertyData("bHidden", y.data)
                    {
                        Value = true
                    },
                    new ArrayPropertyData("BlueprintCreatedComponents", y.data)
                    {
                        ArrayType = "ObjectProperty",
                        Value     = BlueprintCreatedComponentsSerializedList.ToArray()
                    }
                };

                foreach (KeyValuePair <string, int> entry in NodeNameToCatIndex)
                {
                    if (entry.Key == "DefaultSceneRoot")
                    {
                        templateDeterminedPropData.Add(new ObjectPropertyData("RootComponent", y.data)
                        {
                            LinkValue = entry.Value
                        });
                    }
                    templateDeterminedPropData.Add(new ObjectPropertyData(entry.Key, y.data)
                    {
                        LinkValue = entry.Value
                    });
                }

                y.data.categories.Add(new NormalCategory(templateDeterminedPropData, refData1, y.data, new byte[4] {
                    0, 0, 0, 0
                }));

                // Add the template category to the level category
                levelCategory.IndexData.Add(y.data.categories.Count);
            }

            return(y.WriteData(new BinaryReader(new MemoryStream(y.OriginalCopy))));
        }
Beispiel #34
0
    /// <summary>
    /// 测试设置
    /// </summary>
    /// <param name="pro"></param>
    public void TestSetProperty(bool isEnemy, int level)
    {
        PropertyData pro = null;

        if (isEnemy)
        {
            //pro = RoleManager.Instance.examPropertyData;
        }
        else
        {
            pro = RoleManager.Instance.playerPeople.protoData.PropertyData;
        }


        //for (int i = 0; i < pro.CurExamPropertyIdList.Count; i++)
        //{
        //    PropertyIdType idType = (PropertyIdType)pro.CurExamPropertyIdList[i];
        //    SinglePropertyData singlePro = pro.CurExamPropertyDataList[i];
        //    switch (idType)
        //    {
        //        case PropertyIdType.Attack:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].attack.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].attack.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.Defense:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].defense.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].defense.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.CritRate:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].critRate.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].critRate.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.CritNum:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].crit.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].crit.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.SkillAdd:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].skillHurtAdd.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].skillHurtAdd.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.Hp:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].hp.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].hp.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.Speed:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].attackSpeed.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].attackSpeed.ToFloat();
        //            }
        //            break;
        //    }
        //}

        //for (int i = 0; i < pro.ExamPropertyDataList.Count; i++)
        //{
        //    PropertyIdType idType = (PropertyIdType)pro.ExamPropertyIdList[i];
        //    SinglePropertyData singlePro = pro.ExamPropertyDataList[i];
        //    switch (idType)
        //    {
        //        case PropertyIdType.Attack:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].attack.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].attack.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.Defense:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].defense.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].defense.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.CritRate:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].critRate.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].critRate.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.CritNum:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].crit.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].crit.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.SkillAdd:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].skillHurtAdd.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].skillHurtAdd.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.Hp:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].hp.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].hp.ToFloat();
        //            }
        //            break;
        //        case PropertyIdType.Speed:
        //            if (isEnemy)
        //            {
        //                singlePro.PropertyNum = DataTable._testEnemyNumerialList[level - 1].attackSpeed.ToFloat();
        //            }
        //            else
        //            {
        //                singlePro.PropertyNum = DataTable._testNumerialList[level - 1].attackSpeed.ToFloat();
        //            }
        //            break;
        //    }
        //}
    }
Beispiel #35
0
        /// <summary>
        /// Saves the properties data.
        /// </summary>
        /// <param name="classType">Type of the class.</param>
        /// <param name="items">The items.</param>
        /// <param name="languageId">The language id.</param>
        /// <returns></returns>
        public static object SavePropertiesData(Type classType, PropertyData[] items, int languageId)
        {
            PropertyInfo[] propertyInfoArray = classType.GetProperties(
                BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);

            object obj = null;
            if (classType.IsClass)
            {
                if (languageId == NO_LANGUAGE)
                    obj = Activator.CreateInstance(classType);
                else
                {
                    try
                    {
                        obj = Activator.CreateInstance(classType, new object[] {languageId});
                    }
                    catch (MissingMethodException)
                    {
                        obj = Activator.CreateInstance(classType);
                    }
                }
            }

            foreach (PropertyInfo propertyInfo in propertyInfoArray)
            {
                if (propertyInfo.CanRead && propertyInfo.CanWrite)
                {
                    string propertyDesc = GetDescriptionAttribute(propertyInfo);
                    if (propertyDesc == null)
                        continue;

                    string id = classType.FullName + propertyInfo.Name;

                    foreach (PropertyData item in items)
                    {
                        if (id == item.ID)
                        {
                            propertyInfo.SetValue(obj, item.Value, null);
                            break;
                        }
                    }
                }
            }

            Type[] nestedTypes = classType.GetNestedTypes(
                BindingFlags.Public | BindingFlags.Instance);

            foreach (Type nestedType in nestedTypes)
            {
                SavePropertiesData(nestedType, items, languageId);
            }

            return obj;
        }
        private static WmiDataType GetTypeFromPropertyData(PropertyData propertyData)
        {
            bool   flag  = false;
            bool   flag2 = false;
            bool   flag3 = false;
            bool   flag4 = false;
            bool   handleObjectAsGuid = false;
            string stringFormat       = string.Empty;
            string stringTermination  = string.Empty;
            int    index = -1;

            QualifierDataCollection.QualifierDataEnumerator enumerator = propertyData.Qualifiers.GetEnumerator();
            try
            {
                while (enumerator.MoveNext())
                {
                    QualifierData current = enumerator.Current;
                    string        name    = current.Name;
                    if (name.Equals("WmiDataId", StringComparison.Ordinal))
                    {
                        flag  = true;
                        index = (int)current.Value;
                    }
                    if (name.Equals("extension", StringComparison.Ordinal) && current.Value.Equals("Guid"))
                    {
                        handleObjectAsGuid = true;
                    }
                    if (name.Equals("ActivityID", StringComparison.Ordinal))
                    {
                        flag2 = true;
                    }
                    if (name.Equals("RelatedActivityID", StringComparison.Ordinal))
                    {
                        flag3 = true;
                    }
                    if (name.Equals("XMLFragment", StringComparison.Ordinal))
                    {
                        flag4 = true;
                    }
                    if (name.Equals("format", StringComparison.Ordinal))
                    {
                        stringFormat = current.Value.ToString();
                    }
                    if (name.Equals("StringTermination", StringComparison.Ordinal))
                    {
                        stringTermination = current.Value.ToString();
                    }
                }
            }
            finally
            {
                (enumerator as IDisposable)?.Dispose();
            }
            if (flag)
            {
                return(new WmiDataType
                {
                    CimType = propertyData.Type,
                    Index = index,
                    IsActivityId = flag2,
                    IsRelatedActivityId = flag3,
                    IsXmlFragment = (flag4 | flag2 | flag3),
                    Name = propertyData.Name,
                    StringTermination = stringTermination,
                    StringFormat = stringFormat,
                    Type = TypeFromCimType(propertyData.Type, handleObjectAsGuid)
                });
            }
            return(null);
        }
Beispiel #37
0
 public EqualityCheckWeaver(PropertyData propertyData, TypeDefinition typeDefinition, ModuleWeaver typeEqualityFinder)
 {
     this.propertyData       = propertyData;
     this.typeDefinition     = typeDefinition;
     this.typeEqualityFinder = typeEqualityFinder;
 }
Beispiel #38
0
        /// <summary>
        /// Writes the markdown for the object.
        /// </summary>
        private static void WriteObject(string path, ConfigType ct, Type type, bool isYaml)
        {
            var csa = type.GetCustomAttribute <ClassSchemaAttribute>();

            if (csa == null)
            {
                return;
            }

            if (!Enum.TryParse <ConfigurationEntity>(csa.Name, out var ce))
            {
                ce = ConfigurationEntity.CodeGen;
            }

            var fn = Path.Combine(path, $"{ct}-{csa.Name}-{(isYaml ? "Config" : "Config-Xml")}.md");

            Beef.Diagnostics.Logger.Default.LogWarning($" > Creating: {fn}");
            using var sw = File.CreateText(fn);

            var pdlist = new List <PropertyData>();

            foreach (var pi in type.GetProperties())
            {
                var jpa = pi.GetCustomAttribute <JsonPropertyAttribute>();
                if (jpa == null)
                {
                    continue;
                }

                var pd = new PropertyData
                {
                    Name     = jpa.PropertyName ?? StringConversion.ToCamelCase(pi.Name),
                    Property = pi,
                    Psa      = pi.GetCustomAttribute <PropertySchemaAttribute>()
                };

                if (!isYaml)
                {
                    pd.Name = XmlYamlTranslate.GetXmlName(ct, ce, pd.Name !);
                    var xpsa = XmlYamlTranslate.GetXmlPropertySchemaAttribute(ct, ce, pd.Name).Attribute;
                    if (xpsa != null)
                    {
                        pd.Psa = xpsa;
                    }
                }

                if (pd.Psa == null)
                {
                    pd.Pcsa = pi.GetCustomAttribute <PropertyCollectionSchemaAttribute>();
                    if (pd.Pcsa == null)
                    {
                        throw new InvalidOperationException($"Type '{type.Name}' Property '{pi.Name}' does not have a required PropertySchemaAttribute or PropertyCollectionSchemaAttribute.");
                    }

                    pd.Category = pd.Pcsa.Category;
                }
                else
                {
                    pd.Category = pd.Psa.Category;
                }

                pdlist.Add(pd);
            }

            sw.WriteLine($"# {csa.Title} - {(isYaml ? "YAML/JSON" : "XML")}");
            sw.WriteLine();
            sw.WriteLine(csa.Description);
            if (!string.IsNullOrEmpty(csa.Markdown))
            {
                sw.WriteLine();
                sw.WriteLine(csa.Markdown);
            }

            sw.WriteLine();
            sw.WriteLine("<br/>");
            sw.WriteLine();

            if (isYaml && !string.IsNullOrEmpty(csa.ExampleMarkdown))
            {
                sw.WriteLine("## Example");
                sw.WriteLine();
                sw.WriteLine(csa.ExampleMarkdown);
                sw.WriteLine();
                sw.WriteLine("<br/>");
                sw.WriteLine();
            }

            var cats = type.GetCustomAttributes <CategorySchemaAttribute>();

            if (cats.Count() > 1)
            {
                sw.WriteLine("## Property categories");
                sw.WriteLine($"The `{csa.Name}` object supports a number of properties that control the generated code output. These properties are separated into a series of logical categories. The properties with a bold name are those that are more typically used (considered more important).");
                sw.WriteLine();
                sw.WriteLine("Category | Description");
                sw.WriteLine("-|-");

                foreach (var cat in cats)
                {
                    sw.WriteLine($"[`{cat.Category}`](#{cat.Category}) | {cat.Title}");
                }

                sw.WriteLine();
                sw.WriteLine("<br/>");
                sw.WriteLine();
            }
            else
            {
                sw.WriteLine("## Properties");
                sw.WriteLine($"The `{csa.Name}` object supports a number of properties that control the generated code output. The properties with a bold name are those that are more typically used (considered more important).");
                sw.WriteLine();
            }

            foreach (var cat in cats)
            {
                if (cats.Count() > 1)
                {
                    sw.WriteLine($"## {cat.Category}");
                    sw.Write(cat.Title);
                    if (cat.Description != null)
                    {
                        sw.Write($" {cat.Description}");
                    }

                    sw.WriteLine();
                    sw.WriteLine();
                }

                sw.WriteLine("Property | Description");
                sw.WriteLine("-|-");

                foreach (var p in pdlist.Where(x => x.Category == cat.Category))
                {
                    if (p.Psa != null)
                    {
                        WriteTableItem(sw, p.Name, p.Psa.Title, p.Psa.Description, null, p.Psa.IsImportant, p.Psa.Options);
                    }
                    else
                    {
                        var pt    = ComplexTypeReflector.GetItemType(p.Property !.PropertyType);
                        var ptcsa = pt.GetCustomAttribute <ClassSchemaAttribute>() !;
                        if (ptcsa != null)
                        {
                            WriteTableItem(sw, p.Name, $"The corresponding [`{ptcsa.Name}`]({ct}-{ptcsa.Name}-{(isYaml ? "Config" : "Config-Xml")}.md) collection.", p.Pcsa !.Description, p.Pcsa.Markdown, p.Pcsa.IsImportant);
                        }
                        else if (p.Pcsa != null)
                        {
                            WriteTableItem(sw, p.Name, p.Pcsa.Title, p.Pcsa.Description, p.Pcsa.Markdown, p.Pcsa.IsImportant);
                        }
                    }
                }

                sw.WriteLine();
                sw.WriteLine("<br/>");
                sw.WriteLine();
            }

            sw.WriteLine("<sub><sup>Note: This markdown file is generated; any changes will be lost.</sup></sub>");

            // Done, close file, then move onto children.
            sw.Close();

            foreach (var p in pdlist.Where(x => x.Pcsa != null))
            {
                WriteObject(path, ct, ComplexTypeReflector.GetItemType(p.Property !.PropertyType), isYaml);
            }
        }
Beispiel #39
0
        public void GetReadILCode(PropertyData prop, BinaryStruct currentStruct, GroboIL il, GroboIL.Local binaryStruct, GroboIL.Local buffer, GroboIL.Local result, GroboIL.Local typeSize, GroboIL.Local offset, bool listValue)
        {
            var exitLabel = il.DefineLabel("exit");

            BinaryStruct.ReadObjectNull(il, exitLabel, buffer, offset, typeSize);

            var len  = il.DeclareLocal(typeof(int));
            var list = il.DeclareLocal(prop.PropertyInfo.PropertyType);

            il.Ldloc(buffer);
            il.Ldloc(offset);
            il.Call(readBitConverterMethodInfo);
            il.Stloc(len);

            BinaryStruct.WriteOffsetAppend(il, offset, 4);

            il.Newobj(BinaryStruct.GetConstructor(prop.PropertyInfo.PropertyType, null));

            il.Stloc(list);
            il.Ldloc(result);
            il.Ldloc(list);
            il.Call(prop.Setter, isVirtual: true);



            il.Ldloc(len);
            il.Ldc_I4(0);
            il.Ceq();
            il.Brtrue(exitLabel);

            var typeKey   = prop.PropertyInfo.PropertyType.GetGenericArguments()[0];
            var typeValue = prop.PropertyInfo.PropertyType.GetGenericArguments()[1];

            var ivar             = il.DeclareLocal(typeof(int));
            var currentItemKey   = il.DeclareLocal(typeKey);
            var currentItemValue = il.DeclareLocal(typeValue);

            var point = il.DefineLabel("for_label");

            il.Ldc_I4(0);
            il.Stloc(ivar);

            il.MarkLabel(point);

            //body


            //key
            if (typeof(IBasicType).IsAssignableFrom(prop.BinaryAttr.Type.GetGenericArguments()[0]))
            {
                IBasicType t = (IBasicType)Activator.CreateInstance(prop.BinaryAttr.Type.GetGenericArguments()[0]);
                t.GetReadILCode(prop, currentStruct, il, binaryStruct, buffer, currentItemKey, typeSize, offset, true);
            }
            else
            {
                var constr = BinaryStruct.GetConstructor(typeKey, null);
                if (constr == null)
                {
                    throw new Exception($"Type {typeKey} not have constructor with not parameters");
                }

                il.Newobj(constr);
                il.Stloc(currentItemKey);

                BinaryStruct.CompileReader(currentStruct.CurrentStorage.GetTypeInfo(typeKey, currentStruct.Scheme), il, binaryStruct, buffer, offset, currentItemKey, typeSize);
            }

            //value
            if (typeof(IBasicType).IsAssignableFrom(prop.BinaryAttr.Type.GetGenericArguments()[1]))
            {
                IBasicType t = (IBasicType)Activator.CreateInstance(prop.BinaryAttr.Type.GetGenericArguments()[1]);
                t.GetReadILCode(prop, currentStruct, il, binaryStruct, buffer, currentItemValue, typeSize, offset, true);
            }
            else
            {
                var constr = BinaryStruct.GetConstructor(typeValue, null);
                if (constr == null)
                {
                    throw new Exception($"Type {typeValue} not have constructor with not parameters");
                }

                il.Newobj(constr);
                il.Stloc(currentItemValue);

                BinaryStruct.CompileReader(currentStruct.CurrentStorage.GetTypeInfo(typeValue, currentStruct.Scheme), il, binaryStruct, buffer, offset, currentItemValue, typeSize);
            }

            il.Ldloc(list);
            il.Ldloc(currentItemKey);
            il.Ldloc(currentItemValue);
            il.Call(prop.PropertyInfo.PropertyType.GetMethod("TryAdd"), isVirtual: true);
            il.Pop();
            //end body

            il.Ldc_I4(1);
            il.Ldloc(ivar);
            il.Add();
            il.Stloc(ivar);

            il.Ldloc(ivar);
            il.Ldloc(len);

            il.Clt(false);
            il.Brtrue(point);

            il.MarkLabel(exitLabel);
        }
Beispiel #40
0
        /// <inheritdoc/>
        public virtual IProperties ConvertProperties(IDictionary <string, object> properties, IObjectType type, ICollection <ISecondaryType> secondaryTypes, ISet <Updatability> updatabilityFilter)
        {
            // check input
            if (properties == null)
            {
                return(null);
            }

            // get the type
            if (type == null)
            {
                object typeIdObject;
                if (!properties.TryGetValue(PropertyIds.ObjectTypeId, out typeIdObject))
                {
                    throw new ArgumentException("Type or type property must be set!");
                }

                string typeId = typeIdObject as string;
                if (typeId == null)
                {
                    throw new ArgumentException("Type or type property must be set!");
                }

                type = session.GetTypeDefinition(typeId);
            }

            // get secondary types
            ICollection <ISecondaryType> allSecondaryTypes = null;
            object secondaryTypeIds;

            properties.TryGetValue(PropertyIds.SecondaryObjectTypeIds, out secondaryTypeIds);
            if (secondaryTypeIds is IList <string> )
            {
                allSecondaryTypes = new List <ISecondaryType>();

                foreach (string secondaryTypeId in (secondaryTypeIds as IList <string>))
                {
                    if (!(secondaryTypeId is string))
                    {
                        throw new ArgumentException("Secondary types property contains an invalid entry: "
                                                    + secondaryTypeId);
                    }

                    IObjectType secondaryType = session.GetTypeDefinition(secondaryTypeId.ToString());
                    if (!(secondaryType is ISecondaryType))
                    {
                        throw new ArgumentException(
                                  "Secondary types property contains a type that is not a secondary type: " + secondaryTypeId);
                    }

                    allSecondaryTypes.Add((ISecondaryType)secondaryType);
                }
            }

            if (secondaryTypes != null && allSecondaryTypes == null)
            {
                allSecondaryTypes = secondaryTypes;
            }

            Properties result = new Properties();

            // the big loop
            foreach (KeyValuePair <string, object> property in properties)
            {
                string id    = property.Key;
                object value = property.Value;

                if (value is IProperty)
                {
                    IProperty p = (IProperty)value;
                    if (id != p.Id)
                    {
                        throw new ArgumentException("Property id mismatch: '" + id + "' != '" + p.Id + "'!");
                    }
                    value = (p.PropertyDefinition.Cardinality == Cardinality.Single ? p.FirstValue : p.Values);
                }

                // get the property definition
                IPropertyDefinition definition = type[id];
                if (definition == null && allSecondaryTypes != null)
                {
                    foreach (ISecondaryType secondaryType in allSecondaryTypes)
                    {
                        if (secondaryType.PropertyDefinitions != null)
                        {
                            foreach (IPropertyDefinition propertyDefinition in secondaryType.PropertyDefinitions)
                            {
                                if (propertyDefinition.Id == id)
                                {
                                    definition = propertyDefinition;
                                    break;
                                }
                            }
                            if (definition != null)
                            {
                                break;
                            }
                        }
                    }
                    if (definition == null)
                    {
                        throw new ArgumentException("Property +'" + id + "' is not valid for this type!");
                    }
                }

                // check updatability
                if (updatabilityFilter != null)
                {
                    if (definition.Updatability.HasValue && !updatabilityFilter.Contains(definition.Updatability.Value))
                    {
                        continue;
                    }
                }

                PropertyData propertyData = new PropertyData(definition.PropertyType);
                propertyData.Id = id;

                // single and multi value check
                if (value == null)
                {
                    propertyData.Values = null;
                }
                else if (value is IList)
                {
                    if (definition.Cardinality != Cardinality.Multi)
                    {
                        throw new ArgumentException("Property '" + id + "' is not a multi value property!");
                    }

                    IList valueList = (IList)value;

                    // check if the list is homogeneous and does not contain null values
                    foreach (object o in valueList)
                    {
                        if (o == null)
                        {
                            throw new ArgumentException("Property '" + id + "' contains null values!");
                        }

                        propertyData.AddValue(o);
                    }
                }
                else
                {
                    if (definition.Cardinality != Cardinality.Single)
                    {
                        throw new ArgumentException("Property '" + id + "' is not a single value property!");
                    }

                    propertyData.AddValue(value);
                }

                result.AddProperty(propertyData);
            }

            return(result);
        }
 internal WmiPropertyItem(PropertyData propertyData)
 {
     this.propertyData = propertyData;
 }
        protected override bool PrivateUpdate(ScenarioFrame frame)
        {
            List <PropertyData> properties = new List <PropertyData>();

            int max = Maximum;
            int min = Minimum;

            foreach (PropertyData property in Sim.Household.RealEstateManager.AllProperties)
            {
                int cost = GetCost(property);
                if (cost <= 0)
                {
                    continue;
                }

                if (cost < min)
                {
                    continue;
                }

                if (cost > max)
                {
                    continue;
                }

                properties.Add(property);
            }

            if (properties.Count == 0)
            {
                return(false);
            }

            mFail = IsFail(Sim, Target);

            if (!mFail)
            {
                PropertyData choice = RandomUtil.GetRandomObjectFromList(properties);

                mObjectName  = choice.LocalizedName;
                mObjectValue = GetCost(choice);

                if (ActualTransfer)
                {
                    ManagerMoney.TransferProperty(Sim.Household, Target.Household, choice);
                }
                else
                {
                    Money.AdjustFunds(Target, "PropertyTransfer", -mObjectValue);

                    Money.AdjustFunds(Sim, "PropertyTransfer", mObjectValue);
                }

                if (Delta < 0)
                {
                    TraitFunctions.ItemStolenCallback(Target.Household, Origin.FromTheft);

                    foreach (Sim sim in HouseholdsEx.AllSims(Target.Household))
                    {
                        EventTracker.SendEvent(EventTypeId.kWasRobbed, sim);
                    }
                }
            }

            if (Delta < 0)
            {
                if (OnInvestigateScenario != null)
                {
                    OnInvestigateScenario(this, frame);
                }
            }

            return(true);
        }
Beispiel #43
0
 public string WritePropertySyntax(PropertyData propertyData, AssemblyData assemblyData)
 {
     throw new NotImplementedException();
 }
        private void HandleGradientDropOnGradientLevelPairList(PropertyData property, Element element, Dictionary<Element, Tuple<object, PropertyDescriptor>> elementValues, ColorGradient gradient)
        {
            List<GradientLevelPair> gradients = property.Descriptor.GetValue(element.EffectNode.Effect) as List<GradientLevelPair>;
            if (gradients == null) return;

            var parameterPickerControls = CreateGradientLevelPairPickerControls(property, gradients);

            var parameterPicker = CreateParameterPicker(parameterPickerControls);

            ShowMultiDropMessage();
            var dr = parameterPicker.ShowDialog();
            if (dr == DialogResult.OK)
            {
                var newGradients = gradients.ToList();
                newGradients[parameterPicker.SelectedControl.Index] = new GradientLevelPair(gradient, gradients[parameterPicker.SelectedControl.Index].Curve);
                elementValues.Add(element, new Tuple<object, PropertyDescriptor>(parameterPicker.PropertyInfo.GetValue(element.EffectNode.Effect), parameterPicker.PropertyInfo));
                UpdateEffectProperty(parameterPicker.PropertyInfo, element, newGradients);
            }
        }
Beispiel #45
0
 public BuilderPropertyData(PropertyData propertyData, string scheme, TypeStorage storage) : base(propertyData, scheme, storage)
 {
 }
        private string Render(string templateCode, string templateFile)
        {
            DTE vs = this.GetService<DTE>(true);
              string basePath = this.GetBasePath();
              Microsoft.VisualStudio.TextTemplating.ITextTemplatingEngine engine = new Microsoft.VisualStudio.TextTemplating.Engine();
              IValueInfoService service = (IValueInfoService)this.GetService(typeof(IValueInfoService));
              Dictionary<string, PropertyData> arguments = new Dictionary<string, PropertyData>();
              foreach (string str2 in base.additionalArguments.Keys)
              {
            Type type = null;
            try
            {
              type = service.GetInfo(str2).Type;
            }
            catch (ArgumentException)
            {
              if (base.additionalArguments[str2] != null)
              {
                type = base.additionalArguments[str2].GetType();
              }
              else
              {
                continue;
              }
            }
            PropertyData data = new PropertyData(base.additionalArguments[str2], type);
            arguments.Add(str2, data);
              }
              TemplateHost host = new TemplateHost(basePath, arguments);
              host.TemplateFile = templateFile;
              Helpers.LogMessage(vs, this, templateFile);

              string str3 = engine.ProcessTemplate(templateCode, host);
              if (host.Errors.HasErrors)
              {
            string errors = "";
            foreach (CompilerError error in host.Errors)
            {
              Helpers.LogMessage(vs, this, error.ErrorText);
              errors += error.ErrorText + Environment.NewLine;
            }
            throw new TemplateException(host.Errors);
              }
              if (host.Errors.HasWarnings)
              {
            StringBuilder builder = new StringBuilder();
            foreach (CompilerError error in host.Errors)
            {
              builder.AppendLine(error.ErrorText);
            }
            //Trace.WriteLine(string.Format(CultureInfo.CurrentCulture, "CompilationWarnings", new object[] { templateFile, builder.ToString() }));
              }
              return str3;
        }
Beispiel #47
0
 private static IList <PropertyData> GetPropertyList(Type t)
 {
     lock (ValuePropertyLists) {
         IList <PropertyData> ret = new List <PropertyData>();
         if (ValuePropertyLists.ContainsKey(t))
         {
             return(ValuePropertyLists[t]);
         }
         bool anonymous = HasCustomAttribute(
             t,
             "System.Runtime.CompilerServices.CompilerGeneratedAttribute") ||
                          HasCustomAttribute(
             t,
             "Microsoft.FSharp.Core.CompilationMappingAttribute");
         var names = new Dictionary <string, int>();
         foreach (PropertyInfo pi in GetTypeProperties(t))
         {
             var pn = RemoveIsPrefix(pi.Name);
             if (names.ContainsKey(pn))
             {
                 ++names[pn];
             }
             else
             {
                 names[pn] = 1;
             }
         }
         foreach (FieldInfo pi in GetTypeFields(t))
         {
             var pn = RemoveIsPrefix(pi.Name);
             if (names.ContainsKey(pn))
             {
                 ++names[pn];
             }
             else
             {
                 names[pn] = 1;
             }
         }
         foreach (FieldInfo fi in GetTypeFields(t))
         {
             PropertyData pd = new PropertyMap.PropertyData()
             {
                 Name = fi.Name,
                 Prop = fi,
             };
             if (pd.HasUsableGetter() || pd.HasUsableSetter())
             {
                 var pn = RemoveIsPrefix(pd.Name);
                 // Ignore ambiguous properties
                 if (names.ContainsKey(pn) && names[pn] > 1)
                 {
                     continue;
                 }
                 ret.Add(pd);
             }
         }
         foreach (PropertyInfo pi in GetTypeProperties(t))
         {
             if (pi.CanRead && (pi.CanWrite || anonymous) &&
                 pi.GetIndexParameters().Length == 0)
             {
                 if (PropertyData.HasUsableGetter(pi) ||
                     PropertyData.HasUsableSetter(pi))
                 {
                     var pn = RemoveIsPrefix(pi.Name);
                     // Ignore ambiguous properties
                     if (names.ContainsKey(pn) && names[pn] > 1)
                     {
                         continue;
                     }
                     PropertyData pd = new PropertyMap.PropertyData()
                     {
                         Name = pi.Name,
                         Prop = pi,
                     };
                     ret.Add(pd);
                 }
             }
         }
         ValuePropertyLists.Add(
             t,
             ret);
         return(ret);
     }
 }
Beispiel #48
0
        private void GetValueParsed(Dictionary <string, Object> propsOut, String propName, PropertyData prop)
        {
            if (prop.Value != null)
            {
                Debug("Parsing: " + propName + ", propValue: " + prop.Value.ToString() + " CimType: " + prop.Type.ToString());
                switch (prop.Type)
                {
                case CimType.Boolean:
                    propsOut.Add(propName, prop.Value.ToString());
                    break;

                case CimType.DateTime:
                    try
                    {
                        DateTime dateToParse = DateTime.ParseExact(prop.Value.ToString(), "yyyyMMddHHmmss.ffffff-000", System.Globalization.CultureInfo.InvariantCulture);
                        propsOut.Add(propName, (long)(dateToParse - new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc)).TotalMilliseconds);
                    }
                    catch (FormatException fe)
                    {
                        Debug("Could not parse: " + propName + ", propValue: " + prop.Value.ToString() + ", of CimType: " + prop.Type.ToString());
                        Debug("Parsing Exception: " + fe.ToString());
                    }
                    break;

                case CimType.String:
                    if (((String)prop.Value).Length > 0)
                    {
                        propsOut.Add(propName, prop.Value);
                    }
                    break;

                default:
                    propsOut.Add(propName, prop.Value);
                    break;
                }
            }
        }
Beispiel #49
0
        public void GetWriteILCode(PropertyData prop, BinaryStruct currentStruct, GroboIL il, GroboIL.Local binaryStruct, GroboIL.Local value, GroboIL.Local typeSize, GroboIL.Local buffer, GroboIL.Local offset, bool listValue)
        {
            BinaryStruct.WriteSizeChecker(il, buffer, offset, 5);

            var arr       = il.DeclareLocal(typeof(byte[]));
            var arrSize   = il.DeclareLocal(typeof(byte[]));
            var temp      = il.DeclareLocal(typeof(string));
            var exitLabel = il.DefineLabel("exit");


            il.Ldloc(value);

            if (!listValue)
            {
                il.Call(prop.Getter);
            }
            il.Stloc(temp);

            il.Ldloc(temp);
            BinaryStruct.WriteObjectNull(il, exitLabel, buffer, offset, typeSize);

            il.Ldloc(temp);
            il.Call(typeof(string).GetProperty("Length").GetMethod);
            il.Stloc(typeSize);

            il.Ldarg(1);
            il.Call(codingMethodInfo);

            il.Ldloc(temp);

            il.Call(currentStruct.Coding.GetType().GetMethod("GetBytes", new Type[] { typeof(string) }));
            il.Stloc(arr);

            il.Ldloc(arr);
            il.Call(typeof(byte[]).GetProperty("Length").GetMethod);
            il.Stloc(typeSize);

            il.Ldloc(typeSize);
            il.Call(writeBitConverterMethodInfo);
            il.Stloc(arrSize);

            il.Ldloc(buffer);
            il.Ldloc(offset);
            il.Ldloc(arrSize);
            il.Ldc_I4(0);
            il.Ldelem(typeof(byte));
            il.Stelem(typeof(byte));

            for (int i = 1; i < 4; i++)
            {
                il.Ldloc(buffer);
                il.Ldloc(offset);
                il.Ldc_I4(i);
                il.Add();
                il.Ldloc(arrSize);
                il.Ldc_I4(i);
                il.Ldelem(typeof(byte));
                il.Stelem(typeof(byte));
            }

            BinaryStruct.WriteOffsetAppend(il, offset, 4);

            il.Ldloc(typeSize);
            il.Ldc_I4(0);
            il.Ceq();
            il.Brtrue(exitLabel);

            BinaryStruct.WriteSizeChecker(il, buffer, offset, typeSize);

            var ivar  = il.DeclareLocal(typeof(int));
            var point = il.DefineLabel("for_label");

            il.Ldc_I4(0);
            il.Stloc(ivar);

            il.MarkLabel(point);

            //body

            il.Ldloc(buffer);
            il.Ldloc(ivar);
            il.Ldloc(offset);
            il.Add();
            il.Ldloc(arr);
            il.Ldloc(ivar);

            il.Ldelem(typeof(byte));
            il.Stelem(typeof(byte));

            //end body

            il.Ldc_I4(1);
            il.Ldloc(ivar);
            il.Add();
            il.Stloc(ivar);

            il.Ldloc(ivar);
            il.Ldloc(typeSize);

            il.Clt(false);
            il.Brtrue(point);

            BinaryStruct.WriteOffsetAppend(il, offset, typeSize);

            il.MarkLabel(exitLabel);
        }
Beispiel #50
0
 public SinglePropertyMapper(PropertyData propertyData)
 {
     this.propertyData = propertyData;
 }
 public string Map(PageData pageData, PropertyData propertyData)
 {
     return string.Format("{0}", (propertyData.Value != null).ToString(CultureInfo.InvariantCulture)).ToLower();
 }
        private IEnumerable <IArgumentDef> GetArgumentsFromModel(Type modelType,
                                                                 object existingDefault, Action <object> instanceCreated, PropertyData parentProperty = null)
        {
            var instance = existingDefault ?? _appConfig.ResolverService.ResolveArgumentModel(modelType);

            if (existingDefault == null)
            {
                instanceCreated?.Invoke(instance);
            }

            return(modelType
                   .GetDeclaredProperties()
                   .Select(p => new PropertyData(
                               _appConfig.AppSettings.GuaranteeOperandOrderInArgumentModels,
                               p,
                               parentProperty,
                               GetArgumentType(p, _argumentMode)))
                   .SelectMany(propertyInfo => GetArgsFromProperty(propertyInfo, instance)));
        }
Beispiel #53
0
        /// <summary>
        /// Registers a property for a specific type.
        /// </summary>
        /// <param name="name">The name of the property.</param>
        /// <param name="propertyData">The property data.</param>
        /// <exception cref="ArgumentException">The <paramref name="name"/> is <c>null</c> or whitespace.</exception>
        /// <exception cref="ArgumentNullException">The <paramref name="propertyData"/> is <c>null</c>.</exception>
        /// <exception cref="PropertyAlreadyRegisteredException">A property with the same name is already registered.</exception>
        public void RegisterProperty(string name, PropertyData propertyData)
        {
            Argument.IsNotNullOrWhitespace("name", name);
            Argument.IsNotNull("propertyData", propertyData);

            lock (_lockObject)
            {
                if (_catelProperties.ContainsKey(name))
                {
                    throw new PropertyAlreadyRegisteredException(name, Type);
                }

                _catelProperties.Add(name, propertyData);
            }
        }
Beispiel #54
0
 private static bool GetEpiserverBoolProperty(PropertyData content)
 => content is PropertyBoolean property && property.Boolean.GetValueOrDefault(false);
 public string Map(PageData pageData, PropertyData propertyData)
 {
     return string.Format("\"{0}\"", propertyData);
 }
 public void initModel()
 {
     data = new PropertyData();
 }
Beispiel #57
0
        private static PropertyData[] GetPropertiesData(Type classType, object objectInstance, int languageId)
        {
            List<PropertyData> lSettingsItems = new List<PropertyData>();

            PropertyInfo[] propertyInfoArray = classType.GetProperties(
                BindingFlags.Static | BindingFlags.Instance | BindingFlags.Public);

            if (!classType.IsAbstract)
            {
                object obj = null;
                if (objectInstance == null)
                {
                    if (classType.IsClass)
                    {
                        if (languageId == NO_LANGUAGE)
                            obj = Activator.CreateInstance(classType);
                        else
                        {
                            try
                            {
                                obj = Activator.CreateInstance(classType, new object[] { languageId });
                            }
                            catch (MissingMethodException)
                            {
                                obj = Activator.CreateInstance(classType);
                            }
                        }
                    }
                }
                else obj = objectInstance;

                foreach (PropertyInfo propertyInfo in propertyInfoArray)
                {
                    string propertyDesc = GetDescriptionAttribute(propertyInfo);
                    if (propertyDesc == null)
                        continue;

                    string propertyHint = GetHintAttribute(propertyInfo);

                    string classDesc = GetDescriptionAttribute(classType);
                    if (classDesc == null)
                        throw new NoAttributeFoundException(
                            "The parent class should also have description attribute!");

                    Hashtable propertiesToApply = GetPropertiesToApply(propertyInfo);

                    Type controlType;
                    string controlProperty;

                    GetControlInfo(propertyInfo, out controlType, out controlProperty);

                    PropertyData item = new PropertyData();
                    item.ClassDesc = classDesc;
                    item.PropertyName = propertyInfo.Name;
                    item.PropertyDesc = propertyDesc;
                    item.PropertyHint = propertyHint;
                    item.Value = propertyInfo.GetValue(obj, null);
                    item.ID = classType.FullName + propertyInfo.Name;
                    item.ControlType = controlType;
                    item.ControlProperty = controlProperty;
                    item.PropertiesToApply = propertiesToApply;
                    lSettingsItems.Add(item);
                }

                Type[] nestedTypes = classType.GetNestedTypes(
                    BindingFlags.Public | BindingFlags.Instance);

                foreach (Type nestedType in nestedTypes)
                {
                    lSettingsItems.AddRange(GetPropertiesData(nestedType, languageId));
                }
            }
            return lSettingsItems.ToArray();
        }
Beispiel #58
0
 public EmbeddedIdMapper(PropertyData idPropertyData, System.Type compositeIdClass)
     : base(compositeIdClass)
 {
     _idPropertyData = idPropertyData;
 }
        /// <summary>
        /// 保存处理
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnOk_Click(object sender, EventArgs e)
        {
            if (_Object.Text != textBox1.Text.Trim() || _Object.Message != txtMessage.Text.Trim())
            {
                _Object.Text    = textBox1.Text.Trim();
                _Object.Message = txtMessage.Text.Trim();
                if (AfterSave != null)
                {
                    AfterSave(_Object);
                }
            }
            if (comboBox1.Text == "")
            {
                MessageBox.Show("请设置日期。");
                comboBox1.Focus();
                return;
            }
            //保存属性列表
            List <PropertyData> properties = new List <PropertyData>();
            DataGridView        view       = dataGridView1;
            bool change = false;

            if (_datatable.Rows.Count > 0)
            {
                for (int i = 0; i < dataGridView1.RowCount; i++)
                {
                    string colname = dataGridView1.Rows[i].Cells[0].Value.ToString();
                    if (_datatable.Rows[0][colname].ToString() != GetValue(view, i, 1))
                    {
                        change = true;
                        break;
                    }
                }
            }
            else
            {
                change = true;
            }
            if (!change)
            {
                return;
            }
            if (change)
            {
                string type = "0";
                //如果是保存交易信息
                //循环设置保存属性列表
                for (int i = 0; i < view.Rows.Count; i++)
                {
                    if (view.Rows[i].Cells[0].Value != null)
                    {
                        PropertyData data = new PropertyData();
                        if (view.Rows[i].Cells[1].Value != null)
                        {
                            data.Data = view.Rows[i].Cells[1].Value.ToString();
                        }
                        data.PropertyName = view.Rows[i].Cells[0].Value.ToString();
                        properties.Add(data);
                    }
                }
                //保存属性
                MapDBClass.SaveProperty(_MapId, _LayerId, _Object.ID, comboBox1.Text.Trim(), properties, _UpdateDate);
            }
            bool find = false;

            for (int i = 0; i < comboBox1.Items.Count; i++)
            {
                if (comboBox1.Items[i].ToString() == comboBox1.Text.Trim())
                {
                    find = true;
                    break;
                }
            }
            if (!find)
            {
                comboBox1.Items.Add(comboBox1.Text.Trim());
            }
            comboBox1_SelectedIndexChanged(null, null);
        }
 /// <summary>
 /// Converts an instance of PropertyData into a specific Property Model
 /// </summary>
 /// <param name="propertyData">An instance of PropertyData</param>
 public IPropertyModel GetValue(PropertyData propertyData, CultureInfo language, bool excludePersonalizedContent, bool expand)
 {
     return(new BuyTicketBlockPropertyModel((PropertyBlock)propertyData));
 }