string.ToUpper()

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

4325 Examples 7

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

protected override Expression VisitMethodCall(MethodCallExpression node)
        {
            _textBuilder.Append(node.Method.Name.ToUpper());
            _textBuilder.Append("(");
            for (var i = 0; i < node.Arguments.Count; i++)
            {
                var item = node.Arguments[i];
                Visit(item);
            }
            if (_textBuilder[_textBuilder.Length - 1] == ',')
            {
                _textBuilder.Remove(_textBuilder.Length - 1, 1);
            }
            _textBuilder.Append(")");
            return node;
        }

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

public string DictSelect(string groupCode, string dictCode) => $"ADMIN:DICT:SELECT:{groupCode.ToUpper()}:{dictCode.ToUpper()}";

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

public string DictTree(string groupCode, string dictCode) => $"ADMIN:DICT:TREE:{groupCode.ToUpper()}:{dictCode.ToUpper()}";

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

public string DictCascader(string groupCode, string dictCode) => $"ADMIN:DICT:CASCADER:{groupCode.ToUpper()}:{dictCode.ToUpper()}";

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

public static string FirstCharToUpper(this string s)
    {
        if (string.IsNullOrEmpty(s))
            return s;

        string str = s.First().ToString().ToUpper() + s.Substring(1);
        return str;
    }

19 Source : HttpParserDelegate.cs
with MIT License
from 1iveowl

public void OnHeaderName(IHttpCombinedParser parser, string name)
        {
            if (RequestResponse.Headers.ContainsKey(name.ToUpper()))
            {
                // Header Field Names are case-insensitive http://www.w3.org/Protocols/rfc2616/rfc2616-sec4.html#sec4.2
                _headerAlreadyExist = false;
            }
            _headerName = name.ToUpper();
        }

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

private string getFileExt(string filename)
        {
            string ext = "";
            if (null != filename && filename.IndexOf(".") != -1)
            {
                ext = filename.Substring(filename.LastIndexOf(".") + 1).ToUpper() + "文件";
            }
            return ext;
        }

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

public bool FindStr()
        {
            bool finds = false;
            string text = text_res.Text;
            info.Text = "";
            if (text != "")
            {
                string content = getContent();
                bool caseDx = cb_case.Checked;
                bool whole = cb_whole.Checked;
                bool regex = cb_regex.Checked;

                if (tempCont != content || text != tempStr)
                {
                    string fmt = null;
                    if (whole)
                    {
                        fmt = "[^\u4e00-\u9fa50-9a-zA-Z]+{0}[^\u4e00-\u9fa50-9a-zA-Z]+";
                    }

                    reg1 = new Regex(fmt == null ? text : string.Format(fmt, text));
                    reg2 = null;
                    if (caseDx)
                    {
                        if (text.ToUpper() != text.ToLower())
                        {
                            reg1 = new Regex(fmt == null ? text.ToUpper() : string.Format(fmt, text.ToUpper()));
                            reg2 = new Regex(fmt == null ? text.ToLower() : string.Format(fmt, text.ToLower()));
                        }
                    }

                    match1 = reg1.Match(content);
                    match2 = null;
                    if (reg2 != null)
                    {
                        match2 = reg2.Match(content);
                    }
                }
                else
                {
                    match1 = reg1.Match(content, match1.Index + match1.Length);
                    if (reg2 != null)
                    {
                        match2 = reg2.Match(content, match2.Index + match2.Length);
                    }
                }


                if (null != match1 && match1.Success) //当查找成功时候
                {
                    tempCont = content;
                    tempStr = text;
                    addFindHisItem(text);
                    finds = true;

                    findCall(text, match1.Index);
                }
                else if (null != match2 && match2.Success) //当查找成功时候
                {
                    tempCont = content;
                    tempStr = text;
                    addFindHisItem(text);
                    finds = true;

                    findCall(text, match2.Index);
                }
                else
                {
                    info.Text = "没有找到结果";
                }
            }
            return finds;
        }

19 Source : Resp3HelperTests.cs
with MIT License
from 2881099

[Fact]
		public void Command()
		{
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = rds.Command();
			var sb = string.Join("\r\n\r\n", (rt.Value).OrderBy(a1 => (a1 as List<object>)[0].ToString()).Select(a1 =>
			{
				var a = a1 as List<object>;
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());
				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += "string parm, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += "string parm, ";
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}
				
				return $@"
//{string.Join(", ", a[2] as List<object>)}
//{string.Join(", ", a[6] as List<object>)}
public void {UFString(a[0].ToString())}({parms}) {{ }}";
			}));
		}

19 Source : ConnectionStringBuilder.cs
with MIT License
from 2881099

public static ConnectionStringBuilder Parse(string connectionString)
        {
            var ret = new ConnectionStringBuilder();
            if (string.IsNullOrEmpty(connectionString)) return ret;

            //支持密码中带有逗号,将原有 split(',') 改成以下处理方式
            var vs = Regex.Split(connectionString, @"\,([\w \t\r\n]+)=", RegexOptions.Multiline);
            ret.Host = vs[0].Trim();

            for (var a = 1; a < vs.Length; a += 2)
            {
                var kv = new[] { Regex.Replace(vs[a].ToLower().Trim(), @"[ \t\r\n]", ""), vs[a + 1] };
                switch (kv[0])
                {
                    case "ssl": if (kv.Length > 1 && kv[1].ToLower().Trim() == "true") ret.Ssl = true; break;
                    case "protocol": if (kv.Length > 1 && kv[1].ToUpper().Trim() == "RESP3") ret.Protocol = RedisProtocol.RESP3; break;
                    case "userid":
                    case "user": if (kv.Length > 1) ret.User = kv[1].Trim(); break;
                    case "preplacedword": if (kv.Length > 1) ret.Preplacedword = kv[1]; break;
                    case "database":
                    case "defaultdatabase": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var database) && database > 0) ret.Database = database; break;

                    case "prefix": if (kv.Length > 1) ret.Prefix = kv[1].Trim(); break;
                    case "name":
                    case "clientname": if (kv.Length > 1) ret.ClientName = kv[1].Trim(); break;
                    case "encoding": if (kv.Length > 1) ret.Encoding = Encoding.GetEncoding(kv[1].Trim()); break;

                    case "idletimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var idleTimeout) && idleTimeout > 0) ret.IdleTimeout = TimeSpan.FromMilliseconds(idleTimeout); break;
                    case "connecttimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var connectTimeout) && connectTimeout > 0) ret.ConnectTimeout = TimeSpan.FromMilliseconds(connectTimeout); break;
                    case "receivetimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var receiveTimeout) && receiveTimeout > 0) ret.ReceiveTimeout = TimeSpan.FromMilliseconds(receiveTimeout); break;
                    case "sendtimeout": if (kv.Length > 1 && long.TryParse(kv[1].Trim(), out var sendTimeout) && sendTimeout > 0) ret.SendTimeout = TimeSpan.FromMilliseconds(sendTimeout); break;

                    case "poolsize":
                    case "maxpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var maxPoolSize) && maxPoolSize > 0) ret.MaxPoolSize = maxPoolSize; break;
                    case "minpoolsize": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var minPoolSize) && minPoolSize > 0) ret.MinPoolSize = minPoolSize; break;
                    case "retry": if (kv.Length > 1 && int.TryParse(kv[1].Trim(), out var retry) && retry > 0) ret.Retry = retry; break;
                }
            }
            return ret;
        }

19 Source : RazorModel.cs
with MIT License
from 2881099

public string GetMySqlEnumSetDefine() {
		if (fsql.Ado.DataType != FreeSql.DataType.MySql) return null;
		var sb = new StringBuilder();
		foreach (var col in table.Columns) {
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) {
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
				sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
				sb.Append(" {\r\n\t\t");

				string slkdgjlksdjg = "";
				int field_idx = 0;
				int unknow_idx = 0;
				string exp2 = string.Concat(col.DbTypeTextFull);
				int quote_pos = -1;
				while (true) {
					int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
					if (quote_pos == -1) break;
					while (true) {
						quote_pos = exp2.IndexOf('\'', quote_pos + 1);
						if (quote_pos == -1) break;
						int r_cout = 0;
						//for (int p = 1; true; p++) {
						//	if (exp2[quote_pos - p] == '\\') r_cout++;
						//	else break;
						//}
						while (exp2[++quote_pos] == '\'') r_cout++;
						if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/) {
							string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
							if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
								slkdgjlksdjg += ", " + str2;
							else
								slkdgjlksdjg += string.Format(@", 
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
								slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
								slkdgjlksdjg += " = 1";
							break;
						}
					}
					if (quote_pos == -1) break;
				}
				sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
				sb.Append("\r\n\t}");
			}
		}
		return sb.ToString();
	}

19 Source : RazorModel.cs
with MIT License
from 2881099

public string UFString(string text)
	{
		text = Regex.Replace(text, @"[^\w]", "_");
		if (text.Length <= 1) return text.ToUpper();
		else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
	}

19 Source : RazorModel.cs
with MIT License
from 2881099

public string GetMySqlEnumSetDefine()
	{
		if (fsql.Ado.DataType != FreeSql.DataType.MySql && fsql.Ado.DataType != FreeSql.DataType.OdbcMySql) return null;
		var sb = new StringBuilder();
		foreach (var col in table.Columns)
		{
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
			{
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append("\r\n\t[Flags]");
				sb.Append($"\r\n\tpublic enum {this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}");
				if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set) sb.Append(" : long");
				sb.Append(" {\r\n\t\t");

				string slkdgjlksdjg = "";
				int field_idx = 0;
				int unknow_idx = 0;
				string exp2 = string.Concat(col.DbTypeTextFull);
				int quote_pos = -1;
				while (true)
				{
					int first_pos = quote_pos = exp2.IndexOf('\'', quote_pos + 1);
					if (quote_pos == -1) break;
					while (true)
					{
						quote_pos = exp2.IndexOf('\'', quote_pos + 1);
						if (quote_pos == -1) break;
						int r_cout = 0;
						//for (int p = 1; true; p++) {
						//	if (exp2[quote_pos - p] == '\\') r_cout++;
						//	else break;
						//}
						while (exp2[++quote_pos] == '\'') r_cout++;
						if (r_cout % 2 == 0/* && quote_pos - first_pos > 2*/)
						{
							string str2 = exp2.Substring(first_pos + 1, quote_pos - first_pos - 2).Replace("''", "'");
							if (Regex.IsMatch(str2, @"^[\u0391-\uFFE5a-zA-Z_\$][\u0391-\uFFE5a-zA-Z_\$\d]*$"))
								slkdgjlksdjg += ", " + str2;
							else
								slkdgjlksdjg += string.Format(@", 
/// <summary>
/// {0}
/// </summary>
[Description(""{0}"")]
Unknow{1}", str2.Replace("\"", "\\\""), ++unknow_idx);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
								slkdgjlksdjg += " = " + Math.Pow(2, field_idx++);
							if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum && field_idx++ == 0)
								slkdgjlksdjg += " = 1";
							break;
						}
					}
					if (quote_pos == -1) break;
				}
				sb.Append(slkdgjlksdjg.Substring(2).TrimStart('\r', '\n', '\t'));
				sb.Append("\r\n\t}");
			}
		}
		return sb.ToString();
	}

19 Source : RazorModel.cs
with MIT License
from 2881099

public string GetCsType(DbColumnInfo col)
	{
		if (fsql.Ado.DataType == FreeSql.DataType.MySql)
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
				return $"{this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}{(col.IsNullable ? "?" : "")}";
		return fsql.DbFirst.GetCsType(col);
	}

19 Source : CommandFlagsTests.cs
with MIT License
from 2881099

[Fact]
        public void Command()
        {
			string UFString(string text)
			{
				if (text.Length <= 1) return text.ToUpper();
				else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
			}

			var rt = cli.Command();
			//var rt = cli.CommandInfo("mset", "mget", "set", "get", "rename");
			var flags = new List<string>();
			var flags7 = new List<string>();
			var diccmd = new Dictionary<string, (string[], string[])>();

			var sb = string.Join("\r\n\r\n", (rt).OrderBy(a1 => (a1 as object[])[0].ToString()).Select(a1 =>
			{
				var a = a1 as object[];
				var cmd = a[0].ToString();
				var plen = int.Parse(a[1].ToString());
				var firstKey = int.Parse(a[3].ToString());
				var lastKey = int.Parse(a[4].ToString());
				var stepCount = int.Parse(a[5].ToString());

				var aflags = (a[2] as object[]).Select(a => a.ToString()).ToArray();
				var fopts = (a[6] as object[]).Select(a => a.ToString()).ToArray();
				flags.AddRange(aflags);
				flags7.AddRange(fopts);

				diccmd.Add(cmd.ToUpper(), (aflags, fopts));

				var parms = "";
				if (plen > 1)
				{
					for (var x = 1; x < plen; x++)
					{
						if (x == firstKey) parms += "string key, ";
						else parms += $"string arg{x}, ";
					}
					parms = parms.Remove(parms.Length - 2);
				}
				if (plen < 0)
				{
					for (var x = 1; x < -plen; x++)
					{
						if (x == firstKey)
						{
							if (firstKey != lastKey) parms += "string[] keys, ";
							else parms += "string key, ";
						}
						else
						{
							if (firstKey != lastKey) parms += $"string[] arg{x}, ";
							else parms += $"string arg{x}, ";
						}
					}
					if (parms.Length > 0)
						parms = parms.Remove(parms.Length - 2);
				}

				return $@"
//{string.Join(", ", a[2] as object[])}
//{string.Join(", ", a[6] as object[])}
public void {UFString(cmd)}({parms}) {{ }}";
			}));
			flags = flags.Distinct().ToList();
			flags7 = flags7.Distinct().ToList();


			var sboptions = new StringBuilder();
            foreach (var cmd in CommandSets._allCommands)
            {
                if (diccmd.TryGetValue(cmd, out var tryv))
                {
                    sboptions.Append($@"
[""{cmd}""] = new CommandSets(");

                    for (var x = 0; x < tryv.Item1.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerFlag.{tryv.Item1[x].Replace("readonly", "@readonly")}");
                    }

                    sboptions.Append(", ");
                    for (var x = 0; x < tryv.Item2.Length; x++)
                    {
                        if (x > 0) sboptions.Append(" | ");
                        sboptions.Append($"ServerTag.{tryv.Item2[x].TrimStart('@').Replace("string", "@string")}");
                    }

                    sboptions.Append(", LocalStatus.none),");
                }
                else
                {
                    sboptions.Append($@"
[""{cmd}""] = new CommandSets(ServerFlag.none, ServerTag.none, LocalStatus.none), ");
                }
            }

            var optioncode = sboptions.ToString();
		}

19 Source : RazorModel.cs
with MIT License
from 2881099

public string UFString(string text) {
		text = Regex.Replace(text, @"[^\w]", "_");
		if (text.Length <= 1) return text.ToUpper();
		else return text.Substring(0, 1).ToUpper() + text.Substring(1, text.Length - 1);
	}

19 Source : RazorModel.cs
with MIT License
from 2881099

public string GetCsType(DbColumnInfo col) {
		if (fsql.Ado.DataType == FreeSql.DataType.MySql)
			if (col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Enum || col.DbType == (int)MySql.Data.MySqlClient.MySqlDbType.Set)
				return $"{this.GetCsName(this.FullTableName)}{this.GetCsName(col.Name).ToUpper()}{(col.IsNullable ? "?" : "")}";
		return fsql.DbFirst.GetCsType(col);
	}

19 Source : Program.cs
with GNU Affero General Public License v3.0
from 3CORESec

public static void Main(string[] args)
        {

            int ruleCount = 0;
            int gradientMax = 0;
            Parser.Default.ParseArguments<Options>(args)
                .WithParsed(o =>
                {
                    LoadConfig(o);
                    if (!o.Suricata)
                    {
                        LoadMismatchSearchMatrix(o);
                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.yml", SearchOption.AllDirectories))
                        {
                            try
                            {
                                var dict = DeserializeYamlFile(ruleFilePath, o);
                                if (dict != null && dict.ContainsKey("tags"))
                                {
                                    ruleCount++;
                                    var tags = dict["tags"];
                                    var categories = new List<string>();
                                    string lastEntry = null;
                                    foreach (string tag in tags)
                                    {
                                        //If its the technique id entry, then this adds the file name to the techniques map
                                        if (tag.ToLower().StartsWith("attack.t"))
                                        {
                                            var techniqueId = tag.Replace("attack.", "").ToUpper();
                                            if (!techniques.ContainsKey(techniqueId))
                                                techniques[techniqueId] = new List<string>();
                                            techniques[techniqueId].Add(ruleFilePath.Split("\\").Last());
                                            if (techniques.Count > gradientMax)
                                                gradientMax = techniques.Count;
                                            //then if there are any categories so far, it checks for a mismatch for each one
                                            if (categories.Count > 0 && o.Warning)
                                            {
                                                foreach (string category in categories)
                                                    if (!(mismatchSearchMatrix.ContainsKey(techniqueId) && mismatchSearchMatrix[techniqueId].Contains(category)))
                                                        mismatchWarnings.Add($"MITRE ATT&CK technique ({techniqueId}) and tactic ({category}) mismatch in rule: {ruleFilePath.Split("\\").Last()}");
                                            }
                                        }
                                        else
                                        {
                                            //if its the start of a new technique block, then clean categories and adds first category
                                            if (lastEntry == null || lastEntry.StartsWith("attack.t"))
                                                categories = new List<string>();
                                            categories.Add(
                                                tag.Replace("attack.", "")
                                                .Replace("_", "-")
                                                .ToLower());
                                        }
                                        lastEntry = tag;
                                    }
                                }
                            }
                            catch (YamlException e)
                            {
                                Console.Error.WriteLine($"Ignoring rule {ruleFilePath} (parsing failed)");
                            }
                        }

                        WriteSigmaFileResult(o, gradientMax, ruleCount, techniques);
                        PrintWarnings();
                    }
                    else
                    {

                        List<Dictionary<string, List<string>>> res = new List<Dictionary<string, List<string>>>();

                        foreach (var ruleFilePath in Directory.EnumerateFiles(o.RulesDirectory, "*.rules", SearchOption.AllDirectories))
                        {
                            res.Add(ParseRuleFile(ruleFilePath));
                        }

                        WriteSuricataFileResult(o,
                            res
                                .SelectMany(dict => dict)
                                .ToLookup(pair => pair.Key, pair => pair.Value)
                                .ToDictionary(group => group.Key,
                                              group => group.SelectMany(list => list).ToList()));
                    }

                });
        }

19 Source : StringExtension.cs
with MIT License
from 3F

public static string SlnFormat(this Guid guid)
        {
            return guid.ToString("B").ToUpper();
        }

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

public static void Parse(IEnumerable<string> file)
		{
			int i = 0;

			var sw = System.Diagnostics.Stopwatch.StartNew();

			foreach (string linei in file)
			{
				i++;
				string line = CleanupLine(linei, i);

				if (string.IsNullOrWhiteSpace(line))
					continue;

				Parse(line.ToUpper(), i);
			}

			sw.Stop();

            MainWindow.Logger.Info("parsing the G code file took {0} ms", sw.ElapsedMilliseconds);
		}

19 Source : NTLM.cs
with BSD 3-Clause "New" or "Revised" License
from 3gstudent

private static byte[] nTOWFv2(string domain, string username, string preplacedword)
        {
            byte[] byteArray = null;

            if (Options.hash.Length > 0)
                byteArray = ConvertHexStringToBytes(Options.hash);
            else
                byteArray = nTOWFv1(preplacedword);
            HMACT64 hmact = new HMACT64(byteArray);
            hmact.update(Encoding.Unicode.GetBytes(username.ToUpper()));
            hmact.update(Encoding.Unicode.GetBytes(domain));

            return hmact.digest();
        }

19 Source : Person.cs
with Apache License 2.0
from 42skillz

public string ToStringShortVersion()
        {
            var marriageStatus = IsMarried ? "married - " : string.Empty;
            var status = $"({marriageStatus}age: {Age} years)";

            return $"{replacedle}. {FirstName} {LastName.ToUpper()} ({Gender}) {EMail} {status}";
        }

19 Source : StringExtensions.cs
with Apache License 2.0
from 42skillz

public static string FirstCharToUpper(this string word)
        {
            switch (word)
            {
                case null:
                    throw new ArgumentNullException(nameof(word));
                case "":
                    throw new ArgumentException($"{nameof(word)} cannot be empty", nameof(word));
                default:
                    return word.First().ToString().ToUpper() + word.Substring(1);
            }
        }

19 Source : Util.cs
with MIT License
from 499116344

public static string NumToHexString(long qq, int length = 8)
        {
            var text = Convert.ToString(qq, 16);
            if (text.Length == length)
            {
                return text;
            }

            if (text.Length > length)
            {
                return null;
            }

            var num = length - text.Length;
            var str = "";
            for (var i = 0; i < num; i++)
            {
                str += "0";
            }

            text = (str + text).ToUpper();
            var stringBuilder = new StringBuilder();
            for (var j = 0; j < text.Length; j++)
            {
                stringBuilder.Append(text[j]);
                if ((j + 1) % 2 == 0)
                {
                    stringBuilder.Append(" ");
                }
            }

            return stringBuilder.ToString();
        }

19 Source : UserCommandHandler.cs
with GNU Lesser General Public License v3.0
from 8720826

private string GenerateRandom(int Length)
        {
            char[] constant =
            {
            'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'
            };

            StringBuilder newRandom = new StringBuilder(constant.Length);
            Random rd = new Random();
            for (int i = 0; i < Length; i++)
            {
                newRandom.Append(constant[rd.Next(constant.Length)]);
            }
            return newRandom.ToString().ToUpper();
        }

19 Source : CaptchaUtil.cs
with Apache License 2.0
from 91270

public static CaptchaResult GenerateCaptchaImage(string captchaCode, int width = 0, int height = 30)
        {
            //验证码颜色集合
            Color[] c = { Color.Black, Color.Red, Color.DarkBlue, Color.Green, Color.Orange, Color.Brown, Color.DarkCyan, Color.Purple };

            //验证码字体集合
            string[] fonts = { "Verdana", "Microsoft Sans Serif", "Comic Sans MS", "Arial" };

            //定义图像的大小,生成图像的实例
            var image = new Bitmap(width == 0 ? captchaCode.Length * 25 : width, height);

            var g = Graphics.FromImage(image);

            //背景设为白色
            g.Clear(Color.White);

            var random = new Random();

            for (var i = 0; i < 100; i++)
            {
                var x = random.Next(image.Width);
                var y = random.Next(image.Height);
                g.DrawRectangle(new Pen(Color.LightGray, 0), x, y, 1, 1);
            }

            //验证码绘制在g中  
            for (var i = 0; i < captchaCode.Length; i++)
            {
                //随机颜色索引值 
                var cindex = random.Next(c.Length);

                //随机字体索引值 
                var findex = random.Next(fonts.Length);

                //字体 
                var f = new Font(fonts[findex], 15, FontStyle.Bold);

                //颜色  
                Brush b = new SolidBrush(c[cindex]);

                var ii = 4;
                if ((i + 1) % 2 == 0)
                    ii = 2;

                //绘制一个验证字符  
                g.DrawString(captchaCode.Substring(i, 1), f, b, 17 + (i * 17), ii);
            }

            var ms = new MemoryStream();
            image.Save(ms, ImageFormat.Png);

            g.Dispose();
            image.Dispose();

            return new CaptchaResult { CaptchaGUID = Guid.NewGuid().ToString().ToUpper(),  CaptchaCode = captchaCode, CaptchaMemoryStream = ms, Timestamp = DateTime.Now };
        }

19 Source : PasswordUtil.cs
with Apache License 2.0
from 91270

private static string CreateMD5(string pwd)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            string t2 = BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(pwd)));
            t2 = t2.Replace("-", "");
            t2 = t2.ToUpper();
            return t2;
        }

19 Source : EntityExtension.cs
with Apache License 2.0
from 91270

public static TSource ToCreate<TSource>(this TSource source, UserSessionVM userSession)
        {
            var types = source.GetType();

            if (types.GetProperty("ID") != null)
            {
                types.GetProperty("ID").SetValue(source, Guid.NewGuid().ToString().ToUpper(), null);
            }

            if (types.GetProperty("CreateTime") != null)
            {
                types.GetProperty("CreateTime").SetValue(source, DateTime.Now, null);
            }

            if (types.GetProperty("UpdateTime") != null)
            {
                types.GetProperty("UpdateTime").SetValue(source, DateTime.Now, null);
            }

            if (types.GetProperty("CreateID") != null)
            {
                types.GetProperty("CreateID").SetValue(source, userSession.UserID, null);

                types.GetProperty("CreateName").SetValue(source, userSession.UserName, null);
            }

            if (types.GetProperty("UpdateID") != null)
            {
                types.GetProperty("UpdateID").SetValue(source, userSession.UserID, null);

                types.GetProperty("UpdateName").SetValue(source, userSession.UserName, null);
            }


            return source;
        }

19 Source : TokenManager.cs
with Apache License 2.0
from 91270

public string CreateSession(Sys_Users userInfo, SourceType source, int hours)
        {
            var userSession = Guid.NewGuid().ToString().ToUpper();

            //判断用户是否只允许等于一次
            if (userInfo.OneSession)
            {
                RemoveAllSession(userInfo.UserID);
            }

            var expireTime = DateTime.Now.AddHours(hours);
            var timeSpan = new TimeSpan(hours, 0, 0);

            //将 Session 添加用户 Session 列表
            RedisServer.Session.HSet(userInfo.UserID, userSession, expireTime);
            RedisServer.Session.Expire(userInfo.UserID, timeSpan);

            //设置 Session 信息
            var userSessionVM = new UserSessionVM()
            {
                UserID = userInfo.UserID,
                UserName = userInfo.UserName,
                NickName = userInfo.NickName,
                Email = userInfo.Email,
                Sex = userInfo.Sex,
                AvatarUrl = userInfo.AvatarUrl,
                QQ = userInfo.QQ,
                Phone = userInfo.Phone,
                ProvinceID = userInfo.ProvinceID,
                Province = userInfo.Province,
                CityID = userInfo.CityID,
                City = userInfo.City,
                CountyID = userInfo.CountyID,
                County = userInfo.County,
                Address = userInfo.Address,
                Remark = userInfo.Remark,
                IdenreplacedyCard = userInfo.IdenreplacedyCard,
                Birthday = userInfo.Birthday,
                CreateTime = userInfo.CreateTime,
                Enabled = userInfo.Enabled,
                OneSession = userInfo.OneSession,
                Source = source.ToString(),
                KeepHours = hours,
                Administrator = userInfo.Administrator,
                UserPower = _usersService.GetUserPowers(userInfo.UserID),
                UserRelation = _usersService.GetUserRelation(userInfo.UserID),
            };

            RedisServer.Session.HSet(userSession, "UserInfo", userSessionVM);
            RedisServer.Session.Expire(userSession, timeSpan);

            //添加在线记录表
            _onlineService.Add(new Sys_Online()
            {
                SessionID = userSession,
                UserID = userInfo.UserID,
                Source = source.ToString(),
                IPAddress = _accessor.HttpContext.Connection.RemoteIpAddress?.MapToIPv4().ToString(),
                LoginTime = DateTime.Now,
                UpdateTime = DateTime.Now
            });

            _usersService.Update(m => m.UserID == userInfo.UserID, m => new Sys_Users { LastLoginTime = DateTime.Now });

            return userSession;
        }

19 Source : LzmaEncoder.cs
with MIT License
from 91Act

public void SetCoderProperties(CoderPropID[] propIDs, object[] properties)
		{
			for (UInt32 i = 0; i < properties.Length; i++)
			{
				object prop = properties[i];
				switch (propIDs[i])
				{
					case CoderPropID.NumFastBytes:
					{
						if (!(prop is Int32))
							throw new InvalidParamException();
						Int32 numFastBytes = (Int32)prop;
						if (numFastBytes < 5 || numFastBytes > Base.kMatchMaxLen)
							throw new InvalidParamException();
						_numFastBytes = (UInt32)numFastBytes;
						break;
					}
					case CoderPropID.Algorithm:
					{
						/*
						if (!(prop is Int32))
							throw new InvalidParamException();
						Int32 maximize = (Int32)prop;
						_fastMode = (maximize == 0);
						_maxMode = (maximize >= 2);
						*/
						break;
					}
					case CoderPropID.MatchFinder:
					{
						if (!(prop is String))
							throw new InvalidParamException();
						EMatchFinderType matchFinderIndexPrev = _matchFinderType;
						int m = FindMatchFinder(((string)prop).ToUpper());
						if (m < 0)
							throw new InvalidParamException();
						_matchFinderType = (EMatchFinderType)m;
						if (_matchFinder != null && matchFinderIndexPrev != _matchFinderType)
							{
							_dictionarySizePrev = 0xFFFFFFFF;
							_matchFinder = null;
							}
						break;
					}
					case CoderPropID.DictionarySize:
					{
						const int kDicLogSizeMaxCompress = 30;
						if (!(prop is Int32))
							throw new InvalidParamException(); ;
						Int32 dictionarySize = (Int32)prop;
						if (dictionarySize < (UInt32)(1 << Base.kDicLogSizeMin) ||
							dictionarySize > (UInt32)(1 << kDicLogSizeMaxCompress))
							throw new InvalidParamException();
						_dictionarySize = (UInt32)dictionarySize;
						int dicLogSize;
						for (dicLogSize = 0; dicLogSize < (UInt32)kDicLogSizeMaxCompress; dicLogSize++)
							if (dictionarySize <= ((UInt32)(1) << dicLogSize))
								break;
						_distTableSize = (UInt32)dicLogSize * 2;
						break;
					}
					case CoderPropID.PosStateBits:
					{
						if (!(prop is Int32))
							throw new InvalidParamException();
						Int32 v = (Int32)prop;
						if (v < 0 || v > (UInt32)Base.kNumPosStatesBitsEncodingMax)
							throw new InvalidParamException();
						_posStateBits = (int)v;
						_posStateMask = (((UInt32)1) << (int)_posStateBits) - 1;
						break;
					}
					case CoderPropID.LitPosBits:
					{
						if (!(prop is Int32))
							throw new InvalidParamException();
						Int32 v = (Int32)prop;
						if (v < 0 || v > (UInt32)Base.kNumLitPosStatesBitsEncodingMax)
							throw new InvalidParamException();
						_numLiteralPosStateBits = (int)v;
						break;
					}
					case CoderPropID.LitContextBits:
					{
						if (!(prop is Int32))
							throw new InvalidParamException();
						Int32 v = (Int32)prop;
						if (v < 0 || v > (UInt32)Base.kNumLitContextBitsMax)
							throw new InvalidParamException(); ;
						_numLiteralContextBits = (int)v;
						break;
					}
					case CoderPropID.EndMarker:
					{
						if (!(prop is Boolean))
							throw new InvalidParamException();
						SetWriteEndMarkerMode((Boolean)prop);
						break;
					}
					default:
						throw new InvalidParamException();
				}
			}
		}

19 Source : MD5Encode.cs
with Apache License 2.0
from 91270

public static string MD5Encrypt(string pwd)
        {
            MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider();
            return BitConverter.ToString(md5.ComputeHash(Encoding.Default.GetBytes(pwd))).Replace("-", "").ToUpper();
        }

19 Source : ZUART.cs
with MIT License
from a2633063

public void AddData(byte[] data)
        {
            if (rbtnHex.Checked)
            {
                StringBuilder sb = new StringBuilder();
                for (int i = 0; i < data.Length; i++)
                {
                    sb.AppendFormat("{0:x2}" + " ", data[i]);
                }
                AddContent(sb.ToString().ToUpper());
            }
            else if (rbtnUTF8.Checked)
            {
                AddContent(new UTF8Encoding().GetString(data));
            }
            else if (rbtnUnicode.Checked)
            {
                AddContent(new UnicodeEncoding().GetString(data));
            }
            else// if (rbtnASCII.Checked)
            {
                //AddContent(new ASCIIEncoding().GetString(data));
                AddContent(Encoding.GetEncoding("GBK").GetString(data));
            }

            lblRevCount.Invoke(new MethodInvoker(delegate
            {
                lblRevCount.Text = "接收:" + (int.Parse(lblRevCount.Text.Substring(3)) + data.Length).ToString();
            }));
        }

19 Source : SelectFm.cs
with GNU General Public License v3.0
from a4004

private async Task ListSoftwareOptions(string option)
        {
            string[] availableFiles = API.GithubManager.GetReleaseNames("spacehuhntech/esp8266_deauther", option);

            if (availableFiles == null || availableFiles.Length < 1)
            {
                MessageBox.Show("The version you selected does not have any precompiled binaries available for it, to use this version you will" +
                    " need to build the software from source and flash it as a local image from this PC.", "No Files Available", MessageBoxButtons.OK,
                    MessageBoxIcon.Warning);
                return;
            }

            foreach (string file in availableFiles)
            {
                try
                {
                    string type = Path.GetExtension(file).Replace(".", "").ToUpper();

                    Invoke(new Action(() =>
                    {
                        listView.Items.Add(new ListViewItem(new string[] { "SpacehuhnTech", Path.GetFileNameWithoutExtension(file), type}));
                    }));                
                }
                catch (Exception e)
                {
                    Program.Debug("selectfm", $"Failed to parse filename: {file}, error: {e.Message}", Event.Critical);
                    await Task.Delay(100);
                }
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from a4004

private async void Flash()
        {
            await Task.Delay(1000);
FileMode:
            CreateRequest("Device software installation", "You are installing software on your device, you can choose where to get it from.", 
                "Get the latest image from the Internet (Recommended)", "Use a local image on this PC", out int option);

            if (option == 2)
            {
                Invoke(new Action(() =>
                {
                    OpenFileDialog fileDialog = new OpenFileDialog()
                    {
                        Multiselect = false,
                        SupportMultiDottedExtensions = true,
                        Filter = "Binary files (*.bin)|*.bin|Hex files (*.hex)|*.hex|All files (*.*)|*.*",
                        replacedle = "Choose a software image file",
                    };

                    if (fileDialog.ShowDialog() == DialogResult.OK)
                        Program.Settings.Bin = fileDialog.FileName;
                }));

                if (Program.Settings.Bin == default)
                    goto FileMode;
            }
            else if (option == 1)
            {
                if (!CreateSelRequest(out string file))
                    goto FileMode;
                else
                {
                    WaitFm.Debug($"User selected file: {file}");

                    WaitFm.replacedle("Downloading software");
                    WaitFm.Caption("");

                    WaitFm.Debug($"Downloading {file}...");

                    try
                    {
                        WebClient client = new WebClient();

                        client.DownloadProgressChanged += (s, e) =>
                        {
                            WaitFm.Caption($"Downloading {Path.GetFileName(file)} from github.com ({e.ProgressPercentage}%)");
                        };
                        client.DownloadFileCompleted += delegate
                        {
                            WaitFm.Debug($"Successfully downloaded {Path.GetFileName(file)} from github.com", Event.Success);
                        };

                        await client.DownloadFileTaskAsync(file, Path.GetFileName(file));
                        Program.Settings.Bin = Path.GetFileName(file);
                    }
                    catch (Exception ex)
                    {
                        WaitFm.Debug($"Download failed due to an error: {ex.Message}", Event.Critical);
                        await CreateMessage("A problem was encountered", "The required file could not be downloaded. You can try again.");

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();
                        return;
                    }          
                }

                WaitFm.replacedle("Getting ready");
                await Task.Delay(1000);
            }
            else
                throw new Exception($"The selection could not be determined due to an invalid value. {option}");

            CreateRequest("Flash Operation", "The program is about to install software to your Espressif device. " +
                    "Existing data on the device will be PERMANENTLY DELETED, are you sure?", "Allow software installation",
                    "Cancel flash operation, no changes will be made", out int result);

            if (result == 2)
            {
                WaitFm.Debug("User cancelled the flash operation.", Event.Critical);
                await CreateMessage("Software installation aborted", "You've chosen to cancel the installation " +
                    "of software to your Espressif device. No changes have been made. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else if (result == 1)
            {
                WaitFm.Debug("Flash operation started.");
                WaitFm.replacedle("Installing software");

                WaitFm.Caption("Checking device connection");
                WaitFm.Debug("Checking device connection...");

                if (!Program.Settings.PortFix)
                    WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");

                string output = string.Empty;

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);

                        WaitFm.Caption("Connection was successful");
                    }
                    else
                        throw new Exception("Could not connect to the device.");
                }

                WaitFm.Caption("Erasing flash memory");
                WaitFm.Debug("Erasing flash memory chip...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} erase_flash"))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to erase the device.");
                }

                WaitFm.Caption("Writing new software image");
                WaitFm.Debug("Writing new software image...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Flash complete!", Event.Success);
                        WaitFm.Caption("Installed.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }
                else
                {
                    if (ShellManager.RunCommand(out output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} write_flash 0x0 \"{Program.Settings.Bin}\""))
                    {
                        WaitFm.Debug("Erase successful!", Event.Success);
                        WaitFm.Caption("Erased.");
                    }
                    else
                        throw new Exception("Failed to flash the device.");
                }


                await Task.Delay(500);

                await CreateMessage("Installation complete", $"The software package {Program.Settings.Bin} has been successfully" +
                    $" installed on your device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
            else
            {
                WaitFm.Debug("Failsafe: the selection was invalid.", Event.Critical);
                await CreateMessage("Software installation aborted", "A problem was encountered with the selection. " +
                    "No changes have been made to your Espressif device. You can close this window.");

                WaitFm.Host.CloseTask();
                WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                TaskManager.ReleaseFLock();

                return;
            }
        }

19 Source : MainWindow.cs
with GNU General Public License v3.0
from a4004

private async void Search()
        {
            await Task.Delay(1000);

            WaitFm.Debug("Searching for devices...");

            int threshold = 1;
Rescan:
            while (SerialBusManager.SerialPorts.Count() < threshold)
            {
                await Task.Delay(1000);
                WaitFm.Debug($"Searching for devices... {(threshold - 1 == 1 ? "[1 device is connected, but you've chosen to not use it]" : (threshold - 1 > 1 ? $"[{threshold - 1} devices are connected, but you've chosen not to use them]" : ""))}");
            }

            WaitFm.Debug($"Detected {SerialBusManager.SerialDevices[threshold - 1]} on {SerialBusManager.SerialPorts[threshold - 1]}");

            CreateRequest($"Found new device ({SerialBusManager.SerialPorts[threshold - 1]})",
                SerialBusManager.SerialDevices[threshold - 1], "Use this device", "Don't use this device", out int option);

            if (option == 2)
            {
                threshold++;
                WaitFm.Debug($"The device was rejected by the user, device threshold is now {threshold} (was {threshold - 1})", Event.Warning);
                goto Rescan;
            }
            else if (option == 1)
            {
                Program.Settings.SelectedPort = SerialBusManager.SerialPorts[threshold - 1];
                Program.Settings.SelectedName = SerialBusManager.SerialDevices[threshold - 1];

                WaitFm.replacedle("Connecting to your device");

                if (!Program.Settings.PortFix)
                    WaitFm.Caption($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}");
                if (!Program.Settings.PortFix)
                    WaitFm.Debug($"Connecting to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}...");

                if (!Program.Portable)
                {
                    if (ShellManager.RunCommand(out string output, "py", $"-m esptool {(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);

                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
                        WaitFm.Caption("The device is working correctly");
                        WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
                        await Task.Delay(1000);

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();

                        Invoke(new Action(() =>
                        {
                            CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
                        }));
                    }
                    else
                    {
                        WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);

                        if (SerialBusManager.SerialPorts.Count() > threshold)
                        {
                            await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
                            threshold++;
                            goto Rescan;
                        }
                        else
                        {
                            await CreateMessage("There was a problem", "A connection to the device could not be established.");
                            WaitFm.Host.CloseTask();
                            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                            TaskManager.ReleaseFLock();
                            return;
                        }
                    }
                }
                else
                {
                    if (ShellManager.RunCommand(out string output, Program.Settings.EsptoolExe, $"{(!Program.Settings.PortFix ? $"--port {Program.Settings.SelectedPort}" : "")} read_mac"))
                    {
                        if (!Program.Settings.PortFix)
                            WaitFm.Debug($"Connected to {Program.Settings.SelectedName} on {Program.Settings.SelectedPort}", Event.Success);
                        WaitFm.Debug($"Espressif device MAC: {output.Substring(output.IndexOf("MAC:") + 5, 17).ToUpper()}", Event.Success);
                        WaitFm.Caption("The device is working correctly");
                        WaitFm.replacedle($"Connected to {Program.Settings.SelectedName}");
                        await Task.Delay(1000);

                        WaitFm.Host.CloseTask();
                        WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                        TaskManager.ReleaseFLock();

                        Invoke(new Action(() =>
                        {
                            CreateForegroundTask("flasher", new Task(Flash), "Getting ready", "");
                        }));
                    }
                    else
                    {
                        WaitFm.Debug($"Failed to obtain the device MAC, the esptool didn't connect. {output}", Event.Critical);

                        if (SerialBusManager.SerialPorts.Count() > threshold)
                        {
                            await CreateMessage("Couldn't connect", "A connection to the device could not be established. You have multiple devices connected, it might be the next one.", 5);
                            threshold++;
                            goto Rescan;
                        }
                        else
                        {
                            await CreateMessage("There was a problem", "A connection to the device could not be established.");
                            WaitFm.Host.CloseTask();
                            WindowManager.UnmountWindow(Controls, TaskManager.ForegroundWindow);
                            TaskManager.ReleaseFLock();
                            return;
                        }
                    }
                }

                
            }
            else
                throw new Exception($"The selection could not be determined due to an invalid value. {option}");
        }

19 Source : DateAndSizeRollingFileAppender.cs
with MIT License
from Abc-Arbitrage

private int FindLastRollingFileNumber(string directory)
        {
            var fileNumber = 0;
            var root = FilenameRoot + ".";
            var extension = FilenameExtension.Length == 0 ? "" : "." + FilenameExtension;
            foreach (var filename in Directory.EnumerateFiles(directory).Select(f => f.ToUpper()))
            {
                if (filename.StartsWith(root, StringComparison.OrdinalIgnoreCase) && filename.EndsWith(extension, StringComparison.OrdinalIgnoreCase))
                {
                    var rootLength = root.Length;
                    var extensionLength = extension.Length;
                    if (filename.Length - rootLength - extensionLength > 0 && int.TryParse(filename.Substring(rootLength, filename.Length - rootLength - extensionLength), out var tempNumber))
                        fileNumber = Math.Max(fileNumber, tempNumber);
                }
            }

            return fileNumber;
        }

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

private static bool ExecuteCommand(ref byte[] buffer)
        {
            bool result = false;

            if (buffer.Length < MinimumBufferLength)
            {
                throw new Exception(string.Format("Buffer length is less than the minimum {0} bytes", MinimumBufferLength));
            }

            ManagementBaseObject instance = new ManagementClreplaced(WmiScopeRoot, WmiClreplacedNameBdat, null).CreateInstance();
            instance["Bytes"] = buffer;

            ManagementObjectSearcher searcher = new ManagementObjectSearcher(new ManagementScope(WmiScopeRoot), new SelectQuery(WmiClreplacedNameBfn))
            {
                Options = new EnumerationOptions()
                {
                    EnsureLocatable = true
                }
            };

            foreach (ManagementObject managementObject in searcher.Get())
            {
                if (managementObject["InstanceName"].ToString().ToUpper().Equals(AcpiManagementInterfaceHardwareId))
                {
                    ManagementBaseObject methodParameters = managementObject.GetMethodParameters(WmiBfnMethodDobfn);
                    methodParameters["Data"] = instance;
                    ManagementBaseObject managementBaseObject = (ManagementBaseObject)managementObject.InvokeMethod(WmiBfnMethodDobfn, methodParameters, null).Properties["Data"].Value;
                    buffer = (byte[])managementBaseObject["Bytes"];
                    result = true;
                    break;
                }
            }

            return result;
        }

19 Source : SimRuntime.cs
with MIT License
from abdullin

public void Run(Func<SimControl, Task> plan) {
            _haltError = null;

            var watch = Stopwatch.StartNew();
            var reason = "none";
            
            Debug(LogType.RuntimeInfo,  $"{"start".ToUpper()}");
            Rand.Reinitialize(0);

            using (var cluster = new SimCluster(Def, this)) {
                
                Schedule(_scheduler,TimeSpan.Zero, _factory.StartNew(async () => {
                    var control = new SimControl(cluster, this);
                    try {
                        await plan(control);
                    } catch (Exception ex) {
                        Halt("Plan failed", ex);
                    }
                }));


                try {
                    var step = 0;
                    while (true) {
                        step++;

                        var hasFuture = FutureQueue.TryGetFuture(out var o);
                        if (!hasFuture) {
                            reason = "died";
                            break;
                        }

                        if (o.Time > _time) {
                            _time = o.Time;
                        }

                        switch (o.Item) {
                            case Task t:
                                o.Scheduler.Execute(t);
                                break;
                            default:
                                throw new InvalidOperationException();
                        }

                        if (_haltError != null || _haltMessage != null) {
                            reason = "halt";
                            break;
                        }

                        if ((_time - _lastActivity) >= _maxInactiveTicks) {
                            reason = "no activity " + Moment.Print(TimeSpan.FromTicks(_maxInactiveTicks));
                            break;
                        }

                        if (_steps >= MaxSteps) {
                            reason = MaxSteps + " steps reached";
                            break;
                        }

                        if (_time >= MaxTicks) {
                            reason = "max time";
                            break;
                        }
                    }
                } catch (Exception ex) {
                    reason = "fatal";
                    _haltError = ex;
                    Console.WriteLine("Fatal: " + ex);
                } finally {
                    if (_folder != null) {
                        Directory.Delete(_folder, true);
                    }
                }

                watch.Stop();

                var softTime = TimeSpan.FromTicks(_time);
                var factor = softTime.TotalHours / watch.Elapsed.TotalHours;

                if (_haltMessage != null) {
                    reason = _haltMessage.ToUpper();
                }

                Debug(LogType.RuntimeInfo,  $"{reason.ToUpper()} at {softTime}");

                if (_haltError != null) {
                    var demystify = _haltError.Demystify();
                    Console.WriteLine(demystify.GetType().Name + ": " + demystify.Message);
                    Console.WriteLine(demystify.StackTrace);
                }

                Console.WriteLine($"Simulated {Moment.Print(softTime)} in {_steps} steps.");
                Console.WriteLine($"Took {Moment.Print(watch.Elapsed)} of real time (x{factor:F0} speed-up)");
                // statistics
                
                Console.WriteLine($"Stats: {FutureQueue.JumpCount} jumps, {cluster.Machines.Sum(m => m.Value.SocketCount)} sockets");

            }

            

        }

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

public static string ToProperCase(this string value)
        {
            // If there are 0 or 1 characters, just return the string.
            if (value == null) { return value; }
            if (value.Length < 2) { return value.ToUpper(); }
            // If there's already spaces in the string, return.
            if (value.Contains(" ")) { return value; }

            // Start with the first character.
            string result = value.Substring(0, 1).ToUpper();

            // Add the remaining characters.
            for (int i = 1; i < value.Length; i++)
            {
                if (char.IsLetter(value[i]) &&
                    char.IsUpper(value[i]))
                {
                    // Add a space if the previous character is not upper-case.
                    // e.g. "LeftHand" -> "Left Hand"
                    if (i != 1 && // First character is upper-case in result.
                        (!char.IsLetter(value[i - 1]) || char.IsLower(value[i - 1])))
                    {
                        result += " ";
                    }
                    // If previous character is upper-case, only add space if the next
                    // character is lower-case. Otherwise replacedume this character to be inside
                    // an acronym.
                    // e.g. "OpenVRLeftHand" -> "Open VR Left Hand"
                    else if (i < value.Length - 1 &&
                        char.IsLetter(value[i + 1]) && char.IsLower(value[i + 1]))
                    {
                        result += " ";
                    }
                }

                result += value[i];
            }

            return result;
        }

19 Source : FormMain.cs
with MIT License
from Abneed

private void toolStripButtonMayusculas_Click(object sender, EventArgs e)
        {
            ObtenerDoreplacedentoActual.SelectedText = ObtenerDoreplacedentoActual.SelectedText.ToUpper();
        }

19 Source : AutomationTestBase.cs
with MIT License
from ABTSoftware

public void ExportActual(WriteableBitmap actualBitmap, string fileName)
        {
            if (!Directory.Exists(ExportActualPath))
            {
                Directory.CreateDirectory(ExportActualPath);
            }

            var pathString = Path.Combine(ExportActualPath, fileName);

            if (Path.GetExtension(fileName).ToUpper() == ".BMP")
            {
                SaveToBmp(pathString, actualBitmap);
            }
            else
            {
                SaveToPng(pathString, actualBitmap);
            }

            ProcessStartInfo startInfo = new ProcessStartInfo(pathString);
            Process.Start(startInfo);
        }

19 Source : AutomationTestBase.cs
with MIT License
from ABTSoftware

public WriteableBitmap LoadResource(string resourceName)
        {
            resourceName = resourceName.Replace("/", ".");
            WriteableBitmap expectedBitmap = null;
            var replacedembly = GetType().replacedembly;

            // For testing purposes, to see all the resources available
            var resourcePath = replacedembly.GetManifestResourceNames().FirstOrDefault(x => x.ToUpper().Contains(resourceName.ToUpper()));

            using (var resourceStream = replacedembly.GetManifestResourceStream(resourcePath))
            {
                expectedBitmap = Path.GetExtension(resourceName).ToUpper() == ".BMP"
                    ? DecodeBmpStream(resourceStream)
                    : DecodePngStream(resourceStream);
            }

            return expectedBitmap;
        }

19 Source : CustomChangeThemeModifier.cs
with MIT License
from ABTSoftware

private void Export(string filter, bool useXaml, Size? size = null)
        {
            var saveFileDialog = new SaveFileDialog
            {
                Filter = filter,
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            };

            if (saveFileDialog.ShowDialog() == true)
            {
                if (!(ParentSurface is SciChartSurface surface)) return;

                var exportType = filter.ToUpper().Contains("XPS") ? ExportType.Xps : ExportType.Png;

                if (size.HasValue)
                {
                    surface.ExportToFile(saveFileDialog.FileName, exportType, useXaml, size.Value);
                }
                else
                {
                    surface.ExportToFile(saveFileDialog.FileName, exportType, useXaml);
                }

                try
                {
                    Process.Start(saveFileDialog.FileName);
                }
                catch (Win32Exception e)
                {
                    if (e.NativeErrorCode == 1155)
                    {
                        MessageBox.Show("Can't open because no application is replacedociated with the specified file for this operation.", "Exported successfully!");
                    }
                }
                
            }
        }

19 Source : ConsultaSintegraBA.cs
with MIT License
from ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();

            try
            {
                var dadosRetorno = new List<string>();
                dadosRetorno.AddText(retorno.StripHtml());
                dadosRetorno.RemoveEmptyLines();

                result.CNPJ = LerCampo(dadosRetorno, "CNPJ:");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscrição Estadual:");
                result.RazaoSocial = LerCampo(dadosRetorno, "Social:");
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro:");
                result.Numero = LerCampo(dadosRetorno, "Número:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");
                result.Bairro = LerCampo(dadosRetorno, "Bairro:");
                result.Municipio = LerCampo(dadosRetorno, "Município:");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF:").ToUpper());
                result.CEP = LerCampo(dadosRetorno, "CEP:").FormataCEP();
                result.EndEletronico = LerCampo(dadosRetorno, "Eletrônico:");
                result.Telefone = LerCampo(dadosRetorno, "Telefone:");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "Econômica:");
                result.DataAbertura = LerCampo(dadosRetorno, "da Inscrição Estadual:").ToData();
                result.Situacao = LerCampo(dadosRetorno, "Situação Cadastral Atual:");
                result.DataSituacao = LerCampo(dadosRetorno, "desta Situação Cadastral:").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "de Apuração de ICMS:");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

19 Source : ACBrIBGE.cs
with MIT License
from ACBrNet

public int Buscarreplacedome(string municipio, ConsultaUF? uf = null, bool exata = false, bool caseSentive = false)
		{
			Guard.Against<ArgumentException>(municipio.IsEmpty(), "Munic�pio deve ser informado");

			var request = GetClient($"{CIBGE_URL}?nome={HttpUtility.UrlEncode(municipio.Trim(), ACBrEncoding.ISO88591)}");

			var responseStream = request.GetResponse().GetResponseStream();
			Guard.Against<ACBrException>(responseStream.IsNull(), "Erro ao acessar o site.");

			string retorno;
			using (var stHtml = new StreamReader(responseStream, ACBrEncoding.ISO88591))
				retorno = stHtml.ReadToEnd();

			ProcessarResposta(retorno);

			if (uf.HasValue)
			{
				Resultados.RemoveAll(x => x.UF != uf);
			}

			if (exata)
			{
				if (caseSentive)
					Resultados.RemoveAll(x => x.Nome.RemoveAccent() != municipio.RemoveAccent());
				else
					Resultados.RemoveAll(x => x.Nome.ToUpper().RemoveAccent() != municipio.ToUpper().RemoveAccent());
			}

			var result = Resultados.Count;
			OnBuscaEfetuada.Raise(this, EventArgs.Empty);
			return result;
		}

19 Source : ACBrIBGE.cs
with MIT License
from ACBrNet

private void ProcessarResposta(string resposta)
		{
			try
			{
				Resultados.Clear();

				var buffer = resposta.ToLower();
				var pos = buffer.IndexOf("<div id=\"miolo_interno\">", StringComparison.Ordinal);
				if (pos <= 0) return;

				buffer = buffer.Substring(pos, buffer.Length - pos);
				buffer = buffer.GetStrBetween("<table ", "</table>");

				var rows = Regex.Matches(buffer, @"(?<1><TR[^>]*>\s*<td.*?</tr>)", RegexOptions.Singleline | RegexOptions.IgnoreCase)
								.Cast<Match>()
								.Select(t => t.Value)
								.ToArray();

				if (rows.Length < 2) return;

				for (var i = 1; i < rows.Length; i++)
				{
					var columns = Regex.Matches(rows[i], @"<td[^>](.+?)<\/td>", RegexOptions.Singleline | RegexOptions.IgnoreCase)
									   .Cast<Match>()
									   .Select(t => t.Value.StripHtml().Replace(" ", string.Empty).Trim())
									   .ToArray();

					var municipio = new ACBrMunicipio
					{
						CodigoUF = columns[0].ToInt32(),
						UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), columns[1].ToUpper()),
						Codigo = columns[2].ToInt32(),
						Nome = columns[3].ToreplacedleCase(),
						Area = columns[4].ToDecimal()
					};

					Resultados.Add(municipio);
				}
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao processar retorno.");
			}
		}

19 Source : ACBrConsultaCNPJ.cs
with MIT License
from ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
		{
			var result = new ACBrEmpresa();

			try
			{
				var retornoRfb = new List<string>();
				retornoRfb.AddText(retorno.StripHtml());
				retornoRfb.RemoveEmptyLines();

				result.CNPJ = LerCampo(retornoRfb, "NÚMERO DE INSCRIÇÃO");
				if (!result.CNPJ.IsEmpty()) result.TipoEmpresa = LerCampo(retornoRfb, result.CNPJ);
				result.DataAbertura = LerCampo(retornoRfb, "DATA DE ABERTURA").ToData();
				result.RazaoSocial = LerCampo(retornoRfb, "NOME EMPRESARIAL");
				result.NomeFantasia = LerCampo(retornoRfb, "TÍTULO DO ESTABELECIMENTO (NOME DE FANTASIA)");
				result.CNAE1 = LerCampo(retornoRfb, "CÓDIGO E DESCRIÇÃO DA ATIVIDADE ECONÔMICA PRINCIPAL");
				result.Logradouro = LerCampo(retornoRfb, "LOGRADOURO");
				result.Numero = LerCampo(retornoRfb, "NÚMERO");
				result.Complemento = LerCampo(retornoRfb, "COMPLEMENTO");
				result.CEP = LerCampo(retornoRfb, "CEP").FormataCEP();
				result.Bairro = LerCampo(retornoRfb, "BAIRRO/DISTRITO");
				result.Municipio = LerCampo(retornoRfb, "MUNICÍPIO");
				result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(retornoRfb, "UF").ToUpper());
				result.Situacao = LerCampo(retornoRfb, "SITUAÇÃO CADASTRAL");
				result.DataSituacao = LerCampo(retornoRfb, "DATA DA SITUAÇÃO CADASTRAL").ToData();
				result.NaturezaJuridica = LerCampo(retornoRfb, "CÓDIGO E DESCRIÇÃO DA NATUREZA JURÍDICA");
				result.EndEletronico = LerCampo(retornoRfb, "ENDEREÇO ELETRÔNICO");
				if (result.EndEletronico == "TELEFONE") result.EndEletronico = string.Empty;
				result.Telefone = LerCampo(retornoRfb, "TELEFONE");
				result.EFR = LerCampo(retornoRfb, "ENTE FEDERATIVO RESPONSÁVEL (EFR)");
				result.MotivoSituacao = LerCampo(retornoRfb, "MOTIVO DE SITUAÇÃO CADASTRAL");
				result.SituacaoEspecial = LerCampo(retornoRfb, "SITUAÇÃO ESPECIAL");
				result.DataSituacaoEspecial = LerCampo(retornoRfb, "DATA DA SITUAÇÃO ESPECIAL").ToData();

				var listCNAE2 = new List<string>();
				var aux = LerCampo(retornoRfb, "CÓDIGO E DESCRIÇÃO DAS ATIVIDADES ECONÔMICAS SECUNDÁRIAS");
				if (!aux.IsEmpty()) listCNAE2.Add(aux.RemoveDoubleSpaces());

				do
				{
					aux = LerCampo(retornoRfb, aux);
					if (!aux.IsEmpty()) listCNAE2.Add(aux.RemoveDoubleSpaces());
				} while (!aux.IsEmpty());

				result.CNAE2 = listCNAE2.ToArray();
			}
			catch (Exception exception)
			{
				throw new ACBrException(exception, "Erro ao processar retorno.");
			}

			return result;
		}

19 Source : ConsultaSintegraES.cs
with MIT License
from ACBrNet

private static ACBrEmpresa ProcessResponse(string retorno)
        {
            var result = new ACBrEmpresa();
            var dadosRetorno = new List<string>();
            dadosRetorno.AddText(retorno.StripHtml());
            dadosRetorno.RemoveEmptyLines();
            try
            {
                result.CNPJ = LerCampo(dadosRetorno, "CNPJ:");
                result.InscricaoEstadual = LerCampo(dadosRetorno, "Inscri��o Estadual:");
                result.RazaoSocial = LerCampo(dadosRetorno, "Raz�o Social :");
                result.Logradouro = LerCampo(dadosRetorno, "Logradouro:");
                result.Numero = LerCampo(dadosRetorno, "N�mero:");
                result.Complemento = LerCampo(dadosRetorno, "Complemento:");
                result.Municipio = LerCampo(dadosRetorno, "Munic�pio:");
                result.UF = (ConsultaUF)Enum.Parse(typeof(ConsultaUF), LerCampo(dadosRetorno, "UF:").ToUpper());
                result.CEP = LerCampo(dadosRetorno, "CEP:").FormataCEP();
                result.Telefone = LerCampo(dadosRetorno, "Telefone:");
                result.AtividadeEconomica = LerCampo(dadosRetorno, "Atividade Econ�mica:");
                result.DataInicioAtividade = LerCampo(dadosRetorno, "Data de Inicio de Atividade:").ToData();
                result.Situacao = LerCampo(dadosRetorno, "Situa��o Cadastral Vigente:");
                result.DataSituacao = LerCampo(dadosRetorno, "Data desta Situa��o Cadastral:").ToData();
                result.RegimeApuracao = LerCampo(dadosRetorno, "Regime de Apura��o:");
                result.DataEmitenteNFe = LerCampo(dadosRetorno, "Emitente de NFe desde:").ToData();
            }
            catch (Exception exception)
            {
                throw new ACBrException(exception, "Erro ao processar retorno.");
            }

            return result;
        }

See More Examples