System.Exception.ToString()

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

9382 Examples 7

19 Source : Form1.cs
with GNU General Public License v3.0
from 00000vish

private void getHWID()
        {
            try
            {
                using (RegistryKey key = Registry.LocalMachine.OpenSubKey(WIN_10_PATH))
                {
                    if (key != null)
                    {
                        backupHWID = key.GetValue("HwProfileGuid").ToString();
                        label1.Text = backupHWID;                       
                        
                    }else
                    {
                        throw new Exception();
                    }                  
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show("Error accessing the Registry... Maybe run as admin?\n\n" + ex.ToString() , "HWID_CHNGER",MessageBoxButtons.OK,MessageBoxIcon.Exclamation );
            }
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 00000vish

[STAThread]
        static void Main()
        {
            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            try
            {
                //since cant detect if user open or started with windows
                //this app will only open with windows and opens app with -startup let main know its open with windowws
                checkArgs();
            }
            catch (Exception D) { MessageBox.Show(D.ToString());}           
            Environment.Exit(0);
        }

19 Source : Program.cs
with GNU General Public License v3.0
from 00000vish

private static void createRegistryKey()
        {
            Microsoft.Win32.RegistryKey regKey = default(Microsoft.Win32.RegistryKey);
            regKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("SOFTWARE\\Microsoft\\Windows\\CurrentVersion\\Run", true);
            try
            {
                string KeyName = "Steam Two";
                string KeyValue = Environment.CurrentDirectory + "\\SteamTwo Launcher.exe";
                regKey.SetValue(KeyName, KeyValue, Microsoft.Win32.RegistryValueKind.String);
            }
            catch (Exception e) { System.Windows.Forms.MessageBox.Show(e.ToString()); }
            Properties.Settings.Default.Save();
            regKey.Close();
        }

19 Source : CelesteNetClient.cs
with MIT License
from 0x0ade

private void OnUDPError(CelesteNetTCPUDPConnection con, Exception e, bool read) {
            if (!read)
                return;

            con.SendUDP = false;

            UDPDeathScore++;
            if (UDPDeathScore < UDPDeathScoreMax) {
                Logger.Log(LogLevel.CRI, "main", $"UDP connection died. Retrying.\nUDP score: {UDPDeathScore} / {UDPAliveScore}\n{this}\n{(e is ObjectDisposedException ? "Disposed" : e is SocketException ? e.Message : e.ToString())}");

            } else {
                UDPDeathScore = UDPDeathScoreMax;
                Logger.Log(LogLevel.CRI, "main", $"UDP connection died too often. Switching to TCP only.\nUDP score: {UDPDeathScore} / {UDPAliveScore}\n{this}\n{(e is ObjectDisposedException ? "Disposed" : e is SocketException ? e.Message : e.ToString())}");
                con.UDP?.Close();
                con.UDP = null;
            }

            con.Send(new DataTCPOnlyDowngrade());
        }

19 Source : RCEPControl.cs
with MIT License
from 0x0ade

[RCEndpoint(true, "/settings", "?module={id}", "?module=CelesteNet.Server", "Server Settings", "Get the settings of any server module as YAML.")]
        public static void Settings(Frontend f, HttpRequestEventArgs c) {
            NameValueCollection args = f.ParseQueryString(c.Request.RawUrl);
            string? moduleID = args["module"];
            if (moduleID.IsNullOrEmpty()) {
                c.Response.StatusCode = (int) HttpStatusCode.BadRequest;
                f.RespondJSON(c, new {
                    Error = "No ID."
                });
                return;
            }

            CelesteNetServerModuleSettings? settings;
            if (moduleID == "CelesteNet.Server") {
                settings = f.Server.Settings;
            } else {
                lock (f.Server.Modules)
                    settings = f.Server.Modules.FirstOrDefault(m => m.Wrapper.ID == moduleID)?.GetSettings();
            }

            if (settings == null) {
                c.Response.StatusCode = (int) HttpStatusCode.NotFound;
                f.RespondJSON(c, new {
                    Error = $"Module {moduleID} not loaded or doesn't have settings."
                });
                return;
            }

            if (c.Request.HttpMethod == "POST") {
                try {
                    using (StreamReader sr = new(c.Request.InputStream, Encoding.UTF8, false, 1024, true))
                        settings.Load(sr);
                    settings.Save();
                    f.RespondJSON(c, new {
                        Info = "Success."
                    });
                    return;
                } catch (Exception e) {
                    f.RespondJSON(c, new {
                        Error = e.ToString()
                    });
                    return;
                }
            }

            StringBuilder sb = new();
            using (StringWriter sw = new(sb))
                settings.Save(sw);
            f.Respond(c, sb.ToString());
        }

19 Source : RCEPControl.cs
with MIT License
from 0x0ade

[RCEndpoint(true, "/notes", "", "", "Admin Notes", "Get or set some administrative notes.")]
        public static void Notes(Frontend f, HttpRequestEventArgs c) {
            string path = Path.ChangeExtension(f.Settings.FilePath, ".notes.txt");
            string text;

            if (c.Request.HttpMethod == "POST") {
                try {
                    using (StreamReader sr = new(c.Request.InputStream, Encoding.UTF8, false, 1024, true))
                        text = sr.ReadToEnd();
                    File.WriteAllText(path, text);
                    f.RespondJSON(c, new {
                        Info = "Success."
                    });
                    return;
                } catch (Exception e) {
                    f.RespondJSON(c, new {
                        Error = e.ToString()
                    });
                    return;
                }
            }

            if (!File.Exists(path)) {
                f.Respond(c, "");
                return;
            }

            try {
                text = File.ReadAllText(path);
                f.Respond(c, text);
            } catch (Exception e) {
                f.RespondJSON(c, new {
                    Error = e.ToString()
                });
                return;
            }
        }

19 Source : FrontendWebSocket.cs
with MIT License
from 0x0ade

private void RunCommand(object? input) {
            if (CurrentCommand == null)
                throw new Exception("Cannot run no command.");
            if (Frontend == null)
                throw new Exception("Not ready.");

            try {
                object? output = CurrentCommand.Run(input);

                using MemoryStream ms = new();
                using (StreamWriter sw = new(ms, CelesteNetUtils.UTF8NoBOM, 1024, true))
                using (JsonTextWriter jtw = new(sw))
                    Frontend.Serializer.Serialize(jtw, output);

                ms.Seek(0, SeekOrigin.Begin);

                Send("data");
                using StreamReader sr = new(ms, Encoding.UTF8, false, 1024, true);
                Send(sr.ReadToEnd());

                State = EState.WaitForType;
            } catch (Exception e) {
                Logger.Log(LogLevel.ERR, "frontend-ws", e.ToString());
                Close("error on cmd run");
            }
        }

19 Source : RCEPControl.cs
with MIT License
from 0x0ade

[RCEndpoint(false, "/auth", null, null, "Authenticate", "Basic POST authentication endpoint.")]
        public static void Auth(Frontend f, HttpRequestEventArgs c) {
            string? key = c.Request.Cookies[Frontend.COOKIE_SESSION]?.Value;
            string? preplaced;

            try {
                using StreamReader sr = new(c.Request.InputStream, Encoding.UTF8, false, 1024, true);
                using JsonTextReader jtr = new(sr);
                preplaced = f.Serializer.Deserialize<string>(jtr);
            } catch (Exception e) {
                Logger.Log(LogLevel.DEV, "frontend-auth", e.ToString());
                preplaced = null;
            }

            if (preplaced.IsNullOrEmpty() && !key.IsNullOrEmpty()) {
                if (f.CurrentSessionKeys.Contains(key)) {
                    f.RespondJSON(c, new {
                        Key = key,
                        Info = "Resumed previous session based on cookies."
                    });
                    return;

                } else {
                    c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
                    f.RespondJSON(c, new {
                        Error = "Previous session expired."
                    });
                    return;
                }
            }

            if (preplaced == null) {
                c.Response.StatusCode = (int) HttpStatusCode.BadRequest;
                f.RespondJSON(c, new {
                    Error = "Invalid data."
                });
                return;
            }

            if (preplaced == f.Settings.PreplacedwordExec) {
                do {
                    key = Guid.NewGuid().ToString();
                } while (!f.CurrentSessionKeys.Add(key) || !f.CurrentSessionExecKeys.Add(key));
                c.Response.SetCookie(new(Frontend.COOKIE_SESSION, key));
                f.RespondJSON(c, new {
                    Key = key
                });
                return;
            }

            if (preplaced == f.Settings.Preplacedword) {
                do {
                    key = Guid.NewGuid().ToString();
                } while (!f.CurrentSessionKeys.Add(key));
                c.Response.SetCookie(new(Frontend.COOKIE_SESSION, key));
                f.RespondJSON(c, new {
                    Key = key
                });
                return;
            }

            c.Response.StatusCode = (int) HttpStatusCode.Unauthorized;
            f.RespondJSON(c, new {
                Error = "Incorrect preplacedword."
            });
        }

19 Source : CelesteNetTCPUDPConnection.cs
with MIT License
from 0x0ade

protected virtual void ReadTCPLoop() {
            try {
                bool loopend;
                lock (TCPReceiveLock)
                    loopend = Loopend;
                while ((TCP?.Connected ?? false) && IsAlive && !loopend) {
                    DataType data = Data.Read(TCPReader);
                    lock (TCPReceiveLock) {
                        loopend = Loopend;
                        if (loopend)
                            break;
                        Receive(data);
                    }
                }

            } catch (ThreadAbortException) {

            } catch (Exception e) {
                if (!IsAlive)
                    return;

                Logger.Log(LogLevel.CRI, "tcpudpcon", $"TCP loop error:\n{this}\n{(e is ObjectDisposedException ? "Disposed" : e is IOException ? e.Message : e.ToString())}");
                ReadTCPThread = null;
                Dispose();
            }
        }

19 Source : FrontendWebSocket.cs
with MIT License
from 0x0ade

protected override void OnMessage(MessageEventArgs c) {
            if (Frontend == null)
                throw new Exception("Not ready.");

            switch (State) {
                case EState.WaitForType:
                    switch (c.Data) {
                        case "cmd":
                            State = EState.WaitForCMDID;
                            break;

                        case "data":
                            State = EState.WaitForData;
                            break;

                        default:
                            Close("unknown type");
                            break;
                    }
                    break;


                case EState.WaitForCMDID:
                    Logger.Log(LogLevel.DEV, "frontend-ws", $"CMD: {Context.UserEndPoint} - {c.Data}");
                    WSCMD? cmd = Commands.Get(c.Data);
                    if (cmd == null) {
                        Close("unknown cmd");
                        break;
                    }

                    if (cmd.Auth && !IsAuthorized) {
                        Close("unauthorized");
                        break;
                    }

                    CurrentCommand = cmd;
                    State = EState.WaitForCMDPayload;
                    break;


                case EState.WaitForCMDPayload:
                    object? input = null;

                    try {
                        using MemoryStream ms = new(c.RawData);
                        using StreamReader sr = new(ms, Encoding.UTF8, false, 1024, true);
                        using JsonTextReader jtr = new(sr);
                        input =
                            CurrentCommand?.InputType != null ? Frontend.Serializer.Deserialize(jtr, CurrentCommand.InputType) :
                            Frontend.Serializer.Deserialize<dynamic>(jtr);
                    } catch (Exception e) {
                        Logger.Log(LogLevel.ERR, "frontend-ws", e.ToString());
                        Close("error on cmd data parse");
                        break;
                    }

                    RunCommand(input);
                    break;


                case EState.WaitForData:
                    // TODO: Handle receiving responses!
                    State = EState.WaitForType;
                    break;


                default:
                    Close("unknown state");
                    break;
            }
        }

19 Source : CelesteNetTCPUDPConnection.cs
with MIT License
from 0x0ade

protected virtual void ReadUDPLoop() {
            try {
                using MemoryStream stream = new();
                using CelesteNetBinaryReader reader = new(Data, UDPQueue.Strings, stream);
                while (UDP != null && IsAlive && !Loopend) {
                    IPEndPoint? remote = null;
                    byte[] raw = UDP.Receive(ref remote);
                    if (UDPRemoteEndPoint != null && !remote.Equals(UDPRemoteEndPoint))
                        continue;

                    stream.Seek(0, SeekOrigin.Begin);
                    stream.Write(raw, 0, raw.Length);

                    stream.Seek(0, SeekOrigin.Begin);
                    Receive(Data.Read(reader));
                }

            } catch (ThreadAbortException) {

            } catch (Exception e) {
                if (!IsAlive)
                    return;

                ReadUDPThread = null;
                lock (UDPErrorLock) {
                    UDPErrorLast = e;
                    if (_OnUDPError != null) {
                        _OnUDPError(this, e, true);
                    } else {
                        Logger.Log(LogLevel.CRI, "tcpudpcon", $"UDP loop error:\n{this}\n{(e is ObjectDisposedException ? "Disposed" : e is SocketException ? e.Message : e.ToString())}");
                        Dispose();
                    }
                }
            }
        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

public static byte[] GetMasterKey(string LocalStateFolder)
        {
            //Key saved in Local State file
            string filePath = LocalStateFolder + @"\Local State";
            byte[] masterKey = new byte[] { };

            if (File.Exists(filePath) == false)
                return null;

            //Get key with regex.
            var pattern = new System.Text.RegularExpressions.Regex("\"encrypted_key\":\"(.*?)\"", System.Text.RegularExpressions.RegexOptions.Compiled).Matches(File.ReadAllText(filePath));

            foreach (System.Text.RegularExpressions.Match prof in pattern)
            {
                if (prof.Success)
                    masterKey = Convert.FromBase64String((prof.Groups[1].Value)); //Decode base64
            }

            //Trim first 5 bytes. Its signature "DPAPI"
            byte[] temp = new byte[masterKey.Length - 5];
            Array.Copy(masterKey, 5, temp, 0, masterKey.Length - 5);

            try
            {
                return ProtectedData.Unprotect(temp, null, DataProtectionScope.CurrentUser);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

public static string Decrypt(string encryptedData)
        {
            if (encryptedData == null || encryptedData.Length == 0)
                return null;
            try
            {
                return Encoding.UTF8.GetString(ProtectedData.Unprotect(Encoding.Default.GetBytes(encryptedData), null, DataProtectionScope.CurrentUser));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

private static List<Account> Accounts(string path, string browser, string table = "logins")
        {

            //Get all created profiles from browser path
            List<string> loginDataFiles = GetAllProfiles(path); 

            List<Account> data = new List<Account>();

            foreach (string loginFile in loginDataFiles.ToArray())
            {
                if (!File.Exists(loginFile))
                    continue;

                SQLiteHandler SQLDatabase;

                try
                {
                    SQLDatabase = new SQLiteHandler(loginFile); //Open database with Sqlite
                }
                catch (System.Exception ex)
                {
                    Console.WriteLine(ex.ToString());
                    continue;
                }

                if (!SQLDatabase.ReadTable(table)) 
                    continue;

                for (int I = 0; I <= SQLDatabase.GetRowCount() - 1; I++)
                {
                    try
                    {
                        //Get values with row number and column name
                        string host = SQLDatabase.GetValue(I, "origin_url");
                        string username = SQLDatabase.GetValue(I, "username_value");
                        string preplacedword = SQLDatabase.GetValue(I, "preplacedword_value");

                        if (preplacedword != null)
                        {
                            //check v80 preplacedword signature. its starting with v10 or v11
                            if (preplacedword.StartsWith("v10") || preplacedword.StartsWith("v11"))
                            {
                                //Local State file located in the parent folder of profile folder.
                                byte[] masterKey = GetMasterKey(Directory.GetParent(loginFile).Parent.FullName); 

                                if (masterKey == null)
                                    continue;

                                preplacedword = DecryptWithKey(Encoding.Default.GetBytes(preplacedword), masterKey);
                            }
                            else
                                preplacedword = Decrypt(preplacedword); //Old versions using UnprotectData for decryption without any key
                        }
                        else
                            continue;

                        if (!string.IsNullOrEmpty(host) && !string.IsNullOrEmpty(username) && !string.IsNullOrEmpty(preplacedword))
                            data.Add(new Account() { URL = host, UserName = username, Preplacedword = preplacedword, Application = browser });
                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.ToString());
                    }
                }
            }

            return data;
        }

19 Source : Chromium.cs
with GNU General Public License v3.0
from 0xfd3

public static string DecryptWithKey(byte[] encryptedData, byte[] MasterKey)
        {
            byte[] iv = new byte[] { 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0 }; // IV 12 bytes

            //trim first 3 bytes(signature "v10") and take 12 bytes after signature.
            Array.Copy(encryptedData, 3, iv, 0, 12);

            try
            {
                //encryptedData without IV
                byte[] Buffer = new byte[encryptedData.Length - 15];
                Array.Copy(encryptedData, 15, Buffer, 0, encryptedData.Length - 15);

                byte[] tag = new byte[16]; //AuthTag
                byte[] data = new byte[Buffer.Length - tag.Length]; //Encrypted Data

                //Last 16 bytes for tag
                Array.Copy(Buffer, Buffer.Length - 16, tag, 0, 16);

                //encrypted preplacedword
                Array.Copy(Buffer, 0, data, 0, Buffer.Length - tag.Length);

                AesGcm aesDecryptor = new AesGcm();
                var result = Encoding.UTF8.GetString(aesDecryptor.Decrypt(MasterKey, iv, null, data, tag));

                return result;
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.ToString());
                return null;
            }
        }

19 Source : Program.cs
with MIT License
from 0xd4d

static int Main(string[] args) {
			try {
				switch (System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture) {
				case System.Runtime.InteropServices.Architecture.X64:
				case System.Runtime.InteropServices.Architecture.X86:
					break;
				default:
					throw new ApplicationException($"Unsupported CPU arch: {System.Runtime.InteropServices.RuntimeInformation.ProcessArchitecture}");
				}

				var jitDasmOptions = CommandLineParser.Parse(args);
				if (!string2.IsNullOrEmpty(jitDasmOptions.LoadModule)) {
#if DEBUG
					Console.Error.WriteLine($"Trying to jit methods in module '{jitDasmOptions.LoadModule}' but JitDasm is a debug build, not a release build!");
#endif
					MethodJitter.JitMethods(jitDasmOptions.LoadModule, jitDasmOptions.TypeFilter, jitDasmOptions.MethodFilter, jitDasmOptions.RunClreplacedConstructors, jitDasmOptions.replacedemblySearchPaths);
				}
				var (bitness, methods, knownSymbols) = GetMethodsToDisreplacedemble(jitDasmOptions.Pid, jitDasmOptions.ModuleName, jitDasmOptions.TypeFilter, jitDasmOptions.MethodFilter, jitDasmOptions.HeapSearch);
				var jobs = GetJobs(methods, jitDasmOptions.OutputDir, jitDasmOptions.FileOutputKind, jitDasmOptions.FilenameFormat, out var baseDir);
				if (!string2.IsNullOrEmpty(baseDir))
					Directory.CreateDirectory(baseDir);
				var sourceDoreplacedentProvider = new SourceDoreplacedentProvider();
				using (var mdProvider = new MetadataProvider()) {
					var sourceCodeProvider = new SourceCodeProvider(mdProvider, sourceDoreplacedentProvider);
					using (var context = new DisasmJobContext(bitness, knownSymbols, sourceCodeProvider, jitDasmOptions.DisreplacedemblerOutputKind, jitDasmOptions.Diffable, jitDasmOptions.ShowAddresses, jitDasmOptions.ShowHexBytes, jitDasmOptions.ShowSourceCode)) {
						foreach (var job in jobs)
							Disreplacedemble(context, job);
					}
				}
				return 0;
			}
			catch (ShowCommandLineHelpException) {
				CommandLineParser.ShowHelp();
				return 1;
			}
			catch (CommandLineParserException ex) {
				Console.WriteLine(ex.Message);
				return 1;
			}
			catch (ApplicationException ex) {
				Console.WriteLine(ex.Message);
				return 1;
			}
			catch (ClrDiagnosticsException ex) {
				Console.WriteLine(ex.Message);
				Console.WriteLine("Make sure this process has the same bitness as the target process");
				return 1;
			}
			catch (Exception ex) {
				Console.WriteLine(ex.ToString());
				return 1;
			}
		}

19 Source : Log.cs
with MIT License
from 13xforever

private static void LogInternal(Exception e, string message, LogLevel level, ConsoleColor foregroundColor, ConsoleColor? backgroundColor = null)
        {
            try
            {
#if DEBUG
                const LogLevel minLevel = LogLevel.TRACE;
#else
                const LogLevel minLevel = LogLevel.DEBUG;
#endif
                if (level >= minLevel && message != null)
                {
                    Console.ForegroundColor = foregroundColor;
                    if (backgroundColor is ConsoleColor bg)
                        Console.BackgroundColor = bg;
                    Console.WriteLine(DateTime.Now.ToString("hh:mm:ss ") + message);
                    Console.ResetColor();
                }
                if (FileLog != null)
                {
                    if (message != null)
                        FileLog.WriteLine($"{DateTime.Now:yyyy-MM-dd hh:mm:ss}\t{(long)Timer.Elapsed.TotalMilliseconds}\t{level}\t{message}");
                    if (e != null)
                        FileLog.WriteLine(e.ToString());
                    FileLog.Flush();
                }
            }
            catch { }
        }

19 Source : ExceptionHandleMiddleware.cs
with MIT License
from 17MKH

private Task HandleExceptionAsync(HttpContext context, Exception exception)
    {
        context.Response.ContentType = "application/json";
        context.Response.StatusCode = (int)HttpStatusCode.InternalServerError;

        //开发环境返回详细异常信息
        var error = _env.IsDevelopment() ? exception.ToString() : exception.Message;

        _logger.LogError(error);

        return context.Response.WriteAsync(_jsonHelper.Serialize(ResultModel.Failed(error)));
    }

19 Source : Server.cs
with MIT License
from 1ZouLTReX1

private void StartServer()
    {
        // Establish the local endpoint for the socket. 
        IPAddress ipAddress = ServerInfo.ipAddress;
        IPEndPoint localEndPoint = ServerInfo.localEP;

        Console.WriteLine("The server is running at: " + localEndPoint.Address.ToString() + " : " + localEndPoint.Port.ToString());
        Console.WriteLine("Is loopback: " + IPAddress.IsLoopback(localEndPoint.Address));

        // Create a TCP/IP socket.  
        listenerSocket = new Socket(ipAddress.AddressFamily,
            SocketType.Stream, ProtocolType.Tcp);

        // Bind the socket to the local endpoint and listen for incoming connections.  
        try
        {
            listenerSocket.Bind(localEndPoint);
            listenerSocket.Listen(MaximumPlayers);

            Thread selectThr = new Thread(StartListening);
            selectThr.Start();
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
            Application.Quit();
        }
    }

19 Source : About.cs
with MIT License
from 1CM69

private void GetSettingsValues()
        {
            try
            {
                this.RegularMode.Checked = Convert.ToBoolean(Properties.Settings.Default.Regular);
                this.NightMode.Checked = Convert.ToBoolean(Properties.Settings.Default.Night);

            }
            catch (Exception ex)
            {
                int num = (int)MessageBox.Show(ex.ToString());
                Properties.Settings.Default.Regular = RegularMode.Checked;
                Properties.Settings.Default.Night =  NightMode.Checked;
                Properties.Settings.Default.Save();
            }
        }

19 Source : Help.cs
with MIT License
from 1CM69

private void GetSettingsValues()
        {
            try
            {
                this.RegularMode.Checked = Convert.ToBoolean(Properties.Settings.Default.Regular);
                this.NightMode.Checked = Convert.ToBoolean(Properties.Settings.Default.Night);

            }
            catch (Exception ex)
            {
                int num = (int)MessageBox.Show(ex.ToString());
                Properties.Settings.Default.Regular = RegularMode.Checked;
                Properties.Settings.Default.Night = NightMode.Checked;
                Properties.Settings.Default.Save();
            }
        }

19 Source : AIClient.cs
with MIT License
from 1ZouLTReX1

private void ClientConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.  
            Socket client = (Socket)ar.AsyncState;
            // Complete the connection.  
            client.EndConnect(ar);
            // Disable the Nagle Algorithm for this tcp socket.
            client.NoDelay = true;
            // Set the receive buffer size to 4k
            client.ReceiveBufferSize = 4096;
            // Set the send buffer size to 4k.
            client.SendBufferSize = 4096;

            isConnected = true;
        }
        catch (Exception e)
        {
            Debug.Log("Something went wrong and the socket couldn't connect");
            Debug.Log(e.ToString());
            return;
        }

        // Setup done, ConnectDone.
        Debug.Log(string.Format("Socket connected to {0}", clientSock.RemoteEndPoint.ToString()));
        Debug.Log("Connected, Setup Done");
    }

19 Source : AIClient.cs
with MIT License
from 1ZouLTReX1

private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.  
            Socket client = (Socket) ar.AsyncState;
            // Complete sending the data to the remote device.  
            int bytesSent = client.EndSend(ar);

            // string str = string.Format("Sent {0} bytes to server.", bytesSent);
            // Debug.Log(str);-
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }

19 Source : AIClient.cs
with MIT License
from 1ZouLTReX1

private void Update()
    {
        try
        {
            if (clientSock != null && !clientSock.Connected)
            {
                // If we got disconnected or we couldn't connect after at least 10 seconds we close the program.
                if (Time.realtimeSinceStartup > 10)
                {
                    Application.Quit();
                }
            }

            AIInputHandler.AddInputEvent(statisticsModule.tickAck, PacketStartTime.Time);
            ClientTick();
        } 
        catch (Exception e)
        {
            Debug.Log(e.ToString());

            Debug.Log("We got hit");
            Application.Quit();
        }
    }

19 Source : Client.cs
with MIT License
from 1ZouLTReX1

private void ClientConnectCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.  
            Socket client = (Socket)ar.AsyncState;
            // Complete the connection.  
            client.EndConnect(ar);
            // Disable the Nagle Algorithm for this tcp socket.
            client.NoDelay = true;
            // Set the receive buffer size to 4k
            client.ReceiveBufferSize = 4096;
            // Set the send buffer size to 4k.
            client.SendBufferSize = 4096;

            isConnected = true;
        }
        catch (Exception e)
        {
            UnityThread.executeInUpdate(() =>
            {
                networkErrorMsgFailed.SetActive(true);
            });

            Debug.Log("Something went wrong and the socket couldn't connect");
            Debug.Log(e.ToString());
            return;
        }

        // Setup done, ConnectDone.
        Debug.Log(string.Format("Socket connected to {0}", clientSock.RemoteEndPoint.ToString()));
        Debug.Log("Connected, Setup Done");

        UnityThread.executeInUpdate(() =>
        {
            networkStatePanel.SetActive(false);
            networkConnectPanel.SetActive(false);

            networkAlgorithmsPanel.SetActive(true);
            graphyOverlay.SetActive(true);
        });

        // Start the receive thread
        StartReceive();
    }

19 Source : Client.cs
with MIT License
from 1ZouLTReX1

private void StartReceive()
    {
        try
        {
            // Start the receive thread.
            Thread recThr = new Thread(new ThreadStart(ReceiveLoop));
            recThr.Start();
        }
        catch (Exception e)
        {
            Debug.Log("Something went wrong and the socket couldn't receive");
            Debug.Log(e.ToString());
        }
    }

19 Source : Client.cs
with MIT License
from 1ZouLTReX1

private static void SendCallback(IAsyncResult ar)
    {
        try
        {
            // Retrieve the socket from the state object.  
            Socket client = (Socket) ar.AsyncState;
            // Complete sending the data to the remote device.  
            int bytesSent = client.EndSend(ar);

            // string str = string.Format("Sent {0} bytes to server.", bytesSent);
            // Debug.Log(str);
        }
        catch (Exception e)
        {
            Debug.Log(e.ToString());
        }
    }

19 Source : Form1.cs
with Mozilla Public License 2.0
from 1M50RRY

private void button2_Click(object sender, EventArgs e)
        {
            //choose file
            int size = -1;
            DialogResult result = openFileDialog1.ShowDialog(); 
            if (result == DialogResult.OK) 
            {
                string file = openFileDialog1.FileName;
                try
                {
                    byte[] bytes = File.ReadAllBytes(file);
                    size = bytes.Length;
                    encFile = bytes;
                    fpath.Text = file;
                }
                catch (IOException exc)
                {
                    MessageBox.Show(exc.ToString());
                }
            }
        }

19 Source : Utils.cs
with GNU General Public License v3.0
from 2dust

public static void SaveLog(string strreplacedle, Exception ex)
        {
            try
            {
                string path = Path.Combine(StartupPath(), "guiLogs");
                string FilePath = Path.Combine(path, DateTime.Now.ToString("yyyyMMdd") + ".txt");
                if (!Directory.Exists(path))
                {
                    Directory.CreateDirectory(path);
                }
                if (!File.Exists(FilePath))
                {
                    FileStream FsCreate = new FileStream(FilePath, FileMode.Create);
                    FsCreate.Close();
                    FsCreate.Dispose();
                }
                FileStream FsWrite = new FileStream(FilePath, FileMode.Append, FileAccess.Write);
                StreamWriter SwWrite = new StreamWriter(FsWrite);

                string strContent = ex.ToString();

                SwWrite.WriteLine(string.Format("{0}{1}[{2}]{3}", "--------------------------------", strreplacedle, DateTime.Now.ToString("HH:mm:ss"), "--------------------------------"));
                SwWrite.Write(strContent);
                SwWrite.WriteLine(Environment.NewLine);
                SwWrite.WriteLine(" ");
                SwWrite.Flush();
                SwWrite.Close();
            }
            catch { }
        }

19 Source : DownloadHandle.cs
with GNU General Public License v3.0
from 2dust

void ws_DownloadFileCompleted(object sender, System.ComponentModel.AsyncCompletedEventArgs e)
        {
            try
            {
                if (UpdateCompleted != null)
                {
                    if (e.Cancelled)
                    {
                        ((WebClientEx)sender).Dispose();
                        TimeSpan ts = (DateTime.Now - totalDatetime);
                        string speed = string.Format("{0} M/s", (totalBytesToReceive / ts.TotalMilliseconds / 1000).ToString("#0.0"));
                        UpdateCompleted(this, new ResultEventArgs(true, speed.PadLeft(8, ' ')));
                        return;
                    }

                    if (e.Error == null
                        || Utils.IsNullOrEmpty(e.Error.ToString()))
                    {

                        TimeSpan ts = (DateTime.Now - totalDatetime);
                        string speed = string.Format("{0} M/s", (totalBytesToReceive / ts.TotalMilliseconds / 1000).ToString("#0.0"));
                        UpdateCompleted(this, new ResultEventArgs(true, speed.PadLeft(8, ' ')));
                    }
                    else
                    {
                        throw e.Error;
                    }
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);

                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
        }

19 Source : DownloadHandle.cs
with GNU General Public License v3.0
from 2dust

private void Ws_DownloadStringCompleted(object sender, DownloadStringCompletedEventArgs e)
        {
            try
            {
                if (e.Error == null
                    || Utils.IsNullOrEmpty(e.Error.ToString()))
                {
                    string source = e.Result;
                    UpdateCompleted?.Invoke(this, new ResultEventArgs(true, source));
                }
                else
                {
                    throw e.Error;
                }
            }
            catch (Exception ex)
            {
                Utils.SaveLog(ex.Message, ex);

                Error?.Invoke(this, new ErrorEventArgs(ex));
            }
        }

19 Source : MainWindow.xaml.cs
with MIT License
from 3RD-Dimension

private void UnhandledException(object sender, UnhandledExceptionEventArgs ea)
		{
			Exception e = (Exception)ea.ExceptionObject;

			string info = "Unhandled Exception:\r\nMessage:\r\n";
			info += e.Message;
			info += "\r\nStackTrace:\r\n";
			info += e.StackTrace;
			info += "\r\nToString():\r\n";
			info += e.ToString();

			MessageBox.Show("There has been an Unhandled Exception, the error has been logged to a file in the directory");
            Logger.Error(info);

            Environment.Exit(1);
		}

19 Source : AsyncETVoidMethodBuilder.cs
with MIT License
from 404Lcc

[DebuggerHidden]
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        public void SetException(Exception exception)
        {
            LogUtil.LogError(exception.ToString());
        }

19 Source : MultiTenantMigrateExecuter.cs
with MIT License
from 52ABP

public bool Run(bool skipConnVerification)
        {
            var hostConnStr = CensorConnectionString(_connectionStringResolver.GetNameOrConnectionString(new ConnectionStringResolveArgs(MulreplacedenancySides.Host)));
            if (hostConnStr.IsNullOrWhiteSpace())
            {
                _log.Write("Configuration file should contain a connection string named 'Default'");
                return false;
            }

            _log.Write("Host database: " + ConnectionStringHelper.GetConnectionString(hostConnStr));
            if (!skipConnVerification)
            {
                _log.Write("Continue to migration for this host database and all tenants..? (Y/N): ");
                var command = Console.ReadLine();
                if (!command.IsIn("Y", "y"))
                {
                    _log.Write("Migration canceled.");
                    return false;
                }
            }

            _log.Write("HOST database migration started...");

            try
            {
                _migrator.CreateOrMigrateForHost(SeedHelper.SeedHostDb);
            }
            catch (Exception ex)
            {
                _log.Write("An error occured during migration of host database:");
                _log.Write(ex.ToString());
                _log.Write("Canceled migrations.");
                return false;
            }

            _log.Write("HOST database migration completed.");
            _log.Write("--------------------------------------------------------");

            var migratedDatabases = new HashSet<string>();
            var tenants = _tenantRepository.GetAllList(t => t.ConnectionString != null && t.ConnectionString != "");
            for (var i = 0; i < tenants.Count; i++)
            {
                var tenant = tenants[i];
                _log.Write(string.Format("Tenant database migration started... ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("Name              : " + tenant.Name);
                _log.Write("TenancyName       : " + tenant.TenancyName);
                _log.Write("Tenant Id         : " + tenant.Id);
                _log.Write("Connection string : " + SimpleStringCipher.Instance.Decrypt(tenant.ConnectionString));

                if (!migratedDatabases.Contains(tenant.ConnectionString))
                {
                    try
                    {
                        _migrator.CreateOrMigrateForTenant(tenant);
                    }
                    catch (Exception ex)
                    {
                        _log.Write("An error occured during migration of tenant database:");
                        _log.Write(ex.ToString());
                        _log.Write("Skipped this tenant and will continue for others...");
                    }

                    migratedDatabases.Add(tenant.ConnectionString);
                }
                else
                {
                    _log.Write("This database has already migrated before (you have more than one tenant in same database). Skipping it....");
                }

                _log.Write(string.Format("Tenant database migration completed. ({0} / {1})", (i + 1), tenants.Count));
                _log.Write("--------------------------------------------------------");
            }

            _log.Write("All databases have been migrated.");

            return true;
        }

19 Source : CometaryAnalyzer.cs
with MIT License
from 71

[SuppressMessage("replacedyzerPerformance", "RS1012", Justification = "Yes, all those methods register no action. It's okay.")]
        public override void Initialize(replacedysisContext context)
        {
            // Initialize this exception here
            // When testing Cometary, I noticed that 'StartAction' often wasn't called at all,
            // and nothing indicated it (no error, or warning of the sort).
            // It hasn't happened since I fixed some other stuff (huh R# won't let me use the B u g word)
            // but I'm leaving this like this, just in case.

            // basically, we default to an error, and iff StartAction is successfully ran, we
            // remove this error. if it does run an throws, we replace this error with the exception.
            Exception encounteredException = new Exception("Could not initialize Cometary.");

            void RegisterAction(CompilationStartreplacedysisContext ctx)
            {
                replacedemblyLoading.CurrentCompilation = ctx.Compilation;
            }

            void StartAction(CompilationStartreplacedysisContext ctx)
            {
                try
                {
                    Hooks.EnsureInitialized();

                    encounteredException = null;
                }
                catch (Exception e)
                {
                    encounteredException = e;
                }
            }

            void EndAction(CompilationreplacedysisContext ctx)
            {
                ctx.ReportDiagnostic(encounteredException != null
                    ? Diagnostic.Create(HookError, Location.None, encounteredException.ToString())
                    : Diagnostic.Create(HookSuccess, Location.None));
            }

            // Make sure we Cometary.Core can be loaded
            context.RegisterCompilationStartAction(RegisterAction);

            // Create a matching CometaryManager
            context.RegisterCompilationStartAction(StartAction);

            // Logs a message on success
            context.RegisterCompilationAction(EndAction);
        }

19 Source : TaskExtensionTest.cs
with MIT License
from 5argon

public static async Task ShouldThrow<T>(this Task asyncMethod, string message) where T : Exception
        {
            try
            {
                await asyncMethod; //Should throw..
            }
            catch (T)
            {
                //Task should throw Aggregate but add this just in case.
                Debug.Log("Caught an exception : " + typeof(T).FullName + " !!");
                return;
            }
            catch (AggregateException ag)
            {
                foreach (Exception e in ag.InnerExceptions)
                {
                    Debug.Log("Caught an exception : " + e.GetType().FullName + " !!");
                    if (message != "")
                    {
                        //Fails here if we find any other inner exceptions
                        replacedert.That(e, Is.TypeOf<T>(), message + " | " + e.ToString());
                    }
                    else
                    {
                        //Fails here also
                        replacedert.That(e, Is.TypeOf<T>(), e.ToString() + " " + "An exception should be of type " + typeof(T).FullName);
                    }
                }
                return;
            }
            replacedert.Fail("Expected an exception of type " + typeof(T).FullName + " but no exception was thrown.");
        }

19 Source : Program.cs
with MIT License
from 8bitbytes

public static int Main()
        {
            bool done = false;
            UdpClient listener = new UdpClient(listenPort);
            IPEndPoint groupEP = new IPEndPoint(IPAddress.Any, listenPort);
            string received_data;
            byte[] receive_byte_array;
            try
            {
                while (!done)
                {
                    Console.WriteLine("Waiting for broadcast");
                    receive_byte_array = listener.Receive(ref groupEP);
                    Console.WriteLine("Received a broadcast from {0}", groupEP.ToString());
                    received_data = Encoding.ASCII.GetString(receive_byte_array, 0, receive_byte_array.Length);
                    Console.WriteLine("data follows \n{0}\n\n", received_data);
                    if (received_data.IndexOf("?") > -1)
                    {
                        var resp = processRequestReponseMessage(received_data);
                        SendMessage(listener, resp, groupEP);
                    }
                    else
                    {
                        processCommand(received_data);
                        SendMessage(listener, "OK", groupEP);
                    }
                }
            }
            catch (Exception e)
            {
                writeErrorMessage(e.ToString());
                SendMessage(listener, e.Message, groupEP);
            }
            listener.Close();
            return 0;
        }

19 Source : CloudCluster.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                var cgh = new GH_Cloud();
                DA.GetData(0, ref cgh);
                var cghRef = new GH_Cloud();
               if(! DA.GetData(1, ref cghRef)) {
                    cghRef = cgh;
                }

                double r = 0.1;
               // int it = 30;
                int n = 10;
                bool split = false;
                DA.GetData(2, ref r);
                //DA.GetData(2, ref it);
                DA.GetData(3, ref n);
                DA.GetData(4, ref split);


                var c =  PInvokeCSharp.TestCGAL.Clustering(cgh.Value, cghRef.Value, r,n, split);
                //this.Message = c.Count.ToString();

                GH_Cloud[] clouds = new GH_Cloud[c.Length];
                for (int i = 0; i < c.Length; i++) {
                    clouds[i] = new GH_Cloud(c[i]);
                }

                DA.SetDataList(0, clouds);
            }catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : MeshBoolean.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            Random random = new Random();
            //Input
            GH_Structure<GH_Mesh> B0 = new GH_Structure<GH_Mesh>();
            GH_Structure<GH_Mesh> B1 = new GH_Structure<GH_Mesh>();
            DA.GetDataTree(0, out B0);
            DA.GetDataTree(1, out B1);

            int t = 0;
            DA.GetData(2, ref t);



            double scale = 1.001;
            DA.GetData(3, ref scale);


            bool showEdges = false;
            DA.GetData(5, ref showEdges);


            var color = System.Drawing.Color.White;
            bool f = DA.GetData(4, ref color);
            if (color.R == 255 && color.G == 255 && color.B == 255) {
                f = false;
            }

            //Match trees

            var result = new DataTree<Mesh>();



            for (int i = 0; i < B0.PathCount; i++) {

                var path = B0.Paths[i];


                result.Add(B0.get_DataItem(path, 0).Value, path);
                if (!B1.PathExists(path)) continue;

                HashSet<Point3d> cylindersCenters = new HashSet<Point3d>();

  

                var nonNulls = new List<GH_Mesh>();
                foreach (var v in B1[path]) {
                    if (v != null) {
                        nonNulls.Add(v);
                    }
                }


                for (int j = 0; j < nonNulls.Count; j++) {

                    var brep = nonNulls[j].Value.DuplicateMesh();
                    brep.Transform(Rhino.Geometry.Transform.Scale(brep.GetBoundingBox(true).Center, scale));
                    Mesh mesh = brep;
                    result.Add(mesh, path);
                }

            }



            //Perform boolean
            var resultBoolean = new DataTree<Mesh>();

            for (int b = 0; b < result.BranchCount; b++) {
                GH_Path path = result.Paths[b];
                List<Mesh> m = result.Branch(path);

                //Rhino.RhinoApp.WriteLine(m.Count.ToString());
                if (m.Count == 1) {
                    Mesh mm = m[0].DuplicateMesh();
                    mm.Unweld(0, true);

                    //DA.SetDataList(0, new Mesh[] { mm });

                    //if (!f) 
                    mm.VertexColors.CreateMonotoneMesh(System.Drawing.Color.FromArgb(200, 200, 200));
                    m_.Append(mm);
                    if(showEdges)
                        l_.AddRange(MeshEdgesByAngle(mm, 0.37));
                    if (bbox_.IsValid) bbox_.Union(m_.GetBoundingBox(false)); else bbox_ = m_.GetBoundingBox(false);


                    resultBoolean.Add(mm, path);

                } else {
                    try {
                        //Mesh r = f ? PInvokeCSharp.TestLIBIGL.CreateLIBIGLMeshBoolean(m.ToArray(), t) : PInvokeCSharp.TestCGAL.CreateMeshBooleanArray(m.ToArray(), t);
                        Mesh r = f ? PInvokeCSharp.TestCGAL.CreateMeshBooleanArrayTrackColors(m.ToArray(), color,Math.Abs( t)) : PInvokeCSharp.TestCGAL.CreateMeshBooleanArray(m.ToArray(), Math.Abs(t));
                        // Mesh r = PInvokeCSharp.TestCGAL.CreateMeshBooleanArrayTrackColors(m.ToArray(), color, t) ;
                        //resultBoolean.Add(r, path);
                        if (r.IsValid) {

                            Mesh[] s = null;
                            if (t == 0 || t == 1) {
                              s = r.SplitDisjointPieces();

                                double[] a = new double[s.Length];
                                for (int i = 0; i < s.Length; i++)
                                    a[i] = s[i].GetBoundingBox(false).Diagonal.Length;

                                Array.Sort(a, s);
                            } else {
                                s = new Mesh[] { r };
                            }

                            if (!f) s[s.Length - 1].VertexColors.CreateMonotoneMesh(System.Drawing.Color.FromArgb(200, 200, 200));
                            m_.Append(s[s.Length - 1]);

                            if (showEdges)
                                l_.AddRange(MeshEdgesByAngle(s[s.Length - 1], 0.37));
                            if (bbox_.IsValid) bbox_.Union(m_.GetBoundingBox(false)); else bbox_ = m_.GetBoundingBox(false);
                            resultBoolean.Add(s[s.Length - 1], path);

                        }
                    } catch (Exception e) {
                        Rhino.RhinoApp.WriteLine(e.ToString());
                    }
                }
            }

            DA.SetDataTree(0, resultBoolean);

        }

19 Source : CloudPreview.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {


                GH_Cloud cloud = new GH_Cloud();
                DA.GetData(0, ref cloud);

                var color = System.Drawing.Color.Red;
                DA.GetData(1, ref color);

                int t = 2;
                DA.GetData(2, ref t);
                StaticParameters.DisplayRadius = t;

                var points  = cloud.Value.GetPoints();
                //var normals = cloud.Value.GetNormals();
                var colors = System.Linq.Enumerable.ToArray(System.Linq.Enumerable.Repeat(color,cloud.Value.Count));

                //System.Threading.Tasks.Parallel.For(0, cloud.Value.Count, i => {
                //    colors[i] = color;

                //});
     
                PointCloud c = new PointCloud();
                c.AddRange(points, colors);
     
        
                DA.SetData(0, new GH_Cloud(c));







            } catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : CloudRANSAC.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                var cgh = new GH_Cloud();
                DA.GetData(0, ref cgh);
   

                double distance = 0.1;
                double neighbours = 10;
                double iterations = 10;
    bool InliersOrOutliers = true; 
                DA.GetData(1, ref distance);
                DA.GetData(2, ref neighbours);
                DA.GetData(3, ref iterations);
                DA.GetData(4, ref InliersOrOutliers);


                var c =  PInvokeCSharp.TestOpen3D.RANSACPlane(cgh.Value, distance, neighbours, iterations, InliersOrOutliers);
  

                GH_Cloud[] clouds = new GH_Cloud[c.Length];
                for (int i = 0; i < c.Length; i++) {
                    clouds[i] = new GH_Cloud(c[i]);
                }

                DA.SetDataList(0, clouds);
            }catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : CloudSOR.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                var cgh = new GH_Cloud();
                DA.GetData(0, ref cgh);
      

                double radius = 0;
                double percent = 0;
                double neighbours = 0;
                double type = 0;

                DA.GetData(1, ref radius);
                DA.GetData(2, ref percent);
                DA.GetData(3, ref neighbours);
                DA.GetData(4, ref type);


                var c =  PInvokeCSharp.TestCGAL.SOR(cgh.Value, radius,percent,(int)neighbours, (int)type);
                DA.SetData(0, new GH_Cloud(c));

            }catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : CloudMesh.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                var cgh = new GH_Cloud();
                DA.GetData(0, ref cgh);

                int PoisonMaxDepth = 8;  int PoisonMinDepth = 0;    double PoisonScale = 1.1f; bool Linear = false; bool color = false; bool Open3d_CGAL = true;
                DA.GetData(1, ref PoisonMaxDepth);
                DA.GetData(2, ref PoisonMinDepth);
                DA.GetData(3, ref PoisonScale);
                DA.GetData(4, ref Linear);
                DA.GetData(5, ref color);
                DA.GetData(6, ref Open3d_CGAL);


      

                if (Open3d_CGAL) {
                    var m = PInvokeCSharp.TestOpen3D.Poisson(cgh.Value, (ulong)PoisonMaxDepth, (ulong)PoisonMinDepth, (float)PoisonScale, Linear);
                    Mesh mm = m.Item1;
                    if (!color)
                        mm.VertexColors.Clear();
                    //this.Message = c.Count.ToString();

                    DA.SetData(0, mm);
                    DA.SetDataList(1, m.Item2);
                } else {
                    DA.SetData(0, PInvokeCSharp.TestCGAL.CreatePoissonSurfaceReconstruction(cgh.Value));

                }

                
            } catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : CloudNormals.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                var cgh = new GH_Cloud();
                DA.GetData(0, ref cgh);

                double r = 0.1;
                int it = 30;
                int n = 10;
                double length = 1;
                bool erase = true;
                DA.GetData(1, ref r);
                DA.GetData(2, ref it);
                DA.GetData(3, ref n);
                DA.GetData(4, ref length);
                DA.GetData(5, ref erase);

                var c =  PInvokeCSharp.TestCGAL.CreateNormals(cgh.Value, r, it, n,erase);//f ? PInvokeCSharp.TestOpen3D.Normals(cgh.Value, r, it, n) :
                bbox = c.GetBoundingBox(false);


                if (length > 0.0001) {
                    lines = new Line[c.Count];
                    for (int i = 0; i < c.Count; i++) {
                        lines[i] = new Line(c[i].Location,c[i].Location+c[i].Normal*length);
                    }
                }


                //this.Message = c.Count.ToString();

                DA.SetData(0, new GH_Cloud(c));
            }catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : CloudPopulateMesh.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                Mesh mesh = new Mesh();
                DA.GetData(0, ref mesh);

                int n = 100;  int type = 0;  
                DA.GetData(1, ref n);
                DA.GetData(2, ref type);


                DA.SetData(0, PInvokeCSharp.TestOpen3D.PopulateMesh(mesh, type,n));


                
            } catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : CloudCreate.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {

                var p = new List<Point3d>();
                var n = new List<Vector3d>();
                var c = new List<System.Drawing.Color>();

                DA.GetDataList(0, p);
                DA.GetDataList(1, n);
                DA.GetDataList(2, c);

                PointCloud cloud = new PointCloud();



                if (p.Count == n.Count && p.Count == c.Count)
                    cloud.AddRange(p, n, c);
                else if (p.Count == n.Count)
                    cloud.AddRange(p, n);
                else if (p.Count == c.Count)
                    cloud.AddRange(p, c);
                else if (p.Count > 0)
                    cloud.AddRange(p);
                else
                    return;

                var cgh = new GH_Cloud(cloud);
                DA.SetData(0, cgh);
            } catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : CloudExplode.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                var cgh = new GH_Cloud();
                DA.GetData(0, ref cgh);

                DA.SetDataList(0, cgh.Value.GetPoints());
                DA.SetDataList(1, cgh.Value.GetNormals());
                DA.SetDataList(2, cgh.Value.GetColors());
            } catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : LoaderIntegrityCheck.cs
with GNU General Public License v3.0
from 9E4ECDDE

private static void PopupMsg()
        {
            try
            {
                if (MessageBox(IntPtr.Zero, "You're using MelonLoader with important security features missing. Do you want to download the official installer?", "Multiplayer Dynamic Bones Mod", 0x04 | 0x40 | 0x1000) == 6)
                {
                    Process.Start("https://github.com/LavaGang/MelonLoader/releases");
                    MessageBox(IntPtr.Zero, "Please close the game, and reinstall MelonLoader using the link on the page that just loaded.", "Multiplayer Dynamic Bones Mod", 0x40 | 0x1000);
                }
            }
            catch (Exception ex) { MelonLogger.Error(ex.ToString()); return; }
        }

19 Source : CloudClusterCilantro.cs
with GNU Lesser General Public License v3.0
from 9and3

protected override void SolveInstance(IGH_DataAccess DA) {

            // Input
            try {
                var cgh = new GH_Cloud();
                DA.GetData(0, ref cgh);

                double voxelSizeSearch = 0.1;
                double normalThresholdDegree = 2.0;
                int minClusterSize = 100;
                bool colorPointCloud = true;
                bool split = false;

                DA.GetData(1, ref voxelSizeSearch);
                DA.GetData(2, ref normalThresholdDegree);
                DA.GetData(3, ref minClusterSize);
                DA.GetData(4, ref colorPointCloud);
                DA.GetData(5, ref split);


                var c =  PInvokeCSharp.TestCilantro.GetClusterConnectedComponentRadius(cgh.Value, voxelSizeSearch, normalThresholdDegree, minClusterSize, colorPointCloud, split);
                //this.Message = c.Count.ToString();

                //GH_Cloud[] clouds = new GH_Cloud[1] { new GH_Cloud(c) };
                GH_Cloud[] clouds = new GH_Cloud[c.Length];
                for (int i = 0; i < c.Length; i++) {
                    clouds[i] = new GH_Cloud(c[i]);
                }

                DA.SetDataList(0, clouds);
            } catch(Exception e) {
                Rhino.RhinoApp.WriteLine(e.ToString());
            }

        }

19 Source : IOServer.cs
with MIT License
from a11s

internal Task<bool> InitServerAsync(ChannelHandlerAdapter handler, IPEndPoint localipep,Action afterchannel)
        {
            iogroup = new MulreplacedhreadEventLoopGroup();
            //workergroup = new MulreplacedhreadEventLoopGroup();
            try
            {
                if (bootstrap != null)
                {
                    throw new InvalidOperationException("重复init");
                }
                bootstrap = new Bootstrap();
                bootstrap.Group(iogroup)
                    .Channel<SocketDatagramChannel>()
                    .Option(ChannelOption.SoBroadcast, true)
                    .Handler(handler);
                var _channel = bootstrap.BindAsync(localipep);
                //channel = _channel.Result;
                _channel.ContinueWith((c) =>
                {
                    var ch = c.Result;
                    this.Channel = ch;
                    if (ch.LocalAddress is IPEndPoint ipep)
                    {
                        IPAddress[] ipaddrs = Dns.GetHostAddresses(Environment.MachineName);
                        foreach (var ipaddr in ipaddrs)
                        {
                            DebugLog(ipaddr.ToString());
                        }
                    }
                    DebugLog($"inited {ch.LocalAddress}");
                    afterchannel.Invoke();
                });
                return Task.FromResult(true);
            }
            catch (System.Threading.ThreadInterruptedException e)
            {
                DebugLog(e.ToString());
                DebugLog("shutdown");
                iogroup.ShutdownGracefullyAsync();
            }
            return Task.FromResult(false);
        }

See More Examples