System.Object.GetType()

Here are the examples of the csharp api System.Object.GetType() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

698 Examples 7

19 View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel

public static void SetSealedPropertyValue(this Enreplacedy enreplacedy, string sPropertyName, object value)
        {
            enreplacedy.GetType().GetProperty(sPropertyName).SetValue(enreplacedy, value, null);
        }

19 View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel

public static void SetSealedPropertyValue(this EnreplacedyMetadata enreplacedyMetadata, string sPropertyName, object value)
        {
            enreplacedyMetadata.GetType().GetProperty(sPropertyName).SetValue(enreplacedyMetadata, value, null);
        }

19 View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel

public static void SetSealedPropertyValue(this AttributeMetadata attributeMetadata, string sPropertyName, object value)
        {
            attributeMetadata.GetType().GetProperty(sPropertyName).SetValue(attributeMetadata, value, null);
        }

19 View Source File : SupportMethods.cs
License : MIT License
Project Creator : abvogel

public static void SetSealedPropertyValue(this Microsoft.Xrm.Sdk.Metadata.ManyToManyRelationshipMetadata manyToManyRelationshipMetadata, string sPropertyName, object value)
        {
            manyToManyRelationshipMetadata.GetType().GetProperty(sPropertyName).SetValue(manyToManyRelationshipMetadata, value, null);
        }

19 View Source File : AppManager.cs
License : MIT License
Project Creator : admaiorastudio

private async Task WhenReloadXaml(string pageId, byte[] data, bool refresh)
        {
            Application app = null;
            _app.TryGetTarget(out app);
            if (app == null)
                return;

            string xaml = DecompressXaml(data);

            replacedembly replacedembly = app.GetType().replacedembly;
            Type itemType = replacedembly.GetType(pageId);
            if (itemType != null
                && itemType.BaseType == typeof(Xamarin.Forms.Application))
            {
                Device.BeginInvokeOnMainThread(
                    () =>
                    {
                        app.Resources.Clear();
                        app.LoadFromXaml(xaml);
                    });
                // Do we need to refresh pages?
                if (refresh)
                {
                    var pages = _pages.Values
                        .Where(x => x.IsAlive)
                        .Select(x => x.Target as Page)
                        .Where(x => x.Parent != null)
                        .ToArray();

                    foreach (var page in pages)
                        await ReloadXaml(page);
                }
            }
            else
            {
                // For each page store the latest xaml
                // sended by the IDE or saved by the user. 
                // This allow every new page instace to have the latest xaml
                _xamlCache[pageId] = data;

                // Do we need to refresh pages?
                if (refresh)
                {
                    var pages = _pages.Values
                        .Where(x => x.IsAlive)
                        .Select(x => x.Target as Page)
                        .Where(x => x.Parent != null)
                        .ToArray();

                    foreach (var page in pages)
                    {
                        string pid = page.GetType().FullName;
                        if (pid == pageId)
                            await ReloadXaml(page, data);
                    }
                }
            }
        }

19 View Source File : RealXamlPacakge.cs
License : MIT License
Project Creator : admaiorastudio

protected override async Task InitializeAsync(CancellationToken cancellationToken, IProgress<ServiceProgressData> progress)
        {
            // When initialized asynchronously, the current thread may be a background thread at this point.
            // Do any initialization that requires the UI thread after switching to the UI thread.
            await this.JoinableTaskFactory.SwitchToMainThreadAsync(cancellationToken);

            _dte = await GetServiceAsync(typeof(EnvDTE.DTE)) as EnvDTE.DTE;
            if (_dte == null)
                return;

            // Intercept build commands
            string[] buildCommandNames = new[]
            {                
                "Build.BuildSolution",
                "Build.RebuildSolution",
                "Build.BuildSelection",
                "Build.RebuildSelection",
                "ClreplacedViewContextMenus.ClreplacedViewProject.Build",
                "ClreplacedViewContextMenus.ClreplacedViewProject.Rebuild",
                "Build.ProjectPickerBuild",
                "Build.ProjectPickerRebuild",
                "Build.BuildOnlyProject",
                "Build.RebuildOnlyProject"
            };

            _cmdEvents = new List<CommandEvents>();
            foreach (string buildCommandName in buildCommandNames)
            {                
                var buildCommand = _dte.Commands.Item(buildCommandName);
                var cmdev = _dte.Events.CommandEvents[buildCommand.Guid, buildCommand.ID];
                cmdev.BeforeExecute += this.BuildCommand_BeforeExecute;
                _cmdEvents.Add(cmdev);
            }

            _dte.Events.SolutionEvents.BeforeClosing += SolutionEvents_BeforeClosing;            
            _dte.Events.BuildEvents.OnBuildBegin += BuildEvents_OnBuildBegin;
            _dte.Events.BuildEvents.OnBuildDone += BuildEvents_OnBuildDone;
            _dte.Events.BuildEvents.OnBuildProjConfigBegin += BuildEvents_OnBuildProjConfigBegin;                        


            _rdt = (IVsRunningDoreplacedentTable)(await GetServiceAsync(typeof(SVsRunningDoreplacedentTable)));
            _rdt.AdviseRunningDocTableEvents(this, out _rdtCookie);            
                       
            await AdMaiora.RealXaml.Extension.Commands.EnableRealXamlCommand.InitializeAsync(this, _dte);
            await AdMaiora.RealXaml.Extension.Commands.DisableRealXamlCommand.InitializeAsync(this, _dte);

            CreateOutputPane();

            try
            {
                string currentPath = Path.GetDirectoryName(GetType().replacedembly.Location);
                _replacedemblyResolver = new ManualreplacedemblyResolver(
                    replacedembly.LoadFile(Path.Combine(currentPath, "Newtonsoft.Json.dll")),
                    replacedembly.LoadFile(Path.Combine(currentPath, "System.Buffers.dll")),
                    replacedembly.LoadFile(Path.Combine(currentPath, "System.Numerics.Vectors.dll"))
                    );
            }
            catch (Exception ex)
            {
                System.Diagnostics.Debug.WriteLine(ex);
                _outputPane.OutputString("Something went wrong loading replacedemblies.");
                _outputPane.OutputString(ex.ToString());
            }

            UpdateManager.Current.IdeRegistered += this.UpdateManager_IdeRegistered;
            UpdateManager.Current.ClientRegistered += this.UpdateManager_ClientRegistered;
            UpdateManager.Current.PageAppeared += this.UpdateManager_PageAppeared;
            UpdateManager.Current.PageDisappeared += this.UpdateManager_PageDisappeared;
            UpdateManager.Current.XamlUpdated += this.UpdateManager_XamlUpdated;
            UpdateManager.Current.replacedemblyLoaded += this.UpdateManager_replacedemblyLoaded;
            UpdateManager.Current.ExceptionThrown += this.UpdateManager_ExceptionThrown;
            UpdateManager.Current.IdeNotified += this.Current_IdeNotified;

            _xamlCache.Clear();
        }

19 View Source File : WwwResult{T}.cs
License : MIT License
Project Creator : Arvtesh

public override string ToString()
		{
			var result = new StringBuilder();
			var errorStr = _www.error;

			result.Append(_www.GetType().Name);
			result.Append(" (");
			result.Append(_www.url);

			if (IsFaulted && !string.IsNullOrEmpty(errorStr))
			{
				result.Append(", ");
				result.Append(errorStr);
			}

			result.Append(')');
			return result.ToString();
		}

19 View Source File : EntityInvoker.cs
License : MIT License
Project Creator : Azure

internal static object GetTaskResult(Task task)
        {
            if (task.IsFaulted)
            {
                throw task.Exception;
            }

            Type taskType = task.GetType();

            if (taskType.IsGenericType)
            {
                return taskType.GetProperty("Result").GetValue(task);
            }

            return null;
        }

19 View Source File : CosmosVirtualUnitTest.cs
License : MIT License
Project Creator : Azure

[TestMethod]
        public void VerifyInlineOverride()
        {
            replacedembly replacedembly = replacedembly.Getreplacedembly(typeof(CosmosClient));
            IEnumerable<Type> allClreplacedes = from t in replacedembly.GetTypes()
                                           where t.IsClreplaced && !t.IsPublic && !t.IsAbstract
                                           where t.Namespace != null
                                           where t.Namespace.StartsWith("Microsoft.Azure.Cosmos") && t.Name.EndsWith("InlineCore")
                                           select t;

            List<Type> inlineClreplacedes = allClreplacedes.ToList();
            replacedert.IsTrue(inlineClreplacedes.Count >= 7);

            foreach (Type inlineType in inlineClreplacedes)
            {
                string contractClreplacedName = inlineType.FullName.Replace("InlineCore", string.Empty);
                Type contractClreplaced = replacedembly.GetType(contractClreplacedName);
                replacedert.IsNotNull(contractClreplaced);
                string[] allContractMethods = contractClreplaced.GetMethods()
                    .Where(x => x.DeclaringType == contractClreplaced && x.Name.EndsWith("Async"))
                    .Select(x => x.ToString())
                    .ToArray();

                HashSet<string> allInlineMethods = inlineType.GetMethods()
                    .Where(x => x.Name.EndsWith("Async") && x.DeclaringType == inlineType)
                    .Select(x => x.ToString())
                    .ToHashSet<string>();

                foreach (string contractMethod in allContractMethods)
                {
                    if (!allInlineMethods.Contains(contractMethod))
                    {
                        replacedert.Fail($"The clreplaced: {inlineType.FullName} does not override method \"{contractMethod}\" in the inline clreplaced");
                    }
                }
            }
        }

19 View Source File : TaskMethodInvoker.cs
License : MIT License
Project Creator : Azure

private static void ThrowIfWrappedTaskInstance(Task task)
        {
            if (task == null)
            {
                return;
            }

            Type taskType = task.GetType();
            Debug.replacedert(taskType != null);

            Type innerTaskType = GetTaskInnerTypeOrNull(taskType);

            if (innerTaskType != null && typeof(Task).IsreplacedignableFrom(innerTaskType))
            {
                throw new InvalidOperationException("Returning a nested Task is not supported. Did you mean to await " +
                    "or Unwrap the task instead of returning it?");
            }
        }

19 View Source File : TaskMethodInvokerTests.cs
License : MIT License
Project Creator : Azure

[Fact]
        public void InvokeAsync_IfLambdaReturnsTaskDelayTask_ReturnsCompletedTask()
        {
            // Arrange
            Func<object, object[], Task<object>> lambda = async (i1, i2) =>
            {
                Task innerTask = Task.Delay(1);
                replacedert.False(innerTask.GetType().IsGenericType); // Guard
                await innerTask;
                return null;
            };

            IMethodInvoker<object, object> invoker = CreateProductUnderTest(lambda);
            object instance = null;
            object[] arguments = null;

            // Act
            Task task = invoker.InvokeAsync(instance, arguments);

            // replacedert
            replacedert.NotNull(task);
            task.WaitUntilCompleted();
            replacedert.Equal(TaskStatus.RanToCompletion, task.Status);
        }

19 View Source File : TaskMethodInvokerTests.cs
License : MIT License
Project Creator : Azure

[Fact]
        public void InvokeAsync_IfLambdaReturnsTaskWhenAllTask_ReturnsCompletedTask()
        {
            // Arrange
            Func<object, object[], Task<object>> lambda = async (i1, i2) =>
            {
                Task innerTask = Task.WhenAll(Task.Delay(1));
                replacedert.False(innerTask.GetType().IsGenericType); // Guard
                await innerTask;
                return null;
            };

            IMethodInvoker<object, object> invoker = CreateProductUnderTest(lambda);
            object instance = null;
            object[] arguments = null;

            // Act
            Task task = invoker.InvokeAsync(instance, arguments);

            // replacedert
            replacedert.NotNull(task);
            task.WaitUntilCompleted();
            replacedert.Equal(TaskStatus.RanToCompletion, task.Status);
        }

19 View Source File : TaskMethodInvokerTests.cs
License : MIT License
Project Creator : Azure

[Fact]
        public void InvokeAsync_IfLambdaReturnsTaskWhenAllCancelledTask_ReturnsCancelledTask()
        {
            // Arrange
            Func<object, object[], Task<object>> lambda = async (i1, i2) =>
            {
                var cancellationSource = new System.Threading.CancellationTokenSource();
                Task innerTask = new Task(() => { }, cancellationSource.Token);
                replacedert.False(innerTask.GetType().IsGenericType); // Guard
                cancellationSource.Cancel();
                await Task.WhenAll(innerTask);
                return null;
            };

            IMethodInvoker<object, object> invoker = CreateProductUnderTest(lambda);
            object instance = null;
            object[] arguments = null;

            // Act
            Task task = invoker.InvokeAsync(instance, arguments);

            // replacedert
            replacedert.NotNull(task);
            task.WaitUntilCompleted();
            replacedert.Equal(TaskStatus.Canceled, task.Status);
        }

19 View Source File : TaskMethodInvokerTests.cs
License : MIT License
Project Creator : Azure

[Fact]
        public void InvokeAsync_IfLambdaReturnsTaskWhenAllFaultedTask_ReturnsFaultedTask()
        {
            // Arrange
            Exception expectedException = new InvalidOperationException();
            Func<object, object[], Task<object>> lambda = async (i1, i2) =>
            {
                Task innerTask = new Task(() => { throw expectedException; });
                innerTask.Start();
                replacedert.False(innerTask.GetType().IsGenericType); // Guard
                await Task.WhenAll(innerTask);
                return null;
            };

            IMethodInvoker<object, object> invoker = CreateProductUnderTest(lambda);
            object instance = null;
            object[] arguments = null;

            // Act
            Task task = invoker.InvokeAsync(instance, arguments);

            // replacedert
            replacedert.NotNull(task);
            task.WaitUntilCompleted();
            replacedert.Equal(TaskStatus.Faulted, task.Status);
            replacedert.NotNull(task.Exception);
            replacedert.Same(expectedException, task.Exception.InnerException);
        }

19 View Source File : DefaultMethodInfoLocator.cs
License : MIT License
Project Creator : Azure

public MethodInfo GetMethod(string pathToreplacedembly, string entryPoint)
        {
            var entryPointMatch = _entryPointRegex.Match(entryPoint);
            if (!entryPointMatch.Success)
            {
                throw new InvalidOperationException("Invalid entry point configuration. The function entry point must be defined in the format <fulltypename>.<methodname>");
            }

            string typeName = entryPointMatch.Groups["typename"].Value;
            string methodName = entryPointMatch.Groups["methodname"].Value;

            replacedembly replacedembly = replacedemblyLoadContext.Default.LoadFromreplacedemblyPath(pathToreplacedembly);

            Type? functionType = replacedembly.GetType(typeName);

            MethodInfo? methodInfo = functionType?.GetMethod(methodName);

            if (methodInfo == null)
            {
                throw new InvalidOperationException($"Method '{methodName}' specified in {nameof(FunctionDefinition.EntryPoint)} was not found. This function cannot be created.");
            }

            return methodInfo;
        }

19 View Source File : DurableEntityContext.cs
License : MIT License
Project Creator : Azure

async Task IDurableEnreplacedyContext.DispatchAsync<T>(params object[] constructorParameters)
        {
            IDurableEnreplacedyContext context = (IDurableEnreplacedyContext)this;
            MethodInfo method = FindMethodForContext<T>(context);

            if (method == null)
            {
                // We support a default delete operation even if the interface does not explicitly have a Delete method.
                if (string.Equals("delete", context.OperationName, StringComparison.InvariantCultureIgnoreCase))
                {
                    Enreplacedy.Current.DeleteState();
                    return;
                }
                else
                {
                    throw new InvalidOperationException($"No operation named '{context.OperationName}' was found.");
                }
            }

            // check that the number of arguments is zero or one
            ParameterInfo[] parameters = method.GetParameters();
            if (parameters.Length > 1)
            {
                throw new InvalidOperationException("Only a single argument can be used for operation input.");
            }

            object[] args;
            if (parameters.Length == 1)
            {
                // determine the expected type of the operation input and deserialize
                Type inputType = method.GetParameters()[0].ParameterType;
                object input = context.GetInput(inputType);
                args = new object[1] { input };
            }
            else
            {
                args = Array.Empty<object>();
            }

#if !FUNCTIONS_V1
            T Constructor() => (T)context.FunctionBindingContext.CreateObjectInstance(typeof(T), constructorParameters);
#else
            T Constructor() => (T)Activator.CreateInstance(typeof(T), constructorParameters);
#endif

            var state = ((Extensions.DurableTask.DurableEnreplacedyContext)context).GetStateWithInjectedDependencies(Constructor);

            object result = method.Invoke(state, args);

            if (method.ReturnType != typeof(void))
            {
                if (result is Task task)
                {
                    await task;

                    if (task.GetType().IsGenericType)
                    {
                        context.Return(task.GetType().GetProperty("Result").GetValue(task));
                    }
                }
                else
                {
                    context.Return(result);
                }
            }
        }

19 View Source File : DiagnosticVerifier.cs
License : MIT License
Project Creator : Azure

private static string FormatDiagnostics(Diagnosticreplacedyzer replacedyzer, params Diagnostic[] diagnostics)
        {
            var builder = new StringBuilder();
            for (int i = 0; i < diagnostics.Length; ++i)
            {
                builder.AppendLine("// " + diagnostics[i].ToString());

                var replacedyzerType = replacedyzer.GetType();
                var rules = replacedyzer.SupportedDiagnostics;

                foreach (var rule in rules)
                {
                    if (rule != null && rule.Id == diagnostics[i].Id)
                    {
                        var location = diagnostics[i].Location;
                        if (location == Location.None)
                        {
                            builder.AppendFormat("GetGlobalResult({0}.{1})", replacedyzerType.Name, rule.Id);
                        }
                        else
                        {
                            replacedert.IsTrue(location.IsInSource,
                                $"Test base does not currently handle diagnostics in metadata locations. Diagnostic in metadata: {diagnostics[i]}\r\n");

                            string resultMethodName = diagnostics[i].Location.SourceTree.FilePath.EndsWith(".cs") ? "GetCSharpResultAt" : "GetBasicResultAt";
                            var linePosition = diagnostics[i].Location.GetLineSpan().StartLinePosition;

                            builder.AppendFormat("{0}({1}, {2}, {3}.{4})",
                                resultMethodName,
                                linePosition.Line + 1,
                                linePosition.Character + 1,
                                replacedyzerType.Name,
                                rule.Id);
                        }

                        if (i != diagnostics.Length - 1)
                        {
                            builder.Append(',');
                        }

                        builder.AppendLine();
                        break;
                    }
                }
            }
            return builder.ToString();
        }

19 View Source File : Utils.cs
License : MIT License
Project Creator : Azure

internal static void CleanupGlobalVariables(PowerShell pwsh)
        {
            List<string> varsToRemove = null;
            ICollection<PSVariable> globalVars = GetGlobalVariables(pwsh);

            foreach (PSVariable var in globalVars)
            {
                // The variable is one of the built-in global variables.
                if (s_globalVariables.Contains(var.Name)) { continue; }

                // We cannot remove a constant variable, so leave it as is.
                if (var.Options.HasFlag(ScopedItemOptions.Constant)) { continue; }

                // The variable is exposed by a module. We don't remove modules, so leave it as is.
                if (var.Module != null) { continue; }

                // The variable is not a regular PSVariable.
                // It's likely not created by the user, so leave it as is.
                if (var.GetType() != typeof(PSVariable)) { continue; }

                if (varsToRemove == null)
                {
                    // Create a list only if it's needed.
                    varsToRemove = new List<string>();
                }

                // Add the variable path.
                varsToRemove.Add($"{VariableDriveRoot}{var.Name}");
            }

            if (varsToRemove != null)
            {
                // Remove the global variable added by the function invocation.
                pwsh.Runspace.SessionStateProxy.InvokeProvider.Item.Remove(
                    varsToRemove.ToArray(),
                    recurse: true,
                    force: true,
                    literalPath: true);
            }
        }

19 View Source File : TypeUtility.cs
License : MIT License
Project Creator : Azure

public static Type ToReflectionType(this TypeReference typeDef)
        {
            Type t = Type.GetType(typeDef.GetReflectionFullName());

            if (t == null)
            {
#if NETCOREAPP2_1
                replacedembly a = replacedemblyLoadContext.Default.LoadFromreplacedemblyPath(Path.GetFullPath(typeDef.Resolve().Module.FileName));
#else
                replacedembly a = replacedembly.LoadFrom(Path.GetFullPath(typeDef.Resolve().Module.FileName));
#endif
                t = a.GetType(typeDef.GetReflectionFullName());
            }

            return t;
        }

19 View Source File : DeviceClient.cs
License : MIT License
Project Creator : Azure

private async Task SendProtobufMessageAsync(string message, DeviceModel.DeviceModelMessageSchema schema)
        {
            var eventMessage = default(Message);
            Type type = replacedembly.GetExecutingreplacedembly().GetType(schema.ClreplacedName, false);

            if (type != null)
            {
                object jsonObj = JsonConvert.DeserializeObject(message, type);

                MethodInfo methodInfo = Utilities.GetExtensionMethod("imessage", "Google.Protobuf", "ToByteArray");
                if (methodInfo != null)
                {
                    object result = methodInfo.Invoke(jsonObj, new object[] { jsonObj });
                    if (result != null)
                    {
                        byte[] byteArray = result as byte[];
                        eventMessage = new Message(byteArray);
                        eventMessage.Properties.Add(CLreplacedNAME_PROPERTY, schema.ClreplacedName);
                    }
                    else
                    {
                        throw new InvalidDataException("Json message transformation to byte array yielded null");
                    }
                }
                else
                {
                    throw new ResourceNotFoundException($"Method: ToByteArray not found in {schema.ClreplacedName}");
                }
            }
            else
            {
                throw new ResourceNotFoundException($"Type: {schema.ClreplacedName} not found");
            }

            eventMessage.Properties.Add(CREATION_TIME_PROPERTY, DateTimeOffset.UtcNow.ToString(DATE_FORMAT));
            eventMessage.Properties.Add(MESSAGE_SCHEMA_PROPERTY, schema.Name);
            eventMessage.Properties.Add(CONTENT_PROPERTY, schema.Format.ToString());

            eventMessage.MessageSchema = schema.Name;
            eventMessage.CreationTimeUtc = DateTime.UtcNow;

            this.log.Debug("Sending message from device",
                () => new { this.deviceId, Schema = schema.Name });

            await this.SendRawMessageAsync(eventMessage);
        }

19 View Source File : ReflectionService.cs
License : MIT License
Project Creator : Azure

public List<PropertyInfo> GetProperties(string typeNameStartWith, string propertyName)
        {
            List<PropertyInfo> propertyList = new List<PropertyInfo>();
            try
            {
                var exportedNS = Getreplacedembly(true).ExportedTypes.Select<Type, string>((item) => item.Namespace);
                var distinctNS = exportedNS.Distinct<string>();
                Type sdkInfoType = null;

                foreach(string ns in distinctNS)
                {
                    string fqtype = string.Format("{0}.sdkinfo", ns);
                    sdkInfoType = Getreplacedembly(false).GetType(fqtype, throwOnError: true, ignoreCase: true);
                    if(sdkInfoType != null)
                    {
                        break;
                    }
                }

                UtilLogger.LogInfo("Querying Type '{0}' for propertyName '{1}'", sdkInfoType.Name, propertyName);
                PropertyInfo[] memInfos = sdkInfoType.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public);

                foreach (PropertyInfo mInfo in memInfos)
                {
                    UtilLogger.LogInfo("Found:'{0}'", mInfo.Name);
                    if (mInfo.Name.Contains(propertyName))
                    {
                        UtilLogger.LogInfo("Added:'{0}' to list", mInfo.Name);
                        propertyList.Add(mInfo);
                    }
                }
            }
            catch (Exception ex)
            {
                UtilLogger.LogWarning(ex.Message);
            }

            return propertyList;
        }

19 View Source File : AssemblyEx.cs
License : MIT License
Project Creator : Azure

public static JObject GetVersionInfoObject(this replacedembly replacedembly) {
            if (replacedembly == null) {
                throw new ArgumentNullException(nameof(replacedembly));
            }
            var o = new JObject();
            foreach (var p in replacedembly.GetType("Thisreplacedembly")?
                .GetFields(BindingFlags.Static | BindingFlags.NonPublic)
                .Select(f => new JProperty(f.Name, f.GetValue(null))) ??
                    new JProperty("replacedemblyVersion", "No version information found.")
                        .YieldReturn()) {
                o.Add(p);
            }
            return o;
        }

19 View Source File : ServerWebSocketTransport.cs
License : MIT License
Project Creator : Azure

void ValidateIsOpen()
        {
            WebSocketState webSocketState = this.webSocket.State;
            switch (webSocketState)
            {
                case WebSocketState.Open:
                    return;
                case WebSocketState.Aborted:
                    throw new ObjectDisposedException(this.GetType().Name);
                case WebSocketState.Closed:
                case WebSocketState.CloseReceived:
                case WebSocketState.CloseSent:
                    throw new ObjectDisposedException(this.GetType().Name);
                default:
                    throw new AmqpException(AmqpErrorCode.IllegalState, null);
            }
        }

19 View Source File : Settings.cs
License : MIT License
Project Creator : Azure

private static void PopulateSettings(object enreplacedyToPopulate, IDictionary<string, object> settings)
        {
            if (enreplacedyToPopulate == null)
            {
                throw new ArgumentNullException("enreplacedyToPopulate");
            }

            if (settings != null && settings.Count > 0)
            {
                // Setting property value from dictionary
                foreach (var setting in settings.ToArray())
                {
                    PropertyInfo property = enreplacedyToPopulate.GetType().GetProperties()
                        .FirstOrDefault(p => setting.Key.Equals(p.Name, StringComparison.OrdinalIgnoreCase) ||
                                             p.GetCustomAttributes<SettingsAliasAttribute>()
                                                .Any(a => setting.Key.Equals(a.Alias, StringComparison.OrdinalIgnoreCase)));

                    if (property != null)
                    {
                        try
                        {
                            if (property.PropertyType == typeof(bool) && (setting.Value == null || String.IsNullOrEmpty(setting.Value.ToString())))
                            {
                                property.SetValue(enreplacedyToPopulate, true);
                            }
                            else if (property.PropertyType.GetTypeInfo().IsEnum)
                            {
                                property.SetValue(enreplacedyToPopulate, Enum.Parse(property.PropertyType, setting.Value.ToString(), true));
                            }
                            else if (property.PropertyType.IsArray && setting.Value.GetType() == typeof(JArray))
                            {
                                var elementType = property.PropertyType.GetElementType();
                                if (elementType == typeof(string))
                                {
                                    var stringArray = ((JArray)setting.Value).Children().
                                    Select(
                                        c => c.ToString())
                                    .ToArray();

                                    property.SetValue(enreplacedyToPopulate, stringArray);
                                }
                                else if (elementType == typeof(int))
                                {
                                    var intValues = ((JArray)setting.Value).Children().
                                         Select(c => (int)Convert.ChangeType(c, elementType, CultureInfo.InvariantCulture))
                                         .ToArray();
                                    property.SetValue(enreplacedyToPopulate, intValues);
                                }
                            }
                            else if (property.CanWrite)
                            {
                                property.SetValue(enreplacedyToPopulate,
                                    Convert.ChangeType(setting.Value, property.PropertyType, CultureInfo.InvariantCulture), null);
                            }

                            settings.Remove(setting.Key);
                        }
                        catch (Exception exception)
                        {
                            throw new ArgumentException(String.Format(CultureInfo.InvariantCulture, Resources.ParameterValueIsNotValid,
                                setting.Key, property.GetType().Name), exception);
                        }
                    }
                }
            }
        }

19 View Source File : CinemachineConfiner.cs
License : MIT License
Project Creator : BattleDawnNZ

bool ValidatePathCache()
        {
#if CINEMACHINE_PHYSICS_2D
            Type colliderType = m_BoundingShape2D == null ? null:  m_BoundingShape2D.GetType();
            if (colliderType == typeof(PolygonCollider2D))
            {
                PolygonCollider2D poly = m_BoundingShape2D as PolygonCollider2D;
                if (m_pathCache == null || m_pathCache.Count != poly.pathCount || m_pathTotalPointCount != poly.GetTotalPointCount())
                {
                    m_pathCache = new List<List<Vector2>>();
                    for (int i = 0; i < poly.pathCount; ++i)
                    {
                        Vector2[] path = poly.GetPath(i);
                        List<Vector2> dst = new List<Vector2>();
                        for (int j = 0; j < path.Length; ++j)
                            dst.Add(path[j]);
                        m_pathCache.Add(dst);
                    }
                    m_pathTotalPointCount = poly.GetTotalPointCount();
                }
                return true;
            }
            else if (colliderType == typeof(CompositeCollider2D))
            {
                CompositeCollider2D poly = m_BoundingShape2D as CompositeCollider2D;
                if (m_pathCache == null || m_pathCache.Count != poly.pathCount || m_pathTotalPointCount != poly.pointCount)
                {
                    m_pathCache = new List<List<Vector2>>();
                    Vector2[] path = new Vector2[poly.pointCount];
                    for (int i = 0; i < poly.pathCount; ++i)
                    {
                        int numPoints = poly.GetPath(i, path);
                        List<Vector2> dst = new List<Vector2>();
                        for (int j = 0; j < numPoints; ++j)
                            dst.Add(path[j]);
                        m_pathCache.Add(dst);
                    }
                    m_pathTotalPointCount = poly.pointCount;
                }
                return true;
            }
#endif
            InvalidatePathCache();
            return false;
        }

19 View Source File : TrackAsset.cs
License : MIT License
Project Creator : BattleDawnNZ

public TimelineClip CreateDefaultClip()
        {
            var trackClipTypeAttributes = GetType().GetCustomAttributes(typeof(TrackClipTypeAttribute), true);
            Type playablereplacedetType = null;
            foreach (var trackClipTypeAttribute in trackClipTypeAttributes)
            {
                var attribute = trackClipTypeAttribute as TrackClipTypeAttribute;
                if (attribute != null && typeof(IPlayablereplacedet).IsreplacedignableFrom(attribute.inspectedType) && typeof(ScriptableObject).IsreplacedignableFrom(attribute.inspectedType))
                {
                    playablereplacedetType = attribute.inspectedType;
                    break;
                }
            }

            if (playablereplacedetType == null)
            {
                Debug.LogWarning("Cannot create a default clip for type " + GetType());
                return null;
            }
            return CreateAndAddNewClipOfType(playablereplacedetType);
        }

19 View Source File : TrackAsset.cs
License : MIT License
Project Creator : BattleDawnNZ

internal TimelineClip CreateClip(System.Type requestedType)
        {
            if (ValidateClipType(requestedType))
                return CreateAndAddNewClipOfType(requestedType);

            throw new InvalidOperationException("Clips of type " + requestedType + " are not permitted on tracks of type " + GetType());
        }

19 View Source File : TrackAsset.cs
License : MIT License
Project Creator : BattleDawnNZ

internal TimelineClip CreateClipOfType(Type requestedType)
        {
            if (!ValidateClipType(requestedType))
                throw new System.InvalidOperationException("Clips of type " + requestedType + " are not permitted on tracks of type " + GetType());

            var playablereplacedet = CreateInstance(requestedType);
            if (playablereplacedet == null)
            {
                throw new System.InvalidOperationException("Could not create an instance of the ScriptableObject type " + requestedType.Name);
            }
            playablereplacedet.name = requestedType.Name;
            TimelineCreateUtilities.SavereplacedetIntoObject(playablereplacedet, this);
            TimelineUndo.RegisterCreatedObjectUndo(playablereplacedet, "Create Clip");

            return CreateClipFromreplacedet(playablereplacedet);
        }

19 View Source File : TrackAsset.cs
License : MIT License
Project Creator : BattleDawnNZ

internal TimelineClip CreateClipFromPlayablereplacedet(IPlayablereplacedet replacedet)
        {
            if (replacedet == null)
                throw new ArgumentNullException("replacedet");

            if ((replacedet as ScriptableObject) == null)
                throw new System.ArgumentException("CreateClipFromPlayablereplacedet " + " only supports ScriptableObject-derived Types");

            if (!ValidateClipType(replacedet.GetType()))
                throw new System.InvalidOperationException("Clips of type " + replacedet.GetType() + " are not permitted on tracks of type " + GetType());

            return CreateClipFromreplacedet(replacedet as ScriptableObject);
        }

19 View Source File : TrackAsset.cs
License : MIT License
Project Creator : BattleDawnNZ

internal Playable CreatePlayableGraph(PlayableGraph graph, GameObject go, IntervalTree<RuntimeElement> tree, Playable timelinePlayable)
        {
            UpdateDuration();
            var mixerPlayable = Playable.Null;
            if (CanCompileClipsRecursive())
                mixerPlayable = OnCreateClipPlayableGraph(graph, go, tree);

            var notificationsPlayable = CreateNotificationsPlayable(graph, mixerPlayable, go, timelinePlayable);
            if (!notificationsPlayable.IsValid() && !mixerPlayable.IsValid())
            {
                Debug.LogErrorFormat("Track {0} of type {1} has no notifications and returns an invalid mixer Playable", name,
                    GetType().FullName);

                return Playable.Create(graph);
            }

            return notificationsPlayable.IsValid() ? notificationsPlayable : mixerPlayable;
        }

19 View Source File : TrackAsset.cs
License : MIT License
Project Creator : BattleDawnNZ

internal bool ValidateClipType(Type clipType)
        {
            var attrs = GetType().GetCustomAttributes(typeof(TrackClipTypeAttribute), true);
            for (var c = 0; c < attrs.Length; ++c)
            {
                var attr = (TrackClipTypeAttribute)attrs[c];
                if (attr.inspectedType.IsreplacedignableFrom(clipType))
                    return true;
            }

            // special case for playable tracks, they accept all clips (in the runtime)
            return typeof(PlayableTrack).IsreplacedignableFrom(GetType()) &&
                typeof(IPlayablereplacedet).IsreplacedignableFrom(clipType) &&
                typeof(ScriptableObject).IsreplacedignableFrom(clipType);
        }

19 View Source File : TrackAsset.cs
License : MIT License
Project Creator : BattleDawnNZ

internal bool IsCompilable()
        {
            var isContainer = typeof(GroupTrack).IsreplacedignableFrom(GetType());

            if (isContainer)
                return false;

            var ret = !mutedInHierarchy && (CanCompileClips() || CanCompileNotifications());
            if (!ret)
            {
                foreach (var t in GetChildTracks())
                {
                    if (t.IsCompilable())
                        return true;
                }
            }

            return ret;
        }

19 View Source File : AnimatorToolWindow.cs
License : MIT License
Project Creator : BlueMonk1107

[MenuItem("replacedets/AnimatorTool/Add", true)]
        public static bool ShowWindowInProjectValidate()
        {
            return Selection.activeObject.GetType() == typeof(GameObject);
        }

19 View Source File : AnimatorToolWindow.cs
License : MIT License
Project Creator : BlueMonk1107

[MenuItem("replacedets/AnimatorTool/AddAnimatorHelp", true)]
        public static bool AddAnimatorHelpInProjectValidate()
        {
            return Selection.activeObject.GetType() == typeof(AnimatorController);
        }

19 View Source File : SteamVR_TrackedCamera.cs
License : GNU General Public License v3.0
Project Creator : brandonmousseau

void Update()
            {
                if (Time.frameCount == prevFrameCount)
                    return;

                prevFrameCount = Time.frameCount;

                if (videostream.handle == 0)
                    return;

                var vr = SteamVR.instance;
                if (vr == null)
                    return;

                var trackedCamera = OpenVR.TrackedCamera;
                if (trackedCamera == null)
                    return;

                var nativeTex = System.IntPtr.Zero;
                var deviceTexture = (_texture != null) ? _texture : new Texture2D(2, 2);
                var headerSize = (uint)System.Runtime.InteropServices.Marshal.SizeOf(header.GetType());

                if (vr.textureType == ETextureType.OpenGL)
                {
                    if (glTextureId != 0)
                        trackedCamera.ReleaseVideoStreamTextureGL(videostream.handle, glTextureId);

                    if (trackedCamera.GetVideoStreamTextureGL(videostream.handle, frameType, ref glTextureId, ref header, headerSize) != EVRTrackedCameraError.None)
                        return;

                    nativeTex = (System.IntPtr)glTextureId;
                }
                else if (vr.textureType == ETextureType.DirectX)
                {
                    if (trackedCamera.GetVideoStreamTextureD3D11(videostream.handle, frameType, deviceTexture.GetNativeTexturePtr(), ref nativeTex, ref header, headerSize) != EVRTrackedCameraError.None)
                        return;
                }

                if (_texture == null)
                {
                    _texture = Texture2D.CreateExternalTexture((int)header.nWidth, (int)header.nHeight, TextureFormat.RGBA32, false, false, nativeTex);

                    uint width = 0, height = 0;
                    var frameBounds = new VRTextureBounds_t();
                    if (trackedCamera.GetVideoStreamTextureSize(deviceIndex, frameType, ref frameBounds, ref width, ref height) == EVRTrackedCameraError.None)
                    {
                        // Account for textures being upside-down in Unity.
                        frameBounds.vMin = 1.0f - frameBounds.vMin;
                        frameBounds.vMax = 1.0f - frameBounds.vMax;
                        this.frameBounds = frameBounds;
                    }
                }
                else
                {
                    _texture.UpdateExternalTexture(nativeTex);
                }
            }

19 View Source File : SteamVR_Utils.cs
License : GNU General Public License v3.0
Project Creator : brandonmousseau

public static System.Type FindType(string typeName)
	{
		var type = System.Type.GetType(typeName);
		if (type != null) return type;
		foreach (var a in System.AppDomain.CurrentDomain.Getreplacedemblies())
		{
			type = a.GetType(typeName);
			if (type != null)
				return type;
		}
		return null;
	}

19 View Source File : ExecuteMultipleResponseItemExtensions.cs
License : MIT License
Project Creator : Capgemini

public static OperationType GetOperationType(this ExecuteMultipleResponseItem response)
        {
            response.ThrowArgumentNullExceptionIfNull(nameof(response));

            if (response.Fault != null)
            {
                return OperationType.Failed;
            }

            switch (response.Response.GetType().Name)
            {
                case nameof(replacedignResponse):
                    return OperationType.replacedign;

                case nameof(replacedociateResponse):
                    return OperationType.replacedociate;

                case nameof(CreateResponse):
                    return OperationType.Create;

                case nameof(UpdateResponse):
                    return OperationType.Update;

                case nameof(UpsertResponse):
                    var responseTyped = response.Response as UpsertResponse;
                    return responseTyped.RecordCreated ? OperationType.Create : OperationType.Update;

                default:
                    throw new ArgumentOutOfRangeException($"Type {response.Response.GetType().Name} is not supported");
            }
        }

19 View Source File : ExecuteMultipleResponseItemExtensions.cs
License : MIT License
Project Creator : Capgemini

public static string GetOperationMessage(this ExecuteMultipleResponseItem response, Enreplacedy enreplacedy)
        {
            enreplacedy.ThrowArgumentNullExceptionIfNull(nameof(enreplacedy));
            response.ThrowArgumentNullExceptionIfNull(nameof(response));

            if (response.Fault != null)
            {
                return GetOperationResultError(response.Fault);
            }

            switch (response.Response.GetType().Name)
            {
                case nameof(CreateResponse):
                    var createResponse = response.Response as CreateResponse;
                    return $"Enreplacedy {enreplacedy.LogicalName}:{createResponse.id} {response.Response.ResponseName}";

                case nameof(UpsertResponse):
                    var upsertResponse = response.Response as UpsertResponse;
                    return $"Enreplacedy {enreplacedy.LogicalName}:{upsertResponse.Target.Id} {response.Response.ResponseName}";

                default:
                    return $"Enreplacedy {enreplacedy.LogicalName}:{enreplacedy.Id} {response.Response.ResponseName}";
            }
        }

19 View Source File : Attributes.cs
License : Apache License 2.0
Project Creator : codexguy

private Type? FindTypeByName(string name)
        {
            if (_typeCache.TryGetValue(name, out var t))
            {
                return t;
            }

            foreach (var a in AppDomain.CurrentDomain.Getreplacedemblies())
            {
                t = a.GetType(name, false);

                if (t != null)
                {
                    _typeCache[name] = t;
                    return t;
                }
            }

            return null;
        }

19 View Source File : TestRunnerStateSerializer.cs
License : Creative Commons Zero v1.0 Universal
Project Creator : Colanderp

public void RestoreContext()
        {
            var currentContext = UnityTestExecutionContext.CurrentContext;

            var outputProp = currentContext.CurrentResult.GetType().BaseType.GetField("_output", Flags);
            (outputProp.GetValue(currentContext.CurrentResult) as StringBuilder).Append(output);

            currentContext.StartTicks = StartTicks;
            currentContext.StartTime = DateTime.FromOADate(StartTimeOA);
            if (LogScope.HasCurrentLogScope())
            {
                LogScope.Current.ExpectedLogs = new Queue<LogMatch>(m_ExpectedLogs);
            }

            m_ShouldRestore = false;
        }

19 View Source File : TestResultSerializer.cs
License : Creative Commons Zero v1.0 Universal
Project Creator : Colanderp

public void RestoreTestResult(TestResult result)
        {
            var resultState = new ResultState((TestStatus)Enum.Parse(typeof(TestStatus), status), label,
                (FailureSite)Enum.Parse(typeof(FailureSite), site));
            result.GetType().BaseType.GetField("_resultState", flags).SetValue(result, resultState);
            result.GetType().BaseType.GetField("_output", flags).SetValue(result, new StringBuilder(output));
            result.GetType().BaseType.GetField("_duration", flags).SetValue(result, duration);
            result.GetType().BaseType.GetField("_message", flags).SetValue(result, message);
            result.GetType().BaseType.GetField("_stackTrace", flags).SetValue(result, stacktrace);
            result.GetType()
                .BaseType.GetProperty("StartTime", flags)
                .SetValue(result, DateTime.FromOADate(startTimeAO), null);
        }

19 View Source File : DefaultTestWorkItem.cs
License : Creative Commons Zero v1.0 Universal
Project Creator : Colanderp

protected override IEnumerable PerformWork()
        {
            if (m_DontRunRestoringResult && EditModeTestCallbacks.RestoringTestContext != null)
            {
                EditModeTestCallbacks.RestoringTestContext();
                Result = Context.CurrentResult;
                yield break;
            }

            try
            {
                if (_command is SkipCommand || _command is FailCommand)
                {
                    Result = _command.Execute(Context);
                    yield break;
                }

                if (!(_command is IEnumerableTestMethodCommand))
                {
                    Debug.LogError("Cannot perform work on " + _command.GetType().Name);
                    yield break;
                }

                foreach (var workItemStep in ((IEnumerableTestMethodCommand)_command).ExecuteEnumerable(Context))
                {
                    ResultedInDomainReload = false;

                    if (workItemStep is IEditModeTestYieldInstruction)
                    {
                        var editModeTestYieldInstruction = (IEditModeTestYieldInstruction)workItemStep;
                        yield return editModeTestYieldInstruction;
                        var enumerator = editModeTestYieldInstruction.Perform();
                        while (true)
                        {
                            bool moveNext;
                            try
                            {
                                moveNext = enumerator.MoveNext();
                            }
                            catch (Exception e)
                            {
                                Context.CurrentResult.RecordException(e);
                                break;
                            }

                            if (!moveNext)
                            {
                                break;
                            }

                            yield return null;
                        }
                    }
                    else
                    {
                        yield return workItemStep;
                    }
                }

                Result = Context.CurrentResult;
            }
            finally
            {
                WorkItemComplete();
            }
        }

19 View Source File : EditorGUIExtra.cs
License : MIT License
Project Creator : Crazy-Marvin

public static void MinMaxScroller(Rect position, int id, ref float value, ref float size, float visualStart, float visualEnd, float startLimit, float endLimit, GUIStyle slider, GUIStyle thumb, GUIStyle leftButton, GUIStyle rightButton, bool horiz)
		{
			Type editorGUIExtType = typeof(EditorWindow).replacedembly.GetType("UnityEditor.EditorGUIExt");

			MethodInfo minMaxScrollerMethod = editorGUIExtType.GetMethod("MinMaxScroller", BindingFlags.Static | BindingFlags.Public);

			if(minMaxScrollerMethod != null)
			{
				object[] parameters = new object[] { position, id, value, size, visualStart, visualEnd, startLimit, endLimit, slider, thumb, leftButton, rightButton, horiz };
				minMaxScrollerMethod.Invoke(null,parameters);

				value = (float)parameters[2];
				size = (float)parameters[3];
			}
		}

19 View Source File : SpriteMeshEditorWindow.cs
License : MIT License
Project Creator : Crazy-Marvin

bool GetLinearSampled(Texture2D texture)
		{
			bool result = false;
			
			MethodInfo methodInfo = typeof(Editor).replacedembly.GetType("UnityEditor.TextureUtil").GetMethod("GetLinearSampled", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			
			if(methodInfo != null)
			{
				object[] parameters = new object[] { texture };
				result = (bool)methodInfo.Invoke(null,parameters);
			}
			
			return result;
		}

19 View Source File : EditorExtra.cs
License : MIT License
Project Creator : Crazy-Marvin

public static GameObject PickGameObject(Vector2 mousePosition)
		{
			MethodInfo methodInfo = typeof(EditorWindow).replacedembly.GetType("UnityEditor.SceneViewPicking").GetMethod("PickGameObject", BindingFlags.Static | BindingFlags.Public);

			if(methodInfo != null)
			{
				return (GameObject)methodInfo.Invoke(null, new object[] { mousePosition });
			}

			return null;
		}

19 View Source File : SpriteMeshEditor.cs
License : MIT License
Project Creator : Crazy-Marvin

Texture2D BuildPreviewTexture(int width, int height, Sprite sprite, Material spriteRendererMaterial)
		{
			Texture2D result = null;
			
			MethodInfo methodInfo = typeof(Editor).replacedembly.GetType("UnityEditor.SpriteInspector").GetMethod("BuildPreviewTexture", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			
			if(methodInfo != null)
			{
#if UNITY_5_0_0 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
				object[] parameters = new object[] { width, height, sprite, spriteRendererMaterial };
#else
				object[] parameters = new object[] { width, height, sprite, spriteRendererMaterial, false };
#endif
				result = (Texture2D)methodInfo.Invoke(null,parameters);
			}
			
			return result;
		}

19 View Source File : SpriteMeshEditor.cs
License : MIT License
Project Creator : Crazy-Marvin

public static void DrawPreview(Rect r, Sprite frame, Material spriteRendererMaterial)
		{
			if (frame == null)
			{
				return;
			}
			MethodInfo methodInfo = typeof(Editor).replacedembly.GetType("UnityEditor.SpriteInspector").GetMethod("DrawPreview", BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic);
			
			if(methodInfo != null)
			{
#if UNITY_5_0_0 || UNITY_5_0 || UNITY_5_1 || UNITY_5_2
				object[] parameters = new object[] { r, frame, spriteRendererMaterial };
#else
				object[] parameters = new object[] { r, frame, spriteRendererMaterial, false };
#endif
				methodInfo.Invoke(null,parameters);
			}
			
		}

19 View Source File : PropertyCollectionForm.cs
License : MIT License
Project Creator : CslaGenFork

public void OnSelect(object sender, EventArgs e)
        {
            _propGrid.SelectedObjectsChanged -= OnSelect;

            if (_collectionType == typeof (ValueProperty))
            {
                var selectedObject = (ValueProperty) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                {
                    propertyInfo.SetValue(_propGrid, new ValuePropertyBag(selectedObject), null);
                    _parentValProp = selectedObject.Name;
                }
            }
            else if (_collectionType == typeof (ChildProperty))
            {
                var selectedObject = (ChildProperty) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                {
                    propertyInfo.SetValue(_propGrid, new ChildPropertyBag(selectedObject), null);
                    _parentValProp = selectedObject.Name;
                }
            }
            else if (_collectionType == typeof (UnitOfWorkProperty))
            {
                var selectedObject = (UnitOfWorkProperty) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new UnitOfWorkPropertyBag(selectedObject), null);
            }
            else if (_collectionType == typeof (Criteria))
            {
                var selectedObject = (Criteria) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new CriteriaBag(selectedObject), null);
            }
            else if (_collectionType == typeof (CriteriaProperty))
            {
                var selectedObject = (CriteriaProperty) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new CriteriaPropertyBag(selectedObject), null);
            }
            else if (_collectionType == typeof (ConvertValueProperty))
            {
                var selectedObject = (ConvertValueProperty) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                {
                    propertyInfo.SetValue(_propGrid, new ConvertValuePropertyBag(selectedObject), null);
                    _parentValProp = selectedObject.Name;
                }
            }
            else if (_collectionType == typeof (UpdateValueProperty))
            {
                var selectedObject = (UpdateValueProperty) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new UpdateValuePropertyBag(selectedObject), null);
            }
            else if (_collectionType == typeof (Rule))
            {
                var selectedObject = (Rule) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new RuleBag(selectedObject), null);
            }
            else if (_collectionType == typeof(BusinessRule))
            {
                var selectedObject = (BusinessRule) _propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                {
                    if (!string.IsNullOrEmpty(ParentValProp))
                    {
                        selectedObject.IsPropertyRule = true;
                        selectedObject.Parent = _parentValProp;
                    }
                    else
                    {
                        selectedObject.IsPropertyRule= false;
                        selectedObject.Parent = string.Empty;
                    }
                    
                    propertyInfo.SetValue(_propGrid, new BusinessRuleBag(selectedObject), null);

                    var ruleCount = 0;
                    var baseCount = 0;
                    var heightIncrease = 0;
                    var rules = ((BusinessRuleBag) _propGrid.SelectedObject).SelectedObject;
                    foreach (var businessRule in rules)
                    {
                        ruleCount = businessRule.RuleProperties.Count;
                        if (ruleCount > 0)
                            heightIncrease = 16 + (ruleCount*16);

                        baseCount = businessRule.BaseRuleProperties.Count;
                        if (baseCount > 0)
                            heightIncrease += 16 + (baseCount*16);

                        if (ruleCount == 0 && baseCount == 0)
                        {
                            if (_form.Size.Height != 330)
                                _form.Size = new Size(_form.Size.Width, 330);
                        }
                        else
                        {
                            if (_form.Size.Height != 294 + heightIncrease)
                                _form.Size = new Size(_form.Size.Width, 294 + heightIncrease);
                        }
                    }
                }
            }
            else if (_collectionType == typeof(BusinessRuleConstructor))
            {
                var selectedObject = (BusinessRuleConstructor)_propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                {
                    //selectedObject.Parent = _parentValProp;
                    propertyInfo.SetValue(_propGrid, new BusinessRuleConstructorBag(selectedObject), null);

                    var parameterCount = 0;
                    var genericCount = 0;
                    var heightIncrease = 0;
                    var constructors = ((BusinessRuleConstructorBag)_propGrid.SelectedObject).SelectedObject;
                    foreach (var constructor in constructors)
                    {
                        parameterCount = constructor.ConstructorParameters.Count;
                        heightIncrease = parameterCount * 16;

                        foreach (var parameter in constructor.ConstructorParameters)
                        {
                            if (parameter.IsGenericType)
                                genericCount++;
                        }
                        if (genericCount > 0)
                            heightIncrease += 16 + (genericCount * 16);

                        if (parameterCount == 0 && genericCount == 0)
                        {
                            if (_form.Size.Height != 330)
                                _form.Size = new Size(_form.Size.Width, 330);
                        }
                        else
                        {
                            if (_form.Size.Height != 262 + heightIncrease)
                                _form.Size = new Size(_form.Size.Width, 262 + heightIncrease);
                        }
                    }
                }
            }
            /*else if (_collectionType == typeof(BusinessRuleProperty))
            {
                var selectedObject = (BusinessRuleProperty)_propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new BusinessRulePropertyBag(selectedObject), null);
            }
            else if (_collectionType == typeof(BusinessRuleParameter))
            {
                var selectedObject = (BusinessRuleParameter)_propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new BusinessRuleParameterBag(selectedObject), null);
            }*/
            else if (_collectionType == typeof(DecoratorArgument))
            {
                var selectedObject = (DecoratorArgument)_propGrid.SelectedObject;
                //Get the property grid's type.
                //This is a vsPropertyGrid located in System.Windows.Forms.Design
                var propertyInfo = _propGrid.GetType().GetProperty("SelectedObject", BindingFlags.Public | BindingFlags.Instance);
                if (selectedObject != null)
                    propertyInfo.SetValue(_propGrid, new DecoratorArgumentBag(selectedObject), null);
            }

            _propGrid.Layout += pgEditor_Layout;

            _propGrid.SelectedObjectsChanged += OnSelect;
        }

19 View Source File : PropertyCollectionForm.cs
License : MIT License
Project Creator : CslaGenFork

protected override CollectionForm CreateCollectionForm()
        {
            _form = base.CreateCollectionForm();

            HandleFormCollectionType();

            // hook events for expanding Criteria properties hierarchy
            if (_collectionType == typeof (Criteria))
            {
                foreach (Control control in _form.Controls)
                {
                    if (control is TableLayoutPanel)
                    {
                        foreach (var panelControl in control.Controls)
                        {
                            if (panelControl is ListBox)
                            {
                                ((ListBox) panelControl).SelectedIndexChanged += OnIndexChanged;
                            }
                            else if (panelControl is TableLayoutPanel)
                            {
                                var layoutPanel = (TableLayoutPanel) panelControl;
                                foreach (var tableControl in layoutPanel.Controls)
                                {
                                    if (tableControl is Button)
                                    {
                                        var button = (Button) tableControl;
                                        if (button.Text.IndexOf("Add") > 0 || button.Text.IndexOf("Remove") > 0)
                                            button.Click += OnItemAddedOrRemoved;
                                    }
                                }
                            }
                            else if (panelControl is PropertyGrid)
                            {
                                ((PropertyGrid) panelControl).SelectedGridItemChanged += OnGridItemChanged;
                            }
                        }
                    }
                }
            }
            else if (_collectionType == typeof(ValueProperty) || _collectionType == typeof(ChildProperty))
            {
                foreach (Control control in _form.Controls)
                {
                    if (control is TableLayoutPanel)
                    {
                        foreach (var panelControl in control.Controls)
                        {
                            if (panelControl is PropertyGrid)
                            {
                                ((PropertyGrid) panelControl).SelectedGridItemChanged += OnGridItemChangedProperty;
                            }
                            
                            if (panelControl is TableLayoutPanel)
                            {
                                var layoutPanel = (TableLayoutPanel)panelControl;
                                if (layoutPanel.Name == "okCancelTableLayoutPanel")
                                {
                                    foreach (var tableControl in layoutPanel.Controls)
                                    {
                                        if (tableControl is Button)
                                        {
                                            var button = (Button) tableControl;
                                            if (button.Name == "cancelButton" || button.Name == "okButton")
                                            {
                                                exitButton[button.Name] = button;
                                                button.Click += ExitButtonClickHandler;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }
            /*else if (_collectionType == typeof (BusinessRuleProperty))
            {
                // hide Add & Remove buttons
                foreach (Control control in _form.Controls)
                {
                    if (control is TableLayoutPanel)
                    {
                        foreach (var panelControl in control.Controls)
                        {
                            if (panelControl is TableLayoutPanel)
                            {
                                var layoutPanel = (TableLayoutPanel) panelControl;
                                foreach (var tableControl in layoutPanel.Controls)
                                {
                                    if (tableControl is Button)
                                    {
                                        var button = (Button) tableControl;
                                        if (button.Text.IndexOf("Add") > 0 || button.Text.IndexOf("Remove") > 0)
                                        {
                                            button.Hide();
                                            button.Enabled = false;
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }*/
            else if (_collectionType == typeof(BusinessRuleConstructor))
            {
                // hide Add & Remove buttons
                foreach (Control control in _form.Controls)
                {
                    if (control is TableLayoutPanel)
                    {
                        foreach (var panelControl in control.Controls)
                        {
                            if (panelControl is TableLayoutPanel)
                            {
                                var layoutPanel = (TableLayoutPanel)panelControl;
                                if (layoutPanel.Name == "addRemoveTableLayoutPanel")
                                {
                                    foreach (var tableControl in layoutPanel.Controls)
                                    {
                                        if (tableControl is Button)
                                        {
                                            var button = (Button) tableControl;
                                            if (button.Name == "addButton" || button.Name == "removeButton")
                                            {
                                                button.Hide();
                                                button.Enabled = false;
                                            }
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
            }

            var formType = _form.GetType();

            //Get a reference to the private fieldtype propertyBrowser
            //This is the PropertGrid inside the CollectionForm
            var fieldInfo = formType.GetField("propertyBrowser", BindingFlags.NonPublic | BindingFlags.Instance);

            if (fieldInfo != null)
            {
                _propGrid = (PropertyGrid) fieldInfo.GetValue(_form);

                if (_propGrid != null)
                {
                    _propGrid.ToolbarVisible = true;
                    _propGrid.HelpVisible = true;
                    _propGrid.PropertySort = PropertySort.Categorized;
                    _propGrid.PropertySortChanged += OnSort;
                    _propGrid.SelectedObjectsChanged += OnSelect;

                    /*//Get the property grid's type.
                    //This is a vsPropertyGrid located in System.Windows.Forms.Design
                    Type propertyGridType = _propGrid.GetType();

                    //Get a reference to the non-public property ToolStripRenderer
                    PropertyInfo propertyInfo = propertyGridType.GetProperty("ToolStripRenderer", BindingFlags.NonPublic | BindingFlags.Instance);

                    if (propertyInfo != null)
                    {
                        //replacedign a ToolStripProfessionalRenderer with our custom color table
                        propertyInfo.SetValue(_propGrid, new ToolStripProfessionalRenderer(new CustomColorTable()), null);
                    }*/
                }
            }
            _form.Shown += OnFormShow;

            return _form;
        }

19 View Source File : AuthorizationRule.cs
License : MIT License
Project Creator : CslaGenFork

public Type GetInheritedType()
        {
            if (_replacedemblyFile != null && _replacedemblyFile != String.Empty)
            {
                replacedembly replacedembly = replacedembly.LoadFrom(_replacedemblyFile);
                Type t = replacedembly.GetType(_type);
                if (t == null)
                {
                    throw new Exception("Type does not exist in replacedembly");
                }
                return t;
            }
            return null;
        }

See More Examples