IT Blog

  • Blog
  • Technology
    • Architecture
    • CMS
    • CRM
    • Web
    • DotNET
    • Python
    • Database
    • BI
    • Program Language
  • Users
    • Login
    • Register
    • Forgot Password?
  • ENEN
    • ENEN
DotNET
DotNET

Extend some useful string functions in C#

Add some useful extension methods for string manipulations in C#. Make coding more elegent, interesting and productive. string.ToBoolean(); string.ToInt(); string.RemoveSufix(string suffix); string.RemovePrefix(string prefix); string.Remove(string toBeRemoved); string.RemoveSpace(); string.RemoveWhiteSpace();   /// <summary> /// Accept string value: "true", "t", "1" as true, all others will be evaluated as false. /// </summary> /// <returns></returns> public static bool ToBoolean(this string value) { if (string.IsNullOrEmpty(value)) return false; switch (value.Trim().ToLower()) { case "true": return true; case "t": return true; case "1": return true; case "0": return false; case "false": return false; case "f": return false; case "": return false; default: return false; //throw new InvalidCastException("You can't cast that value to a bool!"); } } /// <summary> /// Convert a string to int with default value /// </summary> /// <returns></returns> public static int ToInt(this string value) { if (string.IsNullOrEmpty(value)) return 0; int.TryParse(value, out int i); return i; } /// <summary> /// Remove string suffix /// </summary> /// <param name="suffix"></param> /// <returns></returns> public static string RemoveSufix(this string value, string suffix) { if (value.EndsWith(suffix)) { value.Substring(0, value.Length - suffix.Length); } return value; } /// <summary> /// Remove string prefix /// </summary> /// <param name="prefix"></param> /// <returns></returns> public static string RemovePrefix(this string value, string prefix) { if (value.StartsWith(prefix)) { value.Substring(prefix.Length); } return value; } /// <summary> /// Remove all spaces from a string /// </summary> /// <returns></returns> public static string RemoveSpace(this string value) { return value.Replace(" ", string.Empty); } /// <summary> /// Remove all white spaces from a string, including " ", \t, \r, \n /// </summary> /// <returns></returns> public static string RemoveWhiteSpace(this string value) { return value.Replace(" ", string.Empty) .Replace("\t",…

2020年09月24日 0条评论 809点热度 0人点赞 阅读全文
DotNET

Unicode to Chinese conversion notes

Unicode expressed like "\u4a44". Chinese words located from 0x3400 to 0x9fa5, including simplified and traditional words. Online tool: Unicode to Chinese covnerter C# Stores unicode data as a string, for each unicode in a string lookup the string by hex or integer number to get the right characters to replace them in the string. string ZHTable = "㐀㐁㐂㐃㐄㐅㐆㐇㐈㐉㐊㐋㐌㐍㐎㐏㐐... ...";   private string GetChar(string unicode) { unicode = unicode.Replace("\\u", ""); var code = Convert.ToInt32(unicode, 16); return ZHTable[code - 13312].ToString(); } var matches = Regex.Matches(text, @"\\u[a-f0-9]{4}"); string result = text; if (matches.Count > 0) { foreach (var m in matches) { var key = m.ToString(); result = result.Replace(key, GetChar(m.ToString())); } }   public string ToChinese(string text) { var matches = Regex.Matches(text, @"\\u[a-f0-9]{4}"); string result = text; if (matches.Count > 0) { foreach (var m in matches) { var key = m.ToString(); result = result.Replace(m.ToString(), GetChar(key)); } } return result; } PHP Stores unicode data in a dictionary like array, for each unicode in a string look up the dictionary to get the right characters to replace them in the string. $unicodedata = [ ... ... 0x3437 => '㐷', 0x3438 => '㐸', 0x3439 => '㐹', 0x343a => '㐺', 0x343b => '㐻', 0x343c => '㐼', ... ... ]; for number calculate as power of 16; for a-f, convert to ascii code - 87, so as a=10, f=15, then calculate as power of 16; for hex letter only has a-f, other than that throw exception. if($this->is_number($u[$i])){ $val += $u[$i] * pow(16, 3-$i); } elseif($this->is_hexletter($u[$i])){ $val += ord($u[$i])-87 * pow(16,3-$i); } to match all unicode, which…

2020年09月18日 0条评论 146点热度 0人点赞 阅读全文
DotNET

Accessing private fields in C#

Based OO principles the private fields should not be accessd by anything outside of the object. However, for some reason we have to access the private fields, a good example is unit testing. With dotnet reflection we could access any fields, members in an object. The accessibility is controled by BindingFlags, specify proper bindingFlags we can access all private fields in a class. To access the private fields in base class we need to add one more level of the type with BaseType. Here is the extension method to get the value of a public and private field in an instance. public static T GetFieldValue<T>(this object obj, string name) { var bindingFlags = BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance; var field = obj.GetType().GetField(name, bindingFlags); if (field == null) field = obj.GetType().BaseType.GetField(name, bindingFlags); //father else if (field == null) field = obj.GetType().BaseType.BaseType.GetField(name, bindingFlags); //granpa else if (field == null) field = obj.GetType().BaseType.BaseType.BaseType.GetField(name, bindingFlags); //father of granpa return (T)field?.GetValue(obj); }

2020年09月03日 0条评论 341点热度 0人点赞 阅读全文
DotNET

用设计模式降低循环复杂性

条件语句的作用是更改控制流,任何程序都离不开条件判断。但条件判断会增加程序的复杂度,过多的条件判断会导致循环复杂度(Cyclomatic Complexity)。 这种复杂度取决于3个因素: 分支变量数 分支数 条件嵌套深度 if else if else if else if switch case 1: ... case 2: ... end switch ...... end if end if end if end if 这种形状也叫 Arrow Anti Pattern。它不仅降低程序的可读性,难以扩展和重用,还会轻易地隐藏许多bug。是我们必须避免的代码。 设计模式注重于软件的重用性和扩展性,但大多数模式都可以用来降低循环复杂度。设计模式可以让不同参与者分担这些条件语句,每个参与者解决一部分问题,这样控制流程就更简单,从而降低他们的循环复杂性。 这里介绍一个用策略(Strategy)设计模式来降低循环复杂度的例子。 假设现在我们可以用 C# 写一个简单的计算器,代码如下: using System; public class Calculator { public double Calculate(double operand1, double operand2, char operater) { double result = 0.0; switch (operater) { case '+': result = operand1 + operand2; break; case '-': result = operand1 - operand2; break; case '*': result = operand1 * operand2; break; case '/': if (Math.Abs(operand2) > 0.0) { result = operand1 / operand2; } else { throw new ArithmeticException("分母为零。"); } break; default: throw new ArgumentException("未知运算符: " + operater); } return result; } public static void Main(String[] args) { args = new[] { "2", "*", "3" }; double operand1 = Double.Parse(args[0]); double operand2 = Double.Parse(args[2]); char operater = args[1][0]; double result = new Calculator().Calculate(operand1, operand2, operater); Console.WriteLine(operand1 + args[1] + operand2 + " = " + result); Console.ReadKey(); } } 现在用策略模式来重构这段代码: 模式角色: Strategy: IProcessor ConcreteStrategy: Adder, Subtractor, Multiplier, Divider Context: Calculator using System; using System.Collections.Generic; public interface IProcessor { double Process(double operand1, double operand2); } public class Adder : IProcessor { public double Process(double operand1, double operand2) { return operand1 + operand2; } } public class Subtractor : IProcessor { public double Process(double operand1, double operand2) { return operand1 - operand2; } } public class Multiplier : IProcessor { public double Process(double operand1, double operand2) { return operand1 * operand2; } } public class Divider : IProcessor { public double Process(double operand1, double operand2) { double…

2020年07月27日 0条评论 339点热度 1人点赞 阅读全文
DotNET

Crawler - Split column

Problem The second line contains pingying and alias. html code: Zhōngfǔ&nbsp;&nbsp;&nbsp;肺之募穴 First try get data roughly: alias = p.Select(Selectors.XPath("//span[@style]"))?.Value.Replace("&nbsp;", " "); Result: Zhōngfǔ   肺之募穴 Split the alias column in MySQL: UPDATE `xuewei` set pingying=substring_index(alias,' ',1); UPDATE `xuewei` set bieming=substring_index(alias,' ',-1); Split the column in process: alias = p.Select(Selectors.XPath("//span[@style]"))?.Value.Replace("&nbsp;", " "); var arr = alias.Split(' '); pingying = arr[0]; alias = arr[arr.Length-1]; //get last item in the array for the space in between is uncertain. Save to database: await conn.ExecuteAsync( $"INSERT IGNORE INTO xuewei (name,pingying,alias,position,anatomy,indication,operation,imagegeneral,imagepoint) VALUES " + $"('{data.Name}', '{data.Pingying}', '{data.Alias}', '{data.Position}', '{data.Anatomy}', '{data.Indication}', '{data.Operation}', '{data.ImageGeneral}', '{data.ImagePoint}');");

2020年05月18日 0条评论 332点热度 0人点赞 阅读全文
DotNET

Crawler - get data from unwrapped html content

Content data on webpage: It's html code looks like this: Parsing data using regular expression with named group. Use foreach loop to avoid the order change on page. Do not use the text value from dom function/property, because the text value does not contain html tag, which gives you the mark on data.

2020年05月17日 0条评论 292点热度 0人点赞 阅读全文
DotNET

String concatenation in c# and php

C# Using + operator Console.WriteLine("Hello" + " " + "String " + "!"); String Interpolation string author = "Mahesh Chand"; string book = "C# Programming"; string bookAuthor = $"{author} is the author of {book}."; String.Concatenate() method string fName = "Mahesh"; string lName = "Chand"; string Name = string.Concat(fName, lName); string[] authors = { "Mahesh Chand ", "Chris Love ", "Dave McCarter ", "Praveen Kumar "}; string arrayStr = string.Concat(authors); String.Join() method int[] intArray = { 1, 3, 5, 7, 9 }; String seperator = ", "; string result = "Int, "; result += String.Join(seperator, intArray); // Using String.Join(String, String[], int int) // Let's concatenate first two strings of the array String[] arr2 = { "Mahesh Chand ", "Chris Love ", "Dave McCarter ", "Praveen Kumar " }; String seperator2 = ", "; string result2 = "First Author, "; result2 += String.Join(seperator2, arr2, 1, 2); Console.WriteLine($"Result: {result2}"); String.Format() method string date = String.Format("Today's date is {0}", DateTime.Now); StringBuilder.Append() method builder.Append(", "); PHP Using . operator $b = "Hello " . "World!"; // slow String Interpolation $a = '3'; echo "qwe{$a}rty"; // double quote echo "Result: " . ($a + 3); // result 6 "{$str1}{$str2}{$str3}"; // one concat = fast   $str1. $str2. $str3;    // two concats = slow //Use double quotes to concat more than two strings instead of multiple '.' operators.  PHP is forced to re-concatenate with every '.' operator. $logMessage = "A {$user->type} with e-mailaddress {$user->email} has performed {$action} on {$subject}." Using printf() $logMessage = sprintf('A %s with email %s has performed %s on %s.', $user->type, $user->email, $action, $subject);  

2020年04月29日 0条评论 557点热度 0人点赞 阅读全文
DotNET

工业企业订单管理系统升级(2) — 数据读取器读取数据

项目中用MySqlDataReader 读取数据。我见过很多人错误地使用DataReader。 在这篇文章中,我将尝试解释从数据读取器读取时可以遵循的一些良好习惯。 考虑以下有问题的代码, MySqlDataReader reader = /* ... */; while (reader.Read()) { string id= reader["name"].ToString(); int name= int.Parse( reader["age"].ToString() ); /* ... */ } reader.Close(); 你能从上面的代码中找到多少问题? 这段代码有很多问题, “name”和“age”列可能存在也可能不存在。 如果阅读器中不存在该列,则会出错。 您可能正在对可能指向NULL的对象调用ToString() 。 这将导致空引用异常。 DataReader 实现IDisposable ,用户代码必须每次调用Dispose()以确定性地释放资源。这不会发生在这里。 reader["age"]可能包含与整数不兼容的值。 在这种情况下, int.Parse()将抛出FormatException 。 以下部分将显示从DataReader读取数据的安全方法。 了解序数 Ordinal是阅读器中列的索引。 GetOrdinal()方法将为您提供所提供的列名的序数。 因此,从读取器读取数据的第一步应该是找到我们想要读取的列的序数。 在获得序数值之前,您必须确保读者可以阅读。SqlDataReader提供了一个在这里很有用的HasRows属性。 这是你如何阅读序数。

2018年12月11日 0条评论 1010点热度 0人点赞 阅读全文
DotNET

MS security patches lead to ams login failure

AMS issue reported: here were Microsoft Security Patches updated and now we have an “Unspecified Error”. Investigation amsapp01 .net versions amsapp01-error-service-call-failed amsapp01 TombstoneWCF error – duplicate scriptResourceHandler amsapp01iis apppools fix ams stop working after patch – install svc in iis for dotnet 2.0 Reason The Windows security patch broke dotnet service model registration on IIS, and lead to WCF service stop working. Solution “C:\Windows\Microsoft.NET\Framework\v3.0\Windows Communication Foundation\ServiceModelReg.exe” -i Improve In the future, better test it on dev server before applying the patch to the production.

2017年10月28日 0条评论 353点热度 0人点赞 阅读全文
最新 热点 随机
最新 热点 随机
Generating Test Data with SQL Scripts Remote connection to MySQL on SiteGround Hide author information from WordPress How to do some trick to improve WordPress performance Recovering user role in WordPress Sending email using gmail SMTP
How to do some trick to improve WordPress performanceRemote connection to MySQL on SiteGroundGenerating Test Data with SQL ScriptsRecovering user role in WordPressHide author information from WordPress
Send report in the attachment from database Customize theme CityZen Temporary tables lifetime Hide author information from WordPress Automation report and validating WordPress EventCalendar visibility
Categories
  • AdSense
  • Architecture
  • BI
  • C#
  • CSS
  • Database
  • Digital Marketing
  • DotNET
  • Hosting
  • HTML
  • JavaScript
  • PHP
  • Program Language
  • Python
  • Security
  • SEO
  • Technology
  • Web
  • Wordpress

COPYRIGHT © 20203-2021 Hostlike.com. ALL RIGHTS RESERVED.