### 2021-09-12更新

------
#### ryControls    V3.0.2109.1201
- *.[改进]ObjectListView控件的AspectToStringConverter函数新增行数据参数。
- *.[改进]ObjectListView控件的行高默认到25像素。
- *.[改进]ObjectListView控件默认行选择而不是列选择。
- *.[改进]ObjectListView控件新增大量中文注释。
- *.[改进]ObjectListView控件的ShowGroups属性默认值为false。
This commit is contained in:
鑫Intel 2021-09-12 14:54:13 +08:00
parent 14503efbda
commit 83d0e095d5
286 changed files with 69057 additions and 1183 deletions

View File

@ -1416,6 +1416,32 @@
<param name="exe_path"></param>
<returns></returns>
</member>
<member name="M:ryCommon.RySoft.GetVerByVerStr(System.String,System.Double@,System.Double@)">
<summary>
根据版本字符串输出double类型的版本号
</summary>
<param name="ver"></param>
<param name="_softVer"></param>
<param name="_reVer"></param>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.String,System.String)">
<summary>
比较两个版本号大小
</summary>
<param name="oldVer"></param>
<param name="NewVer"></param>
<returns>oldVer小于newVer,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.Double,System.Double,System.Double,System.Double)">
<summary>
比较版本号
</summary>
<param name="_old_softVer"></param>
<param name="_old_reVer"></param>
<param name="_new_softVer"></param>
<param name="_new_reVer"></param>
<returns>old小于new,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.IsAdministrator">
<summary>
判断是否是管理员方式运行
@ -6455,6 +6481,31 @@
<param name="Msg">发送消息</param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int64)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int32)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.UInt32,System.String)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="structSize"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.UInt32,System.Type,System.String)">
<summary>
读共享内存

View File

@ -1,2 +1,2 @@
[Money_Op]
hwnd=602346
hwnd=75948

View File

@ -1,4 +1,4 @@
<root>
<list id="LastUpdateTime" Value="2021/9/3 14:27:07" />
<list id="LastUpdateTime" Value="2021/9/9 8:54:07" />
<list id="UpdateAfterTime" Value="0" />
</root>

View File

@ -14498,22 +14498,26 @@
</summary>
<remarks>
<para>
The contents of the control will be updated immediately after setting this property.
设置此属性后,控件的内容将立即更新。
</para>
<para>This method preserves selection, if possible. Use <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
you do not want to preserve the selection. Preserving selection is the slowest part of this
code and performance is O(n) where n is the number of selected rows.</para>
<para>This method is not thread safe.</para>
<para>The property DOES work on virtual lists: setting is problem-free, but if you try to get it
and the list has 10 million objects, it may take some time to return.</para>
<para>This collection is unfiltered. Use <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> to access just those objects
that survive any installed filters.</para>
<para>如果可能,此方法将保留所选内容。使用 <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
如果您不想保留所选内容,请执行以下操作。
保留选择是该代码中最慢的部分性能为O(N)其中n是选定的行数。</para>
<para>此方法不是线程安全的。</para>
<para>该属性确实适用于虚拟列表:设置是没有问题的,但如果您尝试获取它,
并且列表有1000万个对象则可能需要一些时间才能返回。</para>
<para>此集合未经过筛选。使用 <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> 只访问那些在任何已安装的筛选器中幸存下来的对象。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsList">
<summary>
获取当前控件所有对象组成的列表
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsForClustering">
<summary>
Gets the collection of objects that will be considered when creating clusters
(which are used to generate Excel-like column filters)
获取创建群集时将考虑的对象集合。
(用于生成类似Excel的列筛选器)
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.OverlayImage">
@ -14647,18 +14651,17 @@
<remarks>SelectColumnsOnRightClickBehaviour设置为InlineMenu时才有效。当行为设置为SubMenu菜单时该选项不起作用。</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedColumn">
<summary>
Gets or sets the column that is drawn with a slight tint.
</summary>
<remarks>
<para>
If TintSortColumn is true, the sort column will automatically
be made the selected column.
</para>
<para>
The colour of the tint is controlled by SelectedColumnTint.
</para>
</remarks>
<summary>
获取或设置选定列
</summary>
<remarks>
<para>
如果TintSortColumn为true则排序列将自动成为选定列。
</para>
<para>
色调的颜色由SelectedColumnTint控制。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedRowDecoration">
<summary>
@ -14996,12 +14999,11 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.BooleanCheckStateGetter">
<summary>
This delegate fetches the checkedness of an object as a boolean only.
此委托仅将对象的检查性作为布尔值获取。
</summary>
<remarks>Use this if you never want to worry about the
Indeterminate state (which is fairly common).
<remarks>如果您永远不想担心不确定状态(这是相当常见的),请使用此选项。
<para>
This is a convenience wrapper around the CheckStateGetter property.
这是CheckStateGetter属性的便捷包装。
</para>
</remarks>
</member>
@ -15019,7 +15021,7 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanShowGroups">
<summary>
Gets whether or not this listview is capabale of showing groups
获取此列表视图是否能够显示组
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanUseApplicationIdle">
@ -15057,20 +15059,17 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckedAspectName">
<summary>
The name of the property (or field) that holds whether or not a model is checked.
保存是否选中模型的属性(或字段)的名称。
</summary>
<remarks>
<para>The property be modifiable. It must have a return type of bool (or of bool? if
TriStateCheckBoxes is true).</para>
<para>Setting this property replaces any CheckStateGetter or CheckStatePutter that have been installed.
Conversely, later setting the CheckStateGetter or CheckStatePutter properties will take precedence
over the behavior of this property.</para>
<para>该属性是可修改的。它必须具有bool(或bool)返回类型。如果TriStateCheckBooks为真)。</para>
<para>设置此属性将替换任何已安装的CheckStateGetter或CheckStatePutter。
相反稍后设置CheckStateGetter或CheckStatePutter属性将优先于此属性的行为。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckStateGetter">
<summary>
This delegate will be called whenever the ObjectListView needs to know the check state
of the row associated with a given model object.
只要ObjectListView需要知道与给定模型对象关联的行的检查状态就会调用此委托。
</summary>
<remarks>
<para>.NET has no support for indeterminate values, but as of v2.0, this class allows
@ -15085,20 +15084,19 @@
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CustomSorter">
<summary>
This delegate can be used to sort the table in a custom fasion.
</summary>
<remarks>
<para>
The delegate must install a ListViewItemSorter on the ObjectListView.
Installing the ItemSorter does the actual work of sorting the ListViewItems.
See ColumnComparer in the code for an example of what an ItemSorter has to do.
</para>
<para>
Do not install a CustomSorter on a VirtualObjectListView. Override the SortObjects()
method of the IVirtualListDataSource instead.
</para>
</remarks>
<summary>
此委托可用于以自定义方式对表进行排序。
</summary>
<remarks>
<para>
委托必须在ObjectListView上安装ListViewItemSorter。
安装ItemSorter会执行对ListViewItems进行排序的实际工作。
有关ItemSorter必须执行的操作的示例请参见代码中的ColumnCompeller。
</para>
<para>
请勿在VirtualObjectListView上安装CustomSorter。改为重写IVirtualListDataSource的SortObjects()方法。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.HeaderToolTipGetter">
<summary>
@ -15132,77 +15130,69 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObject(System.Object)">
<summary>
Add the given model object to this control.
将给定的模型对象添加到此控件。
</summary>
<param name="modelObject">The model object to be displayed</param>
<param name="modelObject">要显示的模型对象</param>
<remarks>See AddObjects() for more details</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObjects(System.Collections.ICollection)">
<summary>
Add the given collection of model objects to this control.
将给定的模型对象集合添加到此控件。
</summary>
<param name="modelObjects">A collection of model objects</param>
<param name="modelObjects">要显示的模型对象集合</param>
<remarks>
<para>The added objects will appear in their correct sort position, if sorting
is active (i.e. if PrimarySortColumn is not null). Otherwise, they will appear at the end of the list.</para>
<para>No check is performed to see if any of the objects are already in the ListView.</para>
<para>Null objects are silently ignored.</para>
<para>如果排序处于活动状态(即如果PrimarySortColumn不为空),则添加的对象将出现在其正确的排序位置。否则,它们将出现在列表的末尾。</para>
<para>不执行任何检查以查看是否有任何对象已在ListView中。</para>
<para>空对象将被静默忽略。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns">
<summary>
Resize the columns to the maximum of the header width and the data.
将列的大小调整到页眉宽度和数据的最大值。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoSizeColumns">
<summary>
Set up any automatically initialized column widths (columns that
have a width of 0 or -1 will be resized to the width of their
contents or header respectively).
</summary>
<remarks>
Obviously, this will only work once. Once it runs, the columns widths will
be changed to something else (other than 0 or -1), so it wont do anything the
second time through. Use <see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/> to force all columns
to change their size.
</remarks>
<summary>
设置任何自动初始化的列宽(宽度为0或-1的列将分别调整为其内容或标题的宽度)。
</summary>
<remarks>
显然,这只会起作用一次。一旦运行,列宽将更改为其他值(不是0或-1),因此第二次运行时不会执行任何操作。
若要强制所有列更改其大小,请使用<see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups">
<summary>
Organise the view items into groups, based on the last sort column or the first column
if there is no last sort column
根据最后一个排序列或第一列(如果没有最后一个排序列)将视图项组织到组中
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given column
根据给定列将视图项组织成组
</summary>
<remarks>
<para>
If the AlwaysGroupByColumn property is not null,
the list view items will be organisd by that column,
and the 'column' parameter will be ignored.
如果AlwaysGroupByColumn属性不为Null则列表视图项将按该列组织并且将忽略Column参数。
</para>
<para>This method triggers sorting events: BeforeSorting and AfterSorting.</para>
<para>此方法触发排序事件BeforeSorting和AfterSorting。</para>
</remarks>
<param name="column">The column whose values should be used for sorting.</param>
<param name="column">其值应用于排序的列。</param>
<param name="order"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given columns
根据给定列将视图项组织成组
</summary>
<param name="groupByColumn">What column will be used for grouping</param>
<param name="groupByOrder">What ordering will be used for groups</param>
<param name="column">The column whose values should be used for sorting. Cannot be null</param>
<param name="order">The order in which the values from column will be sorted</param>
<param name="secondaryColumn">When the values from 'column' are equal, use the values provided by this column</param>
<param name="secondaryOrder">How will the secondary values be sorted</param>
<remarks>This method does not trigger sorting events. Use BuildGroups() to do that</remarks>
<param name="groupByColumn">将使用哪一列进行分组</param>
<param name="groupByOrder">组将使用什么顺序</param>
<param name="column">其值应用于排序的列。不能为空</param>
<param name="order">列中值的排序顺序</param>
<param name="secondaryColumn">column中的值相等时请使用此列提供的值</param>
<param name="secondaryOrder">次级值将如何排序</param>
<remarks>此方法不会触发排序事件。使用BuildGroups()执行此操作</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CollectGroupingParameters(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Collect and return all the variables that influence the creation of groups
收集并返回影响组创建的所有变量
</summary>
<returns></returns>
</member>
@ -15217,12 +15207,12 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList">
<summary>
Build/rebuild all the list view items in the list, preserving as much state as is possible
生成/重新生成列表中的所有列表视图项,尽可能多地保留状态
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList(System.Boolean)">
<summary>
Build/rebuild all the list view items in the list
生成/重新生成列表中的所有列表视图项
</summary>
<param name="shouldPreserveState">If this is true, the control will try to preserve the selection,
focused item, and the scroll position (see Remarks)
@ -15236,7 +15226,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearCachedInfo">
<summary>
Clear any cached info this list may have been using
清除此列表可能一直在使用的所有缓存信息
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ApplyExtendedStyles">
@ -15277,79 +15267,79 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearUrlVisited">
<summary>
Reset the memory of which URLs have been visited
重置已访问其URL的内存
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopySelectionToClipboard">
<summary>
Copy a text and html representation of the selected rows onto the clipboard.
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
<summary>
将选定行的文本和HTML表示复制到剪贴板上。
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopyObjectsToClipboard(System.Collections.IList)">
<summary>
Copy a text and html representation of the given objects onto the clipboard.
将给定对象的文本和HTML表示复制到剪贴板上。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ObjectsToHtml(System.Collections.IList)">
<summary>
Return a html representation of the given objects
返回给定对象的html表示形式
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.DeselectAll">
<summary>
Deselect all rows in the listview
取消选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNextItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately after the given item.
If the given item is null, the first item in the list will be returned.
Return null if the given item is the last item.
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
<summary>
返回紧跟在给定项后面的ListViewItem。
如果给定项为空,则返回列表中的第一个项。
如果给定项是最后一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetLastItemInDisplayOrder">
<summary>
Return the last item in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<returns></returns>
<summary>
按向用户显示的顺序返回最后一项。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNthItemInDisplayOrder(System.Int32)">
<summary>
Return the n'th item (0-based) in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="n"></param>
<returns></returns>
<summary>
按向用户显示的顺序返回第n项(从0开始)。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="n"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetDisplayOrderOfItemIndex(System.Int32)">
<summary>
Return the display index of the given listviewitem index.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="itemIndex"></param>
<returns></returns>
<summary>
返回给定listviewitem索引的显示索引。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="itemIndex"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetPreviousItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately before the given item.
If the given item is null, the last item in the list will be returned.
Return null if the given item is the first item.
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
<summary>
返回紧接在给定项之前出现的ListViewItem。
如果给定项为空,则返回列表中的最后一项。
如果给定项是第一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.InsertObjects(System.Int32,System.Collections.ICollection)">
<summary>
Insert the given collection of objects before the given position
在给定位置之前插入给定的对象集合
</summary>
<param name="index">Where to insert the objects</param>
<param name="modelObjects">The objects to be inserted</param>
@ -15364,21 +15354,21 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsSelected(System.Object)">
<summary>
Return true if the row representing the given model is selected
如果选择了表示给定模型的行则返回TRUE
</summary>
<param name="model">The model object to look for</param>
<returns>Is the row selected</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsUrlVisited(System.String)">
<summary>
Has the given URL been visited?
给定的URL是否已被访问
</summary>
<param name="url">The string to be consider</param>
<returns>Has it been visited</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelScroll(System.Int32,System.Int32)">
<summary>
Scroll the ListView by the given deltas.
按给定的值增量滚动ListView。
</summary>
<param name="dx">Horizontal delta</param>
<param name="dy">Vertical delta</param>
@ -15389,32 +15379,32 @@
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MarkUrlVisited(System.String)">
<summary>
Remember that the given URL has been visited
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
<summary>
记住给定的URL已被访问
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MoveObjects(System.Int32,System.Collections.ICollection)">
<summary>
Move the given collection of objects to the given index.
将给定的对象集合移动到给定的索引。
</summary>
<remarks>This operation only makes sense on non-grouped ObjectListViews.</remarks>
<remarks>此操作仅对未分组的ObjectListViews有意义。</remarks>
<param name="index"></param>
<param name="modelObjects"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.HitTest(System.Int32,System.Int32)">
<summary>
Calculate what item is under the given point?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
<summary>
计算在给定点下的项目是什么?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelHitTest(System.Int32,System.Int32)">
<summary>
Perform a hit test using the Windows control's SUBITEMHITTEST message.
This provides information about group hits that the standard ListView.HitTest() does not.
使用Windows控件的SUBITEMHITTEST消息执行点击测试。
这提供了标准ListView.HitTest()不提供的有关组点击的信息。
</summary>
<param name="x"></param>
<param name="y"></param>
@ -15459,7 +15449,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObject(System.Object)">
<summary>
Remove the given model object from the ListView
从ListView中删除给定的模型对象
</summary>
<param name="modelObject">The model to be removed</param>
<remarks>See RemoveObjects() for more details
@ -15467,58 +15457,56 @@
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)">
<summary>
Remove all of the given objects from the control.
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
<summary>
从控件中移除所有给定对象。
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SelectAll">
<summary>
Select all rows in the listview
选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)">
<summary>
Set the given image to be fixed in the bottom right of the list view.
This image will not scroll when the list view scrolls.
</summary>
<remarks>
<para>
This method uses ListView's native ability to display a background image.
It has a few limitations:
</para>
<list type="bullet">
<item><description>It doesn't work well with owner drawn mode. In owner drawn mode, each cell draws itself,
including its background, which covers the background image.</description></item>
<item><description>It doesn't look very good when grid lines are enabled, since the grid lines are drawn over the image.</description></item>
<item><description>It does not work at all on XP.</description></item>
<item><description>Obviously, it doesn't look good when alternate row background colors are enabled.</description></item>
</list>
<para>
If you can live with these limitations, native watermarks are quite neat. They are true backgrounds, not
translucent overlays like the OverlayImage uses. They also have the decided advantage over overlays in that
they work correctly even in MDI applications.
</para>
<para>Setting this clears any background image.</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<summary>
在列表视图的右下角设置要固定的给定图像。
当列表视图滚动时,此图像不会滚动。
</summary>
<remarks>
<para>
此方法使用ListView的原生功能显示背景图像。
它有几个限制:
</para>
<list type="bullet">
<item><description>它在owner drawn模式下不能很好地工作。在owner drawn绘制模式下
每个单元格都会绘制自身,包括覆盖背景图像的背景。</description></item>
<item><description>启用网格线时看起来不是很好,因为网格线是在图像上绘制的。</description></item>
<item><description>它在XP上完全不起作用。</description></item>
<item><description>显然,当启用交替行背景色时,效果不佳。</description></item>
</list>
<para>
如果你能忍受这些限制,原生水印就相当不错了。
它们是真实的背景而不是像OverlayImage使用的半透明覆盖。
与覆盖相比它们也有明显的优势因为即使在MDI应用程序中它们也可以正常工作。
</para>
<para>设置此选项将清除所有背景图像。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)">
<summary>
Set the given image to be background of the ListView so that it appears at the given
percentage offsets within the list.
将给定的图像设置为ListView的背景以便它在列表中以给定的百分比偏移量显示。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>. Make sure those limitations
are understood before using the method.</para>
<para>This is very similar to setting the <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> property of the standard .NET ListView, except that the standard
BackgroundImage does not handle images with transparent areas properly -- it renders transparent areas as black. This
method does not have that problem.</para>
<para>Setting this clears any background watermark.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>中所述的相同限制.
在使用该方法之前,请确保了解这些限制。</para>
<para>这非常类似于 <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> 属性,
但标准Backround Image不能正确处理具有透明区域的图像--它将透明区域呈现为黑色。这种方法没有这个问题。</para>
<para>设置此选项将清除所有背景水印。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="xOffset">The horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right.</param>
@ -15526,64 +15514,63 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundTiledImage(System.Drawing.Image)">
<summary>
Set the given image to be the tiled background of the ListView.
将给定图像设置为ListView的平铺背景。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/> and <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/>.
Make sure those limitations
are understood before using the method.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/><see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/> 相同的限制.
在使用该方法之前,请确保了解这些限制。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="image">要绘制的图像。如果为null则将删除所有现有图像。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法。</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法.</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
<param name="preserveState">Should the state of the list be preserved as far as is possible.</param>
<param name="preserveState">是否应尽可能保留列表的状态。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObject(System.Object)">
<summary>
Update the given model object into the ListView. The model will be added if it doesn't already exist.
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>This method is thread-safe.</para>
<para>This method will cause the list to be resorted.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
将给定的模型对象更新到ListView中。
如果该模型尚不存在,则会添加该模型。
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>此方法是线程安全的。</para>
<para>此方法将导致重新排序列表。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObjects(System.Collections.ICollection)">
<summary>
Update the pre-existing models that are equal to the given objects. If any of the model doesn't
already exist in the control, they will be added.
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>This method will cause the list to be resorted.</para>
<para>Nulls are silently ignored.</para>
<para>This method is thread-safe.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
更新与给定对象相等的预先存在的模型。
如果控件中不存在任何模型,则会添加它们。
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>此方法将导致重新排序列表。</para>
<para>null值将被静默忽略。</para>
<para>此方法是线程安全的。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateNotificationSubscriptions(System.Collections.IEnumerable)">
<summary>
Change any subscriptions to INotifyPropertyChanged events on our current
model objects so that we no longer listen for events on the old models
and do listen for events on the given collection.
更改当前模型对象上对INotifyPropertyChanged事件的任何订阅
以便我们不再侦听旧模型上的事件,而侦听给定集合上的事件。
</summary>
<remarks>This does nothing if UseNotifyPropertyChanged is false.</remarks>
<param name="collection"></param>
@ -16607,7 +16594,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetCellToolTip(System.Int32,System.Int32)">
<summary>
Return the tooltip that should be shown when the mouse is hovered over the given cell
返回当鼠标悬停在给定单元格上时应显示的工具提示
</summary>
<param name="columnIndex">The column index whose tool tip is to be fetched</param>
<param name="rowIndex">The row index whose tool tip is to be fetched</param>
@ -16615,7 +16602,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ModelToItem(System.Object)">
<summary>
Return the OLVListItem that displays the given model object
返回显示给定模型对象的OLVListItem
</summary>
<param name="modelObject">The modelObject whose item is to be found</param>
<returns>The OLVListItem that displays the model, or null</returns>
@ -16633,7 +16620,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.PrepareAlternateBackColors">
<summary>
Prepare the listview to show alternate row backcolors
准备列表视图以显示交替的行背景色
</summary>
<remarks>We cannot rely on lvi.Index in this method.
In a straight list, lvi.Index is the display index, and can be used to determine
@ -16648,7 +16635,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetSubItemImages(System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Tell the underlying list control which images to show against the subitems
告诉基础列表控件针对子项显示哪些图像
</summary>
<param name="rowIndex">the index at which the item occurs</param>
<param name="item">the item whose subitems are to be set</param>
@ -16687,7 +16674,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatRowEvent(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatRow and possibly FormatCell events for the given item
触发给定项目的FormatRow和可能的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -16695,7 +16682,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatCellEvents(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatCell events for the given item
触发给定项目的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -22335,6 +22322,20 @@
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.ValueToString(System.Object,System.Object)">
<summary>
Convert the aspect object to its string representation.
</summary>
<remarks>
If the column has been given a AspectToStringConverter, that will be used to do
the conversion, otherwise just use ToString().
The returned value will not be null. Nulls are always converted
to empty strings.
</remarks>
<param name = "rowobject" ></param>
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.DecideDefaultClusteringStrategy">
<summary>
Decide the clustering strategy that will be used for this column

View File

@ -1416,6 +1416,32 @@
<param name="exe_path"></param>
<returns></returns>
</member>
<member name="M:ryCommon.RySoft.GetVerByVerStr(System.String,System.Double@,System.Double@)">
<summary>
根据版本字符串输出double类型的版本号
</summary>
<param name="ver"></param>
<param name="_softVer"></param>
<param name="_reVer"></param>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.String,System.String)">
<summary>
比较两个版本号大小
</summary>
<param name="oldVer"></param>
<param name="NewVer"></param>
<returns>oldVer小于newVer,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.Double,System.Double,System.Double,System.Double)">
<summary>
比较版本号
</summary>
<param name="_old_softVer"></param>
<param name="_old_reVer"></param>
<param name="_new_softVer"></param>
<param name="_new_reVer"></param>
<returns>old小于new,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.IsAdministrator">
<summary>
判断是否是管理员方式运行
@ -6455,6 +6481,31 @@
<param name="Msg">发送消息</param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int64)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int32)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.UInt32,System.String)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="structSize"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.UInt32,System.Type,System.String)">
<summary>
读共享内存

View File

@ -14498,22 +14498,26 @@
</summary>
<remarks>
<para>
The contents of the control will be updated immediately after setting this property.
设置此属性后,控件的内容将立即更新。
</para>
<para>This method preserves selection, if possible. Use <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
you do not want to preserve the selection. Preserving selection is the slowest part of this
code and performance is O(n) where n is the number of selected rows.</para>
<para>This method is not thread safe.</para>
<para>The property DOES work on virtual lists: setting is problem-free, but if you try to get it
and the list has 10 million objects, it may take some time to return.</para>
<para>This collection is unfiltered. Use <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> to access just those objects
that survive any installed filters.</para>
<para>如果可能,此方法将保留所选内容。使用 <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
如果您不想保留所选内容,请执行以下操作。
保留选择是该代码中最慢的部分性能为O(N)其中n是选定的行数。</para>
<para>此方法不是线程安全的。</para>
<para>该属性确实适用于虚拟列表:设置是没有问题的,但如果您尝试获取它,
并且列表有1000万个对象则可能需要一些时间才能返回。</para>
<para>此集合未经过筛选。使用 <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> 只访问那些在任何已安装的筛选器中幸存下来的对象。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsList">
<summary>
获取当前控件所有对象组成的列表
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsForClustering">
<summary>
Gets the collection of objects that will be considered when creating clusters
(which are used to generate Excel-like column filters)
获取创建群集时将考虑的对象集合。
(用于生成类似Excel的列筛选器)
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.OverlayImage">
@ -14647,18 +14651,17 @@
<remarks>SelectColumnsOnRightClickBehaviour设置为InlineMenu时才有效。当行为设置为SubMenu菜单时该选项不起作用。</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedColumn">
<summary>
Gets or sets the column that is drawn with a slight tint.
</summary>
<remarks>
<para>
If TintSortColumn is true, the sort column will automatically
be made the selected column.
</para>
<para>
The colour of the tint is controlled by SelectedColumnTint.
</para>
</remarks>
<summary>
获取或设置选定列
</summary>
<remarks>
<para>
如果TintSortColumn为true则排序列将自动成为选定列。
</para>
<para>
色调的颜色由SelectedColumnTint控制。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedRowDecoration">
<summary>
@ -14996,12 +14999,11 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.BooleanCheckStateGetter">
<summary>
This delegate fetches the checkedness of an object as a boolean only.
此委托仅将对象的检查性作为布尔值获取。
</summary>
<remarks>Use this if you never want to worry about the
Indeterminate state (which is fairly common).
<remarks>如果您永远不想担心不确定状态(这是相当常见的),请使用此选项。
<para>
This is a convenience wrapper around the CheckStateGetter property.
这是CheckStateGetter属性的便捷包装。
</para>
</remarks>
</member>
@ -15019,7 +15021,7 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanShowGroups">
<summary>
Gets whether or not this listview is capabale of showing groups
获取此列表视图是否能够显示组
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanUseApplicationIdle">
@ -15057,20 +15059,17 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckedAspectName">
<summary>
The name of the property (or field) that holds whether or not a model is checked.
保存是否选中模型的属性(或字段)的名称。
</summary>
<remarks>
<para>The property be modifiable. It must have a return type of bool (or of bool? if
TriStateCheckBoxes is true).</para>
<para>Setting this property replaces any CheckStateGetter or CheckStatePutter that have been installed.
Conversely, later setting the CheckStateGetter or CheckStatePutter properties will take precedence
over the behavior of this property.</para>
<para>该属性是可修改的。它必须具有bool(或bool)返回类型。如果TriStateCheckBooks为真)。</para>
<para>设置此属性将替换任何已安装的CheckStateGetter或CheckStatePutter。
相反稍后设置CheckStateGetter或CheckStatePutter属性将优先于此属性的行为。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckStateGetter">
<summary>
This delegate will be called whenever the ObjectListView needs to know the check state
of the row associated with a given model object.
只要ObjectListView需要知道与给定模型对象关联的行的检查状态就会调用此委托。
</summary>
<remarks>
<para>.NET has no support for indeterminate values, but as of v2.0, this class allows
@ -15085,20 +15084,19 @@
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CustomSorter">
<summary>
This delegate can be used to sort the table in a custom fasion.
</summary>
<remarks>
<para>
The delegate must install a ListViewItemSorter on the ObjectListView.
Installing the ItemSorter does the actual work of sorting the ListViewItems.
See ColumnComparer in the code for an example of what an ItemSorter has to do.
</para>
<para>
Do not install a CustomSorter on a VirtualObjectListView. Override the SortObjects()
method of the IVirtualListDataSource instead.
</para>
</remarks>
<summary>
此委托可用于以自定义方式对表进行排序。
</summary>
<remarks>
<para>
委托必须在ObjectListView上安装ListViewItemSorter。
安装ItemSorter会执行对ListViewItems进行排序的实际工作。
有关ItemSorter必须执行的操作的示例请参见代码中的ColumnCompeller。
</para>
<para>
请勿在VirtualObjectListView上安装CustomSorter。改为重写IVirtualListDataSource的SortObjects()方法。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.HeaderToolTipGetter">
<summary>
@ -15132,77 +15130,69 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObject(System.Object)">
<summary>
Add the given model object to this control.
将给定的模型对象添加到此控件。
</summary>
<param name="modelObject">The model object to be displayed</param>
<param name="modelObject">要显示的模型对象</param>
<remarks>See AddObjects() for more details</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObjects(System.Collections.ICollection)">
<summary>
Add the given collection of model objects to this control.
将给定的模型对象集合添加到此控件。
</summary>
<param name="modelObjects">A collection of model objects</param>
<param name="modelObjects">要显示的模型对象集合</param>
<remarks>
<para>The added objects will appear in their correct sort position, if sorting
is active (i.e. if PrimarySortColumn is not null). Otherwise, they will appear at the end of the list.</para>
<para>No check is performed to see if any of the objects are already in the ListView.</para>
<para>Null objects are silently ignored.</para>
<para>如果排序处于活动状态(即如果PrimarySortColumn不为空),则添加的对象将出现在其正确的排序位置。否则,它们将出现在列表的末尾。</para>
<para>不执行任何检查以查看是否有任何对象已在ListView中。</para>
<para>空对象将被静默忽略。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns">
<summary>
Resize the columns to the maximum of the header width and the data.
将列的大小调整到页眉宽度和数据的最大值。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoSizeColumns">
<summary>
Set up any automatically initialized column widths (columns that
have a width of 0 or -1 will be resized to the width of their
contents or header respectively).
</summary>
<remarks>
Obviously, this will only work once. Once it runs, the columns widths will
be changed to something else (other than 0 or -1), so it wont do anything the
second time through. Use <see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/> to force all columns
to change their size.
</remarks>
<summary>
设置任何自动初始化的列宽(宽度为0或-1的列将分别调整为其内容或标题的宽度)。
</summary>
<remarks>
显然,这只会起作用一次。一旦运行,列宽将更改为其他值(不是0或-1),因此第二次运行时不会执行任何操作。
若要强制所有列更改其大小,请使用<see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups">
<summary>
Organise the view items into groups, based on the last sort column or the first column
if there is no last sort column
根据最后一个排序列或第一列(如果没有最后一个排序列)将视图项组织到组中
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given column
根据给定列将视图项组织成组
</summary>
<remarks>
<para>
If the AlwaysGroupByColumn property is not null,
the list view items will be organisd by that column,
and the 'column' parameter will be ignored.
如果AlwaysGroupByColumn属性不为Null则列表视图项将按该列组织并且将忽略Column参数。
</para>
<para>This method triggers sorting events: BeforeSorting and AfterSorting.</para>
<para>此方法触发排序事件BeforeSorting和AfterSorting。</para>
</remarks>
<param name="column">The column whose values should be used for sorting.</param>
<param name="column">其值应用于排序的列。</param>
<param name="order"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given columns
根据给定列将视图项组织成组
</summary>
<param name="groupByColumn">What column will be used for grouping</param>
<param name="groupByOrder">What ordering will be used for groups</param>
<param name="column">The column whose values should be used for sorting. Cannot be null</param>
<param name="order">The order in which the values from column will be sorted</param>
<param name="secondaryColumn">When the values from 'column' are equal, use the values provided by this column</param>
<param name="secondaryOrder">How will the secondary values be sorted</param>
<remarks>This method does not trigger sorting events. Use BuildGroups() to do that</remarks>
<param name="groupByColumn">将使用哪一列进行分组</param>
<param name="groupByOrder">组将使用什么顺序</param>
<param name="column">其值应用于排序的列。不能为空</param>
<param name="order">列中值的排序顺序</param>
<param name="secondaryColumn">column中的值相等时请使用此列提供的值</param>
<param name="secondaryOrder">次级值将如何排序</param>
<remarks>此方法不会触发排序事件。使用BuildGroups()执行此操作</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CollectGroupingParameters(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Collect and return all the variables that influence the creation of groups
收集并返回影响组创建的所有变量
</summary>
<returns></returns>
</member>
@ -15217,12 +15207,12 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList">
<summary>
Build/rebuild all the list view items in the list, preserving as much state as is possible
生成/重新生成列表中的所有列表视图项,尽可能多地保留状态
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList(System.Boolean)">
<summary>
Build/rebuild all the list view items in the list
生成/重新生成列表中的所有列表视图项
</summary>
<param name="shouldPreserveState">If this is true, the control will try to preserve the selection,
focused item, and the scroll position (see Remarks)
@ -15236,7 +15226,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearCachedInfo">
<summary>
Clear any cached info this list may have been using
清除此列表可能一直在使用的所有缓存信息
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ApplyExtendedStyles">
@ -15277,79 +15267,79 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearUrlVisited">
<summary>
Reset the memory of which URLs have been visited
重置已访问其URL的内存
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopySelectionToClipboard">
<summary>
Copy a text and html representation of the selected rows onto the clipboard.
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
<summary>
将选定行的文本和HTML表示复制到剪贴板上。
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopyObjectsToClipboard(System.Collections.IList)">
<summary>
Copy a text and html representation of the given objects onto the clipboard.
将给定对象的文本和HTML表示复制到剪贴板上。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ObjectsToHtml(System.Collections.IList)">
<summary>
Return a html representation of the given objects
返回给定对象的html表示形式
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.DeselectAll">
<summary>
Deselect all rows in the listview
取消选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNextItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately after the given item.
If the given item is null, the first item in the list will be returned.
Return null if the given item is the last item.
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
<summary>
返回紧跟在给定项后面的ListViewItem。
如果给定项为空,则返回列表中的第一个项。
如果给定项是最后一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetLastItemInDisplayOrder">
<summary>
Return the last item in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<returns></returns>
<summary>
按向用户显示的顺序返回最后一项。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNthItemInDisplayOrder(System.Int32)">
<summary>
Return the n'th item (0-based) in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="n"></param>
<returns></returns>
<summary>
按向用户显示的顺序返回第n项(从0开始)。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="n"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetDisplayOrderOfItemIndex(System.Int32)">
<summary>
Return the display index of the given listviewitem index.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="itemIndex"></param>
<returns></returns>
<summary>
返回给定listviewitem索引的显示索引。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="itemIndex"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetPreviousItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately before the given item.
If the given item is null, the last item in the list will be returned.
Return null if the given item is the first item.
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
<summary>
返回紧接在给定项之前出现的ListViewItem。
如果给定项为空,则返回列表中的最后一项。
如果给定项是第一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.InsertObjects(System.Int32,System.Collections.ICollection)">
<summary>
Insert the given collection of objects before the given position
在给定位置之前插入给定的对象集合
</summary>
<param name="index">Where to insert the objects</param>
<param name="modelObjects">The objects to be inserted</param>
@ -15364,21 +15354,21 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsSelected(System.Object)">
<summary>
Return true if the row representing the given model is selected
如果选择了表示给定模型的行则返回TRUE
</summary>
<param name="model">The model object to look for</param>
<returns>Is the row selected</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsUrlVisited(System.String)">
<summary>
Has the given URL been visited?
给定的URL是否已被访问
</summary>
<param name="url">The string to be consider</param>
<returns>Has it been visited</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelScroll(System.Int32,System.Int32)">
<summary>
Scroll the ListView by the given deltas.
按给定的值增量滚动ListView。
</summary>
<param name="dx">Horizontal delta</param>
<param name="dy">Vertical delta</param>
@ -15389,32 +15379,32 @@
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MarkUrlVisited(System.String)">
<summary>
Remember that the given URL has been visited
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
<summary>
记住给定的URL已被访问
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MoveObjects(System.Int32,System.Collections.ICollection)">
<summary>
Move the given collection of objects to the given index.
将给定的对象集合移动到给定的索引。
</summary>
<remarks>This operation only makes sense on non-grouped ObjectListViews.</remarks>
<remarks>此操作仅对未分组的ObjectListViews有意义。</remarks>
<param name="index"></param>
<param name="modelObjects"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.HitTest(System.Int32,System.Int32)">
<summary>
Calculate what item is under the given point?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
<summary>
计算在给定点下的项目是什么?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelHitTest(System.Int32,System.Int32)">
<summary>
Perform a hit test using the Windows control's SUBITEMHITTEST message.
This provides information about group hits that the standard ListView.HitTest() does not.
使用Windows控件的SUBITEMHITTEST消息执行点击测试。
这提供了标准ListView.HitTest()不提供的有关组点击的信息。
</summary>
<param name="x"></param>
<param name="y"></param>
@ -15459,7 +15449,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObject(System.Object)">
<summary>
Remove the given model object from the ListView
从ListView中删除给定的模型对象
</summary>
<param name="modelObject">The model to be removed</param>
<remarks>See RemoveObjects() for more details
@ -15467,58 +15457,56 @@
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)">
<summary>
Remove all of the given objects from the control.
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
<summary>
从控件中移除所有给定对象。
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SelectAll">
<summary>
Select all rows in the listview
选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)">
<summary>
Set the given image to be fixed in the bottom right of the list view.
This image will not scroll when the list view scrolls.
</summary>
<remarks>
<para>
This method uses ListView's native ability to display a background image.
It has a few limitations:
</para>
<list type="bullet">
<item><description>It doesn't work well with owner drawn mode. In owner drawn mode, each cell draws itself,
including its background, which covers the background image.</description></item>
<item><description>It doesn't look very good when grid lines are enabled, since the grid lines are drawn over the image.</description></item>
<item><description>It does not work at all on XP.</description></item>
<item><description>Obviously, it doesn't look good when alternate row background colors are enabled.</description></item>
</list>
<para>
If you can live with these limitations, native watermarks are quite neat. They are true backgrounds, not
translucent overlays like the OverlayImage uses. They also have the decided advantage over overlays in that
they work correctly even in MDI applications.
</para>
<para>Setting this clears any background image.</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<summary>
在列表视图的右下角设置要固定的给定图像。
当列表视图滚动时,此图像不会滚动。
</summary>
<remarks>
<para>
此方法使用ListView的原生功能显示背景图像。
它有几个限制:
</para>
<list type="bullet">
<item><description>它在owner drawn模式下不能很好地工作。在owner drawn绘制模式下
每个单元格都会绘制自身,包括覆盖背景图像的背景。</description></item>
<item><description>启用网格线时看起来不是很好,因为网格线是在图像上绘制的。</description></item>
<item><description>它在XP上完全不起作用。</description></item>
<item><description>显然,当启用交替行背景色时,效果不佳。</description></item>
</list>
<para>
如果你能忍受这些限制,原生水印就相当不错了。
它们是真实的背景而不是像OverlayImage使用的半透明覆盖。
与覆盖相比它们也有明显的优势因为即使在MDI应用程序中它们也可以正常工作。
</para>
<para>设置此选项将清除所有背景图像。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)">
<summary>
Set the given image to be background of the ListView so that it appears at the given
percentage offsets within the list.
将给定的图像设置为ListView的背景以便它在列表中以给定的百分比偏移量显示。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>. Make sure those limitations
are understood before using the method.</para>
<para>This is very similar to setting the <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> property of the standard .NET ListView, except that the standard
BackgroundImage does not handle images with transparent areas properly -- it renders transparent areas as black. This
method does not have that problem.</para>
<para>Setting this clears any background watermark.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>中所述的相同限制.
在使用该方法之前,请确保了解这些限制。</para>
<para>这非常类似于 <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> 属性,
但标准Backround Image不能正确处理具有透明区域的图像--它将透明区域呈现为黑色。这种方法没有这个问题。</para>
<para>设置此选项将清除所有背景水印。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="xOffset">The horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right.</param>
@ -15526,64 +15514,63 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundTiledImage(System.Drawing.Image)">
<summary>
Set the given image to be the tiled background of the ListView.
将给定图像设置为ListView的平铺背景。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/> and <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/>.
Make sure those limitations
are understood before using the method.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/><see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/> 相同的限制.
在使用该方法之前,请确保了解这些限制。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="image">要绘制的图像。如果为null则将删除所有现有图像。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法。</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法.</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
<param name="preserveState">Should the state of the list be preserved as far as is possible.</param>
<param name="preserveState">是否应尽可能保留列表的状态。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObject(System.Object)">
<summary>
Update the given model object into the ListView. The model will be added if it doesn't already exist.
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>This method is thread-safe.</para>
<para>This method will cause the list to be resorted.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
将给定的模型对象更新到ListView中。
如果该模型尚不存在,则会添加该模型。
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>此方法是线程安全的。</para>
<para>此方法将导致重新排序列表。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObjects(System.Collections.ICollection)">
<summary>
Update the pre-existing models that are equal to the given objects. If any of the model doesn't
already exist in the control, they will be added.
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>This method will cause the list to be resorted.</para>
<para>Nulls are silently ignored.</para>
<para>This method is thread-safe.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
更新与给定对象相等的预先存在的模型。
如果控件中不存在任何模型,则会添加它们。
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>此方法将导致重新排序列表。</para>
<para>null值将被静默忽略。</para>
<para>此方法是线程安全的。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateNotificationSubscriptions(System.Collections.IEnumerable)">
<summary>
Change any subscriptions to INotifyPropertyChanged events on our current
model objects so that we no longer listen for events on the old models
and do listen for events on the given collection.
更改当前模型对象上对INotifyPropertyChanged事件的任何订阅
以便我们不再侦听旧模型上的事件,而侦听给定集合上的事件。
</summary>
<remarks>This does nothing if UseNotifyPropertyChanged is false.</remarks>
<param name="collection"></param>
@ -16607,7 +16594,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetCellToolTip(System.Int32,System.Int32)">
<summary>
Return the tooltip that should be shown when the mouse is hovered over the given cell
返回当鼠标悬停在给定单元格上时应显示的工具提示
</summary>
<param name="columnIndex">The column index whose tool tip is to be fetched</param>
<param name="rowIndex">The row index whose tool tip is to be fetched</param>
@ -16615,7 +16602,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ModelToItem(System.Object)">
<summary>
Return the OLVListItem that displays the given model object
返回显示给定模型对象的OLVListItem
</summary>
<param name="modelObject">The modelObject whose item is to be found</param>
<returns>The OLVListItem that displays the model, or null</returns>
@ -16633,7 +16620,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.PrepareAlternateBackColors">
<summary>
Prepare the listview to show alternate row backcolors
准备列表视图以显示交替的行背景色
</summary>
<remarks>We cannot rely on lvi.Index in this method.
In a straight list, lvi.Index is the display index, and can be used to determine
@ -16648,7 +16635,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetSubItemImages(System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Tell the underlying list control which images to show against the subitems
告诉基础列表控件针对子项显示哪些图像
</summary>
<param name="rowIndex">the index at which the item occurs</param>
<param name="item">the item whose subitems are to be set</param>
@ -16687,7 +16674,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatRowEvent(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatRow and possibly FormatCell events for the given item
触发给定项目的FormatRow和可能的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -16695,7 +16682,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatCellEvents(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatCell events for the given item
触发给定项目的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -22335,6 +22322,20 @@
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.ValueToString(System.Object,System.Object)">
<summary>
Convert the aspect object to its string representation.
</summary>
<remarks>
If the column has been given a AspectToStringConverter, that will be used to do
the conversion, otherwise just use ToString().
The returned value will not be null. Nulls are always converted
to empty strings.
</remarks>
<param name = "rowobject" ></param>
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.DecideDefaultClusteringStrategy">
<summary>
Decide the clustering strategy that will be used for this column

View File

@ -1416,6 +1416,32 @@
<param name="exe_path"></param>
<returns></returns>
</member>
<member name="M:ryCommon.RySoft.GetVerByVerStr(System.String,System.Double@,System.Double@)">
<summary>
根据版本字符串输出double类型的版本号
</summary>
<param name="ver"></param>
<param name="_softVer"></param>
<param name="_reVer"></param>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.String,System.String)">
<summary>
比较两个版本号大小
</summary>
<param name="oldVer"></param>
<param name="NewVer"></param>
<returns>oldVer小于newVer,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.Double,System.Double,System.Double,System.Double)">
<summary>
比较版本号
</summary>
<param name="_old_softVer"></param>
<param name="_old_reVer"></param>
<param name="_new_softVer"></param>
<param name="_new_reVer"></param>
<returns>old小于new,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.IsAdministrator">
<summary>
判断是否是管理员方式运行
@ -6428,6 +6454,31 @@
<param name="Msg">发送消息</param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int64)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int32)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.UInt32,System.String)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="structSize"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.UInt32,System.Type,System.String)">
<summary>
读共享内存

View File

@ -14498,22 +14498,26 @@
</summary>
<remarks>
<para>
The contents of the control will be updated immediately after setting this property.
设置此属性后,控件的内容将立即更新。
</para>
<para>This method preserves selection, if possible. Use <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
you do not want to preserve the selection. Preserving selection is the slowest part of this
code and performance is O(n) where n is the number of selected rows.</para>
<para>This method is not thread safe.</para>
<para>The property DOES work on virtual lists: setting is problem-free, but if you try to get it
and the list has 10 million objects, it may take some time to return.</para>
<para>This collection is unfiltered. Use <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> to access just those objects
that survive any installed filters.</para>
<para>如果可能,此方法将保留所选内容。使用 <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
如果您不想保留所选内容,请执行以下操作。
保留选择是该代码中最慢的部分性能为O(N)其中n是选定的行数。</para>
<para>此方法不是线程安全的。</para>
<para>该属性确实适用于虚拟列表:设置是没有问题的,但如果您尝试获取它,
并且列表有1000万个对象则可能需要一些时间才能返回。</para>
<para>此集合未经过筛选。使用 <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> 只访问那些在任何已安装的筛选器中幸存下来的对象。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsList">
<summary>
获取当前控件所有对象组成的列表
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsForClustering">
<summary>
Gets the collection of objects that will be considered when creating clusters
(which are used to generate Excel-like column filters)
获取创建群集时将考虑的对象集合。
(用于生成类似Excel的列筛选器)
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.OverlayImage">
@ -14647,18 +14651,17 @@
<remarks>SelectColumnsOnRightClickBehaviour设置为InlineMenu时才有效。当行为设置为SubMenu菜单时该选项不起作用。</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedColumn">
<summary>
Gets or sets the column that is drawn with a slight tint.
</summary>
<remarks>
<para>
If TintSortColumn is true, the sort column will automatically
be made the selected column.
</para>
<para>
The colour of the tint is controlled by SelectedColumnTint.
</para>
</remarks>
<summary>
获取或设置选定列
</summary>
<remarks>
<para>
如果TintSortColumn为true则排序列将自动成为选定列。
</para>
<para>
色调的颜色由SelectedColumnTint控制。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedRowDecoration">
<summary>
@ -14996,12 +14999,11 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.BooleanCheckStateGetter">
<summary>
This delegate fetches the checkedness of an object as a boolean only.
此委托仅将对象的检查性作为布尔值获取。
</summary>
<remarks>Use this if you never want to worry about the
Indeterminate state (which is fairly common).
<remarks>如果您永远不想担心不确定状态(这是相当常见的),请使用此选项。
<para>
This is a convenience wrapper around the CheckStateGetter property.
这是CheckStateGetter属性的便捷包装。
</para>
</remarks>
</member>
@ -15019,7 +15021,7 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanShowGroups">
<summary>
Gets whether or not this listview is capabale of showing groups
获取此列表视图是否能够显示组
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanUseApplicationIdle">
@ -15057,20 +15059,17 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckedAspectName">
<summary>
The name of the property (or field) that holds whether or not a model is checked.
保存是否选中模型的属性(或字段)的名称。
</summary>
<remarks>
<para>The property be modifiable. It must have a return type of bool (or of bool? if
TriStateCheckBoxes is true).</para>
<para>Setting this property replaces any CheckStateGetter or CheckStatePutter that have been installed.
Conversely, later setting the CheckStateGetter or CheckStatePutter properties will take precedence
over the behavior of this property.</para>
<para>该属性是可修改的。它必须具有bool(或bool)返回类型。如果TriStateCheckBooks为真)。</para>
<para>设置此属性将替换任何已安装的CheckStateGetter或CheckStatePutter。
相反稍后设置CheckStateGetter或CheckStatePutter属性将优先于此属性的行为。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckStateGetter">
<summary>
This delegate will be called whenever the ObjectListView needs to know the check state
of the row associated with a given model object.
只要ObjectListView需要知道与给定模型对象关联的行的检查状态就会调用此委托。
</summary>
<remarks>
<para>.NET has no support for indeterminate values, but as of v2.0, this class allows
@ -15085,20 +15084,19 @@
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CustomSorter">
<summary>
This delegate can be used to sort the table in a custom fasion.
</summary>
<remarks>
<para>
The delegate must install a ListViewItemSorter on the ObjectListView.
Installing the ItemSorter does the actual work of sorting the ListViewItems.
See ColumnComparer in the code for an example of what an ItemSorter has to do.
</para>
<para>
Do not install a CustomSorter on a VirtualObjectListView. Override the SortObjects()
method of the IVirtualListDataSource instead.
</para>
</remarks>
<summary>
此委托可用于以自定义方式对表进行排序。
</summary>
<remarks>
<para>
委托必须在ObjectListView上安装ListViewItemSorter。
安装ItemSorter会执行对ListViewItems进行排序的实际工作。
有关ItemSorter必须执行的操作的示例请参见代码中的ColumnCompeller。
</para>
<para>
请勿在VirtualObjectListView上安装CustomSorter。改为重写IVirtualListDataSource的SortObjects()方法。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.HeaderToolTipGetter">
<summary>
@ -15132,77 +15130,69 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObject(System.Object)">
<summary>
Add the given model object to this control.
将给定的模型对象添加到此控件。
</summary>
<param name="modelObject">The model object to be displayed</param>
<param name="modelObject">要显示的模型对象</param>
<remarks>See AddObjects() for more details</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObjects(System.Collections.ICollection)">
<summary>
Add the given collection of model objects to this control.
将给定的模型对象集合添加到此控件。
</summary>
<param name="modelObjects">A collection of model objects</param>
<param name="modelObjects">要显示的模型对象集合</param>
<remarks>
<para>The added objects will appear in their correct sort position, if sorting
is active (i.e. if PrimarySortColumn is not null). Otherwise, they will appear at the end of the list.</para>
<para>No check is performed to see if any of the objects are already in the ListView.</para>
<para>Null objects are silently ignored.</para>
<para>如果排序处于活动状态(即如果PrimarySortColumn不为空),则添加的对象将出现在其正确的排序位置。否则,它们将出现在列表的末尾。</para>
<para>不执行任何检查以查看是否有任何对象已在ListView中。</para>
<para>空对象将被静默忽略。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns">
<summary>
Resize the columns to the maximum of the header width and the data.
将列的大小调整到页眉宽度和数据的最大值。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoSizeColumns">
<summary>
Set up any automatically initialized column widths (columns that
have a width of 0 or -1 will be resized to the width of their
contents or header respectively).
</summary>
<remarks>
Obviously, this will only work once. Once it runs, the columns widths will
be changed to something else (other than 0 or -1), so it wont do anything the
second time through. Use <see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/> to force all columns
to change their size.
</remarks>
<summary>
设置任何自动初始化的列宽(宽度为0或-1的列将分别调整为其内容或标题的宽度)。
</summary>
<remarks>
显然,这只会起作用一次。一旦运行,列宽将更改为其他值(不是0或-1),因此第二次运行时不会执行任何操作。
若要强制所有列更改其大小,请使用<see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups">
<summary>
Organise the view items into groups, based on the last sort column or the first column
if there is no last sort column
根据最后一个排序列或第一列(如果没有最后一个排序列)将视图项组织到组中
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given column
根据给定列将视图项组织成组
</summary>
<remarks>
<para>
If the AlwaysGroupByColumn property is not null,
the list view items will be organisd by that column,
and the 'column' parameter will be ignored.
如果AlwaysGroupByColumn属性不为Null则列表视图项将按该列组织并且将忽略Column参数。
</para>
<para>This method triggers sorting events: BeforeSorting and AfterSorting.</para>
<para>此方法触发排序事件BeforeSorting和AfterSorting。</para>
</remarks>
<param name="column">The column whose values should be used for sorting.</param>
<param name="column">其值应用于排序的列。</param>
<param name="order"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given columns
根据给定列将视图项组织成组
</summary>
<param name="groupByColumn">What column will be used for grouping</param>
<param name="groupByOrder">What ordering will be used for groups</param>
<param name="column">The column whose values should be used for sorting. Cannot be null</param>
<param name="order">The order in which the values from column will be sorted</param>
<param name="secondaryColumn">When the values from 'column' are equal, use the values provided by this column</param>
<param name="secondaryOrder">How will the secondary values be sorted</param>
<remarks>This method does not trigger sorting events. Use BuildGroups() to do that</remarks>
<param name="groupByColumn">将使用哪一列进行分组</param>
<param name="groupByOrder">组将使用什么顺序</param>
<param name="column">其值应用于排序的列。不能为空</param>
<param name="order">列中值的排序顺序</param>
<param name="secondaryColumn">column中的值相等时请使用此列提供的值</param>
<param name="secondaryOrder">次级值将如何排序</param>
<remarks>此方法不会触发排序事件。使用BuildGroups()执行此操作</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CollectGroupingParameters(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Collect and return all the variables that influence the creation of groups
收集并返回影响组创建的所有变量
</summary>
<returns></returns>
</member>
@ -15217,12 +15207,12 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList">
<summary>
Build/rebuild all the list view items in the list, preserving as much state as is possible
生成/重新生成列表中的所有列表视图项,尽可能多地保留状态
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList(System.Boolean)">
<summary>
Build/rebuild all the list view items in the list
生成/重新生成列表中的所有列表视图项
</summary>
<param name="shouldPreserveState">If this is true, the control will try to preserve the selection,
focused item, and the scroll position (see Remarks)
@ -15236,7 +15226,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearCachedInfo">
<summary>
Clear any cached info this list may have been using
清除此列表可能一直在使用的所有缓存信息
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ApplyExtendedStyles">
@ -15277,79 +15267,79 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearUrlVisited">
<summary>
Reset the memory of which URLs have been visited
重置已访问其URL的内存
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopySelectionToClipboard">
<summary>
Copy a text and html representation of the selected rows onto the clipboard.
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
<summary>
将选定行的文本和HTML表示复制到剪贴板上。
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopyObjectsToClipboard(System.Collections.IList)">
<summary>
Copy a text and html representation of the given objects onto the clipboard.
将给定对象的文本和HTML表示复制到剪贴板上。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ObjectsToHtml(System.Collections.IList)">
<summary>
Return a html representation of the given objects
返回给定对象的html表示形式
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.DeselectAll">
<summary>
Deselect all rows in the listview
取消选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNextItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately after the given item.
If the given item is null, the first item in the list will be returned.
Return null if the given item is the last item.
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
<summary>
返回紧跟在给定项后面的ListViewItem。
如果给定项为空,则返回列表中的第一个项。
如果给定项是最后一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetLastItemInDisplayOrder">
<summary>
Return the last item in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<returns></returns>
<summary>
按向用户显示的顺序返回最后一项。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNthItemInDisplayOrder(System.Int32)">
<summary>
Return the n'th item (0-based) in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="n"></param>
<returns></returns>
<summary>
按向用户显示的顺序返回第n项(从0开始)。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="n"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetDisplayOrderOfItemIndex(System.Int32)">
<summary>
Return the display index of the given listviewitem index.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="itemIndex"></param>
<returns></returns>
<summary>
返回给定listviewitem索引的显示索引。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="itemIndex"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetPreviousItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately before the given item.
If the given item is null, the last item in the list will be returned.
Return null if the given item is the first item.
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
<summary>
返回紧接在给定项之前出现的ListViewItem。
如果给定项为空,则返回列表中的最后一项。
如果给定项是第一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.InsertObjects(System.Int32,System.Collections.ICollection)">
<summary>
Insert the given collection of objects before the given position
在给定位置之前插入给定的对象集合
</summary>
<param name="index">Where to insert the objects</param>
<param name="modelObjects">The objects to be inserted</param>
@ -15364,21 +15354,21 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsSelected(System.Object)">
<summary>
Return true if the row representing the given model is selected
如果选择了表示给定模型的行则返回TRUE
</summary>
<param name="model">The model object to look for</param>
<returns>Is the row selected</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsUrlVisited(System.String)">
<summary>
Has the given URL been visited?
给定的URL是否已被访问
</summary>
<param name="url">The string to be consider</param>
<returns>Has it been visited</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelScroll(System.Int32,System.Int32)">
<summary>
Scroll the ListView by the given deltas.
按给定的值增量滚动ListView。
</summary>
<param name="dx">Horizontal delta</param>
<param name="dy">Vertical delta</param>
@ -15389,32 +15379,32 @@
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MarkUrlVisited(System.String)">
<summary>
Remember that the given URL has been visited
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
<summary>
记住给定的URL已被访问
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MoveObjects(System.Int32,System.Collections.ICollection)">
<summary>
Move the given collection of objects to the given index.
将给定的对象集合移动到给定的索引。
</summary>
<remarks>This operation only makes sense on non-grouped ObjectListViews.</remarks>
<remarks>此操作仅对未分组的ObjectListViews有意义。</remarks>
<param name="index"></param>
<param name="modelObjects"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.HitTest(System.Int32,System.Int32)">
<summary>
Calculate what item is under the given point?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
<summary>
计算在给定点下的项目是什么?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelHitTest(System.Int32,System.Int32)">
<summary>
Perform a hit test using the Windows control's SUBITEMHITTEST message.
This provides information about group hits that the standard ListView.HitTest() does not.
使用Windows控件的SUBITEMHITTEST消息执行点击测试。
这提供了标准ListView.HitTest()不提供的有关组点击的信息。
</summary>
<param name="x"></param>
<param name="y"></param>
@ -15459,7 +15449,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObject(System.Object)">
<summary>
Remove the given model object from the ListView
从ListView中删除给定的模型对象
</summary>
<param name="modelObject">The model to be removed</param>
<remarks>See RemoveObjects() for more details
@ -15467,58 +15457,56 @@
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)">
<summary>
Remove all of the given objects from the control.
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
<summary>
从控件中移除所有给定对象。
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SelectAll">
<summary>
Select all rows in the listview
选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)">
<summary>
Set the given image to be fixed in the bottom right of the list view.
This image will not scroll when the list view scrolls.
</summary>
<remarks>
<para>
This method uses ListView's native ability to display a background image.
It has a few limitations:
</para>
<list type="bullet">
<item><description>It doesn't work well with owner drawn mode. In owner drawn mode, each cell draws itself,
including its background, which covers the background image.</description></item>
<item><description>It doesn't look very good when grid lines are enabled, since the grid lines are drawn over the image.</description></item>
<item><description>It does not work at all on XP.</description></item>
<item><description>Obviously, it doesn't look good when alternate row background colors are enabled.</description></item>
</list>
<para>
If you can live with these limitations, native watermarks are quite neat. They are true backgrounds, not
translucent overlays like the OverlayImage uses. They also have the decided advantage over overlays in that
they work correctly even in MDI applications.
</para>
<para>Setting this clears any background image.</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<summary>
在列表视图的右下角设置要固定的给定图像。
当列表视图滚动时,此图像不会滚动。
</summary>
<remarks>
<para>
此方法使用ListView的原生功能显示背景图像。
它有几个限制:
</para>
<list type="bullet">
<item><description>它在owner drawn模式下不能很好地工作。在owner drawn绘制模式下
每个单元格都会绘制自身,包括覆盖背景图像的背景。</description></item>
<item><description>启用网格线时看起来不是很好,因为网格线是在图像上绘制的。</description></item>
<item><description>它在XP上完全不起作用。</description></item>
<item><description>显然,当启用交替行背景色时,效果不佳。</description></item>
</list>
<para>
如果你能忍受这些限制,原生水印就相当不错了。
它们是真实的背景而不是像OverlayImage使用的半透明覆盖。
与覆盖相比它们也有明显的优势因为即使在MDI应用程序中它们也可以正常工作。
</para>
<para>设置此选项将清除所有背景图像。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)">
<summary>
Set the given image to be background of the ListView so that it appears at the given
percentage offsets within the list.
将给定的图像设置为ListView的背景以便它在列表中以给定的百分比偏移量显示。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>. Make sure those limitations
are understood before using the method.</para>
<para>This is very similar to setting the <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> property of the standard .NET ListView, except that the standard
BackgroundImage does not handle images with transparent areas properly -- it renders transparent areas as black. This
method does not have that problem.</para>
<para>Setting this clears any background watermark.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>中所述的相同限制.
在使用该方法之前,请确保了解这些限制。</para>
<para>这非常类似于 <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> 属性,
但标准Backround Image不能正确处理具有透明区域的图像--它将透明区域呈现为黑色。这种方法没有这个问题。</para>
<para>设置此选项将清除所有背景水印。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="xOffset">The horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right.</param>
@ -15526,64 +15514,63 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundTiledImage(System.Drawing.Image)">
<summary>
Set the given image to be the tiled background of the ListView.
将给定图像设置为ListView的平铺背景。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/> and <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/>.
Make sure those limitations
are understood before using the method.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/><see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/> 相同的限制.
在使用该方法之前,请确保了解这些限制。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="image">要绘制的图像。如果为null则将删除所有现有图像。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法。</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法.</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
<param name="preserveState">Should the state of the list be preserved as far as is possible.</param>
<param name="preserveState">是否应尽可能保留列表的状态。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObject(System.Object)">
<summary>
Update the given model object into the ListView. The model will be added if it doesn't already exist.
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>This method is thread-safe.</para>
<para>This method will cause the list to be resorted.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
将给定的模型对象更新到ListView中。
如果该模型尚不存在,则会添加该模型。
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>此方法是线程安全的。</para>
<para>此方法将导致重新排序列表。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObjects(System.Collections.ICollection)">
<summary>
Update the pre-existing models that are equal to the given objects. If any of the model doesn't
already exist in the control, they will be added.
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>This method will cause the list to be resorted.</para>
<para>Nulls are silently ignored.</para>
<para>This method is thread-safe.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
更新与给定对象相等的预先存在的模型。
如果控件中不存在任何模型,则会添加它们。
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>此方法将导致重新排序列表。</para>
<para>null值将被静默忽略。</para>
<para>此方法是线程安全的。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateNotificationSubscriptions(System.Collections.IEnumerable)">
<summary>
Change any subscriptions to INotifyPropertyChanged events on our current
model objects so that we no longer listen for events on the old models
and do listen for events on the given collection.
更改当前模型对象上对INotifyPropertyChanged事件的任何订阅
以便我们不再侦听旧模型上的事件,而侦听给定集合上的事件。
</summary>
<remarks>This does nothing if UseNotifyPropertyChanged is false.</remarks>
<param name="collection"></param>
@ -16607,7 +16594,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetCellToolTip(System.Int32,System.Int32)">
<summary>
Return the tooltip that should be shown when the mouse is hovered over the given cell
返回当鼠标悬停在给定单元格上时应显示的工具提示
</summary>
<param name="columnIndex">The column index whose tool tip is to be fetched</param>
<param name="rowIndex">The row index whose tool tip is to be fetched</param>
@ -16615,7 +16602,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ModelToItem(System.Object)">
<summary>
Return the OLVListItem that displays the given model object
返回显示给定模型对象的OLVListItem
</summary>
<param name="modelObject">The modelObject whose item is to be found</param>
<returns>The OLVListItem that displays the model, or null</returns>
@ -16633,7 +16620,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.PrepareAlternateBackColors">
<summary>
Prepare the listview to show alternate row backcolors
准备列表视图以显示交替的行背景色
</summary>
<remarks>We cannot rely on lvi.Index in this method.
In a straight list, lvi.Index is the display index, and can be used to determine
@ -16648,7 +16635,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetSubItemImages(System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Tell the underlying list control which images to show against the subitems
告诉基础列表控件针对子项显示哪些图像
</summary>
<param name="rowIndex">the index at which the item occurs</param>
<param name="item">the item whose subitems are to be set</param>
@ -16687,7 +16674,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatRowEvent(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatRow and possibly FormatCell events for the given item
触发给定项目的FormatRow和可能的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -16695,7 +16682,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatCellEvents(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatCell events for the given item
触发给定项目的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -22335,6 +22322,20 @@
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.ValueToString(System.Object,System.Object)">
<summary>
Convert the aspect object to its string representation.
</summary>
<remarks>
If the column has been given a AspectToStringConverter, that will be used to do
the conversion, otherwise just use ToString().
The returned value will not be null. Nulls are always converted
to empty strings.
</remarks>
<param name = "rowobject" ></param>
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.DecideDefaultClusteringStrategy">
<summary>
Decide the clustering strategy that will be used for this column

View File

@ -1416,6 +1416,32 @@
<param name="exe_path"></param>
<returns></returns>
</member>
<member name="M:ryCommon.RySoft.GetVerByVerStr(System.String,System.Double@,System.Double@)">
<summary>
根据版本字符串输出double类型的版本号
</summary>
<param name="ver"></param>
<param name="_softVer"></param>
<param name="_reVer"></param>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.String,System.String)">
<summary>
比较两个版本号大小
</summary>
<param name="oldVer"></param>
<param name="NewVer"></param>
<returns>oldVer小于newVer,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.CompareVer(System.Double,System.Double,System.Double,System.Double)">
<summary>
比较版本号
</summary>
<param name="_old_softVer"></param>
<param name="_old_reVer"></param>
<param name="_new_softVer"></param>
<param name="_new_reVer"></param>
<returns>old小于new,返回1,大于则返回-1,相等返回0</returns>
</member>
<member name="M:ryCommon.RySoft.IsAdministrator">
<summary>
判断是否是管理员方式运行
@ -6428,6 +6454,31 @@
<param name="Msg">发送消息</param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int64)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.Int32)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.String,System.UInt32,System.String)">
<summary>
读共享内存
</summary>
<param name="fileName"></param>
<param name="structSize"></param>
<param name="defValue"></param>
<returns></returns>
</member>
<member name="M:QuickMsg.RyMemoryShare.ReadFromMemory(System.UInt32,System.Type,System.String)">
<summary>
读共享内存

View File

@ -14498,22 +14498,26 @@
</summary>
<remarks>
<para>
The contents of the control will be updated immediately after setting this property.
设置此属性后,控件的内容将立即更新。
</para>
<para>This method preserves selection, if possible. Use <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
you do not want to preserve the selection. Preserving selection is the slowest part of this
code and performance is O(n) where n is the number of selected rows.</para>
<para>This method is not thread safe.</para>
<para>The property DOES work on virtual lists: setting is problem-free, but if you try to get it
and the list has 10 million objects, it may take some time to return.</para>
<para>This collection is unfiltered. Use <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> to access just those objects
that survive any installed filters.</para>
<para>如果可能,此方法将保留所选内容。使用 <see cref="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)"/> if
如果您不想保留所选内容,请执行以下操作。
保留选择是该代码中最慢的部分性能为O(N)其中n是选定的行数。</para>
<para>此方法不是线程安全的。</para>
<para>该属性确实适用于虚拟列表:设置是没有问题的,但如果您尝试获取它,
并且列表有1000万个对象则可能需要一些时间才能返回。</para>
<para>此集合未经过筛选。使用 <see cref="P:BrightIdeasSoftware.ObjectListView.FilteredObjects"/> 只访问那些在任何已安装的筛选器中幸存下来的对象。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsList">
<summary>
获取当前控件所有对象组成的列表
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.ObjectsForClustering">
<summary>
Gets the collection of objects that will be considered when creating clusters
(which are used to generate Excel-like column filters)
获取创建群集时将考虑的对象集合。
(用于生成类似Excel的列筛选器)
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.OverlayImage">
@ -14647,18 +14651,17 @@
<remarks>SelectColumnsOnRightClickBehaviour设置为InlineMenu时才有效。当行为设置为SubMenu菜单时该选项不起作用。</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedColumn">
<summary>
Gets or sets the column that is drawn with a slight tint.
</summary>
<remarks>
<para>
If TintSortColumn is true, the sort column will automatically
be made the selected column.
</para>
<para>
The colour of the tint is controlled by SelectedColumnTint.
</para>
</remarks>
<summary>
获取或设置选定列
</summary>
<remarks>
<para>
如果TintSortColumn为true则排序列将自动成为选定列。
</para>
<para>
色调的颜色由SelectedColumnTint控制。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.SelectedRowDecoration">
<summary>
@ -14996,12 +14999,11 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.BooleanCheckStateGetter">
<summary>
This delegate fetches the checkedness of an object as a boolean only.
此委托仅将对象的检查性作为布尔值获取。
</summary>
<remarks>Use this if you never want to worry about the
Indeterminate state (which is fairly common).
<remarks>如果您永远不想担心不确定状态(这是相当常见的),请使用此选项。
<para>
This is a convenience wrapper around the CheckStateGetter property.
这是CheckStateGetter属性的便捷包装。
</para>
</remarks>
</member>
@ -15019,7 +15021,7 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanShowGroups">
<summary>
Gets whether or not this listview is capabale of showing groups
获取此列表视图是否能够显示组
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CanUseApplicationIdle">
@ -15057,20 +15059,17 @@
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckedAspectName">
<summary>
The name of the property (or field) that holds whether or not a model is checked.
保存是否选中模型的属性(或字段)的名称。
</summary>
<remarks>
<para>The property be modifiable. It must have a return type of bool (or of bool? if
TriStateCheckBoxes is true).</para>
<para>Setting this property replaces any CheckStateGetter or CheckStatePutter that have been installed.
Conversely, later setting the CheckStateGetter or CheckStatePutter properties will take precedence
over the behavior of this property.</para>
<para>该属性是可修改的。它必须具有bool(或bool)返回类型。如果TriStateCheckBooks为真)。</para>
<para>设置此属性将替换任何已安装的CheckStateGetter或CheckStatePutter。
相反稍后设置CheckStateGetter或CheckStatePutter属性将优先于此属性的行为。</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CheckStateGetter">
<summary>
This delegate will be called whenever the ObjectListView needs to know the check state
of the row associated with a given model object.
只要ObjectListView需要知道与给定模型对象关联的行的检查状态就会调用此委托。
</summary>
<remarks>
<para>.NET has no support for indeterminate values, but as of v2.0, this class allows
@ -15085,20 +15084,19 @@
</summary>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.CustomSorter">
<summary>
This delegate can be used to sort the table in a custom fasion.
</summary>
<remarks>
<para>
The delegate must install a ListViewItemSorter on the ObjectListView.
Installing the ItemSorter does the actual work of sorting the ListViewItems.
See ColumnComparer in the code for an example of what an ItemSorter has to do.
</para>
<para>
Do not install a CustomSorter on a VirtualObjectListView. Override the SortObjects()
method of the IVirtualListDataSource instead.
</para>
</remarks>
<summary>
此委托可用于以自定义方式对表进行排序。
</summary>
<remarks>
<para>
委托必须在ObjectListView上安装ListViewItemSorter。
安装ItemSorter会执行对ListViewItems进行排序的实际工作。
有关ItemSorter必须执行的操作的示例请参见代码中的ColumnCompeller。
</para>
<para>
请勿在VirtualObjectListView上安装CustomSorter。改为重写IVirtualListDataSource的SortObjects()方法。
</para>
</remarks>
</member>
<member name="P:BrightIdeasSoftware.ObjectListView.HeaderToolTipGetter">
<summary>
@ -15132,77 +15130,69 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObject(System.Object)">
<summary>
Add the given model object to this control.
将给定的模型对象添加到此控件。
</summary>
<param name="modelObject">The model object to be displayed</param>
<param name="modelObject">要显示的模型对象</param>
<remarks>See AddObjects() for more details</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AddObjects(System.Collections.ICollection)">
<summary>
Add the given collection of model objects to this control.
将给定的模型对象集合添加到此控件。
</summary>
<param name="modelObjects">A collection of model objects</param>
<param name="modelObjects">要显示的模型对象集合</param>
<remarks>
<para>The added objects will appear in their correct sort position, if sorting
is active (i.e. if PrimarySortColumn is not null). Otherwise, they will appear at the end of the list.</para>
<para>No check is performed to see if any of the objects are already in the ListView.</para>
<para>Null objects are silently ignored.</para>
<para>如果排序处于活动状态(即如果PrimarySortColumn不为空),则添加的对象将出现在其正确的排序位置。否则,它们将出现在列表的末尾。</para>
<para>不执行任何检查以查看是否有任何对象已在ListView中。</para>
<para>空对象将被静默忽略。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns">
<summary>
Resize the columns to the maximum of the header width and the data.
将列的大小调整到页眉宽度和数据的最大值。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.AutoSizeColumns">
<summary>
Set up any automatically initialized column widths (columns that
have a width of 0 or -1 will be resized to the width of their
contents or header respectively).
</summary>
<remarks>
Obviously, this will only work once. Once it runs, the columns widths will
be changed to something else (other than 0 or -1), so it wont do anything the
second time through. Use <see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/> to force all columns
to change their size.
</remarks>
<summary>
设置任何自动初始化的列宽(宽度为0或-1的列将分别调整为其内容或标题的宽度)。
</summary>
<remarks>
显然,这只会起作用一次。一旦运行,列宽将更改为其他值(不是0或-1),因此第二次运行时不会执行任何操作。
若要强制所有列更改其大小,请使用<see cref="M:BrightIdeasSoftware.ObjectListView.AutoResizeColumns"/>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups">
<summary>
Organise the view items into groups, based on the last sort column or the first column
if there is no last sort column
根据最后一个排序列或第一列(如果没有最后一个排序列)将视图项组织到组中
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given column
根据给定列将视图项组织成组
</summary>
<remarks>
<para>
If the AlwaysGroupByColumn property is not null,
the list view items will be organisd by that column,
and the 'column' parameter will be ignored.
如果AlwaysGroupByColumn属性不为Null则列表视图项将按该列组织并且将忽略Column参数。
</para>
<para>This method triggers sorting events: BeforeSorting and AfterSorting.</para>
<para>此方法触发排序事件BeforeSorting和AfterSorting。</para>
</remarks>
<param name="column">The column whose values should be used for sorting.</param>
<param name="column">其值应用于排序的列。</param>
<param name="order"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildGroups(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Organise the view items into groups, based on the given columns
根据给定列将视图项组织成组
</summary>
<param name="groupByColumn">What column will be used for grouping</param>
<param name="groupByOrder">What ordering will be used for groups</param>
<param name="column">The column whose values should be used for sorting. Cannot be null</param>
<param name="order">The order in which the values from column will be sorted</param>
<param name="secondaryColumn">When the values from 'column' are equal, use the values provided by this column</param>
<param name="secondaryOrder">How will the secondary values be sorted</param>
<remarks>This method does not trigger sorting events. Use BuildGroups() to do that</remarks>
<param name="groupByColumn">将使用哪一列进行分组</param>
<param name="groupByOrder">组将使用什么顺序</param>
<param name="column">其值应用于排序的列。不能为空</param>
<param name="order">列中值的排序顺序</param>
<param name="secondaryColumn">column中的值相等时请使用此列提供的值</param>
<param name="secondaryOrder">次级值将如何排序</param>
<remarks>此方法不会触发排序事件。使用BuildGroups()执行此操作</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CollectGroupingParameters(BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder,BrightIdeasSoftware.OLVColumn,System.Windows.Forms.SortOrder)">
<summary>
Collect and return all the variables that influence the creation of groups
收集并返回影响组创建的所有变量
</summary>
<returns></returns>
</member>
@ -15217,12 +15207,12 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList">
<summary>
Build/rebuild all the list view items in the list, preserving as much state as is possible
生成/重新生成列表中的所有列表视图项,尽可能多地保留状态
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.BuildList(System.Boolean)">
<summary>
Build/rebuild all the list view items in the list
生成/重新生成列表中的所有列表视图项
</summary>
<param name="shouldPreserveState">If this is true, the control will try to preserve the selection,
focused item, and the scroll position (see Remarks)
@ -15236,7 +15226,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearCachedInfo">
<summary>
Clear any cached info this list may have been using
清除此列表可能一直在使用的所有缓存信息
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ApplyExtendedStyles">
@ -15277,79 +15267,79 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ClearUrlVisited">
<summary>
Reset the memory of which URLs have been visited
重置已访问其URL的内存
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopySelectionToClipboard">
<summary>
Copy a text and html representation of the selected rows onto the clipboard.
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
<summary>
将选定行的文本和HTML表示复制到剪贴板上。
</summary>
<remarks>Be careful when using this with virtual lists. If the user has selected
10,000,000 rows, this method will faithfully try to copy all of them to the clipboard.
From the user's point of view, your program will appear to have hung.</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.CopyObjectsToClipboard(System.Collections.IList)">
<summary>
Copy a text and html representation of the given objects onto the clipboard.
将给定对象的文本和HTML表示复制到剪贴板上。
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ObjectsToHtml(System.Collections.IList)">
<summary>
Return a html representation of the given objects
返回给定对象的html表示形式
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.DeselectAll">
<summary>
Deselect all rows in the listview
取消选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNextItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately after the given item.
If the given item is null, the first item in the list will be returned.
Return null if the given item is the last item.
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
<summary>
返回紧跟在给定项后面的ListViewItem。
如果给定项为空,则返回列表中的第一个项。
如果给定项是最后一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned, or null</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetLastItemInDisplayOrder">
<summary>
Return the last item in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<returns></returns>
<summary>
按向用户显示的顺序返回最后一项。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetNthItemInDisplayOrder(System.Int32)">
<summary>
Return the n'th item (0-based) in the order they are shown to the user.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="n"></param>
<returns></returns>
<summary>
按向用户显示的顺序返回第n项(从0开始)。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="n"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetDisplayOrderOfItemIndex(System.Int32)">
<summary>
Return the display index of the given listviewitem index.
If the control is not grouped, the display order is the same as the
sorted list order. But if the list is grouped, the display order is different.
</summary>
<param name="itemIndex"></param>
<returns></returns>
<summary>
返回给定listviewitem索引的显示索引。
如果控件未分组,则显示顺序与排序的列表顺序相同。
但如果列表是分组的,则显示顺序不同。
</summary>
<param name="itemIndex"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetPreviousItem(BrightIdeasSoftware.OLVListItem)">
<summary>
Return the ListViewItem that appears immediately before the given item.
If the given item is null, the last item in the list will be returned.
Return null if the given item is the first item.
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
<summary>
返回紧接在给定项之前出现的ListViewItem。
如果给定项为空,则返回列表中的最后一项。
如果给定项是第一项则返回NULL。
</summary>
<param name="itemToFind">The item that is before the item that is returned</param>
<returns>A ListViewItem</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.InsertObjects(System.Int32,System.Collections.ICollection)">
<summary>
Insert the given collection of objects before the given position
在给定位置之前插入给定的对象集合
</summary>
<param name="index">Where to insert the objects</param>
<param name="modelObjects">The objects to be inserted</param>
@ -15364,21 +15354,21 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsSelected(System.Object)">
<summary>
Return true if the row representing the given model is selected
如果选择了表示给定模型的行则返回TRUE
</summary>
<param name="model">The model object to look for</param>
<returns>Is the row selected</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.IsUrlVisited(System.String)">
<summary>
Has the given URL been visited?
给定的URL是否已被访问
</summary>
<param name="url">The string to be consider</param>
<returns>Has it been visited</returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelScroll(System.Int32,System.Int32)">
<summary>
Scroll the ListView by the given deltas.
按给定的值增量滚动ListView。
</summary>
<param name="dx">Horizontal delta</param>
<param name="dy">Vertical delta</param>
@ -15389,32 +15379,32 @@
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MarkUrlVisited(System.String)">
<summary>
Remember that the given URL has been visited
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
<summary>
记住给定的URL已被访问
</summary>
<param name="url">The url to be remembered</param>
<remarks>This does not cause the control be redrawn</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.MoveObjects(System.Int32,System.Collections.ICollection)">
<summary>
Move the given collection of objects to the given index.
将给定的对象集合移动到给定的索引。
</summary>
<remarks>This operation only makes sense on non-grouped ObjectListViews.</remarks>
<remarks>此操作仅对未分组的ObjectListViews有意义。</remarks>
<param name="index"></param>
<param name="modelObjects"></param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.HitTest(System.Int32,System.Int32)">
<summary>
Calculate what item is under the given point?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
<summary>
计算在给定点下的项目是什么?
</summary>
<param name="x"></param>
<param name="y"></param>
<returns></returns>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.LowLevelHitTest(System.Int32,System.Int32)">
<summary>
Perform a hit test using the Windows control's SUBITEMHITTEST message.
This provides information about group hits that the standard ListView.HitTest() does not.
使用Windows控件的SUBITEMHITTEST消息执行点击测试。
这提供了标准ListView.HitTest()不提供的有关组点击的信息。
</summary>
<param name="x"></param>
<param name="y"></param>
@ -15459,7 +15449,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObject(System.Object)">
<summary>
Remove the given model object from the ListView
从ListView中删除给定的模型对象
</summary>
<param name="modelObject">The model to be removed</param>
<remarks>See RemoveObjects() for more details
@ -15467,58 +15457,56 @@
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)">
<summary>
Remove all of the given objects from the control.
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
<summary>
从控件中移除所有给定对象。
</summary>
<param name="modelObjects">Collection of objects to be removed</param>
<remarks>
<para>Nulls and model objects that are not in the ListView are silently ignored.</para>
<para>This method is thread-safe.</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SelectAll">
<summary>
Select all rows in the listview
选择列表视图中的所有行
</summary>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)">
<summary>
Set the given image to be fixed in the bottom right of the list view.
This image will not scroll when the list view scrolls.
</summary>
<remarks>
<para>
This method uses ListView's native ability to display a background image.
It has a few limitations:
</para>
<list type="bullet">
<item><description>It doesn't work well with owner drawn mode. In owner drawn mode, each cell draws itself,
including its background, which covers the background image.</description></item>
<item><description>It doesn't look very good when grid lines are enabled, since the grid lines are drawn over the image.</description></item>
<item><description>It does not work at all on XP.</description></item>
<item><description>Obviously, it doesn't look good when alternate row background colors are enabled.</description></item>
</list>
<para>
If you can live with these limitations, native watermarks are quite neat. They are true backgrounds, not
translucent overlays like the OverlayImage uses. They also have the decided advantage over overlays in that
they work correctly even in MDI applications.
</para>
<para>Setting this clears any background image.</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<summary>
在列表视图的右下角设置要固定的给定图像。
当列表视图滚动时,此图像不会滚动。
</summary>
<remarks>
<para>
此方法使用ListView的原生功能显示背景图像。
它有几个限制:
</para>
<list type="bullet">
<item><description>它在owner drawn模式下不能很好地工作。在owner drawn绘制模式下
每个单元格都会绘制自身,包括覆盖背景图像的背景。</description></item>
<item><description>启用网格线时看起来不是很好,因为网格线是在图像上绘制的。</description></item>
<item><description>它在XP上完全不起作用。</description></item>
<item><description>显然,当启用交替行背景色时,效果不佳。</description></item>
</list>
<para>
如果你能忍受这些限制,原生水印就相当不错了。
它们是真实的背景而不是像OverlayImage使用的半透明覆盖。
与覆盖相比它们也有明显的优势因为即使在MDI应用程序中它们也可以正常工作。
</para>
<para>设置此选项将清除所有背景图像。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)">
<summary>
Set the given image to be background of the ListView so that it appears at the given
percentage offsets within the list.
将给定的图像设置为ListView的背景以便它在列表中以给定的百分比偏移量显示。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>. Make sure those limitations
are understood before using the method.</para>
<para>This is very similar to setting the <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> property of the standard .NET ListView, except that the standard
BackgroundImage does not handle images with transparent areas properly -- it renders transparent areas as black. This
method does not have that problem.</para>
<para>Setting this clears any background watermark.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/>中所述的相同限制.
在使用该方法之前,请确保了解这些限制。</para>
<para>这非常类似于 <see cref="P:System.Windows.Forms.Control.BackgroundImage"/> 属性,
但标准Backround Image不能正确处理具有透明区域的图像--它将透明区域呈现为黑色。这种方法没有这个问题。</para>
<para>设置此选项将清除所有背景水印。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="xOffset">The horizontal percentage where the image will be placed. 0 is absolute left, 100 is absolute right.</param>
@ -15526,64 +15514,63 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundTiledImage(System.Drawing.Image)">
<summary>
Set the given image to be the tiled background of the ListView.
将给定图像设置为ListView的平铺背景。
</summary>
<remarks>
<para>This has the same limitations as described in <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/> and <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/>.
Make sure those limitations
are understood before using the method.</para>
<para>这具有与 <see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundWatermark(System.Drawing.Image)"/><see cref="M:BrightIdeasSoftware.ObjectListView.SetNativeBackgroundImage(System.Drawing.Image,System.Int32,System.Int32)"/> 相同的限制.
在使用该方法之前,请确保了解这些限制。</para>
</remarks>
<param name="image">The image to be drawn. If null, any existing image will be removed.</param>
<param name="image">要绘制的图像。如果为null则将删除所有现有图像。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法。</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetObjects(System.Collections.IEnumerable,System.Boolean)">
<summary>
Set the collection of objects that will be shown in this list view.
设置将在此列表视图中显示的对象集合。
</summary>
<remark>This method can safely be called from background threads.</remark>
<remarks>The list is updated immediately</remarks>
<remark>可以从后台线程安全地调用此方法.</remark>
<remarks>该列表将立即更新</remarks>
<param name="collection">The objects to be displayed</param>
<param name="preserveState">Should the state of the list be preserved as far as is possible.</param>
<param name="preserveState">是否应尽可能保留列表的状态。</param>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObject(System.Object)">
<summary>
Update the given model object into the ListView. The model will be added if it doesn't already exist.
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>This method is thread-safe.</para>
<para>This method will cause the list to be resorted.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
将给定的模型对象更新到ListView中。
如果该模型尚不存在,则会添加该模型。
</summary>
<param name="modelObject">The model to be updated</param>
<remarks>
<para>
See <see cref="M:BrightIdeasSoftware.ObjectListView.RemoveObjects(System.Collections.ICollection)"/> for more details
</para>
<para>此方法是线程安全的。</para>
<para>此方法将导致重新排序列表。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateObjects(System.Collections.ICollection)">
<summary>
Update the pre-existing models that are equal to the given objects. If any of the model doesn't
already exist in the control, they will be added.
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>This method will cause the list to be resorted.</para>
<para>Nulls are silently ignored.</para>
<para>This method is thread-safe.</para>
<para>This method only works on ObjectListViews and FastObjectListViews.</para>
</remarks>
<summary>
更新与给定对象相等的预先存在的模型。
如果控件中不存在任何模型,则会添加它们。
</summary>
<param name="modelObjects">Collection of objects to be updated/added</param>
<remarks>
<para>此方法将导致重新排序列表。</para>
<para>null值将被静默忽略。</para>
<para>此方法是线程安全的。</para>
<para>此方法仅适用于ObjectListViews和FastObjectListViews。</para>
</remarks>
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.UpdateNotificationSubscriptions(System.Collections.IEnumerable)">
<summary>
Change any subscriptions to INotifyPropertyChanged events on our current
model objects so that we no longer listen for events on the old models
and do listen for events on the given collection.
更改当前模型对象上对INotifyPropertyChanged事件的任何订阅
以便我们不再侦听旧模型上的事件,而侦听给定集合上的事件。
</summary>
<remarks>This does nothing if UseNotifyPropertyChanged is false.</remarks>
<param name="collection"></param>
@ -16607,7 +16594,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.GetCellToolTip(System.Int32,System.Int32)">
<summary>
Return the tooltip that should be shown when the mouse is hovered over the given cell
返回当鼠标悬停在给定单元格上时应显示的工具提示
</summary>
<param name="columnIndex">The column index whose tool tip is to be fetched</param>
<param name="rowIndex">The row index whose tool tip is to be fetched</param>
@ -16615,7 +16602,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.ModelToItem(System.Object)">
<summary>
Return the OLVListItem that displays the given model object
返回显示给定模型对象的OLVListItem
</summary>
<param name="modelObject">The modelObject whose item is to be found</param>
<returns>The OLVListItem that displays the model, or null</returns>
@ -16633,7 +16620,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.PrepareAlternateBackColors">
<summary>
Prepare the listview to show alternate row backcolors
准备列表视图以显示交替的行背景色
</summary>
<remarks>We cannot rely on lvi.Index in this method.
In a straight list, lvi.Index is the display index, and can be used to determine
@ -16648,7 +16635,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.SetSubItemImages(System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Tell the underlying list control which images to show against the subitems
告诉基础列表控件针对子项显示哪些图像
</summary>
<param name="rowIndex">the index at which the item occurs</param>
<param name="item">the item whose subitems are to be set</param>
@ -16687,7 +16674,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatRowEvent(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatRow and possibly FormatCell events for the given item
触发给定项目的FormatRow和可能的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -16695,7 +16682,7 @@
</member>
<member name="M:BrightIdeasSoftware.ObjectListView.TriggerFormatCellEvents(System.Int32,System.Int32,BrightIdeasSoftware.OLVListItem)">
<summary>
Trigger FormatCell events for the given item
触发给定项目的FormatCell事件
</summary>
<param name="rowIndex"></param>
<param name="displayIndex"></param>
@ -22335,6 +22322,20 @@
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.ValueToString(System.Object,System.Object)">
<summary>
Convert the aspect object to its string representation.
</summary>
<remarks>
If the column has been given a AspectToStringConverter, that will be used to do
the conversion, otherwise just use ToString().
The returned value will not be null. Nulls are always converted
to empty strings.
</remarks>
<param name = "rowobject" ></param>
<param name="value">The value of the aspect that should be displayed</param>
<returns>A string representation of the aspect</returns>
</member>
<member name="M:BrightIdeasSoftware.OLVColumn.DecideDefaultClusteringStrategy">
<summary>
Decide the clustering strategy that will be used for this column

View File

@ -1,4 +1,26 @@
### 2021-09-07更新
### 2021-09-12更新
------
#### ryControls V3.0.2109.1201
- *.[改进]ObjectListView控件的AspectToStringConverter函数新增行数据参数。
- *.[改进]ObjectListView控件的行高默认到25像素。
- *.[改进]ObjectListView控件默认行选择而不是列选择。
- *.[改进]ObjectListView控件新增大量中文注释。
- *.[改进]ObjectListView控件的ShowGroups属性默认值为false。
------
### 2021-09-07更新
------
#### MyDb V3.0.2109.0801
- *.[新增]RySoft类新增版本号比对函数。
#### ryUpdate V3.0.2109.0801
- *.[新增]新增支持按不同版本号下载不同url升级包的功能。
### 2021-09-07更新
------
#### MyDb V3.0.2109.0701
- *.[新增]WinHotReg类新增Clear和Count属性。

View File

@ -150,6 +150,18 @@ namespace Itrycn_Project2
//db.Free();
LiveUpdate.RyUpdate update = new LiveUpdate.RyUpdate(Soft_ConstInfo.Update_Url);
update.CheckUpdate();
var http = new DotNet4.Utilities.HttpHelper();
var item = new DotNet4.Utilities.HttpItem
{
URL = "http://www.huaan.cn/api/applet/qrcode/queryComponent",
Method = "POST",
IsToLower = false,
Postdata = "{\"tempId\":1619,\"excludeVisibility\":4,\"status\":1,\"valueStatus\":1,\"visibleAndEditableUserId\":3}",
ContentType = "application/json",
ProtocolVersion = System.Net.HttpVersion.Version11,
ProxyIp = "192.168.1.12"
};
var r= http.GetHtml(item);
}
private void ToolStripMenuItem_Click(object sender, EventArgs e)

View File

@ -40,6 +40,66 @@ namespace ryCommon
catch { return ""; }
//Version ver = Assembly.LoadFile(exe_path).GetName().Version;
//return ver.Major.ToString() + "." + ver.Minor.ToString() + "." + ver.Build.ToString() + "." + ver.Revision.ToString();
}
/// <summary>
/// 根据版本字符串输出double类型的版本号
/// </summary>
/// <param name="ver"></param>
/// <param name="_softVer"></param>
/// <param name="_reVer"></param>
public static void GetVerByVerStr(string ver, out double _softVer, out double _reVer)
{
_softVer = 0;
_reVer = 0;
string[] ver_item = ver.Split('.');
switch (ver_item.Length)
{
case 1:
_softVer = ver_item[0].ToDouble(0);
break;
case 2:
_softVer = ver.ToDouble(0);
break;
case 3:
_softVer = (ver_item[0] + "." + ver_item[1]).ToDouble(0);
_reVer = ver_item[2].ToDouble(0);
break;
case 4:
_softVer = (ver_item[0] + "." + ver_item[1]).ToDouble(0);
_reVer = (ver_item[2] + "." + ver_item[3]).ToDouble(0);
break;
}
}
/// <summary>
/// 比较两个版本号大小
/// </summary>
/// <param name="oldVer"></param>
/// <param name="NewVer"></param>
/// <returns>oldVer小于newVer,返回1,大于则返回-1,相等返回0</returns>
public static int CompareVer(string oldVer,string NewVer)
{
GetVerByVerStr(oldVer, out double _old_softVer, out double _old_reVer);
GetVerByVerStr(NewVer, out double _new_softVer, out double _new_reVer);
return CompareVer(_old_softVer, _old_reVer, _new_softVer, _new_reVer);
}
/// <summary>
/// 比较版本号
/// </summary>
/// <param name="_old_softVer"></param>
/// <param name="_old_reVer"></param>
/// <param name="_new_softVer"></param>
/// <param name="_new_reVer"></param>
/// <returns>old小于new,返回1,大于则返回-1,相等返回0</returns>
public static int CompareVer(double _old_softVer,double _old_reVer, double _new_softVer, double _new_reVer)
{
if (_old_softVer < _new_softVer) { return 1; }
if (_old_softVer == _new_softVer)
{
if (_old_reVer < _new_reVer) { return 1; }
else if (_old_reVer == _new_reVer) { return 0; }
else { return -1; }
}
else { return -1; }
}
/// <summary>
/// 判断是否是管理员方式运行

View File

@ -134,6 +134,43 @@ namespace QuickMsg
}
return 0;
}
/// <summary>
/// 读共享内存
/// </summary>
/// <param name="fileName"></param>
/// <param name="defValue"></param>
/// <returns></returns>
public static Int64 ReadFromMemory(string fileName,Int64 defValue)
{
var result= ReadFromMemory(1024, typeof(Int64), fileName);
if (result == null) { return defValue; }
return (Int64)result;
}
/// <summary>
/// 读共享内存
/// </summary>
/// <param name="fileName"></param>
/// <param name="defValue"></param>
/// <returns></returns>
public static int ReadFromMemory(string fileName, int defValue)
{
var result = ReadFromMemory(1024, typeof(int), fileName);
if (result == null) { return defValue; }
return (int)result;
}
/// <summary>
/// 读共享内存
/// </summary>
/// <param name="fileName"></param>
/// <param name="structSize"></param>
/// <param name="defValue"></param>
/// <returns></returns>
public static string ReadFromMemory(string fileName, uint structSize, string defValue)
{
var result = ReadFromMemory(structSize, typeof(string), fileName);
if (result == null) { return defValue; }
return (string)result;
}
/// <summary>
/// 读共享内存
/// </summary>

View File

@ -200,13 +200,13 @@
<DependentUpon>FrmCapture.cs</DependentUpon>
</EmbeddedResource>
</ItemGroup>
<ItemGroup />
<ItemGroup>
<None Include="HtmlAgilityPack.Shared\HtmlAgilityPack.Shared.projitems" />
<None Include="HtmlAgilityPack.Shared\HtmlAgilityPack.Shared.projitems.vspscc" />
<None Include="HtmlAgilityPack.Shared\HtmlAgilityPack.Shared.shproj" />
<None Include="HtmlAgilityPack.Shared\HtmlAgilityPack.Shared.shproj.vspscc" />
</ItemGroup>
<ItemGroup />
<Import Project="$(MSBuildToolsPath)\Microsoft.CSharp.targets" />
<!-- To modify your build process, add your task inside one of the targets below and uncomment it.
Other similar extension points exist, see Microsoft.Common.targets.

View File

@ -0,0 +1,46 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal enum BsonBinaryType : byte
{
Binary = 0x00,
Function = 0x01,
[Obsolete("This type has been deprecated in the BSON specification. Use Binary instead.")]
BinaryOld = 0x02,
[Obsolete("This type has been deprecated in the BSON specification. Use Uuid instead.")]
UuidOld = 0x03,
Uuid = 0x04,
Md5 = 0x05,
UserDefined = 0x80
}
}

View File

@ -0,0 +1,330 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.IO;
using System.Text;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal class BsonBinaryWriter
{
private static readonly Encoding Encoding = new UTF8Encoding(false);
private readonly BinaryWriter _writer;
private byte[] _largeByteBuffer;
public DateTimeKind DateTimeKindHandling { get; set; }
public BsonBinaryWriter(BinaryWriter writer)
{
DateTimeKindHandling = DateTimeKind.Utc;
_writer = writer;
}
public void Flush()
{
_writer.Flush();
}
public void Close()
{
#if HAVE_STREAM_READER_WRITER_CLOSE
_writer.Close();
#else
_writer.Dispose();
#endif
}
public void WriteToken(BsonToken t)
{
CalculateSize(t);
WriteTokenInternal(t);
}
private void WriteTokenInternal(BsonToken t)
{
switch (t.Type)
{
case BsonType.Object:
{
BsonObject value = (BsonObject)t;
_writer.Write(value.CalculatedSize);
foreach (BsonProperty property in value)
{
_writer.Write((sbyte)property.Value.Type);
WriteString((string)property.Name.Value, property.Name.ByteCount, null);
WriteTokenInternal(property.Value);
}
_writer.Write((byte)0);
}
break;
case BsonType.Array:
{
BsonArray value = (BsonArray)t;
_writer.Write(value.CalculatedSize);
ulong index = 0;
foreach (BsonToken c in value)
{
_writer.Write((sbyte)c.Type);
WriteString(index.ToString(CultureInfo.InvariantCulture), MathUtils.IntLength(index), null);
WriteTokenInternal(c);
index++;
}
_writer.Write((byte)0);
}
break;
case BsonType.Integer:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToInt32(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.Long:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToInt64(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.Number:
{
BsonValue value = (BsonValue)t;
_writer.Write(Convert.ToDouble(value.Value, CultureInfo.InvariantCulture));
}
break;
case BsonType.String:
{
BsonString value = (BsonString)t;
WriteString((string)value.Value, value.ByteCount, value.CalculatedSize - 4);
}
break;
case BsonType.Boolean:
_writer.Write(t == BsonBoolean.True);
break;
case BsonType.Null:
case BsonType.Undefined:
break;
case BsonType.Date:
{
BsonValue value = (BsonValue)t;
long ticks = 0;
if (value.Value is DateTime dateTime)
{
if (DateTimeKindHandling == DateTimeKind.Utc)
{
dateTime = dateTime.ToUniversalTime();
}
else if (DateTimeKindHandling == DateTimeKind.Local)
{
dateTime = dateTime.ToLocalTime();
}
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTime, false);
}
#if HAVE_DATE_TIME_OFFSET
else
{
DateTimeOffset dateTimeOffset = (DateTimeOffset)value.Value;
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(dateTimeOffset.UtcDateTime, dateTimeOffset.Offset);
}
#endif
_writer.Write(ticks);
}
break;
case BsonType.Binary:
{
BsonBinary value = (BsonBinary)t;
byte[] data = (byte[])value.Value;
_writer.Write(data.Length);
_writer.Write((byte)value.BinaryType);
_writer.Write(data);
}
break;
case BsonType.Oid:
{
BsonValue value = (BsonValue)t;
byte[] data = (byte[])value.Value;
_writer.Write(data);
}
break;
case BsonType.Regex:
{
BsonRegex value = (BsonRegex)t;
WriteString((string)value.Pattern.Value, value.Pattern.ByteCount, null);
WriteString((string)value.Options.Value, value.Options.ByteCount, null);
}
break;
default:
throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
}
}
private void WriteString(string s, int byteCount, int? calculatedlengthPrefix)
{
if (calculatedlengthPrefix != null)
{
_writer.Write(calculatedlengthPrefix.GetValueOrDefault());
}
WriteUtf8Bytes(s, byteCount);
_writer.Write((byte)0);
}
public void WriteUtf8Bytes(string s, int byteCount)
{
if (s != null)
{
if (byteCount <= 256)
{
if (_largeByteBuffer == null)
{
_largeByteBuffer = new byte[256];
}
Encoding.GetBytes(s, 0, s.Length, _largeByteBuffer, 0);
_writer.Write(_largeByteBuffer, 0, byteCount);
}
else
{
byte[] bytes = Encoding.GetBytes(s);
_writer.Write(bytes);
}
}
}
private int CalculateSize(int stringByteCount)
{
return stringByteCount + 1;
}
private int CalculateSizeWithLength(int stringByteCount, bool includeSize)
{
int baseSize = (includeSize)
? 5 // size bytes + terminator
: 1; // terminator
return baseSize + stringByteCount;
}
private int CalculateSize(BsonToken t)
{
switch (t.Type)
{
case BsonType.Object:
{
BsonObject value = (BsonObject)t;
int bases = 4;
foreach (BsonProperty p in value)
{
int size = 1;
size += CalculateSize(p.Name);
size += CalculateSize(p.Value);
bases += size;
}
bases += 1;
value.CalculatedSize = bases;
return bases;
}
case BsonType.Array:
{
BsonArray value = (BsonArray)t;
int size = 4;
ulong index = 0;
foreach (BsonToken c in value)
{
size += 1;
size += CalculateSize(MathUtils.IntLength(index));
size += CalculateSize(c);
index++;
}
size += 1;
value.CalculatedSize = size;
return value.CalculatedSize;
}
case BsonType.Integer:
return 4;
case BsonType.Long:
return 8;
case BsonType.Number:
return 8;
case BsonType.String:
{
BsonString value = (BsonString)t;
string s = (string)value.Value;
value.ByteCount = (s != null) ? Encoding.GetByteCount(s) : 0;
value.CalculatedSize = CalculateSizeWithLength(value.ByteCount, value.IncludeLength);
return value.CalculatedSize;
}
case BsonType.Boolean:
return 1;
case BsonType.Null:
case BsonType.Undefined:
return 0;
case BsonType.Date:
return 8;
case BsonType.Binary:
{
BsonBinary value = (BsonBinary)t;
byte[] data = (byte[])value.Value;
value.CalculatedSize = 4 + 1 + data.Length;
return value.CalculatedSize;
}
case BsonType.Oid:
return 12;
case BsonType.Regex:
{
BsonRegex value = (BsonRegex)t;
int size = 0;
size += CalculateSize(value.Pattern);
size += CalculateSize(value.Options);
value.CalculatedSize = size;
return value.CalculatedSize;
}
default:
throw new ArgumentOutOfRangeException(nameof(t), "Unexpected token when writing BSON: {0}".FormatWith(CultureInfo.InvariantCulture, t.Type));
}
}
}
}

View File

@ -0,0 +1,60 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a BSON Oid (object id).
/// </summary>
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonObjectId
{
/// <summary>
/// Gets or sets the value of the Oid.
/// </summary>
/// <value>The value of the Oid.</value>
public byte[] Value { get; }
/// <summary>
/// Initializes a new instance of the <see cref="BsonObjectId"/> class.
/// </summary>
/// <param name="value">The Oid value.</param>
public BsonObjectId(byte[] value)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value.Length != 12)
{
throw new ArgumentException("An ObjectId must be 12 bytes", nameof(value));
}
Value = value;
}
}
}

View File

@ -0,0 +1,836 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Text;
using System.IO;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
#nullable disable
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a reader that provides fast, non-cached, forward-only access to serialized BSON data.
/// </summary>
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonReader : JsonReader
{
private const int MaxCharBytesSize = 128;
private static readonly byte[] SeqRange1 = new byte[] { 0, 127 }; // range of 1-byte sequence
private static readonly byte[] SeqRange2 = new byte[] { 194, 223 }; // range of 2-byte sequence
private static readonly byte[] SeqRange3 = new byte[] { 224, 239 }; // range of 3-byte sequence
private static readonly byte[] SeqRange4 = new byte[] { 240, 244 }; // range of 4-byte sequence
private readonly BinaryReader _reader;
private readonly List<ContainerContext> _stack;
private byte[] _byteBuffer;
private char[] _charBuffer;
private BsonType _currentElementType;
private BsonReaderState _bsonReaderState;
private ContainerContext _currentContext;
private bool _readRootValueAsArray;
private bool _jsonNet35BinaryCompatibility;
private DateTimeKind _dateTimeKindHandling;
private enum BsonReaderState
{
Normal = 0,
ReferenceStart = 1,
ReferenceRef = 2,
ReferenceId = 3,
CodeWScopeStart = 4,
CodeWScopeCode = 5,
CodeWScopeScope = 6,
CodeWScopeScopeObject = 7,
CodeWScopeScopeEnd = 8
}
private class ContainerContext
{
public readonly BsonType Type;
public int Length;
public int Position;
public ContainerContext(BsonType type)
{
Type = type;
}
}
/// <summary>
/// Gets or sets a value indicating whether binary data reading should be compatible with incorrect Json.NET 3.5 written binary.
/// </summary>
/// <value>
/// <c>true</c> if binary data reading will be compatible with incorrect Json.NET 3.5 written binary; otherwise, <c>false</c>.
/// </value>
[Obsolete("JsonNet35BinaryCompatibility will be removed in a future version of Json.NET.")]
public bool JsonNet35BinaryCompatibility
{
get => _jsonNet35BinaryCompatibility;
set => _jsonNet35BinaryCompatibility = value;
}
/// <summary>
/// Gets or sets a value indicating whether the root object will be read as a JSON array.
/// </summary>
/// <value>
/// <c>true</c> if the root object will be read as a JSON array; otherwise, <c>false</c>.
/// </value>
public bool ReadRootValueAsArray
{
get => _readRootValueAsArray;
set => _readRootValueAsArray = value;
}
/// <summary>
/// Gets or sets the <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.
/// </summary>
/// <value>The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</value>
public DateTimeKind DateTimeKindHandling
{
get => _dateTimeKindHandling;
set => _dateTimeKindHandling = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing the BSON data to read.</param>
public BsonReader(Stream stream)
: this(stream, false, DateTimeKind.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="reader">The <see cref="BinaryReader"/> containing the BSON data to read.</param>
public BsonReader(BinaryReader reader)
: this(reader, false, DateTimeKind.Local)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> containing the BSON data to read.</param>
/// <param name="readRootValueAsArray">if set to <c>true</c> the root object will be read as a JSON array.</param>
/// <param name="dateTimeKindHandling">The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</param>
public BsonReader(Stream stream, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(stream, nameof(stream));
_reader = new BinaryReader(stream);
_stack = new List<ContainerContext>();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonReader"/> class.
/// </summary>
/// <param name="reader">The <see cref="BinaryReader"/> containing the BSON data to read.</param>
/// <param name="readRootValueAsArray">if set to <c>true</c> the root object will be read as a JSON array.</param>
/// <param name="dateTimeKindHandling">The <see cref="DateTimeKind" /> used when reading <see cref="DateTime"/> values from BSON.</param>
public BsonReader(BinaryReader reader, bool readRootValueAsArray, DateTimeKind dateTimeKindHandling)
{
ValidationUtils.ArgumentNotNull(reader, nameof(reader));
_reader = reader;
_stack = new List<ContainerContext>();
_readRootValueAsArray = readRootValueAsArray;
_dateTimeKindHandling = dateTimeKindHandling;
}
private string ReadElement()
{
_currentElementType = ReadType();
string elementName = ReadString();
return elementName;
}
/// <summary>
/// Reads the next JSON token from the underlying <see cref="Stream"/>.
/// </summary>
/// <returns>
/// <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.
/// </returns>
public override bool Read()
{
try
{
bool success;
switch (_bsonReaderState)
{
case BsonReaderState.Normal:
success = ReadNormal();
break;
case BsonReaderState.ReferenceStart:
case BsonReaderState.ReferenceRef:
case BsonReaderState.ReferenceId:
success = ReadReference();
break;
case BsonReaderState.CodeWScopeStart:
case BsonReaderState.CodeWScopeCode:
case BsonReaderState.CodeWScopeScope:
case BsonReaderState.CodeWScopeScopeObject:
case BsonReaderState.CodeWScopeScopeEnd:
success = ReadCodeWScope();
break;
default:
throw JsonReaderException.Create(this, "Unexpected state: {0}".FormatWith(CultureInfo.InvariantCulture, _bsonReaderState));
}
if (!success)
{
SetToken(JsonToken.None);
return false;
}
return true;
}
catch (EndOfStreamException)
{
SetToken(JsonToken.None);
return false;
}
}
/// <summary>
/// Changes the reader's state to <see cref="JsonReader.State.Closed"/>.
/// If <see cref="JsonReader.CloseInput"/> is set to <c>true</c>, the underlying <see cref="Stream"/> is also closed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseInput)
{
#if HAVE_STREAM_READER_WRITER_CLOSE
_reader?.Close();
#else
_reader?.Dispose();
#endif
}
}
private bool ReadCodeWScope()
{
switch (_bsonReaderState)
{
case BsonReaderState.CodeWScopeStart:
SetToken(JsonToken.PropertyName, "$code");
_bsonReaderState = BsonReaderState.CodeWScopeCode;
return true;
case BsonReaderState.CodeWScopeCode:
// total CodeWScope size - not used
ReadInt32();
SetToken(JsonToken.String, ReadLengthString());
_bsonReaderState = BsonReaderState.CodeWScopeScope;
return true;
case BsonReaderState.CodeWScopeScope:
if (CurrentState == State.PostValue)
{
SetToken(JsonToken.PropertyName, "$scope");
return true;
}
else
{
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeScopeObject;
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case BsonReaderState.CodeWScopeScopeObject:
bool result = ReadNormal();
if (result && TokenType == JsonToken.EndObject)
{
_bsonReaderState = BsonReaderState.CodeWScopeScopeEnd;
}
return result;
case BsonReaderState.CodeWScopeScopeEnd:
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
default:
throw new ArgumentOutOfRangeException();
}
}
private bool ReadReference()
{
switch (CurrentState)
{
case State.ObjectStart:
{
SetToken(JsonToken.PropertyName, JsonTypeReflector.RefPropertyName);
_bsonReaderState = BsonReaderState.ReferenceRef;
return true;
}
case State.Property:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.String, ReadLengthString());
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.Bytes, ReadBytes(12));
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
case State.PostValue:
{
if (_bsonReaderState == BsonReaderState.ReferenceRef)
{
SetToken(JsonToken.PropertyName, JsonTypeReflector.IdPropertyName);
_bsonReaderState = BsonReaderState.ReferenceId;
return true;
}
else if (_bsonReaderState == BsonReaderState.ReferenceId)
{
SetToken(JsonToken.EndObject);
_bsonReaderState = BsonReaderState.Normal;
return true;
}
else
{
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + _bsonReaderState);
}
}
default:
throw JsonReaderException.Create(this, "Unexpected state when reading BSON reference: " + CurrentState);
}
}
private bool ReadNormal()
{
switch (CurrentState)
{
case State.Start:
{
JsonToken token = (!_readRootValueAsArray) ? JsonToken.StartObject : JsonToken.StartArray;
BsonType type = (!_readRootValueAsArray) ? BsonType.Object : BsonType.Array;
SetToken(token);
ContainerContext newContext = new ContainerContext(type);
PushContext(newContext);
newContext.Length = ReadInt32();
return true;
}
case State.Complete:
case State.Closed:
return false;
case State.Property:
{
ReadType(_currentElementType);
return true;
}
case State.ObjectStart:
case State.ArrayStart:
case State.PostValue:
ContainerContext context = _currentContext;
if (context == null)
{
if (SupportMultipleContent)
{
goto case State.Start;
}
return false;
}
int lengthMinusEnd = context.Length - 1;
if (context.Position < lengthMinusEnd)
{
if (context.Type == BsonType.Array)
{
ReadElement();
ReadType(_currentElementType);
return true;
}
else
{
SetToken(JsonToken.PropertyName, ReadElement());
return true;
}
}
else if (context.Position == lengthMinusEnd)
{
if (ReadByte() != 0)
{
throw JsonReaderException.Create(this, "Unexpected end of object byte value.");
}
PopContext();
if (_currentContext != null)
{
MovePosition(context.Length);
}
JsonToken endToken = (context.Type == BsonType.Object) ? JsonToken.EndObject : JsonToken.EndArray;
SetToken(endToken);
return true;
}
else
{
throw JsonReaderException.Create(this, "Read past end of current container context.");
}
case State.ConstructorStart:
break;
case State.Constructor:
break;
case State.Error:
break;
case State.Finished:
break;
default:
throw new ArgumentOutOfRangeException();
}
return false;
}
private void PopContext()
{
_stack.RemoveAt(_stack.Count - 1);
if (_stack.Count == 0)
{
_currentContext = null;
}
else
{
_currentContext = _stack[_stack.Count - 1];
}
}
private void PushContext(ContainerContext newContext)
{
_stack.Add(newContext);
_currentContext = newContext;
}
private byte ReadByte()
{
MovePosition(1);
return _reader.ReadByte();
}
private void ReadType(BsonType type)
{
switch (type)
{
case BsonType.Number:
double d = ReadDouble();
if (_floatParseHandling == FloatParseHandling.Decimal)
{
SetToken(JsonToken.Float, Convert.ToDecimal(d, CultureInfo.InvariantCulture));
}
else
{
SetToken(JsonToken.Float, d);
}
break;
case BsonType.String:
case BsonType.Symbol:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.Object:
{
SetToken(JsonToken.StartObject);
ContainerContext newContext = new ContainerContext(BsonType.Object);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Array:
{
SetToken(JsonToken.StartArray);
ContainerContext newContext = new ContainerContext(BsonType.Array);
PushContext(newContext);
newContext.Length = ReadInt32();
break;
}
case BsonType.Binary:
BsonBinaryType binaryType;
byte[] data = ReadBinary(out binaryType);
object value = (binaryType != BsonBinaryType.Uuid)
? data
: (object)new Guid(data);
SetToken(JsonToken.Bytes, value);
break;
case BsonType.Undefined:
SetToken(JsonToken.Undefined);
break;
case BsonType.Oid:
byte[] oid = ReadBytes(12);
SetToken(JsonToken.Bytes, oid);
break;
case BsonType.Boolean:
bool b = Convert.ToBoolean(ReadByte());
SetToken(JsonToken.Boolean, b);
break;
case BsonType.Date:
long ticks = ReadInt64();
DateTime utcDateTime = DateTimeUtils.ConvertJavaScriptTicksToDateTime(ticks);
DateTime dateTime;
switch (DateTimeKindHandling)
{
case DateTimeKind.Unspecified:
dateTime = DateTime.SpecifyKind(utcDateTime, DateTimeKind.Unspecified);
break;
case DateTimeKind.Local:
dateTime = utcDateTime.ToLocalTime();
break;
default:
dateTime = utcDateTime;
break;
}
SetToken(JsonToken.Date, dateTime);
break;
case BsonType.Null:
SetToken(JsonToken.Null);
break;
case BsonType.Regex:
string expression = ReadString();
string modifiers = ReadString();
string regex = @"/" + expression + @"/" + modifiers;
SetToken(JsonToken.String, regex);
break;
case BsonType.Reference:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.ReferenceStart;
break;
case BsonType.Code:
SetToken(JsonToken.String, ReadLengthString());
break;
case BsonType.CodeWScope:
SetToken(JsonToken.StartObject);
_bsonReaderState = BsonReaderState.CodeWScopeStart;
break;
case BsonType.Integer:
SetToken(JsonToken.Integer, (long)ReadInt32());
break;
case BsonType.TimeStamp:
case BsonType.Long:
SetToken(JsonToken.Integer, ReadInt64());
break;
default:
throw new ArgumentOutOfRangeException(nameof(type), "Unexpected BsonType value: " + type);
}
}
private byte[] ReadBinary(out BsonBinaryType binaryType)
{
int dataLength = ReadInt32();
binaryType = (BsonBinaryType)ReadByte();
#pragma warning disable 612,618
// the old binary type has the data length repeated in the data for some reason
if (binaryType == BsonBinaryType.BinaryOld && !_jsonNet35BinaryCompatibility)
{
dataLength = ReadInt32();
}
#pragma warning restore 612,618
return ReadBytes(dataLength);
}
private string ReadString()
{
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
while (true)
{
int count = offset;
byte b;
while (count < MaxCharBytesSize && (b = _reader.ReadByte()) > 0)
{
_byteBuffer[count++] = b;
}
int byteCount = count - offset;
totalBytesRead += byteCount;
if (count < MaxCharBytesSize && builder == null)
{
// pref optimization to avoid reading into a string builder
// if string is smaller than the buffer then return it directly
int length = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
MovePosition(totalBytesRead + 1);
return new string(_charBuffer, 0, length);
}
else
{
// calculate the index of the end of the last full character in the buffer
int lastFullCharStop = GetLastFullCharStop(count - 1);
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
if (builder == null)
{
builder = new StringBuilder(MaxCharBytesSize * 2);
}
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
// reached end of string
if (count < MaxCharBytesSize)
{
MovePosition(totalBytesRead + 1);
return builder.ToString();
}
offset = 0;
}
}
}
}
private string ReadLengthString()
{
int length = ReadInt32();
MovePosition(length);
string s = GetString(length - 1);
_reader.ReadByte();
return s;
}
private string GetString(int length)
{
if (length == 0)
{
return string.Empty;
}
EnsureBuffers();
StringBuilder builder = null;
int totalBytesRead = 0;
// used in case of left over multibyte characters in the buffer
int offset = 0;
do
{
int count = ((length - totalBytesRead) > MaxCharBytesSize - offset)
? MaxCharBytesSize - offset
: length - totalBytesRead;
int byteCount = _reader.Read(_byteBuffer, offset, count);
if (byteCount == 0)
{
throw new EndOfStreamException("Unable to read beyond the end of the stream.");
}
totalBytesRead += byteCount;
// Above, byteCount is how many bytes we read this time.
// Below, byteCount is how many bytes are in the _byteBuffer.
byteCount += offset;
if (byteCount == length)
{
// pref optimization to avoid reading into a string builder
// first iteration and all bytes read then return string directly
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, byteCount, _charBuffer, 0);
return new string(_charBuffer, 0, charCount);
}
else
{
int lastFullCharStop = GetLastFullCharStop(byteCount - 1);
if (builder == null)
{
builder = new StringBuilder(length);
}
int charCount = Encoding.UTF8.GetChars(_byteBuffer, 0, lastFullCharStop + 1, _charBuffer, 0);
builder.Append(_charBuffer, 0, charCount);
if (lastFullCharStop < byteCount - 1)
{
offset = byteCount - lastFullCharStop - 1;
// copy left over multi byte characters to beginning of buffer for next iteration
Array.Copy(_byteBuffer, lastFullCharStop + 1, _byteBuffer, 0, offset);
}
else
{
offset = 0;
}
}
} while (totalBytesRead < length);
return builder.ToString();
}
private int GetLastFullCharStop(int start)
{
int lookbackPos = start;
int bis = 0;
while (lookbackPos >= 0)
{
bis = BytesInSequence(_byteBuffer[lookbackPos]);
if (bis == 0)
{
lookbackPos--;
continue;
}
else if (bis == 1)
{
break;
}
else
{
lookbackPos--;
break;
}
}
if (bis == start - lookbackPos)
{
//Full character.
return start;
}
else
{
return lookbackPos;
}
}
private int BytesInSequence(byte b)
{
if (b <= SeqRange1[1])
{
return 1;
}
if (b >= SeqRange2[0] && b <= SeqRange2[1])
{
return 2;
}
if (b >= SeqRange3[0] && b <= SeqRange3[1])
{
return 3;
}
if (b >= SeqRange4[0] && b <= SeqRange4[1])
{
return 4;
}
return 0;
}
private void EnsureBuffers()
{
if (_byteBuffer == null)
{
_byteBuffer = new byte[MaxCharBytesSize];
}
if (_charBuffer == null)
{
int charBufferSize = Encoding.UTF8.GetMaxCharCount(MaxCharBytesSize);
_charBuffer = new char[charBufferSize];
}
}
private double ReadDouble()
{
MovePosition(8);
return _reader.ReadDouble();
}
private int ReadInt32()
{
MovePosition(4);
return _reader.ReadInt32();
}
private long ReadInt64()
{
MovePosition(8);
return _reader.ReadInt64();
}
private BsonType ReadType()
{
MovePosition(1);
return (BsonType)_reader.ReadSByte();
}
private void MovePosition(int count)
{
_currentContext.Position += count;
}
private byte[] ReadBytes(int count)
{
MovePosition(count);
return _reader.ReadBytes(count);
}
}
}

View File

@ -0,0 +1,168 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System.Collections;
using System.Collections.Generic;
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal abstract class BsonToken
{
public abstract BsonType Type { get; }
public BsonToken Parent { get; set; }
public int CalculatedSize { get; set; }
}
internal class BsonObject : BsonToken, IEnumerable<BsonProperty>
{
private readonly List<BsonProperty> _children = new List<BsonProperty>();
public void Add(string name, BsonToken token)
{
_children.Add(new BsonProperty { Name = new BsonString(name, false), Value = token });
token.Parent = this;
}
public override BsonType Type => BsonType.Object;
public IEnumerator<BsonProperty> GetEnumerator()
{
return _children.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class BsonArray : BsonToken, IEnumerable<BsonToken>
{
private readonly List<BsonToken> _children = new List<BsonToken>();
public void Add(BsonToken token)
{
_children.Add(token);
token.Parent = this;
}
public override BsonType Type => BsonType.Array;
public IEnumerator<BsonToken> GetEnumerator()
{
return _children.GetEnumerator();
}
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
internal class BsonEmpty : BsonToken
{
public static readonly BsonToken Null = new BsonEmpty(BsonType.Null);
public static readonly BsonToken Undefined = new BsonEmpty(BsonType.Undefined);
private BsonEmpty(BsonType type)
{
Type = type;
}
public override BsonType Type { get; }
}
internal class BsonValue : BsonToken
{
private readonly object _value;
private readonly BsonType _type;
public BsonValue(object value, BsonType type)
{
_value = value;
_type = type;
}
public object Value => _value;
public override BsonType Type => _type;
}
internal class BsonBoolean : BsonValue
{
public static readonly BsonBoolean False = new BsonBoolean(false);
public static readonly BsonBoolean True = new BsonBoolean(true);
private BsonBoolean(bool value)
: base(value, BsonType.Boolean)
{
}
}
internal class BsonString : BsonValue
{
public int ByteCount { get; set; }
public bool IncludeLength { get; }
public BsonString(object value, bool includeLength)
: base(value, BsonType.String)
{
IncludeLength = includeLength;
}
}
internal class BsonBinary : BsonValue
{
public BsonBinaryType BinaryType { get; set; }
public BsonBinary(byte[] value, BsonBinaryType binaryType)
: base(value, BsonType.Binary)
{
BinaryType = binaryType;
}
}
internal class BsonRegex : BsonToken
{
public BsonString Pattern { get; set; }
public BsonString Options { get; set; }
public BsonRegex(string pattern, string options)
{
Pattern = new BsonString(pattern, false);
Options = new BsonString(options, false);
}
public override BsonType Type => BsonType.Regex;
}
internal class BsonProperty
{
public BsonString Name { get; set; }
public BsonToken Value { get; set; }
}
}

View File

@ -0,0 +1,53 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#nullable disable
namespace Newtonsoft.Json.Bson
{
internal enum BsonType : sbyte
{
Number = 1,
String = 2,
Object = 3,
Array = 4,
Binary = 5,
Undefined = 6,
Oid = 7,
Boolean = 8,
Date = 9,
Null = 10,
Regex = 11,
Reference = 12,
Code = 13,
Symbol = 14,
CodeWScope = 15,
Integer = 16,
TimeStamp = 17,
Long = 18,
MinKey = -1,
MaxKey = 127
}
}

View File

@ -0,0 +1,539 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
#if HAVE_BIG_INTEGER
using System.Numerics;
#endif
using System.Text;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Linq;
using System.Globalization;
#nullable disable
namespace Newtonsoft.Json.Bson
{
/// <summary>
/// Represents a writer that provides a fast, non-cached, forward-only way of generating BSON data.
/// </summary>
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonWriter : JsonWriter
{
private readonly BsonBinaryWriter _writer;
private BsonToken _root;
private BsonToken _parent;
private string _propertyName;
/// <summary>
/// Gets or sets the <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON.
/// When set to <see cref="DateTimeKind.Unspecified" /> no conversion will occur.
/// </summary>
/// <value>The <see cref="DateTimeKind" /> used when writing <see cref="DateTime"/> values to BSON.</value>
public DateTimeKind DateTimeKindHandling
{
get => _writer.DateTimeKindHandling;
set => _writer.DateTimeKindHandling = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonWriter"/> class.
/// </summary>
/// <param name="stream">The <see cref="Stream"/> to write to.</param>
public BsonWriter(Stream stream)
{
ValidationUtils.ArgumentNotNull(stream, nameof(stream));
_writer = new BsonBinaryWriter(new BinaryWriter(stream));
}
/// <summary>
/// Initializes a new instance of the <see cref="BsonWriter"/> class.
/// </summary>
/// <param name="writer">The <see cref="BinaryWriter"/> to write to.</param>
public BsonWriter(BinaryWriter writer)
{
ValidationUtils.ArgumentNotNull(writer, nameof(writer));
_writer = new BsonBinaryWriter(writer);
}
/// <summary>
/// Flushes whatever is in the buffer to the underlying <see cref="Stream"/> and also flushes the underlying stream.
/// </summary>
public override void Flush()
{
_writer.Flush();
}
/// <summary>
/// Writes the end.
/// </summary>
/// <param name="token">The token.</param>
protected override void WriteEnd(JsonToken token)
{
base.WriteEnd(token);
RemoveParent();
if (Top == 0)
{
_writer.WriteToken(_root);
}
}
/// <summary>
/// Writes a comment <c>/*...*/</c> containing the specified text.
/// </summary>
/// <param name="text">Text to place inside the comment.</param>
public override void WriteComment(string text)
{
throw JsonWriterException.Create(this, "Cannot write JSON comment as BSON.", null);
}
/// <summary>
/// Writes the start of a constructor with the given name.
/// </summary>
/// <param name="name">The name of the constructor.</param>
public override void WriteStartConstructor(string name)
{
throw JsonWriterException.Create(this, "Cannot write JSON constructor as BSON.", null);
}
/// <summary>
/// Writes raw JSON.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRaw(string json)
{
throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
/// <summary>
/// Writes raw JSON where a value is expected and updates the writer's state.
/// </summary>
/// <param name="json">The raw JSON to write.</param>
public override void WriteRawValue(string json)
{
throw JsonWriterException.Create(this, "Cannot write raw JSON as BSON.", null);
}
/// <summary>
/// Writes the beginning of a JSON array.
/// </summary>
public override void WriteStartArray()
{
base.WriteStartArray();
AddParent(new BsonArray());
}
/// <summary>
/// Writes the beginning of a JSON object.
/// </summary>
public override void WriteStartObject()
{
base.WriteStartObject();
AddParent(new BsonObject());
}
/// <summary>
/// Writes the property name of a name/value pair on a JSON object.
/// </summary>
/// <param name="name">The name of the property.</param>
public override void WritePropertyName(string name)
{
base.WritePropertyName(name);
_propertyName = name;
}
/// <summary>
/// Closes this writer.
/// If <see cref="JsonWriter.CloseOutput"/> is set to <c>true</c>, the underlying <see cref="Stream"/> is also closed.
/// If <see cref="JsonWriter.AutoCompleteOnClose"/> is set to <c>true</c>, the JSON is auto-completed.
/// </summary>
public override void Close()
{
base.Close();
if (CloseOutput)
{
_writer?.Close();
}
}
private void AddParent(BsonToken container)
{
AddToken(container);
_parent = container;
}
private void RemoveParent()
{
_parent = _parent.Parent;
}
private void AddValue(object value, BsonType type)
{
AddToken(new BsonValue(value, type));
}
internal void AddToken(BsonToken token)
{
if (_parent != null)
{
if (_parent is BsonObject bo)
{
bo.Add(_propertyName, token);
_propertyName = null;
}
else
{
((BsonArray)_parent).Add(token);
}
}
else
{
if (token.Type != BsonType.Object && token.Type != BsonType.Array)
{
throw JsonWriterException.Create(this, "Error writing {0} value. BSON must start with an Object or Array.".FormatWith(CultureInfo.InvariantCulture, token.Type), null);
}
_parent = token;
_root = token;
}
}
#region WriteValue methods
/// <summary>
/// Writes a <see cref="Object"/> value.
/// An error will raised if the value cannot be written as a single JSON token.
/// </summary>
/// <param name="value">The <see cref="Object"/> value to write.</param>
public override void WriteValue(object value)
{
#if HAVE_BIG_INTEGER
if (value is BigInteger i)
{
SetWriteState(JsonToken.Integer, null);
AddToken(new BsonBinary(i.ToByteArray(), BsonBinaryType.Binary));
}
else
#endif
{
base.WriteValue(value);
}
}
/// <summary>
/// Writes a null value.
/// </summary>
public override void WriteNull()
{
base.WriteNull();
AddToken(BsonEmpty.Null);
}
/// <summary>
/// Writes an undefined value.
/// </summary>
public override void WriteUndefined()
{
base.WriteUndefined();
AddToken(BsonEmpty.Undefined);
}
/// <summary>
/// Writes a <see cref="String"/> value.
/// </summary>
/// <param name="value">The <see cref="String"/> value to write.</param>
public override void WriteValue(string value)
{
base.WriteValue(value);
AddToken(value == null ? BsonEmpty.Null : new BsonString(value, true));
}
/// <summary>
/// Writes a <see cref="Int32"/> value.
/// </summary>
/// <param name="value">The <see cref="Int32"/> value to write.</param>
public override void WriteValue(int value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="UInt32"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt32"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(uint value)
{
if (value > int.MaxValue)
{
throw JsonWriterException.Create(this, "Value is too large to fit in a signed 32 bit integer. BSON does not support unsigned values.", null);
}
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Int64"/> value.
/// </summary>
/// <param name="value">The <see cref="Int64"/> value to write.</param>
public override void WriteValue(long value)
{
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
/// <summary>
/// Writes a <see cref="UInt64"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt64"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(ulong value)
{
if (value > long.MaxValue)
{
throw JsonWriterException.Create(this, "Value is too large to fit in a signed 64 bit integer. BSON does not support unsigned values.", null);
}
base.WriteValue(value);
AddValue(value, BsonType.Long);
}
/// <summary>
/// Writes a <see cref="Single"/> value.
/// </summary>
/// <param name="value">The <see cref="Single"/> value to write.</param>
public override void WriteValue(float value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="Double"/> value.
/// </summary>
/// <param name="value">The <see cref="Double"/> value to write.</param>
public override void WriteValue(double value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="Boolean"/> value.
/// </summary>
/// <param name="value">The <see cref="Boolean"/> value to write.</param>
public override void WriteValue(bool value)
{
base.WriteValue(value);
AddToken(value ? BsonBoolean.True : BsonBoolean.False);
}
/// <summary>
/// Writes a <see cref="Int16"/> value.
/// </summary>
/// <param name="value">The <see cref="Int16"/> value to write.</param>
public override void WriteValue(short value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="UInt16"/> value.
/// </summary>
/// <param name="value">The <see cref="UInt16"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(ushort value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Char"/> value.
/// </summary>
/// <param name="value">The <see cref="Char"/> value to write.</param>
public override void WriteValue(char value)
{
base.WriteValue(value);
string s = null;
#if HAVE_CHAR_TO_STRING_WITH_CULTURE
s = value.ToString(CultureInfo.InvariantCulture);
#else
s = value.ToString();
#endif
AddToken(new BsonString(s, true));
}
/// <summary>
/// Writes a <see cref="Byte"/> value.
/// </summary>
/// <param name="value">The <see cref="Byte"/> value to write.</param>
public override void WriteValue(byte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="SByte"/> value.
/// </summary>
/// <param name="value">The <see cref="SByte"/> value to write.</param>
[CLSCompliant(false)]
public override void WriteValue(sbyte value)
{
base.WriteValue(value);
AddValue(value, BsonType.Integer);
}
/// <summary>
/// Writes a <see cref="Decimal"/> value.
/// </summary>
/// <param name="value">The <see cref="Decimal"/> value to write.</param>
public override void WriteValue(decimal value)
{
base.WriteValue(value);
AddValue(value, BsonType.Number);
}
/// <summary>
/// Writes a <see cref="DateTime"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTime"/> value to write.</param>
public override void WriteValue(DateTime value)
{
base.WriteValue(value);
value = DateTimeUtils.EnsureDateTime(value, DateTimeZoneHandling);
AddValue(value, BsonType.Date);
}
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Writes a <see cref="DateTimeOffset"/> value.
/// </summary>
/// <param name="value">The <see cref="DateTimeOffset"/> value to write.</param>
public override void WriteValue(DateTimeOffset value)
{
base.WriteValue(value);
AddValue(value, BsonType.Date);
}
#endif
/// <summary>
/// Writes a <see cref="Byte"/>[] value.
/// </summary>
/// <param name="value">The <see cref="Byte"/>[] value to write.</param>
public override void WriteValue(byte[] value)
{
if (value == null)
{
WriteNull();
return;
}
base.WriteValue(value);
AddToken(new BsonBinary(value, BsonBinaryType.Binary));
}
/// <summary>
/// Writes a <see cref="Guid"/> value.
/// </summary>
/// <param name="value">The <see cref="Guid"/> value to write.</param>
public override void WriteValue(Guid value)
{
base.WriteValue(value);
AddToken(new BsonBinary(value.ToByteArray(), BsonBinaryType.Uuid));
}
/// <summary>
/// Writes a <see cref="TimeSpan"/> value.
/// </summary>
/// <param name="value">The <see cref="TimeSpan"/> value to write.</param>
public override void WriteValue(TimeSpan value)
{
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
/// <summary>
/// Writes a <see cref="Uri"/> value.
/// </summary>
/// <param name="value">The <see cref="Uri"/> value to write.</param>
public override void WriteValue(Uri value)
{
if (value == null)
{
WriteNull();
return;
}
base.WriteValue(value);
AddToken(new BsonString(value.ToString(), true));
}
#endregion
/// <summary>
/// Writes a <see cref="Byte"/>[] value that represents a BSON object id.
/// </summary>
/// <param name="value">The Object ID value to write.</param>
public void WriteObjectId(byte[] value)
{
ValidationUtils.ArgumentNotNull(value, nameof(value));
if (value.Length != 12)
{
throw JsonWriterException.Create(this, "An object id must be 12 bytes", null);
}
// hack to update the writer state
SetWriteState(JsonToken.Undefined, null);
AddValue(value, BsonType.Oid);
}
/// <summary>
/// Writes a BSON regex.
/// </summary>
/// <param name="pattern">The regex pattern.</param>
/// <param name="options">The regex options.</param>
public void WriteRegex(string pattern, string options)
{
ValidationUtils.ArgumentNotNull(pattern, nameof(pattern));
// hack to update the writer state
SetWriteState(JsonToken.Undefined, null);
AddToken(new BsonRegex(pattern, options));
}
}
}

View File

@ -0,0 +1,43 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies how constructors are used when initializing objects during deserialization by the <see cref="JsonSerializer"/>.
/// </summary>
public enum ConstructorHandling
{
/// <summary>
/// First attempt to use the public default constructor, then fall back to a single parameterized constructor, then to the non-public default constructor.
/// </summary>
Default = 0,
/// <summary>
/// Json.NET will use a non-public default constructor before falling back to a parameterized constructor.
/// </summary>
AllowNonPublicDefaultConstructor = 1
}
}

View File

@ -0,0 +1,212 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_LINQ || HAVE_ADO_NET
using System;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System.Collections.Generic;
using System.Diagnostics;
#if HAVE_ADO_NET
using System.Data.SqlTypes;
#endif
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a binary value to and from a base 64 string value.
/// </summary>
public class BinaryConverter : JsonConverter
{
#if HAVE_LINQ
private const string BinaryTypeName = "System.Data.Linq.Binary";
private const string BinaryToArrayName = "ToArray";
private static ReflectionObject? _reflectionObject;
#endif
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
byte[] data = GetByteArray(value);
writer.WriteValue(data);
}
private byte[] GetByteArray(object value)
{
#if HAVE_LINQ
if (value.GetType().FullName == BinaryTypeName)
{
EnsureReflectionObject(value.GetType());
MiscellaneousUtils.Assert(_reflectionObject != null);
return (byte[])_reflectionObject.GetValue(value, BinaryToArrayName)!;
}
#endif
#if HAVE_ADO_NET
if (value is SqlBinary binary)
{
return binary.Value;
}
#endif
throw new JsonSerializationException("Unexpected value type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, value.GetType()));
}
#if HAVE_LINQ
private static void EnsureReflectionObject(Type t)
{
if (_reflectionObject == null)
{
_reflectionObject = ReflectionObject.Create(t, t.GetConstructor(new[] { typeof(byte[]) }), BinaryToArrayName);
}
}
#endif
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
return null;
}
byte[] data;
if (reader.TokenType == JsonToken.StartArray)
{
data = ReadByteArray(reader);
}
else if (reader.TokenType == JsonToken.String)
{
// current token is already at base64 string
// unable to call ReadAsBytes so do it the old fashion way
string encodedData = reader.Value!.ToString();
data = Convert.FromBase64String(encodedData);
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token parsing binary. Expected String or StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
#if HAVE_LINQ
if (t.FullName == BinaryTypeName)
{
EnsureReflectionObject(t);
MiscellaneousUtils.Assert(_reflectionObject != null);
return _reflectionObject.Creator!(data);
}
#endif
#if HAVE_ADO_NET
if (t == typeof(SqlBinary))
{
return new SqlBinary(data);
}
#endif
throw JsonSerializationException.Create(reader, "Unexpected object type when writing binary: {0}".FormatWith(CultureInfo.InvariantCulture, objectType));
}
private byte[] ReadByteArray(JsonReader reader)
{
List<byte> byteList = new List<byte>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Integer:
byteList.Add(Convert.ToByte(reader.Value, CultureInfo.InvariantCulture));
break;
case JsonToken.EndArray:
return byteList.ToArray();
case JsonToken.Comment:
// skip
break;
default:
throw JsonSerializationException.Create(reader, "Unexpected token when reading bytes: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading bytes.");
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
#if HAVE_LINQ
if (objectType.FullName == BinaryTypeName)
{
return true;
}
#endif
#if HAVE_ADO_NET
if (objectType == typeof(SqlBinary) || objectType == typeof(SqlBinary?))
{
return true;
}
#endif
return false;
}
}
}
#endif

View File

@ -0,0 +1,93 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Bson;
using System.Globalization;
using Newtonsoft.Json.Utilities;
#nullable disable
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="BsonObjectId"/> to and from JSON and BSON.
/// </summary>
[Obsolete("BSON reading and writing has been moved to its own package. See https://www.nuget.org/packages/Newtonsoft.Json.Bson for more details.")]
public class BsonObjectIdConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer)
{
BsonObjectId objectId = (BsonObjectId)value;
if (writer is BsonWriter bsonWriter)
{
bsonWriter.WriteObjectId(objectId.Value);
}
else
{
writer.WriteValue(objectId.Value);
}
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
if (reader.TokenType != JsonToken.Bytes)
{
throw new JsonSerializationException("Expected Bytes but got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
byte[] value = (byte[])reader.Value;
return new BsonObjectId(value);
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(BsonObjectId));
}
}
}

View File

@ -0,0 +1,101 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Reflection;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Creates a custom object.
/// </summary>
/// <typeparam name="T">The object type to convert.</typeparam>
public abstract class CustomCreationConverter<T> : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
throw new NotSupportedException("CustomCreationConverter should only be used while deserializing.");
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
T value = Create(objectType);
if (value == null)
{
throw new JsonSerializationException("No object created.");
}
serializer.Populate(reader, value);
return value;
}
/// <summary>
/// Creates an object which will then be populated by the serializer.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>The created object.</returns>
public abstract T Create(Type objectType);
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite => false;
}
}

View File

@ -0,0 +1,125 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ADO_NET
using System;
using System.Data;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DataSet"/> to and from JSON.
/// </summary>
public class DataSetConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DataSet dataSet = (DataSet)value;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
DataTableConverter converter = new DataTableConverter();
writer.WriteStartObject();
foreach (DataTable table in dataSet.Tables)
{
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(table.TableName) : table.TableName);
converter.WriteJson(writer, table, serializer);
}
writer.WriteEndObject();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
// handle typed datasets
DataSet ds = (objectType == typeof(DataSet))
? new DataSet()
: (DataSet)Activator.CreateInstance(objectType);
DataTableConverter converter = new DataTableConverter();
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.PropertyName)
{
DataTable dt = ds.Tables[(string)reader.Value!];
bool exists = (dt != null);
dt = (DataTable)converter.ReadJson(reader, typeof(DataTable), dt, serializer)!;
if (!exists)
{
ds.Tables.Add(dt);
}
reader.ReadAndAssert();
}
return ds;
}
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
return typeof(DataSet).IsAssignableFrom(valueType);
}
}
}
#endif

View File

@ -0,0 +1,254 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ADO_NET
using System.Collections;
using System.Collections.Generic;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System;
using System.Data;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DataTable"/> to and from JSON.
/// </summary>
public class DataTableConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DataTable table = (DataTable)value;
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartArray();
foreach (DataRow row in table.Rows)
{
writer.WriteStartObject();
foreach (DataColumn column in row.Table.Columns)
{
object columnValue = row[column];
if (serializer.NullValueHandling == NullValueHandling.Ignore && (columnValue == null || columnValue == DBNull.Value))
{
continue;
}
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(column.ColumnName) : column.ColumnName);
serializer.Serialize(writer, columnValue);
}
writer.WriteEndObject();
}
writer.WriteEndArray();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
if (!(existingValue is DataTable dt))
{
// handle typed datasets
dt = (objectType == typeof(DataTable))
? new DataTable()
: (DataTable)Activator.CreateInstance(objectType);
}
// DataTable is inside a DataSet
// populate the name from the property name
if (reader.TokenType == JsonToken.PropertyName)
{
dt.TableName = (string)reader.Value!;
reader.ReadAndAssert();
if (reader.TokenType == JsonToken.Null)
{
return dt;
}
}
if (reader.TokenType != JsonToken.StartArray)
{
throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable. Expected StartArray, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
reader.ReadAndAssert();
while (reader.TokenType != JsonToken.EndArray)
{
CreateRow(reader, dt, serializer);
reader.ReadAndAssert();
}
return dt;
}
private static void CreateRow(JsonReader reader, DataTable dt, JsonSerializer serializer)
{
DataRow dr = dt.NewRow();
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.PropertyName)
{
string columnName = (string)reader.Value!;
reader.ReadAndAssert();
DataColumn column = dt.Columns[columnName];
if (column == null)
{
Type columnType = GetColumnDataType(reader);
column = new DataColumn(columnName, columnType);
dt.Columns.Add(column);
}
if (column.DataType == typeof(DataTable))
{
if (reader.TokenType == JsonToken.StartArray)
{
reader.ReadAndAssert();
}
DataTable nestedDt = new DataTable();
while (reader.TokenType != JsonToken.EndArray)
{
CreateRow(reader, nestedDt, serializer);
reader.ReadAndAssert();
}
dr[columnName] = nestedDt;
}
else if (column.DataType.IsArray && column.DataType != typeof(byte[]))
{
if (reader.TokenType == JsonToken.StartArray)
{
reader.ReadAndAssert();
}
List<object?> o = new List<object?>();
while (reader.TokenType != JsonToken.EndArray)
{
o.Add(reader.Value);
reader.ReadAndAssert();
}
Array destinationArray = Array.CreateInstance(column.DataType.GetElementType(), o.Count);
((IList)o).CopyTo(destinationArray, 0);
dr[columnName] = destinationArray;
}
else
{
object columnValue = (reader.Value != null)
? serializer.Deserialize(reader, column.DataType) ?? DBNull.Value
: DBNull.Value;
dr[columnName] = columnValue;
}
reader.ReadAndAssert();
}
dr.EndEdit();
dt.Rows.Add(dr);
}
private static Type GetColumnDataType(JsonReader reader)
{
JsonToken tokenType = reader.TokenType;
switch (tokenType)
{
case JsonToken.Integer:
case JsonToken.Boolean:
case JsonToken.Float:
case JsonToken.String:
case JsonToken.Date:
case JsonToken.Bytes:
return reader.ValueType!;
case JsonToken.Null:
case JsonToken.Undefined:
case JsonToken.EndArray:
return typeof(string);
case JsonToken.StartArray:
reader.ReadAndAssert();
if (reader.TokenType == JsonToken.StartObject)
{
return typeof(DataTable); // nested datatable
}
Type arrayType = GetColumnDataType(reader);
return arrayType.MakeArrayType();
default:
throw JsonSerializationException.Create(reader, "Unexpected JSON token when reading DataTable: {0}".FormatWith(CultureInfo.InvariantCulture, tokenType));
}
}
/// <summary>
/// Determines whether this instance can convert the specified value type.
/// </summary>
/// <param name="valueType">Type of the value.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified value type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type valueType)
{
return typeof(DataTable).IsAssignableFrom(valueType);
}
}
}
#endif

View File

@ -0,0 +1,58 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Provides a base class for converting a <see cref="DateTime"/> to and from JSON.
/// </summary>
public abstract class DateTimeConverterBase : JsonConverter
{
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
if (objectType == typeof(DateTime) || objectType == typeof(DateTime?))
{
return true;
}
#if HAVE_DATE_TIME_OFFSET
if (objectType == typeof(DateTimeOffset) || objectType == typeof(DateTimeOffset?))
{
return true;
}
#endif
return false;
}
}
}

View File

@ -0,0 +1,298 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_FSHARP_TYPES
using Newtonsoft.Json.Linq;
using System;
using System.Collections;
using System.Collections.Generic;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
using System.Reflection;
using Newtonsoft.Json.Serialization;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a F# discriminated union type to and from JSON.
/// </summary>
public class DiscriminatedUnionConverter : JsonConverter
{
#region UnionDefinition
internal class Union
{
public readonly FSharpFunction TagReader;
public readonly List<UnionCase> Cases;
public Union(FSharpFunction tagReader, List<UnionCase> cases)
{
TagReader = tagReader;
Cases = cases;
}
}
internal class UnionCase
{
public readonly int Tag;
public readonly string Name;
public readonly PropertyInfo[] Fields;
public readonly FSharpFunction FieldReader;
public readonly FSharpFunction Constructor;
public UnionCase(int tag, string name, PropertyInfo[] fields, FSharpFunction fieldReader, FSharpFunction constructor)
{
Tag = tag;
Name = name;
Fields = fields;
FieldReader = fieldReader;
Constructor = constructor;
}
}
#endregion
private const string CasePropertyName = "Case";
private const string FieldsPropertyName = "Fields";
private static readonly ThreadSafeStore<Type, Union> UnionCache = new ThreadSafeStore<Type, Union>(CreateUnion);
private static readonly ThreadSafeStore<Type, Type> UnionTypeLookupCache = new ThreadSafeStore<Type, Type>(CreateUnionTypeLookup);
private static Type CreateUnionTypeLookup(Type t)
{
// this lookup is because cases with fields are derived from union type
// need to get declaring type to avoid duplicate Unions in cache
// hacky but I can't find an API to get the declaring type without GetUnionCases
object[] cases = (object[])FSharpUtils.Instance.GetUnionCases(null, t, null)!;
object caseInfo = cases.First();
Type unionType = (Type)FSharpUtils.Instance.GetUnionCaseInfoDeclaringType(caseInfo)!;
return unionType;
}
private static Union CreateUnion(Type t)
{
Union u = new Union((FSharpFunction)FSharpUtils.Instance.PreComputeUnionTagReader(null, t, null), new List<UnionCase>());
object[] cases = (object[])FSharpUtils.Instance.GetUnionCases(null, t, null)!;
foreach (object unionCaseInfo in cases)
{
UnionCase unionCase = new UnionCase(
(int)FSharpUtils.Instance.GetUnionCaseInfoTag(unionCaseInfo),
(string)FSharpUtils.Instance.GetUnionCaseInfoName(unionCaseInfo),
(PropertyInfo[])FSharpUtils.Instance.GetUnionCaseInfoFields(unionCaseInfo)!,
(FSharpFunction)FSharpUtils.Instance.PreComputeUnionReader(null, unionCaseInfo, null),
(FSharpFunction)FSharpUtils.Instance.PreComputeUnionConstructor(null, unionCaseInfo, null));
u.Cases.Add(unionCase);
}
return u;
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
Type unionType = UnionTypeLookupCache.Get(value.GetType());
Union union = UnionCache.Get(unionType);
int tag = (int)union.TagReader.Invoke(value);
UnionCase caseInfo = union.Cases.Single(c => c.Tag == tag);
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(CasePropertyName) : CasePropertyName);
writer.WriteValue(caseInfo.Name);
if (caseInfo.Fields != null && caseInfo.Fields.Length > 0)
{
object[] fields = (object[])caseInfo.FieldReader.Invoke(value)!;
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(FieldsPropertyName) : FieldsPropertyName);
writer.WriteStartArray();
foreach (object field in fields)
{
serializer.Serialize(writer, field);
}
writer.WriteEndArray();
}
writer.WriteEndObject();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
UnionCase? caseInfo = null;
string? caseName = null;
JArray? fields = null;
// start object
reader.ReadAndAssert();
while (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value!.ToString();
if (string.Equals(propertyName, CasePropertyName, StringComparison.OrdinalIgnoreCase))
{
reader.ReadAndAssert();
Union union = UnionCache.Get(objectType);
caseName = reader.Value!.ToString();
caseInfo = union.Cases.SingleOrDefault(c => c.Name == caseName);
if (caseInfo == null)
{
throw JsonSerializationException.Create(reader, "No union type found with the name '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
}
}
else if (string.Equals(propertyName, FieldsPropertyName, StringComparison.OrdinalIgnoreCase))
{
reader.ReadAndAssert();
if (reader.TokenType != JsonToken.StartArray)
{
throw JsonSerializationException.Create(reader, "Union fields must been an array.");
}
fields = (JArray)JToken.ReadFrom(reader);
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected property '{0}' found when reading union.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
reader.ReadAndAssert();
}
if (caseInfo == null)
{
throw JsonSerializationException.Create(reader, "No '{0}' property with union name found.".FormatWith(CultureInfo.InvariantCulture, CasePropertyName));
}
object?[] typedFieldValues = new object?[caseInfo.Fields.Length];
if (caseInfo.Fields.Length > 0 && fields == null)
{
throw JsonSerializationException.Create(reader, "No '{0}' property with union fields found.".FormatWith(CultureInfo.InvariantCulture, FieldsPropertyName));
}
if (fields != null)
{
if (caseInfo.Fields.Length != fields.Count)
{
throw JsonSerializationException.Create(reader, "The number of field values does not match the number of properties defined by union '{0}'.".FormatWith(CultureInfo.InvariantCulture, caseName));
}
for (int i = 0; i < fields.Count; i++)
{
JToken t = fields[i];
PropertyInfo fieldProperty = caseInfo.Fields[i];
typedFieldValues[i] = t.ToObject(fieldProperty.PropertyType, serializer);
}
}
object[] args = { typedFieldValues };
return caseInfo.Constructor.Invoke(args);
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
if (typeof(IEnumerable).IsAssignableFrom(objectType))
{
return false;
}
// all fsharp objects have CompilationMappingAttribute
// get the fsharp assembly from the attribute and initialize latebound methods
object[] attributes;
#if HAVE_FULL_REFLECTION
attributes = objectType.GetCustomAttributes(true);
#else
attributes = objectType.GetTypeInfo().GetCustomAttributes(true).ToArray();
#endif
bool isFSharpType = false;
foreach (object attribute in attributes)
{
Type attributeType = attribute.GetType();
if (attributeType.FullName == "Microsoft.FSharp.Core.CompilationMappingAttribute")
{
FSharpUtils.EnsureInitialized(attributeType.Assembly());
isFSharpType = true;
break;
}
}
if (!isFSharpType)
{
return false;
}
return (bool)FSharpUtils.Instance.IsUnion(null, objectType, null);
}
}
}
#endif

View File

@ -0,0 +1,165 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ENTITY_FRAMEWORK
using System;
using Newtonsoft.Json.Serialization;
using System.Globalization;
using Newtonsoft.Json.Utilities;
using System.Diagnostics;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts an Entity Framework <see cref="T:System.Data.EntityKeyMember"/> to and from JSON.
/// </summary>
public class EntityKeyMemberConverter : JsonConverter
{
private const string EntityKeyMemberFullTypeName = "System.Data.EntityKeyMember";
private const string KeyPropertyName = "Key";
private const string TypePropertyName = "Type";
private const string ValuePropertyName = "Value";
private static ReflectionObject? _reflectionObject;
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
EnsureReflectionObject(value.GetType());
MiscellaneousUtils.Assert(_reflectionObject != null);
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
string keyName = (string)_reflectionObject.GetValue(value, KeyPropertyName)!;
object? keyValue = _reflectionObject.GetValue(value, ValuePropertyName);
Type? keyValueType = keyValue?.GetType();
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyPropertyName) : KeyPropertyName);
writer.WriteValue(keyName);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(TypePropertyName) : TypePropertyName);
writer.WriteValue(keyValueType?.FullName);
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValuePropertyName) : ValuePropertyName);
if (keyValueType != null)
{
if (JsonSerializerInternalWriter.TryConvertToString(keyValue!, keyValueType, out string? valueJson))
{
writer.WriteValue(valueJson);
}
else
{
writer.WriteValue(keyValue);
}
}
else
{
writer.WriteNull();
}
writer.WriteEndObject();
}
private static void ReadAndAssertProperty(JsonReader reader, string propertyName)
{
reader.ReadAndAssert();
if (reader.TokenType != JsonToken.PropertyName || !string.Equals(reader.Value?.ToString(), propertyName, StringComparison.OrdinalIgnoreCase))
{
throw new JsonSerializationException("Expected JSON property '{0}'.".FormatWith(CultureInfo.InvariantCulture, propertyName));
}
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
EnsureReflectionObject(objectType);
MiscellaneousUtils.Assert(_reflectionObject != null);
object entityKeyMember = _reflectionObject.Creator!();
ReadAndAssertProperty(reader, KeyPropertyName);
reader.ReadAndAssert();
_reflectionObject.SetValue(entityKeyMember, KeyPropertyName, reader.Value?.ToString());
ReadAndAssertProperty(reader, TypePropertyName);
reader.ReadAndAssert();
string? type = reader.Value?.ToString();
Type t = Type.GetType(type);
ReadAndAssertProperty(reader, ValuePropertyName);
reader.ReadAndAssert();
_reflectionObject.SetValue(entityKeyMember, ValuePropertyName, serializer.Deserialize(reader, t));
reader.ReadAndAssert();
return entityKeyMember;
}
private static void EnsureReflectionObject(Type objectType)
{
if (_reflectionObject == null)
{
_reflectionObject = ReflectionObject.Create(objectType, KeyPropertyName, ValuePropertyName);
}
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return objectType.AssignableToTypeName(EntityKeyMemberFullTypeName, false);
}
}
}
#endif

View File

@ -0,0 +1,165 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_DYNAMIC
using System;
using System.Collections.Generic;
using System.Dynamic;
using System.Globalization;
using System.Linq;
using System.Text;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts an <see cref="ExpandoObject"/> to and from JSON.
/// </summary>
public class ExpandoObjectConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
// can write is set to false
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
return ReadValue(reader);
}
private object? ReadValue(JsonReader reader)
{
if (!reader.MoveToContent())
{
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadObject(reader);
case JsonToken.StartArray:
return ReadList(reader);
default:
if (JsonTokenUtils.IsPrimitiveToken(reader.TokenType))
{
return reader.Value;
}
throw JsonSerializationException.Create(reader, "Unexpected token when converting ExpandoObject: {0}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
}
private object ReadList(JsonReader reader)
{
IList<object?> list = new List<object?>();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.Comment:
break;
default:
object? v = ReadValue(reader);
list.Add(v);
break;
case JsonToken.EndArray:
return list;
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
private object ReadObject(JsonReader reader)
{
IDictionary<string, object?> expandoObject = new ExpandoObject();
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value!.ToString();
if (!reader.Read())
{
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
object? v = ReadValue(reader);
expandoObject[propertyName] = v;
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
return expandoObject;
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading ExpandoObject.");
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return (objectType == typeof(ExpandoObject));
}
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value>
/// <c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.
/// </value>
public override bool CanWrite => false;
}
}
#endif

View File

@ -0,0 +1,194 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DateTime"/> to and from the ISO 8601 date format (e.g. <c>"2008-04-12T12:53Z"</c>).
/// </summary>
public class IsoDateTimeConverter : DateTimeConverterBase
{
private const string DefaultDateTimeFormat = "yyyy'-'MM'-'dd'T'HH':'mm':'ss.FFFFFFFK";
private DateTimeStyles _dateTimeStyles = DateTimeStyles.RoundtripKind;
private string? _dateTimeFormat;
private CultureInfo? _culture;
/// <summary>
/// Gets or sets the date time styles used when converting a date to and from JSON.
/// </summary>
/// <value>The date time styles used when converting a date to and from JSON.</value>
public DateTimeStyles DateTimeStyles
{
get => _dateTimeStyles;
set => _dateTimeStyles = value;
}
/// <summary>
/// Gets or sets the date time format used when converting a date to and from JSON.
/// </summary>
/// <value>The date time format used when converting a date to and from JSON.</value>
public string? DateTimeFormat
{
get => _dateTimeFormat ?? string.Empty;
set => _dateTimeFormat = (StringUtils.IsNullOrEmpty(value)) ? null : value;
}
/// <summary>
/// Gets or sets the culture used when converting a date to and from JSON.
/// </summary>
/// <value>The culture used when converting a date to and from JSON.</value>
public CultureInfo Culture
{
get => _culture ?? CultureInfo.CurrentCulture;
set => _culture = value;
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
string text;
if (value is DateTime dateTime)
{
if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
{
dateTime = dateTime.ToUniversalTime();
}
text = dateTime.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
}
#if HAVE_DATE_TIME_OFFSET
else if (value is DateTimeOffset dateTimeOffset)
{
if ((_dateTimeStyles & DateTimeStyles.AdjustToUniversal) == DateTimeStyles.AdjustToUniversal
|| (_dateTimeStyles & DateTimeStyles.AssumeUniversal) == DateTimeStyles.AssumeUniversal)
{
dateTimeOffset = dateTimeOffset.ToUniversalTime();
}
text = dateTimeOffset.ToString(_dateTimeFormat ?? DefaultDateTimeFormat, Culture);
}
#endif
else
{
throw new JsonSerializationException("Unexpected value when converting date. Expected DateTime or DateTimeOffset, got {0}.".FormatWith(CultureInfo.InvariantCulture, ReflectionUtils.GetObjectType(value)!));
}
writer.WriteValue(text);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullableType(objectType);
if (reader.TokenType == JsonToken.Null)
{
if (!nullable)
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
return null;
}
#if HAVE_DATE_TIME_OFFSET
Type t = (nullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
#endif
if (reader.TokenType == JsonToken.Date)
{
#if HAVE_DATE_TIME_OFFSET
if (t == typeof(DateTimeOffset))
{
return (reader.Value is DateTimeOffset) ? reader.Value : new DateTimeOffset((DateTime)reader.Value!);
}
// converter is expected to return a DateTime
if (reader.Value is DateTimeOffset offset)
{
return offset.DateTime;
}
#endif
return reader.Value;
}
if (reader.TokenType != JsonToken.String)
{
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
string? dateText = reader.Value?.ToString();
if (StringUtils.IsNullOrEmpty(dateText) && nullable)
{
return null;
}
#if HAVE_DATE_TIME_OFFSET
if (t == typeof(DateTimeOffset))
{
if (!StringUtils.IsNullOrEmpty(_dateTimeFormat))
{
return DateTimeOffset.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
}
else
{
return DateTimeOffset.Parse(dateText, Culture, _dateTimeStyles);
}
}
#endif
if (!StringUtils.IsNullOrEmpty(_dateTimeFormat))
{
return DateTime.ParseExact(dateText, _dateTimeFormat, Culture, _dateTimeStyles);
}
else
{
return DateTime.Parse(dateText, Culture, _dateTimeStyles);
}
}
}
}

View File

@ -0,0 +1,111 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DateTime"/> to and from a JavaScript <c>Date</c> constructor (e.g. <c>new Date(52231943)</c>).
/// </summary>
public class JavaScriptDateTimeConverter : DateTimeConverterBase
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
long ticks;
if (value is DateTime dateTime)
{
DateTime utcDateTime = dateTime.ToUniversalTime();
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTime);
}
#if HAVE_DATE_TIME_OFFSET
else if (value is DateTimeOffset dateTimeOffset)
{
DateTimeOffset utcDateTimeOffset = dateTimeOffset.ToUniversalTime();
ticks = DateTimeUtils.ConvertDateTimeToJavaScriptTicks(utcDateTimeOffset.UtcDateTime);
}
#endif
else
{
throw new JsonSerializationException("Expected date object value.");
}
writer.WriteStartConstructor("Date");
writer.WriteValue(ticks);
writer.WriteEndConstructor();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullable(objectType))
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
return null;
}
if (reader.TokenType != JsonToken.StartConstructor || !string.Equals(reader.Value?.ToString(), "Date", StringComparison.Ordinal))
{
throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing date. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
}
if (!JavaScriptUtils.TryGetDateFromConstructorJson(reader, out DateTime d, out string? errorMessage))
{
throw JsonSerializationException.Create(reader, errorMessage);
}
#if HAVE_DATE_TIME_OFFSET
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (t == typeof(DateTimeOffset))
{
return new DateTimeOffset(d);
}
#endif
return d;
}
}
}

View File

@ -0,0 +1,159 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
using System.Reflection;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="KeyValuePair{TKey,TValue}"/> to and from JSON.
/// </summary>
public class KeyValuePairConverter : JsonConverter
{
private const string KeyName = "Key";
private const string ValueName = "Value";
private static readonly ThreadSafeStore<Type, ReflectionObject> ReflectionObjectPerType = new ThreadSafeStore<Type, ReflectionObject>(InitializeReflectionObject);
private static ReflectionObject InitializeReflectionObject(Type t)
{
IList<Type> genericArguments = t.GetGenericArguments();
Type keyType = genericArguments[0];
Type valueType = genericArguments[1];
return ReflectionObject.Create(t, t.GetConstructor(new[] { keyType, valueType }), KeyName, ValueName);
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
ReflectionObject reflectionObject = ReflectionObjectPerType.Get(value.GetType());
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(KeyName) : KeyName);
serializer.Serialize(writer, reflectionObject.GetValue(value, KeyName), reflectionObject.GetType(KeyName));
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(ValueName) : ValueName);
serializer.Serialize(writer, reflectionObject.GetValue(value, ValueName), reflectionObject.GetType(ValueName));
writer.WriteEndObject();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to KeyValuePair.");
}
return null;
}
object? key = null;
object? value = null;
reader.ReadAndAssert();
Type t = ReflectionUtils.IsNullableType(objectType)
? Nullable.GetUnderlyingType(objectType)
: objectType;
ReflectionObject reflectionObject = ReflectionObjectPerType.Get(t);
JsonContract keyContract = serializer.ContractResolver.ResolveContract(reflectionObject.GetType(KeyName));
JsonContract valueContract = serializer.ContractResolver.ResolveContract(reflectionObject.GetType(ValueName));
while (reader.TokenType == JsonToken.PropertyName)
{
string propertyName = reader.Value!.ToString();
if (string.Equals(propertyName, KeyName, StringComparison.OrdinalIgnoreCase))
{
reader.ReadForTypeAndAssert(keyContract, false);
key = serializer.Deserialize(reader, keyContract.UnderlyingType);
}
else if (string.Equals(propertyName, ValueName, StringComparison.OrdinalIgnoreCase))
{
reader.ReadForTypeAndAssert(valueContract, false);
value = serializer.Deserialize(reader, valueContract.UnderlyingType);
}
else
{
reader.Skip();
}
reader.ReadAndAssert();
}
return reflectionObject.Creator!(key, value);
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (t.IsValueType() && t.IsGenericType())
{
return (t.GetGenericTypeDefinition() == typeof(KeyValuePair<,>));
}
return false;
}
}
}

View File

@ -0,0 +1,235 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Text.RegularExpressions;
using Newtonsoft.Json.Bson;
using System.Globalization;
using System.Runtime.CompilerServices;
using Newtonsoft.Json.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="Regex"/> to and from JSON and BSON.
/// </summary>
public class RegexConverter : JsonConverter
{
private const string PatternName = "Pattern";
private const string OptionsName = "Options";
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
Regex regex = (Regex)value;
#pragma warning disable 618
if (writer is BsonWriter bsonWriter)
{
WriteBson(bsonWriter, regex);
}
#pragma warning restore 618
else
{
WriteJson(writer, regex, serializer);
}
}
private bool HasFlag(RegexOptions options, RegexOptions flag)
{
return ((options & flag) == flag);
}
#pragma warning disable 618
private void WriteBson(BsonWriter writer, Regex regex)
{
// Regular expression - The first cstring is the regex pattern, the second
// is the regex options string. Options are identified by characters, which
// must be stored in alphabetical order. Valid options are 'i' for case
// insensitive matching, 'm' for multiline matching, 'x' for verbose mode,
// 'l' to make \w, \W, etc. locale dependent, 's' for dotall mode
// ('.' matches everything), and 'u' to make \w, \W, etc. match unicode.
string? options = null;
if (HasFlag(regex.Options, RegexOptions.IgnoreCase))
{
options += "i";
}
if (HasFlag(regex.Options, RegexOptions.Multiline))
{
options += "m";
}
if (HasFlag(regex.Options, RegexOptions.Singleline))
{
options += "s";
}
options += "u";
if (HasFlag(regex.Options, RegexOptions.ExplicitCapture))
{
options += "x";
}
writer.WriteRegex(regex.ToString(), options);
}
#pragma warning restore 618
private void WriteJson(JsonWriter writer, Regex regex, JsonSerializer serializer)
{
DefaultContractResolver? resolver = serializer.ContractResolver as DefaultContractResolver;
writer.WriteStartObject();
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(PatternName) : PatternName);
writer.WriteValue(regex.ToString());
writer.WritePropertyName((resolver != null) ? resolver.GetResolvedPropertyName(OptionsName) : OptionsName);
serializer.Serialize(writer, regex.Options);
writer.WriteEndObject();
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
switch (reader.TokenType)
{
case JsonToken.StartObject:
return ReadRegexObject(reader, serializer);
case JsonToken.String:
return ReadRegexString(reader);
case JsonToken.Null:
return null;
}
throw JsonSerializationException.Create(reader, "Unexpected token when reading Regex.");
}
private object ReadRegexString(JsonReader reader)
{
string regexText = (string)reader.Value!;
if (regexText.Length > 0 && regexText[0] == '/')
{
int patternOptionDelimiterIndex = regexText.LastIndexOf('/');
if (patternOptionDelimiterIndex > 0)
{
string patternText = regexText.Substring(1, patternOptionDelimiterIndex - 1);
string optionsText = regexText.Substring(patternOptionDelimiterIndex + 1);
RegexOptions options = MiscellaneousUtils.GetRegexOptions(optionsText);
return new Regex(patternText, options);
}
}
throw JsonSerializationException.Create(reader, "Regex pattern must be enclosed by slashes.");
}
private Regex ReadRegexObject(JsonReader reader, JsonSerializer serializer)
{
string? pattern = null;
RegexOptions? options = null;
while (reader.Read())
{
switch (reader.TokenType)
{
case JsonToken.PropertyName:
string propertyName = reader.Value!.ToString();
if (!reader.Read())
{
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
}
if (string.Equals(propertyName, PatternName, StringComparison.OrdinalIgnoreCase))
{
pattern = (string?)reader.Value;
}
else if (string.Equals(propertyName, OptionsName, StringComparison.OrdinalIgnoreCase))
{
options = serializer.Deserialize<RegexOptions>(reader);
}
else
{
reader.Skip();
}
break;
case JsonToken.Comment:
break;
case JsonToken.EndObject:
if (pattern == null)
{
throw JsonSerializationException.Create(reader, "Error deserializing Regex. No pattern found.");
}
return new Regex(pattern, options ?? RegexOptions.None);
}
}
throw JsonSerializationException.Create(reader, "Unexpected end when reading Regex.");
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return objectType.Name == nameof(Regex) && IsRegex(objectType);
}
[MethodImpl(MethodImplOptions.NoInlining)]
private bool IsRegex(Type objectType)
{
return (objectType == typeof(Regex));
}
}
}

View File

@ -0,0 +1,276 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using Newtonsoft.Json.Utilities;
using Newtonsoft.Json.Serialization;
#if !HAVE_LINQ
using Newtonsoft.Json.Utilities.LinqBridge;
#else
using System.Linq;
#endif
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts an <see cref="Enum"/> to and from its name string value.
/// </summary>
public class StringEnumConverter : JsonConverter
{
/// <summary>
/// Gets or sets a value indicating whether the written enum text should be camel case.
/// The default value is <c>false</c>.
/// </summary>
/// <value><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</value>
[Obsolete("StringEnumConverter.CamelCaseText is obsolete. Set StringEnumConverter.NamingStrategy with CamelCaseNamingStrategy instead.")]
public bool CamelCaseText
{
get => NamingStrategy is CamelCaseNamingStrategy ? true : false;
set
{
if (value)
{
if (NamingStrategy is CamelCaseNamingStrategy)
{
return;
}
NamingStrategy = new CamelCaseNamingStrategy();
}
else
{
if (!(NamingStrategy is CamelCaseNamingStrategy))
{
return;
}
NamingStrategy = null;
}
}
}
/// <summary>
/// Gets or sets the naming strategy used to resolve how enum text is written.
/// </summary>
/// <value>The naming strategy used to resolve how enum text is written.</value>
public NamingStrategy? NamingStrategy { get; set; }
/// <summary>
/// Gets or sets a value indicating whether integer values are allowed when serializing and deserializing.
/// The default value is <c>true</c>.
/// </summary>
/// <value><c>true</c> if integers are allowed when serializing and deserializing; otherwise, <c>false</c>.</value>
public bool AllowIntegerValues { get; set; } = true;
/// <summary>
/// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
/// </summary>
public StringEnumConverter()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
/// </summary>
/// <param name="camelCaseText"><c>true</c> if the written enum text will be camel case; otherwise, <c>false</c>.</param>
[Obsolete("StringEnumConverter(bool) is obsolete. Create a converter with StringEnumConverter(NamingStrategy, bool) instead.")]
public StringEnumConverter(bool camelCaseText)
{
if (camelCaseText)
{
NamingStrategy = new CamelCaseNamingStrategy();
}
}
/// <summary>
/// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
/// </summary>
/// <param name="namingStrategy">The naming strategy used to resolve how enum text is written.</param>
/// <param name="allowIntegerValues"><c>true</c> if integers are allowed when serializing and deserializing; otherwise, <c>false</c>.</param>
public StringEnumConverter(NamingStrategy namingStrategy, bool allowIntegerValues = true)
{
NamingStrategy = namingStrategy;
AllowIntegerValues = allowIntegerValues;
}
/// <summary>
/// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
/// </summary>
/// <param name="namingStrategyType">The <see cref="System.Type"/> of the <see cref="Newtonsoft.Json.Serialization.NamingStrategy"/> used to write enum text.</param>
public StringEnumConverter(Type namingStrategyType)
{
ValidationUtils.ArgumentNotNull(namingStrategyType, nameof(namingStrategyType));
NamingStrategy = JsonTypeReflector.CreateNamingStrategyInstance(namingStrategyType, null);
}
/// <summary>
/// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
/// </summary>
/// <param name="namingStrategyType">The <see cref="System.Type"/> of the <see cref="Newtonsoft.Json.Serialization.NamingStrategy"/> used to write enum text.</param>
/// <param name="namingStrategyParameters">
/// The parameter list to use when constructing the <see cref="Newtonsoft.Json.Serialization.NamingStrategy"/> described by <paramref name="namingStrategyType"/>.
/// If <c>null</c>, the default constructor is used.
/// When non-<c>null</c>, there must be a constructor defined in the <see cref="Newtonsoft.Json.Serialization.NamingStrategy"/> that exactly matches the number,
/// order, and type of these parameters.
/// </param>
public StringEnumConverter(Type namingStrategyType, object[] namingStrategyParameters)
{
ValidationUtils.ArgumentNotNull(namingStrategyType, nameof(namingStrategyType));
NamingStrategy = JsonTypeReflector.CreateNamingStrategyInstance(namingStrategyType, namingStrategyParameters);
}
/// <summary>
/// Initializes a new instance of the <see cref="StringEnumConverter"/> class.
/// </summary>
/// <param name="namingStrategyType">The <see cref="System.Type"/> of the <see cref="Newtonsoft.Json.Serialization.NamingStrategy"/> used to write enum text.</param>
/// <param name="namingStrategyParameters">
/// The parameter list to use when constructing the <see cref="Newtonsoft.Json.Serialization.NamingStrategy"/> described by <paramref name="namingStrategyType"/>.
/// If <c>null</c>, the default constructor is used.
/// When non-<c>null</c>, there must be a constructor defined in the <see cref="Newtonsoft.Json.Serialization.NamingStrategy"/> that exactly matches the number,
/// order, and type of these parameters.
/// </param>
/// <param name="allowIntegerValues"><c>true</c> if integers are allowed when serializing and deserializing; otherwise, <c>false</c>.</param>
public StringEnumConverter(Type namingStrategyType, object[] namingStrategyParameters, bool allowIntegerValues)
{
ValidationUtils.ArgumentNotNull(namingStrategyType, nameof(namingStrategyType));
NamingStrategy = JsonTypeReflector.CreateNamingStrategyInstance(namingStrategyType, namingStrategyParameters);
AllowIntegerValues = allowIntegerValues;
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
return;
}
Enum e = (Enum)value;
if (!EnumUtils.TryToString(e.GetType(), value, NamingStrategy, out string? enumName))
{
if (!AllowIntegerValues)
{
throw JsonSerializationException.Create(null, writer.ContainerPath, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, e.ToString("D")), null);
}
// enum value has no name so write number
writer.WriteValue(value);
}
else
{
writer.WriteValue(enumName);
}
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
if (!ReflectionUtils.IsNullableType(objectType))
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
return null;
}
bool isNullable = ReflectionUtils.IsNullableType(objectType);
Type t = isNullable ? Nullable.GetUnderlyingType(objectType) : objectType;
try
{
if (reader.TokenType == JsonToken.String)
{
string? enumText = reader.Value?.ToString();
if (StringUtils.IsNullOrEmpty(enumText) && isNullable)
{
return null;
}
return EnumUtils.ParseEnum(t, NamingStrategy, enumText!, !AllowIntegerValues);
}
if (reader.TokenType == JsonToken.Integer)
{
if (!AllowIntegerValues)
{
throw JsonSerializationException.Create(reader, "Integer value {0} is not allowed.".FormatWith(CultureInfo.InvariantCulture, reader.Value));
}
return ConvertUtils.ConvertOrCast(reader.Value, CultureInfo.InvariantCulture, t);
}
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error converting value {0} to type '{1}'.".FormatWith(CultureInfo.InvariantCulture, MiscellaneousUtils.ToString(reader.Value), objectType), ex);
}
// we don't actually expect to get here.
throw JsonSerializationException.Create(reader, "Unexpected token {0} when parsing enum.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
Type t = (ReflectionUtils.IsNullableType(objectType))
? Nullable.GetUnderlyingType(objectType)
: objectType;
return t.IsEnum();
}
}
}

View File

@ -0,0 +1,132 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="DateTime"/> to and from Unix epoch time
/// </summary>
public class UnixDateTimeConverter : DateTimeConverterBase
{
internal static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
long seconds;
if (value is DateTime dateTime)
{
seconds = (long)(dateTime.ToUniversalTime() - UnixEpoch).TotalSeconds;
}
#if HAVE_DATE_TIME_OFFSET
else if (value is DateTimeOffset dateTimeOffset)
{
seconds = (long)(dateTimeOffset.ToUniversalTime() - UnixEpoch).TotalSeconds;
}
#endif
else
{
throw new JsonSerializationException("Expected date object value.");
}
if (seconds < 0)
{
throw new JsonSerializationException("Cannot convert date value that is before Unix epoch of 00:00:00 UTC on 1 January 1970.");
}
writer.WriteValue(seconds);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
bool nullable = ReflectionUtils.IsNullable(objectType);
if (reader.TokenType == JsonToken.Null)
{
if (!nullable)
{
throw JsonSerializationException.Create(reader, "Cannot convert null value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
return null;
}
long seconds;
if (reader.TokenType == JsonToken.Integer)
{
seconds = (long)reader.Value!;
}
else if (reader.TokenType == JsonToken.String)
{
if (!long.TryParse((string)reader.Value!, out seconds))
{
throw JsonSerializationException.Create(reader, "Cannot convert invalid value to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token parsing date. Expected Integer or String, got {0}.".FormatWith(CultureInfo.InvariantCulture, reader.TokenType));
}
if (seconds >= 0)
{
DateTime d = UnixEpoch.AddSeconds(seconds);
#if HAVE_DATE_TIME_OFFSET
Type t = (nullable)
? Nullable.GetUnderlyingType(objectType)
: objectType;
if (t == typeof(DateTimeOffset))
{
return new DateTimeOffset(d, TimeSpan.Zero);
}
#endif
return d;
}
else
{
throw JsonSerializationException.Create(reader, "Cannot convert value that is before Unix epoch of 00:00:00 UTC on 1 January 1970 to {0}.".FormatWith(CultureInfo.InvariantCulture, objectType));
}
}
}
}

View File

@ -0,0 +1,106 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json.Converters
{
/// <summary>
/// Converts a <see cref="Version"/> to and from a string (e.g. <c>"1.2.3.4"</c>).
/// </summary>
public class VersionConverter : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (value == null)
{
writer.WriteNull();
}
else if (value is Version)
{
writer.WriteValue(value.ToString());
}
else
{
throw new JsonSerializationException("Expected Version object value");
}
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing property value of the JSON that is being converted.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
if (reader.TokenType == JsonToken.Null)
{
return null;
}
else
{
if (reader.TokenType == JsonToken.String)
{
try
{
Version v = new Version((string)reader.Value!);
return v;
}
catch (Exception ex)
{
throw JsonSerializationException.Create(reader, "Error parsing version string: {0}".FormatWith(CultureInfo.InvariantCulture, reader.Value), ex);
}
}
else
{
throw JsonSerializationException.Create(reader, "Unexpected token or value when parsing version. Token: {0}, Value: {1}".FormatWith(CultureInfo.InvariantCulture, reader.TokenType, reader.Value));
}
}
}
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public override bool CanConvert(Type objectType)
{
return objectType == typeof(Version);
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,43 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies how dates are formatted when writing JSON text.
/// </summary>
public enum DateFormatHandling
{
/// <summary>
/// Dates are written in the ISO 8601 format, e.g. <c>"2012-03-21T05:40Z"</c>.
/// </summary>
IsoDateFormat,
/// <summary>
/// Dates are written in the Microsoft JSON format, e.g. <c>"\/Date(1198908717056)\/"</c>.
/// </summary>
MicrosoftDateFormat
}
}

View File

@ -0,0 +1,49 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies how date formatted strings, e.g. <c>"\/Date(1198908717056)\/"</c> and <c>"2012-03-21T05:40Z"</c>, are parsed when reading JSON text.
/// </summary>
public enum DateParseHandling
{
/// <summary>
/// Date formatted strings are not parsed to a date type and are read as strings.
/// </summary>
None = 0,
/// <summary>
/// Date formatted strings, e.g. <c>"\/Date(1198908717056)\/"</c> and <c>"2012-03-21T05:40Z"</c>, are parsed to <see cref="System.DateTime"/>.
/// </summary>
DateTime = 1,
#if HAVE_DATE_TIME_OFFSET
/// <summary>
/// Date formatted strings, e.g. <c>"\/Date(1198908717056)\/"</c> and <c>"2012-03-21T05:40Z"</c>, are parsed to <see cref="System.DateTimeOffset"/>.
/// </summary>
DateTimeOffset = 2
#endif
}
}

View File

@ -0,0 +1,56 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies how to treat the time value when converting between string and <see cref="DateTime"/>.
/// </summary>
public enum DateTimeZoneHandling
{
/// <summary>
/// Treat as local time. If the <see cref="DateTime"/> object represents a Coordinated Universal Time (UTC), it is converted to the local time.
/// </summary>
Local = 0,
/// <summary>
/// Treat as a UTC. If the <see cref="DateTime"/> object represents a local time, it is converted to a UTC.
/// </summary>
Utc = 1,
/// <summary>
/// Treat as a local time if a <see cref="DateTime"/> is being converted to a string.
/// If a string is being converted to <see cref="DateTime"/>, convert to a local time if a time zone is specified.
/// </summary>
Unspecified = 2,
/// <summary>
/// Time zone information should be preserved when converting.
/// </summary>
RoundtripKind = 3
}
}

View File

@ -0,0 +1,197 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// The default JSON name table implementation.
/// </summary>
public class DefaultJsonNameTable : JsonNameTable
{
// used to defeat hashtable DoS attack where someone passes in lots of strings that hash to the same hash code
private static readonly int HashCodeRandomizer;
private int _count;
private Entry[] _entries;
private int _mask = 31;
static DefaultJsonNameTable()
{
HashCodeRandomizer = Environment.TickCount;
}
/// <summary>
/// Initializes a new instance of the <see cref="DefaultJsonNameTable"/> class.
/// </summary>
public DefaultJsonNameTable()
{
_entries = new Entry[_mask + 1];
}
/// <summary>
/// Gets a string containing the same characters as the specified range of characters in the given array.
/// </summary>
/// <param name="key">The character array containing the name to find.</param>
/// <param name="start">The zero-based index into the array specifying the first character of the name.</param>
/// <param name="length">The number of characters in the name.</param>
/// <returns>A string containing the same characters as the specified range of characters in the given array.</returns>
public override string? Get(char[] key, int start, int length)
{
if (length == 0)
{
return string.Empty;
}
int hashCode = length + HashCodeRandomizer;
hashCode += (hashCode << 7) ^ key[start];
int end = start + length;
for (int i = start + 1; i < end; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
// make sure index is evaluated before accessing _entries, otherwise potential race condition causing IndexOutOfRangeException
var index = hashCode & _mask;
var entries = _entries;
for (Entry entry = entries[index]; entry != null; entry = entry.Next)
{
if (entry.HashCode == hashCode && TextEquals(entry.Value, key, start, length))
{
return entry.Value;
}
}
return null;
}
/// <summary>
/// Adds the specified string into name table.
/// </summary>
/// <param name="key">The string to add.</param>
/// <remarks>This method is not thread-safe.</remarks>
/// <returns>The resolved string.</returns>
public string Add(string key)
{
if (key == null)
{
throw new ArgumentNullException(nameof(key));
}
int length = key.Length;
if (length == 0)
{
return string.Empty;
}
int hashCode = length + HashCodeRandomizer;
for (int i = 0; i < key.Length; i++)
{
hashCode += (hashCode << 7) ^ key[i];
}
hashCode -= hashCode >> 17;
hashCode -= hashCode >> 11;
hashCode -= hashCode >> 5;
for (Entry entry = _entries[hashCode & _mask]; entry != null; entry = entry.Next)
{
if (entry.HashCode == hashCode && entry.Value.Equals(key, StringComparison.Ordinal))
{
return entry.Value;
}
}
return AddEntry(key, hashCode);
}
private string AddEntry(string str, int hashCode)
{
int index = hashCode & _mask;
Entry entry = new Entry(str, hashCode, _entries[index]);
_entries[index] = entry;
if (_count++ == _mask)
{
Grow();
}
return entry.Value;
}
private void Grow()
{
Entry[] entries = _entries;
int newMask = (_mask * 2) + 1;
Entry[] newEntries = new Entry[newMask + 1];
for (int i = 0; i < entries.Length; i++)
{
Entry next;
for (Entry entry = entries[i]; entry != null; entry = next)
{
int index = entry.HashCode & newMask;
next = entry.Next;
entry.Next = newEntries[index];
newEntries[index] = entry;
}
}
_entries = newEntries;
_mask = newMask;
}
private static bool TextEquals(string str1, char[] str2, int str2Start, int str2Length)
{
if (str1.Length != str2Length)
{
return false;
}
for (int i = 0; i < str1.Length; i++)
{
if (str1[i] != str2[str2Start + i])
{
return false;
}
}
return true;
}
private class Entry
{
internal readonly string Value;
internal readonly int HashCode;
internal Entry Next;
internal Entry(string value, int hashCode, Entry next)
{
Value = value;
HashCode = hashCode;
Next = next;
}
}
}
}

View File

@ -0,0 +1,67 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.ComponentModel;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies default value handling options for the <see cref="JsonSerializer"/>.
/// </summary>
/// <example>
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ReducingSerializedJsonSizeDefaultValueHandlingObject" title="DefaultValueHandling Class" />
/// <code lang="cs" source="..\Src\Newtonsoft.Json.Tests\Documentation\SerializationTests.cs" region="ReducingSerializedJsonSizeDefaultValueHandlingExample" title="DefaultValueHandling Ignore Example" />
/// </example>
[Flags]
public enum DefaultValueHandling
{
/// <summary>
/// Include members where the member value is the same as the member's default value when serializing objects.
/// Included members are written to JSON. Has no effect when deserializing.
/// </summary>
Include = 0,
/// <summary>
/// Ignore members where the member value is the same as the member's default value when serializing objects
/// so that it is not written to JSON.
/// This option will ignore all default values (e.g. <c>null</c> for objects and nullable types; <c>0</c> for integers,
/// decimals and floating point numbers; and <c>false</c> for booleans). The default value ignored can be changed by
/// placing the <see cref="DefaultValueAttribute"/> on the property.
/// </summary>
Ignore = 1,
/// <summary>
/// Members with a default value but no JSON will be set to their default value when deserializing.
/// </summary>
Populate = 2,
/// <summary>
/// Ignore members where the member value is the same as the member's default value when serializing objects
/// and set members to their default value when deserializing.
/// </summary>
IgnoreAndPopulate = Ignore | Populate
}
}

Binary file not shown.

View File

@ -0,0 +1,52 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies float format handling options when writing special floating point numbers, e.g. <see cref="Double.NaN"/>,
/// <see cref="Double.PositiveInfinity"/> and <see cref="Double.NegativeInfinity"/> with <see cref="JsonWriter"/>.
/// </summary>
public enum FloatFormatHandling
{
/// <summary>
/// Write special floating point values as strings in JSON, e.g. <c>"NaN"</c>, <c>"Infinity"</c>, <c>"-Infinity"</c>.
/// </summary>
String = 0,
/// <summary>
/// Write special floating point values as symbols in JSON, e.g. <c>NaN</c>, <c>Infinity</c>, <c>-Infinity</c>.
/// Note that this will produce non-valid JSON.
/// </summary>
Symbol = 1,
/// <summary>
/// Write special floating point values as the property's default value in JSON, e.g. 0.0 for a <see cref="Double"/> property, <c>null</c> for a <see cref="Nullable{T}"/> of <see cref="Double"/> property.
/// </summary>
DefaultValue = 2
}
}

View File

@ -0,0 +1,43 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies how floating point numbers, e.g. 1.0 and 9.9, are parsed when reading JSON text.
/// </summary>
public enum FloatParseHandling
{
/// <summary>
/// Floating point numbers are parsed to <see cref="Double"/>.
/// </summary>
Double = 0,
/// <summary>
/// Floating point numbers are parsed to <see cref="Decimal"/>.
/// </summary>
Decimal = 1
}
}

View File

@ -0,0 +1,24 @@

#if HAVE_OBSOLETE_FORMATTER_ASSEMBLY_STYLE
namespace System.Runtime.Serialization.Formatters
{
/// <summary>
/// Indicates the method that will be used during deserialization for locating and loading assemblies.
/// </summary>
[Obsolete("FormatterAssemblyStyle is obsolete. Use TypeNameAssemblyFormatHandling instead.")]
public enum FormatterAssemblyStyle
{
/// <summary>
/// In simple mode, the assembly used during deserialization need not match exactly the assembly used during serialization. Specifically, the version numbers need not match as the <see cref="M:System.Reflection.Assembly.LoadWithPartialName(String)"/> method is used to load the assembly.
/// </summary>
Simple = 0,
/// <summary>
/// In full mode, the assembly used during deserialization must match exactly the assembly used during serialization. The <see cref="System.Reflection.Assembly.Load"/> is used to load the assembly.
/// </summary>
Full = 1
}
}
#endif

View File

@ -0,0 +1,43 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json
{
/// <summary>
/// Specifies formatting options for the <see cref="JsonTextWriter"/>.
/// </summary>
public enum Formatting
{
/// <summary>
/// No special formatting is applied. This is the default.
/// </summary>
None = 0,
/// <summary>
/// Causes child objects to be indented according to the <see cref="JsonTextWriter.Indentation"/> and <see cref="JsonTextWriter.IndentChar"/> settings.
/// </summary>
Indented = 1
}
}

View File

@ -0,0 +1,22 @@
namespace Newtonsoft.Json
{
/// <summary>
/// Provides an interface for using pooled arrays.
/// </summary>
/// <typeparam name="T">The array type content.</typeparam>
public interface IArrayPool<T>
{
/// <summary>
/// Rent an array from the pool. This array must be returned when it is no longer needed.
/// </summary>
/// <param name="minimumLength">The minimum required length of the array. The returned array may be longer.</param>
/// <returns>The rented array from the pool. This array must be returned when it is no longer needed.</returns>
T[] Rent(int minimumLength);
/// <summary>
/// Return an array to the pool.
/// </summary>
/// <param name="array">The array that is being returned.</param>
void Return(T[]? array);
}
}

View File

@ -0,0 +1,53 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
namespace Newtonsoft.Json
{
/// <summary>
/// Provides an interface to enable a class to return line and position information.
/// </summary>
public interface IJsonLineInfo
{
/// <summary>
/// Gets a value indicating whether the class can return line information.
/// </summary>
/// <returns>
/// <c>true</c> if <see cref="LineNumber"/> and <see cref="LinePosition"/> can be provided; otherwise, <c>false</c>.
/// </returns>
bool HasLineInfo();
/// <summary>
/// Gets the current line number.
/// </summary>
/// <value>The current line number or 0 if no line information is available (for example, when <see cref="HasLineInfo"/> returns <c>false</c>).</value>
int LineNumber { get; }
/// <summary>
/// Gets the current line position.
/// </summary>
/// <value>The current line position or 0 if no line information is available (for example, when <see cref="HasLineInfo"/> returns <c>false</c>).</value>
int LinePosition { get; }
}
}

View File

@ -0,0 +1,73 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> how to serialize the collection.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public sealed class JsonArrayAttribute : JsonContainerAttribute
{
private bool _allowNullItems;
/// <summary>
/// Gets or sets a value indicating whether null items are allowed in the collection.
/// </summary>
/// <value><c>true</c> if null items are allowed in the collection; otherwise, <c>false</c>.</value>
public bool AllowNullItems
{
get => _allowNullItems;
set => _allowNullItems = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayAttribute"/> class.
/// </summary>
public JsonArrayAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObjectAttribute"/> class with a flag indicating whether the array can contain null items.
/// </summary>
/// <param name="allowNullItems">A flag indicating whether the array can contain null items.</param>
public JsonArrayAttribute(bool allowNullItems)
{
_allowNullItems = allowNullItems;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonArrayAttribute"/> class with the specified container Id.
/// </summary>
/// <param name="id">The container Id.</param>
public JsonArrayAttribute(string id)
: base(id)
{
}
}
}

View File

@ -0,0 +1,37 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> to use the specified constructor when deserializing that object.
/// </summary>
[AttributeUsage(AttributeTargets.Constructor, AllowMultiple = false)]
public sealed class JsonConstructorAttribute : Attribute
{
}
}

View File

@ -0,0 +1,180 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> how to serialize the object.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public abstract class JsonContainerAttribute : Attribute
{
/// <summary>
/// Gets or sets the id.
/// </summary>
/// <value>The id.</value>
public string? Id { get; set; }
/// <summary>
/// Gets or sets the title.
/// </summary>
/// <value>The title.</value>
public string? Title { get; set; }
/// <summary>
/// Gets or sets the description.
/// </summary>
/// <value>The description.</value>
public string? Description { get; set; }
/// <summary>
/// Gets or sets the collection's items converter.
/// </summary>
/// <value>The collection's items converter.</value>
public Type? ItemConverterType { get; set; }
/// <summary>
/// The parameter list to use when constructing the <see cref="JsonConverter"/> described by <see cref="ItemConverterType"/>.
/// If <c>null</c>, the default constructor is used.
/// When non-<c>null</c>, there must be a constructor defined in the <see cref="JsonConverter"/> that exactly matches the number,
/// order, and type of these parameters.
/// </summary>
/// <example>
/// <code>
/// [JsonContainer(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[]? ItemConverterParameters { get; set; }
/// <summary>
/// Gets or sets the <see cref="Type"/> of the <see cref="NamingStrategy"/>.
/// </summary>
/// <value>The <see cref="Type"/> of the <see cref="NamingStrategy"/>.</value>
public Type? NamingStrategyType
{
get => _namingStrategyType;
set
{
_namingStrategyType = value;
NamingStrategyInstance = null;
}
}
/// <summary>
/// The parameter list to use when constructing the <see cref="NamingStrategy"/> described by <see cref="NamingStrategyType"/>.
/// If <c>null</c>, the default constructor is used.
/// When non-<c>null</c>, there must be a constructor defined in the <see cref="NamingStrategy"/> that exactly matches the number,
/// order, and type of these parameters.
/// </summary>
/// <example>
/// <code>
/// [JsonContainer(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[]? NamingStrategyParameters
{
get => _namingStrategyParameters;
set
{
_namingStrategyParameters = value;
NamingStrategyInstance = null;
}
}
internal NamingStrategy? NamingStrategyInstance { get; set; }
// yuck. can't set nullable properties on an attribute in C#
// have to use this approach to get an unset default state
internal bool? _isReference;
internal bool? _itemIsReference;
internal ReferenceLoopHandling? _itemReferenceLoopHandling;
internal TypeNameHandling? _itemTypeNameHandling;
private Type? _namingStrategyType;
private object[]? _namingStrategyParameters;
/// <summary>
/// Gets or sets a value that indicates whether to preserve object references.
/// </summary>
/// <value>
/// <c>true</c> to keep object reference; otherwise, <c>false</c>. The default is <c>false</c>.
/// </value>
public bool IsReference
{
get => _isReference ?? default;
set => _isReference = value;
}
/// <summary>
/// Gets or sets a value that indicates whether to preserve collection's items references.
/// </summary>
/// <value>
/// <c>true</c> to keep collection's items object references; otherwise, <c>false</c>. The default is <c>false</c>.
/// </value>
public bool ItemIsReference
{
get => _itemIsReference ?? default;
set => _itemIsReference = value;
}
/// <summary>
/// Gets or sets the reference loop handling used when serializing the collection's items.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling ItemReferenceLoopHandling
{
get => _itemReferenceLoopHandling ?? default;
set => _itemReferenceLoopHandling = value;
}
/// <summary>
/// Gets or sets the type name handling used when serializing the collection's items.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling ItemTypeNameHandling
{
get => _itemTypeNameHandling ?? default;
set => _itemTypeNameHandling = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonContainerAttribute"/> class.
/// </summary>
protected JsonContainerAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonContainerAttribute"/> class with the specified container Id.
/// </summary>
/// <param name="id">The container Id.</param>
protected JsonContainerAttribute(string id)
{
Id = id;
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,149 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Utilities;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Diagnostics.CodeAnalysis;
namespace Newtonsoft.Json
{
/// <summary>
/// Converts an object to and from JSON.
/// </summary>
public abstract class JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public abstract void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer);
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public abstract object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer);
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public abstract bool CanConvert(Type objectType);
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can read JSON.
/// </summary>
/// <value><c>true</c> if this <see cref="JsonConverter"/> can read JSON; otherwise, <c>false</c>.</value>
public virtual bool CanRead => true;
/// <summary>
/// Gets a value indicating whether this <see cref="JsonConverter"/> can write JSON.
/// </summary>
/// <value><c>true</c> if this <see cref="JsonConverter"/> can write JSON; otherwise, <c>false</c>.</value>
public virtual bool CanWrite => true;
}
/// <summary>
/// Converts an object to and from JSON.
/// </summary>
/// <typeparam name="T">The object type to convert.</typeparam>
public abstract class JsonConverter<T> : JsonConverter
{
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public sealed override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer)
{
if (!(value != null ? value is T : ReflectionUtils.IsNullable(typeof(T))))
{
throw new JsonSerializationException("Converter cannot write specified value to JSON. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
}
WriteJson(writer, (T?)value, serializer);
}
/// <summary>
/// Writes the JSON representation of the object.
/// </summary>
/// <param name="writer">The <see cref="JsonWriter"/> to write to.</param>
/// <param name="value">The value.</param>
/// <param name="serializer">The calling serializer.</param>
public abstract void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer);
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public sealed override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer)
{
bool existingIsNull = existingValue == null;
if (!(existingIsNull || existingValue is T))
{
throw new JsonSerializationException("Converter cannot read JSON with the specified existing value. {0} is required.".FormatWith(CultureInfo.InvariantCulture, typeof(T)));
}
return ReadJson(reader, objectType, existingIsNull ? default : (T?)existingValue, !existingIsNull, serializer);
}
/// <summary>
/// Reads the JSON representation of the object.
/// </summary>
/// <param name="reader">The <see cref="JsonReader"/> to read from.</param>
/// <param name="objectType">Type of the object.</param>
/// <param name="existingValue">The existing value of object being read. If there is no existing value then <c>null</c> will be used.</param>
/// <param name="hasExistingValue">The existing value has a value.</param>
/// <param name="serializer">The calling serializer.</param>
/// <returns>The object value.</returns>
public abstract T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer);
/// <summary>
/// Determines whether this instance can convert the specified object type.
/// </summary>
/// <param name="objectType">Type of the object.</param>
/// <returns>
/// <c>true</c> if this instance can convert the specified object type; otherwise, <c>false</c>.
/// </returns>
public sealed override bool CanConvert(Type objectType)
{
return typeof(T).IsAssignableFrom(objectType);
}
}
}

View File

@ -0,0 +1,77 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Utilities;
using System.Globalization;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> to use the specified <see cref="JsonConverter"/> when serializing the member or class.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class JsonConverterAttribute : Attribute
{
private readonly Type _converterType;
/// <summary>
/// Gets the <see cref="Type"/> of the <see cref="JsonConverter"/>.
/// </summary>
/// <value>The <see cref="Type"/> of the <see cref="JsonConverter"/>.</value>
public Type ConverterType => _converterType;
/// <summary>
/// The parameter list to use when constructing the <see cref="JsonConverter"/> described by <see cref="ConverterType"/>.
/// If <c>null</c>, the default constructor is used.
/// </summary>
public object[]? ConverterParameters { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonConverterAttribute"/> class.
/// </summary>
/// <param name="converterType">Type of the <see cref="JsonConverter"/>.</param>
public JsonConverterAttribute(Type converterType)
{
if (converterType == null)
{
throw new ArgumentNullException(nameof(converterType));
}
_converterType = converterType;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonConverterAttribute"/> class.
/// </summary>
/// <param name="converterType">Type of the <see cref="JsonConverter"/>.</param>
/// <param name="converterParameters">Parameter list to use when constructing the <see cref="JsonConverter"/>. Can be <c>null</c>.</param>
public JsonConverterAttribute(Type converterType, params object[] converterParameters)
: this(converterType)
{
ConverterParameters = converterParameters;
}
}
}

View File

@ -0,0 +1,39 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
using System.Collections.ObjectModel;
namespace Newtonsoft.Json
{
/// <summary>
/// Represents a collection of <see cref="JsonConverter"/>.
/// </summary>
public class JsonConverterCollection : Collection<JsonConverter>
{
}
}

View File

@ -0,0 +1,52 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> how to serialize the collection.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)]
public sealed class JsonDictionaryAttribute : JsonContainerAttribute
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonDictionaryAttribute"/> class.
/// </summary>
public JsonDictionaryAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonDictionaryAttribute"/> class with the specified container Id.
/// </summary>
/// <param name="id">The container Id.</param>
public JsonDictionaryAttribute(string id)
: base(id)
{
}
}
}

View File

@ -0,0 +1,92 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Runtime.Serialization;
using System.Text;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// The exception thrown when an error occurs during JSON serialization or deserialization.
/// </summary>
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
[Serializable]
#endif
public class JsonException : Exception
{
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class.
/// </summary>
public JsonException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public JsonException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonException(string message, Exception? innerException)
: base(message, innerException)
{
}
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="JsonException"/> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="ArgumentNullException">The <paramref name="info"/> parameter is <c>null</c>.</exception>
/// <exception cref="SerializationException">The class name is <c>null</c> or <see cref="Exception.HResult"/> is zero (0).</exception>
public JsonException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
internal static JsonException Create(IJsonLineInfo lineInfo, string path, string message)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
return new JsonException(message);
}
}
}

View File

@ -0,0 +1,37 @@
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> to deserialize properties with no matching class member into the specified collection
/// and write values during serialization.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public class JsonExtensionDataAttribute : Attribute
{
/// <summary>
/// Gets or sets a value that indicates whether to write extension data when serializing the object.
/// </summary>
/// <value>
/// <c>true</c> to write extension data when serializing the object; otherwise, <c>false</c>. The default is <c>true</c>.
/// </value>
public bool WriteData { get; set; }
/// <summary>
/// Gets or sets a value that indicates whether to read extension data when deserializing the object.
/// </summary>
/// <value>
/// <c>true</c> to read extension data when deserializing the object; otherwise, <c>false</c>. The default is <c>true</c>.
/// </value>
public bool ReadData { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonExtensionDataAttribute"/> class.
/// </summary>
public JsonExtensionDataAttribute()
{
WriteData = true;
ReadData = true;
}
}
}

View File

@ -0,0 +1,39 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> not to serialize the public field or public read/write property value.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class JsonIgnoreAttribute : Attribute
{
}
}

View File

@ -0,0 +1,17 @@
namespace Newtonsoft.Json
{
/// <summary>
/// Base class for a table of atomized string objects.
/// </summary>
public abstract class JsonNameTable
{
/// <summary>
/// Gets a string containing the same characters as the specified range of characters in the given array.
/// </summary>
/// <param name="key">The character array containing the name to find.</param>
/// <param name="start">The zero-based index into the array specifying the first character of the name.</param>
/// <param name="length">The number of characters in the name.</param>
/// <returns>A string containing the same characters as the specified range of characters in the given array.</returns>
public abstract string? Get(char[] key, int start, int length);
}
}

View File

@ -0,0 +1,111 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> how to serialize the object.
/// </summary>
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, AllowMultiple = false)]
public sealed class JsonObjectAttribute : JsonContainerAttribute
{
private MemberSerialization _memberSerialization = MemberSerialization.OptOut;
internal MissingMemberHandling? _missingMemberHandling;
// yuck. can't set nullable properties on an attribute in C#
// have to use this approach to get an unset default state
internal Required? _itemRequired;
internal NullValueHandling? _itemNullValueHandling;
/// <summary>
/// Gets or sets the member serialization.
/// </summary>
/// <value>The member serialization.</value>
public MemberSerialization MemberSerialization
{
get => _memberSerialization;
set => _memberSerialization = value;
}
/// <summary>
/// Gets or sets the missing member handling used when deserializing this object.
/// </summary>
/// <value>The missing member handling.</value>
public MissingMemberHandling MissingMemberHandling
{
get => _missingMemberHandling ?? default;
set => _missingMemberHandling = value;
}
/// <summary>
/// Gets or sets how the object's properties with null values are handled during serialization and deserialization.
/// </summary>
/// <value>How the object's properties with null values are handled during serialization and deserialization.</value>
public NullValueHandling ItemNullValueHandling
{
get => _itemNullValueHandling ?? default;
set => _itemNullValueHandling = value;
}
/// <summary>
/// Gets or sets a value that indicates whether the object's properties are required.
/// </summary>
/// <value>
/// A value indicating whether the object's properties are required.
/// </value>
public Required ItemRequired
{
get => _itemRequired ?? default;
set => _itemRequired = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObjectAttribute"/> class.
/// </summary>
public JsonObjectAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObjectAttribute"/> class with the specified member serialization.
/// </summary>
/// <param name="memberSerialization">The member serialization.</param>
public JsonObjectAttribute(MemberSerialization memberSerialization)
{
MemberSerialization = memberSerialization;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonObjectAttribute"/> class with the specified container Id.
/// </summary>
/// <param name="id">The container Id.</param>
public JsonObjectAttribute(string id)
: base(id)
{
}
}
}

View File

@ -0,0 +1,177 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
internal enum JsonContainerType
{
None = 0,
Object = 1,
Array = 2,
Constructor = 3
}
internal struct JsonPosition
{
private static readonly char[] SpecialCharacters = { '.', ' ', '\'', '/', '"', '[', ']', '(', ')', '\t', '\n', '\r', '\f', '\b', '\\', '\u0085', '\u2028', '\u2029' };
internal JsonContainerType Type;
internal int Position;
internal string? PropertyName;
internal bool HasIndex;
public JsonPosition(JsonContainerType type)
{
Type = type;
HasIndex = TypeHasIndex(type);
Position = -1;
PropertyName = null;
}
internal int CalculateLength()
{
switch (Type)
{
case JsonContainerType.Object:
return PropertyName!.Length + 5;
case JsonContainerType.Array:
case JsonContainerType.Constructor:
return MathUtils.IntLength((ulong)Position) + 2;
default:
throw new ArgumentOutOfRangeException(nameof(Type));
}
}
internal void WriteTo(StringBuilder sb, ref StringWriter? writer, ref char[]? buffer)
{
switch (Type)
{
case JsonContainerType.Object:
string propertyName = PropertyName!;
if (propertyName.IndexOfAny(SpecialCharacters) != -1)
{
sb.Append(@"['");
if (writer == null)
{
writer = new StringWriter(sb);
}
JavaScriptUtils.WriteEscapedJavaScriptString(writer, propertyName, '\'', false, JavaScriptUtils.SingleQuoteCharEscapeFlags, StringEscapeHandling.Default, null, ref buffer);
sb.Append(@"']");
}
else
{
if (sb.Length > 0)
{
sb.Append('.');
}
sb.Append(propertyName);
}
break;
case JsonContainerType.Array:
case JsonContainerType.Constructor:
sb.Append('[');
sb.Append(Position);
sb.Append(']');
break;
}
}
internal static bool TypeHasIndex(JsonContainerType type)
{
return (type == JsonContainerType.Array || type == JsonContainerType.Constructor);
}
internal static string BuildPath(List<JsonPosition> positions, JsonPosition? currentPosition)
{
int capacity = 0;
if (positions != null)
{
for (int i = 0; i < positions.Count; i++)
{
capacity += positions[i].CalculateLength();
}
}
if (currentPosition != null)
{
capacity += currentPosition.GetValueOrDefault().CalculateLength();
}
StringBuilder sb = new StringBuilder(capacity);
StringWriter? writer = null;
char[]? buffer = null;
if (positions != null)
{
foreach (JsonPosition state in positions)
{
state.WriteTo(sb, ref writer, ref buffer);
}
}
if (currentPosition != null)
{
currentPosition.GetValueOrDefault().WriteTo(sb, ref writer, ref buffer);
}
return sb.ToString();
}
internal static string FormatMessage(IJsonLineInfo? lineInfo, string path, string message)
{
// don't add a fullstop and space when message ends with a new line
if (!message.EndsWith(Environment.NewLine, StringComparison.Ordinal))
{
message = message.Trim();
if (!message.EndsWith('.'))
{
message += ".";
}
message += " ";
}
message += "Path '{0}'".FormatWith(CultureInfo.InvariantCulture, path);
if (lineInfo != null && lineInfo.HasLineInfo())
{
message += ", line {0}, position {1}".FormatWith(CultureInfo.InvariantCulture, lineInfo.LineNumber, lineInfo.LinePosition);
}
message += ".";
return message;
}
}
}

View File

@ -0,0 +1,223 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using Newtonsoft.Json.Serialization;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> to always serialize the member with the specified name.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Parameter, AllowMultiple = false)]
public sealed class JsonPropertyAttribute : Attribute
{
// yuck. can't set nullable properties on an attribute in C#
// have to use this approach to get an unset default state
internal NullValueHandling? _nullValueHandling;
internal DefaultValueHandling? _defaultValueHandling;
internal ReferenceLoopHandling? _referenceLoopHandling;
internal ObjectCreationHandling? _objectCreationHandling;
internal TypeNameHandling? _typeNameHandling;
internal bool? _isReference;
internal int? _order;
internal Required? _required;
internal bool? _itemIsReference;
internal ReferenceLoopHandling? _itemReferenceLoopHandling;
internal TypeNameHandling? _itemTypeNameHandling;
/// <summary>
/// Gets or sets the <see cref="JsonConverter"/> type used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items <see cref="JsonConverter"/> type.</value>
public Type? ItemConverterType { get; set; }
/// <summary>
/// The parameter list to use when constructing the <see cref="JsonConverter"/> described by <see cref="ItemConverterType"/>.
/// If <c>null</c>, the default constructor is used.
/// When non-<c>null</c>, there must be a constructor defined in the <see cref="JsonConverter"/> that exactly matches the number,
/// order, and type of these parameters.
/// </summary>
/// <example>
/// <code>
/// [JsonProperty(ItemConverterType = typeof(MyContainerConverter), ItemConverterParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[]? ItemConverterParameters { get; set; }
/// <summary>
/// Gets or sets the <see cref="Type"/> of the <see cref="NamingStrategy"/>.
/// </summary>
/// <value>The <see cref="Type"/> of the <see cref="NamingStrategy"/>.</value>
public Type? NamingStrategyType { get; set; }
/// <summary>
/// The parameter list to use when constructing the <see cref="NamingStrategy"/> described by <see cref="JsonPropertyAttribute.NamingStrategyType"/>.
/// If <c>null</c>, the default constructor is used.
/// When non-<c>null</c>, there must be a constructor defined in the <see cref="NamingStrategy"/> that exactly matches the number,
/// order, and type of these parameters.
/// </summary>
/// <example>
/// <code>
/// [JsonProperty(NamingStrategyType = typeof(MyNamingStrategy), NamingStrategyParameters = new object[] { 123, "Four" })]
/// </code>
/// </example>
public object[]? NamingStrategyParameters { get; set; }
/// <summary>
/// Gets or sets the null value handling used when serializing this property.
/// </summary>
/// <value>The null value handling.</value>
public NullValueHandling NullValueHandling
{
get => _nullValueHandling ?? default;
set => _nullValueHandling = value;
}
/// <summary>
/// Gets or sets the default value handling used when serializing this property.
/// </summary>
/// <value>The default value handling.</value>
public DefaultValueHandling DefaultValueHandling
{
get => _defaultValueHandling ?? default;
set => _defaultValueHandling = value;
}
/// <summary>
/// Gets or sets the reference loop handling used when serializing this property.
/// </summary>
/// <value>The reference loop handling.</value>
public ReferenceLoopHandling ReferenceLoopHandling
{
get => _referenceLoopHandling ?? default;
set => _referenceLoopHandling = value;
}
/// <summary>
/// Gets or sets the object creation handling used when deserializing this property.
/// </summary>
/// <value>The object creation handling.</value>
public ObjectCreationHandling ObjectCreationHandling
{
get => _objectCreationHandling ?? default;
set => _objectCreationHandling = value;
}
/// <summary>
/// Gets or sets the type name handling used when serializing this property.
/// </summary>
/// <value>The type name handling.</value>
public TypeNameHandling TypeNameHandling
{
get => _typeNameHandling ?? default;
set => _typeNameHandling = value;
}
/// <summary>
/// Gets or sets whether this property's value is serialized as a reference.
/// </summary>
/// <value>Whether this property's value is serialized as a reference.</value>
public bool IsReference
{
get => _isReference ?? default;
set => _isReference = value;
}
/// <summary>
/// Gets or sets the order of serialization of a member.
/// </summary>
/// <value>The numeric order of serialization.</value>
public int Order
{
get => _order ?? default;
set => _order = value;
}
/// <summary>
/// Gets or sets a value indicating whether this property is required.
/// </summary>
/// <value>
/// A value indicating whether this property is required.
/// </value>
public Required Required
{
get => _required ?? Required.Default;
set => _required = value;
}
/// <summary>
/// Gets or sets the name of the property.
/// </summary>
/// <value>The name of the property.</value>
public string? PropertyName { get; set; }
/// <summary>
/// Gets or sets the reference loop handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items reference loop handling.</value>
public ReferenceLoopHandling ItemReferenceLoopHandling
{
get => _itemReferenceLoopHandling ?? default;
set => _itemReferenceLoopHandling = value;
}
/// <summary>
/// Gets or sets the type name handling used when serializing the property's collection items.
/// </summary>
/// <value>The collection's items type name handling.</value>
public TypeNameHandling ItemTypeNameHandling
{
get => _itemTypeNameHandling ?? default;
set => _itemTypeNameHandling = value;
}
/// <summary>
/// Gets or sets whether this property's collection items are serialized as a reference.
/// </summary>
/// <value>Whether this property's collection items are serialized as a reference.</value>
public bool ItemIsReference
{
get => _itemIsReference ?? default;
set => _itemIsReference = value;
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonPropertyAttribute"/> class.
/// </summary>
public JsonPropertyAttribute()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonPropertyAttribute"/> class with the specified name.
/// </summary>
/// <param name="propertyName">Name of the property.</param>
public JsonPropertyAttribute(string propertyName)
{
PropertyName = propertyName;
}
}
}

View File

@ -0,0 +1,246 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
#if HAVE_ASYNC
using System;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
public abstract partial class JsonReader
{
/// <summary>
/// Asynchronously reads the next JSON token from the source.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns <c>true</c> if the next token was read successfully; <c>false</c> if there are no more tokens to read.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<bool> ReadAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<bool>() ?? Read().ToAsync();
}
/// <summary>
/// Asynchronously skips the children of the current token.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task"/> that represents the asynchronous operation.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public async Task SkipAsync(CancellationToken cancellationToken = default)
{
if (TokenType == JsonToken.PropertyName)
{
await ReadAsync(cancellationToken).ConfigureAwait(false);
}
if (JsonTokenUtils.IsStartToken(TokenType))
{
int depth = Depth;
while (await ReadAsync(cancellationToken).ConfigureAwait(false) && depth < Depth)
{
}
}
}
internal async Task ReaderReadAndAssertAsync(CancellationToken cancellationToken)
{
if (!await ReadAsync(cancellationToken).ConfigureAwait(false))
{
throw CreateUnexpectedEndException();
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="bool"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="bool"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<bool?> ReadAsBooleanAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<bool?>() ?? Task.FromResult(ReadAsBoolean());
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="byte"/>[].
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="byte"/>[]. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<byte[]?> ReadAsBytesAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<byte[]?>() ?? Task.FromResult(ReadAsBytes());
}
internal async Task<byte[]?> ReadArrayIntoByteArrayAsync(CancellationToken cancellationToken)
{
List<byte> buffer = new List<byte>();
while (true)
{
if (!await ReadAsync(cancellationToken).ConfigureAwait(false))
{
SetToken(JsonToken.None);
}
if (ReadArrayElementIntoByteArrayReportDone(buffer))
{
byte[] d = buffer.ToArray();
SetToken(JsonToken.Bytes, d, false);
return d;
}
}
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTime"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTime"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<DateTime?> ReadAsDateTimeAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<DateTime?>() ?? Task.FromResult(ReadAsDateTime());
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="DateTimeOffset"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<DateTimeOffset?> ReadAsDateTimeOffsetAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<DateTimeOffset?>() ?? Task.FromResult(ReadAsDateTimeOffset());
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="decimal"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="decimal"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<decimal?> ReadAsDecimalAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<decimal?>() ?? Task.FromResult(ReadAsDecimal());
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="double"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="double"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<double?> ReadAsDoubleAsync(CancellationToken cancellationToken = default)
{
return Task.FromResult(ReadAsDouble());
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="Nullable{T}"/> of <see cref="int"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="Nullable{T}"/> of <see cref="int"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<int?> ReadAsInt32Async(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<int?>() ?? Task.FromResult(ReadAsInt32());
}
/// <summary>
/// Asynchronously reads the next JSON token from the source as a <see cref="string"/>.
/// </summary>
/// <param name="cancellationToken">The token to monitor for cancellation requests. The default value is <see cref="CancellationToken.None"/>.</param>
/// <returns>A <see cref="Task{TResult}"/> that represents the asynchronous read. The <see cref="Task{TResult}.Result"/>
/// property returns the <see cref="string"/>. This result will be <c>null</c> at the end of an array.</returns>
/// <remarks>The default behaviour is to execute synchronously, returning an already-completed task. Derived
/// classes can override this behaviour for true asynchronicity.</remarks>
public virtual Task<string?> ReadAsStringAsync(CancellationToken cancellationToken = default)
{
return cancellationToken.CancelIfRequestedAsync<string?>() ?? Task.FromResult(ReadAsString());
}
internal async Task<bool> ReadAndMoveToContentAsync(CancellationToken cancellationToken)
{
return await ReadAsync(cancellationToken).ConfigureAwait(false) && await MoveToContentAsync(cancellationToken).ConfigureAwait(false);
}
internal Task<bool> MoveToContentAsync(CancellationToken cancellationToken)
{
switch (TokenType)
{
case JsonToken.None:
case JsonToken.Comment:
return MoveToContentFromNonContentAsync(cancellationToken);
default:
return AsyncUtils.True;
}
}
private async Task<bool> MoveToContentFromNonContentAsync(CancellationToken cancellationToken)
{
while (true)
{
if (!await ReadAsync(cancellationToken).ConfigureAwait(false))
{
return false;
}
switch (TokenType)
{
case JsonToken.None:
case JsonToken.Comment:
break;
default:
return true;
}
}
}
}
}
#endif

File diff suppressed because it is too large Load Diff

View File

@ -0,0 +1,148 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Globalization;
using System.Runtime.Serialization;
using Newtonsoft.Json.Utilities;
namespace Newtonsoft.Json
{
/// <summary>
/// The exception thrown when an error occurs while reading JSON text.
/// </summary>
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
[Serializable]
#endif
public class JsonReaderException : JsonException
{
/// <summary>
/// Gets the line number indicating where the error occurred.
/// </summary>
/// <value>The line number indicating where the error occurred.</value>
public int LineNumber { get; }
/// <summary>
/// Gets the line position indicating where the error occurred.
/// </summary>
/// <value>The line position indicating where the error occurred.</value>
public int LinePosition { get; }
/// <summary>
/// Gets the path to the JSON where the error occurred.
/// </summary>
/// <value>The path to the JSON where the error occurred.</value>
public string? Path { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonReaderException"/> class.
/// </summary>
public JsonReaderException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReaderException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public JsonReaderException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonReaderException"/> class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonReaderException(string message, Exception innerException)
: base(message, innerException)
{
}
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="JsonReaderException"/> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="ArgumentNullException">The <paramref name="info"/> parameter is <c>null</c>.</exception>
/// <exception cref="SerializationException">The class name is <c>null</c> or <see cref="Exception.HResult"/> is zero (0).</exception>
public JsonReaderException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="JsonReaderException"/> class
/// with a specified error message, JSON path, line number, line position, and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="path">The path to the JSON where the error occurred.</param>
/// <param name="lineNumber">The line number indicating where the error occurred.</param>
/// <param name="linePosition">The line position indicating where the error occurred.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonReaderException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
: base(message, innerException)
{
Path = path;
LineNumber = lineNumber;
LinePosition = linePosition;
}
internal static JsonReaderException Create(JsonReader reader, string message)
{
return Create(reader, message, null);
}
internal static JsonReaderException Create(JsonReader reader, string message, Exception? ex)
{
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static JsonReaderException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
int lineNumber;
int linePosition;
if (lineInfo != null && lineInfo.HasLineInfo())
{
lineNumber = lineInfo.LineNumber;
linePosition = lineInfo.LinePosition;
}
else
{
lineNumber = 0;
linePosition = 0;
}
return new JsonReaderException(message, path, lineNumber, linePosition, ex);
}
}
}

View File

@ -0,0 +1,39 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// Instructs the <see cref="JsonSerializer"/> to always serialize the member, and to require that the member has a value.
/// </summary>
[AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, AllowMultiple = false)]
public sealed class JsonRequiredAttribute : Attribute
{
}
}

View File

@ -0,0 +1,148 @@
#region License
// Copyright (c) 2007 James Newton-King
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Runtime.Serialization;
using System.Text;
namespace Newtonsoft.Json
{
/// <summary>
/// The exception thrown when an error occurs during JSON serialization or deserialization.
/// </summary>
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
[Serializable]
#endif
public class JsonSerializationException : JsonException
{
/// <summary>
/// Gets the line number indicating where the error occurred.
/// </summary>
/// <value>The line number indicating where the error occurred.</value>
public int LineNumber { get; }
/// <summary>
/// Gets the line position indicating where the error occurred.
/// </summary>
/// <value>The line position indicating where the error occurred.</value>
public int LinePosition { get; }
/// <summary>
/// Gets the path to the JSON where the error occurred.
/// </summary>
/// <value>The path to the JSON where the error occurred.</value>
public string? Path { get; }
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class.
/// </summary>
public JsonSerializationException()
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class
/// with a specified error message.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
public JsonSerializationException(string message)
: base(message)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class
/// with a specified error message and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonSerializationException(string message, Exception innerException)
: base(message, innerException)
{
}
#if HAVE_BINARY_EXCEPTION_SERIALIZATION
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class.
/// </summary>
/// <param name="info">The <see cref="SerializationInfo"/> that holds the serialized object data about the exception being thrown.</param>
/// <param name="context">The <see cref="StreamingContext"/> that contains contextual information about the source or destination.</param>
/// <exception cref="ArgumentNullException">The <paramref name="info"/> parameter is <c>null</c>.</exception>
/// <exception cref="SerializationException">The class name is <c>null</c> or <see cref="Exception.HResult"/> is zero (0).</exception>
public JsonSerializationException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endif
/// <summary>
/// Initializes a new instance of the <see cref="JsonSerializationException"/> class
/// with a specified error message, JSON path, line number, line position, and a reference to the inner exception that is the cause of this exception.
/// </summary>
/// <param name="message">The error message that explains the reason for the exception.</param>
/// <param name="path">The path to the JSON where the error occurred.</param>
/// <param name="lineNumber">The line number indicating where the error occurred.</param>
/// <param name="linePosition">The line position indicating where the error occurred.</param>
/// <param name="innerException">The exception that is the cause of the current exception, or <c>null</c> if no inner exception is specified.</param>
public JsonSerializationException(string message, string path, int lineNumber, int linePosition, Exception? innerException)
: base(message, innerException)
{
Path = path;
LineNumber = lineNumber;
LinePosition = linePosition;
}
internal static JsonSerializationException Create(JsonReader reader, string message)
{
return Create(reader, message, null);
}
internal static JsonSerializationException Create(JsonReader reader, string message, Exception? ex)
{
return Create(reader as IJsonLineInfo, reader.Path, message, ex);
}
internal static JsonSerializationException Create(IJsonLineInfo? lineInfo, string path, string message, Exception? ex)
{
message = JsonPosition.FormatMessage(lineInfo, path, message);
int lineNumber;
int linePosition;
if (lineInfo != null && lineInfo.HasLineInfo())
{
lineNumber = lineInfo.LineNumber;
linePosition = lineInfo.LinePosition;
}
else
{
lineNumber = 0;
linePosition = 0;
}
return new JsonSerializationException(message, path, lineNumber, linePosition, ex);
}
}
}

File diff suppressed because it is too large Load Diff

Some files were not shown because too many files have changed in this diff Show More