Ejemplo n.º 1
0
        public void AllEntitiesInheritEntityBase()
        {
            var failed = false;
            var exclusions = new Type[] { };
            foreach (var testType in TestTypes)
            {
                var types =
                    testType.Assembly.GetTypes().Where(t => t.Namespace.IfNullOrEmpty("").Contains(".Entities")).OrderBy(t => t.Name);
                foreach (var type in types)
                {
                    if (exclusions.Contains(type) || type.IsAbstract || type.IsSealed || type.IsEnum || type.Namespace.IfNullOrEmpty("").EndsWith("Entities.Components"))
                        continue;

                    if(typeof (EntityBase).IsAssignableFrom(type))
                    {
                        Debug.WriteLine("PASS | " + type.Name);
                        continue;
                    }

                    failed = true;
                    Debug.WriteLine("FAIL | " + type.Name);
                }
            }
            Assert.IsFalse(failed);
        }
Ejemplo n.º 2
0
        public static HbmMapping LoadMappingFrom(params Assembly[] assemblies)
        {
            Require.NotNull(assemblies, "assemblies");

            var baseTypes = new Type[] {
                typeof(ClassMapping<>),
                typeof(JoinedSubclassMapping<>),
                typeof(UnionSubclassMapping<>),
                typeof(SubclassMapping<>)
            };

            var mapper = new ModelMapper();

            foreach (var asm in assemblies)
            {
                foreach (var type in asm.GetTypes())
                {
                    if (!type.IsClass || type.IsAbstract || type.IsInterface || !type.BaseType.IsGenericType) continue;

                    if (!baseTypes.Contains(type.BaseType.GetGenericTypeDefinition())) continue;

                    mapper.AddMapping(type);
                }
            }

            var mapping = mapper.CompileMappingForAllExplicitlyAddedEntities();
            mapping.autoimport = false;

            return mapping;
        }
Ejemplo n.º 3
0
		/// <inheritdoc />
		public object CreateProxy (Type baseType, Type[] implementedInterfaces, object[] constructorArguments)
		{
			if (baseType.IsInterface) {
				// TODO: should Moq.Core do this work? It's the same for 
				// Castle and LinFu and presumably other (future?) libraries

				var fixedInterfaces = new Type[implementedInterfaces.Length + 1];
				fixedInterfaces[0] = baseType;
				implementedInterfaces.CopyTo (fixedInterfaces, 1);
				implementedInterfaces = fixedInterfaces;
				baseType = typeof (object);
			}

			if (!implementedInterfaces.Contains(typeof(IProxy))) {
				var fixedInterfaces = new Type[implementedInterfaces.Length + 1];
				fixedInterfaces[0] = typeof(IProxy);
				implementedInterfaces.CopyTo (fixedInterfaces, 1);
				implementedInterfaces = fixedInterfaces;
			}

			// TODO: the proxy factory should automatically detect requests to proxy 
			// delegates and generate an interface on the fly for them, without Moq 
			// having to know about it at all.

			return generator.CreateClassProxy (baseType, implementedInterfaces, proxyOptions, constructorArguments, new Interceptor ());
		}
Ejemplo n.º 4
0
		public object CreateProxy (Type baseType, Type[] implementedInterfaces, object[] constructorArguments)
		{
			if (baseType.IsInterface) {
				// TODO: should Moq.Core do this work? It's the same for 
				// Castle and LinFu and presumably other (future?) libraries

				var fixedInterfaces = new Type[implementedInterfaces.Length + 1];
				fixedInterfaces[0] = baseType;
				implementedInterfaces.CopyTo (fixedInterfaces, 1);
				implementedInterfaces = fixedInterfaces;
				baseType = typeof (object);
			}

			// TODO: this code is duplicated exactly from the Castle proxy factory.
			if (!implementedInterfaces.Contains (typeof (IProxy))) {
				var fixedInterfaces = new Type[implementedInterfaces.Length + 1];
				fixedInterfaces[0] = typeof (IProxy);
				implementedInterfaces.CopyTo (fixedInterfaces, 1);
				implementedInterfaces = fixedInterfaces;
			}

			// TODO: the proxy factory should automatically detect requests to proxy 
			// delegates and generate an interface on the fly for them, without Moq 
			// having to know about it at all.

			// NOTE: LinFu doesn't support passing ctor args??!?!?!
			if (constructorArguments.Length != 0)
				throw new NotSupportedException ();

			return factory.CreateProxy(baseType, new Interceptor (), implementedInterfaces);
		}
Ejemplo n.º 5
0
        /// <summary>
        /// 
        /// </summary>
        /// <param name="attributes">The list of available attributes</param>
        /// <param name="container">This is the type of container we are searchig attributes for.</param>
        /// <returns>The attributes matching the <see cref="EdiStructureType"/></returns>
        public static IEnumerable<EdiAttribute> OfType(this IEnumerable<EdiAttribute> attributes, EdiStructureType container) {
            var typesToSearch = new Type[0];
            switch (container) {
                case EdiStructureType.None:
                case EdiStructureType.Interchange:
                    break;
                case EdiStructureType.Group:
                    typesToSearch = new [] { typeof(EdiGroupAttribute) };
                    break;
                case EdiStructureType.Message:
                    typesToSearch = new [] { typeof(EdiMessageAttribute) };
                    break;
                case EdiStructureType.SegmentGroup:
                    typesToSearch = new [] { typeof(EdiSegmentGroupAttribute) };
                    break;
                case EdiStructureType.Segment:
                    typesToSearch = new [] { typeof(EdiSegmentAttribute), typeof(EdiSegmentGroupAttribute) };
                    break;
                case EdiStructureType.Element:
                    typesToSearch = new [] { typeof(EdiElementAttribute) };
                    break;
                default:
                    break;
            }

            return null == typesToSearch ? Enumerable.Empty<EdiAttribute>() : attributes.Where(a => typesToSearch.Contains(a.GetType()));
        }
 public bool HasSupportFor(Type[] scenarios)
 {
     if (IsTravis && scenarios.Contains(Type.Integration))
     {
         return false;
     }
     return true;
 }
        private static Type FindCommandTypeInMethodParameters(Type[] commandTypes, MethodInfo handlerMethod)
        {
            var commandParam =
                handlerMethod.GetParameters().FirstOrDefault(p => commandTypes.Contains(p.ParameterType));
            if (commandParam != null)
                return commandParam.ParameterType;

            return null;
        }
Ejemplo n.º 8
0
        private void InitializeCaches(string expressionStringValue)
        {
            var parser = new ExpressionParser();

            cachedExpressionString = expressionStringValue;
            cachedExpression       = parser.EvaluateExpression(cachedExpressionString.ToLower());

            System.Type[] types = new System.Type[inputs.Length];
            for (int i = 0; i < inputs.Length; i++)
            {
                types[i] = inputs[i].GetVariable(this).Type;
                if (types[i] != typeof(int) && types[i] != typeof(float) && types[i] != typeof(Vector2) && types[i] != typeof(Vector3))
                {
                    Debug.LogError("Expression Action only supports int, float, Vector2 and Vector3 variables!");
                }
            }

            if (types.Contains(typeof(Vector2)) && types.Contains(typeof(Vector3)))
            {
                Debug.LogError("Expression Action can't use Vector2 and Vector3 simultaneously!");
            }

            if (types.Contains(typeof(Vector3)))
            {
                evaluatedOutputType  = typeof(Vector3);
                outputComponentCount = 3;
            }
            else if (types.Contains(typeof(Vector2)))
            {
                evaluatedOutputType  = typeof(Vector2);
                outputComponentCount = 2;
            }
            else if (types.Contains(typeof(float)))
            {
                evaluatedOutputType  = typeof(float);
                outputComponentCount = 1;
            }
            else
            {
                evaluatedOutputType  = typeof(int);
                outputComponentCount = 1;
            }
        }
        private bool IsBetterChoice(ConstructorInfo current, ConstructorInfo candidate, Type[] existingTypes)
        {
            if (current == null)
                return true;

            if (candidate.GetParameters()
                         .Where(x => !existingTypes.Contains(x.ParameterType))
                         .Any(x => x.ParameterType.IsSealed && !x.ParameterType.IsArray))
                return false;

            return current.GetParameters().Length < candidate.GetParameters().Length;
        }
Ejemplo n.º 10
0
        public static string ToJson(this object entityClass)
        {
            JObject json = new JObject();

            Type[] MainProperties = new Type[] {
                typeof(bool),
                typeof(string),
                typeof(long),
                typeof(int),
                typeof(Int32),
                typeof(double),
                typeof(float)
            };
            // Is a Simple Class
            Type t = entityClass.GetType();

            foreach (PropertyInfo info in t.GetProperties())
            {
                // is System Main type of [Custom Type]

                if (!MainProperties.Contains(info.PropertyType))
                {
                    string innerClassJson = info.GetValue(entityClass).ToJson();
                    json.Add(info.Name.ToLower(), innerClassJson);
                }
                else
                {
                    Type propertytype = info.PropertyType;
                    if (propertytype == typeof(string))
                    {
                        json.Add(info.Name.ToLower(), info.GetValue(entityClass) == null ? "" : info.GetValue(entityClass).ToString());
                    }
                    else if (propertytype == typeof(int))
                    {
                        json.Add(info.Name.ToLower(), int.Parse(info.GetValue(entityClass).ToString()));
                    }
                    else if (propertytype == typeof(long))
                    {
                        json.Add(info.Name.ToLower(), long.Parse(info.GetValue(entityClass).ToString()));
                    }
                    else if (propertytype == typeof(double))
                    {
                        json.Add(info.Name.ToLower(), float.Parse(info.GetValue(entityClass).ToString()));
                    }
                    else if (propertytype == typeof(bool))
                    {
                        json.Add(info.Name.ToLower(), bool.Parse(info.GetValue(entityClass).ToString()));
                    }
                }
            }
            return(json.ToString().Replace("\\\"", "\"").Replace("\"[", "[").Replace("]\"", "]").Replace("\"{", "{").Replace("}\"", "}").Replace("\r\n", ""));
        }
Ejemplo n.º 11
0
		/// <summary>
		/// Search an IQueryable's fields for the keywords (objects) - this does not iterate through levels of an object
		/// </summary>
		/// <param name="list_to_search">IQueryable to search</param>
		/// <param name="types_to_explore">array of types to search, others will be ignored</param>
		/// <param name="keywords">objects to search for</param>
		/// <returns>IQueryable of the inputed type filtered by the search specifications</returns>
		public static IQueryable Search( this IQueryable list_to_search, Type[] types_to_explore, object[] keywords )
		{
			list_to_search.NotNull();
			Dictionary<string, Type> dic = new Dictionary<string, Type>();
			foreach( var item in list_to_search.Take( 1 ) )
			{
				foreach( PropertyInfo pi in item.GetType().GetProperties() )
				{
					if( types_to_explore.Contains( pi.PropertyType ) )
					{
						dic.Add( pi.Name, pi.PropertyType );
					}
				}
			}
			return list_to_search.Search( dic, keywords );
		}
Ejemplo n.º 12
0
        public static bool Contains(this Exception e, Type[] exceptionTypes)
        {
            bool result = false;

            while (e != null)
            {
                if (exceptionTypes.Contains(e.GetType()))
                {
                    result = true;
                    break;
                }
                e = e.InnerException;
            }

            return result;
        }
Ejemplo n.º 13
0
        public void AllEntitiesInitializeComponents()
        {
            var failed = false;
            var exclusions = new Type[] { };
            foreach (var testType in TestTypes)
            {
                var types =
                    testType.Assembly.GetTypes().Where(t => t.Namespace.IfNullOrEmpty("").Contains(".Entities")).OrderBy(t => t.Name);
                foreach (var type in types)
                {
                    if (exclusions.Contains(type) || type.IsAbstract || type.IsSealed || type.IsEnum || type.Namespace.IfNullOrEmpty("").EndsWith("Entities.Components"))
                        continue;

                    if (typeof(EntityBase).IsAssignableFrom(type))
                    {
                        var components = type.GetProperties(BindingFlags.Instance | BindingFlags.Public)
                            .Where(t => t.PropertyType.Namespace.EndsWith("Entities.Components"));

                        if (components.Any())
                        {
                            var obj = Activator.CreateInstance(type);
                            foreach (var list in components)
                            {
                                var val = list.GetValue(obj, null);
                                if (val == null)
                                {
                                    Debug.WriteLine("FAIL | " + type.Name + "." + list.Name);
                                    failed = true;
                                }
                                else
                                    Debug.WriteLine("PASS | " + type.Name + "." + list.Name);
                            }
                        }
                    }
                }
            }
            Assert.IsFalse(failed);
        }
Ejemplo n.º 14
0
        /*
         * output - a destination to write results out to. To write output
         * to the standard output, pass in System.Console.Out
         */
        public static void Run(TextWriter output, Result result)
        {
            Assert.Output = output;
              Suite suite = new Suite();
              Type[] entryAssemblyTypes = Assembly.GetEntryAssembly().GetTypes();
              Type[] forbiddenTypes = new Type[] {
            GetTypeFromAssemblyTypes(entryAssemblyTypes, "TestRunner")
              , GetTypeFromAssemblyTypes(entryAssemblyTypes, "WasRunObj")
              , GetTypeFromAssemblyTypes(entryAssemblyTypes, "WasRunSetUpFailed")
              };

              foreach (Type t in entryAssemblyTypes) {
            if (t.IsSubclassOf(typeof(TDDUnit.Case))
              && !forbiddenTypes.Contains(t)) {
              suite.Add(t);
            }
              }

              foreach (string test in suite.FailedTests(result)) {
            output.WriteLine("Failed: " + test);
              }
              output.WriteLine(result.Summary);
        }
Ejemplo n.º 15
0
 public bool AnyOnStack(Type[] parsedTypes)
 {
     return _stack.Any(partial =>
     {
         return parsedTypes.Contains(partial.GetType());
     });
 }
Ejemplo n.º 16
0
        private static bool TryGetGenericType(this Type type, Type[] acceptableTypes, out Type collectionOf)
        {
            if (!type.IsGenericType)
            {
                collectionOf = null;
                return false;
            }

            var genericType = type.GetGenericTypeDefinition();
            if (acceptableTypes.Contains(genericType))
            {
                collectionOf = type.GetGenericArguments()[0];
                return true;
            }

            collectionOf = null;
            return false;
        }
Ejemplo n.º 17
0
    private static void VerifyDependencies()
    {
        var gameObjects = GameObject.FindObjectsOfType(typeof(GameObject)).Where(go => go.name != "[SaveIt]").ToArray();
        var usableDependencyTypes = new System.Type[]
            {
                typeof(Mesh),
                typeof(Material),
                typeof(PhysicMaterial),
                typeof(Shader),
                typeof(Texture),
                typeof(Texture2D),
                typeof(AudioClip),
                typeof(ProceduralMaterial),
                typeof(AnimationClip),
                typeof(Font)
            };
        var dependencies = EditorUtility.CollectDependencies(gameObjects)
            .Where(dependency1 =>
            {
                if (dependency1 == null)
                {
                    return false;
                }
                var want = usableDependencyTypes.Contains(dependency1.GetType());
                return want;
            })
            .Union(new Object[] { new PhysicMaterial() { name = "Default" } })
            .Select(dependency2 =>
            {
                var path = AssetDatabase.GetAssetPath(dependency2);
                if (string.IsNullOrEmpty(path))
                {
                    path = "$" + dependency2.name;
                }
                return new ResourceEntry()
                {
                    Name = dependency2.name,
                    Resource = dependency2,
                    TypeName = dependency2.GetType().FullName
                };
            });

        dependencies = dependencies.Union(GameObject.FindObjectsOfType(typeof(Saveable))
            .Where(saveable => ((Saveable)saveable).Prefab != null)
            .Select(saveable =>
            {
                var prefab = ((Saveable)saveable).Prefab;
                return new ResourceEntry()
                {
                    Name = prefab.name,
                    Resource = prefab,
                    TypeName = prefab.GetType().FullName
                };
            }));

        var saveItGameObject = (GameObject)GameObject.Find("[SaveIt]");
        if (saveItGameObject == null)
        {
            saveItGameObject = new GameObject("[SaveIt]");
        }
        var saveItComponent = saveItGameObject.GetComponent<SaveItComponent>();
        if (saveItComponent == null)
        {
            saveItComponent = saveItGameObject.AddComponent<SaveItComponent>();
        }

        saveItComponent.ResourceEntries = dependencies.Distinct().ToArray();
    }
        /// <summary>
        /// Returns code to instantiate an equivalent instance of the given value
        /// </summary>
        /// <param name="value">value to instantiate</param>
        /// <returns>code to instantiate the value</returns>
        private string ConvertToCode(object value)
        {
            Globalization.CultureInfo realCulture = Globalization.CultureInfo.CurrentCulture;

            // null is easy
            //
            if (value == null)
                return "null";

            try
            { 
                System.Threading.Thread.CurrentThread.CurrentCulture = Globalization.CultureInfo.InvariantCulture;

                // switch based on the type
                Type type = value.GetType();
                Type[] simpleTypes = new Type[] { typeof(bool), typeof(int) };
                Type[] castTypes = new Type[] { typeof(byte), typeof(short), typeof(ushort), typeof(sbyte) };

                if (simpleTypes.Contains(type))
                    return value.ToString().ToLower();
                else if (castTypes.Contains(type))
                    return "(" + type.FullName + ")(" + value.ToString() + ")";
                else if (type == typeof(uint))
                    return value.ToString() + "U";
                else if (type == typeof(long))
                    return value.ToString() + "L";
                else if (type == typeof(ulong))
                    return value.ToString() + "UL";
                else if (type == typeof(decimal))
                    return value.ToString() + "M";
                else if (type == typeof(float))
                {
                    if (float.IsNegativeInfinity((float)value))
                        return "float.NegativeInfinity";
                    if (float.IsPositiveInfinity((float)value))
                        return "float.PositiveInfinity";
                    if (float.IsNaN((float)value))
                        return "float.NaN";
                    if ((float)value == float.MaxValue)
                        return "float.MaxValue";
                    if ((float)value == float.MinValue)
                        return "float.MinValue";
                    return value.ToString() + "f";
                }
                else if (type == typeof(double))
                {
                    if (double.IsNegativeInfinity((double)value))
                        return "double.NegativeInfinity";
                    if (double.IsPositiveInfinity((double)value))
                        return "double.PositiveInfinity";
                    if (double.IsNaN((double)value))
                        return "double.NaN";
                    if ((double)value == double.MaxValue)
                        return "double.MaxValue";
                    if ((double)value == double.MinValue)
                        return "double.MinValue";
                    return value.ToString() + "d";
                }
                else if (type == typeof(string))
                    return "\"" + value + "\"";
                else if (type == typeof(byte[]))
                    return "new byte[] { " + string.Join(", ", (value as byte[]).Select(b => b.ToString()).ToArray()) + "}";
                else if (type == typeof(Guid))
                    return "new Guid(\"" + value.ToString() + "\")";
                else if (type == typeof(DateTime))
                {
                    DateTime dt = (DateTime)value;
                    return "new DateTime(" + dt.Ticks + ", DateTimeKind." + dt.Kind.ToString() + ")";
                }
                else
                {
                    // may need to add more cases in the future, for now this is sufficient
                    throw new NotSupportedException();
                }
            }
            finally
            {
                System.Threading.Thread.CurrentThread.CurrentCulture = realCulture;
            }
        }
 private static bool CheckIfAllowedTemplatesContainsDefaultTemplate(Type[] allowedTemplates, Type defaultTemplate)
 {
     return (allowedTemplates.Any() && !allowedTemplates.Contains(defaultTemplate));
 }
Ejemplo n.º 20
0
        public async Task LoginAsync(UserStatus initialStatus = UserStatus.Online)
        {

            await @lock.WriterLockAsync();

            try
            {

                if (IsLoggedIn)
                    return;

                IConnection connection = null;
                ConnectionStream stream = null;
                CommandReader reader = null;
                CommandWriter writer = null;
                ResponseTracker responseTracker = null;
                IConnectableObservable<Command> commands = null;
                IDisposable commandsDisposable = null;

                int transferCount = 0;

                SocketEndPoint endPoint = SocketEndPoint.Parse("messenger.hotmail.com:1863");

                string authTicket = null;

                while (authTicket == null)
                {

                    connection = new SocketConnection();

                    await connection.ConnectAsync(endPoint);

                    stream = new ConnectionStream(connection);

                    writer = new CommandWriter(stream);
                    reader = new CommandReader(stream, new Dictionary<string, Type> {
                        { "VER", typeof(VersionCommand) },
                        { "CVR", typeof(ClientVersionCommand) },
                        { "USR", typeof(AuthenticateCommand) },
                        { "XFR", typeof(TransferCommand) },
                        { "SYN", typeof(SynchronizeCommand) },
                        { "SBS", typeof(SbsCommand) },
                        { "MSG", typeof(MessageCommand) },
                        { "LST", typeof(UserCommand) },
                        { "LSG", typeof(GroupCommand) },
                        { "BPR", typeof(UserPropertyCommand) },
                        { "BLP", typeof(PrivacySettingCommand) },
                        { "GTC", typeof(PrivacySettingCommand) },
                        { "CHG", typeof(ChangeStatusCommand) },
                        { "UBX", typeof(BroadcastCommand) },
                        { "PRP", typeof(LocalPropertyCommand) },
                        { "NLN", typeof(UserOnlineCommand) },
                        { "ILN", typeof(InitialUserOnlineCommand) },
                        { "FLN", typeof(UserOfflineCommand) },
                        { "UUX", typeof(SendBroadcastCommand) },
                        { "NOT", typeof(NotificationCommand) },
                        { "QNG", typeof(PingCommand) },
                        { "CHL", typeof(ChallengeCommand) },
                        { "ADC", typeof(AddContactCommand) },
                        { "REM", typeof(RemoveContactCommand) },
                        { "ADG", typeof(AddGroupCommand) },
                        { "RMG", typeof(RemoveGroupCommand) },
                        { "REG", typeof(RenameGroupCommand) },  
                        { "QRY", typeof(AcceptChallengeCommand) },  
                        { "RNG", typeof(RingCommand) },
                        { "SBP", typeof(ChangeUserPropertyCommand) },
                        { "IMS", typeof(EnableIMCommand) },
                    });
                    
                    commands = reader.GetReadObservable().Publish();
                    responseTracker = new ResponseTracker(writer, commands);

                    commandsDisposable = commands.Connect();

                    var versionCommand = new VersionCommand("MSNP12");
                    var versionResponse = await responseTracker.GetResponseAsync<VersionCommand>(versionCommand, defaultTimeout);

                    if (versionResponse.Versions.Length == 0)
                        throw new ProtocolNotAcceptedException();

                    var clientVersionCommand = new ClientVersionCommand
                    {
                        LocaleId = "0x0409",
                        OsType = "winnt",
                        OsVersion = "5.0",
                        Architecture = "1386",
                        LibraryName = "MSMSGS",
                        ClientVersion = "5.0.0482",
                        ClientName = "WindowsMessenger",
                        LoginName = credentials.LoginName,
                    };

                    await responseTracker.GetResponseAsync<ClientVersionCommand>(clientVersionCommand, defaultTimeout);

                    var userCommand = new AuthenticateCommand("TWN", "I", credentials.LoginName);
                    var userResponse = await responseTracker.GetResponseAsync(userCommand, new Type[] { typeof(AuthenticateCommand), typeof(TransferCommand) }, defaultTimeout);

                    if (userResponse is AuthenticateCommand)
                    {
                        authTicket = (userResponse as AuthenticateCommand).Argument;
                    }

                    else if (userResponse is TransferCommand)
                    {
                        
                        TransferCommand transferResponse = userResponse as TransferCommand;

                        if (transferCount > 3)
                            throw new InvalidOperationException("The maximum number of redirects has been reached.");

                        transferCount++;

                        endPoint = SocketEndPoint.Parse(transferResponse.Host);

                        commandsDisposable.Dispose();

                        reader.Close();
                        writer.Close();
                        connection.Dispose();

                    }

                }

                PassportAuthentication auth = new PassportAuthentication();

                string authToken = await auth.GetToken(credentials.LoginName, credentials.Password, authTicket);

                var authCommand = new AuthenticateCommand("TWN", "S", authToken);
                var authResponse = await responseTracker.GetResponseAsync<AuthenticateCommand>(authCommand, defaultTimeout);

                var synCommand = new SynchronizeCommand(syncTimeStamp1 ?? "0", syncTimeStamp2 ?? "0");
                var synResponse = await responseTracker.GetResponseAsync<SynchronizeCommand>(synCommand, defaultTimeout);

                IDisposable syncCommandsSubscription = null;
                List<Command> syncCommands = null;

                if (synResponse.TimeStamp1 != syncTimeStamp1 || synResponse.TimeStamp2 != syncTimeStamp2)
                {

                    syncCommands = new List<Command>();

                    Type[] syncTypes = new Type[] { 
                        typeof(MessageCommand), 
                        typeof(UserCommand), 
                        typeof(GroupCommand), 
                        typeof(LocalPropertyCommand), 
                        typeof(PrivacySettingCommand),
                    };

                    syncCommandsSubscription = commands
                        .Where(c => syncTypes.Contains(c.GetType()))
                        .Catch(Observable.Empty<Command>())
                        .Subscribe(c => syncCommands.Add(c));

                    //if we're expecting users/groups, wait for them before we proceed
                    if (synResponse.UserCount + synResponse.GroupCount > 0)
                    {

                        await commands
                            .Where(c => c is UserCommand || c is GroupCommand)
                            .Take(synResponse.UserCount + synResponse.GroupCount)
                            .Timeout(defaultTimeout);

                    }

                }

                UserCapabilities capabilities = 0;
                MSNObject displayPicture = MSNObject.Empty;

                if (LocalUser != null)
                {
                    capabilities = LocalUser.Capabilities;
                    displayPicture = LocalUser.DisplayPicture;
                }

                Command changeStatusCommand = new ChangeStatusCommand(User.StatusToString(UserStatus.Online), (uint)capabilities, displayPicture != MSNObject.Empty ? displayPicture.ToString() : "0");
                await responseTracker.GetResponseAsync(changeStatusCommand, defaultTimeout);

                if (syncCommandsSubscription != null)
                    syncCommandsSubscription.Dispose();

                this.writer = writer;
                this.reader = reader;
                this.stream = stream;
                this.connection = connection;
                this.responseTracker = responseTracker;
                this.commands = commands;
                this.commandsDisposable = commandsDisposable;

                if (LocalUser == null)
                {
                    LocalUser = new LocalUser(this, credentials.LoginName);
                    userCache.Add(credentials.LoginName, new WeakReference(LocalUser));
                }

                LocalUser.Status = initialStatus;

                SyncEvents syncEvents = null;

                if (syncCommands != null)
                {
                    syncTimeStamp1 = synResponse.TimeStamp1;
                    syncTimeStamp2 = synResponse.TimeStamp2;

                    syncEvents = ProcessSyncCommands(syncCommands);
                }

                var commandsSafe = commands
                    .Catch<Command, ConnectionErrorException>(tx => Observable.Empty<Command>());

                commandsSafe.OfType<MessageCommand>().Subscribe(cmd => HandleMessages(cmd, connection));
                commandsSafe.OfType<RingCommand>().Subscribe(cmd => HandleRings(cmd, connection));
                commandsSafe.OfType<BroadcastCommand>().Subscribe(cmd => HandleBroadcasts(cmd, connection));
                commandsSafe.OfType<NotificationCommand>().Subscribe(cmd => HandleNotifications(cmd, connection));
                commandsSafe.OfType<AddContactCommand>().Subscribe(cmd => HandleNewUsers(cmd, connection));
                commandsSafe.OfType<OutCommand>().Subscribe(cmd => HandleOut(cmd, connection));
                commandsSafe.OfType<ChallengeCommand>().Subscribe(cmd => HandleChallenges(cmd, connection));
                commandsSafe.OfType<UserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<InitialUserOnlineCommand>().Subscribe(cmd => HandleOnlineUsers(cmd, connection));
                commandsSafe.OfType<UserOfflineCommand>().Subscribe(cmd => HandleOfflineUsers(cmd, connection));

                connection.Error += connection_Error;

                IsLoggedIn = true;

                OnLoggedIn();

                OnUserStatusChanged(new UserStatusEventArgs(LocalUser, initialStatus, UserStatus.Offline, true));

                if (syncEvents != null)
                    RaiseSyncEvents(syncEvents);


            }
            finally
            {
                @lock.WriterRelease();
            }

        }
        private static IEnumerable<MethodCommandTypeTuple> GetSelfHandlerMethods(Type type, 
            Type[] commandTypes, MethodParameterInjector injector)
        {
            if (!commandTypes.Contains(type)) yield break;

            var methods = type.GetMethods().Where(m => m.GetCustomAttribute<CommandHandlerAttribute>() != null);
            var enumerator = methods.GetEnumerator();
            try
            {
                if (!enumerator.MoveNext())
                    yield break;
                else
                {
                    var method = enumerator.Current;
                    if (method.GetParameters().Any(p => !injector.CanSupply(p.ParameterType)))
                        throw new CommandHandlerMethodHasUnsupportedParameter(type, method);

                    yield return new MethodCommandTypeTuple { Method = method, CommandType = type, HandlerType = type};
                }

                if (enumerator.MoveNext())
                    throw new CommandsMayOnlyDeclareOneHandlerMethod(type);
            }
            finally
            {
                enumerator.Dispose();
            }
        }
Ejemplo n.º 22
0
        private static Dictionary<Type, object> GetMixinDictionary(object[] mixins, Type[] interfaceTypes)
        {
            Dictionary<Type, object> _mixins = new Dictionary<Type, object>();

            foreach (var mixin in mixins)
            {
                if (mixin == null)
                    throw new ArgumentNullException("mixin");

                var mixinType = mixin.GetType();

                foreach (var interfaceType in mixinType.GetInterfaces())
                {
                    if (interfaceTypes.Contains(interfaceType))
                    {
                        throw new InvalidOperationException(String.Format(NLite.Reflection.Dynamic.Internal.Resources.InterfaceTypeWasAlreadyAdded, interfaceType));

                    }

                    _mixins.Add(interfaceType, mixin);
                }
            }

            return _mixins;
        }
Ejemplo n.º 23
0
        public void ControlTestersHaveFourConstructorsAndIndexer()
        {
            IList<Type> typesToSkip = new Type[]{typeof(MessageBoxTester),typeof(FormTester)};

            Type[] types = typeof (ControlTester).Assembly.GetTypes();
            foreach (Type type in types)
            {
                if (typeof(ControlTester).IsAssignableFrom(type))
                {
                    // Skip tests for generic classes (for now.)
                    if (type.IsGenericType)
                        continue;

                    // Explicitly skip tests for these types.
                    if (typesToSkip.Contains(type))
                        continue;

                    ConstructorInfo[] constructors = type.GetConstructors();

                    // OpenFileDialogTester only has one construtor.
                    if (type == typeof (OpenFileDialogTester))
                    {
                        Assert.AreEqual(1, constructors.Length, string.Format("{0}has incorrect constructor count.", type.Name));
                        continue;
                    }

                    Assert.IsTrue(4 <= constructors.Length,  string.Format("{0}has incorrect constructor count.", type.Name));

                    VerifyAllConstructors(type.Name, constructors);
                    Assert.IsTrue(HasIntIndexer(type), string.Format("Type {0} does not have an int indexer.", type.Name));
                }
            }
        }
Ejemplo n.º 24
0
        public static void Start(bool smtpConfig, bool newsletter, bool pop3Config, bool emailReport, Type[] quickLinkFrom)
        {
            if (Navigator.Manager.NotDefined(MethodInfo.GetCurrentMethod()))
            {
                CultureInfoClient.Start();

                Navigator.RegisterArea(typeof(MailingClient));
                Navigator.AddSettings(new List<EntitySettings>
                {
                    new EmbeddedEntitySettings<EmailAttachmentEntity>{ PartialViewName = e => ViewPrefix.FormatWith("EmailAttachment")},
                    new EntitySettings<EmailPackageEntity>{ PartialViewName = e => ViewPrefix.FormatWith("EmailPackage")},
                    
                    new EntitySettings<EmailMessageEntity>{ PartialViewName = e => ViewPrefix.FormatWith("EmailMessage"), AvoidValidateRequest = true },
                    
                    new EmbeddedEntitySettings<EmailAddressEntity>{ PartialViewName = e => ViewPrefix.FormatWith("EmailAddress")},
                    new EmbeddedEntitySettings<EmailRecipientEntity>{ PartialViewName = e => ViewPrefix.FormatWith("EmailRecipient")},
                    
                    new EmbeddedEntitySettings<EmailConfigurationEntity> { PartialViewName = e => ViewPrefix.FormatWith("EmailConfiguration")},
                    new EntitySettings<SystemEmailEntity>{ },
                    
                    new EntitySettings<EmailMasterTemplateEntity> { PartialViewName = e => ViewPrefix.FormatWith("EmailMasterTemplate"), AvoidValidateRequest = true  },
                    new EmbeddedEntitySettings<EmailMasterTemplateMessageEntity>
                    {
                        PartialViewName = e => ViewPrefix.FormatWith("EmailMasterTemplateMessage"),
                        MappingDefault = new EntityMapping<EmailMasterTemplateMessageEntity>(true)
                            .SetProperty(emtm => emtm.MasterTemplate, ctx => 
                            {
                                return (EmailMasterTemplateEntity)ctx.Parent.Parent.Parent.Parent.UntypedValue;
                            })
                    },
                    
                    new EntitySettings<EmailTemplateEntity> { PartialViewName = e => ViewPrefix.FormatWith("EmailTemplate"), AvoidValidateRequest = true },
                    new EmbeddedEntitySettings<EmailTemplateMessageEntity>() 
                    { 
                        PartialViewName = e => ViewPrefix.FormatWith("EmailTemplateMessage"),
                        MappingDefault = new EntityMapping<EmailTemplateMessageEntity>(true)
                            .SetProperty(etm => etm.Template, ctx =>
                            {
                                return (EmailTemplateEntity)ctx.Parent.Parent.Parent.Parent.UntypedValue;
                            })
                    },

                    new EmbeddedEntitySettings<EmailTemplateContactEntity>() 
                    { 
                        PartialViewName = e => ViewPrefix.FormatWith("EmailTemplateContact"),
                        MappingDefault = new EntityMapping<EmailTemplateContactEntity>(true)
                            .SetProperty(ec => ec.Token, ctx =>
                            {
                                string tokenStr = UserAssetsHelper.GetTokenString(ctx);
                                return ParseQueryToken(tokenStr, ctx.Parent.Parent.Parent.Inputs[TypeContextUtilities.Compose("Query", EntityBaseKeys.RuntimeInfo)]);
                            }),
                    },

                    new EmbeddedEntitySettings<EmailTemplateRecipientEntity>() 
                    { 
                        PartialViewName = e => ViewPrefix.FormatWith("EmailTemplateRecipient"),
                        MappingDefault = new EntityMapping<EmailTemplateRecipientEntity>(true)
                            .SetProperty(ec => ec.Token, ctx =>
                            {
                                string tokenStr = UserAssetsHelper.GetTokenString(ctx);

                                return ParseQueryToken(tokenStr, ctx.Parent.Parent.Parent.Parent.Inputs[TypeContextUtilities.Compose("Query", EntityBaseKeys.RuntimeInfo)]);
                            })
                    },
                });

                OperationClient.AddSettings(new List<OperationSettings>
                {
                    new EntityOperationSettings<EmailTemplateEntity>(EmailMessageOperation.CreateMailFromTemplate)
                    {
                        Group = EntityOperationGroup.None,
                        Click = ctx => Module["createMailFromTemplate"](ctx.Options(), JsFunction.Event, 
                            new FindOptions(((EmailTemplateEntity)ctx.Entity).Query.ToQueryName()).ToJS(ctx.Prefix, "New"), 
                            ctx.Url.Action((MailingController mc)=>mc.CreateMailFromTemplateAndEntity()))
                    }
                });

                if (smtpConfig)
                {
                    Navigator.AddSettings(new List<EntitySettings>
                    {
                        new EntitySettings<SmtpConfigurationEntity> { PartialViewName = e => ViewPrefix.FormatWith("SmtpConfiguration") },
                        new EmbeddedEntitySettings<SmtpNetworkDeliveryEntity> { PartialViewName = e => ViewPrefix.FormatWith("SmtpNetworkDelivery") },
                        new EmbeddedEntitySettings<ClientCertificationFileEntity> { PartialViewName = e => ViewPrefix.FormatWith("ClientCertificationFile")},
                    });
                }

                if (newsletter)
                {
                    Navigator.AddSettings(new List<EntitySettings>
                    {
                        new EntitySettings<NewsletterEntity> { PartialViewName = e => ViewPrefix.FormatWith("Newsletter"), AvoidValidateRequest = true},
                        new EntitySettings<NewsletterDeliveryEntity> { PartialViewName = e => ViewPrefix.FormatWith("NewsletterDelivery") },
                    });

                    OperationClient.AddSettings(new List<OperationSettings>
                    {
                        new EntityOperationSettings<NewsletterEntity>(NewsletterOperation.RemoveRecipients)
                        {
                            Click = ctx => Module["removeRecipients"](ctx.Options(),
                                new FindOptions(typeof(NewsletterDeliveryEntity), "Newsletter", ctx.Entity).ToJS(ctx.Prefix, "New"),
                                ctx.Url.Action((MailingController mc)=>mc.RemoveRecipientsExecute()))
                        },

                        new EntityOperationSettings<NewsletterEntity>(NewsletterOperation.Send)
                        {
                            Group = EntityOperationGroup.None,
                        }
                    });
                }

                if (emailReport)
                {
                    Navigator.AddSettings(new List<EntitySettings>
                    {
                        new EntitySettings<SendEmailTaskEntity> { PartialViewName = e => ViewPrefix.FormatWith("SendEmailTask") }
                    });
                }

                if (pop3Config)
                {
                    Navigator.AddSettings(new List<EntitySettings>
                    {
                        new EntitySettings<Pop3ConfigurationEntity> { PartialViewName = e => ViewPrefix.FormatWith("Pop3Configuration") },
                        new EntitySettings<Pop3ReceptionEntity> { PartialViewName = e => ViewPrefix.FormatWith("Pop3Reception") },
                    });
                }

                if (quickLinkFrom != null)
                {
                    LinksClient.RegisterEntityLinks<Entity>((lite,ctx) =>
                    {
                        if (!quickLinkFrom.Contains(lite.EntityType))
                            return null;

                        return new[] { new QuickLinkExplore(typeof(EmailMessageEntity), "Target", lite) };
                    });
                }


                TasksGetWebMailBody += WebMailProcessor.ReplaceUntrusted;
                TasksGetWebMailBody += WebMailProcessor.CidToFilePath;

                TasksSetWebMailBody += WebMailProcessor.AssertNoUntrusted;
                TasksSetWebMailBody += WebMailProcessor.FilePathToCid;

                Navigator.EntitySettings<EmailMessageEntity>().MappingMain.AsEntityMapping()
                    .RemoveProperty(a => a.Body)
                    .SetProperty(a => a.Body, ctx =>
                    {
                        if (!ctx.HasInput)
                            return ctx.None();

                        var email = ((EmailMessageEntity)ctx.Parent.UntypedValue);

                        return SetWebMailBody(ctx.Input, new WebMailOptions
                        {
                             Attachments = email.Attachments,
                             UntrustedImage = null,
                             Url = RouteHelper.New(),
                        });
                    });

                SpecialOmniboxProvider.Register(new SpecialOmniboxAction("AsyncEmailPanel",
                    () => AsyncEmailSenderPermission.ViewAsyncEmailSenderPanel.IsAuthorized(),
                    uh => uh.Action((AsyncEmailSenderController pc) => pc.View())));
            }
        }
Ejemplo n.º 25
0
        public void ValidateNoDanglingAttributes()
        {
            // This list represents attributes that have been cleared to ship without deriving
            // from ArgMetadata.  This test is here to make sure that, by default, the attributes
            // in this project behave like most of the others.  That is, most attributes should
            // derive from ArgMetadata.
            var whitelist = new Type[]
            {
                typeof(ArgReviverAttribute),
            };

            var iArgMetadataSubInterfaces = typeof(Args).Assembly.GetTypes().Where(t =>
                t.IsInterface &&
                t.GetInterfaces().Contains(typeof(IArgMetadata))).ToList();

            // In general, attributes in this project should derive from ArgMetadata
            var danglingAttrs = typeof(Args).Assembly.GetTypes().Where(t =>
                t.IsSubclassOf(typeof(Attribute))   == true &&
                t.GetInterfaces().Contains(typeof(IArgMetadata)) == false &&
                whitelist.Contains(t) == false
            ).ToList();

            // In general, attibutes should use more specific IArgMetadata interfaces
            var danglingAttrs2 = typeof(Args).Assembly.GetTypes().Where(t =>
                t.GetInterfaces().Contains(typeof(Attribute)) == true &&
                (from i in t.GetInterfaces() where iArgMetadataSubInterfaces.Contains(i) select i).Count() == 0 &&
                whitelist.Contains(t) == false
            ).ToList();

            Assert.AreEqual(0, danglingAttrs.Count);
            Assert.AreEqual(0, danglingAttrs2.Count);
        }
Ejemplo n.º 26
0
        void WarnForMissingBindings()
        {
            var ignoredTypes = new Type[] { typeof(DependencyRootStandard), typeof(DisposablesHandler) };

            var boundTypes = _disposables.Select(x => x.Disposable.GetType()).Distinct();

            var unboundTypes = _container.AllConcreteTypes.Where(x => x.DerivesFrom<IDisposable>() && !boundTypes.Contains(x) && !ignoredTypes.Contains(x));

            foreach (var objType in unboundTypes)
            {
                Log.Warn("Found unbound IDisposable with type '" + objType.Name() + "'");
            }
        }
Ejemplo n.º 27
0
    private static void VerifyDependencies()
    {
        var gameObjects           = GameObject.FindObjectsOfType(typeof(GameObject)).Where(go => go.name != "[SaveIt]").ToArray();
        var usableDependencyTypes = new System.Type[]
        {
            typeof(Mesh),
            typeof(Material),
            typeof(PhysicMaterial),
            typeof(Shader),
            typeof(Texture),
            typeof(Texture2D),
            typeof(AudioClip),
            typeof(ProceduralMaterial),
            typeof(AnimationClip),
            typeof(Font)
        };
        var dependencies = EditorUtility.CollectDependencies(gameObjects)
                           .Where(dependency1 =>
        {
            if (dependency1 == null)
            {
                return(false);
            }
            var want = usableDependencyTypes.Contains(dependency1.GetType());
            return(want);
        })
                           .Union(new Object[] { new PhysicMaterial()
                                                 {
                                                     name = "Default"
                                                 } })
                           .Select(dependency2 =>
        {
            var path = AssetDatabase.GetAssetPath(dependency2);
            if (string.IsNullOrEmpty(path))
            {
                path = "$" + dependency2.name;
            }
            return(new ResourceEntry()
            {
                Name = dependency2.name,
                Resource = dependency2,
                TypeName = dependency2.GetType().FullName
            });
        });

        dependencies = dependencies.Union(GameObject.FindObjectsOfType(typeof(Saveable))
                                          .Where(saveable => ((Saveable)saveable).Prefab != null)
                                          .Select(saveable =>
        {
            var prefab = ((Saveable)saveable).Prefab;
            return(new ResourceEntry()
            {
                Name = prefab.name,
                Resource = prefab,
                TypeName = prefab.GetType().FullName
            });
        }));

        var saveItGameObject = (GameObject)GameObject.Find("[SaveIt]");

        if (saveItGameObject == null)
        {
            saveItGameObject = new GameObject("[SaveIt]");
        }
        var saveItComponent = saveItGameObject.GetComponent <SaveItComponent>();

        if (saveItComponent == null)
        {
            saveItComponent = saveItGameObject.AddComponent <SaveItComponent>();
        }

        saveItComponent.ResourceEntries = dependencies.Distinct().ToArray();
    }
        private static IList<Type> GetTypes(Container container, Assembly assembly, Type[] typesToIgnore)
        {
            string assemblyName = assembly.GetName().Name;

            var existingRegistrationsServiceTypes =
                container.GetCurrentRegistrations().Select(instanceProducer => instanceProducer.ServiceType).ToList();

            IList<Type> registrations =
                assembly.GetExportedTypes()
                    .Where(type => !typesToIgnore.Contains(type))
                    .Where(type => !existingRegistrationsServiceTypes.Contains(type))
                    .Where(type => type.Namespace != null)
                    .Where(type => type.Namespace.StartsWith(assemblyName, StringComparison.OrdinalIgnoreCase))
                    .Where(type => (type.Attributes & TypeAttributes.Abstract) != TypeAttributes.Abstract)
                    .Where(type => type.GetInterfaces().Any())
                    .Where(
                        type =>
                            type.GetInterfaces()
                                .Any(
                                    inter =>
                                        !typesToIgnore.Contains(inter) && inter.Namespace != null &&
                                        inter.Namespace.StartsWith(assemblyName, StringComparison.OrdinalIgnoreCase)))

                    .ToList();

            // Ignore already registerd interfaces:
            for (int i = registrations.Count() - 1; i >= 0; i--)
            {
                foreach (var registrationInterface in registrations[i].GetInterfaces())
                {
                    if (existingRegistrationsServiceTypes.Contains(registrationInterface))
                    {
                        registrations.RemoveAt(i);
                        break;
                    }
                }
            }
            return registrations;
        }
Ejemplo n.º 29
0
        static Hashes()
        {
            All = (from hf in Assembly.GetAssembly(typeof(IHash)).GetTypes()
                   where hf.IsClass
                   where !hf.IsAbstract
                   where hf != typeof(HMACNotBuildInAdapter)
                   where hf != typeof(HashCryptoBuildIn)
                   where hf != typeof(HMACBuildInAdapter)
                   where hf != typeof(HashLib.Checksum.CRC32)
                   where hf != typeof(HashLib.Checksum.CRC64)
                   where hf.IsImplementingInterface(typeof(IHash))
                   where !hf.IsNested
                   select hf).ToList().AsReadOnly();

            All = (from hf in All
                         orderby hf.Name
                         select hf).ToList().AsReadOnly();

            var x2 = new Type[]
            {
                typeof(HashLib.Crypto.BuildIn.SHA1Cng),
                typeof(HashLib.Crypto.BuildIn.SHA1Managed),
                typeof(HashLib.Crypto.BuildIn.SHA256Cng),
                typeof(HashLib.Crypto.BuildIn.SHA256Managed),
                typeof(HashLib.Crypto.BuildIn.SHA384Cng),
                typeof(HashLib.Crypto.BuildIn.SHA384Managed),
                typeof(HashLib.Crypto.BuildIn.SHA512Cng),
                typeof(HashLib.Crypto.BuildIn.SHA512Managed),
                typeof(HashLib.Crypto.MD5),
                typeof(HashLib.Crypto.RIPEMD160),
                typeof(HashLib.Crypto.SHA1),
                typeof(HashLib.Crypto.SHA256),
                typeof(HashLib.Crypto.SHA384),
                typeof(HashLib.Crypto.SHA512),
            };

            AllUnique = (from hf in All
                         where !(hf.IsDerivedFrom(typeof(HashLib.Hash32.DotNet)))
                         where !x2.Contains(hf)
                         where !hf.IsNested
                         select hf).ToList().AsReadOnly();

            Hash32 = (from hf in All
                      where hf.IsImplementingInterface(typeof(IHash32))
                      select hf).ToList().AsReadOnly();

            Hash64 = (from hf in All
                      where hf.IsImplementingInterface(typeof(IHash64))
                      select hf).ToList().AsReadOnly();

            Checksums = (from hf in All
                         where hf.IsImplementingInterface(typeof(IChecksum))
                         select hf).ToList().AsReadOnly();

            FastComputes = (from hf in All
                            where hf.IsImplementingInterface(typeof(IFastHashCodes))
                            select hf).ToList().AsReadOnly();

            NonBlock = (from hf in All
                        where hf.IsImplementingInterface(typeof(INonBlockHash))
                        select hf).ToList().AsReadOnly();

            CryptoAll = (from hf in All
                         where hf.IsImplementingInterface(typeof(ICrypto))
                         select hf).ToList().AsReadOnly();

            CryptoNotBuildIn = (from hf in CryptoAll
                                where hf.IsImplementingInterface(typeof(ICryptoNotBuildIn))
                                select hf).ToList().AsReadOnly();

            CryptoBuildIn = (from hf in CryptoAll
                             where hf.IsImplementingInterface(typeof(ICryptoBuildIn))
                             select hf).ToList().AsReadOnly();

            HMACCryptoBuildIn = (from hf in CryptoBuildIn
                                 where hf.IsImplementingInterface(typeof(IHasHMACBuildIn))
                                 select hf).ToList().AsReadOnly();
        }
Ejemplo n.º 30
0
 /// <summary>
 /// Validates that the required ISteamAuthenticator object is attached to the client prior to initiating execution
 /// </summary>
 /// <param name="validAuthMethods">List of valid authenticators for API access.</param>
 /// <returns>Returns 'true' if the proper authenticator is attached. Throws <see cref="SteamAuthenticationException"/> otherwise.</returns>
 internal bool IsAuthorizedCall( Type[] validAuthMethods )
 {
     if( Authenticator == null || !validAuthMethods.Contains( Authenticator.GetType() ) )
         throw new SteamAuthenticationException( "API call has not been properly authenticated. Please ensure the proper ISteamAuthenticator object is added to the SteamClient (SteamClient.Authenticator)." );
     return true;
 }
        public void InterfaceValidatorAutoCheck()
        {
            var edmLib = typeof(IEdmElement).Assembly;
            Type interfaceValidatorType = edmLib.GetType("Microsoft.OData.Edm.Validation.Internal.InterfaceValidator");
            var interfaceVisitorsField = interfaceValidatorType.GetField("InterfaceVisitors", BindingFlags.NonPublic | BindingFlags.Static);
            object interfaceVisitors = interfaceVisitorsField.GetValue(null);
            var containsKeyMethod = interfaceVisitors.GetType().GetMethod("ContainsKey");

            Type[] skips = new Type[]
            {
                typeof(IEdmVocabularyAnnotatable),
                typeof(IEdmSchemaType),
                typeof(IEdmComplexType),
                typeof(IEdmLocatable),
                typeof(IEdmBinaryConstantExpression),
                typeof(IEdmGuidConstantExpression),
                typeof(IEdmDateTimeOffsetConstantExpression),
                typeof(IEdmDurationConstantExpression),
                typeof(IEdmBooleanConstantExpression),
                typeof(IEdmStringConstantExpression),
                typeof(IEdmNullExpression),
                typeof(IEdmIntegerConstantExpression),
                typeof(IEdmFloatingConstantExpression),
                typeof(IEdmDecimalConstantExpression),
                typeof(IEdmNullValue),
                typeof(IEdmPrimitiveValue),
                typeof(IEdmDateTimeOffsetValue),
                typeof(IEdmGuidValue),
                typeof(IEdmBooleanValue),
                typeof(IEdmDurationValue),
                typeof(IEdmDecimalValue),
                typeof(IEdmFloatingValue),
                typeof(IEdmIntegerValue),
                typeof(IEdmDirectValueAnnotationsManager),
                typeof(IEdmDirectValueAnnotationBinding),
                typeof(IEdmNavigationPropertyBinding),
                typeof(IEdmEntitySet),
                typeof(IEdmUnknownEntitySet),
                typeof(IEdmDateValue),
                typeof(IEdmDateConstantExpression),
                typeof(IEdmTimeOfDayValue),
                typeof(IEdmTimeOfDayConstantExpression),
            };

            foreach (Type skip in skips)
            {
                if (skip != typeof(IEdmLocatable) && // location is optional
                    skip != typeof(IEdmNavigationPropertyBinding) && // this interface is processed inline inside IEdmEntitySet visitor

                    skip != typeof(IEdmDateTimeOffsetValue) && // the value properties in these interfaces are structs, so they can't be null.
                    skip != typeof(IEdmDateValue) &&
                    skip != typeof(IEdmGuidValue) &&
                    skip != typeof(IEdmBooleanValue) &&
                    skip != typeof(IEdmDurationValue) &&
                    skip != typeof(IEdmDecimalValue) &&
                    skip != typeof(IEdmFloatingValue) &&
                    skip != typeof(IEdmIntegerValue) &&
                    skip != typeof(IEdmDirectValueAnnotationBinding) &&
                    skip != typeof(IEdmTimeOfDayValue)
                    )
                {
                    Assert.AreEqual(0, skip.GetProperties().Length, "It is not safe to skip interfaces with properties.");
                }
            }

            StringBuilder missingVisitors = new StringBuilder();
            foreach (Type type in edmLib.GetTypes())
            {
                if (type.IsInterface && type.IsPublic &&
                    type.Namespace.StartsWith("Microsoft.OData.Edm", StringComparison.Ordinal) &&
                    type.Name.StartsWith("IEdm", StringComparison.Ordinal))
                {
                    if (!(bool)containsKeyMethod.Invoke(interfaceVisitors, new object[] { type }) && !skips.Contains(type))
                    {
                        missingVisitors.AppendLine(type.FullName);
                    }
                }
            }

            Assert.IsTrue(missingVisitors.Length == 0, "The following interfaces might need a visitor in InterfaceValidator class \r\n" + missingVisitors.ToString());

            var isCriticalMethod = edmLib.GetType("Microsoft.OData.Edm.Validation.Internal.ValidationHelper").GetMethod("IsInterfaceCritical", BindingFlags.NonPublic | BindingFlags.Static);
            foreach (var errorCodeName in Enum.GetNames(typeof(EdmErrorCode)))
            {
                if (errorCodeName.StartsWith("InterfaceCritical", StringComparison.Ordinal))
                {
                    Assert.IsTrue((bool)isCriticalMethod.Invoke(null, new object[] { new EdmError(null, (EdmErrorCode)Enum.Parse(typeof(EdmErrorCode), errorCodeName), errorCodeName) }), "InterfaceValidator.IsCritial must return true for " + errorCodeName);
                }
            }
        }
 private static bool IsExcludedType(Type type, Type[] excludeTypes)
 {
     return excludeTypes.Contains(type);
 }
Ejemplo n.º 33
0
 private static bool isSimpleType(Type type)
 {
     Type[] simpleTypes = new Type[]
     {
         typeof(string),
         typeof(byte), typeof(byte?),
         typeof(short), typeof(short?),
         typeof(int), typeof(int?),
         typeof(long), typeof(long?),
         typeof(Guid), typeof(Guid?)
     };
     return simpleTypes.Contains(type);
 }