GVKun编程网logo

从 PHP 到 C# 的 UUID V1 转换导致错误的 GUID(php错误转异常函数)

1

本篇文章给大家谈谈从PHP到C#的UUIDV1转换导致错误的GUID,以及php错误转异常函数的知识点,同时本文还将给你拓展API控制器接受Guid集合-当没有传递参数值时收到一个空的Guid、api

本篇文章给大家谈谈从 PHP 到 C# 的 UUID V1 转换导致错误的 GUID,以及php错误转异常函数的知识点,同时本文还将给你拓展API 控制器接受 Guid 集合 - 当没有传递参数值时收到一个空的 Guid、api/entity/get 和 api/entity/get?guid={guid} 等的正确 RESTful 实现?、C# MongoDB Upsert - 'BsonValue(Guid) 已过时:'改用 BsonBinaryData 构造函数并指定 Guid 表示'、Flask-SQLAlchemy-SQLite:无法处理 GUID 对象服务器端 - ValueError:格式错误的十六进制 UUID 字符串等相关知识,希望对各位有所帮助,不要忘了收藏本站喔。

本文目录一览:

从 PHP 到 C# 的 UUID V1 转换导致错误的 GUID(php错误转异常函数)

从 PHP 到 C# 的 UUID V1 转换导致错误的 GUID(php错误转异常函数)

如何解决从 PHP 到 C# 的 UUID V1 转换导致错误的 GUID

我不熟悉 PHP 代码。我想将 PHP code 实现的 UUID V1 转换为 C#。我尝试了很多方法,但都失败了。哪部分代码有问题? 此 C# 代码生成错误的 GUID fa570fa10-3b235-472b-500-1ebc212c87e0,参数 node 为 138417599493834080(结果可能因 Unix 日期时间而异)。当我将方法 Hex2Dec 更改为 here 时,它会生成 393031383131343830-3234313135-3138323139-313238-1ebc212c87e0。我对错误的代码没有更多的想法。请帮我解决。

  1. public static function v1($node)
  2. {
  3. // nano second time (only micro second precision) since start of UTC
  4. $time = microtime(true) * 10000000 + 0x01b21dd213814000;
  5. $time = pack("H*",sprintf(''%016x'',$time));
  6. $sequence = random_bytes(2);
  7. $sequence[0] = chr(ord($sequence[0]) & 0x3f | 0x80); // variant bits 10x
  8. $time[0] = chr(ord($time[0]) & 0x0f | 0x10); // version bits 0001
  9. if (!empty($node)) {
  10. // non hex string identifier
  11. if (is_string($node) && preg_match(''/[^a-f0-9]/is'',$node)) {
  12. // base node off md5 hash for sequence
  13. $node = md5($node);
  14. // set multicast bit not IEEE 802 MAC
  15. $node = (hexdec(substr($node,2)) | 1) . substr($node,2,10);
  16. }
  17. if (is_numeric($node))
  18. $node = sprintf(''%012x'',$node);
  19. $len = strlen($node);
  20. if ($len > 12)
  21. $node = substr($node,12);
  22. else if ($len < 12)
  23. $node .= str_repeat(''0'',12 - $len);
  24. } else {
  25. // base node off random sequence
  26. $node = random_bytes(6);
  27. // set multicast bit not IEEE 802 MAC
  28. $node[0] = chr(ord($node[0]) | 1);
  29. $node = bin2hex($node);
  30. }
  31. return bin2hex($time[4] . $time[5] . $time[6] . $time[7]) // time low
  32. . ''-'' . bin2hex($time[2] . $time[3]) // time med
  33. . ''-'' . bin2hex($time[0] . $time[1]) // time hi
  34. . ''-'' . bin2hex($sequence) // seq
  35. . ''-'' . $node; // node
  36. }

这是 C# 部分

  1. public static string MD5(this string input)
  2. {
  3. // Use input string to calculate MD5 hash
  4. using (System.Security.Cryptography.MD5 crypto = System.Security.Cryptography.MD5.Create())
  5. {
  6. byte[] hashBytes = crypto.ComputeHash(Encoding.ASCII.GetBytes(input));
  7. StringBuilder sb = new StringBuilder();
  8. for (int i = 0; i < hashBytes.Length; i++)
  9. sb.Append(hashBytes[i].ToString("x2"));
  10. return sb.ToString();
  11. }
  12. }
  13. public static string GenerateGuidV1(string node)
  14. {
  15. var xtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 10000000 + 0x01b21dd213814000;
  16. var time = Pack(xtime.ToString("x"));
  17. var sequence = new byte[2];
  18. sequence[0] = (byte)((char)sequence[0] & 0x3f | 0x80); // variant bits 10x
  19. time[0] = (byte)((char)time[0] & 0x0f | 0x10); // version bits 0001
  20. if (!string.IsNullOrWhiteSpace(node))
  21. {
  22. // non hex string identifier
  23. if (!IsNumeric(node) && Regex.IsMatch(node,"/[^a-f0-9]/is",RegexOptions.IgnoreCase))
  24. //if (preg_match(''/[^a-f0-9]/is'',$node))
  25. {
  26. // base node off md5 hash for sequence
  27. //$node = md5($node);
  28. node = node.MD5();
  29. // set multicast bit not IEEE 802 MAC
  30. //$node = (hexdec(substr($node,10);
  31. node = (int.Parse(node.Substring(0,2),NumberStyles.Hexnumber) | 1) + node.Substring(2,10);
  32. }
  33. if (IsNumeric(node))
  34. node = Convert.ToInt64(node).ToString("x"); //sprintf(''%012x'',$node);
  35. var len = node.Length;
  36. if (len > 12)
  37. node = node.Substring(0,12); //substr($node,12);
  38. else if (len < 12)
  39. node += string.Concat(Enumerable.Repeat("0",12 - len));//str_repeat(''0'',12 - $len);
  40. }
  41. else
  42. {
  43. // base node off random sequence
  44. var seqNode = new byte[6];//$node = random_bytes(6);
  45. // set multicast bit not IEEE 802 MAC
  46. seqNode[0] = (byte)((char)node[0] | 1);//$node[0] = chr(ord($node[0]) | 1);
  47. node = Convert.ToInt16(seqNode[0].ToString(),2).ToString("x");//bin2hex($node);
  48. }
  49. return Bin2Hex(time[4].ToString() + time[5].ToString() + time[6].ToString() + time[7].ToString()) // time low
  50. + ''-''+ Bin2Hex(time[2].ToString() + time[3].ToString()) // time med
  51. + ''-''+ Bin2Hex(time[0].ToString() + time[1].ToString()) // time hi
  52. + ''-''+ Bin2Hex(sequence[0].ToString() + sequence[1].ToString()) // seq
  53. + ''-''+ node; // node
  54. }
  55. private static string Bin2Hex(string value)
  56. {
  57. return Convert.ToInt64(value).ToString("x");
  58. //byte[] bytes = Encoding.GetEncoding(1252).GetBytes(value);
  59. //string hexString = "";
  60. //for (int ii = 0; ii < bytes.Length; ii++)
  61. //{
  62. // hexString += bytes[ii].ToString("x2");
  63. //}
  64. //return hexString;
  65. }
  66. private static byte[] Pack(string hex)
  67. {
  68. hex = hex.Replace("-","");
  69. byte[] raw = new byte[hex.Length / 2];
  70. for (int i = 0; i < raw.Length; i++)
  71. {
  72. raw[i] = Convert.ToByte(hex.Substring(i * 2,16);
  73. }
  74. return raw;
  75. }
  76. private static bool IsNumeric(string value) => value.All(char.IsNumber);

API 控制器接受 Guid 集合 - 当没有传递参数值时收到一个空的 Guid

API 控制器接受 Guid 集合 - 当没有传递参数值时收到一个空的 Guid

如何解决API 控制器接受 Guid 集合 - 当没有传递参数值时收到一个空的 Guid

我有一个 ASP.NET API 控制器,如下所示:

 [HttpGet,Route("endpoint")]
 public async Task GetValues([FromUri] IReadOnlyCollection<Guid> ids)

当我使用这个 URI 调用这个端点时:

''http://localhost:56132/api/controllers/endpoint?ids=''

然后调试收到的集合,它实际上包含一个条目,它是一个空的 Guid。在这种情况下,我本来希望集合是空的。为什么它会这样工作?有什么我可以做的,这样它就不会将这个空的 Guid 添加到集合中吗?

解决方法

ASP.NET 就像你说的那样:你提供了一个没有价值的元素。您已将集合指定为 <Guid>,该值类型不能为 null,因此您将获得单个元素的默认值,即 Guid.Empty

如果您提供两个没有值的参数,您将在集合中获得两个元素,以 Guid.Empty 作为值:

localhost:56132/api/controllers/endpoint?ids=&ids=

有什么我可以做的,这样它就不会将这个空的 Guid 添加到集合中吗?

如果你想要一个没有元素的集合,就不要指定任何元素:

localhost:56132/api/controllers/endpoint?

如果您想要一个包含 1 个空值的集合,请使用可以为空的类型而不是 Guid,例如 Guid?

api/entity/get 和 api/entity/get?guid={guid} 等的正确 RESTful 实现?

api/entity/get 和 api/entity/get?guid={guid} 等的正确 RESTful 实现?

如何解决api/entity/get 和 api/entity/get?guid={guid} 等的正确 RESTful 实现??

背景:

每个日期只能存在一个实体。

考虑 API 端点:

1: api/entities — returns all entities
2: api/entities?date={date} — returns a singular entity by it''s date

有没有更好的表达方式?

我想返回与日期匹配的单个实体,而不是集合。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

C# MongoDB Upsert - 'BsonValue(Guid) 已过时:'改用 BsonBinaryData 构造函数并指定 Guid 表示'

C# MongoDB Upsert - 'BsonValue(Guid) 已过时:'改用 BsonBinaryData 构造函数并指定 Guid 表示'

如何解决C# MongoDB Upsert - ''BsonValue(Guid) 已过时:''改用 BsonBinaryData 构造函数并指定 Guid 表示''

我是 MongoDB 的新手,正在尝试创建一个 Upsert:

  1. public void UpsertRecord<T>(string collectionName,Guid id,T record)
  2. {
  3. var collection = db.GetCollection<T>(collectionName);
  4. var result = collection.ReplaceOne(
  5. new BsonDocument("_id",id),record,new ReplaceOptions { IsUpsert = true });
  6. }

但我在 Visual Studio 中收到以下警告:

''BsonValue.implicit operator BsonValue(Guid) 已过时:使用 BsonBinaryData 构造函数代替并指定 Guid 表示''

任何帮助将不胜感激!

解决方法

我能够通过这种方式修复它:

  1. public void UpsertRecord<T>(string table,Guid id,T record)
  2. {
  3. BsonBinaryData binData = new BsonBinaryData(id,GuidRepresentation.Standard);
  4. var collection = db.GetCollection<T>(table);
  5. var result = collection.ReplaceOne(
  6. new BsonDocument("_id",binData),record,new ReplaceOptions { IsUpsert = true });
  7. }

Flask-SQLAlchemy-SQLite:无法处理 GUID 对象服务器端 - ValueError:格式错误的十六进制 UUID 字符串

Flask-SQLAlchemy-SQLite:无法处理 GUID 对象服务器端 - ValueError:格式错误的十六进制 UUID 字符串

如何解决Flask-SQLAlchemy-SQLite:无法处理 GUID 对象服务器端 - ValueError:格式错误的十六进制 UUID 字符串

我正在开发一个小 Flask 应用程序,在那里我有一个 sqlite 模型并使用数据表和 jquery 显示这些数据。我实现了一种用于过滤、搜索和分页的服务器端方法。现在我想使用 uuid.uuid4() 模块将每个表的 id 更改为 GUID 对象。但是当我这样做时,我的服务器端处理文件抛出错误:

  1. File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\models\\model.py",line 41,in process_bind_param
  2. return "%.32x" % uuid.UUID(value).int
  3. File "C:\\Users\\s1056280\\AppData\\Local\\Programs\\Python\\python39\\Lib\\uuid.py",line 177,in __init__
  4. raise ValueError(''badly formed hexadecimal UUID string'')
  5. ValueError: badly formed hexadecimal UUID string
  6. File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\views\\queries.py",line 17,in load_projects
  7. returnTable = ProjectsDataTable(request,Projects).output_result()
  8. File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\util\\table_queries.py",line 15,in __init__
  9. self.run_query()
  10. File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\util\\table_queries.py",line 56,in run_query
  11. self.cardinality_filtered = db.session.query(func.count(str(self.model_object.id))) \\
  12. File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\models\\model.py",in __init__
  13. raise ValueError(''badly formed hexadecimal UUID string'')
  14. sqlalchemy.exc.StatementError: (builtins.ValueError) badly formed hexadecimal UUID string
  15. [sql: SELECT count(?) AS count_1
  16. FROM projects
  17. WHERE projects.id LIKE ? OR projects.title LIKE ? OR projects.description LIKE ? OR projects.created_date LIKE ?
  18. LIMIT ? OFFSET ?]
  19. [parameters: [immutabledict({})]]

我的服务器端python脚本如下:

  1. class ProjectsDataTable:
  2. def __init__(self,request,model_object):
  3. self.request = request
  4. self.model_object = model_object
  5. self.cardinality = 0
  6. self.cardinality_filtered = 0
  7. self.results = None
  8. self.run_query()
  9. def output_result(self):
  10. output = {}
  11. output["sEcho"] = int(self.request.args.get(''sEcho''))
  12. output["iTotalRecords"] = self.cardinality
  13. output["iTotaldisplayRecords"] = self.cardinality_filtered
  14. output["aaData"] = self.results
  15. return output
  16. def run_query(self):
  17. self.cardinality = self.model_object.query.count()
  18. #get columns name from request
  19. column_count = int(self.request.args.get(''iColumns''))
  20. column_list = []
  21. for i in range(column_count):
  22. column_name = self.request.args.get(''mDataProp_%d'' % i)
  23. column_list.append(column_name)
  24. #filtering
  25. search_value = self.request.args.get(''sSearch'')
  26. filter_list = []
  27. if search_value != "":
  28. for col in column_list[:-1]:
  29. column_type = getattr(getattr(self.model_object,col),''type'')
  30. print(column_type)
  31. if not isinstance(column_type,db.DateTime):
  32. filter_list.append(getattr(self.model_object,col).like("%" + search_value + "%"))
  33. #sorting
  34. order_column_index = int(self.request.args.get(''iSortCol_0''))
  35. order_column = getattr(self.model_object,column_list[order_column_index])
  36. order_dir = self.request.args.get(''sSortDir_0'')
  37. order_object = getattr(order_column,order_dir)()
  38. #paging
  39. start = self.request.args.get(''idisplayStart'',type=int)
  40. length = self.request.args.get(''idisplayLength'',1,type=int)
  41. items = self.model_object.query.filter(or_).order_by(order_object) \\
  42. .offset(start).limit(length).all()
  43. self.cardinality_filtered = db.session.query(func.count(self.model_object.id)) \\
  44. .filter(or_).order_by(None).first()
  45. self.results = [i.projects_table_to_json for i in items]

模型类本身看起来像这样:

  1. from fastapi_utils.guid_type import GUID,GUID_DEFAULT_sqlITE
  2. class Projects(db.Model):
  3. __tablename__ = ''projects''
  4. id = Column(GUID,primary_key=True,default=GUID_DEFAULT_sqlITE)
  5. title = Column(String(100),unique=False,nullable=False)
  6. description = Column(String(500),nullable=False)
  7. date = Column(Integer,nullable=False)
  8. experiments = relationship("Experiments",backref=''project'',lazy=True)
  9. def __init__(self,title,description,created_date):
  10. self.title = title
  11. self.description = description
  12. self.date= date
  13. @property
  14. def projects_table_to_json(self):
  15. return {
  16. ''id'': str(self.id),''title'': self.title,''description'': self.description,''date'': self.date,}

不知何故,我在声明和填充我的 filter_list 列表时出现了逻辑错误。将 GUID 转换为字符串时,一切正常,但它以某种方式无法与 GUID 本身一起使用。它在我的 sqlite 数据库中存储为 CHAR(32)。

我已经尝试过不同的 uuid 模块以及自己编写的 - 但所有内容都有相同的 ValueError:格式错误的十六进制 UUID 字符串。

有人有想法吗?我会很感激,现在已经连续坐了两天

关于从 PHP 到 C# 的 UUID V1 转换导致错误的 GUIDphp错误转异常函数的介绍已经告一段落,感谢您的耐心阅读,如果想了解更多关于API 控制器接受 Guid 集合 - 当没有传递参数值时收到一个空的 Guid、api/entity/get 和 api/entity/get?guid={guid} 等的正确 RESTful 实现?、C# MongoDB Upsert - 'BsonValue(Guid) 已过时:'改用 BsonBinaryData 构造函数并指定 Guid 表示'、Flask-SQLAlchemy-SQLite:无法处理 GUID 对象服务器端 - ValueError:格式错误的十六进制 UUID 字符串的相关信息,请在本站寻找。

本文标签: