System.Type.ToString()

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

2253 Examples 7

19 Source : JcApiHelper_InitParam.cs
with MIT License
from 279328316

private static ParamModel GetParam(PropertyInfo pi, int index = 0)
        {
            PTypeModel ptype = GetPType(pi.PropertyType);

            string piId = null;
            if (pi.DeclaringType != null)
            {
                string declaringTypeName = pi.DeclaringType.ToString();
                if (declaringTypeName.IndexOf("`") != -1)
                {   //泛型属性Id结构如下:P:Jc.Core.Robj`1.Result
                    declaringTypeName = declaringTypeName.Substring(0, declaringTypeName.IndexOf("`") + 2);
                }
                piId = $"P:{declaringTypeName}.{pi.Name}";
            }

            ParamModel param = new ParamModel()
            {
                Name = pi.Name,
                Id = piId,
                PType = ptype,
                CustomAttrList = pi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
                Position = index + 1
            };
            if(pi.CustomAttributes.Count()>0)
            {

            }
            return param;
        }

19 Source : TypeHelper.cs
with MIT License
from 279328316

internal static string GetModuleMark(Type type)
        {
            string moduleMark = type.ToString();

            switch (type.MemberType)
            {
                case MemberTypes.TypeInfo:
                    moduleMark = type.ToString();
                    break;
            }
            moduleMark = type.MemberType.ToString().Substring(0, 1) + ":" + moduleMark;
            return moduleMark;
        }

19 Source : JcApiHelper_InitParam.cs
with MIT License
from 279328316

private static ParamModel GetParam(FieldInfo fi, int index = 0)
        {
            PTypeModel ptype = GetPType(fi.FieldType);
            int? value = null;
            if (fi.FieldType.IsEnum)
            {
                try
                {
                    value = Convert.ToInt32(Enum.Parse(fi.FieldType, fi.Name));
                }
                catch
                {   //如转换失败,忽略不做处理
                }
            }

            string fiId = null;
            if (fi.DeclaringType != null)
            {
                fiId = $"F:{fi.DeclaringType.ToString()}.{fi.Name}";
            }

            ParamModel param = new ParamModel()
            {
                Name = fi.Name,
                Id = fiId,
                PType = ptype,
                ParamValue = value,
                CustomAttrList = fi.CustomAttributes.Select(a => GetCustomAttribute(a)).ToList(),
                Position = index + 1
            };

            if (fi.CustomAttributes.Count() > 0)
            {

            }
            return param;
        }

19 Source : RedisClient.cs
with MIT License
from 2881099

internal T DeserializeRedisValue<T>(byte[] valueRaw, Encoding encoding)
        {
            if (valueRaw == null) return default(T);
            var type = typeof(T);
            var typename = type.ToString().TrimEnd(']');
            if (typename == "System.Byte[") return (T)Convert.ChangeType(valueRaw, type);
            if (typename == "System.String") return (T)Convert.ChangeType(encoding.GetString(valueRaw), type);
            if (typename == "System.Boolean[") return (T)Convert.ChangeType(valueRaw.Select(a => a == 49).ToArray(), type);
            if (valueRaw.Length == 0) return default(T);

            string valueStr = null;
            if (type.IsValueType)
            {
                valueStr = encoding.GetString(valueRaw);
                bool isNullable = typename.StartsWith("System.Nullable`1[");
                var basename = isNullable ? typename.Substring(18) : typename;

                bool isElse = false;
                object obj = null;
                switch (basename)
                {
                    case "System.Boolean":
                        if (valueStr == "1") obj = true;
                        else if (valueStr == "0") obj = false;
                        break;
                    case "System.Byte":
                        if (byte.TryParse(valueStr, out var trybyte)) obj = trybyte;
                        break;
                    case "System.Char":
                        if (valueStr.Length > 0) obj = valueStr[0];
                        break;
                    case "System.Decimal":
                        if (Decimal.TryParse(valueStr, out var trydec)) obj = trydec;
                        break;
                    case "System.Double":
                        if (Double.TryParse(valueStr, out var trydb)) obj = trydb;
                        break;
                    case "System.Single":
                        if (Single.TryParse(valueStr, out var trysg)) obj = trysg;
                        break;
                    case "System.Int32":
                        if (Int32.TryParse(valueStr, out var tryint32)) obj = tryint32;
                        break;
                    case "System.Int64":
                        if (Int64.TryParse(valueStr, out var tryint64)) obj = tryint64;
                        break;
                    case "System.SByte":
                        if (SByte.TryParse(valueStr, out var trysb)) obj = trysb;
                        break;
                    case "System.Int16":
                        if (Int16.TryParse(valueStr, out var tryint16)) obj = tryint16;
                        break;
                    case "System.UInt32":
                        if (UInt32.TryParse(valueStr, out var tryuint32)) obj = tryuint32;
                        break;
                    case "System.UInt64":
                        if (UInt64.TryParse(valueStr, out var tryuint64)) obj = tryuint64;
                        break;
                    case "System.UInt16":
                        if (UInt16.TryParse(valueStr, out var tryuint16)) obj = tryuint16;
                        break;
                    case "System.DateTime":
                        if (DateTime.TryParse(valueStr, out var trydt)) obj = trydt;
                        break;
                    case "System.DateTimeOffset":
                        if (DateTimeOffset.TryParse(valueStr, out var trydtos)) obj = trydtos;
                        break;
                    case "System.TimeSpan":
                        if (Int64.TryParse(valueStr, out tryint64)) obj = new TimeSpan(tryint64);
                        break;
                    case "System.Guid":
                        if (Guid.TryParse(valueStr, out var tryguid)) obj = tryguid;
                        break;
                    default:
                        isElse = true;
                        break;
                }

                if (isElse == false)
                {
                    if (obj == null) return default(T);
                    return (T)obj;
                }
            }

            if (Adapter.TopOwner.DeserializeRaw != null) return (T)Adapter.TopOwner.DeserializeRaw(valueRaw, typeof(T));

            if (valueStr == null) valueStr = encoding.GetString(valueRaw);
            if (Adapter.TopOwner.Deserialize != null) return (T)Adapter.TopOwner.Deserialize(valueStr, typeof(T));
            return valueStr.ConvertTo<T>();
        }

19 Source : NGUITools.cs
with Apache License 2.0
from 365082218

static public string GetName<T> () where T : Component
	{
		string s = typeof(T).ToString();
		if (s.StartsWith("UI")) s = s.Substring(2);
		else if (s.StartsWith("UnityEngine.")) s = s.Substring(12);
		return s;
	}

19 Source : DOTweenAnimation.cs
with MIT License
from 39M

public static TargetType TypeToDOTargetType(Type t)
        {
            string str = t.ToString();
            int dotIndex = str.LastIndexOf(".");
            if (dotIndex != -1) str = str.Substring(dotIndex + 1);
            if (str.IndexOf("Renderer") != -1 && (str != "SpriteRenderer")) str = "Renderer";
            return (TargetType)Enum.Parse(typeof(TargetType), str);
        }

19 Source : WebhookServerBase.cs
with MIT License
from 4egod

private void CreateWebhookHost()
        {
            var builder = WebHost.CreateDefaultBuilder();

            builder.ConfigureServices(cfg =>
            {
                cfg.AddRouting();
            });

            builder.ConfigureLogging(cfg =>
            {
                cfg.SetMinimumLevel(LogLevel);
                //cfg.ClearProviders();
                //cfg.AddConsole();
                //cfg.AddDebug();
            });

            builder.UseKestrel(options =>
            {
                if (pfxPath == null) options.Listen(IPAddress.Any, Port);
                else options.Listen(IPAddress.Any, Port, op=>
                {
                    op.UseHttps(pfxPath, pfxPreplacedword);
                });
            });

            builder.Configure(cfg =>
            {
                cfg.UseRouter(r =>
                {
                    r.MapGet(StatusPath, Status);
                    r.MapGet(WebhookPath, Get);
                    r.MapPost(WebhookPath, Post);
                });
            });

            Host = builder.Build();
            Logger = Host.Services.GetService<ILoggerFactory>().CreateLogger(this.GetType().ToString() + $"[{IPAddress.Any}:{Port}]");
        }

19 Source : WebhookServer.cs
with MIT License
from 4egod

private void CreateWebhookHost()
        {
            var builder = WebHost.CreateDefaultBuilder();

            builder.ConfigureServices(cfg =>
            {
                cfg.AddRouting();
            });

            builder.ConfigureLogging(cfg =>
            {
                cfg.SetMinimumLevel(logLevel);
                //cfg.ClearProviders();
                //cfg.AddConsole();
                //cfg.AddDebug();
            });

            builder.UseKestrel(options =>
            {
                options.Listen(IPAddress.Any, Port);
            });

            builder.Configure(cfg =>
            {
                cfg.UseRouter(r =>
                {
                    r.MapGet(WebhookTestPath, Test);
                    r.MapGet(WebhookPath, Get);
                    r.MapPost(WebhookPath, Post);
                });
            });

            host = builder.Build();
            Logger = host.Services.GetService<ILoggerFactory>().CreateLogger(this.GetType().ToString() + $"[{IPAddress.Any}:{Port}]");
        }

19 Source : RtmpServer.cs
with MIT License
from a1q123456

private async void AcceptCallback(IAsyncResult ar, CancellationToken ct)
        {
            Socket listener = (Socket)ar.AsyncState;
            Socket client = listener.EndAccept(ar);
            client.NoDelay = true;
            // Signal the main thread to continue.
            _allDone.Set();
            IOPipeLine pipe = null;
            try
            {
                pipe = new IOPipeLine(client, _options);
                await pipe.StartAsync(ct);
            }
            catch (TimeoutException)
            {
                client.Close();
            }
            catch (Exception e)
            {
                Console.WriteLine("{0} Message: {1}", e.GetType().ToString(), e.Message);
                Console.WriteLine(e.StackTrace);
                client.Close();
            }
            finally
            {
                pipe?.Dispose();
            }
        }

19 Source : UMAAssetIndexerEditor.cs
with Apache License 2.0
from A7ocin

public void ShowTypes()
		{
			GUILayout.BeginHorizontal(EditorStyles.toolbarButton);
			GUILayout.Space(10);
			bShowTypes = EditorGUILayout.Foldout(bShowTypes, "Additional Indexed Types");
			GUILayout.EndHorizontal();

			if (bShowTypes)
			{
				GUIHelper.BeginVerticalPadded(10, new Color(0.75f, 0.875f, 1f));

				// Draw and handle the Drag/Drop
				GUILayout.Space(20);
				Rect dropTypeArea = GUILayoutUtility.GetRect(0.0f, 50.0f, GUILayout.ExpandWidth(true));
				GUI.Box(dropTypeArea, "Drag a single type here to start indexing that type.");
				GUILayout.Space(20);
				DropAreaType(dropTypeArea);
				foreach (string s in UAI.IndexedTypeNames)
				{
					System.Type CurrentType = System.Type.GetType(s);
					GUILayout.BeginHorizontal(EditorStyles.textField);
					GUILayout.Label(CurrentType.ToString(), GUILayout.MinWidth(240));
					if (GUILayout.Button("-", GUILayout.Width(20.0f)))
					{
						RemovedTypes.Add(CurrentType);
					}
					GUILayout.EndHorizontal();
				}
				GUIHelper.EndVerticalPadded(10);
			}
		}

19 Source : DownloadingAssetsList.cs
with Apache License 2.0
from A7ocin

private T GetTempreplacedet<T>() where T : UnityEngine.Object
		{
			T thisTempreplacedet = null;
			//we only want the last bit after any replacedembly
			var thisTypeName = typeof(T).ToString().Replace(typeof(T).Namespace + ".", "");
			//check RuntimeAnimatorController because these get called different things in the editor and in game
			if (typeof(T) == typeof(RuntimeAnimatorController))
				thisTypeName = "RuntimeAnimatorController";
			T thisPlaceholder = (T)Resources.Load<T>("Placeholderreplacedets/" + thisTypeName + "Placeholder") as T;
			if (thisPlaceholder != null)//can we replacedume if an replacedet was found its a scriptableobject
			{
				thisTempreplacedet = ScriptableObject.Instantiate(thisPlaceholder) as T;
			}
			else
			{
				if (typeof(ScriptableObject).IsreplacedignableFrom(typeof(T)))
				{
					thisTempreplacedet = ScriptableObject.CreateInstance(typeof(T)) as T;
				}
				else
				{
					thisTempreplacedet = (T)Activator.CreateInstance(typeof(T));
				}
			}
			return thisTempreplacedet;
		}

19 Source : UMATextRecipe.cs
with Apache License 2.0
from A7ocin

public override string GetInfo()
		{
			return string.Format(this.GetType().ToString() + ", internal storage string Length {0}", recipeString.Length);
		}

19 Source : CommonUtils.cs
with Apache License 2.0
from AantCoder

static string Process(object obj, int level, string prefLine, Dictionary<object, int> forParentLink, HashSet<string> excludeTypes)
        {
            try
            {
                if (obj == null) return "";
                Type type = obj.GetType();
                if (excludeTypes.Contains(type.Name)) return "<skip>";
                if (type == typeof(DateTime))
                {
                    return ((DateTime)obj).ToString("g");
                }
                else if (type.IsValueType || type == typeof(string))
                {
                    return obj.ToString();
                }
                else if (type.IsArray || obj is IEnumerable)
                {
                    string elementType = null;
                    Array array = null;

                    if (type.IsArray)
                    {
                        var tt = Type.GetType(type.FullName.Replace("[]", string.Empty));
                        if (tt != null)
                        {
                            elementType = tt.ToString();
                            if (excludeTypes.Contains(tt.Name)) return "<skips>";
                        }
                        //else return "<EEEEEEE" + type.FullName;
                        array = obj as Array;
                    }
                    else
                    {
                        //как лучше узнать кол-во и тип?
                        int cnt = 0;
                        foreach (var o in obj as IEnumerable) cnt++;
                        array = Array.CreateInstance(typeof(object), cnt);
                        int i = 0;
                        foreach (var o in obj as IEnumerable)
                        {
                            if (elementType == null && o != null)
                            {
                                var tt = o.GetType();
                                if (excludeTypes.Contains(tt.Name)) return "<skips>";
                                elementType = tt.ToString();
                            }
                            array.SetValue(o, i++);
                        }
                    }

                    if (elementType == null) elementType = "Object";

                    if (excludeTypes.Contains(elementType)) return "<skips>";

                    var info = "<" + elementType + "[" + array.Length.ToString() + "]" + ">";

                    if (level == 0)
                    {
                        return info + "[...]";
                    }

                    if (array.Length > 0)
                    {
                        var ress = new string[array.Length];
                        var resl = 0;
                        for (int i = 0; i < array.Length; i++)
                        {
                            ress[i] = Process(array.GetValue(i), level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "[" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "]";
                        }
                        else
                        {
                            var res = info + "["
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "]";
                        }
                    }
                    return info + "[]";
                }
                else if (obj is Type) return "<Type>" + obj.ToString();
                else if (type.IsClreplaced)
                {
                    var info = "<" + type.Name + ">";

                    if (forParentLink.ContainsKey(obj))
                    {
                        if (forParentLink[obj] >= level)
                            return info + "{duplicate}";
                        else
                            forParentLink[obj] = level;
                    }
                    else
                        forParentLink.Add(obj, level);

                    if (level == 0)
                    {
                        return info + "{...}";
                    }

                    FieldInfo[] fields = type.GetFields(BindingFlags.Public |
                                BindingFlags.NonPublic | BindingFlags.Instance);

                    if (fields.Length > 0)
                    {
                        var ress = new string[fields.Length];
                        var resl = 0;
                        for (int i = 0; i < fields.Length; i++)
                        {
                            object fieldValue = fields[i].GetValue(obj);
                            ress[i] = fieldValue == null
                                ? fields[i].Name + ": null"
                                : fields[i].Name + ": " + Process(fieldValue, level - 1, prefLine + PrefLineTab, forParentLink, excludeTypes);
                            resl += ress[i].Length;
                        }

                        if (resl < LineLength)
                        {
                            var res = info + "{" + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", " + ress[i];
                            }
                            return res + "}";
                        }
                        else
                        {
                            var res = info + "{"
                                + Environment.NewLine + prefLine + ress[0];
                            for (int i = 1; i < ress.Length; i++)
                            {
                                res += ", "
                                    + Environment.NewLine + prefLine + ress[i];
                            }
                            return res + Environment.NewLine + prefLine + "}";
                        }
                    }
                    return info + "{}";
                }
                else
                    throw new ArgumentException("Unknown type");
            }
            catch
            {
                return "<exception>";
            }
        }

19 Source : DellFanManagementApp.cs
with GNU General Public License v3.0
from AaronKelley

[STAThread]
        static int Main(string[] args)
        {
            if (args.Length == 0)
            {
                // GUI mode.
                try
                {
                    if (UacHelper.IsProcessElevated())
                    {
                        // Looks like we're ready to start up the GUI app.
                        // Set process priority to high.
                        Process.GetCurrentProcess().PriorityClreplaced = ProcessPriorityClreplaced.High;

                        // Boilerplate code to start the app.
                        Application.SetHighDpiMode(HighDpiMode.DpiUnaware);
                        Application.EnableVisualStyles();
                        Application.SetCompatibleTextRenderingDefault(false);
                        Application.Run(new DellFanManagementGuiForm());
                    }
                    else
                    {
                        MessageBox.Show("This program must be run with administrative privileges.", "Dell Fan Management privilege check", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    }
                }
                catch (Exception exception)
                {
                    MessageBox.Show(string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace),
                        "Error starting application", MessageBoxButtons.OK, MessageBoxIcon.Error);
                    return 1;
                }

                return 0;
            }
            else
            {
                // CMD mode.
                try
                {
                    Console.WriteLine("Dell Fan Management, version {0}", Version);
                    Console.WriteLine("By Aaron Kelley");
                    Console.WriteLine("Licensed under GPLv3");
                    Console.WriteLine("Source code available at https://github.com/AaronKelley/DellFanManagement");
                    Console.WriteLine();

                    if (UacHelper.IsProcessElevated())
                    {
                        if (args[0].ToLower() == "packagetest")
                        {
                            return PackageTest.RunPackageTests() ? 0 : 1;
                        }
                        else if (args[0].ToLower() == "setthermalsetting")
                        {
                            return SetThermalSetting.ExecuteSetThermalSetting(args);
                        }
                        else if (args[0].ToLower() == "smi-token-dump")
                        {
                            return SmiTokenDump();
                        }
                        else if (args[0].ToLower() == "smi-get-token")
                        {
                            return SmiGetToken(args);
                        }
                        else if (args[0].ToLower() == "smi-set-token")
                        {
                            return SmiSetToken(args);
                        }
                        else
                        {
                            Console.WriteLine("Dell SMM I/O driver by 424778940z");
                            Console.WriteLine("https://github.com/424778940z/bzh-windrv-dell-smm-io");
                            Console.WriteLine();
                            Console.WriteLine("Derived from \"Dell fan utility\" by 424778940z");
                            Console.WriteLine("https://github.com/424778940z/dell-fan-utility");
                            Console.WriteLine();

                            return DellFanCmd.ProcessCommand(args);
                        }
                    }
                    else
                    {
                        Console.WriteLine();
                        Console.WriteLine("This program must be run with administrative privileges.");
                        return 1;
                    }
                }
                catch (Exception exception)
                {
                    Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                    return 1;
                }
            }
        }

19 Source : PackageTest.cs
with GNU General Public License v3.0
from AaronKelley

private static bool DellSmbiosBzhTest()
        {
            try
            {
                Console.WriteLine("Running DellSmbiosBzhLib test.");

                if (!DellSmbiosBzh.Initialize())
                {
                    Console.WriteLine("  Failed to load driver.");
                    return false;
                }

                uint? result = DellSmbiosBzh.GetFanRpm(BzhFanIndex.Fan1);
                Console.WriteLine("  Fan 1 RPM: {0}", result);

                DellSmbiosBzh.Shutdown();
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                return false;
            }

            Console.WriteLine("  ...Preplaceded.");
            return true;
        }

19 Source : PackageTest.cs
with GNU General Public License v3.0
from AaronKelley

private static bool DellSmbiosSmiTest()
        {
            try
            {
                Console.WriteLine("Running DellSmbiosSmiLib test.");

                ThermalSetting currentSetting = DellSmbiosSmi.GetThermalSetting();
                Console.WriteLine("Thermal setting: {0}", currentSetting);
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                return false;
            }

            Console.WriteLine("  ...Preplaceded.");
            return true;
        }

19 Source : PackageTest.cs
with GNU General Public License v3.0
from AaronKelley

private static bool IrrKlangTest()
        {
            try
            {
                Console.WriteLine("Running irrKlang test.");

                new SoundPlayer().PlaySound(@"C:\Windows\Media\Windows Logon.wav");

                foreach (AudioDevice audioDevice in Utility.GetAudioDevices())
                {
                    Console.WriteLine("  {0}: {1}", audioDevice.DeviceId, audioDevice.DeviceName);
                }
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                return false;
            }

            Console.WriteLine("  ...Preplaceded.");
            return true;
        }

19 Source : Core.cs
with GNU General Public License v3.0
from AaronKelley

private void BackgroundThread()
        {
            _state.WaitOne();
            _state.BackgroundThreadRunning = true;
            _state.Release();

            bool releaseSemapreplaced = false;

            try
            {
                if (_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
                {
                    _fanController.EnableAutomaticFanControl();
                    Log.Write("Enabled EC fan control – startup");
                }

                while (_state.BackgroundThreadRunning)
                {
                    _state.WaitOne();
                    _requestSemapreplaced.WaitOne();
                    releaseSemapreplaced = true;

                    // Update state.
                    _state.Update();

                    // Take action based on configuration.
                    if (_state.OperationMode == OperationMode.Automatic)
                    {
                        if (!_state.EcFanControlEnabled && IsAutomaticFanControlDisableSupported)
                        {
                            _state.EcFanControlEnabled = true;
                            _fanController.EnableAutomaticFanControl();
                            Log.Write("Enabled EC fan control – automatic mode");
                        }
                    }
                    else if (_state.OperationMode == OperationMode.Manual && IsAutomaticFanControlDisableSupported && IsSpecificFanControlSupported)
                    {
                        // Check for EC control state changes that need to be applied.
                        if (_ecFanControlRequested && !_state.EcFanControlEnabled)
                        {
                            _state.EcFanControlEnabled = true;
                            _fanController.EnableAutomaticFanControl();
                            Log.Write("Enabled EC fan control – manual mode");

                            _state.Fan1Level = null;
                            _state.Fan2Level = null;
                            _fan1LevelRequested = null;
                            _fan2LevelRequested = null;
                        }
                        else if (!_ecFanControlRequested && _state.EcFanControlEnabled)
                        {
                            _state.EcFanControlEnabled = false;
                            _fanController.DisableAutomaticFanControl();
                            Log.Write("Disabled EC fan control – manual mode");
                        }

                        // Check for fan control state changes that need to be applied.
                        if (!_state.EcFanControlEnabled)
                        {
                            if (_state.Fan1Level != _fan1LevelRequested)
                            {
                                _state.Fan1Level = _fan1LevelRequested;
                                if (_fan1LevelRequested != null)
                                {
                                    _fanController.SetFanLevel((FanLevel)_fan1LevelRequested, IsIndividualFanControlSupported ? FanIndex.Fan1 : FanIndex.AllFans);
                                }
                            }

                            if (_state.Fan2Present && IsIndividualFanControlSupported && _state.Fan2Level != _fan2LevelRequested)
                            {
                                _state.Fan2Level = _fan2LevelRequested;
                                if (_fan2LevelRequested != null)
                                {
                                    _fanController.SetFanLevel((FanLevel)_fan2LevelRequested, FanIndex.Fan2);
                                }
                            }
                        }

                        // Warn if a fan is set to completely off.
                        if (!_state.EcFanControlEnabled && (_state.Fan1Level == FanLevel.Off || (_state.Fan2Present && _state.Fan2Level == FanLevel.Off)))
                        {
                            _state.ConsistencyModeStatus = "Warning: Fans set to \"off\" will not turn on regardless of temperature or load on the system";
                        }
                        else
                        {
                            _state.ConsistencyModeStatus = " ";
                        }
                    }
                    else if (_state.OperationMode == OperationMode.Consistency && IsAutomaticFanControlDisableSupported)
                    {
                        // Consistency mode logic.
                        ConsistencyModeLogic();
                    }

                    // See if we need to update the BIOS thermal setting.
                    if (_state.ThermalSetting != ThermalSetting.Error && RequestedThermalSetting != _state.ThermalSetting)
                    {
                        DellSmbiosSmi.SetThermalSetting((ThermalSetting)RequestedThermalSetting);
                        _state.UpdateThermalSetting();
                    }

                    // Check to see if the active audio device has disappeared.
                    if (_state.AudioThreadRunning && !_state.AudioDevices.Contains(_state.SelectedAudioDevice))
                    {
                        // Remember the audio device in case it reappears.
                        _state.BringBackAudioDevice = _state.SelectedAudioDevice;

                        // Terminate the audio thread.
                        _soundPlayer?.RequestTermination();
                    }

                    _requestSemapreplaced.Release();
                    _state.Release();
                    releaseSemapreplaced = false;

                    UpdateForm();

                    Thread.Sleep(Core.RefreshInterval);
                }

                // If we got out of the loop without error, the program is terminating.
                if (IsAutomaticFanControlDisableSupported)
                {
                    _fanController.EnableAutomaticFanControl();
                    Log.Write("Enabled EC fan control – shutdown");
                }

                // Clean up as the program terminates.
                _fanController.Shutdown();
            }
            catch (Exception exception)
            {
                if (releaseSemapreplaced)
                {
                    _state.Release();
                }

                _state.WaitOne();
                _state.Error = string.Format("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                _state.Release();

                Log.Write(_state.Error);
            }

            _state.WaitOne();
            _state.BackgroundThreadRunning = false;
            _state.Release();

            UpdateForm();
        }

19 Source : PackageTest.cs
with GNU General Public License v3.0
from AaronKelley

private static bool NvapiTest()
        {
            bool foundGpu = false;

            try
            {
                Console.WriteLine("Running NVAPI test.");

                foreach (PhysicalGPU gpu in PhysicalGPU.GetPhysicalGPUs())
                {
                    Console.WriteLine("  Found GPU: {0}", gpu.FullName);
                    foundGpu = true;

                    try
                    {
                        foreach (GPUThermalSensor sensor in gpu.ThermalInformation.ThermalSensors)
                        {
                            Console.WriteLine("    Current GPU temperature: {0}", sensor.CurrentTemperature);
                        }
                    }
                    catch (NVIDIAApiException exception)
                    {
                        if (exception.Message == "NVAPI_GPU_NOT_POWERED")
                        {
                            Console.WriteLine("    GPU is currently powered off.");
                        }
                        else
                        {
                            throw;
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                return false;
            }

            Console.WriteLine("  ...Preplaceded.");
            if (!foundGpu)
            {
                Console.WriteLine("  (Note: No NVIDIA GPUs found.)");
            }

            return true;
        }

19 Source : PackageTest.cs
with GNU General Public License v3.0
from AaronKelley

private static bool OpenHardwareMonitorTest()
        {
            try
            {
                Console.WriteLine("Running Open Hardware Monitor test.");

                Computer computer = new()
                {
                    IsCpuEnabled = true
                };

                computer.Open();

                foreach (IHardware hardware in computer.Hardware)
                {
                    hardware.Update();

                    foreach (ISensor sensor in hardware.Sensors)
                    {
                        if (sensor.SensorType == SensorType.Temperature && sensor.Value.HasValue)
                        {
                            Console.WriteLine("  {0}: {1}", sensor.Name, sensor.Value);
                        }
                    }
                }
            }
            catch (Exception exception)
            {
                Console.Error.WriteLine("{0}: {1}\n{2}", exception.GetType().ToString(), exception.Message, exception.StackTrace);
                return false;
            }

            Console.WriteLine("  ...Preplaceded.");
            return true;
        }

19 Source : AudioLoFiEffect.cs
with Apache License 2.0
from abist-co-ltd

public override int GetHashCode()
            {
                string s = $"[{GetType().ToString()}] Low: {LowPreplacedCutoff}, High: {HighPreplacedCutoff}";
                return s.GetHashCode();
            }

19 Source : FileCacheManager.cs
with Apache License 2.0
from acarteas

public void WriteSysValue<T>(string filename, T data) where T : struct
        {
            throw new ArgumentException(string.Format("Type is currently unsupported: {0}", typeof(T).ToString()), "data");
        }

19 Source : FileCacheManager.cs
with Apache License 2.0
from acarteas

public bool ReadSysValue<T>(string filename, out T value) where T : struct
        {
            throw new ArgumentException(string.Format("Type is currently unsupported: {0}", typeof(T).ToString()), "value");

            // These types could be easily implemented following the `long` function as a template:
            //   - bool:
            //     + reader.ReadBoolean();
            //   - byte:
            //     + reader.ReadByte();
            //   - char:
            //     + reader.ReadChar();
            //   - decimal:
            //     + reader.ReadDecimal();
            //   - double:
            //     + reader.ReadDouble();
            //   - short:
            //     + reader.ReadInt16();
            //   - int:
            //     + reader.ReadInt32();
            //   - long:
            //     + reader.ReadInt64();
            //   - sbyte:
            //     + reader.ReadSbyte();
            //   - ushort:
            //     + reader.ReadUInt16();
            //   - uint:
            //     + reader.ReadUInt32();
            //   - ulong:
            //     + reader.ReadUInt64();
        }

19 Source : SettingsTest.cs
with MIT License
from adams85

[Fact]
        public void ParsingOptions()
        {
            var configJson =
$@"{{ 
    ""{nameof(FileLoggerOptions.RootPath)}"": ""{Path.DirectorySeparatorChar.ToString().Replace(@"\", @"\\")}"",
    ""{nameof(FileLoggerOptions.BasePath)}"": ""Logs"",
    ""{nameof(FileLoggerOptions.FileAccessMode)}"": ""{LogFileAccessMode.OpenTemporarily}"",
    ""{nameof(FileLoggerOptions.FileEncodingName)}"": ""utf-8"",
    ""{nameof(FileLoggerOptions.Files)}"": [
    {{
        ""{nameof(LogFileOptions.Path)}"": ""logger.log"",
        ""{nameof(LogFileOptions.MinLevel)}"": {{
            ""Karambolo.Extensions.Logging.File"": ""{LogLevel.Warning}"",
            ""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.None}"",
        }},
    }},
    {{
        ""{nameof(LogFileOptions.Path)}"": ""test.log"",
        ""{nameof(LogFileOptions.MinLevel)}"": {{
            ""Karambolo.Extensions.Logging.File.Test"": ""{LogLevel.Debug}"",
            ""{LogFileOptions.DefaultCategoryName}"": ""{LogLevel.None}"",
        }},
    }}],
    ""{nameof(FileLoggerOptions.DateFormat)}"": ""yyyyMMdd"",
    ""{nameof(FileLoggerOptions.CounterFormat)}"": ""000"",
    ""{nameof(FileLoggerOptions.MaxFileSize)}"": 10,
    ""{nameof(FileLoggerOptions.TextBuilderType)}"": ""{typeof(CustomLogEntryTextBuilder).replacedemblyQualifiedName}"",
    ""{nameof(FileLoggerOptions.IncludeScopes)}"": true,
    ""{nameof(FileLoggerOptions.MaxQueueSize)}"": 100,
}}";

            var fileProvider = new MemoryFileProvider();
            fileProvider.CreateFile("config.json", configJson);

            var cb = new ConfigurationBuilder();
            cb.AddJsonFile(fileProvider, "config.json", optional: false, reloadOnChange: false);
            IConfigurationRoot config = cb.Build();

            var services = new ServiceCollection();
            services.AddOptions();
            services.Configure<FileLoggerOptions>(config);
            ServiceProvider serviceProvider = services.BuildServiceProvider();

            IFileLoggerSettings settings = serviceProvider.GetService<IOptions<FileLoggerOptions>>().Value;

            replacedert.True(settings.FileAppender is PhysicalFileAppender);
            replacedert.Equal(Path.GetPathRoot(Environment.CurrentDirectory), ((PhysicalFileAppender)settings.FileAppender).FileProvider.Root);
            replacedert.Equal("Logs", settings.BasePath);
            replacedert.Equal(LogFileAccessMode.OpenTemporarily, settings.FileAccessMode);
            replacedert.Equal(Encoding.UTF8, settings.FileEncoding);

            replacedert.Equal(2, settings.Files.Length);

            ILogFileSettings fileSettings = Array.Find(settings.Files, f => f.Path == "logger.log");
            replacedert.NotNull(fileSettings);
            replacedert.Equal(LogLevel.None, fileSettings.GetMinLevel(typeof(string).ToString()));
            replacedert.Equal(LogLevel.Warning, fileSettings.GetMinLevel(typeof(FileLogger).ToString()));
            replacedert.Equal(LogLevel.Warning, fileSettings.GetMinLevel(typeof(SettingsTest).ToString()));

            fileSettings = Array.Find(settings.Files, f => f.Path == "test.log");
            replacedert.NotNull(fileSettings);
            replacedert.Equal(LogLevel.None, fileSettings.GetMinLevel(typeof(string).ToString()));
            replacedert.Equal(LogLevel.None, fileSettings.GetMinLevel(typeof(FileLogger).ToString()));
            replacedert.Equal(LogLevel.Debug, fileSettings.GetMinLevel(typeof(SettingsTest).ToString()));

            replacedert.Equal("yyyyMMdd", settings.DateFormat);
            replacedert.Equal("000", settings.CounterFormat);
            replacedert.Equal(10, settings.MaxFileSize);
            replacedert.Equal(typeof(CustomLogEntryTextBuilder), settings.TextBuilder.GetType());
            replacedert.True(settings.IncludeScopes);
            replacedert.Equal(100, settings.MaxQueueSize);
        }

19 Source : FileLoggerFactoryExtensions.cs
with MIT License
from adams85

public static ILoggingBuilder AddFile<TProvider>(this ILoggingBuilder builder, FileLoggerContext context = null, Action<FileLoggerOptions> configure = null, string optionsName = null)
            where TProvider : FileLoggerProvider
        {
            if (builder == null)
                throw new ArgumentNullException(nameof(builder));

            if (optionsName == null)
                optionsName = typeof(TProvider).ToString();

            if (context == null)
                context = FileLoggerContext.Default;

            builder.AddFile(optionsName, sp => ActivatorUtilities.CreateInstance<TProvider>(sp, context, optionsName));

            if (configure != null)
                builder.Services.Configure(optionsName, configure);

            return builder;
        }

19 Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio

private static string GereplacedemTelemetryCacheKey(string cacheKey)
		{
			return string.Format("{0}:{1}", typeof(CacheItemTelemetry).ToString().ToLower(), cacheKey.ToLower());
		}

19 Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio

private static JObject GetJsonContent(string name, CacheItemDetail detail, CacheItemTelemetry telemetry, object value, Uri removeLink, bool expanded)
		{
			var policyContent = GetJsonPolicyContent(detail);
			var telemetryContent = telemetry != null
				? new JObject
				{
					{ "memberName", telemetry.Caller.MemberName },
					{ "sourceFilePath", telemetry.Caller.SourceFilePath },
					{ "sourceLineNumber", telemetry.Caller.SourceLineNumber },
					{ "duration", telemetry.Duration },
					{ "accessCount", telemetry.AccessCount },
					{ "cacheItemStatus", detail.CacheItemStatus.ToString() },
					{ "staleAccessCount", telemetry.StaleAccessCount },
					{ "lastAccessedOn", telemetry.LastAccessedOn },
					{ "isStartup", telemetry.IsStartup },
					{ "isAllColumns", telemetry.IsAllColumns },
					{ "attributes", new JArray(telemetry.Attributes) }
				}
				: null;

			var properties = new JObject
			{
				{ "name", name },
				{ "type", value != null ? value.GetType().ToString() : null },
				{ "remove", removeLink.AbsoluteUri }
			};

			if (policyContent != null)
			{
				properties.Add("policy", policyContent);
			}

			if (telemetryContent != null)
			{
				properties.Add("telemetry", telemetryContent);
			}

			if (expanded)
			{
				if (value != null)
				{
					properties.Add("value", JToken.FromObject(value, CrmJsonConvert.CreateJsonSerializer()));
				}

				if (telemetry != null && telemetry.Request != null)
				{
					properties.Add("request", JToken.FromObject(telemetry.Request, CrmJsonConvert.CreateJsonSerializer()));
				}
			}

			var content = new JObject
			{
				{ "properties", properties }
			};

			return content;
		}

19 Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio

public static XmlDoreplacedent GetCacheFootprintXml(this ObjectCache cache, bool expanded, Uri requestUrl)
		{
			var alternateLink = new Uri(requestUrl.GetLeftPart(UriPartial.Path));

			var doc = new XmlDoreplacedent();
			var rootElement = doc.CreateElement("CacheFootprint");
			var enreplacedyElements = new List<XmlElement>();
			var footprint = GetCacheFootprint(cache, alternateLink);
			foreach (var enreplacedyType in footprint)
			{
				var enreplacedyElement = doc.CreateElement("Enreplacedy");
				enreplacedyElement.SetAttribute("Name", enreplacedyType.Name);
				enreplacedyElement.SetAttribute("Count", enreplacedyType.GetCount().ToString());
				enreplacedyElement.SetAttribute("Size", enreplacedyType.GetSize().ToString());

				if (expanded)
				{
					foreach (var item in enreplacedyType.Items)
					{
						var itemElement = doc.CreateElement("Item");
						itemElement.SetAttribute("LogicalName", item.Enreplacedy.LogicalName);
						itemElement.SetAttribute("Name", item.Enreplacedy.GetAttributeValueOrDefault("adx_name", string.Empty));
						itemElement.SetAttribute("Id", item.Enreplacedy.Id.ToString());

						var cacheElement = doc.CreateElement("Cache");
						cacheElement.SetAttribute("Id", item.CacheItemKey);
						cacheElement.SetAttribute("Type", item.CacheItemType.ToString());
						cacheElement.SetAttribute("Link", item.Link.ToString());
						cacheElement.SetAttribute("Size", GetEnreplacedySizeInMemory(item.Enreplacedy).ToString());

						itemElement.AppendChild(cacheElement);
						enreplacedyElement.AppendChild(itemElement);
					}
				}

				enreplacedyElements.Add(enreplacedyElement);
			}

			// Sort the enreplacedies by descending size
			enreplacedyElements = enreplacedyElements.OrderByDescending(el => int.Parse(el.GetAttribute("Size"))).ToList();

			var enreplacediesElement = doc.CreateElement("Enreplacedies");
			foreach (var enreplacedyElement in enreplacedyElements)
			{
				enreplacediesElement.AppendChild(enreplacedyElement);
			}
			
			if (!expanded)
			{
				// Add link to the Expanded view with enreplacedy record details
				var query = System.Web.HttpUtility.ParseQueryString(requestUrl.Query);
				query[Web.Handlers.CacheFeedHandler.QueryKeys.Expanded] = bool.TrueString;
				var uriBuilder = new UriBuilder(requestUrl.ToString()) { Query = query.ToString() };
				var expandedView = doc.CreateElement("expandedView");
				expandedView.InnerText = uriBuilder.ToString();
				rootElement.AppendChild(expandedView);
			}
			rootElement.AppendChild(enreplacediesElement);
			doc.AppendChild(rootElement);
			return doc;
		}

19 Source : ObjectCacheExtensions.cs
with MIT License
from Adoxio

private static SyndicationContent GetContent(string name, CacheItemDetail detail, CacheItemTelemetry telemetry, object value, Uri removeLink, bool expanded)
		{
			var defaultProps = new[]
			{
				new XElement("name", name),
				new XElement("type", value.GetType().ToString()),
				new XElement("remove", new XAttribute("href", removeLink))
			};

			var properties = defaultProps.Concat(GetContent(detail, telemetry)).Concat(GetContentValues(value, expanded));

			var content = new XElement("properties",  properties);
			
			var sc = SyndicationContent.CreateXmlContent(content);
			return sc;
		}

19 Source : CrmSerializationBinder.cs
with MIT License
from Adoxio

public override Type BindToType(string replacedemblyName, string typeName)
		{
			if (string.IsNullOrWhiteSpace(replacedemblyName) && string.IsNullOrWhiteSpace(typeName))
			{
				return null;
			}

			var type = KnownTypes.FirstOrDefault(t => t.ToString() == typeName);
			
			if (type == null)
			{
				throw new InvalidOperationException(string.Format("The type '{0}, {1}' cannot be deserialized.", typeName, replacedemblyName));
			}

			return type;
		}

19 Source : CrmSerializationBinder.cs
with MIT License
from Adoxio

public override void BindToName(Type serializedType, out string replacedemblyName, out string typeName)
		{
			replacedemblyName = serializedType.replacedembly.GetName().Name;
			typeName = serializedType.ToString();
		}

19 Source : FluentSchedulerJob.cs
with MIT License
from Adoxio

public void Execute()
		{
			var id = Guid.NewGuid();
			var name = this.GetType().ToString();
			EventSource.SetCurrentThreadActivityId(id);

			// Register this job with the hosting environment.
			// Allows for a more graceful stop of the job, in the case of IIS shutting down.
			HostingEnvironment.RegisterObject(this);

			try
			{
				ADXTrace.Instance.TraceVerbose(TraceCategory.Application, string.Format("Job registered: {0}", name));

				lock (this.shutDownLock)
				{
					if (this.shuttingDown)
					{
						return;
					}

					ADXTrace.Instance.TraceVerbose(TraceCategory.Application, string.Format("Job begin: {0}", name));

					this.ExecuteInternal(id);

					ADXTrace.Instance.TraceVerbose(TraceCategory.Application, string.Format("Job end: {0}", name));
				}
			}
			catch (Exception e)
			{
				this.OnError(e);

				throw;
			}
			finally
			{
				HostingEnvironment.UnregisterObject(this);

				ADXTrace.Instance.TraceVerbose(TraceCategory.Application, string.Format("Job unregistered: {0}", name));
			}
		}

19 Source : EntityRecord.cs
with MIT License
from Adoxio

protected void ConvertToEnreplacedyRecord(Enreplacedy enreplacedy, EnreplacedyMetadata enreplacedyMetadata = null, OrganizationServiceContext serviceContext = null, OrganizationMoneyFormatInfo organizationMoneyFormatInfo = null, int? crmLcid = null)
		{
			var recordAttributes = new List<EnreplacedyRecordAttribute>();
			var attributes = enreplacedy.Attributes;
			var formattedAttributes = enreplacedy.FormattedValues;
			
			if (serviceContext == null)
			{
				serviceContext = PortalCrmConfigurationManager.CreateServiceContext();
			}

			organizationMoneyFormatInfo = organizationMoneyFormatInfo ?? new OrganizationMoneyFormatInfo(serviceContext);
			var recordMoneyFormatInfo = new EnreplacedyRecordMoneyFormatInfo(serviceContext, enreplacedy);

			foreach (var attribute in attributes)
			{
				var aliasedValue = attribute.Value as AliasedValue;
				var value = aliasedValue != null ? aliasedValue.Value : attribute.Value;
				var type = value.GetType().ToString();
				var formattedValue = string.Empty;
				var displayValue = value;
				DateTimeFormat format = DateTimeFormat.DateAndTime;
				DateTimeBehavior behavior = null;
				AttributeMetadata attributeMetadata = null;

				if (formattedAttributes.Contains(attribute.Key))
				{
					formattedValue = formattedAttributes[attribute.Key];
					displayValue = formattedValue;
				}

				if (aliasedValue != null)
				{
					var aliasedEnreplacedyMetadata = serviceContext.GetEnreplacedyMetadata(aliasedValue.EnreplacedyLogicalName, EnreplacedyFilters.Attributes);

					if (aliasedEnreplacedyMetadata != null)
					{
						attributeMetadata = aliasedEnreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == aliasedValue.AttributeLogicalName);
					}
				}
				else
				{
					if (enreplacedyMetadata != null)
					{
						attributeMetadata = enreplacedyMetadata.Attributes.FirstOrDefault(a => a.LogicalName == attribute.Key);
					}
				}

				if (attributeMetadata != null)
				{
					switch (attributeMetadata.AttributeType)
					{
						case AttributeTypeCode.State:
						case AttributeTypeCode.Status:
						case AttributeTypeCode.Picklist:
							var optionSetValue = (OptionSetValue)value;
							formattedValue = Adxstudio.Xrm.Core.OrganizationServiceContextExtensions.GetOptionSetValueLabel(attributeMetadata,
								optionSetValue.Value, crmLcid.GetValueOrDefault(CultureInfo.CurrentCulture.LCID));
							 displayValue = formattedValue;
							break; 
						case AttributeTypeCode.Customer:
						case AttributeTypeCode.Lookup:
						case AttributeTypeCode.Owner:
							var enreplacedyReference = value as EnreplacedyReference;
							if (enreplacedyReference != null)
							{
								displayValue = enreplacedyReference.Name ?? string.Empty;
							}
							break;
						case AttributeTypeCode.DateTime:
							var datetimeAttributeMetadata = attributeMetadata as DateTimeAttributeMetadata;
							behavior = datetimeAttributeMetadata.DateTimeBehavior;
							format = datetimeAttributeMetadata.Format.GetValueOrDefault(DateTimeFormat.DateAndTime);
							if (datetimeAttributeMetadata != null)
							{
								if (format != DateTimeFormat.DateOnly && behavior == DateTimeBehavior.UserLocal)
								{
									// Don't use the formatted value, as the connection user's timezone is used to format the datetime value. Use the UTC value for display.
									var date = (DateTime)value;
									displayValue = date.ToString(DateTimeClientFormat);
								}
								if (behavior == DateTimeBehavior.TimeZoneIndependent || behavior == DateTimeBehavior.DateOnly)
								{
									// JSON serialization converts the time from server local to UTC automatically
									// to avoid this we can convert to UTC before serialization
									value = DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
								}
							}
							break;
						case AttributeTypeCode.BigInt:
						case AttributeTypeCode.Integer:
							displayValue = string.Format("{0}", value);
							break;
						case AttributeTypeCode.Decimal:
							var decimalAttributeMetadata = attributeMetadata as DecimalAttributeMetadata;
							if (decimalAttributeMetadata != null && value is decimal)
							{
								displayValue = ((decimal)value).ToString("N{0}".FormatWith(decimalAttributeMetadata.Precision.GetValueOrDefault(2)));
							}
							break;
						case AttributeTypeCode.Money:
							var moneyAttributeMetadata = attributeMetadata as MoneyAttributeMetadata;
							if (moneyAttributeMetadata != null && value is Money)
							{
								var moneyFormatter = new MoneyFormatter(organizationMoneyFormatInfo, recordMoneyFormatInfo, moneyAttributeMetadata);

								displayValue = string.Format(moneyFormatter, "{0}", (Money)value);
							}
							break;
					}
				}
				else
				{
					if (attribute.Value is EnreplacedyReference)
					{
						var enreplacedyReference = (EnreplacedyReference)attribute.Value;
						if (enreplacedyReference != null)
						{
							displayValue = enreplacedyReference.Name ?? string.Empty;
						}
					}
					else if (attribute.Value is DateTime)
					{
						format = DateTimeFormat.DateAndTime;
						var dtAttributeValue = (DateTime)attribute.Value;
						// Don't use the formatted value, as the connection user's timezone is used to format the datetime value. Use the UTC value for display.
						if (dtAttributeValue.Kind == DateTimeKind.Utc) // Indicates this is not a date only attribute
						{
							var date = (DateTime)value;
							displayValue = date.ToString(DateTimeClientFormat);
							behavior = DateTimeBehavior.UserLocal;
						}
						// This below logic fails in one condition: when DateTimeBehavior = TimeZoneIndependent and DateTimeFormat = DateAndTime with value having ex: 20-01-2017 12:00 AM
						else if (dtAttributeValue.TimeOfDay.TotalSeconds == 0) 
						{
							behavior = DateTimeBehavior.DateOnly;
							format = DateTimeFormat.DateOnly;
							value = DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
						}
						else
						{
							behavior = DateTimeBehavior.TimeZoneIndependent;
							// JSON serialization converts the time from server local to UTC automatically
							// to avoid this we can convert to UTC before serialization
							value = DateTime.SpecifyKind((DateTime)value, DateTimeKind.Utc);
						}
					}
				}

				recordAttributes.Add(new EnreplacedyRecordAttribute
				{
					Name = attribute.Key,
					Value = value,
					FormattedValue = formattedValue,
					DisplayValue = displayValue,
					DateTimeBehavior = behavior,
					DateTimeFormat = format.ToString(),
					Type = type,
					AttributeMetadata = attributeMetadata
				});
			}

			Id = enreplacedy.Id;
			EnreplacedyName = enreplacedy.LogicalName;
			Attributes = recordAttributes;
		}

19 Source : HttpResponseMessageAssertions.cs
with Apache License 2.0
from adrianiftode

private void ExecuteModelExtractedreplacedertion(bool success, string? errorMessage, Type? modelType, string because, object[] becauseArgs)
        {
            Execute.replacedertion
                .BecauseOf(because, becauseArgs)
                .ForCondition(success)
                .FailWith("Expected {context:response} to have a content equivalent to a model of type {0}, but the JSON representation could not be parsed, as the operation failed with the following message: {2}{reason}. {1}",
                    modelType?.ToString() ?? "unknown type", Subject, errorMessage);
        }

19 Source : EditorGUIHelper.cs
with MIT License
from AdultLink

static void CopySettings(SerializedProperty settings)
        {
            var t = typeof(PostProcessingProfile);
            var settingsStruct = ReflectionUtils.GetFieldValueFromPath(settings.serializedObject.targetObject, ref t, settings.propertyPath);
            var serializedString = t.ToString() + '|' + JsonUtility.ToJson(settingsStruct);
            EditorGUIUtility.systemCopyBuffer = serializedString;
        }

19 Source : NGUITools.cs
with GNU General Public License v3.0
from aelariane

public static string GetName<T>() where T : Component
    {
        string text = typeof(T).ToString();
        if (text.StartsWith("UI"))
        {
            text = text.Substring(2);
        }
        else if (text.StartsWith("UnityEngine."))
        {
            text = text.Substring(12);
        }
        return text;
    }

19 Source : ListBoxObjectCollection.cs
with Mozilla Public License 2.0
from ahyahy

[ContextMethod("Элемент", "Item")]
        public IValue Item(int p1, IValue p2 = null)
        {
            Lisreplacedem Lisreplacedem1 = new Lisreplacedem();
            if (p2 != null)
            {
                if (Base_obj[p1].GetType().ToString() == "System.Data.DataRowView")
                {
                    return (IValue)null;
                }
                else if (Base_obj[p1].GetType().ToString() == "osf.ClListBox")
                {
                    return (IValue)null;
                }
                else if (p2.GetType().ToString() == "osf.ClLisreplacedem")
                {
                    Lisreplacedem Lisreplacedem2 = ((dynamic)p2).Base_obj;
                    Lisreplacedem1 = (Lisreplacedem)Base_obj[p1];
                    Lisreplacedem1.Text = Lisreplacedem2.Text;
                    Lisreplacedem1.Value = Lisreplacedem2.Value;
                    Lisreplacedem1.ForeColor = Lisreplacedem2.ForeColor;
                }
                else
                {
                    string s = "";
                    try
                    {
                        s = p2.GetType().GetCustomAttribute<ContextClreplacedAttribute>().GetName();
                    }
                    catch
                    {
                        s = p2.ToString();
                    }
                    Lisreplacedem1 = (Lisreplacedem)Base_obj[p1];
                    Lisreplacedem1.Text = s;
                    Lisreplacedem1.Value = p2;
                }
                M_obj.Base_obj.Invalidate();
                return (IValue)new ClLisreplacedem(Lisreplacedem1);
            }
            else
            {
                if (Base_obj[p1].GetType().ToString() == "System.Data.DataRowView")
                {
                    DataRowView DataRowView1 = new DataRowView((System.Data.DataRowView)Base_obj[p1]);
                    Lisreplacedem1.Text = DataRowView1.get_Item(M_obj.Base_obj.DisplayMember).ToString();
                    Lisreplacedem1.Value = DataRowView1.get_Item(M_obj.Base_obj.ValueMember);
                }
                else if (Base_obj[p1].GetType().ToString() == "osf.Lisreplacedem")
                {
                    Lisreplacedem1 = (Lisreplacedem)Base_obj[p1];
                }
                else
                {
                    Lisreplacedem1.Text = Base_obj[p1].ToString();
                    Lisreplacedem1.Value = Base_obj[p1];
                    Lisreplacedem1.ForeColor = ((dynamic)Base_obj[p1]).ForeColor;
                }
                return new ClLisreplacedem(Lisreplacedem1);
            }
        }

19 Source : ListBoxSelectedObjectCollection.cs
with Mozilla Public License 2.0
from ahyahy

[ContextMethod("Элемент", "Item")]
        public IValue Item(int p1)
        {
            Lisreplacedem Lisreplacedem1 = new Lisreplacedem();
            if (Base_obj[p1].GetType().ToString() == "System.Data.DataRowView")
            {
                DataRowView DataRowView1 = new DataRowView((System.Data.DataRowView)Base_obj[p1]);
                Lisreplacedem1.Text = DataRowView1.get_Item(M_obj.Base_obj.DisplayMember).ToString();
                Lisreplacedem1.Value = DataRowView1.get_Item(M_obj.Base_obj.ValueMember);
            }
            else if (Base_obj[p1].GetType().ToString() == "osf.Lisreplacedem")
            {
                Lisreplacedem1 = (Lisreplacedem)Base_obj[p1];
            }
            else
            {
                Lisreplacedem1.Text = Base_obj[p1].ToString();
                Lisreplacedem1.Value = Base_obj[p1];
            }
            return new ClLisreplacedem(Lisreplacedem1);
        }

19 Source : Type.cs
with Mozilla Public License 2.0
from ahyahy

public override string ToString()
        {
            return M_Type.ToString();
        }

19 Source : ComboBoxObjectCollection.cs
with Mozilla Public License 2.0
from ahyahy

[ContextMethod("Элемент", "Item")]
        public IValue Item(int p1, IValue p2 = null)
        {
            osf.Lisreplacedem Lisreplacedem1 = new osf.Lisreplacedem();
            if (p2 != null)
            {
                Base_obj.RemoveAt(p1);
                if (p2.GetType().ToString().Contains("osf.ClLisreplacedem"))
                {
                    Lisreplacedem1 = ((dynamic)p2).Base_obj;
                }
                else
                {
                    Lisreplacedem1 = new osf.Lisreplacedem(p2.ToString(), p2);
                }
                Base_obj.Insert(p1, Lisreplacedem1);
            }
            else
            {
                if (Base_obj[p1].GetType().ToString() == "System.Data.DataRowView")
                {
                    osf.DataRowView DataRowView1 = new osf.DataRowView((System.Data.DataRowView)Base_obj[p1]);
                    Lisreplacedem1.Text = DataRowView1.get_Item(m_obj.Base_obj.DisplayMember).ToString();
                    Lisreplacedem1.Value = DataRowView1.get_Item(m_obj.Base_obj.ValueMember);
                }
                else if (Base_obj[p1].GetType().ToString() == "osf.Lisreplacedem")
                {
                    Lisreplacedem1 = (osf.Lisreplacedem)Base_obj[p1];
                }
                else
                {
                    Lisreplacedem1.Text = Base_obj[p1].ToString();
                    Lisreplacedem1.Value = Base_obj[p1];
                    Lisreplacedem1.ForeColor = ((dynamic)Base_obj[p1]).ForeColor;
                }
            }
            return (IValue)new ClLisreplacedem(Lisreplacedem1);
        }

19 Source : ScrollBar.cs
with Mozilla Public License 2.0
from ahyahy

public void ScrollBarManagedProperties()
        {
            if (ManagedProperties.Count > 0)
            {
                foreach (ClManagedProperty ClManagedProperty1 in ManagedProperties.Base_obj)
                {
                    object obj1 = ClManagedProperty1.ManagedObject;
                    string prop1 = "";
                    float ratio1 = 1.0f;
                    if (ClManagedProperty1.Ratio == null)
                    {
                    }
                    else
                    {
                        ratio1 = Convert.ToSingle(ClManagedProperty1.Ratio.AsNumber());
                    }
                    System.Reflection.PropertyInfo[] myPropertyInfo;
                    myPropertyInfo = obj1.GetType().GetProperties();
                    for (int i = 0; i < myPropertyInfo.Length; i++)
                    {
                        System.Collections.Generic.IEnumerable<System.Reflection.CustomAttributeData> CustomAttributeData1 =
                            myPropertyInfo[i].CustomAttributes;
                        foreach (System.Reflection.CustomAttributeData CustomAttribute1 in CustomAttributeData1)
                        {
                            string quote = "\"";
                            string text = CustomAttribute1.ToString();
                            if (text.Contains("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote))
                            {
                                text = text.Replace("[ScriptEngine.Machine.Contexts.ContextPropertyAttribute(" + quote, "");
                                text = text.Replace(quote + ", " + quote, " ");
                                text = text.Replace(quote + ")]", "");
                                string[] stringSeparators = new string[] { };
                                string[] result = text.Split(stringSeparators, StringSplitOptions.RemoveEmptyEntries);
                                if (ClManagedProperty1.ManagedProperty == result[0])
                                {
                                    prop1 = result[1];
                                    break;
                                }
                            }
                        }
                    }
                    System.Type Type1 = obj1.GetType();
                    float _Value = Convert.ToSingle(v_h_ScrollBar.Value);
                    int res = Convert.ToInt32(ratio1 * _Value);
                    if (Type1.GetProperty(prop1).PropertyType.ToString() != "System.String")
                    {
                        Type1.GetProperty(prop1).SetValue(obj1, res);
                    }
                    else
                    {
                        Type1.GetProperty(prop1).SetValue(obj1, res.ToString());
                    }
                }
            }
        }

19 Source : ConvertUtils.cs
with MIT License
from akaskela

private static object EnsureTypereplacedignable(object value, Type initialType, Type targetType)
        {
            Type valueType = (value != null) ? value.GetType() : null;

            if (value != null)
            {
                if (targetType.IsreplacedignableFrom(valueType))
                {
                    return value;
                }

                Func<object, object> castConverter = CastConverters.Get(new TypeConvertKey(valueType, targetType));
                if (castConverter != null)
                {
                    return castConverter(value);
                }
            }
            else
            {
                if (ReflectionUtils.IsNullable(targetType))
                {
                    return null;
                }
            }

            throw new ArgumentException("Could not cast or convert from {0} to {1}.".FormatWith(CultureInfo.InvariantCulture, (initialType != null) ? initialType.ToString() : "{null}", targetType));
        }

19 Source : AssetBundleFilesAnalyzeObject.cs
with MIT License
from akof1314

public static void ObjectAddToFileInfo(Object o, SerializedObject serializedObject, replacedetBundleFileInfo info)
        {
            if (!o)
            {
                return;
            }

            string name2 = o.name;
            string type = o.GetType().ToString();
            if (type.StartsWith("UnityEngine."))
            {
                type = type.Substring(12);
                
                // 如果是内置的组件,就不当作是资源
                if (o as Component)
                {
                    return;
                }
            }
            else if (type == "UnityEditor.Animations.AnimatorController")
            {
                type = "AnimatorController";
            }
            else if (type == "UnityEditorInternal.AnimatorController")
            {
                type = "AnimatorController";
            }
            else if (type == "UnityEditor.MonoScript")
            {
                MonoScript ms = o as MonoScript;
                string type2 = ms.GetClreplaced().ToString();
                if (type2.StartsWith("UnityEngine."))
                {
                    // 内置的脚本对象也不显示出来
                    return;
                }

                // 外部的组件脚本,保留下来
                type = "MonoScript";
            }
            else
            {
                // 外部的组件脚本,走上面的MonoScript
                if (o as Component)
                {
                    return;
                }
                // 外部的序列化对象,已经被脚本给分析完毕了,不需要再添加进来
                if (o as ScriptableObject)
                {
                    return;
                }

                Debug.LogError("What's this? " + type);
                return;
            }

            // 内建的资源排除掉
            string replacedetPath = replacedetDatabase.GetreplacedetPath(o);
            if (!string.IsNullOrEmpty(replacedetPath))
            {
                return;
            }

            long guid;
            if (info.isScene)
            {
                // 场景的话,没法根据PathID来确定唯一性,那么就认为每个场景用到的资源都不一样
                guid = (info.name + name2 + type).GetHashCode();
            }
            else
            {
                SerializedProperty pathIdProp = serializedObject.FindProperty("m_LocalIdentfierInFile");
#if UNITY_5 || UNITY_5_3_OR_NEWER
                guid = pathIdProp.longValue;
#else
                guid = pathIdProp.intValue;
#endif
            }

            if (info.IsreplacedetContain(guid))
            {
                return;
            }

            replacedetFileInfo info2 = replacedetBundleFilesreplacedyze.GetreplacedetFileInfo(guid);
            info2.name = name2;
            info2.type = type;
            info2.includedBundles.Add(info);
            if (info2.detailHyperLink == null)
            {
                // 初次创建对象时链接为空
                info2.detailHyperLink = new OfficeOpenXml.ExcelHyperLink(System.String.Empty, info2.name);
                info2.propertys = replacedyzeObject(o, serializedObject, info.rootPath, info.name);
            }

            info.replacedets.Add(info2);
        }

19 Source : NodeEditorUtilities.cs
with MIT License
from aksyr

public static string PrettyName(this Type type) {
            if (type == null) return "null";
            if (type == typeof(System.Object)) return "object";
            if (type == typeof(float)) return "float";
            else if (type == typeof(int)) return "int";
            else if (type == typeof(long)) return "long";
            else if (type == typeof(double)) return "double";
            else if (type == typeof(string)) return "string";
            else if (type == typeof(bool)) return "bool";
            else if (type.IsGenericType) {
                string s = "";
                Type genericType = type.GetGenericTypeDefinition();
                if (genericType == typeof(List<>)) s = "List";
                else s = type.GetGenericTypeDefinition().ToString();

                Type[] types = type.GetGenericArguments();
                string[] stypes = new string[types.Length];
                for (int i = 0; i < types.Length; i++) {
                    stypes[i] = types[i].PrettyName();
                }
                return s + "<" + string.Join(", ", stypes) + ">";
            } else if (type.IsArray) {
                string rank = "";
                for (int i = 1; i < type.GetArrayRank(); i++) {
                    rank += ",";
                }
                Type elementType = type.GetElementType();
                if (!elementType.IsArray) return elementType.PrettyName() + "[" + rank + "]";
                else {
                    string s = elementType.PrettyName();
                    int i = s.IndexOf('[');
                    return s.Substring(0, i) + "[" + rank + "]" + s.Substring(i);
                }
            } else return type.ToString();
        }

19 Source : NodeGraphEditor.cs
with MIT License
from aksyr

public virtual string GetNodeMenuName(Type type) {
            //Check if type has the CreateNodeMenuAttribute
            XNode.Node.CreateNodeMenuAttribute attrib;
            if (NodeEditorUtilities.GetAttrib(type, out attrib)) // Return custom path
                return attrib.menuName;
            else // Return generated path
                return ObjectNames.NicifyVariableName(type.ToString().Replace('.', '/'));
        }

19 Source : SerializableType.cs
with MIT License
from alelievr

public override string ToString()
		{
			return Type.GetType(typeString).ToString();
		}

19 Source : PopupSelectionMenu.cs
with MIT License
from alen-smajic

public override void OnGUI(Rect rect)
		{
			if (_modTypes == null || _modTypes.Count == 0)
			{
				_modTypes = new List<Type>();

				AppDomain currentDomain = AppDomain.CurrentDomain;
				replacedembly[] replacedemblies = currentDomain.Getreplacedemblies();
				for (int i = 0; i < replacedemblies.Length; i++)
				{
					Type[] types = replacedemblies[i].GetTypes();
					for (int j = 0; j < types.Length; j++)
					{
						if (types[j].IsSubclreplacedOf(_type))
						{
							_modTypes.Add(types[j]);
						}
					}
				}
			}

			GUILayout.Label(String.Format("{0}s", _type.Name), EditorStyles.boldLabel);
			var st = new GUIStyle();
			st.padding = new RectOffset(0, 0, 15, 15);
			_scrollPos = EditorGUILayout.BeginScrollView(_scrollPos, st);

			for (int i = 0; i < _modTypes.Count; i++)
			{
				Type replacedet = _modTypes[i];
				if (replacedet == null) //yea turns out this can happen
					continue;
				var style = GUI.skin.button;
				style.alignment = TextAnchor.MiddleLeft;
				string shortTypeName = GetShortTypeName(replacedet.ToString());
				if (GUILayout.Button(shortTypeName, style))
				{
					CreateNewModiferInstance(replacedet, shortTypeName);
					editorWindow.Close();
				}
			}
			EditorGUILayout.EndScrollView();
		}

19 Source : JsonSerializer.cs
with MIT License
from AlenToma

private DatasetSchema GetSchema(DataTable ds)
        {
            if (ds == null) return null;

            DatasetSchema m = new DatasetSchema();
            m.Info = new List<string>();
            m.Name = ds.TableName;

            foreach (DataColumn c in ds.Columns)
            {
                m.Info.Add(ds.TableName);
                m.Info.Add(c.ColumnName);
                m.Info.Add(c.DataType.ToString());
            }
            // FEATURE : serialize relations and constraints here

            return m;
        }

19 Source : JsonSerializer.cs
with MIT License
from AlenToma

private DatasetSchema GetSchema(DataSet ds)
        {
            if (ds == null) return null;

            DatasetSchema m = new DatasetSchema();
            m.Info = new List<string>();
            m.Name = ds.DataSetName;

            foreach (DataTable t in ds.Tables)
            {
                foreach (DataColumn c in t.Columns)
                {
                    m.Info.Add(t.TableName);
                    m.Info.Add(c.ColumnName);
                    m.Info.Add(c.DataType.ToString());
                }
            }
            // FEATURE : serialize relations and constraints here

            return m;
        }

19 Source : JsonSerializer.cs
with MIT License
from AlenToma

private void WriteObject(object obj)
        {
            int i = 0;
            if (_cirobj.TryGetValue(obj, out i) == false)
                _cirobj.Add(obj, _cirobj.Count + 1);
            else
            {
                if (_current_depth > 0 && _params.InlineCircularReferences == false)
                {
                    //_circular = true;
                    _output.Append("{\"$i\":");
                    _output.Append(i.ToString());
                    _output.Append("}");
                    return;
                }
            }
            if (_params.UsingGlobalTypes == false)
                _output.Append('{');
            else
            {
                if (_TypesWritten == false)
                {
                    _output.Append('{');
                    _before = _output.Length;
                    //_output = new StringBuilder();
                }
                else
                    _output.Append('{');
            }
            _TypesWritten = true;
            _current_depth++;
            if (_current_depth > _MAX_DEPTH)
                throw new Exception("Serializer encountered maximum depth of " + _MAX_DEPTH);


            Dictionary<string, string> map = new Dictionary<string, string>();
            Type t = obj.GetType();
            bool append = false;
            if (_params.UseExtensions)
            {
                if (_params.UsingGlobalTypes == false)
                    WritePairFast("$type", Reflection.Instance.GetTypereplacedemblyName(t));
                else
                {
                    int dt = 0;
                    string ct = Reflection.Instance.GetTypereplacedemblyName(t);
                    if (_globalTypes.TryGetValue(ct, out dt) == false)
                    {
                        dt = _globalTypes.Count + 1;
                        _globalTypes.Add(ct, dt);
                    }
                    WritePairFast("$type", dt.ToString());
                }
                append = true;
            }

            Getters[] g = Reflection.Instance.GetGetters(t, _params.IgnoreAttributes);
            int c = g.Length;
            for (int ii = 0; ii < c; ii++)
            {
                var p = g[ii];
                object o = p.Property.GetValue(obj);
                if (_params.SerializeNullValues == false && (o == null || o is DBNull))
                {
                    //append = false;
                }
                else
                {
                    if (append)
                        _output.Append(',');
                    if (p.memberName != null)
                        WritePair(p.memberName, o);
                    else
                    {
                        WritePair(JsonHelper.SerializaName(_params.JsonFormatting, p.Name), o);
                    }

                    if (o != null && _params.UseExtensions)
                    {
                        Type tt = o.GetType();
                        if (tt == typeof(System.Object))
                            map.Add(p.Name, tt.ToString());
                    }
                    append = true;
                }
            }
            if (map.Count > 0 && _params.UseExtensions)
            {
                _output.Append(",\"$map\":");
                WriteStringDictionary(map);
            }
            _output.Append('}');
            _current_depth--;
        }

See More Examples