concept object in category .net

appears as: n object, object, objects, objects, object, An object, The object, The objects
.NET Core in Action

This is an excerpt from Manning's book .NET Core in Action.

Listing 8.9. Printing an exception and an inner exception
0:000> !pe
Exception object: 00000151b0e54230
Exception type:   System.AggregateException
Message:          One or more errors occurred.
InnerException:   System.NullReferenceException,                        #1
                  Use !PrintException 00000151b0e51a38 to see more.
StackTrace (generated):
<none>
StackTraceString: <none>
HResult: 80131500
0:000> !PrintException 00000151b0e51a38                                 #2
Exception object: 00000151b0e51a38
Exception type:   System.NullReferenceException
Message:          Object reference not set to an instance of an object.
InnerException:   <none>
StackTrace (generated):                                                 #3
    SP               IP               Function
    000000075D17E070 00007FFDD54E22BF
     SqliteDal!SqliteDal.SqliteScmContext.CreateOrder(ScmDataAccess.Order)+0x
     19f

StackTraceString: <none>
HResult: 80004003
Concurrency in .NET

This is an excerpt from Manning's book Concurrency in .NET.

In this chapter, we discussed a number of common issues specific to developing concurrent applications in either imperative or OOP. In these programming paradigms, we’re dealing with objects as a base construct. Conversely, in terms of concurrency, dealing with objects has caveats to consider when passing from a single-thread program to a massively parallelizing work, which is a challenging and entirely different scenario.

In this section you’ll implement a reusable asynchronous object pool. This should be used in cases where the recycling of objects benefits the reduction of memory consumption. Minimizing the number of GC generations allows your program to enjoy better performance speed. Figure 13.1, repeated from chapter 12, shows how to apply concurrent Producer/Consumer patterns, from Listing 12.9, to compress and encrypt a large file in parallel.

13.1.1 Solution: asynchronously recycling a pool of objects

To optimize the performance of a concurrent application with intense memory consumption, recycle the objects that otherwise are subject to be garbage collected by the system. In the parallel compress and encrypt stream example, you want to reuse the same byte buffers (byte arrays) generated instead of creating new ones. This is possible using ObjectPool, a class designed to provide a cached pool of objects that recycles the items that aren’t being used. This reuse of objects avoids expensive acquisition and release of resources, minimizing the potential memory allocation. Specifically, in the highly concurrent example, you need a thread-safe and non-blocking (task-based) concurrent object pool (figure 13.2).

Figure 13.2 An object pool can asynchronously handle multiple concurrent requests for reusable objects from multiple consumers. The consumer then sends the object back to the object pool when it’s done with the work. Internally, object pool generates a queue of objects using a given factory delegate. These objects are then recycled to reduce memory consumption and the cost of new instantiation.

c13-02.png

In Listing 13.1 the implementation of ObjectPoolAsync is based on a TDF that uses the BufferBlock as a building block. The ObjectPoolAsync pre-initializes a set of objects for an application to use and reuse when needed. Furthermore, TDF is intrinsically thread safe while providing an asynchronous, non-blocking semantic.

Listing 13.1 Asynchronous object pool implementation using TDF
public class ObjectPoolAsync<T> :IDisposable
{
 private readonly BufferBlock<T> buffer;   #1  
 private readonly Func<T> factory;   #2  
    private readonly int msecTimeout;

    public ObjectPoolAsync(int initialCount, Func<T> factory, 
➥ CancellationToken cts, int msecTimeout = 0)
    {
        this.msecTimeout = msecTimeout;
 buffer = new BufferBlock<T>(   #1  
            new DataflowBlockOptions { CancellationToken = cts });
 this.factory = () => factory();   #2  

        for (int i = 0; i < initialCount; i++)
 buffer.Post(this.factory());   #3  
    }

 public Task<bool> PutAsync(T item) => buffer.SendAsync(item);   #4  
    
 public Task<T> GetAsync(int timeout = 0)   #5  
    {
        var tcs = new TaskCompletionSource<T>();
        buffer.ReceiveAsync(TimeSpan.FromMilliseconds(msecTimeout))
            .ContinueWith(task =>
            {
                if (task.IsFaulted)
                    if (task.Exception.InnerException is TimeoutException)
                        tcs.SetResult(factory());
                    else
                        tcs.SetException(task.Exception);
                else if (task.IsCanceled)
                    tcs.SetCanceled();
                else
                    tcs.SetResult(task.Result);                
            });
        return tcs.Task;
    }
    public void Dispose() => buffer.Complete();

}

#1   Uses BufferBlock to asynchronously coordinate the underlying set of types T
#2   Uses a factory delegate to generate a new instance of type T
#3   During the initialization of the object pool, the buffer is filled with instances of type T to have objects available from the start.
#4   When the consumer is done, the object type T is sent back to the object pool to be recycled.
#5   The object pool sends an object type T when a consumer makes the request.

ObjectPoolAsync accepts as arguments an initial number of objects to create and a factory delegate constructor. ObjectPoolAsync exposes two functions to orchestrate the object’s recycle:

C# in Depth

This is an excerpt from Manning's book C# in Depth.

  • In C# 3, the assignment to worksheet would fail without a cast, because the type of the ActiveSheet property is represented as object. When using the embedded PIA feature, the type of ActiveSheet becomes dynamic, which leads to an entirely different feature.
  • Listing 12.4. An implementation of IQueryProvider that uses FakeQuery
    class FakeQueryProvider : IQueryProvider { public IQueryable<T> CreateQuery<T>(Expression expression) { Logger.Log(this, expression); return new FakeQuery<T>(this, expression); } public IQueryable CreateQuery(Expression expression) { Type queryType = typeof(FakeQuery<>).MakeGenericType(expression.Type); object[] constructorArgs = new object[] { this, expression }; return (IQueryable)Activator.CreateInstance(queryType, constructorArgs); } public T Execute<T>(Expression expression) { Logger.Log(this, expression); return default(T); } public object Execute(Expression expression) { Logger.Log(this, expression); return null; } }

    The idea behind Parallel LINQ is that you should be able to take a LINQ to Objects query that’s taking a long time and make it run faster by using multiple threads to take advantage of multiple cores—with as few changes to the query as possible. As with anything to do with concurrency, it’s not quite as simple as that, but you may be surprised at what can be achieved. Of course, we’re still trying to think bigger than individual LINQ technologies—we’re thinking about the different models of interaction involved, rather than the precise details. But if you’re interested in concurrency, I heartily recommend that you dive into Parallel Extensions—it’s one of the most promising approaches to parallelism that I’ve come across recently.

    Dependency Injection in .NET

    This is an excerpt from Manning's book Dependency Injection in .NET.

    To create the Salutation class, you pass in the Mock instance of IMessageWriter. Because writerMock is an instance of Mock<IMessageWriter>, the Object property is a dynamically created instance of IMessageWriter. Injecting the required DEPENDENCY through the constructor is called CONSTRUCTOR INJECTION.

    public interface IInstanceProvider
    {
        object GetInstance(InstanceContext instanceContext);
        object GetInstance(InstanceContext instanceContext, Message message);
        void ReleaseInstance(InstanceContext instanceContext, object instance);
    }
    Figure 8.8. When a COMPOSER is asked to resolve an object, it gathers all of the requested object’s DEPENDENCIES. In this case, the requested object has three DEPENDENCIES, and two of them are disposable. One of these disposable DEPENDENCIES is shared with other consumers, so it’s reused, whereas the other DEPENDENCIES are instantiated on the spot. When the request to release the object comes in, the COMPOSER disposes of the private disposable DEPENDENCY and lets the non-disposable DEPENDENCY and the object itself go out of scope. The only interaction with the shared DEPENDENCY is that it’s injected into the requested object; but because it’s shared, it isn’t disposed of (yet).

    On the other hand, the PER GRAPH and TRANSIENT lifestyles don’t keep track of the objects that StructureMap creates. As you saw in listings 8.7 and 8.8, object instances are created and returned with no internal tracking. This has some advantages and disadvantages.

    Because StructureMap doesn’t hold on to instances unnecessarily, the risk of inadvertent memory leaks is much smaller. With a container like Castle Windsor, memory leaks are guaranteed if we forget to call the Release method for all resolved object graphs. This isn’t the case with StructureMap because objects will automatically be garbage-collected as they go out of scope.

    Entity Framework 4 in Action

    This is an excerpt from Manning's book Entity Framework 4 in Action.

    When the query against the database has been executed and the underlying layer has reorganized the data using the mapping, Object Services is responsible for creating objects using the input structure. The input data is organized as rows and columns, but in a conceptual-model way and not in a database manner. This means each row represents an object, and if it has a property that references another class, the column contains the overall row for the class. Figure 1.10 illustrates how the data is organized.

    Figure 1.10. How data is received by the Object Services layer

    Due to this organization of data, the process of creating objects is fairly simple. This process is object materialization.

    When the objects are ready to be consumed, the context comes into play. By context we mean the lifetime of the communication between the application and Entity Framework. It’s established using a well-known class (ObjectContext, or context), and it’s active as long as the class is referenced in the code or it isn’t disposed of. The context class is used from the beginning because this class creates the entry point for querying the object model.

    After the objects are materialized, they’re automatically added to the context memory, but this behavior can be overridden for performance reasons. During the materialization process, if the object that’s going to be created already exists in the context memory, it’s skipped by the engine, and a reference to the in-memory object is returned to the code executing the query. This means the context acts as a sort of local cache.

    The objects that are attached to the context are automatically tracked by the state manager component. This mechanism ensures that any modifications made to objects are correctly managed and recorded in the database. To do this, the state manager stores the original data of every object that’s loaded so it can compare them and perform an optimized update. This component gives you many options to customize its behavior.

    Figure 3.2. How a LINQ to Entities query passes through different layers and becomes a set of objects
    Public Sub New()
      AddHandler ctx.ObjectMaterialized, AddressOf ctx_ObjectMaterialized
    End Sub
    
    Private Sub ctx_ObjectMaterialized(ByVal sender As Object,
      ByVal e As ObjectMaterializedEventArgs)
      Dim o = TryCast(entity, Order)
      'any logic
    End Sub

    Probably the simplest SQL code to generate is the DELETE commands for entities in the Deleted state. The SQL code deletes an object using its key properties.

    DSLs in Boo: Domain-Specific Languages in .NET

    This is an excerpt from Manning's book DSLs in Boo: Domain-Specific Languages in .NET.

    StructureMap (http://structuremap.sourceforge.net/) is an Inversion of Control (IoC) container, probably the oldest on .NET. An Inversion of Control container is a tool that helps you manage dependencies and lifetimes of objects in your application. You can think about them as very smart factories, although that doesn’t do them justice. You can read more about IoC containers here: http://www.martinfowler.com/articles/injection.html.

    A.6.2. Classes and objects

    Think of a class as a box that contains variables and methods. You can create objects (other boxes) based on that class. Each object (box) gets its own independent copy of the variables, whereas all of the objects share the methods. Creating an object from a class is called instantiation, and the object that’s created is often called an instance of its class. We will use both terms interchangeably.

    An element of one of the objects can be accessed by using the object name, followed by a period, followed by the element name:

    Account1.Deposit(400.0)
    Account1.Withdraw(50.0)
    print Account1.Balance # prints 350
    print Account2.Balance # prints 0

    The constructor method is special. It is automatically called when a new object is created. This is where the initialization of the object occurs.

    IronPython in Action

    This is an excerpt from Manning's book IronPython in Action.

    First, dynamic languages are trendy; all the alpha-geeks are using them! Clearly, this isn’t enough of an explanation. Unfortunately, like many programming terms, dynamic is hard to pin down and define precisely. Typically, it applies to languages that are dynamically typed, that don’t need variable declarations, and where you can change the type of object a variable refers to.

    Figure 2.3. Names bound to objects by assignment statements

    When Python encounters iteration over an object—as a result of a for loop, a list comprehension, or an explicit call to the iter function—it will attempt to call __iter__ on the object. If the object supports iteration, then this method should return an iterator. An iterator is an object that obeys the following three rules:

  • It has a __iter__ method that returns itself.[5]

    5 This allows an object to be its own iterator.

  • 5 This allows an object to be its own iterator.

    try:
    instance.someMethod()
    except AttributeError:
    # different kind of object

    Sometimes you want to ask permission, though—perhaps particular objects need different treatment. You could do type checking with isinstance, but this defeats duck typing and requires users of your code to use specific types instead of passing in objects with a compatible API. Instead, you can use hasattr, as follows:

    When you compare objects, the comparison operation will cause the method corresponding to the operation to be called magically (as long as the object provides the appropriate protocol method).

    NHibernate in Action

    This is an excerpt from Manning's book NHibernate in Action.

    Because NHibernate is a transparent persistence mechanism, classes are unaware of their own persistence capability. It’s therefore possible to write application logic that is unaware of whether the objects it operates on represent persistent state or temporary state that exists only in memory. The application shouldn’t necessarily need to care that an object is persistent when invoking its methods.

    But in any application with persistent state, the application must interact with the persistence layer whenever it needs to transmit state held in memory to the database (or vice versa). To do this, you call NHibernate’s persistence API. When interacting with the persistence mechanism that way, it’s necessary for the application to concern itself with the state and lifecycle of an object with respect to persistence. We’ll refer to this as the persistence lifecycle.

    Figure 4.1. States of an object and transitions in an NHibernate application

    In its lifecycle, an object can transition from a transient object to a persistent object to a detached object. Let’s take a closer look at each of these states.

    Let’s first look at the Update() method. Using Update() forces an update to the persistent state of the object in the database; a SQL UPDATE is scheduled and will be later committed. Here’s an example of detached object handling:

    user.Password = "secret";
    using( ISession sessionTwo = sessionFactory.OpenSession() )
    using( sessionTwo.BeginTransaction() ) {
    sessionTwo.Update(user);
    user.Username = "jonny";
    sessionTwo.Transaction.Commit();
    }

    It doesn’t matter if the object is modified before or after it’s passed to Update(). The important thing is that the call to Update() is used to reassociate the detached instance with the new ISession and the current transaction. NHibernate will treat the object as dirty and therefore schedule the SQL UPDATE regardless of whether the object has been updated. This makes Update() a safe way to reassociate objects with a Session, because you know changes will be propagated to the database. There is one exception: when you’ve enabled select-before-update in the persistent class mapping. With this option enabled, a call to Update() will make NHibernate determine whether the object is dirty rather than assuming it is. It does so by executing a SELECT statement and comparing the object’s current state to the current database state. This is still a “safe” option, even though NHibernate won’t force an update if it isn’t needed.

    Now, let’s look a the Lock() method. A call to Lock() associates the object with the ISession without forcing NHibernate to treat the object as dirty. Consider this example:

    The Get() method is special because the identifier uniquely identifies a single instance of a class. Hence it’s common for applications to use the identifier as a convenient handle to a persistent object. Retrieval by identifier can use the cache when retrieving an object, avoiding a database hit if the object is already cached.

    LINQ in Action

    This is an excerpt from Manning's book LINQ in Action.

    Once you are ready, let’s move on to LINQ to XML and LINQ to SQL. We’ll spend some time with these two other flavors of LINQ so you can get an idea of what they taste like. We will get back to LINQ to Objects in detail in part 2 of this book.

    Now that we’ve learned about the LINQ to XML API and seen how to query and transform XML using LINQ to XML, it’s time to explore some common scenarios that you may come across when working with LINQ to XML. These include building objects from XML, creating XML from a set of objects, creating XML with data from a database, filtering and mixing data from a database with XML data, updating a database with data read from an XML file, and transforming text files into XML using LINQ to XML. As we explore these common scenarios, you’ll witness the powerful capabilities offered by LINQ to XML.

    Our goal in the section is to create a collection of objects that contain the data within the XML document shown in listing 11.1 using the capabilities offered by LINQ to XML.

    Listing 11.1. Book data in XML format
    <?xml version="1.0" encoding="utf-8" ?> <books> <book> <title>LINQ in Action</title> <authors> <author> <firstName>Fabrice</firstName> <lastName>Marguerie</lastName> <website>http://linqinaction.net/</website> </author> <author> <firstName>Steve</firstName> <lastName>Eichert</lastName> <webSite>http://iqueryable.com</webSite> </author> <author> <firstName>Jim</firstName> <lastName>Wooley</lastName> <webSite> http://devauthority.com/blogs/jwooley/</webSite> </author> </authors> <subject> <name>LINQ</name> <description>LINQ shall rule the world</description> </subject> <publisher>Manning</publisher> <publicationDate>January 15, 2008</publicationDate> <price>44.99</price> <isbn>1933988169</isbn> <notes>Great book!</notes> <summary>LINQ in Action is great!</summary> <reviews> <review> <user>Steve Eichert</user> <rating>5</rating> <comments>What can I say, I'm biased!</comments> </review> </reviews> </book> <book> <title>Patterns of Enterprise Application Architecture</title> ... </book> </books>

    As we can see, the XML contains a set of information about books. If we move our attention to the classes shown in figure 11.1, we can see that we have a series of objects that correlate to the data contained in the XML file in listing 11.1.

    Listing 11.3. Creating objects from XML

    With LINQ to XML we can transform our XML data into alternate data formats quickly and easily. By combining query expressions with the new object initializer syntax offered by C# 3.0, we can build objects from XML using familiar LINQ language constructs. As you’ll see throughout the remainder of this chapter, LINQ to XML provides a simple and consistent API for transforming data to and from XML.

    Now that we’ve covered how to create objects from XML, let’s look at how we can handle our next common scenario, creating XML from objects using VB9’s XML literals.

    11.1. Building objects from XML

    As we already mentioned, the first scenario that we’re going to cover is building objects from XML. Before we look at the specifics of how we go about building objects from XML with LINQ to XML, let’s talk briefly about why we would want to do it in the first place. When we build applications today, we do so using objects. Objects allow us to encapsulate the logic and data that exist in our software. Since XML is a data format and not a programming language, we need to read the data out of the XML files if we want to use it in our applications. To ensure our application doesn’t get too tightly coupled to the format of an XML file, we’ll convert the data within the XML file into a set of objects using the powerful capabilities offered by LINQ to XML.

    As we’ll see, LINQ to XML allows us to convert XML into objects using the same transformation techniques we learned about in the previous chapter. No matter what format we need to transform our XML into, LINQ to XML is up to the challenge. With that said, let’s get started by examining our goal for this scenario.

    ASP.NET AJAX in Action

    This is an excerpt from Manning's book ASP.NET AJAX in Action.

    The XMLHttpRequest object is at the heart of Ajax programming because it enables JavaScript to make requests to the server and process the responses. It was delivered in the form of an ActiveX object when released in Internet Explorer 5, and it’s supported in most current browsers. Other browsers (such as Safari, Opera, Firefox, and Mozilla) deliver the same functionality in the form of a native JavaScript object. Ironically, Internet Explorer 7 now implements the object in native JavaScript as well, although differences between browsers remain. The fact that there are different implementations of the object based on browsers and their versions requires you to write browser-sensitive code when instantiating it from script. Listing 1.1 uses a technique called object detection to determine which XMLHttpRequest object is available.

    The object literal {} represents a sort of empty object. We’ll discuss the various JavaScript literals in detail in section 3.1.7. Once you’ve created an object, you can take advantage of an important characteristic of the language: You can expand objects at any time by adding new properties to them. This is different from what happens in class-based languages such as C# and VB.NET, where the structure of an object is specified in a class and instances can’t be modified at runtime.

    To add a property to an object, you need to access it and assign a value. You can do this anywhere in the code, at any time. If the property doesn’t exist, it’s automatically created at runtime. The following code shows how to add a property called title to the book object you created before:

    book.title = 'ASP.NET AJAX In Action';

    As we said previously, objects in JavaScript are collections of name and value pairs. To demonstrate, you can add a property to an object using an indexed notation, as if you were accessing a collection such as an array or a hash table. The following is another way to add a title property to the book object:

    book['title'] = 'ASP.NET AJAX In Action';

    You can loop over an object’s properties by using the for-in construct. This construct is similar to the foreach construct of C#. For example, the following code displays the name and values of the properties of the book object:

    for(var property in book) {
        alert('Name: ' + property + ', Value: ' + book[property]);
    }

    In this code snippet, the property variable holds, at each iteration, a string with the name of a property of the object. As result, book[property] returns the value of that property. The name and value of each property are displayed using the JavaScript’s alert function, which displays a string in a message box on screen.

    Figure 3.3. Inheritance in JavaScript is prototype-based. An object inherits all the properties defined in the prototype of the parent objects.

    In JavaScript, implementing inheritance is simple; but it’s done differently than in class-based languages, where the parent class can be specified in the class declaration. For example, one approach is to assign the object returned by the parent constructor to the prototype object of the child constructor. Without going into too much detail, the code in listing 3.7 shows how you can define a Cat object that inherits all the properties from a Pet object using prototype-based inheritance.

    3.1. Working with objects

    JavaScript is a true object-oriented language. The notion of an object in JavaScript is different from that in object-oriented languages such as C# and VB.NET. Objects in JavaScript aren’t instances of classes, because JavaScript doesn’t support the notion of a class. Instead, you obtain the structure—or template—of an object by manipulating a special, native object called the prototype, which you’ll encounter in section 3.1.5.

    A JavaScript object is nothing more than a collection of name and value pairs called properties. Usually, this kind of structure is also called a dictionary or an associative array. JavaScript provides also an array data type, which is a collection of values of different types. A major role in the language is played by functions, which are objects like dictionaries or arrays. Functions are probably the most powerful objects provided by JavaScript; they’re responsible for its great power and flexibility. In the following sections, we’ll do an overview of objects, arrays, and functions, which are the foundations of the JavaScript language.