Remove BinaryFormatter snippets and articles (#33122)
This commit is contained in:
Родитель
083c589a17
Коммит
0f5ecf307f
|
@ -1685,6 +1685,10 @@
|
|||
"source_path_from_root": "/docs/framework/wcf/feature-details/context-exchange-correlation.md",
|
||||
"redirect_url": "/previous-versions/dotnet/netframework-4.0/ee358724(v=vs.100)"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/framework/wcf/feature-details/controlling-serialization-and-deserialization-with-serializationbinder.md",
|
||||
"redirect_url": "/dotnet/framework/wcf/feature-details/data-transfer-and-serialization"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/framework/wcf/feature-details/how-to-create-a-workflow-service-that-calls-another-workflow-service.md",
|
||||
"redirect_url": "/previous-versions/dotnet/netframework-4.0/ff729672(v=vs.100)"
|
||||
|
@ -1798,6 +1802,10 @@
|
|||
"source_path_from_root": "/docs/framework/wcf/samples/transacted-batching.md",
|
||||
"redirect_url": "/previous-versions/dotnet/netframework-4.0/aa395219(v%3dvs.100)"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/framework/wcf/samples/usage-of-serialization-binder.md",
|
||||
"redirect_url": "/dotnet/framework/wcf/samples/"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/framework/wcf/samples/web-extensibility.md",
|
||||
"redirect_url": "/previous-versions/dotnet/netframework-4.0/ee818234(v%3dvs.100)"
|
||||
|
|
|
@ -507,6 +507,10 @@
|
|||
"source_path_from_root": "/docs/standard/guidance-architecture.md",
|
||||
"redirect_url": "/dotnet/architecture/index"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/standard/serialization/how-to-determine-if-netstandard-object-is-serializable.md",
|
||||
"redirect_url": "/dotnet/standard/serialization/binaryformatter-security-guide"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/standard/index.yml",
|
||||
"redirect_url": "/dotnet/fundamentals/"
|
||||
|
|
|
@ -1259,6 +1259,10 @@
|
|||
"source_path_from_root": "/docs/visual-basic/programming-guide/concepts/threading/walkthrough-multithreading-with-the-backgroundworker-component.md",
|
||||
"redirect_url": "/dotnet/api/system.componentmodel.backgroundworker"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/visual-basic/programming-guide/concepts/serialization/walkthrough-persisting-an-object-in-visual-studio.md",
|
||||
"redirect_url": "/dotnet/visual-basic/programming-guide/concepts/serialization/"
|
||||
},
|
||||
{
|
||||
"source_path_from_root": "/docs/visual-basic/programming-guide/language-features/xml/how-to-enable-xml-intellisense.md",
|
||||
"redirect_url": "/previous-versions/visualstudio/visual-studio-2013/bb531402(v=vs.120)"
|
||||
|
|
|
@ -1,24 +0,0 @@
|
|||
---
|
||||
description: "Learn more about: Controlling Serialization and Deserialization with SerializationBinder"
|
||||
title: "Controlling Serialization and Deserialization with SerializationBinder"
|
||||
ms.date: "07/14/2020"
|
||||
ms.assetid: ba8dcecf-acc7-467c-939d-021bbac797d4
|
||||
---
|
||||
# Controlling Serialization and Deserialization with SerializationBinder
|
||||
|
||||
> [!WARNING]
|
||||
> <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter> is not secure and can ***not*** be made secure. For more information, see the [BinaryFormatter security guide](../../../standard/serialization/binaryformatter-security-guide.md).
|
||||
|
||||
During serialization, a formatter transmits the information required to create an instance of an object of the correct type and version. This information generally includes the full type name and assembly name of the object. By default, deserialization uses this information to create an instance of an identical object. Some users may need to control which class to serialize and deserialize, either because the original class may not exist on the machine performing deserialization, the original class has moved between assemblies, or a different version of the class is required on the server and client. For more information, see [Usage of Serialization Binder](../samples/usage-of-serialization-binder.md).
|
||||
|
||||
> [!WARNING]
|
||||
> This functionality is only available when using the <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter> or the <xref:System.Runtime.Serialization.NetDataContractSerializer>.
|
||||
|
||||
## Using SerializationBinder
|
||||
|
||||
<xref:System.Runtime.Serialization.SerializationBinder> is an abstract class used to control the actual types used during serialization and deserialization. To control the types used during serialization and deserialization, derive a class from <xref:System.Runtime.Serialization.SerializationBinder> and override the <xref:System.Runtime.Serialization.SerializationBinder.BindToName(System.Type,System.String@,System.String@)> and <xref:System.Runtime.Serialization.SerializationBinder.BindToType(System.String,System.String)> methods. The <xref:System.Runtime.Serialization.SerializationBinder.BindToName(System.Type,System.String@,System.String@)> method takes a <xref:System.Type> and returns an assembly and type name. The <xref:System.Runtime.Serialization.SerializationBinder.BindToType(System.String,System.String)> method takes an assembly and type name and returns a <xref:System.Type>.
|
||||
|
||||
## See also
|
||||
|
||||
- [Serialization and Deserialization](serialization-and-deserialization.md)
|
||||
- [Usage of Serialization Binder](../samples/usage-of-serialization-binder.md)
|
|
@ -75,7 +75,7 @@ To generate classes from schemas that are usable with Windows Communication Foun
|
|||
|
||||
This corresponds to the **/serializable** switch on the `Svcutil.exe` tool.
|
||||
|
||||
Sometimes it is important for the types generated from the schema to be usable with .NET Framework runtime serialization engines (for example, the <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=nameWithType> and the <xref:System.Runtime.Serialization.Formatters.Soap.SoapFormatter> classes). This is useful when using types for .NET Framework remoting. To enable this, you must apply the <xref:System.SerializableAttribute> attribute to the generated types in addition to the regular <xref:System.Runtime.Serialization.DataContractAttribute> attribute. The attribute is generated automatically if the `GenerateSerializable` import option is set to `true`.
|
||||
Sometimes it is important for the types generated from the schema to be usable with .NET Framework runtime serialization engines. This is useful when using types for .NET Framework remoting. To enable this, you must apply the <xref:System.SerializableAttribute> attribute to the generated types in addition to the regular <xref:System.Runtime.Serialization.DataContractAttribute> attribute. The attribute is generated automatically if the `GenerateSerializable` import option is set to `true`.
|
||||
|
||||
The following example shows the `Vehicle` class generated with the `GenerateSerializable` import option set to `true`.
|
||||
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
items:
|
||||
- name: WCF Feature Details
|
||||
href: index.md
|
||||
items:
|
||||
|
@ -159,8 +160,6 @@
|
|||
href: importing-schema-to-generate-classes.md
|
||||
- name: Exporting Schemas from Classes
|
||||
href: exporting-schemas-from-classes.md
|
||||
- name: Controlling Serialization and Deserialization with SerializationBinder
|
||||
href: controlling-serialization-and-deserialization-with-serializationbinder.md
|
||||
- name: Using a Data Contract Resolver
|
||||
href: using-a-data-contract-resolver.md
|
||||
- name: Using the XmlSerializer Class
|
||||
|
|
|
@ -21,12 +21,12 @@ The data contract programming model fully supports the version-tolerant serializ
|
|||
|
||||
There are four callback attributes. Each attribute can be applied to a method that the serialization/deserialization engine calls at various times. The table below explains when to use each attribute.
|
||||
|
||||
|Attribute|When the corresponding method is called|
|
||||
|---------------|---------------------------------------------|
|
||||
|<xref:System.Runtime.Serialization.OnSerializingAttribute>|Called before serializing the type.|
|
||||
|<xref:System.Runtime.Serialization.OnSerializedAttribute>|Called after serializing the type.|
|
||||
|<xref:System.Runtime.Serialization.OnDeserializingAttribute>|Called before deserializing the type.|
|
||||
|<xref:System.Runtime.Serialization.OnDeserializedAttribute>|Called after deserializing the type.|
|
||||
| Attribute | When the corresponding method is called |
|
||||
| ------------------------------------------------------------ | --------------------------------------- |
|
||||
| <xref:System.Runtime.Serialization.OnSerializingAttribute> | Called before serializing the type. |
|
||||
| <xref:System.Runtime.Serialization.OnSerializedAttribute> | Called after serializing the type. |
|
||||
| <xref:System.Runtime.Serialization.OnDeserializingAttribute> | Called before deserializing the type. |
|
||||
| <xref:System.Runtime.Serialization.OnDeserializedAttribute> | Called after deserializing the type. |
|
||||
|
||||
The methods must accept a <xref:System.Runtime.Serialization.StreamingContext> parameter.
|
||||
|
||||
|
|
|
@ -24,6 +24,3 @@ Demonstrates how to pass objects by references between server and client.
|
|||
|
||||
[POCO Support](poco-support.md)
|
||||
Demonstrates the serialization support for unmarked types; that is, types to which serialization attributes have not been applied, sometimes referred to as Plain Old CLR Object (POCO) types.
|
||||
|
||||
[Usage of Serialization Binder](usage-of-serialization-binder.md)
|
||||
This sample shows how to use the <xref:System.Runtime.Serialization.SerializationBinder> to change the version of a generic type when it is serialized.
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
items:
|
||||
- name: Windows Communication Foundation Samples
|
||||
href: index.md
|
||||
items:
|
||||
|
@ -175,8 +176,6 @@
|
|||
href: object-references.md
|
||||
- name: POCO Support
|
||||
href: poco-support.md
|
||||
- name: Usage of Serialization Binder
|
||||
href: usage-of-serialization-binder.md
|
||||
- name: Message Contracts
|
||||
href: message-contracts.md
|
||||
items:
|
||||
|
|
|
@ -1,31 +0,0 @@
|
|||
---
|
||||
description: "Learn more about: Usage of Serialization Binder"
|
||||
title: "Usage of Serialization Binder"
|
||||
ms.date: "03/30/2017"
|
||||
ms.assetid: ab46c087-200c-45bf-9c95-5a6cda6e8b98
|
||||
---
|
||||
# Usage of Serialization Binder
|
||||
|
||||
This sample shows how to use the <xref:System.Runtime.Serialization.SerializationBinder> to change the version of a generic type when it is serialized.
|
||||
|
||||
## Demonstrates
|
||||
|
||||
<xref:System.Runtime.Serialization.SerializationBinder>, <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter>
|
||||
|
||||
## Discussion
|
||||
|
||||
This sample shows how two entities that are targeting different versions of the .NET Framework can communicate using the binary formatter and the serialization binder.
|
||||
|
||||
This sample was developed using .NET Remoting. It consists of a server targeting .NET Framework 4, which implements a contract with generic types, and two different clients, one targeting .NET Framework 2.0 and another targeting .NET Framework 4.
|
||||
|
||||
The server attaches a <xref:System.Runtime.Serialization.SerializationBinder> to the binary formatter to be able to change the version of the types accordingly on serialization, so both clients can deserialize those types properly.
|
||||
|
||||
#### To set up, build and run the sample
|
||||
|
||||
1. To execute the client, right-click the solution, SBGenericsVTS (6 projects) and then select **Properties**.
|
||||
|
||||
2. In **Common Properties**, select **Startup Project**, then select **Multiple Startup Projects**.
|
||||
|
||||
3. Select **Server** first, then **Client20** and then **Client40**. Select the **Start** action to these three projects and leave the rest set to **None**.
|
||||
|
||||
4. Click **OK** and then press <kbd>F5</kbd> to run the sample.
|
|
@ -42,7 +42,7 @@ ms.assetid: 67d2b3e8-3777-49f8-9084-abbb33b5a766
|
|||
|
||||
### Control Flow
|
||||
|
||||
Just as in any programming language, WF provides support for control flows for workflow definitions by introducing a set of control flow activities for sequencing, looping, branching and other patterns. In WF3, when the same activity needs to be re-executed, a new <xref:System.Workflow.ComponentModel.ActivityExecutionContext> is created and the activity is cloned through a heavy-weight serialization and deserialization logic based on <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter>. Usually the performance for iterative control flows is much slower than executing a sequence of activities.
|
||||
Just as in any programming language, WF provides support for control flows for workflow definitions by introducing a set of control flow activities for sequencing, looping, branching, and other patterns. In WF3, when the same activity needs to be re-executed, a new <xref:System.Workflow.ComponentModel.ActivityExecutionContext> is created and the activity is cloned through a heavy-weight serialization and deserialization logic based on <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter>. Usually the performance for iterative control flows is much slower than executing a sequence of activities.
|
||||
|
||||
WF4 handles this quite differently. It takes the activity template, creates a new ActivityInstance object, and adds it to the scheduler queue. This whole process only involves explicit object creation and is very lightweight.
|
||||
|
||||
|
|
|
@ -34,7 +34,7 @@ This rule finds <xref:System.Web.UI.LosFormatter?displayProperty=nameWithType> d
|
|||
|
||||
## How to fix violations
|
||||
|
||||
- Use a secure serializer instead, and **don't allow an attacker to specify an arbitrary type to deserialize**. For more information see the [Preferred alternatives](../../../standard/serialization/binaryformatter-security-guide.md#preferred-alternatives).
|
||||
- Use a secure serializer instead, and **don't allow an attacker to specify an arbitrary type to deserialize**. For more information see [Preferred alternatives](../../../standard/serialization/binaryformatter-security-guide.md#preferred-alternatives).
|
||||
- Make the serialized data tamper-proof. After serialization, cryptographically sign the serialized data. Before deserialization, validate the cryptographic signature. Protect the cryptographic key from being disclosed and design for key rotations.
|
||||
|
||||
## When to suppress warnings
|
||||
|
|
|
@ -10,15 +10,14 @@ dev_langs:
|
|||
- VB
|
||||
f1_keywords:
|
||||
- "CA2321"
|
||||
- "DoNotCallBinaryFormatterDeserializeWithoutFirstSettingBinaryFormatterBinder"
|
||||
---
|
||||
# CA2321: Do not deserialize with JavaScriptSerializer using a SimpleTypeResolver
|
||||
|
||||
| | Value |
|
||||
|-|-|
|
||||
| **Rule ID** |CA2321|
|
||||
| **Category** |[Security](security-warnings.md)|
|
||||
| **Fix is breaking or non-breaking** |Non-breaking|
|
||||
| | Value |
|
||||
| ----------------------------------- | -------------------------------- |
|
||||
| **Rule ID** | CA2321 |
|
||||
| **Category** | [Security](security-warnings.md) |
|
||||
| **Fix is breaking or non-breaking** | Non-breaking |
|
||||
|
||||
## Cause
|
||||
|
||||
|
|
|
@ -282,8 +282,8 @@ The rules are:
|
|||
|
||||
Orleans supports transmission of arbitrary types at runtime and therefore the in-built code generator cannot determine the entire set of types that will be transmitted ahead of time. Additionally, certain types cannot have serializers generated for them because they are inaccessible (for example, `private`) or have inaccessible fields (for example, `readonly`). Therefore, there is a need for just-in-time serialization of types that were unexpected or could not have serializers generated ahead of time. The serializer responsible for these types is called the *fallback serializer*. Orleans ships with two fallback serializers:
|
||||
|
||||
* <xref:Orleans.Serialization.BinaryFormatterSerializer?displayProperty=fullName> which uses .NET's <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter>; and
|
||||
* <xref:Orleans.Serialization.ILBasedSerializer?displayProperty=fullName> which emits [CIL](../../../standard/glossary.md#il) instructions at runtime to create serializers that leverage Orleans' serialization framework to serialize each field. This means that if an inaccessible type `MyPrivateType` contains a field `MyType` which has a custom serializer, that custom serializer will be used to serialize it.
|
||||
* <xref:Orleans.Serialization.BinaryFormatterSerializer?displayProperty=fullName>, which uses .NET's <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter>; and
|
||||
* <xref:Orleans.Serialization.ILBasedSerializer?displayProperty=fullName>, which emits [CIL](../../../standard/glossary.md#il) instructions at runtime to create serializers that leverage Orleans' serialization framework to serialize each field. This means that if an inaccessible type `MyPrivateType` contains a field `MyType` which has a custom serializer, that custom serializer will be used to serialize it.
|
||||
|
||||
The fallback serializer can be configured using the <xref:Orleans.Configuration.SerializationProviderOptions.FallbackSerializationProvider> property on both <xref:Orleans.Runtime.Configuration.ClientConfiguration> on the client and <xref:Orleans.Runtime.Configuration.GlobalConfiguration> on the silos.
|
||||
|
||||
|
|
|
@ -1,6 +1,6 @@
|
|||
---
|
||||
description: "Learn more about: How to: Round-trip Date and Time Values"
|
||||
title: "How to: Round-trip Date and Time Values"
|
||||
description: "Learn how to round-trip date and time values"
|
||||
ms.date: 11/15/2022
|
||||
dev_langs:
|
||||
- "csharp"
|
||||
|
@ -12,7 +12,7 @@ helpviewer_keywords:
|
|||
- "formatting strings [.NET], round-trip values"
|
||||
ms.assetid: b609b277-edc6-4c74-b03e-ea73324ecbdb
|
||||
---
|
||||
# How to: Round-trip Date and Time Values
|
||||
# How to: Round-trip Date and time values
|
||||
|
||||
In many applications, a date and time value is intended to unambiguously identify a single point in time. This article shows how to save and restore a <xref:System.DateTime> value, a <xref:System.DateTimeOffset> value, and a date and time value with time zone information so that the restored value identifies the same time as the saved value.
|
||||
|
||||
|
|
|
@ -363,7 +363,7 @@ Constructors in CLS-compliant classes and structures must follow these rules:
|
|||
[!code-csharp[Conceptual.CLSCompliant#11](../../samples/snippets/csharp/VS_Snippets_CLR/conceptual.clscompliant/cs/ctor1.cs#11)]
|
||||
[!code-vb[Conceptual.CLSCompliant#11](../../samples/snippets/visualbasic/VS_Snippets_CLR/conceptual.clscompliant/vb/ctor1.vb#11)]
|
||||
|
||||
* An object constructor cannot be called except to create an object. In addition, an object cannot be initialized twice. For example, this means that <xref:System.Object.MemberwiseClone%2A?displayProperty=nameWithType> and deserialization methods such as <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter.Deserialize%2A?displayProperty=nameWithType> must not call constructors.
|
||||
* An object constructor cannot be called except to create an object. In addition, an object cannot be initialized twice. For example, this means that <xref:System.Object.MemberwiseClone%2A?displayProperty=nameWithType> and deserialization methods must not call constructors.
|
||||
|
||||
### Properties
|
||||
|
||||
|
|
|
@ -14,7 +14,7 @@ This functionality is not a substitute for a <xref:System.Runtime.Serialization.
|
|||
|
||||
## Description of events
|
||||
|
||||
The `BinaryFormatter` event source has the well-known name `System.Runtime.Serialization.Formatters.Binary.BinaryFormatterEventSource`. Listeners may subscribe to 6 events.
|
||||
The `BinaryFormatter` event source has the well-known name `System.Runtime.Serialization.Formatters.Binary.BinaryFormatterEventSource`. Listeners can subscribe to six events.
|
||||
|
||||
### SerializationStart event (id = `10`)
|
||||
|
||||
|
|
|
@ -1,32 +0,0 @@
|
|||
---
|
||||
title: "How to determine if a .NET Standard object is binary serializable"
|
||||
description: "Shows how to determine whether a .NET Standard type can be binary serialized at run time."
|
||||
ms.date: 11/15/2022
|
||||
dev_langs:
|
||||
- "csharp"
|
||||
- "vb"
|
||||
helpviewer_keywords:
|
||||
- "serializing objects"
|
||||
- "objects, serializing steps"
|
||||
---
|
||||
# How to determine if a .NET Standard object is binary serializable
|
||||
|
||||
.NET Standard is a specification that defines the types and members that must be present on specific .NET implementations that conform to that version of the standard. However, .NET Standard does not define whether a type is serializable. The types defined in the .NET Standard Library are not marked with the <xref:System.SerializableAttribute> attribute. Instead, specific .NET implementations, such as .NET Framework and .NET Core, are free to determine whether a particular type is binary serializable.
|
||||
|
||||
If you've developed a library that targets .NET Standard, your library can be consumed by any .NET implementation that supports .NET Standard. This means that you cannot know in advance whether a particular type is binary serializable; you can only determine that at run time.
|
||||
|
||||
You can determine whether an object is binary serializable at run time by retrieving the value of the <xref:System.Type.IsSerializable> property of a <xref:System.Type> object that represents that object's type. The following example provides one implementation. It defines an `IsSerializable(Object)` extension method that indicates whether any <xref:System.Object> instance can be binary serialized.
|
||||
|
||||
[!code-csharp[is-a-type-serializable](~/samples/snippets/standard/serialization/is-serializable/csharp/program.cs#2)]
|
||||
[!code-vb[is-a-type-serializable](~/samples/snippets/standard/serialization/is-serializable/vb/library.vb#2)]
|
||||
|
||||
You can then pass any object to the method to determine whether it can be binary serialized and deserialized on the current .NET implementation, as the following example shows:
|
||||
|
||||
[!code-csharp[test-is-a-type-serializable](~/samples/snippets/standard/serialization/is-serializable/csharp/program.cs#1)]
|
||||
[!code-vb[test-is-a-type-serializable](~/samples/snippets/standard/serialization/is-serializable/vb/program.vb#1)]
|
||||
|
||||
## See also
|
||||
|
||||
- [Binary serialization](binary-serialization.md)
|
||||
- <xref:System.SerializableAttribute?displayProperty=nameWithType>
|
||||
- <xref:System.Type.IsSerializable?displayProperty=nameWithType>
|
|
@ -11,7 +11,6 @@ helpviewer_keywords:
|
|||
- "serialization, version tolerant"
|
||||
- "serialization, controlling"
|
||||
- "versions and serialization"
|
||||
- "BinaryFormatter class, samples"
|
||||
- "serialization, attributes"
|
||||
ms.assetid: bea0ffe3-2708-4a16-ac7d-e586ed6b8e8d
|
||||
---
|
||||
|
@ -255,7 +254,7 @@ End Class
|
|||
|
||||
## SerializationBinder
|
||||
|
||||
Some users may need to control which class to serialize and deserialize because a different version of the class is required on the server and client. <xref:System.Runtime.Serialization.SerializationBinder> is an abstract class used to control the actual types used during serialization and deserialization. To use this class, derive a class from <xref:System.Runtime.Serialization.SerializationBinder> and override the <xref:System.Runtime.Serialization.SerializationBinder.BindToName%2A> and <xref:System.Runtime.Serialization.SerializationBinder.BindToType%2A> methods. For more information, see [Controlling Serialization and Deserialization with SerializationBinder](../../framework/wcf/feature-details/controlling-serialization-and-deserialization-with-serializationbinder.md).
|
||||
Some users may need to control which class to serialize and deserialize because a different version of the class is required on the server and client. <xref:System.Runtime.Serialization.SerializationBinder> is an abstract class used to control the actual types used during serialization and deserialization. To use this class, derive a class from <xref:System.Runtime.Serialization.SerializationBinder> and override the <xref:System.Runtime.Serialization.SerializationBinder.BindToName%2A> and <xref:System.Runtime.Serialization.SerializationBinder.BindToType%2A> methods.
|
||||
|
||||
## Best practices
|
||||
|
||||
|
|
|
@ -74,9 +74,6 @@ Binary and XML serialization can be performed in two ways, basic and custom. Bas
|
|||
Designer serialization is a special form of serialization that involves the kind of object persistence usually associated with development tools. Designer serialization is the process of converting an object graph into a source file that can later be used to recover the object graph. A source file can contain code, markup, or even SQL table information.
|
||||
|
||||
## <a name="BKMK_RelatedTopics"></a> Related articles
|
||||
|
||||
[Walkthrough: Persisting an Object in Visual Studio (Visual Basic)](walkthrough-persisting-an-object-in-visual-studio.md)
|
||||
Demonstrates how serialization can be used to persist an object's data between instances, allowing you to store values and retrieve them the next time the object is instantiated.
|
||||
|
||||
[How to: Read Object Data from an XML File (Visual Basic)](how-to-read-object-data-from-an-xml-file.md)
|
||||
Shows how to read object data that was previously written to an XML file using the <xref:System.Xml.Serialization.XmlSerializer> class.
|
||||
|
|
|
@ -1,3 +1,4 @@
|
|||
items:
|
||||
- name: Serialization
|
||||
href: index.md
|
||||
items:
|
||||
|
@ -5,5 +6,3 @@
|
|||
href: how-to-write-object-data-to-an-xml-file.md
|
||||
- name: "How to: Read Object Data from an XML File"
|
||||
href: how-to-read-object-data-from-an-xml-file.md
|
||||
- name: "Walkthrough: Persisting an Object"
|
||||
href: walkthrough-persisting-an-object-in-visual-studio.md
|
||||
|
|
|
@ -1,219 +0,0 @@
|
|||
---
|
||||
description: "Learn more about: Walkthrough: Persisting an Object in Visual Studio (Visual Basic)"
|
||||
title: "Persisting an Object in Visual Studio"
|
||||
ms.date: 07/20/2015
|
||||
ms.assetid: f1d0b562-e349-4dce-ab5f-c05108467030
|
||||
---
|
||||
# Walkthrough: Persisting an Object in Visual Studio (Visual Basic)
|
||||
|
||||
Although you can set an object's properties to default values at design time, any values entered at run time are lost when the object is destroyed. You can use serialization to persist an object's data between instances, which enables you to store values and retrieve them the next time that the object is instantiated.
|
||||
|
||||
> [!NOTE]
|
||||
> In Visual Basic, to store simple data, such as a name or number, you can use the `My.Settings` object. For more information, see [My.Settings Object](../../../language-reference/objects/my-settings-object.md).
|
||||
|
||||
In this walkthrough, you will create a simple `Loan` object and persist its data to a file. You will then retrieve the data from the file when you re-create the object.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> This example creates a new file, if the file does not already exist. If an application must create a file, that application must `Create` permission for the folder. Permissions are set by using access control lists. If the file already exists, the application needs only `Write` permission, a lesser permission. Where possible, it is more secure to create the file during deployment, and only grant `Read` permissions to a single file (instead of Create permissions for a folder). Also, it is more secure to write data to user folders than to the root folder or the Program Files folder.
|
||||
|
||||
> [!IMPORTANT]
|
||||
> This example stores data in a binary. These formats should not be used for sensitive data, such as passwords or credit-card information.
|
||||
|
||||
> [!NOTE]
|
||||
> The dialog boxes and menu commands you see might differ from those described in Help depending on your active settings or edition. To change your settings, click **Import and Export Settings** on the **Tools** menu. For more information, see [Personalize the Visual Studio IDE](/visualstudio/ide/personalizing-the-visual-studio-ide).
|
||||
|
||||
## Creating the Loan Object
|
||||
|
||||
The first step is to create a `Loan` class and a test application that uses the class.
|
||||
|
||||
### To create the Loan class
|
||||
|
||||
1. Create a new Class Library project and name it "LoanClass". For more information, see [Creating Solutions and Projects](/visualstudio/ide/creating-solutions-and-projects).
|
||||
|
||||
2. In **Solution Explorer**, open the shortcut menu for the Class1 file and choose **Rename**. Rename the file to `Loan` and press ENTER. Renaming the file will also rename the class to `Loan`.
|
||||
|
||||
3. Add the following public members to the class:
|
||||
|
||||
```vb
|
||||
Public Class Loan
|
||||
Implements System.ComponentModel.INotifyPropertyChanged
|
||||
|
||||
Public Property LoanAmount As Double
|
||||
Public Property InterestRate As Double
|
||||
Public Property Term As Integer
|
||||
|
||||
Private p_Customer As String
|
||||
Public Property Customer As String
|
||||
Get
|
||||
Return p_Customer
|
||||
End Get
|
||||
Set(ByVal value As String)
|
||||
p_Customer = value
|
||||
RaiseEvent PropertyChanged(Me,
|
||||
New System.ComponentModel.PropertyChangedEventArgs("Customer"))
|
||||
End Set
|
||||
End Property
|
||||
|
||||
Event PropertyChanged As System.ComponentModel.PropertyChangedEventHandler _
|
||||
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
|
||||
|
||||
Public Sub New(ByVal loanAmount As Double,
|
||||
ByVal interestRate As Double,
|
||||
ByVal term As Integer,
|
||||
ByVal customer As String)
|
||||
|
||||
Me.LoanAmount = loanAmount
|
||||
Me.InterestRate = interestRate
|
||||
Me.Term = term
|
||||
p_Customer = customer
|
||||
End Sub
|
||||
End Class
|
||||
```
|
||||
|
||||
You will also have to create a simple application that uses the `Loan` class.
|
||||
|
||||
### To create a test application
|
||||
|
||||
1. To add a Windows Forms Application project to your solution, on the **File** menu, choose **Add**,**New Project**.
|
||||
|
||||
2. In the **Add New Project** dialog box, choose **Windows Forms Application**, and enter `LoanApp` as the name of the project, and then click **OK** to close the dialog box.
|
||||
|
||||
3. In **Solution Explorer**, choose the LoanApp project.
|
||||
|
||||
4. On the **Project** menu, choose **Set as StartUp Project**.
|
||||
|
||||
5. On the **Project** menu, choose **Add Reference**.
|
||||
|
||||
6. In the **Add Reference** dialog box, choose the **Projects** tab and then choose the LoanClass project.
|
||||
|
||||
7. Click **OK** to close the dialog box.
|
||||
|
||||
8. In the designer, add four <xref:System.Windows.Forms.TextBox> controls to the form.
|
||||
|
||||
9. In the Code Editor, add the following code:
|
||||
|
||||
```vb
|
||||
Private WithEvents TestLoan As New LoanClass.Loan(10000.0, 0.075, 36, "Neil Black")
|
||||
|
||||
Private Sub Form1_Load() Handles MyBase.Load
|
||||
TextBox1.Text = TestLoan.LoanAmount.ToString
|
||||
TextBox2.Text = TestLoan.InterestRate.ToString
|
||||
TextBox3.Text = TestLoan.Term.ToString
|
||||
TextBox4.Text = TestLoan.Customer
|
||||
End Sub
|
||||
```
|
||||
|
||||
10. Add an event handler for the `PropertyChanged` event to the form by using the following code:
|
||||
|
||||
```vb
|
||||
Public Sub CustomerPropertyChanged(
|
||||
ByVal sender As Object,
|
||||
ByVal e As System.ComponentModel.PropertyChangedEventArgs
|
||||
) Handles TestLoan.PropertyChanged
|
||||
|
||||
MsgBox(e.PropertyName & " has been changed.")
|
||||
End Sub
|
||||
```
|
||||
|
||||
At this point, you can build and run the application. Note that the default values from the `Loan` class appear in the text boxes. Try to change the interest-rate value from 7.5 to 7.1, and then close the application and run it again—the value reverts to the default of 7.5.
|
||||
|
||||
In the real world, interest rates change periodically, but not necessarily every time that the application is run. Rather than making the user update the interest rate every time that the application runs, it is better to preserve the most recent interest rate between instances of the application. In the next step, you will do just that by adding serialization to the Loan class.
|
||||
|
||||
## Using Serialization to Persist the Object
|
||||
|
||||
In order to persist the values for the Loan class, you must first mark the class with the `Serializable` attribute.
|
||||
|
||||
### To mark a class as serializable
|
||||
|
||||
- Change the class declaration for the Loan class as follows:
|
||||
|
||||
```vb
|
||||
<Serializable()>
|
||||
Public Class Loan
|
||||
```
|
||||
|
||||
The `Serializable` attribute tells the compiler that everything in the class can be persisted to a file. Because the `PropertyChanged` event is handled by a Windows Form object, it cannot be serialized. The `NonSerialized` attribute can be used to mark class members that should not be persisted.
|
||||
|
||||
### To prevent a member from being serialized
|
||||
|
||||
- Change the declaration for the `PropertyChanged` event as follows:
|
||||
|
||||
```vb
|
||||
<NonSerialized()>
|
||||
Event PropertyChanged As System.ComponentModel.PropertyChangedEventHandler _
|
||||
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
|
||||
```
|
||||
|
||||
The next step is to add the serialization code to the LoanApp application. In order to serialize the class and write it to a file, you will use the <xref:System.IO> and <xref:System.Xml.Serialization> namespaces. To avoid typing the fully qualified names, you can add references to the necessary class libraries.
|
||||
|
||||
### To add references to namespaces
|
||||
|
||||
- Add the following statements to the top of the `Form1` class:
|
||||
|
||||
```vb
|
||||
Imports System.IO
|
||||
Imports System.Runtime.Serialization.Formatters.Binary
|
||||
```
|
||||
|
||||
In this case, you are using a binary formatter to save the object in a binary format.
|
||||
|
||||
The next step is to add code to deserialize the object from the file when the object is created.
|
||||
|
||||
### To deserialize an object
|
||||
|
||||
1. Add a constant to the class for the serialized data's file name.
|
||||
|
||||
```vb
|
||||
Const FileName As String = "..\..\SavedLoan.bin"
|
||||
```
|
||||
|
||||
2. Modify the code in the `Form1_Load` event procedure as follows:
|
||||
|
||||
```vb
|
||||
Private WithEvents TestLoan As New LoanClass.Loan(10000.0, 0.075, 36, "Neil Black")
|
||||
|
||||
Private Sub Form1_Load() Handles MyBase.Load
|
||||
If File.Exists(FileName) Then
|
||||
Dim TestFileStream As Stream = File.OpenRead(FileName)
|
||||
Dim deserializer As New BinaryFormatter
|
||||
TestLoan = CType(deserializer.Deserialize(TestFileStream), LoanClass.Loan)
|
||||
TestFileStream.Close()
|
||||
End If
|
||||
|
||||
AddHandler TestLoan.PropertyChanged, AddressOf Me.CustomerPropertyChanged
|
||||
|
||||
TextBox1.Text = TestLoan.LoanAmount.ToString
|
||||
TextBox2.Text = TestLoan.InterestRate.ToString
|
||||
TextBox3.Text = TestLoan.Term.ToString
|
||||
TextBox4.Text = TestLoan.Customer
|
||||
End Sub
|
||||
```
|
||||
|
||||
Note that you first must check that the file exists. If it exists, create a <xref:System.IO.Stream> class to read the binary file and a <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter> class to translate the file. You also need to convert from the stream type to the Loan object type.
|
||||
|
||||
Next you must add code to save the data entered in the text boxes to the `Loan` class, and then you must serialize the class to a file.
|
||||
|
||||
### To save the data and serialize the class
|
||||
|
||||
- Add the following code to the `Form1_FormClosing` event procedure:
|
||||
|
||||
```vb
|
||||
Private Sub Form1_FormClosing() Handles MyBase.FormClosing
|
||||
TestLoan.LoanAmount = CDbl(TextBox1.Text)
|
||||
TestLoan.InterestRate = CDbl(TextBox2.Text)
|
||||
TestLoan.Term = CInt(TextBox3.Text)
|
||||
TestLoan.Customer = TextBox4.Text
|
||||
|
||||
Dim TestFileStream As Stream = File.Create(FileName)
|
||||
Dim serializer As New BinaryFormatter
|
||||
serializer.Serialize(TestFileStream, TestLoan)
|
||||
TestFileStream.Close()
|
||||
End Sub
|
||||
```
|
||||
|
||||
At this point, you can again build and run the application. Initially, the default values appear in the text boxes. Try to change the values and enter a name in the fourth text box. Close the application and then run it again. Note that the new values now appear in the text boxes.
|
||||
|
||||
## See also
|
||||
|
||||
- [Serialization (Visual Basic)](index.md)
|
||||
- [Visual Basic Programming Guide](../../index.md)
|
|
@ -70,8 +70,5 @@ Walkthroughs give step-by-step instructions for common scenarios, which makes th
|
|||
- [Manipulating Files Using .NET Framework Methods](developing-apps/programming/drives-directories-files/walkthrough-manipulating-files-by-using-net-framework-methods.md)
|
||||
Demonstrates how to use .NET Framework methods to determine information about a file, search for a string in a file, and write to a file.
|
||||
|
||||
- [Persisting an Object in Visual Basic](programming-guide/concepts/serialization/walkthrough-persisting-an-object-in-visual-studio.md)
|
||||
Demonstrates how to create a simple object and persist its data to a file.
|
||||
|
||||
- [Walkthrough: Test-First Support with the Generate From Usage Feature](/visualstudio/ide/walkthrough-test-first-support-with-the-generate-from-usage-feature)
|
||||
Demonstrates how to do test-first development, in which you first write unit tests and then write the source code to make the tests succeed.
|
||||
|
|
|
@ -6,13 +6,13 @@ Due to internal changes to the type, <xref:System.Collections.Concurrent.Concurr
|
|||
|
||||
#### Suggestion
|
||||
|
||||
If it is necessary to serialize and deserialize a <xref:System.Collections.Concurrent.ConcurrentDictionary%602?displayProperty=fullName> between the .NET Framework 4.5 and .NET Framework 4.5.1/4.5.2, an alternate serializer like the <xref:System.Runtime.Serialization.DataContractSerializer?displayProperty=fullName> or <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=fullName> serializer should be used instead of the <xref:System.Runtime.Serialization.NetDataContractSerializer?displayProperty=fullName>.Alternatively, because this issue is addressed in the .NET Framework 4.6, it may be solved by upgrading to that version of the .NET Framework.
|
||||
If it is necessary to serialize and deserialize a <xref:System.Collections.Concurrent.ConcurrentDictionary%602?displayProperty=fullName> between the .NET Framework 4.5 and .NET Framework 4.5.1/4.5.2, a different serializer like the <xref:System.Runtime.Serialization.DataContractSerializer?displayProperty=fullName> should be used instead of the <xref:System.Runtime.Serialization.NetDataContractSerializer?displayProperty=fullName>. Alternatively, because this issue is addressed in the .NET Framework 4.6, it may be solved by upgrading to that version of the .NET Framework.
|
||||
|
||||
| Name | Value |
|
||||
|:--------|:------------|
|
||||
| Scope |Minor|
|
||||
|Version|4.5.1|
|
||||
|Type|Runtime|
|
||||
| Name | Value |
|
||||
| :------ | :------ |
|
||||
| Scope | Minor |
|
||||
| Version | 4.5.1 |
|
||||
| Type | Runtime |
|
||||
|
||||
#### Affected APIs
|
||||
|
||||
|
|
|
@ -4,15 +4,17 @@
|
|||
|
||||
As of .NET Framework 4.5, a number of <xref:System.Xml.Serialization.XmlSerializer?displayProperty=fullName> changes may cause differences in deserialization when using <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=fullName> to deserialize types that had been loaded in the LoadFrom context. These changes are due to the new ways <xref:System.Xml.Serialization.XmlSerializer?displayProperty=fullName> now loads a type which causes different behavior when a <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=fullName> attempts to deserialize to that type later on. The default serialization binder does not automatically search the LoadFrom context, although it may have worked in some circumstances based on the old behavior of XmlSerializer. Due to the changes, when a type is being loaded from an assembly loaded in a different context, a <xref:System.IO.FileNotFoundException?displayProperty=fullName> may be thrown.
|
||||
|
||||
[!INCLUDE [binary-serialization-warning](../../../binary-serialization-warning.md)]
|
||||
|
||||
#### Suggestion
|
||||
|
||||
If this exception is seen, the `Binder` property of the <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=fullName> can be set to a custom binder that will find the correct type.<pre><code class="lang-csharp">var formatter = new BinaryFormatter { Binder = new TypeFinderBinder() } </code></pre>And then the custom binder:<pre><code class="lang-csharp">public class TypeFinderBinder : SerializationBinder { private static readonly string s_assemblyName = Assembly.GetExecutingAssembly().FullName; public override Type BindToType(string assemblyName, string typeName) { return Type.GetType(String.Format(CultureInfo.InvariantCulture, "{0}, {1}", typeName, s_assemblyName)); } } </code></pre>
|
||||
|
||||
| Name | Value |
|
||||
|:--------|:------------|
|
||||
| Scope |Edge|
|
||||
|Version|4.5|
|
||||
|Type|Runtime|
|
||||
| Name | Value |
|
||||
| :------ | :------ |
|
||||
| Scope | Edge |
|
||||
| Version | 4.5 |
|
||||
| Type | Runtime |
|
||||
|
||||
#### Affected APIs
|
||||
|
||||
|
|
|
@ -8,11 +8,13 @@ The <xref:System.Runtime.Serialization.Formatters.Soap.SoapFormatter?displayProp
|
|||
|
||||
<xref:System.Runtime.Serialization.Formatters.Soap.SoapFormatter?displayProperty=fullName> serialization should be replaced with <xref:System.Runtime.Serialization.Formatters.Binary.BinaryFormatter?displayProperty=fullName> serialization or <xref:System.Runtime.Serialization.NetDataContractSerializer?displayProperty=fullName> to be resilient to .NET Framework changes.
|
||||
|
||||
| Name | Value |
|
||||
|:--------|:------------|
|
||||
| Scope |Minor|
|
||||
|Version|4.5|
|
||||
|Type|Runtime|
|
||||
[!INCLUDE [binary-serialization-warning](../../../binary-serialization-warning.md)]
|
||||
|
||||
| Name | Value |
|
||||
| :------ | :------ |
|
||||
| Scope | Minor |
|
||||
| Version | 4.5 |
|
||||
| Type | Runtime |
|
||||
|
||||
#### Affected APIs
|
||||
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net7.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -1,8 +1,6 @@
|
|||
using System;
|
||||
using System.Globalization;
|
||||
using System.IO;
|
||||
using System.Runtime.Serialization;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
|
||||
public class Class1
|
||||
{
|
||||
|
@ -12,7 +10,6 @@ public class Class1
|
|||
Console.WriteLine();
|
||||
RoundTripDateTimeOffset();
|
||||
Console.WriteLine();
|
||||
RoundTripTimeWithTimeZone();
|
||||
}
|
||||
|
||||
private static void RoundTripDateTime()
|
||||
|
@ -84,67 +81,6 @@ public class Class1
|
|||
// Read 6/12/2008 6:45:15 PM +07:00 from .\DateOff.txt.
|
||||
// </Snippet2>
|
||||
}
|
||||
|
||||
private static void RoundTripTimeWithTimeZone()
|
||||
{
|
||||
// <Snippet4>
|
||||
const string fileName = @".\DateWithTz.dat";
|
||||
|
||||
DateTime tempDate = new DateTime(2008, 9, 3, 19, 0, 0);
|
||||
TimeZoneInfo tempTz = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time");
|
||||
DateInTimeZone dateWithTz = new DateInTimeZone(new DateTimeOffset(tempDate,
|
||||
tempTz.GetUtcOffset(tempDate)),
|
||||
tempTz);
|
||||
|
||||
// Store DateInTimeZone value to a file
|
||||
FileStream outFile = new FileStream(fileName, FileMode.Create);
|
||||
try
|
||||
{
|
||||
BinaryFormatter formatter = new BinaryFormatter();
|
||||
formatter.Serialize(outFile, dateWithTz);
|
||||
Console.WriteLine("Saving {0} {1} to {2}", dateWithTz.DateAndTime,
|
||||
dateWithTz.TimeZone.IsDaylightSavingTime(dateWithTz.DateAndTime) ?
|
||||
dateWithTz.TimeZone.DaylightName : dateWithTz.TimeZone.DaylightName,
|
||||
fileName);
|
||||
}
|
||||
catch (SerializationException)
|
||||
{
|
||||
Console.WriteLine("Unable to serialize time data to {0}.", fileName);
|
||||
}
|
||||
finally
|
||||
{
|
||||
outFile.Close();
|
||||
}
|
||||
|
||||
// Retrieve DateInTimeZone value
|
||||
if (File.Exists(fileName))
|
||||
{
|
||||
FileStream inFile = new FileStream(fileName, FileMode.Open);
|
||||
DateInTimeZone dateWithTz2 = new DateInTimeZone();
|
||||
try
|
||||
{
|
||||
BinaryFormatter formatter = new BinaryFormatter();
|
||||
dateWithTz2 = formatter.Deserialize(inFile) as DateInTimeZone;
|
||||
Console.WriteLine("Restored {0} {1} from {2}", dateWithTz2.DateAndTime,
|
||||
dateWithTz2.TimeZone.IsDaylightSavingTime(dateWithTz2.DateAndTime) ?
|
||||
dateWithTz2.TimeZone.DaylightName : dateWithTz2.TimeZone.DaylightName,
|
||||
fileName);
|
||||
}
|
||||
catch (SerializationException)
|
||||
{
|
||||
Console.WriteLine("Unable to retrieve date and time information from {0}",
|
||||
fileName);
|
||||
}
|
||||
finally
|
||||
{
|
||||
inFile.Close();
|
||||
}
|
||||
}
|
||||
// This example displays the following output to the console:
|
||||
// Saving 9/3/2008 7:00:00 PM -05:00 Central Daylight Time to .\DateWithTz.dat
|
||||
// Restored 9/3/2008 7:00:00 PM -05:00 Central Daylight Time from .\DateWithTz.dat
|
||||
// </Snippet4>
|
||||
}
|
||||
}
|
||||
|
||||
// <Snippet3>
|
||||
|
@ -158,7 +94,7 @@ public class Class1
|
|||
public DateInTimeZone(DateTimeOffset date, TimeZoneInfo timeZone)
|
||||
{
|
||||
if (timeZone == null)
|
||||
throw new ArgumentNullException("The time zone cannot be null.");
|
||||
throw new ArgumentNullException("timeZone", "The time zone cannot be null.");
|
||||
|
||||
this.thisDate = date;
|
||||
this.tz = timeZone;
|
||||
|
|
|
@ -1,26 +1,22 @@
|
|||
//<snippetUsingSerialization>
|
||||
//<snippetUsing>
|
||||
using System;
|
||||
using System.Linq;
|
||||
using System.Collections.Generic;
|
||||
using System.Text;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Data.Objects;
|
||||
using System.Data.Objects.DataClasses;
|
||||
//</snippetUsing>
|
||||
using System.Runtime.Serialization;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using System.IO;
|
||||
//</snippetUsingSerialization>
|
||||
using System.Xml.Serialization;
|
||||
using System.Data.Common.CommandTrees;
|
||||
using System.Data.Metadata.Edm;
|
||||
using System.Data.EntityClient;
|
||||
//<snippetUsingEvents>
|
||||
using System.ComponentModel;
|
||||
using System.Data;
|
||||
using System.Data.Common;
|
||||
using System.Data.EntityClient;
|
||||
using System.Data.Metadata.Edm;
|
||||
using System.Data.Objects;
|
||||
using System.Data.Objects.DataClasses;
|
||||
//</snippetUsingEvents>
|
||||
using System.Data.SqlClient;
|
||||
//</snippetUsing>
|
||||
using System.IO;
|
||||
using System.Linq;
|
||||
//</snippetUsingSerialization>
|
||||
using System.Xml.Serialization;
|
||||
|
||||
namespace ObjectServicesConceptsCS
|
||||
{
|
||||
|
@ -1581,102 +1577,6 @@ namespace ObjectServicesConceptsCS
|
|||
Console.WriteLine(writer.ToString());
|
||||
}
|
||||
}
|
||||
#region StreamToBinary
|
||||
//<snippetStreamToBinary>
|
||||
public static void ReadFromBinaryStream()
|
||||
{
|
||||
BinaryFormatter formatter = new BinaryFormatter();
|
||||
using (AdventureWorksEntities context = new AdventureWorksEntities())
|
||||
{
|
||||
try
|
||||
{
|
||||
// Get the object graph for the selected customer
|
||||
// as a binary stream.
|
||||
MemoryStream stream = SerializeToBinaryStream(@"Adams");
|
||||
|
||||
// Read from the begining of the stream.
|
||||
stream.Seek(0, SeekOrigin.Begin);
|
||||
|
||||
// Deserialize the customer graph from the binary stream
|
||||
// and attach to an ObjectContext.
|
||||
Contact contact = (Contact)formatter.Deserialize(stream);
|
||||
context.Attach(contact);
|
||||
|
||||
// Display information for each item
|
||||
// in the orders that belong to the first contact.
|
||||
foreach (SalesOrderHeader order in contact.SalesOrderHeaders)
|
||||
{
|
||||
Console.WriteLine(String.Format("PO Number: {0}",
|
||||
order.PurchaseOrderNumber));
|
||||
Console.WriteLine(String.Format("Order Date: {0}",
|
||||
order.OrderDate.ToString()));
|
||||
Console.WriteLine("Order items:");
|
||||
foreach (SalesOrderDetail item in order.SalesOrderDetails)
|
||||
{
|
||||
Console.WriteLine(String.Format("Product: {0} "
|
||||
+ "Quantity: {1}", item.ProductID.ToString(),
|
||||
item.OrderQty.ToString()));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
catch (SerializationException ex)
|
||||
{
|
||||
Console.WriteLine("The object graph could not be deserialized from "
|
||||
+ "the binary stream because of the following error:");
|
||||
Console.WriteLine(ex.ToString());
|
||||
}
|
||||
}
|
||||
}
|
||||
private static MemoryStream SerializeToBinaryStream(string lastName)
|
||||
{
|
||||
BinaryFormatter formatter = new BinaryFormatter();
|
||||
MemoryStream stream = new MemoryStream();
|
||||
|
||||
using (AdventureWorksEntities context = new AdventureWorksEntities())
|
||||
{
|
||||
//<snippetQueryTimeout>
|
||||
// Specify a timeout for queries in this context, in seconds.
|
||||
context.CommandTimeout = 120;
|
||||
//</snippetQueryTimeout>
|
||||
|
||||
// Define a customer contact.
|
||||
Contact customer;
|
||||
|
||||
// Create a Contact query with a path that returns
|
||||
// orders and items for a contact.
|
||||
ObjectQuery<Contact> query =
|
||||
context.Contacts.Include("SalesOrderHeaders.SalesOrderDetails");
|
||||
|
||||
try
|
||||
{
|
||||
// Return the first contact with the specified last name
|
||||
// along with its related orders and items.
|
||||
customer = query.Where("it.LastName = @lastname",
|
||||
new ObjectParameter("lastname", lastName)).First();
|
||||
|
||||
// Serialize the customer object graph.
|
||||
formatter.Serialize(stream, customer);
|
||||
}
|
||||
catch (EntitySqlException ex)
|
||||
{
|
||||
throw new InvalidOperationException("The object query failed", ex);
|
||||
}
|
||||
catch (EntityCommandExecutionException ex)
|
||||
{
|
||||
throw new InvalidOperationException("The object query failed", ex);
|
||||
}
|
||||
catch (SerializationException ex)
|
||||
{
|
||||
throw new InvalidOperationException("The object graph could not be serialized", ex);
|
||||
}
|
||||
|
||||
// Return the streamed object graph.
|
||||
return stream;
|
||||
}
|
||||
}
|
||||
//</snippetStreamToBinary>
|
||||
#endregion
|
||||
|
||||
public static Boolean CleanupOrders()
|
||||
{
|
||||
|
@ -3704,67 +3604,6 @@ namespace ObjectServicesConceptsCS
|
|||
}
|
||||
//</snippetDDL>
|
||||
}
|
||||
|
||||
public static void DDLTest2()
|
||||
{
|
||||
//<snippetDDL2>
|
||||
String connectionString = "metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;" +
|
||||
"provider connection string=\"Data Source=.;Initial Catalog=SchoolTest;Integrated Security=True;MultipleActiveResultSets=True\"";
|
||||
|
||||
ObjectContext context = new ObjectContext(connectionString);
|
||||
if (context.DatabaseExists())
|
||||
{
|
||||
// Make sure the database instance is closed.
|
||||
context.DeleteDatabase();
|
||||
}
|
||||
// View the database creation script.
|
||||
Console.WriteLine(context.CreateDatabaseScript());
|
||||
|
||||
// Create the new database instance based on the storage (SSDL) section
|
||||
// of the .edmx file.
|
||||
context.CreateDatabase();
|
||||
|
||||
//</snippetDDL2>
|
||||
}
|
||||
/*
|
||||
public static void ObjectQueryTablePerHierarchy()
|
||||
{
|
||||
Console.WriteLine("Starting method 'ObjectQueryTablePerHierarchy'");
|
||||
//<snippetObjectQueryTablePerHierarchy>
|
||||
try
|
||||
{
|
||||
using (SchoolEntities context =
|
||||
new SchoolEntities())
|
||||
{
|
||||
int courseId = 1045;
|
||||
// Get all people for the supplied CourseID
|
||||
Course instructorQuery = context.Courses.Where(
|
||||
"it.CourseID = @courseID", new ObjectParameter
|
||||
("courseID", courseId)).Include("People").
|
||||
FirstOrDefault();
|
||||
|
||||
|
||||
// Display instructors for the specified course.
|
||||
foreach (Instructor instructor in instructorQuery.People.
|
||||
OfType<Instructor>())
|
||||
{
|
||||
Console.WriteLine("Instructor: " + instructor.
|
||||
LastName + ", " + instructor.FirstName);
|
||||
}
|
||||
}
|
||||
|
||||
}
|
||||
catch (System.Data.MappingException e)
|
||||
{
|
||||
Console.WriteLine(e.ToString());
|
||||
}
|
||||
catch (System.Data.EntityException e)
|
||||
{
|
||||
Console.WriteLine(e.ToString());
|
||||
}
|
||||
//</snippetObjectQueryTablePerHierarchy>
|
||||
}
|
||||
*/
|
||||
}
|
||||
|
||||
#region partial methods
|
||||
|
|
|
@ -1,58 +0,0 @@
|
|||
// <Snippet1>
|
||||
using System;
|
||||
using System.IO;
|
||||
using System.Runtime.Serialization.Formatters.Binary;
|
||||
using Libraries;
|
||||
|
||||
namespace test_serialization
|
||||
{
|
||||
class Program
|
||||
{
|
||||
static void Main()
|
||||
{
|
||||
var value = ValueTuple.Create("03244562", DateTime.Now, 13452.50m);
|
||||
if (value.IsSerializable())
|
||||
{
|
||||
// Serialize the value tuple.
|
||||
var formatter = new BinaryFormatter();
|
||||
using (var stream = new FileStream("data.bin", FileMode.Create,
|
||||
FileAccess.Write, FileShare.None))
|
||||
{
|
||||
formatter.Serialize(stream, value);
|
||||
}
|
||||
// Deserialize the value tuple.
|
||||
using (var readStream = new FileStream("data.bin", FileMode.Open))
|
||||
{
|
||||
object restoredValue = formatter.Deserialize(readStream);
|
||||
Console.WriteLine($"{restoredValue.GetType().Name}: {restoredValue}");
|
||||
}
|
||||
}
|
||||
else
|
||||
{
|
||||
Console.WriteLine($"{nameof(value)} is not serializable");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
// The example displays output like the following:
|
||||
// ValueTuple`3: (03244562, 10/18/2017 5:25:22 PM, 13452.50)
|
||||
// </Snippet1>
|
||||
|
||||
// <Snippet2>
|
||||
namespace Libraries
|
||||
{
|
||||
using System;
|
||||
|
||||
public static class UtilityLibrary
|
||||
{
|
||||
public static bool IsSerializable(this object obj)
|
||||
{
|
||||
if (obj == null)
|
||||
return false;
|
||||
|
||||
Type t = obj.GetType();
|
||||
return t.IsSerializable;
|
||||
}
|
||||
}
|
||||
}
|
||||
// </Snippet2>
|
|
@ -1,8 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
|
@ -1,16 +0,0 @@
|
|||
' <Snippet2>
|
||||
Imports System.Runtime.CompilerServices
|
||||
|
||||
Namespace Global.Libraries
|
||||
|
||||
Public Module UtilityLibrary
|
||||
<Extension>
|
||||
Public Function IsSerializable(obj As Object) As Boolean
|
||||
If obj Is Nothing Then Return False
|
||||
|
||||
Dim t As Type = obj.GetType()
|
||||
Return t.IsSerializable
|
||||
End Function
|
||||
End Module
|
||||
End Namespace
|
||||
' </Snippet2>
|
|
@ -1,28 +0,0 @@
|
|||
' <Snippet1>
|
||||
Imports System.IO
|
||||
Imports System.Runtime.Serialization.Formatters.Binary
|
||||
Imports Libraries
|
||||
|
||||
Module Program
|
||||
Sub Main()
|
||||
Dim value = ValueTuple.Create("03244562", DateTime.Now, 13452.50d)
|
||||
If value.IsSerializable() Then
|
||||
Dim formatter As New BinaryFormatter()
|
||||
' Serialize the value tuple.
|
||||
Using stream As New FileStream("data.bin", FileMode.Create,
|
||||
FileAccess.Write, FileShare.None)
|
||||
formatter.Serialize(stream, value)
|
||||
End Using
|
||||
' Deserialize the value tuple.
|
||||
Using readStream As New FileStream("data.bin", FileMode.Open)
|
||||
Dim restoredValue = formatter.Deserialize(readStream)
|
||||
Console.WriteLine($"{restoredValue.GetType().Name}: {restoredValue}")
|
||||
End Using
|
||||
Else
|
||||
Console.WriteLine($"{nameof(value)} is not serializable")
|
||||
End If
|
||||
End Sub
|
||||
End Module
|
||||
' The example displays output like the following:
|
||||
' ValueTuple`3: (03244562, 10/18/2017 5:25:22 PM, 13452.50)
|
||||
' </Snippet1>
|
|
@ -1,8 +0,0 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Exe</OutputType>
|
||||
<TargetFramework>net6.0</TargetFramework>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
|
@ -0,0 +1,9 @@
|
|||
<Project Sdk="Microsoft.NET.Sdk">
|
||||
|
||||
<PropertyGroup>
|
||||
<OutputType>Library</OutputType>
|
||||
<TargetFrameworks>net7.0</TargetFrameworks>
|
||||
</PropertyGroup>
|
||||
|
||||
</Project>
|
||||
|
|
@ -3,8 +3,6 @@ Option Strict On
|
|||
|
||||
Imports System.Globalization
|
||||
Imports System.IO
|
||||
Imports System.Runtime.Serialization
|
||||
Imports System.Runtime.Serialization.Formatters.Binary
|
||||
|
||||
Module modMain
|
||||
|
||||
|
@ -13,7 +11,6 @@ Module modMain
|
|||
Console.WriteLine()
|
||||
RoundTripDateTimeOffset()
|
||||
Console.WriteLine()
|
||||
RoundTripTimeWithTimeZone()
|
||||
End Sub
|
||||
|
||||
Private Sub RoundTripDateTime()
|
||||
|
@ -77,55 +74,6 @@ Module modMain
|
|||
' Read 6/12/2008 6:45:15 PM +07:00 from .\DateOff.txt.
|
||||
' </Snippet2>
|
||||
End Sub
|
||||
|
||||
Private Sub RoundTripTimeWithTimeZone()
|
||||
' <Snippet4>
|
||||
Const fileName As String = ".\DateWithTz.dat"
|
||||
|
||||
Dim tempDate As Date = #9/3/2008 7:00:00 PM#
|
||||
Dim tempTz As TimeZoneInfo = TimeZoneInfo.FindSystemTimeZoneById("Central Standard Time")
|
||||
Dim dateWithTz As New DateInTimeZone(New DateTimeOffset(tempDate, _
|
||||
tempTz.GetUtcOffset(tempDate)), _
|
||||
tempTz)
|
||||
|
||||
' Store DateInTimeZone value to a file
|
||||
Dim outFile As New FileStream(fileName, FileMode.Create)
|
||||
Try
|
||||
Dim formatter As New BinaryFormatter()
|
||||
formatter.Serialize(outFile, dateWithTz)
|
||||
Console.WriteLine("Saving {0} {1} to {2}", dateWithTz.DateAndTime, _
|
||||
IIf(dateWithTz.TimeZone.IsDaylightSavingTime(dateWithTz.DateAndTime), _
|
||||
dateWithTz.TimeZone.DaylightName, dateWithTz.TimeZone.DaylightName), _
|
||||
fileName)
|
||||
Catch e As SerializationException
|
||||
Console.WriteLine("Unable to serialize time data to {0}.", fileName)
|
||||
Finally
|
||||
outFile.Close()
|
||||
End Try
|
||||
|
||||
' Retrieve DateInTimeZone value
|
||||
If File.Exists(fileName) Then
|
||||
Dim inFile As New FileStream(fileName, FileMode.Open)
|
||||
Dim dateWithTz2 As New DateInTimeZone()
|
||||
Try
|
||||
Dim formatter As New BinaryFormatter()
|
||||
dateWithTz2 = DirectCast(formatter.Deserialize(inFile), DateInTimeZone)
|
||||
Console.WriteLine("Restored {0} {1} from {2}", dateWithTz2.DateAndTime, _
|
||||
IIf(dateWithTz2.TimeZone.IsDaylightSavingTime(dateWithTz2.DateAndTime), _
|
||||
dateWithTz2.TimeZone.DaylightName, dateWithTz2.TimeZone.DaylightName), _
|
||||
fileName)
|
||||
Catch e As SerializationException
|
||||
Console.WriteLine("Unable to retrieve date and time information from {0}", _
|
||||
fileName)
|
||||
Finally
|
||||
inFile.Close
|
||||
End Try
|
||||
End If
|
||||
' This example displays the following output to the console:
|
||||
' Saving 9/3/2008 7:00:00 PM -05:00 Central Daylight Time to .\DateWithTz.dat
|
||||
' Restored 9/3/2008 7:00:00 PM -05:00 Central Daylight Time from .\DateWithTz.dat
|
||||
' </Snippet4>
|
||||
End Sub
|
||||
End Module
|
||||
|
||||
' <Snippet3>
|
||||
|
@ -138,7 +86,7 @@ End Module
|
|||
|
||||
Public Sub New(date1 As DateTimeOffset, timeZone As TimeZoneInfo)
|
||||
If timeZone Is Nothing Then
|
||||
Throw New ArgumentNullException("The time zone cannot be null.")
|
||||
Throw New ArgumentNullException("timeZone", "The time zone cannot be null.")
|
||||
End If
|
||||
Me.thisDate = date1
|
||||
Me.tz = timeZone
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'------------------------------------------------------------------------------
|
||||
' <auto-generated>
|
||||
' This code was generated by a tool.
|
||||
' Runtime Version:4.0.20926.1
|
||||
' Runtime Version:4.0.30319.42000
|
||||
'
|
||||
' Changes to this file may cause incorrect behavior and will be lost if
|
||||
' the code is regenerated.
|
||||
|
|
|
@ -1,7 +1,7 @@
|
|||
'------------------------------------------------------------------------------
|
||||
' <auto-generated>
|
||||
' This code was generated by a tool.
|
||||
' Runtime Version:4.0.20926.1
|
||||
' Runtime Version:4.0.30319.42000
|
||||
'
|
||||
' Changes to this file may cause incorrect behavior and will be lost if
|
||||
' the code is regenerated.
|
||||
|
@ -13,42 +13,42 @@ Option Explicit On
|
|||
|
||||
|
||||
Namespace My
|
||||
|
||||
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
|
||||
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "10.0.0.0"), _
|
||||
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
|
||||
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
|
||||
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.4.0.0"), _
|
||||
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Partial Friend NotInheritable Class MySettings
|
||||
Inherits Global.System.Configuration.ApplicationSettingsBase
|
||||
|
||||
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings), MySettings)
|
||||
|
||||
|
||||
Private Shared defaultInstance As MySettings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New MySettings()),MySettings)
|
||||
|
||||
#Region "My.Settings Auto-Save Functionality"
|
||||
#If _MyType = "WindowsForms" Then
|
||||
Private Shared addedHandler As Boolean
|
||||
Private Shared addedHandler As Boolean
|
||||
|
||||
Private Shared addedHandlerLockObject As New Object
|
||||
Private Shared addedHandlerLockObject As New Object
|
||||
|
||||
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Private Shared Sub AutoSaveSettings(ByVal sender As Global.System.Object, ByVal e As Global.System.EventArgs)
|
||||
If My.Application.SaveMySettingsOnExit Then
|
||||
My.Settings.Save()
|
||||
End If
|
||||
End Sub
|
||||
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs)
|
||||
If My.Application.SaveMySettingsOnExit Then
|
||||
My.Settings.Save()
|
||||
End If
|
||||
End Sub
|
||||
#End If
|
||||
#End Region
|
||||
|
||||
|
||||
Public Shared ReadOnly Property [Default]() As MySettings
|
||||
Get
|
||||
|
||||
|
||||
#If _MyType = "WindowsForms" Then
|
||||
If Not addedHandler Then
|
||||
SyncLock addedHandlerLockObject
|
||||
If Not addedHandler Then
|
||||
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
|
||||
addedHandler = True
|
||||
End If
|
||||
End SyncLock
|
||||
End If
|
||||
If Not addedHandler Then
|
||||
SyncLock addedHandlerLockObject
|
||||
If Not addedHandler Then
|
||||
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
|
||||
addedHandler = True
|
||||
End If
|
||||
End SyncLock
|
||||
End If
|
||||
#End If
|
||||
Return defaultInstance
|
||||
End Get
|
||||
|
|
|
@ -1,29 +1,18 @@
|
|||
'<snippetUsingSerialization>
|
||||
'<snippetUsing>
|
||||
Imports System.Linq
|
||||
Imports System.Collections.Generic
|
||||
Imports System.Text
|
||||
Imports System.Data
|
||||
Imports System.Data.Common
|
||||
Imports System.Data.Objects
|
||||
Imports System.Data.Objects.DataClasses
|
||||
|
||||
'</snippetUsing>
|
||||
Imports System.Runtime.Serialization
|
||||
Imports System.Runtime.Serialization.Formatters.Binary
|
||||
Imports System.IO
|
||||
|
||||
'</snippetUsingSerialization>
|
||||
Imports System.Xml.Serialization
|
||||
Imports System.Data.Common.CommandTrees
|
||||
Imports System.Data.Metadata.Edm
|
||||
Imports System.Data.EntityClient
|
||||
|
||||
'<snippetUsingEvents>
|
||||
Imports System.ComponentModel
|
||||
|
||||
Imports System.Data.Common
|
||||
Imports System.Data.EntityClient
|
||||
Imports System.Data.Metadata.Edm
|
||||
Imports System.Data.Objects
|
||||
Imports System.Data.Objects.DataClasses
|
||||
'</snippetUsingEvents>
|
||||
Imports System.Data.SqlClient
|
||||
'</snippetUsing>
|
||||
Imports System.IO
|
||||
'</snippetUsingSerialization>
|
||||
Imports System.Xml.Serialization
|
||||
|
||||
Class Source1
|
||||
'<snippetExecuteStoreCommandAndQueryForNewEntity>
|
||||
|
@ -1202,80 +1191,6 @@ Class Source1
|
|||
Console.WriteLine(writer.ToString())
|
||||
End Using
|
||||
End Sub
|
||||
#Region "StreamToBinary"
|
||||
'<snippetStreamToBinary>
|
||||
Public Shared Sub ReadFromBinaryStream()
|
||||
Dim formatter As New BinaryFormatter()
|
||||
Using context As New AdventureWorksEntities()
|
||||
Try
|
||||
' Get the object graph for the selected customer
|
||||
' as a binary stream.
|
||||
Dim stream As MemoryStream = SerializeToBinaryStream("Adams")
|
||||
|
||||
' Read from the begining of the stream.
|
||||
stream.Seek(0, SeekOrigin.Begin)
|
||||
|
||||
' Deserialize the customer graph from the binary stream
|
||||
' and attach to an ObjectContext.
|
||||
Dim contact As Contact = DirectCast(formatter.Deserialize(stream), Contact)
|
||||
context.Attach(contact)
|
||||
|
||||
' Display information for each item
|
||||
' in the orders that belong to the first contact.
|
||||
For Each order As SalesOrderHeader In contact.SalesOrderHeaders
|
||||
Console.WriteLine(String.Format("PO Number: {0}", order.PurchaseOrderNumber))
|
||||
Console.WriteLine(String.Format("Order Date: {0}", order.OrderDate.ToString()))
|
||||
Console.WriteLine("Order items:")
|
||||
For Each item As SalesOrderDetail In order.SalesOrderDetails
|
||||
Console.WriteLine(String.Format("Product: {0}, Quantity: {1}", _
|
||||
item.ProductID.ToString(), item.OrderQty.ToString()))
|
||||
Next
|
||||
Next
|
||||
Catch ex As SerializationException
|
||||
Console.WriteLine("The object graph could not be deserialized from " & _
|
||||
"the binary stream because of the following error:")
|
||||
Console.WriteLine(ex.ToString())
|
||||
End Try
|
||||
End Using
|
||||
End Sub
|
||||
Private Shared Function SerializeToBinaryStream(ByVal lastName As String) As MemoryStream
|
||||
Dim formatter As New BinaryFormatter()
|
||||
Dim stream As New MemoryStream()
|
||||
|
||||
Using context As New AdventureWorksEntities()
|
||||
'<snippetQueryTimeout>
|
||||
' Specify a timeout for queries in this context, in seconds.
|
||||
context.CommandTimeout = 120
|
||||
'</snippetQueryTimeout>
|
||||
|
||||
' Define a customer contact.
|
||||
Dim customer As Contact
|
||||
|
||||
' Create a Contact query with a path that returns
|
||||
' orders and items for a contact.
|
||||
Dim query As ObjectQuery(Of Contact) = context.Contacts.Include("SalesOrderHeaders.SalesOrderDetails")
|
||||
|
||||
Try
|
||||
' Return the first contact with the specified last name
|
||||
' along with its related orders and items.
|
||||
customer = query.Where("it.LastName = @lastname", New ObjectParameter("lastname", lastName)).First()
|
||||
|
||||
' Serialize the customer object graph.
|
||||
formatter.Serialize(stream, customer)
|
||||
Catch ex As EntitySqlException
|
||||
Throw New InvalidOperationException("The object query failed", ex)
|
||||
Catch ex As EntityCommandExecutionException
|
||||
Throw New InvalidOperationException("The object query failed", ex)
|
||||
Catch ex As SerializationException
|
||||
Throw New InvalidOperationException("The object graph could not be serialized", ex)
|
||||
End Try
|
||||
|
||||
' Return the streamed object graph.
|
||||
Return stream
|
||||
End Using
|
||||
End Function
|
||||
'</snippetStreamToBinary>
|
||||
#End Region
|
||||
|
||||
Public Shared Function CleanupOrders() As Boolean
|
||||
Using context As New AdventureWorksEntities()
|
||||
|
@ -2918,8 +2833,8 @@ Class Source1
|
|||
Public Shared Sub DDLTest()
|
||||
'<snippetDDL>
|
||||
' Initialize the connection string.
|
||||
Dim connectionString As String = _
|
||||
"metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;" & _
|
||||
Dim connectionString As String =
|
||||
"metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;" &
|
||||
"provider connection string=""Data Source=.;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True"""
|
||||
|
||||
Using context As New SchoolEntities(connectionString)
|
||||
|
@ -2956,45 +2871,6 @@ Class Source1
|
|||
End Using
|
||||
'</snippetDDL>
|
||||
End Sub
|
||||
'
|
||||
' public static void ObjectQueryTablePerHierarchy()
|
||||
' {
|
||||
' Console.WriteLine("Starting method 'ObjectQueryTablePerHierarchy'");
|
||||
' //<snippetObjectQueryTablePerHierarchy>
|
||||
' try
|
||||
' {
|
||||
' using (SchoolEntities context =
|
||||
' new SchoolEntities())
|
||||
' {
|
||||
' int courseId = 1045;
|
||||
' // Get all people for the supplied CourseID
|
||||
' Course instructorQuery = context.Courses.Where(
|
||||
' "it.CourseID = @courseID", new ObjectParameter
|
||||
' ("courseID", courseId)).Include("People").
|
||||
' FirstOrDefault();
|
||||
'
|
||||
'
|
||||
' // Display instructors for the specified course.
|
||||
' foreach (Instructor instructor in instructorQuery.People.
|
||||
' OfType<Instructor>())
|
||||
' {
|
||||
' Console.WriteLine("Instructor: " + instructor.
|
||||
' LastName + ", " + instructor.FirstName);
|
||||
' }
|
||||
' }
|
||||
'
|
||||
' }
|
||||
' catch (System.Data.MappingException e)
|
||||
' {
|
||||
' Console.WriteLine(e.ToString());
|
||||
' }
|
||||
' catch (System.Data.EntityException e)
|
||||
' {
|
||||
' Console.WriteLine(e.ToString());
|
||||
' }
|
||||
' //</snippetObjectQueryTablePerHierarchy>
|
||||
' }
|
||||
'
|
||||
|
||||
End Class
|
||||
|
||||
|
|
Разница между файлами не показана из-за своего большого размера
Загрузить разницу
|
@ -1,27 +1,27 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<system.diagnostics>
|
||||
<sources>
|
||||
<!-- This section defines the logging configuration for My.Application.Log -->
|
||||
<source name="DefaultSource" switchName="DefaultSwitch">
|
||||
<listeners>
|
||||
<add name="FileLog" />
|
||||
<add name="FileLog"/>
|
||||
<!-- Uncomment the below section to write to the Application Event Log -->
|
||||
<!--<add name="EventLog"/>-->
|
||||
</listeners>
|
||||
</source>
|
||||
</sources>
|
||||
<switches>
|
||||
<add name="DefaultSwitch" value="Information" />
|
||||
<add name="DefaultSwitch" value="Information"/>
|
||||
</switches>
|
||||
<sharedListeners>
|
||||
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter" />
|
||||
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/>
|
||||
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
|
||||
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
|
||||
</sharedListeners>
|
||||
</system.diagnostics>
|
||||
<connectionStrings>
|
||||
<add name="AdventureWorksEntities" connectionString="metadata=res://*/AdventureWorksModel.csdl|res://*/AdventureWorksModel.ssdl|res://*/AdventureWorksModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=juliakornich;Initial Catalog=AdventureWorks;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
|
||||
<add name="SchoolEntities" connectionString="metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;provider connection string="Data Source=juliakornich;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient" />
|
||||
<add name="AdventureWorksEntities" connectionString="metadata=res://*/AdventureWorksModel.csdl|res://*/AdventureWorksModel.ssdl|res://*/AdventureWorksModel.msl;provider=System.Data.SqlClient;provider connection string="Data Source=juliakornich;Initial Catalog=AdventureWorks;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
|
||||
<add name="SchoolEntities" connectionString="metadata=res://*/School.csdl|res://*/School.ssdl|res://*/School.msl;provider=System.Data.SqlClient;provider connection string="Data Source=juliakornich;Initial Catalog=School;Integrated Security=True;MultipleActiveResultSets=True"" providerName="System.Data.EntityClient"/>
|
||||
</connectionStrings>
|
||||
</configuration>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>
|
||||
|
|
|
@ -1,5 +1,5 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project ToolsVersion="4.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Project ToolsVersion="12.0" DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">x86</Platform>
|
||||
|
@ -14,8 +14,9 @@
|
|||
<AssemblyName>ObjectServicesConceptsVB</AssemblyName>
|
||||
<FileAlignment>512</FileAlignment>
|
||||
<MyType>Console</MyType>
|
||||
<TargetFrameworkVersion>v4.0</TargetFrameworkVersion>
|
||||
<TargetFrameworkProfile>Client</TargetFrameworkProfile>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<TargetFrameworkProfile>
|
||||
</TargetFrameworkProfile>
|
||||
<OptionExplicit>On</OptionExplicit>
|
||||
<OptionCompare>Binary</OptionCompare>
|
||||
<OptionStrict>Off</OptionStrict>
|
||||
|
@ -30,6 +31,7 @@
|
|||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DocumentationFile>ObjectServicesConceptsVB.xml</DocumentationFile>
|
||||
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|x86' ">
|
||||
<PlatformTarget>x86</PlatformTarget>
|
||||
|
@ -40,6 +42,7 @@
|
|||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DocumentationFile>ObjectServicesConceptsVB.xml</DocumentationFile>
|
||||
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
|
@ -76,6 +79,7 @@
|
|||
<Compile Include="My Project\Application.Designer.vb">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Application.myapp</DependentUpon>
|
||||
<DesignTime>True</DesignTime>
|
||||
</Compile>
|
||||
<Compile Include="My Project\Settings.Designer.vb">
|
||||
<AutoGen>True</AutoGen>
|
||||
|
|
|
@ -8,14 +8,17 @@
|
|||
' </auto-generated>
|
||||
'------------------------------------------------------------------------------
|
||||
|
||||
Imports System
|
||||
Imports System.ComponentModel
|
||||
Imports System.Data.EntityClient
|
||||
Imports System.Data.Objects
|
||||
Imports System.Data.Objects.DataClasses
|
||||
Imports System.Data.EntityClient
|
||||
Imports System.ComponentModel
|
||||
Imports System.Xml.Serialization
|
||||
Imports System.Linq
|
||||
Imports System.Runtime.Serialization
|
||||
Imports System.Xml.Serialization
|
||||
|
||||
<Assembly: EdmSchemaAttribute("7d0cb770-5e74-4397-a4a5-29fec148c801")>
|
||||
|
||||
<Assembly: EdmSchemaAttribute("ae35fcfc-fb4b-48cf-a3ad-973bdf10a8f7")>
|
||||
#Region "EDM Relationship Metadata"
|
||||
<Assembly: EdmRelationshipAttribute("SchoolModel", "FK_Course_Department", "Department", System.Data.Metadata.Edm.RelationshipMultiplicity.One, GetType(Department), "Course", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, GetType(Course), True)>
|
||||
<Assembly: EdmRelationshipAttribute("SchoolModel", "FK_StudentGrade_Course", "Course", System.Data.Metadata.Edm.RelationshipMultiplicity.One, GetType(Course), "StudentGrade", System.Data.Metadata.Edm.RelationshipMultiplicity.Many, GetType(StudentGrade), True)>
|
||||
|
@ -40,7 +43,6 @@ Public Partial Class SchoolEntities
|
|||
''' </summary>
|
||||
Public Sub New()
|
||||
MyBase.New("name=SchoolEntities", "SchoolEntities")
|
||||
MyBase.ContextOptions.LazyLoadingEnabled = True
|
||||
OnContextCreated()
|
||||
End Sub
|
||||
|
||||
|
@ -49,7 +51,6 @@ Public Partial Class SchoolEntities
|
|||
''' </summary>
|
||||
Public Sub New(ByVal connectionString As String)
|
||||
MyBase.New(connectionString, "SchoolEntities")
|
||||
MyBase.ContextOptions.LazyLoadingEnabled = True
|
||||
OnContextCreated()
|
||||
End Sub
|
||||
|
||||
|
@ -58,7 +59,6 @@ Public Partial Class SchoolEntities
|
|||
''' </summary>
|
||||
Public Sub New(ByVal connection As EntityConnection)
|
||||
MyBase.New(connection, "SchoolEntities")
|
||||
MyBase.ContextOptions.LazyLoadingEnabled = True
|
||||
OnContextCreated()
|
||||
End Sub
|
||||
|
||||
|
@ -144,6 +144,7 @@ Public Partial Class SchoolEntities
|
|||
Private _StudentGrades As ObjectSet(Of StudentGrade)
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "AddTo Methods"
|
||||
|
||||
''' <summary>
|
||||
|
@ -182,6 +183,7 @@ Public Partial Class SchoolEntities
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Function Imports"
|
||||
|
||||
''' <summary>
|
||||
|
@ -234,9 +236,11 @@ Public Partial Class SchoolEntities
|
|||
End Function
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Entities"
|
||||
|
||||
''' <summary>
|
||||
|
@ -354,6 +358,7 @@ Public MustInherit Partial Class Course
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Navigation Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -424,6 +429,7 @@ Public MustInherit Partial Class Course
|
|||
End Property
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
''' <summary>
|
||||
|
@ -453,6 +459,7 @@ Public Partial Class Department
|
|||
End Function
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Primitive Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -583,6 +590,7 @@ Public Partial Class Department
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Navigation Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -604,6 +612,7 @@ Public Partial Class Department
|
|||
End Property
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
''' <summary>
|
||||
|
@ -631,6 +640,7 @@ Public Partial Class OfficeAssignment
|
|||
End Function
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Primitive Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -697,7 +707,7 @@ Public Partial Class OfficeAssignment
|
|||
Set
|
||||
OnTimestampChanging(value)
|
||||
ReportPropertyChanging("Timestamp")
|
||||
_Timestamp = StructuralObject.SetValidValue(value, false)
|
||||
_Timestamp = StructuralObject.SetValidValue(value, true)
|
||||
ReportPropertyChanged("Timestamp")
|
||||
OnTimestampChanged()
|
||||
End Set
|
||||
|
@ -711,6 +721,7 @@ Public Partial Class OfficeAssignment
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Navigation Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -745,6 +756,7 @@ Public Partial Class OfficeAssignment
|
|||
End Property
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
''' <summary>
|
||||
|
@ -776,6 +788,7 @@ Public Partial Class OnlineCourse
|
|||
End Function
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Primitive Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -804,6 +817,7 @@ Public Partial Class OnlineCourse
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
''' <summary>
|
||||
|
@ -839,6 +853,7 @@ Public Partial Class OnsiteCourse
|
|||
End Function
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Primitive Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -917,6 +932,7 @@ Public Partial Class OnsiteCourse
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
''' <summary>
|
||||
|
@ -944,6 +960,7 @@ Public Partial Class Person
|
|||
End Function
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Primitive Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -1074,6 +1091,7 @@ Public Partial Class Person
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Navigation Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -1144,6 +1162,7 @@ Public Partial Class Person
|
|||
End Property
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
''' <summary>
|
||||
|
@ -1171,6 +1190,7 @@ Public Partial Class StudentGrade
|
|||
End Function
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Primitive Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -1276,6 +1296,7 @@ Public Partial Class StudentGrade
|
|||
End Sub
|
||||
|
||||
#End Region
|
||||
|
||||
#Region "Navigation Properties"
|
||||
|
||||
''' <summary>
|
||||
|
@ -1341,7 +1362,9 @@ Public Partial Class StudentGrade
|
|||
End Property
|
||||
|
||||
#End Region
|
||||
|
||||
End Class
|
||||
|
||||
#End Region
|
||||
|
||||
|
||||
|
|
|
@ -1,35 +1,36 @@
|
|||
'------------------------------------------------------------------------------
|
||||
' <autogenerated>
|
||||
' <auto-generated>
|
||||
' This code was generated by a tool.
|
||||
' Runtime Version:2.0.50107.0
|
||||
' Runtime Version:4.0.30319.42000
|
||||
'
|
||||
' Changes to this file may cause incorrect behavior and will be lost if
|
||||
' the code is regenerated.
|
||||
' </autogenerated>
|
||||
' </auto-generated>
|
||||
'------------------------------------------------------------------------------
|
||||
|
||||
Option Strict On
|
||||
Option Explicit On
|
||||
|
||||
|
||||
Namespace My
|
||||
|
||||
'NOTE: This file is auto-generated, do not modify it directly. To make changes,
|
||||
'NOTE: This file is auto-generated; do not modify it directly. To make changes,
|
||||
' or if you encounter build errors in this file, go to the Project Designer
|
||||
' (go to project properties or double-click on the My Project node in the
|
||||
' (go to Project Properties or double-click the My Project node in
|
||||
' Solution Explorer), and make changes on the Application tab.
|
||||
'
|
||||
Partial Class MyApplication
|
||||
Partial Friend Class MyApplication
|
||||
|
||||
<Global.System.Diagnostics.DebuggerStepThrough()> _
|
||||
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
|
||||
Public Sub New()
|
||||
MyBase.New(Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
|
||||
MyBase.New(Global.Microsoft.VisualBasic.ApplicationServices.AuthenticationMode.Windows)
|
||||
Me.IsSingleInstance = false
|
||||
Me.EnableVisualStyles = true
|
||||
Me.SaveMySettingsOnExit = true
|
||||
Me.ShutDownStyle = Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
|
||||
Me.ShutDownStyle = Global.Microsoft.VisualBasic.ApplicationServices.ShutdownMode.AfterMainFormCloses
|
||||
End Sub
|
||||
|
||||
<Global.System.Diagnostics.DebuggerStepThrough()> _
|
||||
<Global.System.Diagnostics.DebuggerStepThroughAttribute()> _
|
||||
Protected Overrides Sub OnCreateMainForm()
|
||||
Me.MainForm = Global.VbVbalrOOP.Form1
|
||||
End Sub
|
||||
|
|
|
@ -1,16 +1,17 @@
|
|||
'------------------------------------------------------------------------------
|
||||
' <autogenerated>
|
||||
' <auto-generated>
|
||||
' This code was generated by a tool.
|
||||
' Runtime Version:2.0.50107.0
|
||||
' Runtime Version:4.0.30319.42000
|
||||
'
|
||||
' Changes to this file may cause incorrect behavior and will be lost if
|
||||
' the code is regenerated.
|
||||
' </autogenerated>
|
||||
' </auto-generated>
|
||||
'------------------------------------------------------------------------------
|
||||
|
||||
Option Strict On
|
||||
Option Explicit On
|
||||
|
||||
Imports System
|
||||
|
||||
Namespace My.Resources
|
||||
|
||||
|
@ -21,7 +22,10 @@ Namespace My.Resources
|
|||
'''<summary>
|
||||
''' A strongly-typed resource class, for looking up localized strings, etc.
|
||||
'''</summary>
|
||||
<Global.Microsoft.VisualBasic.HideModuleName()> _
|
||||
<Global.System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "17.0.0.0"), _
|
||||
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
|
||||
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
|
||||
Global.Microsoft.VisualBasic.HideModuleNameAttribute()> _
|
||||
Friend Module Resources
|
||||
|
||||
Private resourceMan As Global.System.Resources.ResourceManager
|
||||
|
@ -31,10 +35,10 @@ Namespace My.Resources
|
|||
'''<summary>
|
||||
''' Returns the cached ResourceManager instance used by this class.
|
||||
'''</summary>
|
||||
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Friend ReadOnly Property ResourceManager() As Global.System.Resources.ResourceManager
|
||||
Get
|
||||
If (resourceMan Is Nothing) Then
|
||||
If Object.ReferenceEquals(resourceMan, Nothing) Then
|
||||
Dim temp As Global.System.Resources.ResourceManager = New Global.System.Resources.ResourceManager("VbVbalrOOP.Resources", GetType(Resources).Assembly)
|
||||
resourceMan = temp
|
||||
End If
|
||||
|
@ -46,7 +50,7 @@ Namespace My.Resources
|
|||
''' Overrides the current thread's CurrentUICulture property for all
|
||||
''' resource lookups using this strongly typed resource class.
|
||||
'''</summary>
|
||||
<System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Friend Property Culture() As Global.System.Globalization.CultureInfo
|
||||
Get
|
||||
Return resourceCulture
|
||||
|
|
|
@ -1,65 +1,72 @@
|
|||
'------------------------------------------------------------------------------
|
||||
' <autogenerated>
|
||||
' <auto-generated>
|
||||
' This code was generated by a tool.
|
||||
' Runtime Version:2.0.50107.0
|
||||
' Runtime Version:4.0.30319.42000
|
||||
'
|
||||
' Changes to this file may cause incorrect behavior and will be lost if
|
||||
' the code is regenerated.
|
||||
' </autogenerated>
|
||||
' </auto-generated>
|
||||
'------------------------------------------------------------------------------
|
||||
|
||||
Option Strict On
|
||||
Option Explicit On
|
||||
|
||||
<Assembly: Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope:="member", Target:="VbVbalrOOP.Settings.get_Default():VbVbalrOOP.Settings"), _
|
||||
Assembly: Global.System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode", Scope:="member", Target:="VbVbalrOOP.My.MySettingsProperty.get_Settings():VbVbalrOOP.Settings")>
|
||||
|
||||
|
||||
<Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Partial NotInheritable Class Settings
|
||||
Inherits Global.System.Configuration.ApplicationSettingsBase
|
||||
|
||||
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
|
||||
Private Shared defaultInstance As Settings = New Settings
|
||||
Namespace My
|
||||
|
||||
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute(), _
|
||||
Global.System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "17.4.0.0"), _
|
||||
Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Partial Friend NotInheritable Class Settings
|
||||
Inherits Global.System.Configuration.ApplicationSettingsBase
|
||||
|
||||
Private Shared defaultInstance As Settings = CType(Global.System.Configuration.ApplicationSettingsBase.Synchronized(New Settings()),Settings)
|
||||
|
||||
#Region "My.Settings Auto-Save Functionality"
|
||||
#If _MyType = "WindowsForms" Then
|
||||
<Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
|
||||
Private Shared addedHandler As Boolean
|
||||
|
||||
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Private Shared Sub AutoSaveSettings(ByVal sender As Object, ByVal e As EventArgs)
|
||||
If My.Application.SaveMySettingsOnExit Then
|
||||
My.Settings.Save()
|
||||
End If
|
||||
End Sub
|
||||
Private Shared addedHandlerLockObject As New Object
|
||||
|
||||
<Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), Global.System.ComponentModel.EditorBrowsableAttribute(Global.System.ComponentModel.EditorBrowsableState.Advanced)> _
|
||||
Private Shared Sub AutoSaveSettings(sender As Global.System.Object, e As Global.System.EventArgs)
|
||||
If My.Application.SaveMySettingsOnExit Then
|
||||
'My.Settings.Save()
|
||||
End If
|
||||
End Sub
|
||||
#End If
|
||||
#End Region
|
||||
|
||||
Public Shared ReadOnly Property [Default]() As Settings
|
||||
Get
|
||||
|
||||
|
||||
Public Shared ReadOnly Property [Default]() As Settings
|
||||
Get
|
||||
|
||||
#If _MyType = "WindowsForms" Then
|
||||
If Not addedHandler Then
|
||||
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
|
||||
addedHandler = True
|
||||
End If
|
||||
If Not addedHandler Then
|
||||
SyncLock addedHandlerLockObject
|
||||
If Not addedHandler Then
|
||||
AddHandler My.Application.Shutdown, AddressOf AutoSaveSettings
|
||||
addedHandler = True
|
||||
End If
|
||||
End SyncLock
|
||||
End If
|
||||
#End If
|
||||
Return defaultInstance
|
||||
End Get
|
||||
End Property
|
||||
End Class
|
||||
Return defaultInstance
|
||||
End Get
|
||||
End Property
|
||||
End Class
|
||||
End Namespace
|
||||
|
||||
Namespace My
|
||||
|
||||
<Global.Microsoft.VisualBasic.HideModuleNameAttribute(), _
|
||||
Global.System.Diagnostics.DebuggerNonUserCodeAttribute()> _
|
||||
Module MySettingsProperty
|
||||
Global.System.Diagnostics.DebuggerNonUserCodeAttribute(), _
|
||||
Global.System.Runtime.CompilerServices.CompilerGeneratedAttribute()> _
|
||||
Friend Module MySettingsProperty
|
||||
|
||||
<Global.System.ComponentModel.Design.HelpKeywordAttribute("My.Settings")> _
|
||||
Friend ReadOnly Property Settings() As Global.VbVbalrOOP.Settings
|
||||
Friend ReadOnly Property Settings() As Global.VbVbalrOOP.My.Settings
|
||||
Get
|
||||
Return Global.VbVbalrOOP.Settings.Default
|
||||
Return Global.VbVbalrOOP.My.Settings.Default
|
||||
End Get
|
||||
End Property
|
||||
End Module
|
||||
|
|
|
@ -1,174 +0,0 @@
|
|||
' Need a reference to System.Runtime.Serialization.Formatters.Soap
|
||||
' And System.Xml
|
||||
' <snippet83>
|
||||
Imports System.Runtime.Serialization.Formatters.Soap
|
||||
' </snippet83>
|
||||
' <snippet80>
|
||||
Imports System.IO
|
||||
Imports System.Runtime.Serialization.Formatters.Binary
|
||||
' </snippet80>
|
||||
|
||||
Class Classcb0a091708d54578ad2b3764ccf6167f
|
||||
' cb0a0917-08d5-4578-ad2b-3764ccf6167f
|
||||
' Walkthrough: Persisting an Object in Visual Basic
|
||||
|
||||
Class Form77
|
||||
Inherits Form
|
||||
|
||||
Dim TextBox1 As New TextBox
|
||||
Dim TextBox2 As New TextBox
|
||||
Dim TextBox3 As New TextBox
|
||||
Dim TextBox4 As New TextBox
|
||||
|
||||
' <snippet77>
|
||||
Private TestLoan As New LoanClass.Loan
|
||||
Private Sub Form1_Load(ByVal sender As System.Object,
|
||||
ByVal e As System.EventArgs) Handles MyBase.Load
|
||||
|
||||
TextBox1.Text = TestLoan.LoanAmount.ToString
|
||||
TextBox2.Text = TestLoan.InterestRate.ToString
|
||||
TextBox3.Text = TestLoan.Term.ToString
|
||||
TextBox4.Text = TestLoan.Customer
|
||||
End Sub
|
||||
' </snippet77>
|
||||
|
||||
End Class
|
||||
|
||||
Class Form81
|
||||
Inherits Form
|
||||
|
||||
Dim TextBox1 As New TextBox
|
||||
Dim TextBox2 As New TextBox
|
||||
Dim TextBox3 As New TextBox
|
||||
Dim TextBox4 As New TextBox
|
||||
|
||||
|
||||
' <snippet119>
|
||||
Const FileName As String = "SavedLoan.bin"
|
||||
' </snippet119>
|
||||
|
||||
' <snippet81>
|
||||
Private WithEvents TestLoan As Loans.Loan
|
||||
|
||||
Private Sub Form1_Load() Handles MyBase.Load
|
||||
AddHandler TestLoan.PropertyChanged, AddressOf Me.CustomerPropertyChanged
|
||||
|
||||
If File.Exists(FileName) Then
|
||||
Dim TestFileStream As Stream = File.OpenRead(FileName)
|
||||
Dim deserializer As New BinaryFormatter
|
||||
TestLoan = CType(deserializer.Deserialize(TestFileStream), Loans.Loan)
|
||||
TestFileStream.Close()
|
||||
End If
|
||||
TextBox1.Text = TestLoan.LoanAmount.ToString
|
||||
TextBox2.Text = TestLoan.InterestRate.ToString
|
||||
TextBox3.Text = TestLoan.Term.ToString
|
||||
TextBox4.Text = TestLoan.Customer
|
||||
End Sub
|
||||
' </snippet81>
|
||||
|
||||
' <snippet82>
|
||||
Private Sub Form1_Closing() Handles MyBase.Closing
|
||||
TestLoan.LoanAmount = CType(TextBox1.Text, Double)
|
||||
TestLoan.InterestRate = CType(TextBox2.Text, Double)
|
||||
TestLoan.Term = CType(TextBox3.Text, Integer)
|
||||
TestLoan.Customer = TextBox4.Text
|
||||
|
||||
Dim TestFileStream As Stream = File.Create(FileName)
|
||||
Dim serializer As New BinaryFormatter
|
||||
serializer.Serialize(TestFileStream, TestLoan)
|
||||
TestFileStream.Close()
|
||||
End Sub
|
||||
' </snippet82>
|
||||
|
||||
' <snippet122>
|
||||
Public Sub CustomerPropertyChanged(
|
||||
ByVal sender As Object,
|
||||
ByVal e As System.ComponentModel.PropertyChangedEventArgs
|
||||
) Handles TestLoan.PropertyChanged
|
||||
|
||||
MsgBox(e.PropertyName & " has been changed.")
|
||||
End Sub
|
||||
|
||||
' </snippet122>
|
||||
End Class
|
||||
|
||||
|
||||
Class LoanClass
|
||||
Class Class78
|
||||
' <snippet78>
|
||||
<Serializable()>
|
||||
Public Class Loan
|
||||
' </snippet78>
|
||||
Implements System.ComponentModel.INotifyPropertyChanged
|
||||
|
||||
' <snippet79>
|
||||
<NonSerialized()>
|
||||
Public Customer As String
|
||||
' </snippet79>
|
||||
|
||||
' <snippet123>
|
||||
<NonSerialized()>
|
||||
Event PropertyChanged As System.ComponentModel.PropertyChangedEventHandler _
|
||||
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
|
||||
' </snippet123>
|
||||
End Class
|
||||
End Class
|
||||
|
||||
<Serializable()> Public Class Loan
|
||||
' <snippet76>
|
||||
Public LoanAmount As Double = 10000.0
|
||||
Public InterestRate As Double = 7.5
|
||||
Public Term As Integer = 36
|
||||
Public Customer As String
|
||||
' </snippet76>
|
||||
End Class
|
||||
End Class
|
||||
|
||||
Class Loans
|
||||
' <snippet121>
|
||||
Public Class Loan
|
||||
Implements System.ComponentModel.INotifyPropertyChanged
|
||||
|
||||
Public Property LoanAmount As Double = 10000.0
|
||||
Public Property InterestRate As Double = 7.5
|
||||
Public Property Term As Integer = 36
|
||||
|
||||
Private p_Customer As String
|
||||
Public Property Customer As String
|
||||
Get
|
||||
Return p_Customer
|
||||
End Get
|
||||
Set(ByVal value As String)
|
||||
p_Customer = value
|
||||
RaiseEvent PropertyChanged(Me,
|
||||
New System.ComponentModel.PropertyChangedEventArgs("Customer"))
|
||||
End Set
|
||||
End Property
|
||||
|
||||
Event PropertyChanged As System.ComponentModel.PropertyChangedEventHandler _
|
||||
Implements System.ComponentModel.INotifyPropertyChanged.PropertyChanged
|
||||
End Class
|
||||
' </snippet121>
|
||||
End Class
|
||||
|
||||
|
||||
Public Sub Method84()
|
||||
' <snippet84>
|
||||
Dim deserializer As New BinaryFormatter
|
||||
' </snippet84>
|
||||
' <snippet118>
|
||||
Dim serializer As New BinaryFormatter
|
||||
' </snippet118>
|
||||
End Sub
|
||||
|
||||
Public Sub Method85()
|
||||
' <snippet85>
|
||||
Dim deserializer As New SoapFormatter
|
||||
' </snippet85>
|
||||
|
||||
' <snippet86>
|
||||
Dim serializer As New SoapFormatter
|
||||
' </snippet86>
|
||||
End Sub
|
||||
|
||||
End Class
|
|
@ -1,5 +1,5 @@
|
|||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">
|
||||
<Project DefaultTargets="Build" xmlns="http://schemas.microsoft.com/developer/msbuild/2003" ToolsVersion="12.0">
|
||||
<PropertyGroup>
|
||||
<Configuration Condition=" '$(Configuration)' == '' ">Debug</Configuration>
|
||||
<Platform Condition=" '$(Platform)' == '' ">AnyCPU</Platform>
|
||||
|
@ -11,6 +11,13 @@
|
|||
<RootNamespace>VbVbalrOOP</RootNamespace>
|
||||
<AssemblyName>VbVbalrOOP</AssemblyName>
|
||||
<MyType>WindowsForms</MyType>
|
||||
<FileUpgradeFlags>
|
||||
</FileUpgradeFlags>
|
||||
<UpgradeBackupLocation>
|
||||
</UpgradeBackupLocation>
|
||||
<OldToolsVersion>2.0</OldToolsVersion>
|
||||
<TargetFrameworkVersion>v4.8</TargetFrameworkVersion>
|
||||
<TargetFrameworkProfile />
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Debug|AnyCPU' ">
|
||||
<DebugSymbols>true</DebugSymbols>
|
||||
|
@ -19,7 +26,8 @@
|
|||
<DefineTrace>true</DefineTrace>
|
||||
<OutputPath>bin\Debug\</OutputPath>
|
||||
<DocumentationFile>VbVbalrOOP.xml</DocumentationFile>
|
||||
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
|
||||
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022,42353,42354,42355</NoWarn>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<PropertyGroup Condition=" '$(Configuration)|$(Platform)' == 'Release|AnyCPU' ">
|
||||
<DebugType>pdbonly</DebugType>
|
||||
|
@ -28,7 +36,8 @@
|
|||
<Optimize>true</Optimize>
|
||||
<OutputPath>bin\Release\</OutputPath>
|
||||
<DocumentationFile>VbVbalrOOP.xml</DocumentationFile>
|
||||
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022</NoWarn>
|
||||
<NoWarn>42016,41999,42017,42018,42019,42032,42036,42020,42021,42022,42353,42354,42355</NoWarn>
|
||||
<Prefer32Bit>false</Prefer32Bit>
|
||||
</PropertyGroup>
|
||||
<ItemGroup>
|
||||
<Reference Include="System" />
|
||||
|
@ -60,6 +69,7 @@
|
|||
<Compile Include="My Project\Application.Designer.vb">
|
||||
<AutoGen>True</AutoGen>
|
||||
<DependentUpon>Application.myapp</DependentUpon>
|
||||
<DesignTime>True</DesignTime>
|
||||
</Compile>
|
||||
<Compile Include="My Project\Resources.Designer.vb">
|
||||
<AutoGen>True</AutoGen>
|
||||
|
@ -73,7 +83,6 @@
|
|||
</Compile>
|
||||
<Compile Include="My Project\ApplicationEvents.vb" />
|
||||
<Compile Include="OOP.vb" />
|
||||
<Compile Include="Persisting.vb" />
|
||||
<Compile Include="WhidbeyStuff.vb" />
|
||||
</ItemGroup>
|
||||
<ItemGroup>
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
<?xml version="1.0" encoding="utf-8" ?>
|
||||
<?xml version="1.0" encoding="utf-8"?>
|
||||
<configuration>
|
||||
<system.diagnostics>
|
||||
<sources>
|
||||
|
@ -12,14 +12,12 @@
|
|||
</source>
|
||||
</sources>
|
||||
<switches>
|
||||
<add name="DefaultSwitch" value="Information" />
|
||||
<add name="DefaultSwitch" value="Information"/>
|
||||
</switches>
|
||||
<sharedListeners>
|
||||
<add name="FileLog"
|
||||
type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL"
|
||||
initializeData="FileLogWriter"/>
|
||||
<add name="FileLog" type="Microsoft.VisualBasic.Logging.FileLogTraceListener, Microsoft.VisualBasic, Version=8.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a, processorArchitecture=MSIL" initializeData="FileLogWriter"/>
|
||||
<!-- Uncomment the below section and replace APPLICATION_NAME with the name of your application to write to the Application Event Log -->
|
||||
<!--<add name="EventLog" type="System.Diagnostics.EventLogTraceListener" initializeData="APPLICATION_NAME"/> -->
|
||||
</sharedListeners>
|
||||
</system.diagnostics>
|
||||
</configuration>
|
||||
<startup><supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.8"/></startup></configuration>
|
||||
|
|
Загрузка…
Ссылка в новой задаче