public static void CreateComponentIfMissing(Transform t, List <AudioEnvelope> Envelopes) { foreach (var env in Envelopes) { System.Type c = null; switch (env.filter) { case AudioEnvelope.FilterType.Highpass: c = typeof(AudioHighPassFilter); break; case AudioEnvelope.FilterType.Lowpass: c = typeof(AudioLowPassFilter); break; case AudioEnvelope.FilterType.Pitch: c = typeof(AudioSource); break; case AudioEnvelope.FilterType.Volume: c = typeof(AudioSource); break; } if (c != null) { var components = t.GetComponents(c.GetType()); if (components.Length == 0) { t.gameObject.AddComponent(c.GetType()); } } } }
/// <summary> /// Very importat to avoid out of order reflection /// The CLR caches previous fields access to speed up reflection but can return the fields in wrong order /// Clearing the m_fieldInfoCache of the Cache property resolves the issue /// </summary> /// <param name="type">Type of Object</param> public static void ResetFieldInfoCache(Type type) { if (mCacheProperty == null) { mCacheProperty = type.GetType().GetProperty("Cache", BindingFlags.DeclaredOnly | BindingFlags.Instance | BindingFlags.NonPublic); } Debug.Assert(mCacheProperty != null, "There is no Cache property in the RuntimeType: " + type.GetType().Name); if (mCacheProperty != null) { var cacheObject = mCacheProperty.GetValue(type, null); Debug.Assert(cacheObject != null, "There is no value for the Cache property in the RuntimeType: " + type.Name); var cacheField = cacheObject.GetType().GetField("m_fieldInfoCache", BindingFlags.FlattenHierarchy | BindingFlags.Instance | BindingFlags.NonPublic); Debug.Assert(cacheField != null, "There is no m_fieldInfoCache field for the RuntimeTypeCache: " + type.Name); if (cacheField != null) cacheField.SetValue(cacheObject, null); } }
public object GetService( Type serviceType ) { if( this.container.IsRegistered( serviceType.GetType() ) ) { return this.container.Resolve( serviceType.GetType() ); } return null; }
public static Type GetUnderlyingType(Type type) { Type type2 = typeof(int); if (type.GetType().FullName.Equals("System.Workflow.ComponentModel.Compiler.DesignTimeType", StringComparison.Ordinal)) { MethodInfo method = type.GetType().GetMethod("GetEnumType"); if (method != null) { Type type3 = method.Invoke(type, new object[0]) as Type; type2 = (type3 != null) ? type3 : type2; } return type2; } return Enum.GetUnderlyingType(type); }
public override Type GetDataContractType(Type requestedType) { // Serialize proxies as the base type if(typeof(INHibernateProxy).IsAssignableFrom(requestedType)) { requestedType = requestedType.GetType().BaseType; } // Serialize persistent collections as the collection interface type if(typeof(IPersistentCollection).IsAssignableFrom(requestedType)) { foreach(var collInterface in requestedType.GetInterfaces()) { if(collInterface.IsGenericType) { requestedType = collInterface; break; } if(!collInterface.Equals(typeof(IPersistentCollection))) { requestedType = collInterface; } } } return requestedType; }
/// <summary> /// Initializes a new instance of the <see cref="CommandExecutorNotFoundException"/> class. /// </summary> /// <param name="commandType">Type of the command.</param> /// <param name="message">The message.</param> /// <param name="inner">The inner exception.</param> /// <exception cref="ArgumentNullException">Occurs when <i>commandType</i> is a <c>null</c> dereference.</exception> public CommandExecutorNotFoundException(Type commandType, string message, Exception inner) : base((String.IsNullOrEmpty(message) ? String.Format("No handler was found for command {0}.", commandType.GetType().FullName) : message), inner) { Contract.Requires<ArgumentNullException>(commandType != null); CommandType = commandType; }
public DataWraper(Type tableName, BindingSource componentId, ErrorProvider errorProvider) { errorProvider1 = errorProvider; bindingSourceMain = componentId; bindingSourceMain.PositionChanged += bindingSourceMain_PositionChanged; InitializeComponent(); WrapperBindingSource.PositionChanged += WrapperBindingSource_PositionChanged; WrapperBindingSource.DataSource = tableName.GetType(); //Type yy = tableName.GetType(); Text = tableName.Name + "s"; dataTableAdaptor = new MySqlTableAdaptor(tableName); dataTable = dataTableAdaptor.GetTable(); WrapperBindingSource.DataSource = dataTable; errorProvider1.DataSource = WrapperBindingSource; if (componentId.Current != null) { WrapperBindingSource.Position = (int)componentId.Current; } WrapperID.DataBindings.Add("Text", WrapperBindingSource, "ID"); WrapperComboBox.DataSource = dataTable; WrapperComboBox.AutoCompleteMode = AutoCompleteMode.SuggestAppend; WrapperComboBox.AutoCompleteSource = AutoCompleteSource.ListItems; WrapperComboBox.DisplayMember = dataTable.Columns[1].ColumnName; WrapperComboBox.ValueMember = dataTable.Columns[0].ColumnName; //WrapperComboBox.DataSource = WrapperBindingSource; WrapperComboBox.SelectedValueChanged += WrapperComboBox_SelectedValueChanged; WrapperComponentSelection.Click+=WrapperComponentSelection_Click; WrapperComboBox.Validated += WrapperComboBox_Validated; WrapperLabel.Text = tableName.Name; WrapperID.TextChanged += WrapperID_TextChanged; //WrapperComboBox.DataBin type = tableName; }
public RtsBrushDatabaseWrapper() { records = new List <RtsBrushAssetRecordWrapper>(); _databaseType = Type.GetType("Rotorz.TileSystem.Editor.BrushDatabase,RotorzTileSystemEditor"); if (_databaseType == null) { return; } PropertyInfo piInstance = _databaseType.GetProperty("instance", BindingFlags.Public | BindingFlags.Static); if (piInstance == null) { piInstance = _databaseType.GetProperty("Instance", BindingFlags.Public | BindingFlags.Static); if (piInstance == null) { return; } } _rawDatabase = piInstance.GetValue(null, null); Update(); }
public object CallStaticFunction(Type type, string funcName, object[] args) { return PerformInvocation(type, funcName, args, innerArgs => type.CallMethod(funcName, StaticFlags, innerArgs), innerArgs => type.TryCallMethodWithValues(TryConvert, funcName, StaticFlags, innerArgs), innerArgs => type.GetType().GetMethod(funcName).Invoke(type, args)); }
public override void BeginCatchBlock(Type exceptionType) { if (base.CurrExcStackCount == 0) { throw new NotSupportedException(Environment.GetResourceString("Argument_NotInExceptionBlock")); } __ExceptionInfo info = base.CurrExcStack[base.CurrExcStackCount - 1]; if (info.GetCurrentState() == 1) { if (exceptionType != null) { throw new ArgumentException(Environment.GetResourceString("Argument_ShouldNotSpecifyExceptionType")); } this.Emit(OpCodes.Endfilter); } else { if (exceptionType == null) { throw new ArgumentNullException("exceptionType"); } if (!exceptionType.GetType().IsRuntimeType) { throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); } Label endLabel = info.GetEndLabel(); this.Emit(OpCodes.Leave, endLabel); base.UpdateStackSize(OpCodes.Nop, 1); } info.MarkCatchAddr(this.ILOffset, exceptionType); info.m_filterAddr[info.m_currentCatch - 1] = this.m_scope.GetTokenFor(exceptionType.TypeHandle); }
public IModelObject GetSpecialCaseClass(Type o) { if (o.FullName == typeof(Category).FullName) { return new MissingCategory(); } else if (o.FullName == typeof(ProvidedAnswer).FullName) { return new MissingProvidedAnswer(); } else if (o.FullName == typeof(Question).FullName) { return new MissingQuestion(); } else if (o.FullName == typeof(Rating).FullName) { return new MissingRating(); } else if (o.FullName == typeof(Solution).FullName) { return new MissingSolution(); } else if (o.FullName == typeof(Tag).FullName) { return null; // new MissingTag(); } else if (o.FullName == typeof(User).FullName) { return new MissingUser(); } else { throw new Exception("Special case class not found for type: " + o.GetType()); } }
/// <summary> /// Refresh list of v1.x tile systems in current scene. /// </summary> void RefreshTileSystems() { if (_systems == null) { _systems = new List <TileSystemItem>(); } else { _systems.Clear(); } // Is tile system class available? Type tyRotorzTileSystem = Type.GetType("Rotorz.TileSystem.RotorzTileSystem,RotorzTileSystem"); if (tyRotorzTileSystem == null) { return; } foreach (MonoBehaviour system in Resources.FindObjectsOfTypeAll(tyRotorzTileSystem) as MonoBehaviour[]) { if (PrefabUtility.GetPrefabType(system) == PrefabType.Prefab) { continue; } _systems.Add(new TileSystemItem(system)); } }
static LayoutUtility() { Type tyWindowLayout = Type.GetType("UnityEditor.WindowLayout,UnityEditor"); Type tyEditorUtility = Type.GetType("UnityEditor.EditorUtility,UnityEditor"); Type tyInternalEditorUtility = Type.GetType("UnityEditorInternal.InternalEditorUtility,UnityEditor"); if (tyWindowLayout != null && tyEditorUtility != null && tyInternalEditorUtility != null) { MethodInfo miGetLayoutsPath = tyWindowLayout.GetMethod("GetLayoutsPath", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static); _miLoadWindowLayout = tyWindowLayout.GetMethod("LoadWindowLayout", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string), typeof(bool) }, null); _miSaveWindowLayout = tyWindowLayout.GetMethod("SaveWindowLayout", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null); _miReloadWindowLayoutMenu = tyInternalEditorUtility.GetMethod("ReloadWindowLayoutMenu", BindingFlags.Public | BindingFlags.Static); if (miGetLayoutsPath == null || _miLoadWindowLayout == null || _miSaveWindowLayout == null || _miReloadWindowLayoutMenu == null) { return; } _layoutsPath = (string)miGetLayoutsPath.Invoke(null, null); if (string.IsNullOrEmpty(_layoutsPath)) { return; } _available = true; } }
private void CheckProperty(Type t, string propName, Type[] propTypes) { var props = t.GetProperties(); var prop = props.Where(p => p.Name == propName).FirstOrDefault(); Assert.IsNotNull(prop, $" - {t.GetType().Name} has no public {propName} property"); Assert.IsTrue(Array.Exists(propTypes,p => p.Name == prop.PropertyType.Name), $"- {typeof(object).Name}: property {propName} is a {prop.PropertyType.Name}"); }
public static Route GetRouteAttribute(Type callToGetUrlFor) { object[] routeable = callToGetUrlFor.GetCustomAttributes(typeof(Route), true); if(routeable.Length == 0) { throw new Exception("tried to get a url from a non-routable object:" + callToGetUrlFor.GetType()); } return (routeable[0] as Route); }
/// <summary> /// Applies all effects to target creature's gameobject as components. /// </summary> /// <param name="target"></param> protected void AddEffectToTarget(Character target, System.Type effect) { if (typeof(Effect) != effect.BaseType) { return; } target.gameObject.AddComponent(effect.GetType()); }
void KontrolListe(Type t) { var kontroller = from Control ctrl in this.Controls where ctrl.GetType() == t.GetType() select ctrl.Name; foreach(var v in kontroller) MessageBox.Show(v); //dataGridView1.DataSource = kontroller; }
/// <summary> /// Gets the member info of the identifier property for a given entity /// </summary> /// <param name="modelInspector">An instance the model inspector</param> /// <param name="entityType">The type of the entity</param> /// <returns>The member info of the ID property</returns> public static MemberInfo GetIdentifierMember(this IModelInspector modelInspector, Type entityType) { string idPropertyName = GetIdentifierPropertyName(modelInspector, entityType); if (string.IsNullOrEmpty(idPropertyName)) { throw new System.Configuration.ConfigurationErrorsException(string.Format("Missing identifier property. Wrong mapping or missing mapping class for the type {0}", entityType.GetType().FullName)); } return entityType.GetMember(idPropertyName).SingleOrDefault(); }
public void CreaturesFactory_WhenValidNameIsPassed_ShouldReturnExpectedType(string name, Type expectedCreature) { // Arrange var factory = new ExtendedCreaturesFactory(); // Act var creature = factory.CreateCreature(name); // Assert Assert.IsInstanceOf(expectedCreature.GetType(), creature.GetType()); }
/** * Creates an instance by copying values from the given other CoreMap, * using the values it associates with the given set of hashkeys for * the immutable, hashable keys used by hashcode and equals. */ /*public HashableCoreMap<T>(ArrayCoreMap other, Set<Key<T>> hashkey):base(other) { int keyHashcode = 0; int valueHashcode = 0; foreach (Key<T> key in hashkey) { // NB it is important to compose these hashcodes in an order-independent // way, so we just add them all here. keyHashcode += key.hashCode(); valueHashcode += base.get((Class)key).hashCode(); } this.immutableKeys = hashkey; this.hashcode = keyHashcode * 31 + valueHashcode; }*/ /// <summary> /// Sets the value associated with the given key; if the the key is one /// of the hashable keys, throws an exception. /// </summary> /// <exception cref="HashableCoreMapException">Attempting to set the value for an immutable, hashable key.</exception> public override /*<VALUE> VALUE*/ Object Set(Type key, Object value) { if (immutableKeys.Contains(key)) { throw new HashableCoreMapException("Attempt to change value " + "of immutable field " + key.GetType().Name); } return base.Set(key, value); }
/// <summary> /// Handles web specific details of context instantiation. /// </summary> protected override IApplicationContext InstantiateContext(IApplicationContext parent, object configContext, string contextName, Type contextType, bool caseSensitive, string[] resources) { if (!contextType.GetType().IsSubclassOf(typeof (FluentWebApplicationContext))) { Log.Warn(string.Format("This context type {0} does not support fluent configuration for object definitions.", contextType)); } // the get assembly resources method will parse my resource strings I definied in spring config and return me an extended set string[] overridenResources = GetAssemblyResources(resources); return base.InstantiateContext(parent, configContext, contextName, contextType, caseSensitive, overridenResources); }
private static Type CreateDynamicType(Type entityType) { AssemblyName name = new AssemblyName("DynamicAssembly_" + Guid.NewGuid()); TypeBuilder builder3 = AppDomain.CurrentDomain.DefineDynamicAssembly(name, AssemblyBuilderAccess.Run).DefineDynamicModule("DynamicModule_" + Guid.NewGuid()).DefineType(entityType.GetType() + "$DynamicType", TypeAttributes.Public); builder3.DefineDefaultConstructor(MethodAttributes.Public); foreach (PropertyInfo info in entityType.GetProperties()) { builder3.DefineField(info.Name, info.PropertyType, FieldAttributes.Public); } return builder3.CreateType(); }
public CacheEntry(Type t) { this.t = t; if (t.GetType() != typeof(object).GetType()) { // not a runtime type, TypeInfoProvider missing - return nothing constructors = fields = properties = events = methods = empty; defaultMember = null; } }
internal static void RequireRuntimeType(Type type) { // To avoid injection of derived System.Types that lie about their identity // (and spoof other types), only allow RuntimeTypes. // S.W.M.XamlReader only supports live reflection, anyway. Type runtimeType = typeof(object).GetType(); if (!runtimeType.IsAssignableFrom(type.GetType())) { throw new ArgumentException(SR.Get(SRID.RuntimeTypeRequired, type), "type"); } }
/// <summary> /// Gets the member info of the identifier property for a given entity /// </summary> /// <param name="modelInspector">An instance the model inspector</param> /// <param name="entityType">The type of the entity</param> /// <returns>The member info of the ID property</returns> public static MemberInfo GetIdentifierMember(this IModelInspector modelInspector, Type entityType) { string idPropertyName = GetIdentifierPropertyName(modelInspector, entityType); if (string.IsNullOrEmpty(idPropertyName)) { throw new System.Configuration.ConfigurationErrorsException(string.Format(ExceptionMessages.MemberNotFound, entityType.GetType().FullName)); } return entityType.GetMember(idPropertyName).SingleOrDefault(); }
public ExceptionNotThrownException(Type expectedException, Exception actualException) { if (actualException == null) { message = string.Format("{0} was not thrown", expectedException.ToString()); } else { message = string.Format("{0} was not thrown, but {1} was", expectedException.ToString(),expectedException.GetType().ToString()); } }
/// <summary> /// Initializes a new instance of the <see cref="PostItAttribute"/> class. /// </summary> /// <param name="message">The message to attach to the tagged object.</param> /// <param name="author">An <see cref="AuthorAttribute"/> class representing the author of the message</param> /// <exception cref="ArgumentNullException">Thrown if <paramref name="message"/> or <paramref name="author"/> /// is null</exception> /// <exception cref="ArgumentException">Thrown if <paramref name="author"/> is not derived from <see cref="AuthorAttribute"/></exception> public PostItAttribute(string message, Type author) { if (message == null) throw new ArgumentNullException("message"); if (author == null) throw new ArgumentNullException("author"); if (!typeof(AuthorAttribute).IsAssignableFrom(author.GetType())) throw new ArgumentException("author must derive from AuthorAttribute"); this.message = message; ConstructorInfo ci = TypeHelper.GetConstructor(author, Type.EmptyTypes); this.author = (AuthorAttribute)ci.Invoke(null); }
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> props = base.CreateProperties(type, memberSerialization); if (type.GetType() == typeof(IPAddress)) { var filteredProps = props.Where(p => p.PropertyName.ToLower() != "scopeid"); return filteredProps.ToList(); } return props.Where(p => p.Writable).ToList(); }
// *** ILGenerator api *** public override LocalBuilder DeclareLocal(Type localType, bool pinned) { LocalBuilder localBuilder; if (localType == null) throw new ArgumentNullException("localType"); if (localType.GetType() != typeof(RuntimeType)) throw new ArgumentException(Environment.GetResourceString("Argument_MustBeRuntimeType")); localBuilder = new LocalBuilder(m_localCount, localType, m_methodBuilder); // add the localType to local signature m_localSignature.AddArgument(localType, pinned); m_localCount++; return localBuilder; }
public System.Object GetClass(System.Type classToSearch) { foreach (var item in classes) { if (item.GetType() == classToSearch.GetType()) { return(item); } } Debug.LogError("GetClass(System.Object classToSearch) -> Classe não encontrada!"); return(null); }
public CloningTypeMetadata CreateMetadataForType(Type type) { ClonableAttribute attribute = type.GetType().GetCustomAttributes(typeof(ClonableAttribute), true) .OfType<ClonableAttribute>() .SingleOrDefault(); IFactory factory = GetFactory(attribute); CloningTypeMetadata metadata = new CloningTypeMetadata(type, factory, this); metadata.Clonable = attribute != null; return metadata; }
public static Type[] TypesWithAttribute(Type attribute) { List<Type> types = new List<Type>(); Assembly asm = Assembly.GetEntryAssembly(); foreach (Type t in asm.GetTypes()) { foreach (Attribute attrib in t.GetCustomAttributes(attribute.GetType(), false)) { types.Add(t); } } return types.ToArray(); }
static RtsBrushAssetRecordWrapper() { BindingFlags instanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; _tyBrushAssetRecord = Type.GetType("Rotorz.TileSystem.Editor.BrushAssetRecord,RotorzTileSystemEditor"); _fiBrushAssetRecord_brush = _tyBrushAssetRecord.GetField("brush", instanceBindingFlags); _fiBrushAssetRecord_displayName = _tyBrushAssetRecord.GetField("displayName", instanceBindingFlags); _piBrushAssetRecord_DisplayName = _tyBrushAssetRecord.GetProperty("DisplayName", instanceBindingFlags); _fiBrushAssetRecord_filePath = _tyBrushAssetRecord.GetField("filePath", instanceBindingFlags); _piBrushAssetRecord_AssetPath = _tyBrushAssetRecord.GetProperty("AssetPath", instanceBindingFlags); _fiBrushAssetRecord_master = _tyBrushAssetRecord.GetField("master", instanceBindingFlags); _piBrushAssetRecord_IsMaster = _tyBrushAssetRecord.GetProperty("IsMaster", instanceBindingFlags); }
public object Convert(object value, Type targetType, object parameter, string language) { var not = object.Equals(parameter, "not") || Opposite; if (value is bool && targetType == typeof(Visibility)) { return ((bool)value) != not ? Visibility.Visible : Visibility.Collapsed; } if (value is Visibility && targetType.GetType() == typeof(Boolean)) { return (((Visibility)value) == Visibility.Visible) != not; } return value; }
// based on ideas from http://bradwilson.typepad.com/blog/2009/04/dataannotations-and-aspnet-mvc.html // and code from http://goneale.wordpress.com/2009/03/04/using-metadatatype-attribute-with-aspnet-mvc-xval-validation-framework/ public static IEnumerable<PropertyDescriptor> GetPropertyInfo(Type t) { var metadataAttrib = t.GetCustomAttributes(typeof (MetadataTypeAttribute), true).OfType <MetadataTypeAttribute>().FirstOrDefault(); var buddyClassOrModelClass = metadataAttrib != null ? metadataAttrib.MetadataClassType : t.GetType(); var buddyClassProperties = TypeDescriptor.GetProperties(buddyClassOrModelClass).Cast <PropertyDescriptor>(); return buddyClassProperties; }
/// <summary> /// Get the enum Value /// </summary> /// <param name="enumType"></param> /// <param name="val"></param> /// <returns></returns> public static object GetValue(Type enumType, string val, string defaultVal) { if (!IsValid(enumType, val)) { // Can't do anything if a default value was not supplied. if (string.IsNullOrEmpty(defaultVal)) throw new ArgumentException("Value '" + val + "' is not a valid value for " + enumType.GetType().Name); else return Enum.Parse(enumType, defaultVal, true); } val = val.ToLower().Trim(); string actualValue = _enumMap[enumType.FullName][val]; return Enum.Parse(enumType, actualValue, true); }
/// <summary> /// Adds a service to this <see cref="GameServiceRegistry"/>. /// </summary> /// <param name="type">The type of service to add.</param> /// <param name="provider">The service provider to add.</param> /// <exception cref="System.ArgumentNullException">type;Service type cannot be null</exception> /// <exception cref="System.ArgumentException">Service is already registered;type</exception> public void AddService(Type type, object provider) { if (type == null) throw new ArgumentNullException("type"); if (provider == null) throw new ArgumentNullException("provider"); #if WIN8METRO if (!type.GetTypeInfo().IsAssignableFrom(provider.GetType().GetTypeInfo())) throw new ArgumentException(string.Format("Service [{0}] must be assignable to [{1}]", provider.GetType().FullName, type.GetType().FullName)); #else if (!type.IsAssignableFrom(provider.GetType())) throw new ArgumentException(string.Format("Service [{0}] must be assignable to [{1}]", provider.GetType().FullName, type.GetType().FullName)); #endif lock (registeredService) { if (registeredService.ContainsKey(type)) throw new ArgumentException("Service is already registered", "type"); registeredService.Add(type, provider); } OnServiceAdded(new ServiceEventArgs(type, provider)); }
private static OrderItems.OrderItem GenerateItem(int itemComplexity) { int randomTypeIndex = Random.Range(0, ItemsOrderable.itemTypes.Count); System.Type item = ItemsOrderable.itemTypes[randomTypeIndex]; if (item == typeof(CustomPotion)) { return(GenerateCustomPotion(itemComplexity)); } else if (item == typeof(CustomYokaiMask)) { return(GenerateCustomYokaiMask(itemComplexity)); } Debug.LogError("Error: Item of type '" + item.GetType().ToString() + "' cannot be generated in order."); return(null); }
void OnEnable() { base.title = "RTS: Upgrader"; base.minSize = new Vector2(327, 300); GUISkin skin = EditorGUIUtility.GetBuiltinSkin(EditorSkin.Inspector); _boldWrapStyle = new GUIStyle(skin.label); _boldWrapStyle.fontStyle = FontStyle.Bold; _boldWrapStyle.wordWrap = true; Type tyProductVersion = Type.GetType("Rotorz.TileSystem.ProductInfo,RotorzTileSystem"); if (tyProductVersion != null) { object version = null; PropertyInfo piVersion = tyProductVersion.GetProperty("version", BindingFlags.Public | BindingFlags.Static); if (piVersion != null) { version = piVersion.GetValue(null, null); } else { FieldInfo fiVersion = tyProductVersion.GetField("version", BindingFlags.Public | BindingFlags.Static); version = fiVersion.GetValue(null); } if (version != null) { string originalVersion = (string)(version is System.Version ? (version as System.Version).ToString(3) : version); _welcomeMessage = string.Format( "Thank you for upgrading from version {0} to {1} of Rotorz Tile System!", originalVersion, Rotorz.Tile.ProductInfo.version.ToString(3) ); } } }
public bool HasEventRecipients() { if (null == _thisType) { _thisType = this.GetType(); } foreach (NetRuntimeSystem.Reflection.EventInfo item in _thisType.GetEvents()) { MulticastDelegate eventDelegate = (MulticastDelegate)_thisType.GetType().GetField(item.Name, NetRuntimeSystem.Reflection.BindingFlags.NonPublic | NetRuntimeSystem.Reflection.BindingFlags.Instance).GetValue(this); if ((null != eventDelegate) && (eventDelegate.GetInvocationList().Length > 0)) { return(false); } } return(false); }
static MethodInfo GetMethod(MethodType method_type) { Type layout = Type.GetType("UnityEditor.WindowLayout,UnityEditor"); MethodInfo save = null; MethodInfo load = null; if (layout != null) { load = layout.GetMethod("LoadWindowLayout", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string), typeof(bool) }, null); save = layout.GetMethod("SaveWindowLayout", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static, null, new Type[] { typeof(string) }, null); } if (method_type == MethodType.Save) { return(save); } else { return(load); } }
public DataTable GetWorkFlowNodeList(int InstanceId, string DictionaryCode) { SqlParameter[] parameters = { new SqlParameter("@InstanceId", SqlDbType.Int), new SqlParameter("@DictionaryCode", SqlDbType.VarChar, 50) }; parameters[0].Value = InstanceId; parameters[1].Value = DictionaryCode; DataTable dTable = DbHelperSQL.RunProcedure("Proc_OAWorkFlow_GetWorkFlowNode", parameters, "RetDataSet").Tables[0]; DataColumn NewColumn = new DataColumn(); NewColumn.ColumnName = "RandCode"; NewColumn.DataType = STP.GetType("System.String"); dTable.Columns.Add(NewColumn); foreach (DataRow Row in dTable.Rows) { Row["RandCode"] = Row["InfoId"].ToString(); } return(dTable); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { NodeModel node = null; var obj = JObject.Load(reader); var type = Type.GetType(obj["$type"].Value <string>()); // If we can't find this type - try to look in our load from assemblies, // but only during testing - this is required during testing because some dlls are loaded // using Assembly.LoadFrom using the assemblyHelper - which loads dlls into loadFrom context - // dlls loaded with LoadFrom context cannot be found using Type.GetType() - this should // not be an issue during normal dynamo use but if it is we can enable this code. if (type == null && this.isTestMode == true) { List <Assembly> resultList; var typeName = obj["$type"].Value <string>().Split(',').FirstOrDefault(); // This assemblyName does not usually contain version information... var assemblyName = obj["$type"].Value <string>().Split(',').Skip(1).FirstOrDefault().Trim(); if (assemblyName != null) { if (this.loadedAssemblies.TryGetValue(assemblyName, out resultList)) { var matchingTypes = resultList.Select(x => x.GetType(typeName)).ToList(); type = matchingTypes.FirstOrDefault(); } } } // Check for and attempt to resolve an unknown type before proceeding if (type == null) { // Attempt to resolve the type using `AlsoKnownAs` var unresolvedName = obj["$type"].Value <string>().Split(',').FirstOrDefault(); Type newType; nodeFactory.ResolveType(unresolvedName, out newType); // If resolved update the type if (newType != null) { type = newType; } } // If the id is not a guid, makes a guid based on the id of the node var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value <string>()); var replication = obj["Replication"].Value <string>(); var inPorts = obj["Inputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var resolver = (IdReferenceResolver)serializer.ReferenceResolver; string assemblyLocation = objectType.Assembly.Location; bool remapPorts = true; // If type is still null at this point return a dummy node if (type == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } // Attempt to create a valid node using the type else if (type == typeof(Function)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); CustomNodeDefinition def = null; CustomNodeInfo info = null; bool isUnresolved = !manager.TryGetCustomNodeData(functionId, null, false, out def, out info); Function function = manager.CreateCustomNodeInstance(functionId, null, false, def, info); node = function; if (isUnresolved) { function.UpdatePortsForUnresolved(inPorts, outPorts); } } else if (type == typeof(CodeBlockNodeModel)) { var code = obj["Code"].Value <string>(); CodeBlockNodeModel codeBlockNode = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver); node = codeBlockNode; // If the code block node is in an error state read the extra port data // and initialize the input and output ports if (node.IsInErrorState) { List <string> inPortNames = new List <string>(); var inputs = obj["Inputs"]; foreach (var input in inputs) { inPortNames.Add(input["Name"].ToString()); } // NOTE: This could be done in a simpler way, but is being implemented // in this manner to allow for possible future port line number // information being available in the file List <int> outPortLineIndexes = new List <int>(); var outputs = obj["Outputs"]; int outputLineIndex = 0; foreach (var output in outputs) { outPortLineIndexes.Add(outputLineIndex++); } codeBlockNode.SetErrorStatePortData(inPortNames, outPortLineIndexes); } } else if (typeof(DSFunctionBase).IsAssignableFrom(type)) { var mangledName = obj["FunctionSignature"].Value <string>(); var priorNames = libraryServices.GetPriorNames(); var functionDescriptor = libraryServices.GetFunctionDescriptor(mangledName); string newName; // Update the function descriptor if a newer migrated version of the node exists if (priorNames.TryGetValue(mangledName, out newName)) { functionDescriptor = libraryServices.GetFunctionDescriptor(newName); } // Use the functionDescriptor to try and restore the proper node if possible if (functionDescriptor == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } else { if (type == typeof(DSVarArgFunction)) { node = new DSVarArgFunction(functionDescriptor); // The node syncs with the function definition. // Then we need to make the inport count correct var varg = (DSVarArgFunction)node; varg.VarInputController.SetNumInputs(inPorts.Count()); } else if (type == typeof(DSFunction)) { node = new DSFunction(functionDescriptor); } } } else if (type == typeof(DSVarArgFunction)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); } else if (type.ToString() == "CoreNodeModels.Formula") { node = (NodeModel)obj.ToObject(type); } else { node = (NodeModel)obj.ToObject(type); // if node is an customNode input symbol - assign the element resolver. if (node is Nodes.CustomNodes.Symbol) { (node as Nodes.CustomNodes.Symbol).ElementResolver = ElementResolver; } // We don't need to remap ports for any nodes with json constructors which pass ports remapPorts = false; } if (remapPorts) { RemapPorts(node, inPorts, outPorts, resolver, manager.AsLogger()); } // Cannot set Lacing directly as property is protected node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication)); node.GUID = guid; // Add references to the node and the ports to the reference resolver, // so that they are available for entities which are deserialized later. serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node); foreach (var p in node.InPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } foreach (var p in node.OutPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } return(node); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { NodeModel node = null; var obj = JObject.Load(reader); var type = Type.GetType(obj["$type"].Value <string>()); //if the id is not a guid, makes a guid based on the id of the node var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value <string>()); var replication = obj["Replication"].Value <string>(); var inPorts = obj["Inputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var resolver = (IdReferenceResolver)serializer.ReferenceResolver; if (type == typeof(Function)) { var functionId = Guid.Parse(obj["FunctionUuid"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); RemapPorts(node, inPorts, outPorts, resolver); } else if (type == typeof(CodeBlockNodeModel)) { var code = obj["Code"].Value <string>(); node = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver); RemapPorts(node, inPorts, outPorts, resolver); } else if (typeof(DSFunctionBase).IsAssignableFrom(type)) { var mangledName = obj["FunctionSignature"].Value <string>(); var description = libraryServices.GetFunctionDescriptor(mangledName); if (type == typeof(DSVarArgFunction)) { node = new DSVarArgFunction(description); // The node syncs with the function definition. // Then we need to make the inport count correct var varg = (DSVarArgFunction)node; varg.VarInputController.SetNumInputs(inPorts.Count()); } else if (type == typeof(DSFunction)) { node = new DSFunction(description); } RemapPorts(node, inPorts, outPorts, resolver); } else if (type == typeof(DSVarArgFunction)) { var functionId = Guid.Parse(obj["FunctionUuid"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); RemapPorts(node, inPorts, outPorts, resolver); } else if (type.ToString() == "CoreNodeModels.Formula") { node = (NodeModel)obj.ToObject(type); RemapPorts(node, inPorts, outPorts, resolver); } else { node = (NodeModel)obj.ToObject(type); } //cannot set Lacing directly as property is protected node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication)); node.GUID = guid; // Add references to the node and the ports to the reference resolver, // so that they are available for entities which are deserialized later. serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node); foreach (var p in node.InPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } foreach (var p in node.OutPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } return(node); }
/// <summary> /// Use reflection to access properties that may or may not be defined. /// </summary> private static void PrepareReflection() { BindingFlags instanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; _tyRotorzTileSystem = Type.GetType("Rotorz.TileSystem.RotorzTileSystem,RotorzTileSystem"); // Tile Instance Component _tyTileInstance = Type.GetType("Rotorz.TileSystem.TileInstance,RotorzTileSystem"); if (_tyTileInstance != null) { _fiTileInstance_row = _tyTileInstance.GetField("row", instanceBindingFlags); _fiTileInstance_column = _tyTileInstance.GetField("column", instanceBindingFlags); _piTileInstance_brush = _tyTileInstance.GetProperty("brush", instanceBindingFlags); _fiTileInstance_orientationName = _tyTileInstance.GetField("orientationName", instanceBindingFlags); _fiTileInstance_variationIndex = _tyTileInstance.GetField("variationIndex", instanceBindingFlags); } // Tile Data _tyTileData = Type.GetType("Rotorz.TileSystem.TileData,RotorzTileSystem"); if (_tyTileData != null) { _fiTileData_brush = _tyTileData.GetField("brush", instanceBindingFlags); _fiTileData_gameObject = _tyTileData.GetField("gameObject", instanceBindingFlags); _fiTileData_orientationMask = _tyTileData.GetField("orientationMask", instanceBindingFlags); _fiTileData_variationIndex = _tyTileData.GetField("variationIndex", instanceBindingFlags); } // Tile Systems _miTileSystem_GetTile = _tyRotorzTileSystem.GetMethod("GetTile", instanceBindingFlags, null, new Type[] { typeof(int), typeof(int) }, null); _fiTileSystem_version = _tyRotorzTileSystem.GetField("version", instanceBindingFlags); _fiTileSystem_tileSize = _tyRotorzTileSystem.GetField("tileSize", instanceBindingFlags); _fiTileSystem_rows = _tyRotorzTileSystem.GetField("rows", instanceBindingFlags); _fiTileSystem_columns = _tyRotorzTileSystem.GetField("columns", instanceBindingFlags); _fiTileSystem_activeColumn = _tyRotorzTileSystem.GetField("activeColumn", instanceBindingFlags); _fiTileSystem_activeRow = _tyRotorzTileSystem.GetField("activeRow", instanceBindingFlags); _fiTileSystem_chunkWidth = _tyRotorzTileSystem.GetField("chunkWidth", instanceBindingFlags); if (_fiTileSystem_chunkWidth == null) { _fiTileSystem_chunkWidth = _tyRotorzTileSystem.GetField("_chunkWidth", instanceBindingFlags); } _fiTileSystem_chunkHeight = _tyRotorzTileSystem.GetField("chunkHeight", instanceBindingFlags); if (_fiTileSystem_chunkHeight == null) { _fiTileSystem_chunkHeight = _tyRotorzTileSystem.GetField("_chunkHeight", instanceBindingFlags); } _piTileSystem_chunks = _tyRotorzTileSystem.GetProperty("chunks", instanceBindingFlags); _piTileSystem_strippingPreset = _tyRotorzTileSystem.GetProperty("strippingPreset", instanceBindingFlags); _piTileSystem_strippingOptions = _tyRotorzTileSystem.GetProperty("strippingOptions", instanceBindingFlags); _fiTileSystem_applyRuntimeStripping = _tyRotorzTileSystem.GetField("applyRuntimeStripping", instanceBindingFlags); _fiTileSystem_combineChunkWidth = _tyRotorzTileSystem.GetField("combineChunkWidth", instanceBindingFlags); _fiTileSystem_combineChunkHeight = _tyRotorzTileSystem.GetField("combineChunkHeight", instanceBindingFlags); _fiTileSystem_combineMethod = _tyRotorzTileSystem.GetField("combineMethod", instanceBindingFlags); _fiTileSystem_generateSecondUVs = _tyRotorzTileSystem.GetField("generateSecondUVs", instanceBindingFlags); _fiTileSystem_hintEraseEmptyChunks = _tyRotorzTileSystem.GetField("hintEraseEmptyChunks", instanceBindingFlags); _fiTileSystem_staticVertexSnapping = _tyRotorzTileSystem.GetField("staticVertexSnapping", instanceBindingFlags); }
public EnumDescConverter(System.Type type) : base(type.GetType()) { myVal = type; }
private void GenerateChapterContent(IEntity chapter, string chapterNumber, string alternateTitle, bool pageBreak, IReadOnlyDictionary <string, string> parameters, Document document) { var title = string.IsNullOrWhiteSpace(alternateTitle) ? chapter.Name : alternateTitle; var settings = _config.Descendants("generator").FirstOrDefault(e => e.Attribute("name").Value == chapter.Name); if (settings != null) { var className = settings.Attribute("class").Value; var rotation = false; var margins = DocumentationDefaultValues.Margins; var pageProperties = settings.Descendants("page").SingleOrDefault(); if (pageProperties != null) { rotation = Boolean.Parse(pageProperties.Attribute("rotation").Value); margins = pageProperties.Attribute("margins").Value; } var createdInstance = Activator.CreateInstance(Type.GetType(className)); if (createdInstance is ITableBuilder) { var instance = createdInstance as ITableBuilder; instance.Documentation = Documentation; foreach (var arg in settings.Descendants("parameter")) { var name = arg.Attribute("name").Value; var value = arg.Attribute("value").Value; instance.GetType().GetProperty(name).SetValue(instance, value); } instance.GetType().GetProperty("Parameters").SetValue(instance, parameters); var root = instance.GetType().GetProperty("RootDirectory"); if (root != null) { root.SetValue(instance, RootDirectory); } SetPageFormat(rotation, margins, document); GenerateChapterHeader(title, chapterNumber, alternateTitle, pageBreak, document); Flush(document); if (instance.HasMultipleTables) { foreach (var table in instance.GetTables()) { GenerateChapterHeader(table.Title, chapterNumber + ".1", null, false, document); _parent.Add(table.Table); Flush(document); } } else { document.Add(instance.GetTables().First().Table); } SetPageFormat(false, DocumentationDefaultValues.Margins, document); } } else if (chapter.Name == "Tittel") { GenerateChapterHeader(title, chapterNumber, alternateTitle, pageBreak, document); } }
/// <summary> /// Use reflection to access properties that may or may not be defined. /// </summary> private void PrepareReflection() { BindingFlags instanceBindingFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic; // Brush types _tyBasicTileBrush = Type.GetType("Rotorz.TileSystem.BasicTileBrush,RotorzTileSystem"); _tyOrientedTileBrush = Type.GetType("Rotorz.TileSystem.OrientedTileBrush,RotorzTileSystem"); _tyAliasTileBrush = Type.GetType("Rotorz.TileSystem.AliasTileBrush,RotorzTileSystem"); _tyAtlasTileBrush = Type.GetType("Rotorz.TileSystem.AtlasTileBrush,RotorzTileSystem"); _tyEmptyTileBrush = Type.GetType("Rotorz.TileSystem.EmptyTileBrush,RotorzTileSystem"); // Note: `BasicTileBrush` used to be the base class, then it was later changed // to `TileBrush`, so this may vary now! _tyTileBrush = Type.GetType("Rotorz.TileSystem.TileBrush,RotorzTileSystem"); if (_tyTileBrush == null) { _tyTileBrush = _tyBasicTileBrush; } // Tile Brush if (_tyTileBrush != null) { _fiTileBrush_hideBrush = _tyTileBrush.GetField("hideBrush", instanceBindingFlags); _fiTileBrush_tileGroup = _tyTileBrush.GetField("tileGroup", instanceBindingFlags); _fiTileBrush_userFlags = _tyTileBrush.GetField("_userFlags", instanceBindingFlags); _fiTileBrush_overrideTag = _tyTileBrush.GetField("overrideTag", instanceBindingFlags); _fiTileBrush_overrideLayer = _tyTileBrush.GetField("overrideLayer", instanceBindingFlags); _fiTileBrush_category = _tyTileBrush.GetField("category", instanceBindingFlags); _fiTileBrush_applyPrefabTransform = _tyTileBrush.GetField("applyPrefabTransform", instanceBindingFlags); _fiTileBrush_scaleMode = _tyTileBrush.GetField("scaleMode", instanceBindingFlags); _fiTileBrush_smooth = _tyTileBrush.GetField("smooth", instanceBindingFlags); _fiTileBrush_materialMapFrom = _tyTileBrush.GetField("materialMapFrom", instanceBindingFlags); _fiTileBrush_materialMapTo = _tyTileBrush.GetField("materialMapTo", instanceBindingFlags); _fiTileBrush_coalesce = _tyTileBrush.GetField("coalesce", instanceBindingFlags); _fiTileBrush_coalesceTileGroup = _tyTileBrush.GetField("coalesceTileGroup", instanceBindingFlags); } // Oriented Tile Brush if (_tyOrientedTileBrush != null) { _fiOrientedTileBrush_defaultOrientation = _tyOrientedTileBrush.GetField("defaultOrientation", instanceBindingFlags); _fiOrientedTileBrush_fallbackMode = _tyOrientedTileBrush.GetField("fallbackMode", instanceBindingFlags); _fiOrientedTileBrush_forceOverrideFlags = _tyOrientedTileBrush.GetField("forceOverrideFlags", instanceBindingFlags); } _tyTileBrushOrientation = Type.GetType("Rotorz.TileSystem.TileBrushOrientation,RotorzTileSystem"); if (_tyTileBrushOrientation != null) { _fiTileBrushOrientation_variations = _tyTileBrushOrientation.GetField("variations", instanceBindingFlags); } // Alias Tile Brush if (_tyAliasTileBrush != null) { _fiAliasTileBrush_overrideFlags = _tyAliasTileBrush.GetField("overrideFlags", instanceBindingFlags); _fiAliasTileBrush_overrideTransforms = _tyAliasTileBrush.GetField("overrideTransforms", instanceBindingFlags); _fiAliasTileBrush_aliasOf = _tyAliasTileBrush.GetField("aliasOf", instanceBindingFlags); } // Atlas Tile Brush if (_tyAtlasTileBrush != null) { _fiAtlasTileBrush_atlasTexture = _tyAtlasTileBrush.GetField("atlasTexture", instanceBindingFlags); _fiAtlasTileBrush_atlasTileWidth = _tyAtlasTileBrush.GetField("atlasTileWidth", instanceBindingFlags); _fiAtlasTileBrush_atlasTileHeight = _tyAtlasTileBrush.GetField("atlasTileHeight", instanceBindingFlags); _fiAtlasTileBrush_atlasRow = _tyAtlasTileBrush.GetField("atlasRow", instanceBindingFlags); _fiAtlasTileBrush_atlasColumn = _tyAtlasTileBrush.GetField("atlasColumn", instanceBindingFlags); } // New Base Brush _fiBrush_userFlags = typeof(Brush).GetField("_userFlags", instanceBindingFlags); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { NodeModel node = null; var obj = JObject.Load(reader); var type = Type.GetType(obj["$type"].Value <string>()); //if we can't find this type - try to look in our load from assemblies, //but only during testing - this is required during testing because some dlls are loaded //using Assembly.LoadFrom using the assemblyHelper - which loads dlls into loadFrom context - //dlls loaded with LoadFrom context cannot be found using Type.GetType() - this should //not be an issue during normal dynamo use but if it is we can enable this code. if (type == null && this.isTestMode == true) { List <Assembly> resultList; var typeName = obj["$type"].Value <string>().Split(',').FirstOrDefault(); //this assemblyName does not usually contain version information... var assemblyName = obj["$type"].Value <string>().Split(',').Skip(1).FirstOrDefault().Trim(); if (assemblyName != null) { if (this.loadedAssemblies.TryGetValue(assemblyName, out resultList)) { var matchingTypes = resultList.Select(x => x.GetType(typeName)).ToList(); type = matchingTypes.FirstOrDefault(); } } } // If the id is not a guid, makes a guid based on the id of the node var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value <string>()); var replication = obj["Replication"].Value <string>(); var inPorts = obj["Inputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var resolver = (IdReferenceResolver)serializer.ReferenceResolver; string assemblyLocation = objectType.Assembly.Location; bool remapPorts = true; if (type == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } else if (type == typeof(Function)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); CustomNodeDefinition def = null; CustomNodeInfo info = null; bool isUnresolved = !manager.TryGetCustomNodeData(functionId, null, false, out def, out info); Function function = manager.CreateCustomNodeInstance(functionId, null, false, def, info); node = function; if (isUnresolved) { function.UpdatePortsForUnresolved(inPorts, outPorts); } } else if (type == typeof(CodeBlockNodeModel)) { var code = obj["Code"].Value <string>(); node = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver); } else if (typeof(DSFunctionBase).IsAssignableFrom(type)) { var mangledName = obj["FunctionSignature"].Value <string>(); var functionDescriptor = libraryServices.GetFunctionDescriptor(mangledName); if (functionDescriptor == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } else { if (type == typeof(DSVarArgFunction)) { node = new DSVarArgFunction(functionDescriptor); // The node syncs with the function definition. // Then we need to make the inport count correct var varg = (DSVarArgFunction)node; varg.VarInputController.SetNumInputs(inPorts.Count()); } else if (type == typeof(DSFunction)) { node = new DSFunction(functionDescriptor); } } } else if (type == typeof(DSVarArgFunction)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); } else if (type.ToString() == "CoreNodeModels.Formula") { node = (NodeModel)obj.ToObject(type); } else { node = (NodeModel)obj.ToObject(type); // We don't need to remap ports for any nodes with json constructors which pass ports remapPorts = false; } if (remapPorts) { RemapPorts(node, inPorts, outPorts, resolver); } // Cannot set Lacing directly as property is protected node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication)); node.GUID = guid; // Add references to the node and the ports to the reference resolver, // so that they are available for entities which are deserialized later. serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node); foreach (var p in node.InPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } foreach (var p in node.OutPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } return(node); }
public bool in_caring_state() { return(current.GetType() == typeof(CaringState)); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { NodeModel node = null; var obj = JObject.Load(reader); var type = Type.GetType(obj["$type"].Value <string>()); // If the id is not a guid, makes a guid based on the id of the node var guid = GuidUtility.tryParseOrCreateGuid(obj["Id"].Value <string>()); var replication = obj["Replication"].Value <string>(); var inPorts = obj["Inputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var outPorts = obj["Outputs"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var resolver = (IdReferenceResolver)serializer.ReferenceResolver; string assemblyLocation = objectType.Assembly.Location; bool remapPorts = true; if (type == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } else if (type == typeof(Function)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); CustomNodeDefinition def = null; CustomNodeInfo info = null; bool isUnresolved = !manager.TryGetCustomNodeData(functionId, null, false, out def, out info); Function function = manager.CreateCustomNodeInstance(functionId, null, false, def, info); node = function; if (isUnresolved) { function.UpdatePortsForUnresolved(inPorts, outPorts); } } else if (type == typeof(CodeBlockNodeModel)) { var code = obj["Code"].Value <string>(); node = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver); } else if (typeof(DSFunctionBase).IsAssignableFrom(type)) { var mangledName = obj["FunctionSignature"].Value <string>(); var functionDescriptor = libraryServices.GetFunctionDescriptor(mangledName); if (functionDescriptor == null) { node = CreateDummyNode(obj, assemblyLocation, inPorts, outPorts); } else { if (type == typeof(DSVarArgFunction)) { node = new DSVarArgFunction(functionDescriptor); // The node syncs with the function definition. // Then we need to make the inport count correct var varg = (DSVarArgFunction)node; varg.VarInputController.SetNumInputs(inPorts.Count()); } else if (type == typeof(DSFunction)) { node = new DSFunction(functionDescriptor); } } } else if (type == typeof(DSVarArgFunction)) { var functionId = Guid.Parse(obj["FunctionSignature"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); } else if (type.ToString() == "CoreNodeModels.Formula") { node = (NodeModel)obj.ToObject(type); } else { node = (NodeModel)obj.ToObject(type); // We don't need to remap ports for any nodes with json constructors which pass ports remapPorts = false; } if (remapPorts) { RemapPorts(node, inPorts, outPorts, resolver); } // Cannot set Lacing directly as property is protected node.UpdateValue(new UpdateValueParams("ArgumentLacing", replication)); node.GUID = guid; // Add references to the node and the ports to the reference resolver, // so that they are available for entities which are deserialized later. serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node); foreach (var p in node.InPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } foreach (var p in node.OutPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } return(node); }
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { NodeModel node = null; var obj = JObject.Load(reader); var type = Type.GetType(obj["$type"].Value <string>()); var guid = Guid.Parse(obj["Uuid"].Value <string>()); var displayName = obj["DisplayName"].Value <string>(); //var x = obj["X"].Value<double>(); //var y = obj["Y"].Value<double>(); var inPorts = obj["InputPorts"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var outPorts = obj["OutputPorts"].ToArray().Select(t => t.ToObject <PortModel>()).ToArray(); var resolver = (IdReferenceResolver)serializer.ReferenceResolver; if (type == typeof(Function)) { var functionId = Guid.Parse(obj["FunctionUuid"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); RemapPorts(node, inPorts, outPorts, resolver); } else if (type == typeof(CodeBlockNodeModel)) { var code = obj["Code"].Value <string>(); node = new CodeBlockNodeModel(code, guid, 0.0, 0.0, libraryServices, ElementResolver); RemapPorts(node, inPorts, outPorts, resolver); } else if (typeof(DSFunctionBase).IsAssignableFrom(type)) { var mangledName = obj["FunctionName"].Value <string>(); var description = libraryServices.GetFunctionDescriptor(mangledName); if (type == typeof(DSVarArgFunction)) { node = new DSVarArgFunction(description); // The node syncs with the function definition. // Then we need to make the inport count correct var varg = (DSVarArgFunction)node; varg.VarInputController.SetNumInputs(inPorts.Count()); } else if (type == typeof(DSFunction)) { node = new DSFunction(description); } RemapPorts(node, inPorts, outPorts, resolver); } else if (type == typeof(DSVarArgFunction)) { var functionId = Guid.Parse(obj["FunctionUuid"].Value <string>()); node = manager.CreateCustomNodeInstance(functionId); RemapPorts(node, inPorts, outPorts, resolver); } else if (type == typeof(Formula)) { node = (Formula)obj.ToObject(type); RemapPorts(node, inPorts, outPorts, resolver); } else { node = (NodeModel)obj.ToObject(type); } node.GUID = guid; node.NickName = displayName; //node.X = x; //node.Y = y; // Add references to the node and the ports to the reference resolver, // so that they are available for entities which are deserialized later. serializer.ReferenceResolver.AddReference(serializer.Context, node.GUID.ToString(), node); foreach (var p in node.InPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } foreach (var p in node.OutPorts) { serializer.ReferenceResolver.AddReference(serializer.Context, p.GUID.ToString(), p); } return(node); }
public static IOrderConfirmationParser GetParser(string root, File file) { var doc = XDocument.Load(root + @"\Config\Orders.xml"); IOrderConfirmationParser instance = null; var filename = string.Format("{0}{1}", root, file.GetPath()); var reader = new PdfReader(filename); var strategy = new LocationTextExtractionStrategy(); var text = PdfTextExtractor.GetTextFromPage(reader, 1, strategy); // Replace non-breaking spaces with normal spaces text = text.Replace('\u00A0', ' '); var nodes = doc.Descendants("order"); var actualNode = nodes.FirstOrDefault(n => { var vendor = n.Descendants("vendor").FirstOrDefault(); if (vendor != null) { var vendorName = vendor.Attribute("value").Value; var hint = vendor.Attribute("hint"); return(text.Contains(vendorName) || (hint != null && text.Contains(hint.Value))); } return(false); }); if (actualNode != null) { var vendorName = actualNode.Descendants("vendor").First().Attribute("value").Value; var className = actualNode.Attribute("class"); if (className == null) { throw new ArgumentException("No order confirmation parser found for vendor " + vendorName); } var type = Type.GetType(className.Value, true); instance = Activator.CreateInstance(type, root, file.GetPath()) as IOrderConfirmationParser; instance.VendorName = vendorName; foreach (var arg in actualNode.Descendants("parameter")) { var name = arg.Attribute("name").Value; var value = arg.Attribute("value").Value; var property = type.GetProperty(name); if (property != null) { if (name.StartsWith("PdfConverterRules") && arg.Attribute("extend") != null && Boolean.Parse(arg.Attribute("extend").Value)) { property.SetValue(instance, TableFileExtender.ExtendFile(root, value, 25)); } else { property.SetValue(instance, value); } } else { throw new ArgumentException("Parameter " + name + " not found on type " + type.Name); } } } return(instance); }
/// <summary>Creates an explicitly non-HA-enabled proxy object.</summary> /// <remarks> /// Creates an explicitly non-HA-enabled proxy object. Most of the time you /// don't want to use this, and should instead use /// <see cref="CreateProxy{T}(Org.Apache.Hadoop.Conf.Configuration, Sharpen.URI, System.Type{T}) /// "/> /// . /// </remarks> /// <param name="conf">the configuration object</param> /// <param name="nnAddr">address of the remote NN to connect to</param> /// <param name="xface">the IPC interface which should be created</param> /// <param name="ugi">the user who is making the calls on the proxy object</param> /// <param name="withRetries">certain interfaces have a non-standard retry policy</param> /// <param name="fallbackToSimpleAuth"> /// - set to true or false during this method to /// indicate if a secure client falls back to simple auth /// </param> /// <returns> /// an object containing both the proxy and the associated /// delegation token service it corresponds to /// </returns> /// <exception cref="System.IO.IOException"/> public static NameNodeProxies.ProxyAndInfo <T> CreateNonHAProxy <T>(Configuration conf , IPEndPoint nnAddr, UserGroupInformation ugi, bool withRetries, AtomicBoolean fallbackToSimpleAuth ) { System.Type xface = typeof(T); Text dtService = SecurityUtil.BuildTokenService(nnAddr); T proxy; if (xface == typeof(ClientProtocol)) { proxy = (T)CreateNNProxyWithClientProtocol(nnAddr, conf, ugi, withRetries, fallbackToSimpleAuth ); } else { if (xface == typeof(JournalProtocol)) { proxy = (T)CreateNNProxyWithJournalProtocol(nnAddr, conf, ugi); } else { if (xface == typeof(NamenodeProtocol)) { proxy = (T)CreateNNProxyWithNamenodeProtocol(nnAddr, conf, ugi, withRetries); } else { if (xface == typeof(GetUserMappingsProtocol)) { proxy = (T)CreateNNProxyWithGetUserMappingsProtocol(nnAddr, conf, ugi); } else { if (xface == typeof(RefreshUserMappingsProtocol)) { proxy = (T)CreateNNProxyWithRefreshUserMappingsProtocol(nnAddr, conf, ugi); } else { if (xface == typeof(RefreshAuthorizationPolicyProtocol)) { proxy = (T)CreateNNProxyWithRefreshAuthorizationPolicyProtocol(nnAddr, conf, ugi); } else { if (xface == typeof(RefreshCallQueueProtocol)) { proxy = (T)CreateNNProxyWithRefreshCallQueueProtocol(nnAddr, conf, ugi); } else { string message = "Unsupported protocol found when creating the proxy " + "connection to NameNode: " + ((xface != null) ? xface.GetType().FullName : "null"); Log.Error(message); throw new InvalidOperationException(message); } } } } } } } return(new NameNodeProxies.ProxyAndInfo <T>(proxy, dtService, nnAddr)); }
public List <T> GetElementsFromTransversal(string fromId, string edgeName) { List <T> listOfObjects = new List <T>(); Type thisType = typeof(T); Attribute att; object edgePropertyValue; List <Property> edgeProperties; string transversalQuery = $"g.V('{fromId}').out('{edgeName}')"; string getEdgeQuery = string.Empty; if (thisType != typeof(GraphObject)) { transversalQuery = transversalQuery + $".hasLabel('{thisType.Name}')"; } foreach (Vertex vertex in ExecuteCommandQueryVertex(transversalQuery)) { if (thisType == typeof(GraphObject)) { thisType = Type.GetType($"DAL_CV_Fiches.Models.Graph.{vertex.Label}"); } T embeddedObject = GetObjectFromVertex(vertex, thisType); foreach (PropertyInfo propInfo in thisType.GetProperties()) { att = propInfo.GetCustomAttribute(typeof(EdgeProperty)); if (att != null) { getEdgeQuery = $"g.V('{fromId}').outE('{edgeName}').where(inV().has('id', '{embeddedObject.GraphKey}'))"; foreach (Microsoft.Azure.Graphs.Elements.Edge edge in ExecuteCommandQueryEdge(getEdgeQuery)) { try { edgeProperties = edge.GetProperties().ToList(); } catch (NullReferenceException) { continue; } if (edgeProperties.Any(x => x.Key == propInfo.Name)) { edgePropertyValue = edgeProperties.First(x => x.Key == propInfo.Name).Value; if (propInfo.PropertyType.BaseType == typeof(Enum)) { propInfo.SetValue(embeddedObject, Convert.ToInt32(edgePropertyValue)); } else if (propInfo.PropertyType == typeof(DateTime)) { propInfo.SetValue(embeddedObject, DateTime.Parse(edgePropertyValue.ToString())); } else { propInfo.SetValue(embeddedObject, Convert.ChangeType(edgePropertyValue, propInfo.PropertyType)); } } } } } listOfObjects.Add(embeddedObject); } return(listOfObjects); }
protected virtual void OnPropertyNotFound(string propertyName) { throw new PropertyNotFoundException(_resultClass.GetType(), propertyName, "setter"); }