本篇文章给大家谈谈从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错误转异常函数)
- 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 code 实现的 UUID V1 转换为 C#。我尝试了很多方法,但都失败了。哪部分代码有问题?
此 C# 代码生成错误的 GUID fa570fa10-3b235-472b-500-1ebc212c87e0
,参数 node
为 138417599493834080(结果可能因 Unix 日期时间而异)。当我将方法 Hex2Dec
更改为 here 时,它会生成 393031383131343830-3234313135-3138323139-313238-1ebc212c87e0
。我对错误的代码没有更多的想法。请帮我解决。
public static function v1($node)
{
// nano second time (only micro second precision) since start of UTC
$time = microtime(true) * 10000000 + 0x01b21dd213814000;
$time = pack("H*",sprintf(''%016x'',$time));
$sequence = random_bytes(2);
$sequence[0] = chr(ord($sequence[0]) & 0x3f | 0x80); // variant bits 10x
$time[0] = chr(ord($time[0]) & 0x0f | 0x10); // version bits 0001
if (!empty($node)) {
// non hex string identifier
if (is_string($node) && preg_match(''/[^a-f0-9]/is'',$node)) {
// base node off md5 hash for sequence
$node = md5($node);
// set multicast bit not IEEE 802 MAC
$node = (hexdec(substr($node,2)) | 1) . substr($node,2,10);
}
if (is_numeric($node))
$node = sprintf(''%012x'',$node);
$len = strlen($node);
if ($len > 12)
$node = substr($node,12);
else if ($len < 12)
$node .= str_repeat(''0'',12 - $len);
} else {
// base node off random sequence
$node = random_bytes(6);
// set multicast bit not IEEE 802 MAC
$node[0] = chr(ord($node[0]) | 1);
$node = bin2hex($node);
}
return bin2hex($time[4] . $time[5] . $time[6] . $time[7]) // time low
. ''-'' . bin2hex($time[2] . $time[3]) // time med
. ''-'' . bin2hex($time[0] . $time[1]) // time hi
. ''-'' . bin2hex($sequence) // seq
. ''-'' . $node; // node
}
这是 C# 部分
public static string MD5(this string input)
{
// Use input string to calculate MD5 hash
using (System.Security.Cryptography.MD5 crypto = System.Security.Cryptography.MD5.Create())
{
byte[] hashBytes = crypto.ComputeHash(Encoding.ASCII.GetBytes(input));
StringBuilder sb = new StringBuilder();
for (int i = 0; i < hashBytes.Length; i++)
sb.Append(hashBytes[i].ToString("x2"));
return sb.ToString();
}
}
public static string GenerateGuidV1(string node)
{
var xtime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() * 10000000 + 0x01b21dd213814000;
var time = Pack(xtime.ToString("x"));
var sequence = new byte[2];
sequence[0] = (byte)((char)sequence[0] & 0x3f | 0x80); // variant bits 10x
time[0] = (byte)((char)time[0] & 0x0f | 0x10); // version bits 0001
if (!string.IsNullOrWhiteSpace(node))
{
// non hex string identifier
if (!IsNumeric(node) && Regex.IsMatch(node,"/[^a-f0-9]/is",RegexOptions.IgnoreCase))
//if (preg_match(''/[^a-f0-9]/is'',$node))
{
// base node off md5 hash for sequence
//$node = md5($node);
node = node.MD5();
// set multicast bit not IEEE 802 MAC
//$node = (hexdec(substr($node,10);
node = (int.Parse(node.Substring(0,2),NumberStyles.Hexnumber) | 1) + node.Substring(2,10);
}
if (IsNumeric(node))
node = Convert.ToInt64(node).ToString("x"); //sprintf(''%012x'',$node);
var len = node.Length;
if (len > 12)
node = node.Substring(0,12); //substr($node,12);
else if (len < 12)
node += string.Concat(Enumerable.Repeat("0",12 - len));//str_repeat(''0'',12 - $len);
}
else
{
// base node off random sequence
var seqNode = new byte[6];//$node = random_bytes(6);
// set multicast bit not IEEE 802 MAC
seqNode[0] = (byte)((char)node[0] | 1);//$node[0] = chr(ord($node[0]) | 1);
node = Convert.ToInt16(seqNode[0].ToString(),2).ToString("x");//bin2hex($node);
}
return Bin2Hex(time[4].ToString() + time[5].ToString() + time[6].ToString() + time[7].ToString()) // time low
+ ''-''+ Bin2Hex(time[2].ToString() + time[3].ToString()) // time med
+ ''-''+ Bin2Hex(time[0].ToString() + time[1].ToString()) // time hi
+ ''-''+ Bin2Hex(sequence[0].ToString() + sequence[1].ToString()) // seq
+ ''-''+ node; // node
}
private static string Bin2Hex(string value)
{
return Convert.ToInt64(value).ToString("x");
//byte[] bytes = Encoding.GetEncoding(1252).GetBytes(value);
//string hexString = "";
//for (int ii = 0; ii < bytes.Length; ii++)
//{
// hexString += bytes[ii].ToString("x2");
//}
//return hexString;
}
private static byte[] Pack(string hex)
{
hex = hex.Replace("-","");
byte[] raw = new byte[hex.Length / 2];
for (int i = 0; i < raw.Length; i++)
{
raw[i] = Convert.ToByte(hex.Substring(i * 2,16);
}
return raw;
}
private static bool IsNumeric(string value) => value.All(char.IsNumber);
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 端点:
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 表示''
我是 MongoDB 的新手,正在尝试创建一个 Upsert:
public void UpsertRecord<T>(string collectionName,Guid id,T record)
{
var collection = db.GetCollection<T>(collectionName);
var result = collection.ReplaceOne(
new BsonDocument("_id",id),record,new ReplaceOptions { IsUpsert = true });
}
但我在 Visual Studio 中收到以下警告:
''BsonValue.implicit operator BsonValue(Guid) 已过时:使用 BsonBinaryData 构造函数代替并指定 Guid 表示''
任何帮助将不胜感激!
解决方法
我能够通过这种方式修复它:
public void UpsertRecord<T>(string table,Guid id,T record)
{
BsonBinaryData binData = new BsonBinaryData(id,GuidRepresentation.Standard);
var collection = db.GetCollection<T>(table);
var result = collection.ReplaceOne(
new BsonDocument("_id",binData),record,new ReplaceOptions { IsUpsert = true });
}
Flask-SQLAlchemy-SQLite:无法处理 GUID 对象服务器端 - ValueError:格式错误的十六进制 UUID 字符串
如何解决Flask-SQLAlchemy-SQLite:无法处理 GUID 对象服务器端 - ValueError:格式错误的十六进制 UUID 字符串
我正在开发一个小 Flask 应用程序,在那里我有一个 sqlite 模型并使用数据表和 jquery 显示这些数据。我实现了一种用于过滤、搜索和分页的服务器端方法。现在我想使用 uuid.uuid4() 模块将每个表的 id 更改为 GUID 对象。但是当我这样做时,我的服务器端处理文件抛出错误:
File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\models\\model.py",line 41,in process_bind_param
return "%.32x" % uuid.UUID(value).int
File "C:\\Users\\s1056280\\AppData\\Local\\Programs\\Python\\python39\\Lib\\uuid.py",line 177,in __init__
raise ValueError(''badly formed hexadecimal UUID string'')
ValueError: badly formed hexadecimal UUID string
File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\views\\queries.py",line 17,in load_projects
returnTable = ProjectsDataTable(request,Projects).output_result()
File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\util\\table_queries.py",line 15,in __init__
self.run_query()
File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\util\\table_queries.py",line 56,in run_query
self.cardinality_filtered = db.session.query(func.count(str(self.model_object.id))) \\
File "C:\\Users\\s1056280\\Projects\\dev\\proj\\app\\models\\model.py",in __init__
raise ValueError(''badly formed hexadecimal UUID string'')
sqlalchemy.exc.StatementError: (builtins.ValueError) badly formed hexadecimal UUID string
[sql: SELECT count(?) AS count_1
FROM projects
WHERE projects.id LIKE ? OR projects.title LIKE ? OR projects.description LIKE ? OR projects.created_date LIKE ?
LIMIT ? OFFSET ?]
[parameters: [immutabledict({})]]
我的服务器端python脚本如下:
class ProjectsDataTable:
def __init__(self,request,model_object):
self.request = request
self.model_object = model_object
self.cardinality = 0
self.cardinality_filtered = 0
self.results = None
self.run_query()
def output_result(self):
output = {}
output["sEcho"] = int(self.request.args.get(''sEcho''))
output["iTotalRecords"] = self.cardinality
output["iTotaldisplayRecords"] = self.cardinality_filtered
output["aaData"] = self.results
return output
def run_query(self):
self.cardinality = self.model_object.query.count()
#get columns name from request
column_count = int(self.request.args.get(''iColumns''))
column_list = []
for i in range(column_count):
column_name = self.request.args.get(''mDataProp_%d'' % i)
column_list.append(column_name)
#filtering
search_value = self.request.args.get(''sSearch'')
filter_list = []
if search_value != "":
for col in column_list[:-1]:
column_type = getattr(getattr(self.model_object,col),''type'')
print(column_type)
if not isinstance(column_type,db.DateTime):
filter_list.append(getattr(self.model_object,col).like("%" + search_value + "%"))
#sorting
order_column_index = int(self.request.args.get(''iSortCol_0''))
order_column = getattr(self.model_object,column_list[order_column_index])
order_dir = self.request.args.get(''sSortDir_0'')
order_object = getattr(order_column,order_dir)()
#paging
start = self.request.args.get(''idisplayStart'',type=int)
length = self.request.args.get(''idisplayLength'',1,type=int)
items = self.model_object.query.filter(or_).order_by(order_object) \\
.offset(start).limit(length).all()
self.cardinality_filtered = db.session.query(func.count(self.model_object.id)) \\
.filter(or_).order_by(None).first()
self.results = [i.projects_table_to_json for i in items]
模型类本身看起来像这样:
from fastapi_utils.guid_type import GUID,GUID_DEFAULT_sqlITE
class Projects(db.Model):
__tablename__ = ''projects''
id = Column(GUID,primary_key=True,default=GUID_DEFAULT_sqlITE)
title = Column(String(100),unique=False,nullable=False)
description = Column(String(500),nullable=False)
date = Column(Integer,nullable=False)
experiments = relationship("Experiments",backref=''project'',lazy=True)
def __init__(self,title,description,created_date):
self.title = title
self.description = description
self.date= date
@property
def projects_table_to_json(self):
return {
''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 转换导致错误的 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 字符串的相关信息,请在本站寻找。
本文标签: