.NET Questions and Solutions

As a software engineer, I focus on .NET, especially asp.net, C#, WCF and so on, and I am also very interested in Search Engine Optimization.

Entries Tagged ‘Class’

BUG: You may receive a “COMException (0×80010105): The server threw an exception” error message in Visual Studio .NET 2003

Symptoms
In Microsoft Visual Studio .NET 2003, if you automate your application to run out-of-process, you may receive a COM exception error message that is similar to the following from the Devenv.exe out-of-processcomponent:

Unhandled Exception: System.ApplicationException: Failed —> System.Runtime.Int
eropServices.COMException (0×80010105): The server threw an exception.at EnvDTE._Solution.Open(String FileName)at DTEAutomation.Class1.Main(String[] args) in c:\vs7play\enterprisetemplate\dteautomation\class1.cs:line 45
— End of inner exception stack trace —at DTEAutomation.Class1.Main(String[] args) in c:\vs7play\enterprisetemplate\dteautomation\class1.cs:line 80
Resolution
This problem occurs because a cached pointer to the selected data is not valid.Then,the Enterprise Template Project is opened.

BUG: The System.Collections.Queue.Clone method loses data while cloning objects

Symptoms
The Queue class is a Microsoft .NET Framework Class Library class. It represents a first-in, first-out collection of objects. However, if you use the Queue.Clone method to clone a queue, and if the call to the Queue.Dequeue method is made before the call to Queue.Clone method is made, the data is lost.
Resolution
A bounded buffer is used to implement the Queue class. The Clone method uses the beginning of the buffer, instead of the head pointer, as the starting point. When the Dequeue method is called, the first element is removed. However, the beginning of the buffer remains the same. Therefore, the first element appears as an empty element and the last element is lost in the cloning process.

BUG: “System.Runtime.Serialization.SerializationException” exception if you declare a static local variable in a method of a Visual Basic .NET or Visual Basic 2005 class and try to serialize the …

Symptoms
Microsoft Visual Basic .NET or Microsoft Visual Basic 2005 allows you to declare static local variables inside a method of class. However, if you declare a static local variable in a method of the Visual Basic .NET or Visual Basic 2005 class, and then you try to serialize the object of the class by using BinaryFormatter or SoapFormatter, you receive the following exception during run time:

An unhandled exception of type ‘System.Runtime.Serialization.SerializationException’ occurred in mscorlib.dll
Additional information: The type Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag in Assembly Microsoft.VisualBasic, Version=7.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a is not marked as serialized.
Resolution
The common language runtime does not support static variables in methods. When Visual Basic .NET or Visual Basic 2005 compiler compiles your code, it translates this high-level Visual Basic .NET or Visual Basic 2005 code to Microsoft intermediate language (MSIL) code that the common language runtime can understand to give you shared variable functionality. Visual Basic .NET or Visual Basic 2005 uses the Microsoft.VisualBasic.CompilerServices.StaticLocalInitFlag class to provide this functionality. In Visual Basic .NET or in Visual Basic 2005 compiler, the StaticLocalInitFlag is not marked as serialized. Therefore, you receive the exception during run time.

BUG: “Cannot implicitly convert type ‘System.Data.DataSet’” error when application is built

Symptoms
You have a Web Service that has a Web Service method that returns an instance of a custom class. The class that is returned by the Web Service method implements the IXmlSerializable interface. If you use this Web Service in an application, you may receive the following error message when you build the application:

Cannot implicitly convert type ‘System.Data.DataSet’ to ‘ClassLibrary.ClassName’
Resolution
When you add a Web reference to a Web Service, Microsoft Visual Studio .NET incorrectly uses System.Data.DataSet instead of the class that implements the IXmlSerializable interface. Therefore, the Web Service method in the proxy class returns System.Data.DataSet instead of the custom class that implements the IXmlSerializable interface. Therefore, you receive the error message when you consume the Web Service method in your Web application.

Binary serialization exceptions occur when you serialize or deserialize the DateTimeFormatInfo class or the TextInfo class between different versions of the .NET Framework

Symptoms
When you serialize or deserialize the DateTimeFormatInfo class or the TextInfo class between a computer that is running the Microsoft .NET Framework 2.0 Service Pack 1 (SP1) and a computer that is running a pre-SP1 version of the .NET Framework 2.0, you receive one of the following binary serialization exceptions:
Exception 1

Exception type: System.Runtime.Serialization.Serialization
ExceptionMessage: Binary stream ‘0′ does not contain a valid BinaryHeader. Possible causes are invalid stream or object version change between serialization and deserialization.Exception 2

Exception type: System.ArgumentNull
ExceptionMessage: Value cannot be null.This problem occurs when you serializethe DateTimeFormatInfo class and the TextInfo class by setting the TypeFormat property of the BinaryFormatter class to FormatterTypeStyle.XsdString.
Resolution
This problem occurs because the FormatterTypeStyle.XsdString serialization formatting and the FormatterTypeStyle.TypesWhenNeeded serialization formatting drop type information for performance reasons when you serialize types across different versions of the .NET Framework.

ACC2000: How to Use Collections to Manage Class Objects in VBA

Symptoms
Advanced: Requires expert coding, interoperability, and multiuser skills.
This article shows you how to use collections in Visual Basic forApplications to manage references to class objects in Access 2000.This technique allows your class objects to persist, and enables you tocontrol the individual properties of those objects by using the familiarcollection syntax used in Microsoft Access for implementing Data AccessObjects (DAO) and other Microsoft Office Object models.
Microsoft provides programming examples for illustration only, without warranty either expressed or implied. This includes, but is not limited to, the implied warranties of merchantability or fitness for a particular purpose. This article assumes that you are familiar with the programming language that is being demonstrated and with the tools that are used to create and to debug procedures. Microsoft support engineers can help explain the functionality of a particular procedure, but they will not modify these examples to provide added functionality or construct procedures to meet your specific requirements.
Resolution
In order to use collections to manage class objects, you must do thefollowing:Create an instance of the classSet the properties and methods of the classAdd the class to a public collectionUnload the instance of the classYou might expect that unloading the instance of the class results in theclass being closed and terminated. However, the class object persistsbecause you add it to a collection, which then owns the reference to theclass. This is a very powerful technique that allows you to control objectreferences through a collection; the class object does not terminate untilyou remove it from the collection.
The following example creates a class object and a form object, and thenmanages both objects from a collection in a standard module.
Create a Class ModuleCreate a new database called ClassTest.mdb.On the Insert menu, click Class Module.Save the class module as clsTest.Type the following lines in the Declarations section:

Private This_ClassID As StringPrivate This_frm As New Form_frmTest Select Class in the Object box of the Module window. “Initialize” isautomatically selected in the Procedure box.Type the following procedure:

Private Sub Class_Initialize()On Local Error GoTo Class_Initialize_ErrDim Msg As StringThis_frm.Visible = TrueThis_ClassID = “Initialized”This_frm.Caption = This_ClassIDMsgBox “Class Initialized”, vbInformation, “Class Example”Class_Initialize_End:Exit SubClass_Initialize_Err:Msg = “Error #: ” & Format$(Err.Number) & vbCrLfMsg = Msg & Err.DescriptionErr.Raise vbObjectError, “clsTest.Initialize (Private)”, MsgResume Class_Initialize_EndEnd Sub On the Insert menu, click Procedure.In the Insert Procedure dialog box, type ClassID in the Name box andclick Property in the Type box. Then type the following procedures

Public Property Get ClassID() As VariantClassID = This_ClassIDEnd PropertyPublic Property Let ClassID(ByVal vNewValue As Variant)This_ClassID = vNewValueThis_frm.ClassID = This_ClassIDThis_frm.Caption = This_ClassIDEnd Property Save and close the clsTest class module.
Create a FormCreate the following form not based on any table or query in Designview:

Form: frmTest—————–Caption: TestForm With the form still open in Design view, click Code on the View menu.Type the following line in the Declarations section of the form’s classmodule:

Dim This_ClassID As String Add the following event procedure to the form’s Unload property:

Private Sub Form_Unload(Cancel As Integer)col.Remove This_ClassIDEnd Sub On the Insert menu, click Procedure.In the Insert Procedure dialog box, type ClassID in the Name box andclick Property in the Type box. Then type the following procedures. Notethat the Get ClassID() function and vNewValue variable in this exampleare dimensioned as String instead of the default, which is Variant:

Public Property Get ClassID() As StringClassID = This_ClassIDEnd PropertyPublic Property Let ClassID(ByVal vNewValue As String)This_ClassID = vNewValueEnd Property Save and close the frmTest form.
Create a Standard ModuleCreate a new standard module and save it as Module1.Type the following line in the Declarations section:

Public col As New Collection Type the following procedure:

Function CreateClassTest() As String’ Create an instance of the clsTest class module, which creates’ an instance of the frmTest form.Dim cls As New clsTest’ Create a unique identifier string and set it to the upper index’ of the Public col Collection plus one.Dim varClassId As StringvarClassId = “Key_” & CStr(col.Count + 1)’ Set the clsTest class module’s ClassID property to the value of’ varClassId, which in turn sets the frmTest.ClassId property to’ the same value. This is so the form has a method to track its’ relationship to the collection.cls.ClassID = varClassId’ Add the instance of the class object to the collection passing’ varClassId as the Key argument.col.Add cls, varClassIdMsgBox “Created New Collection Item: ” & varClassId, _vbInformation, “Class Example”‘ Unload the cls object variable.Set cls = Nothing’ Return the varClassId.CreateClassTest = varClassIdEnd Function Close and save the module.
Test the ExampleWhen you call the CreateClassTest() function multiple times, it opensmultiple instances of the frmTest form, each of which is unique and capableof managing itself and its participation in the public collection. Eachform is aware of its Key position in the collection, and each one removesitself from the collection when you close the form.
The following sample procedure creates three instances of the clsTestclass:Create a standard module and type the following procedure:

Function CreateThreeItems() As BooleanDim strKeys(1 To 3) As StringDim i As IntegerFor i = LBound(strKeys) To UBound(strKeys)strKeys(i) = CreateClassTest()Next iFor i = LBound(strKeys) To UBound(strKeys)MsgBox col.Item(strKeys(i)).ClassID, vbInformation, _”Class Test”Next iEnd Function To test this function, type the following line in the Immediate window,and then press ENTER:

?CreateThreeItems() Note that messages boxes are displayed each time the clsTest classmodule initializes, when each of three instances of the frmTest form iscreated, and again after all three instances of the form are open.